Skip to content

Complete reference

Continuous concepts, guides and complete API reference for Cytoscape.js.

Read the guides and API reference for the v4 preview on one page. See Migration to port a v3 application.

Browse focused topic pages · Alphabetical API index

Agent and tooling downloads: structured API JSON · documentation index.

352 API members, grouped with their related guides below.

#Introduction

Explore graph modelling, analysis and interactive visualisation.

Cytoscape.js lets you model, analyse and display networks. Nodes represent things, edges connect them, and application data describes their attributes. Use graph algorithms to find paths and groups, then layouts and styles to make the relationships visible.

A graph instance is the core, usually named cy. Methods such as cy.nodes() return collections: ordered sets of element handles. A single element is also a collection, so the same methods work on one element or many. Begin with Getting started, then read Notation & glossary for graph concepts, coordinates and data.

#Factsheet

At a glance Cytoscape.js
Purpose Graph modelling, analysis and interactive visualisation.
Data model Nodes, directed edges, loops, parallel edges and compound containment.
Analysis Traversal, set operations and algorithms from breadth-first search to PageRank.
Display Layouts, declarative styles, animation, and desktop/touch interaction.
Execution Browser rendering, or headless graph work without a canvas.
Language and types JavaScript package with TypeScript declarations.
License MIT, including commercial use under its terms.

These pages describe the preview. Its package version is 4.0.0-unstable; see Releases for published distributions and Supported environments for runtime requirements. Graph reads and writes are synchronous; methods returning promises explain when to await completion.

#Who uses Cytoscape.js

The project's adopter list includes Amazon, Google and Microsoft, research resources such as GeneMANIA and Pathway Commons, and libraries such as Mermaid. It documents the wider Cytoscape.js ecosystem. Browse that list for more examples across industry, research, government and open-source software, or share your use case.

#About

Cytoscape.js is an open-source network library for application developers and researchers. It combines a graph model and analysis API with optional interactive rendering. Use it in a browser interface, on a server, or in a headless analysis task.

The project originated at the Donnelly Centre, University of Toronto, as reported in the original publication. Development is collaborative: the GitHub repository contains source, issues, discussions and contribution guidance.

#Packages

The published package is cytoscape on npm. Use Getting started to choose a version and install it. The entries documented in this preview are:

Entry Use it for
cytoscape Interactive browser graphs, with rendering and pointer gestures.
cytoscape/headless Graph queries, CPU algorithms and layouts without a canvas.
cytoscape/headless-gpu Headless work with GPU algorithms or GPU force layouts.

The entries share a graph API, with capabilities appropriate to each build. Check Supported environments before choosing a renderer or GPU executor.

#Releases

Find published versions and release notes in GitHub releases, and package distribution tags on npm. Use documentation matching the version installed in your application. These pages document an unreleased preview. See Migration for changes from earlier releases and archived documentation.

#Citation

When publishing work that uses Cytoscape.js, cite Franz et al. (2016), Bioinformatics 32(2), 309–311, doi:10.1093/bioinformatics/btv557. Record the software version used so the analysis can be reproduced. The project's Zenodo record provides version-specific software citations where available.

#Publications

These papers describe the project's published history. Use this reference and its migration notes for the preview's current API contracts.

#Funding

Cytoscape.js has received NIH support, including through the National Resource for Network Biology (NRNB). The original paper's funding acknowledgements list P41 GM103504, R01 GM070743 and U41 HG006623. These are historical acknowledgements; current project support and participation information is available through NRNB and the Cytoscape Consortium.

#Cytoscape Consortium

The Cytoscape Consortium is an independent not-for-profit organisation supporting open software and public resources for biological networks. Cytoscape.js is part of the broader Cytoscape community, alongside the Cytoscape platform. Visit the consortium for its mission, participating projects and support information.

#License

Cytoscape.js is distributed under the MIT license. It permits use, modification and redistribution, including in commercial applications, subject to its notice requirements. The software is provided without warranty. Consult the license shipped with the version you use; separately installed extensions and other packages have their own licenses.

#Notation & glossary

Understand graph elements, coordinates and the data forms used throughout the API.

#Nodes, edges and compound graphs

Notation & glossary › Nodes, edges and compound graphs

Understand element identity and compound containment.

#Graph theory basics

A graph is a set of nodes (vertices) and edges connecting pairs of nodes. A directed edge runs from its source to its target; an undirected algorithm treats either direction as traversable. A loop joins a node to itself. Parallel edges share the same endpoints; a simple graph has neither loops nor parallel edges.

A neighbourhood contains the nodes adjacent to a node. Its degree counts incident edges; in-degree and out-degree count incoming and outgoing edges. A path follows consecutive edges. A cycle returns to its starting node. A directed acyclic graph (DAG) has no directed cycle. A connected component is a maximal set joined by paths when direction is ignored; a strongly connected component allows directed paths in both directions between every pair. A tree is connected and has no cycles; a forest is a set of trees.

An edge weight is an application-defined cost or strength. Algorithms state whether they read weights and what restrictions apply; the fewest-edge path and the least-weight path can differ. Compound parenthood is a separate containment relation, rather than an extra graph edge. Use traversal to inspect topology and the algorithm reference to choose an operation.

#Nodes, edges and compounds

A graph contains nodes and directed edges. A node has a stable id; an edge has its own id, a source node id and a target node id. Application fields belong under data. A node may also have one parent node id, which models compound containment. Compound ancestry is a tree relation: it does not create multiple parents or replace pairwise edge topology.

const elements = [
{ data: { id: 'pathway', label: 'Pathway' } },
{ data: { id: 'a', parent: 'pathway', score: 0.7 } },
{ data: { id: 'b', parent: 'pathway', score: 0.2 } },
{ data: { id: 'a-to-b', source: 'a', target: 'b', weight: 3 } },
];

id, source, target and parent are first-class fields. They can be read through data() but are not ordinary mutable data keys: use move() to re-parent a node or re-point an edge. Other data values are application state; writes refresh data-driven style mappings and emit the corresponding events. With TypeScript, explicit cytoscape<NodeData, EdgeData>(...) generics type node and edge data separately. The generics are not inferred from constructor options.

#Model and rendered coordinates

Notation & glossary › Model and rendered coordinates

Choose the coordinate system that matches the operation.

position() reads or writes node coordinates in model space. The core viewport maps model coordinates into rendered CSS pixels through its zoom and pan. renderedPosition() and the rendered bounds methods use that displayed coordinate system. Use cy.pan() and cy.zoom() for a view change; they do not move nodes. cy.fit() and cy.center() derive a viewport from element bounds, with labels included where the bounds contract says so. Headless cores still have model positions and configurable dimensions, but no rendered canvas.

An element's public handle is a one-element Collection; a Collection is the ordinary public view for zero, one or many elements. It is not a raw array of mutable internal records. Scalar collection reads generally use the first element and return undefined when the collection is empty; bulk methods explicitly say when they return an array, a collection or a per-element result. Most graph reads and writes take effect synchronously. Methods that return promises explain when to await completion.

Removed elements are terminally removed. A removal result can include the receiver's descendants and incident edges, and those returned handles are dead; cached id() and group() are the remaining identity reads. The library does not restore a removed handle or add an element collection back into a graph. Retain definitions or serialized data if an application needs to recreate those elements.

#Element input forms: objects, columnar data and wire buffers

Notation & glossary › Element input forms: objects, columnar data and wire buffers

Choose an input form and understand what each form carries.

#Three element input forms

The classic element-definition form accepts one element, an array, or a { nodes, edges } object. Nodes are established before edges in one add/load operation, so edges may refer to nodes in that same payload. Input can be provided to the constructor or passed to cy.add(), cy.patch() and cy.load(). An add into a populated graph fires per-element add events; the constructor's initial bulk ingest happens before a listener can exist.

The columnar form stores grouped fields in typed-array columns and represents edge endpoints as references to node positions in the payload. It is intended for large imports and streaming chunks where allocating one object per element would be costly. cytoscape.toColumnarElements() converts element-definition JSON to this form. The public type is ColumnarElements; use its documented shape rather than assuming an internal column order.

The binary wire form is emitted by cy.serialize() or cytoscape.serializeElements() and accepted by the loading APIs. A whole-graph serialization is self-contained: edge endpoints resolve within that payload. It carries graph/element data and current element state needed by the wire contract, but does not carry a stylesheet, viewport or scratchpad. cy.json() is a readable export, not a restoration API. serialize() is the compact round-trip form; cytoscape.deserializeElements() exposes a decoded payload when an application needs to inspect it.

Wire graph-level data() needs care. A constructor load applies that data, and cy.serialize() includes it. cy.add(buffer) ignores graph-level data so that adding elements cannot overwrite the receiving graph's own fields. If the application intends to replace those fields, read them from the decoded wire payload and call cy.data() explicitly.

#What each form carries

Ids, data, positions, parents, endpoints selected, selectable locked, grabbable, pannable Bypasses
Wire (serialize()) yes yes no no
json() element form yes yes yes no
cy.clone() yes yes yes yes, in the carried sheet

A clone also carries graph data(), the sheet, the viewport, the gating flags, every interaction setting and the construction options minus elements, container and layout. It does not carry scratch, listeners, running animations or layouts, or transient hover, active and grabbed state.

#Graph snapshots and session state

Notation & glossary › Graph snapshots and session state

Distinguish graph payloads from the state of a live session.

#A session is more than its elements

cy.json() exports elements, stylesheet, viewport, core flags and graph-level data as a plain object. That object is useful for inspection or application storage, but cy.json(object) is deliberately not an import form. To apply incoming element data, use patch(); to recreate a graph, load the element definitions or a binary payload into a new core. cy.serialize() is the supported compact wire export. cy.clone() makes another independent core, carrying graph and selected session state while giving the clone its own renderer, stylesheet, viewport and interactions. Scratch, active gestures, listeners and running layouts/animations are not shared.

Nodes and edges are the two element kinds. Each node has at most one compound parent. See Feature availability for alternatives to overlapping membership and annotations.

#Type boundaries and JSON schemas

Notation & glossary › Type boundaries and JSON schemas

Type your graph data and validate saved configurations.

#Where typing stops

Typed element data does not reach:

  • columnar and wire payloads, because an ArrayBuffer carries no type;
  • the 'data(name)' label string, because a style value is any string. The { data } mapper is the typed form;
  • a condition's value (eq, gt, in), which is not correlated with its field's type;
  • algorithm and layout callbacks and results, which take and return plain Collections. Clustering results are typed;
  • json() and jsons(), which stay Record<string, unknown>;
  • isNode(), which does not narrow, because it answers for the first element.

#JSON schemas

The schemas in schemas/ are open where the runtime ignores unknown keys: element definitions, mapper objects, layout options and factory options. They are closed where it throws: the sheet's keys, a group's property names and a bypass entry. Where the runtime coerces a form the declaration does not name, the declaration is the contract and the schema follows it.

#Public type glossary

The API reference shows JavaScript calls with TypeScript signatures. ? marks an optional argument or field; A | B accepts either type; T[] is an array; Promise<T> resolves asynchronously to T; this returns the receiver for chaining. A rest parameter (...args) accepts the tuple or list shown in its type. unknown requires narrowing before use; it is not a promise of a particular object shape.

Core is one graph instance. Collection is an ordered set of element handles owned by a core, including singleton node and edge handles. Position is an { x, y } coordinate pair. BoundingBoxInput supplies a layout rectangle; extent readers return an axis-aligned rectangle. NodeData and EdgeData are application-supplied data types; Data is the current collection's data view. Generic declarations preserve these types without changing runtime data validation.

The following glossary describes public option and result types. Fields are shown beside the functions that accept options; this index gives each named type a stable link.

AlgoRun #
The promise an async algorithm returns: a `Promise` of the result plus `cancel()`. A caller that never cancels sees an ordinary promise.
BoundingBoxInput #
Public type used by the API; see the linked function contract for its fields and behavior.
BoxSelectionMode #
How the box-selection gesture decides what the band caught: `'contain'` selects only elements wholly inside it (the default), while `'overlap'` selects anything it touches.
BreadthFirstLayoutOptions #
Depth rows. Without a `boundingBox` the rows and ranks are spread over the viewport in *pixels*, as grid, circle, concentric and radial spread theirs (125.4). A compound parent is never a root or a placed node; parents derive from their children.
CaseClause #
One case clause: `when` (a condition, or an array AND-ed together) → `then`.
CaseMapper #
A conditional mapper: the first clause whose `when` holds supplies the value, else `else` (or the channel default). Clauses are tried in order. CPU-evaluated (multi-key, data-driven) — the declarative replacement for `(ele) => cond ? a: b` style functions, and the natural form for typed edges (`type == 'activation' →...`).
ChartScaleSpec #
Public type used by the API; see the linked function contract for its fields and behavior.
CircleLayoutOptions #
Public type used by the API; see the linked function contract for its fields and behavior.
CloneOptions #
Options for `cy.clone()`.
Collection #
An ordered set of element handles owned by one core.
ColumnarEdges #
Columnar edge payload; endpoints are indices into the payload's nodes (and, past them, its {@link ColumnarElements.refs}).
ColumnarElements #
Columnar bulk-load form of `elements`: typed-array columns ingest directly into the store with no per-element objects, and edges resolve endpoints by index with no id lookups. Optional miniature-state columns preserve a node's collapsed flag and applied factor with its current positions; ingest does not rescale those coordinates. A payload is self-contained — every edge endpoint indexes a node in the same payload — unless it carries `refs`, the ids of nodes already in the graph that it indexes past its own (a chunk of a progressive `cy.load()`). Convert definition-form JSON with `cytoscape.toColumnarElements(json)`.
ColumnarNodes #
Columnar node payload; all arrays are index-aligned with `count`.
ComponentPackingOptions #
The component-packing options the discrete layouts take under `packComponents: true` (item 58), the same spellings a force run's settle re-pack takes.
ConcentricLayoutOptions #
Public type used by the API; see the linked function contract for its fields and behavior.
Condition #
A condition over one data key: exactly one comparison operator. String and boolean data support `eq`/`ne`/`in` (strict equality); numeric data supports all. Missing data fails every comparison (so an unset key never matches).
Core #
One graph instance, including its viewport and lifecycle.
CursorMap #
The CSS cursor per interaction state. Every value is a CSS cursor keyword, or `''` meaning inherit — which hands that state back to whatever the app's own container sets, and is the default for `idle` so the canvas is silent where it has nothing to say.
CursorState #
What the pointer is doing and what it is over, as the cursor map reads it. `gesture` is the press mode the interaction layer decided at pointerdown — a press outranks hover, so a drag that crosses another node keeps saying `grabbing`.
CustomLayout #
The wrapper cy.layout({ impl }) returns: the builtins' shape plus promise() (resolves at this run's layoutstop).
CustomLayoutOptions #
The extension contract: a direct impl object/class — no name, no registry — plus any custom knobs the impl reads off ctx.options.
CytoscapeOptions #
Public type used by the API; see the linked function contract for its fields and behavior.
DataColumn #
One data() column, index-aligned with the payload: a plain array (holes/undefined = absent), a Float64Array (NaN = absent), or a dictionary-encoded string column.
DefinitionData #
A definition's `data`: {@link ElementData} untyped (any key), and the application's shape plus the first-class fields typed — so a misspelt key is an excess-property error.
DictColumn #
A dictionary-encoded string data column: `indices[i]` is a 1-based index into `dict` (0 = absent). Data values repeat heavily, so this is both the compact in-memory shape and the wire shape.
ElementData #
Public type used by the API; see the linked function contract for its fields and behavior.
ElementDefinition #
One element definition. Typed by `Data` — the node or edge shape given to `cytoscape<NodeData, EdgeData>( …)` — and untyped by default.
ElementFields #
The first-class fields a definition's `data` may carry beside the application's own: the typed counterpart of {@link ElementData}'s named members, without its index signature.
ElementsDefinition #
Many elements: a flat array (each def's group inferred), or the `{ nodes, edges }` map, whose buckets are typed by the node and edge shapes respectively.
ElementsInput #
Any accepted `elements` input: the definition form (JSON objects), a single definition, the columnar bulk-load form, or a binary buffer from `cytoscape.serializeElements` (one little-endian ArrayBuffer + header — fetch it as binary and pass it straight in; no JSON parse).
Event #
An event. Handlers receive one of these; `cy.emit()` and `eles.emit()` accept either a type string or a props object, and build it.
EventHandler #
An event handler. `this` is the callback context the emitter's options choose — the core, or the phase element during compound bubbling.
EventProps #
The fields an emit may carry.
EventTarget #
What an event can target: the core for core-level events (viewport gestures, `layoutstart`, graph `data`), or a one-element collection for element events. Typed by the instance's data shapes, untyped by default.
ExportOptions #
Options for `cy.png()`/`cy.jpg()` image export. Export is async (the pixels are rendered on and read back from the GPU) and only available on rendered instances — headless instances reject.
FlowLayoutOptions #
The built-in flow layout: the Sugiyama-class layered layout — greedy-FAS cycle removal, network-simplex layering, crossing minimization by weighted layer sweep, Brandes–Köpf coordinates. Emits node positions only: pair it with `curve-style: taxi` (or bezier) and the edges route themselves, staying correct when nodes are dragged. Runs through the extension contract, so `cy.layout({ name: 'flow' })` returns a wrapper with `promise()`.
FollowOptions #
How a following clone synchronizes with its source.
ForceLayoutOptions #
The built-in force layout: spring–electric with uniform-grid cutoff repulsion, seeded and deterministic; runs through the extension contract.
GpuErrorInfo #
The payload of the core's `gpuerror` event: `cy.on( 'gpuerror', ( evt, info) => …)`. Fired when the renderer's device refused an allocation, reported an error nothing else caught, or when the renderer stopped drawing a feature because its buffer would not fit the device — the degradation order: labels first, then charts and images, then gradients.
GpuMemoryStats #
The renderer's allocation ledger: every buffer and texture its device creates, counted at creation and at `destroy()`. WebGPU exposes no memory meter, so these are the renderer's own figures — requested bytes, not what the driver commits — and a figure that trends upward across a session at a fixed graph size is a leak. All zero before `ready`.
GridLayoutOptions #
Public type used by the API; see the linked function contract for its fields and behavior.
HeadlessOptions #
The options of the slim builds' factories — `cytoscape/headless` and `cytoscape/headless-gpu`: {@link CytoscapeOptions} minus the fields only a renderer or the pointer handler reads. A build with no renderer has nothing to honour them with, so the type rejects them (TypeScript's excess-property check) and, at run time, a `container` throws `this build has no renderer — import 'cytoscape'`.
LayoutBaseOptions #
Options shared by the discrete layouts (scope, fit, spacing, animation).
LayoutComponentInfo #
What `componentGroup` and `componentOrder` see: one description per disconnected component (121.1; shared by force, the discrete layouts under `packComponents` and the `pack` layout since 123).
LayoutContext #
Public type used by the API; see the linked function contract for its fields and behavior.
LayoutImpl #
Public type used by the API; see the linked function contract for its fields and behavior.
LayoutOptions #
Public type used by the API; see the linked function contract for its fields and behavior.
LayoutScoreMapping #
A data-driven score for a layout param (#1514) — the canonical, serializable alternative to a function. Bare `{ data }` passes the column value through (the value *is* the score/length); with `range`, the column's extent is normalized through `scale` into `[range[0], range[1]]`, and `invert: true` flips it — e.g. `edgeLength: { data: 'score', scale: 'log', range: [40, 200], invert: true }` maps large scores to short edges. Resolved once at layout start; a missing value takes `default` (else the option's own default); an unknown key or a non-number column throws.
LayoutSortMapping #
A data-driven sort for a layout param — the canonical, serializable alternative to a comparator function: order by one column, missing values last, ties broken ascending on the id (so the order is deterministic by construction). A number or string column; mixed throws.
Legend #
JSON-safe, detached legend metadata for one Cytoscape instance.
LegendEntry #
One shared mapper or chart description returned by {@link Core.legend }.
LegendException #
A bounded summary of style bypasses affecting one shared legend entry.
LegendGroup #
A group named by an authored stylesheet definition.
LoadOptions #
Options for `cy.load()`.
LoadProgress #
How far a load has got: the chunks ingested and the elements they added.
LoadRun #
The promise `cy.load()` returns: it resolves with the final {@link LoadProgress} once the source is exhausted and the last chunk is ingested. Call `cancel()` to stop an unfinished load.
Mapper #
A data-driven style mapping: a plain serializable object appearing as a prop value in the sheet. `{ data: key }` alone is a passthrough (the datum is the value; 'id' reads the first-class id — label only); adding `range` (and usually `domain`) scales the datum.
MapperSpec #
Any data-driven style value: a scale mapper or a conditional.
PackedIds #
Ids as bytes: one UTF-8 blob + prefix byte offsets (length count + 1). Zero-length entries are auto-generated. This is the wire format's id representation, and the store ingests it without materializing any JS strings — id strings are decoded lazily, per element touched.
PackLayoutOptions #
The `pack` layout (item 58): a translation-only re-pack of the components at their current positions — force's settle re-pack on its own, for a drawing whose structure is done (a sim, a preset, a hand arrangement) and only wants its components grouped, ordered and packed. The largest component holds its centre. No shapes or orientation: those need edge lengths and belong to `force`.
PatchDiff #
What a patch did — returned by `cy.patch()` and carried by its `patch` event as `event.diff`. An edge the payload rewired (the same id, a new source or target) is in both `removed` and `added`, since it was removed and re-added; an element is never in `updated` and either of the others.
PatchMode #
How a patch treats the live elements its payload does not name: `'reconcile'` removes them (the payload is the new state), `'merge'` keeps them (the payload is a set of upserts).
PatchOptions #
Options for `cy.patch()`.
Position #
Public type used by the API; see the linked function contract for its fields and behavior.
PresetLayoutOptions #
Public type used by the API; see the linked function contract for its fields and behavior.
RadialLayoutOptions #
The radial tree layout: concentric rings with hierarchy-aware angular wedges — each subtree occupies a contiguous sector sized by its weight, so subtrees never interleave.
RandomLayoutOptions #
Public type used by the API; see the linked function contract for its fields and behavior.
RendererOptions #
Renderer tuning knobs (all LOD values in device px).
RendererStats #
Snapshot returned by `cy.renderer().stats()`.
StyleProps #
Style props for one element or group; names are kebab-case or camelCase. Values are constants, scale mappers ({@link Mapper}), conditionals ({@link CaseMapper}), or chart scale objects ({@link ChartScaleSpec}); `label` also takes the `data(key)` mapper string ('id' reads the first-class id). Node props: background-color, width, height, shape, opacity, border-color, border-width, label, font-size, font-family (constant only, effectively global — one font per glyph atlas), color. Edge props: line-color, width, opacity, source/target-arrow-shape and -color.
StylePropValue #
A style prop value: a constant, mapper, or chart scale object.
Stylesheet #
The stylesheet — no selectors, no style functions. Each group key is a props object whose values are constants or mapper objects; all per-element variation is expressed declaratively through mappers ({@link Mapper} scales, {@link CaseMapper} conditionals), which are analyzable, serializable, and evaluated on the GPU where possible. Everything stays fresh automatically: a data write re-derives the mapped channels of the affected elements (gated on the mapped keys).
ToColumnarOptions #
Options for {@link toColumnarElements}.
ViewportCounts #
What `cy.viewportCounts()` resolves with: how many nodes and edges the renderer's cull kept for one drawn frame — the elements actually drawn, after the viewport test, `visibility` and the level of detail (a node below `hidePx`, a decimated hairline edge). Compound parents count as nodes; labels are not counted.
WheelBehavior #
What a wheel over the canvas does (the #1905/#3287 family). The trackpad pinch arrives as a ctrl+wheel, so every mode keeps pinch-zoom:
WorkerFontFace #
One font face for the worker-hosted renderer's labels. A worker does not inherit the page's `@font-face` registrations, so the worker host registers the faces listed in `renderer.fonts` in its own worker, from their bytes — the family, the descriptors and the source the `FontFace` constructor takes, with a url fetched rather than passed through.

#Getting started

Choose a runtime entry, create a graph and handle readiness.

#Package and runtime entries

Getting started › Package and runtime entries

Choose the full, headless or headless GPU entry.

#Package and runtime

The preview is currently 4.0.0-unstable and has not been published to npm. Use a local build of this repository to try it. The import examples below assume your project resolves cytoscape to that local package.

To build locally, use Node 24 or later in the repository root:

Terminal window
npm install
npm run build
npm run build:types

Then install the local package in your application (replace the path):

Terminal window
npm install /absolute/path/to/cytoscape.js

Choose the full entry for an interactive browser graph, or the headless entry for analysis on a server. Node 24 or later and Bun 1.4.0 or later support headless work. See Supported environments for details.

#First graph and readiness

Getting started › First graph and readiness

Create a core and handle synchronous construction and asynchronous renderer readiness.

In a browser application with a module bundler and WebGPU, put the container, its size and the script together. You will see two labelled nodes, Alpha and Beta, joined by an edge:

<div id="graph" style="width: 800px; max-width: 100%; height: 600px"></div>
<script type="module">
import cytoscape from 'cytoscape';
try {
const cy = cytoscape({
container: document.getElementById('graph'),
elements: [
{ data: { id: 'a', label: 'Alpha' } },
{ data: { id: 'b', label: 'Beta' } },
{ data: { id: 'ab', source: 'a', target: 'b' } },
],
style: { nodes: { label: 'data(label)' } },
layout: { name: 'grid' },
});
await cy.ready;
} catch (error) {
document.getElementById('graph').textContent = error.message;
}
</script>

The rendered build needs a non-zero-size container and WebGPU. The factory throws immediately if the browser has no navigator.gpu; a browser can still expose WebGPU while failing to acquire a usable adapter, in which case cy.ready rejects. Keep both stages in the error path of an application. The factory creates the model synchronously, ingests initial elements through a bulk path and starts the requested layout; ready reports renderer readiness, not a general promise that makes graph reads asynchronous.

For CPU-only work, omit the container or import the explicit headless entry:

import cytoscape from 'cytoscape/headless';
const cy = cytoscape({
elements: [
{ data: { id: 'a' } },
{ data: { id: 'b' } },
{ data: { id: 'ab', source: 'a', target: 'b', weight: 2 } },
],
});
const path = cy.elements().dijkstra({
root: cy.getElementById('a'),
weight: edge => edge.data('weight'),
}).pathTo(cy.getElementById('b'));

cytoscape/headless has no renderer or WebGPU code. It includes the CPU algorithm path and all layouts, with a worker pool where available. If a headless process needs an explicit GPU algorithm executor or GPU force host, use cytoscape/headless-gpu; it does not provide png(), jpg(), pointer gestures or a canvas. An explicit GPU executor rejects when the required device is not available. An auto executor can choose a supported CPU or worker lane according to that algorithm's documented policy.

In a browser without a module bundler, the full package also builds UMD files. Serve the locally built UMD bundle from your application and use the global cytoscape factory:

<div id="graph" style="width: 800px; max-width: 100%; height: 600px"></div>
<script src="/vendor/cytoscape.min.js"></script>
<script>
const cy = cytoscape({
container: document.getElementById('graph'),
elements: [{ data: { id: 'a' } }],
});
</script>

Serve the bundle from your application, replacing /vendor/cytoscape.min.js with its actual path. A container-backed instance has the same WebGPU requirement regardless of how its JavaScript was loaded.

#Layout and container size

Getting started › Layout and container size

Give the container a size and wait for layout completion when needed.

#Layout and size

The first-graph examples set the container's width and height inline. You can move these rules into your stylesheet; keep a non-zero width and height.

After construction, query cy.ready, then read or mutate the core and its collections synchronously. For a later layout, create a handle, call run(), and await promise() when completion matters:

const layout = cy.layout({ name: 'circle', fit: true });
layout.run();
await layout.promise();

Layout lifecycle events are emitted on the core (layoutstart, layoutready, layoutstop). Layout objects are handles, not event emitters.

The API reference describes the contract for constructor options, built-in layouts, algorithms and their failure modes. See notation for the graph data forms, styles for sheet values and layouts for layout scope and extension behavior.

#Supported environments

Getting started › Supported environments

Choose a supported runtime for rendering or headless analysis.

Choose an entry according to the environment and the work it needs to do. The headless entry supports graph data, queries, CPU algorithms and layouts. Rendering requires a browser page with a usable WebGPU adapter.

#Requirements and support

Capability Entry Requirements
Headless graph operations cytoscape/headless ES2022, typed arrays, TextEncoder with encodeInto, TextDecoder and queueMicrotask.
Worker algorithms and force simulation Any entry Node/Bun worker_threads, or a browser page with Worker, Blob and URL.createObjectURL.
GPU algorithms and force simulation cytoscape/headless-gpu or cytoscape navigator.gpu and a usable adapter. No canvas is needed for compute.
Interactive rendering and image export cytoscape A browser page with WebGPU and a container with a non-zero size. No Canvas 2D fallback.

Browser and GPU capabilities depend on the operating system, drivers and browser settings. Limited support applies to the listed versions; check the required APIs when using another version or host.

Environment Headless graph work Workers Rendering / GPU compute Support
Node 24 or later Yes Yes Unavailable without navigator.gpu. Supported.
Bun 1.4.0 or later Yes Yes, using worker_threads No WebGPU in tested Bun 1.4.0 and 1.4.3. Supported.
Cloudflare Workers (workerd) Yes, using cytoscape/headless No worker pool; auto runs on the current thread. No. Supported.
Other V8 isolate environments Expected where the required APIs are present. No worker pool. No. Compatibility must be checked in the target host.
Chromium and WebKit pages Yes Yes Available where WebGPU and an adapter are available. Supported; GPU features require a usable adapter.
Chromium and WebKit dedicated, shared and service workers Yes No pool; work runs on the hosting worker's thread. Rendering unavailable; GPU compute unmeasured. Headless supported.
Firefox pages and workers Tested on Firefox 151. In pages; no pool in worker contexts. Depends on WebGPU availability; Linux WebGPU was unavailable in testing. Limited support: Firefox 151.
Electron Main process supports headless operations and workers. Yes in the main process. Renderer process needs WebGPU; Linux may require explicit flags. Limited support: Electron 44.4.5.
Tauri with a Node sidecar The sidecar follows Node requirements. The sidecar's workers. Depends on the system webview. Sidecar only; webview compatibility varies.
React Native / Hermes Requires a TextDecoder polyfill and compatible modern Hermes. No. No. Experimental; not supported.
QuickJS-ng and GraalJS Requires UTF-8 codec shims; GraalJS also needs queueMicrotask. No. No. Experimental; not supported.
Deno Not evaluated. Not evaluated. Not evaluated. Not supported.
Audio worklets Required APIs are missing in tested engines. No. No. Not supported.

#Choosing a runtime

A headless instance does not become rendered when it runs in a browser. Supply a container with the full entry to display a graph. When WebGPU is absent, construction with a container throws. When adapter acquisition fails later, cy.ready rejects. Handle both failures in your application.

A graph hosted inside a worker already runs off the page's main thread. Its algorithms can execute on that thread without creating a nested pool. The page's renderer: { worker: true } option is a separate feature: it hosts rendering through an OffscreenCanvas belonging to the page.

Edge runtimes often impose CPU limits. Ingest, algorithms and layouts all consume that budget, even when the library itself fits in the deployment. Measure your actual graph and operation mix against the host's current limits.

Electron applications on Linux may need to configure WebGPU before the app's ready event. Testing with X11 and --use-angle=vulkan --enable-features=Vulkan reached a hardware adapter; --enable-unsafe-webgpu alone used a software adapter. A web page cannot set these application flags.

#Error types

Getting started › Error types

Handle cancellation and unavailable GPU execution using the documented error types.

#cytoscape.CancelledError

// Thrown (as a rejection) by a cancelled run: an async algorithm whose handle's cancel() was called, a layout's promise() after layout.cancel(), or either when cy.destroy() ran while the run was in flight
cytoscape.CancelledError: CancelledError

Thrown (as a rejection) by a cancelled run: an async algorithm whose handle's cancel() was called, a layout's promise() after layout.cancel(), or either when cy.destroy() ran while the run was in flight. error.name is 'CancelledError', so a .catch can tell a cancellation from a defect without importing the class.

Returns CancelledError

Example

const error = new cytoscape.CancelledError();
console.log(error instanceof cytoscape.CancelledError); // true

Example graph and handle setup

#cytoscape.GpuUnfitError

// A graph or algorithm input exceeds the GPU device's limits
cytoscape.GpuUnfitError: GpuUnfitError

A graph or algorithm input exceeds the GPU device's limits.

Adding, loading or patching elements on a rendered core can throw this error before changing the graph. Mounting a graph that does not fit rejects cy.ready.

An explicit GPU algorithm rejects with this error when its input does not fit. With executor: 'auto', that algorithm falls back to the CPU instead. Other GPU errors still propagate.

Test error instanceof cytoscape.GpuUnfitError, or check error.name === 'GpuUnfitError', to distinguish this failure.

Returns GpuUnfitError

Example

// Catch an algorithm or layout error before choosing a CPU fallback.
const isDeviceLimit = error => error instanceof cytoscape.GpuUnfitError;
console.log(isDeviceLimit(new Error('application error'))); // false

Example graph and handle setup

#Task recipes

Combine reference methods into common application tasks.

These recipes combine small operations into application tasks. The reference's short examples use the three-node path below unless they say they require a browser, an event handler, an animation handle or a layout handle. Start each example with a fresh graph; examples that remove or destroy objects are deliberately independent.

#Example graph

import cytoscape from 'cytoscape/headless';
const cy = cytoscape({
headless: true,
styleEnabled: true,
layout: { name: 'preset' },
elements: [
{ data: { id: 'a', score: 1 }, position: { x: 0, y: 0 } },
{ data: { id: 'b', score: 2 }, position: { x: 50, y: 0 } },
{ data: { id: 'c', score: 3 }, position: { x: 100, y: 0 } },
{ data: { id: 'ab', source: 'a', target: 'b', weight: 2 } },
{ data: { id: 'bc', source: 'b', target: 'c', weight: 3 } },
],
});
const eles = cy.elements();

cy owns the graph; eles initially contains five elements. An event in an example is the argument supplied to an event handler. An ani is obtained with cy.animation({ pan: { x: 10, y: 10 }, duration: 1 }); layout is obtained with cy.layout({ impl: { run(ctx) { ctx.layoutPositions((node, i) => ({ x: i * 40, y: 0 }), { fit: false }); } } }). A ctx is supplied to a custom layout's run(ctx) method. Call cy.destroy() when the task ends.

#Add and style a neighbourhood

Add nodes before using their ids in subsequent calls. A single payload may contain both new nodes and their edges. Use one batch for related data writes; style-derived reads belong after the batch ends.

const added = cy.add([
{ data: { id: 'd', score: 4 } },
{ data: { id: 'cd', source: 'c', target: 'd', weight: 1 } },
]);
cy.batch(() => {
added.nodes().data('reviewed', true);
cy.getElementById('c').data('reviewed', true);
});
cy.style({ nodes: { 'background-color': '#369', width: 30 } });
console.log(cy.getElementById('d').data('reviewed')); // true

Reference: add, batch, element data, stylesheet.

#Trace a weighted route

Choose the graph scope, direction and weight explicitly. On the example path, the cost from a to c is 2 + 3 = 5. Dijkstra is synchronous for this execution form; methods that return an AlgoRun require await run.

const result = eles.dijkstra({
root: cy.getElementById('a'),
directed: true,
weight: edge => edge.data('weight'),
});
const destination = cy.getElementById('c');
console.log(result.distanceTo(destination)); // 5
console.log(result.pathTo(destination).nodes().map(node => node.id()));
// ['a', 'b', 'c']

Reference: Dijkstra, lookup by id, mapping collections.

#Attach and remove a delegated listener

Store the predicate and handler so cleanup uses the same function objects. Delegation follows targets added after the listener was attached. Event names match literally; an application event named review is independent of review.ui.

const isNode = ele => ele.isNode();
const reviewed = [];
const onReview = event => reviewed.push(event.target.id());
cy.on('review', isNode, onReview);
cy.getElementById('a').emit('review');
cy.off('review', isNode, onReview);
cy.getElementById('b').emit('review');
console.log(reviewed); // ['a']

Reference: listen, remove listener, emit, event target.

#Save graph data and recreate a core

The compact wire payload carries graph data and element state covered by its contract. Keep stylesheet, viewport and other application state separately. Adding a wire payload into an existing graph deliberately ignores graph-level data; constructor loading applies it.

cy.data('title', 'Three-node path');
const buffer = cy.serialize();
const restored = cytoscape({ headless: true, elements: buffer });
console.log(restored.nodes().length); // 3
console.log(restored.data('title')); // 'Three-node path'
restored.destroy();

Reference: serialize, construct a core, graph data.

#Core

The core owns a graph, its viewport and instance-wide operations.

The core (cy) is the graph, its stylesheet and its viewport. It owns instance-wide data, events, loading, layouts, exports and renderer lifetime. An application creates one core per independent graph/view. cy.clone() makes a second model and renderer when the same graph should appear in another container; it is not a second renderer attached to one mutable store.

#Initialisation and lifecycle

Core › Initialisation and lifecycle

Construct, mount, inspect readiness and dispose of a core.

#Construction and readiness

The factory reads options.elements through the bulk path and runs options.layout if supplied. It returns a usable core synchronously. With a container, it also installs the renderer and pointer handler and requires WebGPU. Missing navigator.gpu is a synchronous constructor error; adapter acquisition is asynchronous and settles through cy.ready. In headless mode, there is no renderer readiness wait and no GPU requirement.

Unknown options are ignored at runtime. TypeScript catches excess option keys at compile time; runtime option validation does not try to recreate that type check. Style sheets and structured queries are stricter: their unknown keys throw because a typo there could otherwise silently alter rendering or match the whole graph.

#cytoscape(options?)

// Create a graph instance for queries, analysis, layouts and optional interactive rendering — Full entry
cytoscape<NodeData = Untyped, EdgeData = DefaultEdgeData<NodeData>>(options?: CytoscapeOptions<NoInfer<NodeData>, NoInfer<EdgeData>>): Core<NodeData, EdgeData>

// Create a graph instance for queries, analysis, layouts and optional interactive rendering — Headless entry
cytoscape<NodeData = Untyped, EdgeData = DefaultEdgeData<NodeData>>(options?: HeadlessOptions<NoInfer<NodeData>, NoInfer<EdgeData>>): Core<NodeData, EdgeData>

// Create a graph instance for queries, analysis, layouts and optional interactive rendering — Headless GPU entry
cytoscape<NodeData = Untyped, EdgeData = DefaultEdgeData<NodeData>>(options?: HeadlessOptions<NoInfer<NodeData>, NoInfer<EdgeData>>): Core<NodeData, EdgeData>

Create a graph instance for queries, analysis, layouts and optional interactive rendering. Supply container to display the graph, or omit it for headless use. Initial elements and the requested layout are applied during construction.

Rendering requires WebGPU. Construction throws when navigator.gpu is missing; cy.ready rejects if adapter acquisition fails later.

Use cytoscape/headless for CPU graph work without rendering, or cytoscape/headless-gpu for headless GPU algorithms and force layouts.

For typed application data, call cytoscape<NodeData, EdgeData>(options). Those shapes check element data, queries, mapper fields and event targets. Without type arguments, keys remain unrestricted and reads return unknown. Unknown constructor options are ignored at runtime; use TypeScript's CytoscapeOptions to catch misspelled names.

Parameters
NameDescription
options: CytoscapeOptions<NoInfer<NodeData>, NoInfer<EdgeData>>?Default: {}

the instance options; every field is optional, and an omitted container is what selects headless mode

Fields of options
NameDescription
container: HTMLElement | null?

Where to render. When given, WebGPU is required: the factory throws synchronously if navigator.gpu is missing. When omitted, the instance is headless (works in Node, never throws for missing GPU).

elements: ElementsInput<NodeData, EdgeData>?

the initial elements — typed by the instance's shapes

style: Stylesheet<NodeData, EdgeData>?

the stylesheet — its field references typed likewise

layout: LayoutOptions?
zoom: number?
pan: Position?
minZoom: number?
maxZoom: number?
autolock: boolean?

disable node dragging globally (default false)

autoungrabify: boolean?

make all nodes ungrabbable globally (default false)

autounselectify: boolean?

disable selection globally (default false)

panningEnabled: boolean?

allow panning at all — programmatic and user (default true)

userPanningEnabled: boolean?

allow user (pointer) panning (default true)

zoomingEnabled: boolean?

allow zooming at all — programmatic and user (default true)

userZoomingEnabled: boolean?

allow user (wheel/pinch) zooming (default true)

boxSelectionEnabled: boolean?

allow box selection (default true)

boxSelectionIncludesLabels: boolean?

box selection considers label boxes too (default false). Its sense follows boxSelectionMode: it narrows a 'contain' selection and widens an 'overlap' one.

boxSelectionMode: BoxSelectionMode?

what the box-selection gesture counts as selected: 'contain' (default) takes only elements wholly inside the band; 'overlap' takes anything the band touches.

selectionType: 'single' | 'additive'?

'single' (tap/box replaces the selection) or 'additive' (taps toggle, boxes add); default 'single'

multiClickDebounceTime: number?

the dbltap/onetap debounce window in ms (default 250)

wheelSensitivity: number?

wheel-zoom rate multiplier (default 1; custom values warn once — a sensitivity tuned to one mouse/OS zooms unnaturally on others).

wheelBehavior: WheelBehavior?

what a wheel does: 'zoom' (default), 'pan' (ctrl/meta — the pinch — still zooms) or 'modifier-zoom' (only a ctrl/meta wheel zooms; a plain wheel scrolls the page).

desktopTapThreshold: number?

css px a mouse/pen press may move and still count as a tap (default 4).

touchTapThreshold: number?

css px a touch press may move and still count as a tap (default 8).

tapholdDuration: number?

unmoved-press duration before 'taphold' fires, in ms (default 500).

pointerCursors: boolean | Partial<CursorMap>?

whether the canvas writes CSS cursors for the gesture affordances — grab/grabbing around dragging, pointer over an element, crosshair while boxing (default true).

false means the interaction layer never touches style.cursor, for an app that sets its own; an object overrides individual entries ({ pan: 'move' }), where '' means inherit.

headlessWidth: number?

rendered dimensions used when headless

headlessHeight: number?
pixelRatio: number | 'auto'?

device pixel ratio override; defaults to the window's

renderer: RendererOptions?
Returns Core<NodeData, EdgeData>

the new core, usable synchronously — reads and writes do not wait on the device, and a rendered instance additionally resolves cy.ready

Example

const graph = cytoscape({ headless: true, elements: [{ data: { id: 'start' } }] });
console.log(graph.nodes().length); // 1
graph.destroy();

Example graph and handle setup

Throws

when container is given and navigator.gpu is missing

Create a graph for queries, CPU algorithms and layouts without rendering. Use this entry on a server or whenever your application does not need a canvas. Worker execution is available where the environment supports it.

Initial elements and the requested layout are applied during construction. Use cytoscape<NodeData, EdgeData>(options) to check application data shapes with TypeScript. Unknown constructor options are ignored at runtime.

Parameters
NameDescription
options: HeadlessOptions<NoInfer<NodeData>, NoInfer<EdgeData>>?Default: {}

the instance options, without the renderer- and pointer-only fields (HeadlessOptions)

Fields of options
NameDescription
zoom: number?
pan: Position?
elements: ElementsInput<NodeData, EdgeData>?

the initial elements — typed by the instance's shapes

style: Stylesheet<NodeData, EdgeData>?

the stylesheet — its field references typed likewise

layout: LayoutOptions?
minZoom: number?
maxZoom: number?
autolock: boolean?

disable node dragging globally (default false)

autoungrabify: boolean?

make all nodes ungrabbable globally (default false)

autounselectify: boolean?

disable selection globally (default false)

panningEnabled: boolean?

allow panning at all — programmatic and user (default true)

zoomingEnabled: boolean?

allow zooming at all — programmatic and user (default true)

selectionType: 'single' | 'additive'?

'single' (tap/box replaces the selection) or 'additive' (taps toggle, boxes add); default 'single'

headlessWidth: number?

rendered dimensions used when headless

headlessHeight: number?
Returns Core<NodeData, EdgeData>

the new core

Throws

when a container is given — this build has no renderer

Create a headless graph that can also run GPU algorithms and GPU force layouts. This entry includes the CPU graph features of cytoscape/headless, but no canvas, pointer gestures or image export.

Initial elements and the requested layout are applied during construction. An explicit GPU executor requires a usable WebGPU adapter. Use cytoscape<NodeData, EdgeData>(options) to check application data shapes with TypeScript. Unknown constructor options are ignored at runtime.

Parameters
NameDescription
options: HeadlessOptions<NoInfer<NodeData>, NoInfer<EdgeData>>?Default: {}

the instance options, without the renderer- and pointer-only fields (HeadlessOptions)

Fields of options
NameDescription
zoom: number?
pan: Position?
elements: ElementsInput<NodeData, EdgeData>?

the initial elements — typed by the instance's shapes

style: Stylesheet<NodeData, EdgeData>?

the stylesheet — its field references typed likewise

layout: LayoutOptions?
minZoom: number?
maxZoom: number?
autolock: boolean?

disable node dragging globally (default false)

autoungrabify: boolean?

make all nodes ungrabbable globally (default false)

autounselectify: boolean?

disable selection globally (default false)

panningEnabled: boolean?

allow panning at all — programmatic and user (default true)

zoomingEnabled: boolean?

allow zooming at all — programmatic and user (default true)

selectionType: 'single' | 'additive'?

'single' (tap/box replaces the selection) or 'additive' (taps toggle, boxes add); default 'single'

headlessWidth: number?

rendered dimensions used when headless

headlessHeight: number?
Returns Core<NodeData, EdgeData>

the new core

Throws

when a container is given — this build has no renderer

#cy.ready

// Resolves once the render pipeline is usable (immediately when headless) — and, under an initial cy.load(), once its first chunk is drawn (headless, once it is in the model)
cy.ready: Promise<Core<NodeData, EdgeData>>

Resolves once the render pipeline is usable (immediately when headless) — and, under an initial cy.load(), once its first chunk is drawn (headless, once it is in the model). Rejects when no adapter can be had.

Returns Promise<Core<NodeData, EdgeData>>

Example

await cy.ready;
console.log(cy.isReady()); // true

Example graph and handle setup

#cy.isReady()

// Whether the render pipeline is usable yet
cy.isReady(): boolean

Whether the render pipeline is usable yet. Always true on a headless instance; on a rendered one this flips when cy.ready resolves.

Returns boolean

true once rendering can proceed

Example

console.log(cy.isReady()); // true

Example graph and handle setup

#cy.unmount()

// Detach the renderer: the instance becomes headless (the model is CPU-canonical, so nothing is lost)
cy.unmount(): this

Detach the renderer: the instance becomes headless (the model is CPU-canonical, so nothing is lost). No-op when already headless.

Returns this

Example

// Detach a rendered core without removing its graph data.
cy.unmount();
console.log(cy.nodes().length); // 3

Example graph and handle setup

#cy.mount(container)

// (Re)attach a renderer to a container
cy.mount(container: HTMLElement): this

(Re)attach a renderer to a container. Re-mounting to a different container unmounts first; the fresh renderer re-uploads every column from the CPU-canonical model and rebuilds all glyph runs.

Parameters
NameDescription
container: HTMLElement

the element to render into

Returns this

this

Example

// container is an existing, sized HTML element.
cy.mount(document.getElementById('graph'));
await cy.ready;

Example graph and handle setup

Throws

if no container is given, if the instance was built directly rather than through the cytoscape factory (there is no renderer to attach), if it was built by cytoscape/headless or cytoscape/headless-gpu (a build with no renderer), or if WebGPU is unavailable — mounting is the one way a headless instance can demand a GPU after construction

#cy.container()

// The DOM element this instance renders into, or null when headless or unmounted
cy.container(): HTMLElement | null

The DOM element this instance renders into, or null when headless or unmounted.

Returns HTMLElement | null

the container element, or null

Example

console.log(cy.container()); // null

Example graph and handle setup

#cy.destroy()

// Tear the instance down: emit destroy, drop every listener, and release the pointer handler and the renderer (with its GPU resources)
cy.destroy(): this

Tear the instance down: emit a destroy event, drop every listener, and release the pointer handler and the renderer (with its GPU resources). Idempotent. The store is left intact but the instance must not be used afterwards.

Returns this

this core

Example

cy.destroy();
console.log(cy.destroyed()); // true

Example graph and handle setup

#cy.destroyed()

// Whether destroy() has run
cy.destroyed(): boolean

Whether destroy() has run.

Returns boolean

true once destroyed

Example

console.log(cy.destroyed()); // false
cy.destroy();
console.log(cy.destroyed()); // true

Example graph and handle setup

#Graph manipulation

Core › Graph manipulation

Add, reconcile or progressively load graph data, and batch related writes.

#Adding, removing and reconciling

Core › Graph manipulation › Adding, removing and reconciling

Insert definitions or reconcile a fresh graph payload by identity.

#Loading, mutation and batching

add() inserts new definitions, columnar data or wire data. Edges in a payload can refer to nodes supplied alongside them. patch() reconciles a fresh view of the same graph by id: it updates surviving elements, removes absent ones in reconcile mode and returns added/removed/updated collections. Reconciliation keeps the surviving element's session state such as listeners and selection; the payload replaces data fields rather than deep-merging them. Rewiring an edge is a removal/addition, not an update to its identity.

#cy.add(input)
// Add elements to the graph and return them as a collection
cy.add(input: | ElementsInput<NodeData, EdgeData> | Iterable<ElementDefinition<NodeData | EdgeData>>): Collection<NodeData, EdgeData>

Add elements to the graph and return them as a collection.

Takes all three input forms: the element-definition form (one object, an array, or { nodes, edges }), the columnar bulk form (typed-array columns with edge endpoints as node indices), and the binary wire buffer produced by serializeElements/cy.serialize(). Nodes are added before edges, so an edge may reference a node added in the same call. Wire and columnar inputs may carry miniature state with current positions; adding them does not rescale those coordinates.

Fires an add event per element. Inside a batch the first style application of the new elements defers to the outermost endBatch(), so style-derived reads (width(), label()) may be stale until then.

Graph-level data() in a wire buffer is ignored here, where options.elements applies it: adding elements to a populated graph must not overwrite that graph's own data(). Apply it explicitly with cy.data( deserializeElements( buf).data) if that is what you want.

Any iterable of element definitions is accepted too — a generator, a Set, a Map's values() — and is read once into an array, then added exactly as that array would be. A wire buffer's typed-array view is iterable as well, and is decoded as a wire payload, never walked as definitions.

Parameters
NameDescription
input: | ElementsInput<NodeData, EdgeData> | Iterable<ElementDefinition<NodeData | EdgeData>>

elements in definition, columnar or wire form, or an iterable of element definitions

Fields of input
NameDescription
columnar: true

discriminant so the loader can tell the forms apart

nodes: ElementDefinition<NodeData>[]?
edges: ElementDefinition<EdgeData>[]?
refs: string[] | PackedIds?

Node references (experimental with the wire format until 4.x): the ids of nodes this payload does not carry but indexes — an edge endpoint or a node parent nodes.count + i names refs[i]. Each must name a node already in the graph when the payload loads (an earlier chunk of a cy.load(), or anything cy.add() put there); one that does not throws before anything is added. Each id resolves once however many edges index it, which is what makes a chunk's cut edges as cheap as its own. The factory's options.elements loads into an empty graph, so a payload with refs cannot load there; cy.patch() refuses one. Build it from definitions with toColumnarElements( defs, { refs: true }).

data: DefinitionData<Data>?
group: GroupName?

inferred from data.source/data.target when omitted

position: Position?

nodes only

collapsed: boolean?

nodes only: persisted miniature-compound state

appliedCollapseScale: number?

nodes only: current applied factor when collapsed; omitted uses the configured collapse-scale

selected: boolean?
selectable: boolean?
grabbable: boolean?
locked: boolean?
pannable: boolean?

dragging this element pans the graph instead (default: true for edges, false for nodes)

Returns Collection<NodeData, EdgeData>

a collection of the added elements

Example

const added = cy.add([
{ data: { id: 'd' } },
{ data: { id: 'cd', source: 'c', target: 'd' } },
]);
console.log(added.length); // 2

Example graph and handle setup

Throws

if input is a collection: removed elements cannot be restored (MIGRATING.md, "Removed elements are terminally dead") — add the definitions you kept, e.g. from eles.jsons() taken before the removal

#cy.remove(eles)
// Remove elements from the graph
cy.remove<Data>(eles: Collection<NodeData, EdgeData, Data>): Collection<NodeData, EdgeData, Data>

Remove elements from the graph. Removing a node removes its connected edges, and removing a compound parent removes its descendants. Equivalent to eles.remove().

Parameters
NameDescription
eles: Collection<NodeData, EdgeData, Data>

the elements to remove

Returns Collection<NodeData, EdgeData, Data>

the removed elements

Example

cy.remove(cy.getElementById('c'));
console.log(cy.hasElementWithId('c')); // false

Example graph and handle setup

#cy.patch(input, options?)
// Reconcile a fresh payload into the live graph by id: the payload is the next state of the same graph — the next query result, a server's refresh — and the patch computes what to add, remove and update, applies it as one batch, and returns what it did
cy.patch(input: ElementsInput<NodeData, EdgeData>, options?: PatchOptions): PatchDiff<NodeData, EdgeData>

Reconcile a fresh payload into the live graph by id: the payload is the next state of the same graph — the next query result, a server's refresh — and the patch computes what to add, remove and update, applies it as one batch, and returns what it did. A surviving element keeps selection, bypasses, running animations, listeners and scratch. Position follows the payload when carried; miniature state and its applied factor are adopted together with those current positions. The sheet, viewport and graph-level data() are never touched — elements only.

cy.json() is export-only; use a fresh core to restore a serialized session. patch() updates an existing graph. It reconciles a data refresh, and it takes all three input forms — definition, columnar and wire — through the load path's one funnel.

The rules, per payload element, keyed on its id: - Survives when the graph holds the id in the same group (and, for an edge, the same source and target). Its data record is replaced, not deep-merged: a key the payload element lacks is cleared, and a value compares structurally, so a fresh payload equal to the state changes nothing. Its position is written when the payload carries one and kept when it does not — except that a locked node (or every node, under autolock) holds its position and a compound parent's derives from its children, as at load. Its parent follows the payload (none means an orphan). Its miniature state follows when carried; the payload's applied factor is installed without rescaling its already-current positions. Its selection and selectable/locked/grabbable/pannable flags are session state and are never read from the payload. - Added when the id is new, and when the payload element has no id — exactly as cy.add() would add it, flags included. - Removed and re-added when an edge's source or target changed identity (rewiring is not a patch), or when the id changed group. - Removed when the graph holds an id the payload does not name — in 'reconcile' mode, the default. In 'merge' mode it is kept, and a definition-form payload may name kept nodes as endpoints and parents. Removal cascades as remove() does.

Events: remove, add, moveout + move (a reparented survivor), data, position, and committed collapse/expand state changes fire once per element, inside the batch and after every mutation has landed; then one core-level patch event carries the diff as event.diff — for an app that only wants the summary. A patch whose payload equals the state fires no element event, writes nothing and returns an empty diff (its patch event still fires). The patch is one transaction: batchstart, the element events, patch, then batchend; inside an app's batch it joins that one, and patch fires before the app's batchend.

Parameters
NameDescription
input: ElementsInput<NodeData, EdgeData>

the payload, in definition, columnar or wire form

options: PatchOptions?

{ mode }: 'reconcile' (default) or 'merge'

Fields of input
NameDescription
columnar: true

discriminant so the loader can tell the forms apart

nodes: ElementDefinition<NodeData>[]?
edges: ElementDefinition<EdgeData>[]?
refs: string[] | PackedIds?

Node references (experimental with the wire format until 4.x): the ids of nodes this payload does not carry but indexes — an edge endpoint or a node parent nodes.count + i names refs[i]. Each must name a node already in the graph when the payload loads (an earlier chunk of a cy.load(), or anything cy.add() put there); one that does not throws before anything is added. Each id resolves once however many edges index it, which is what makes a chunk's cut edges as cheap as its own. The factory's options.elements loads into an empty graph, so a payload with refs cannot load there; cy.patch() refuses one. Build it from definitions with toColumnarElements( defs, { refs: true }).

data: DefinitionData<Data>?
group: GroupName?

inferred from data.source/data.target when omitted

position: Position?

nodes only

collapsed: boolean?

nodes only: persisted miniature-compound state

appliedCollapseScale: number?

nodes only: current applied factor when collapsed; omitted uses the configured collapse-scale

selected: boolean?
selectable: boolean?
grabbable: boolean?
locked: boolean?
pannable: boolean?

dragging this element pans the graph instead (default: true for edges, false for nodes)

Fields of options
NameDescription
mode: PatchMode?

'reconcile' (the default): the payload is the new state, and a live element it does not name is removed. 'merge': the payload is a set of upserts, and a live element it does not name is kept — a definition-form payload may then name kept nodes as endpoints and parents.

Returns PatchDiff<NodeData, EdgeData>

the diff: the added, removed and updated collections

Example

cy.patch([{ data: { id: 'a', score: 10 } }]);
console.log(cy.getElementById('a').data('score')); // 10

Example graph and handle setup

Throws

before anything is mutated, if the payload names an id twice, if an edge lacks a source or target or names one that is not a node (in the payload, or — merge mode — in the graph), if a column does not fit the payload's counts, or on an unknown option or mode

#Progressive loading

Core › Graph manipulation › Progressive loading

Consume chunks progressively and understand cancellation and partial failure.

load() progressively consumes an iterable or async iterable of chunks. It bulk-applies each chunk and gives the renderer a frame between chunks, so a partial graph can appear while a stream continues. Its promise resolves with progress counts and can be cancelled. Cancellation stops pulling the source but keeps already loaded chunks. A layout should start after the load promise resolves. See progressive loading for readiness, fit, event and failure details. cy.destroy() cancels active work owned by the core and disposes its renderer.

cy.load() ingests an iterable or async iterable whose values are graph chunks. Each chunk may use the standard element-definition array, a columnar payload or serialized wire data. It goes through the bulk ingest path, and the renderer gets a turn between chunks. The first chunk is drawn before the loader requests the next one, so the page can show correct partial state while the remaining data arrives.

async function* graphChunks() {
yield [
{ data: { id: 'a' } },
{ data: { id: 'b' } },
];
yield [{ data: { id: 'ab', source: 'a', target: 'b' } }];
}
cy.on('loadchunk', event => {
const { chunks, nodes, edges } = event.progress;
console.log(`chunk ${chunks}: ${nodes} nodes, ${edges} edges so far`);
});
const progress = await cy.load(graphChunks());
console.log(progress); // { chunks: 2, nodes: 2, edges: 1 }

An initial load starts while the core has no elements. It keeps cy.ready pending until the first chunk is drawn (or ingested in headless mode), and fits once to that first chunk by default. A load into a populated graph behaves like streamed add(): it does not replace existing elements, re-fit the viewport or apply chunk graph-level data. fit controls the one initial fit; padding supplies its rendered-pixel padding. No later chunk changes the viewport. Read cy.ready after calling load(), since an initial load replaces the promise with one that resolves after the first chunk is drawn.

Each chunk emits a loadchunk event after ingestion. loadstart fires before the source is first read, loadready follows the first drawn chunk, and loadstop closes a completed, failed or cancelled run. These events carry a progress snapshot { chunks, nodes, edges }. Bulk add events are also emitted for inserted elements when listeners are registered. No loadready event is emitted for a source that yields no chunks.

load() returns a promise with a required cancel() method. Cancelling stops the iterator, calls its return() when available, preserves chunks already ingested and rejects the promise with CancelledError. The loadstop event has cancelled: true; normal completion and input failure have cancelled: false. A failed chunk rejects the promise and earlier chunks remain. A chunk that refers to a node not yet present fails before adding any part of that chunk. Only one load may run on a core at a time. Start a layout after the load promise settles, so it sees the final intended graph.

load() consumes iterable values as chunks. A top-level array of element definitions is therefore a sequence of single-definition chunks; to load the whole array as one chunk, nest it: cy.load([[nodeA, nodeB]]). A lone definition object is not iterable and is rejected. A columnar or wire payload is also rejected as the source itself because its own iterable shape is not a chunk stream; wrap that payload in a one-item iterable such as cy.load([columnarPayload]). For a single addition, prefer cy.add(payload).

Type Contract
LoadOptions fit fits once to the first chunk (default on for an initial load, off into a populated graph); padding is rendered-pixel padding for that fit (default 0).
LoadProgress Cumulative { chunks, nodes, edges } counts.
LoadRun Promise<LoadProgress> augmented with cancel(): boolean; cancellation rejects while running, and cancel() returns false after settlement.

See cy.load() for parameters, return values and errors.

#Sizing a load

Use 5–20 chunks, with a small first chunk. A chunk costs about 1.5 ms of fixed overhead headless, plus a frame in a page. Node references repeat ids across chunks: +6% vertex-closed and +12% nodes-first at 10 chunks. Choose a small first chunk to show useful content early, then adjust later chunk sizes for your network and graph.

For ndex-x-large (19.6k nodes, 465k edges) from a wire payload, in milliseconds to the first frame and to the whole graph:

Link Scene First Whole
none monolithic 902 902
none vertex-closed, 10 chunks 374 1,107
100 Mbit/s monolithic 1,960 1,960
100 Mbit/s vertex-closed, 10 chunks 110 1,210
20 Mbit/s monolithic 6,176 6,176
20 Mbit/s vertex-closed, 10 chunks 350 5,667

With the whole payload in hand, the first frame comes about 2× sooner and the whole graph about 23% later. Over a link, progressive loading wins both, because ingest overlaps the transfer.

#cy.load(source, options?)
// Progressive ingest: load the graph chunk by chunk from an async iterable — a streamed response, a server's pages — and show a correct partial graph before the last byte arrives
cy.load(source: | AsyncIterable<ElementsInput<NodeData, EdgeData>> | Iterable<ElementsInput<NodeData, EdgeData>>, options?: LoadOptions): LoadRun

Progressive ingest: load the graph chunk by chunk from an async iterable — a streamed response, a server's pages — and show a correct partial graph before the last byte arrives. Each chunk is any input form (definition, columnar or wire); a chunk may name nodes an earlier chunk loaded — by id in the definition form, and through node references (refs) in the columnar and wire forms, which is what keeps a chunk's cut edges as cheap as its own. A plain iterable (an array of chunks) works too.

Every chunk lands through the bulk load path — one bulk style pass, no per-element handle — and the renderer gets a turn between chunks, even when the source hands them over synchronously; the second chunk is not asked for until the first is drawn. Every element drawn is correct; completeness arrives — a frame may show some of the graph, never a wrong piece of it.

An initial load — one that starts on an instance holding no elements, the streamed counterpart of options.elements — holds cy.ready until its first chunk is drawn (headless: until it is in the model), fits the viewport once to that chunk and then holds it (never a re-fit per chunk; fit: false keeps the viewport as it is), and applies the graph-level data() a wire chunk carries. The load re-points cy.ready, so read it after calling load() — a reference taken before resolves on the renderer alone. A load into a populated graph is a streamed cy.add(): cy.ready, the viewport and data() are left alone. Positions are the payload's (the preset layout case); a layout cannot start while a load runs — run it once the promise resolves.

Events: loadstart; loadchunk after each chunk (with add per element while anyone listens for it, as the bulk path emits them); loadready once the first chunk is drawn; loadstop when the load ends — completed, failed or cancelled (event.cancelled). Each carries event.progress: { chunks, nodes, edges } so far.

Completion is the returned promise, resolving with the final progress; it carries cancel() (contract): cancelling stops pulling chunks, closes the source's iterator, keeps what has landed, and rejects with a CancelledError. cy.destroy() cancels a running load. A chunk that fails to ingest rejects the load; the chunks before it stay, and a node reference that names no node fails its chunk before anything of it is added.

Parameters
NameDescription
source: | AsyncIterable<ElementsInput<NodeData, EdgeData>> | Iterable<ElementsInput<NodeData, EdgeData>>

an async iterable (or iterable) of chunks, each a definition, columnar or wire payload

options: LoadOptions?

{ fit, padding }: fit once to the first chunk (default: on for an initial load), and that fit's padding

Fields of options
NameDescription
fit: boolean?

Fit the viewport once, to the first chunk, and then hold it — a load never re-fits per chunk, so the screen does not jump as the graph fills in. Default: true for an initial load (one that starts on an instance holding no elements), false for a load into a populated graph.

padding: number?

the rendered-space padding of that fit, in px (default 0, as cy.fit())

Returns LoadRun

the load's completion: a promise of the final { chunks, nodes, edges }, with cancel()

Example

await cy.load([[{ data: { id: 'd' } }]]);
console.log(cy.hasElementWithId('d')); // true

Example graph and handle setup

Throws

synchronously, when source is not an (async) iterable of chunks (a single payload is refused — pass [ payload ]), on an unknown option, while another load is running on this instance, or on a destroyed instance

#Batching and compaction

Core › Graph manipulation › Batching and compaction

Defer style application across related writes; understand stale reads and undo costs.

Use cy.batch(fn) when multiple writes should defer style application to one outermost flush. Batches nest; the close happens even if the callback throws. Inside a batch, the model writes have landed but style-derived reads such as width() and label() can be stale until endBatch(). This is different from deferred graph writes. Sheet parsing and validation still occur at the cy.style(sheet) call site, while the style application waits for the batch flush.

cy.batch(() => {
cy.getElementById('a').data('score', 0.9);
cy.getElementById('b').position({ x: 120, y: 80 });
cy.add({ data: { id: 'a-to-b', source: 'a', target: 'b' } });
});

A cy.load() is not a transaction: it spans macrotasks and has its own lifecycle. Layouts, animations and gestures write outside any batch unless the app wraps them. cy.style(sheet) in a batch applies at the flush, but the wire format carries no style, so an app undoing sheet changes keeps its own sheet history.

To build undo, listen for batchstart and batchend around application changes. Save element payloads with serialize() and reconcile them with patch() when appropriate. Keep stylesheet, viewport and selection history separately if your undo operation must restore them: an element patch does not restore those parts of the session.

#cy.compact()
// Reclaim unused storage after removing many elements
cy.compact(): this

Reclaim unused storage after removing many elements. Existing element handles, listeners and drawing order are preserved.

Compaction normally happens automatically. Call this method to choose when its work occurs, for example after a bulk removal. It throws during a batch and defers with a warning while a GPU force layout is running.

Returns this

Example

cy.remove(cy.getElementById('c'));
cy.compact();
console.log(cy.nodes().map(node => node.id())); // ['a', 'b']

Example graph and handle setup

Also spelled cy.gc.

#cy.startBatch()
// Open a batch: defer style application until the matching endBatch()
cy.startBatch(): this

Open a batch: defer style application until the matching endBatch(). Pairs nest — only the outermost endBatch() flushes. Prefer batch( fn), which cannot leak a depth on an exception.

The outermost open is a transaction and fires batchstart on the core — before any of the batch's mutations, with batching() already true, so a listener sees the state the transaction starts from (the place to take an undo snapshot) and anything it mutates belongs to the transaction. A nested open fires nothing.

Returns this

this core, for chaining

Example

cy.startBatch();
try { cy.getElementById('a').data('score', 5); }
finally { cy.endBatch(); }
console.log(cy.getElementById('a').data('score')); // 5

Example graph and handle setup

#cy.endBatch()
// Close a batch
cy.endBatch(): this

Close a batch. Only the outermost close applies deferred styles and fires a batchend event. After that event, style reads reflect the completed batch. Nested closes and calls without an open batch do nothing.

batchend follows all element events and any patch summary produced by the batch. It carries no diff: listen to the events between batchstart and batchend to collect the changes.

Returns this

this core, for chaining

Example

cy.startBatch();
cy.getElementById('a').data('score', 5);
cy.endBatch();
console.log(cy.getElementById('a').data('score')); // 5

Example graph and handle setup

#cy.batch(fn)
// Run fn inside a startBatch()/endBatch() pair
cy.batch(fn: () => void): this

Run fn inside a startBatch()/endBatch() pair. The batch closes even if fn throws, so this is the form to prefer. As the outermost pair it is one transaction, batchstart … batchend; there is no rollback, so a throwing fn still ends in batchend, with the mutations that landed before the throw.

Parameters
NameDescription
fn: () => void

the mutations to batch; its return value is discarded

Returns this

this core, for chaining

Example

cy.batch(() => { cy.nodes().unselect(); cy.getElementById('a').select(); });
console.log(cy.getElementById('a').selected()); // true

Example graph and handle setup

#Accessing elements

Core › Accessing elements

Look up elements by identity, region, query object or predicate.

#cy.collection()

// Create an empty collection bound to this core
cy.collection(): Collection<NodeData, EdgeData>

Create an empty collection bound to this core. Use it as an accumulator, for example cy.collection().union(cy.nodes({ selected: true })).

This method takes no arguments. Query with cy.elements(query) or build a collection with union() to include existing elements.

Returns Collection<NodeData, EdgeData>

a collection of zero elements

Example

console.log(cy.collection().map(ele => ele.id())); // []

Example graph and handle setup

Throws

if called with any argument — use cy.add() to insert definitions or set operations to build collections

#cy.getElementById(id)

// Look up one element by id through the O(1) id index
cy.getElementById(id: string): Collection<NodeData, EdgeData>

Look up one element by id through the O(1) id index.

Parameters
NameDescription
id: string

the element id

Returns Collection<NodeData, EdgeData>

a collection of one element, or an empty collection when no element has that id

Example

console.log(cy.getElementById('a').id()); // 'a'

Example graph and handle setup

Also spelled cy.$id, cy.byId.

#cy.elements(query?)

// Get all nodes and edges, or only those matching a query
cy.elements(query?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>

Get all nodes and edges, or only those matching a query. Nodes appear first, in insertion order, followed by edges.

Pass a query object such as { selected: true, data: { score: { gt: 2 } } } or a predicate such as ele => ele.data('score') > 2. Unknown query keys and selector strings throw.

Collections preserve their membership while reading current element values. Query again to include newly matching elements. Calls without a query return the same collection object until an element is added or removed.

Parameters
NameDescription
query: FilterLike<NodeData, EdgeData>?

a query object or an ( ele) => boolean predicate; omit for everything

Fields of query
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData>

the matching elements

Example

console.log(cy.elements().map(ele => ele.id())); // ["a","b","c","ab","bc"]

Example graph and handle setup

#cy.nodes(query?)

// The graph's nodes, optionally filtered
cy.nodes(query?: FilterLike<NodeData, EdgeData, NodeData>): Collection<NodeData, EdgeData, NodeData>

The graph's nodes, optionally filtered. Same query forms as elements(), restricted to the node group — and, with no query, the same cached collection behaviour.

Parameters
NameDescription
query: FilterLike<NodeData, EdgeData, NodeData>?

a query object or an ( ele) => boolean predicate

Fields of query
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the matching nodes

Example

console.log(cy.nodes().map(ele => ele.id())); // ["a","b","c"]

Example graph and handle setup

#cy.edges(query?)

// The graph's edges, optionally filtered
cy.edges(query?: FilterLike<NodeData, EdgeData, EdgeData>): Collection<NodeData, EdgeData, EdgeData>

The graph's edges, optionally filtered. Same query forms as elements(), restricted to the edge group — and, with no query, the same cached collection behaviour.

Parameters
NameDescription
query: FilterLike<NodeData, EdgeData, EdgeData>?

a query object or an ( ele) => boolean predicate

Fields of query
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, EdgeData>

the matching edges

Example

console.log(cy.edges().map(ele => ele.id())); // ["ab","bc"]

Example graph and handle setup

#cy.filter(query)

// Filter the whole graph
cy.filter(query: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>

Filter the whole graph. Identical to elements( query), kept for symmetry with eles.filter().

Parameters
NameDescription
query: FilterLike<NodeData, EdgeData>

a query object or an ( ele) => boolean predicate

Fields of query
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData>

the matching elements

Example

console.log(cy.filter(ele => ele.isNode()).length); // 3

Example graph and handle setup

Also spelled cy.$.

#cy.elementsInBox(x1, y1, x2, y2)

// Live, visible elements contained in the model-coordinate box (corners in any order): the box-selection query, answered by one columnar scan
cy.elementsInBox(x1: number, y1: number, x2: number, y2: number): Collection<NodeData, EdgeData>

Live, visible elements contained in the model-coordinate box (corners in any order): the box-selection query, answered by one columnar scan. Nodes count when their bounding box lies fully inside; edges when both endpoint node centers do (straight-edge endpoints are taken at the node centers).

boxSelectionMode does not reach here: this stays the pure geometric containment query whatever the gesture is set to. For the overlap question, boxSelectionMode( 'overlap') and drag a box, or test intersection yourself against eles.boundingBox(). (boxSelectionIncludesLabels is the one interaction setting that does reach here: with it on, a node's label box must be contained too.)

Parameters
NameDescription
x1: number

one corner's model x

y1: number

that corner's model y

x2: number

the opposite corner's model x

y2: number

that corner's model y

Returns Collection<NodeData, EdgeData>

the contained elements

Example

console.log(cy.elementsInBox(-50, -50, 50, 50).length); // 2

Example graph and handle setup

#Data and scratch

Core › Data and scratch

Keep serializable graph data separate from transient application scratch.

#Core data, viewport and events

cy.data() holds graph-level application data; cy.scratch() is transient application metadata. Graph data can be serialized, while scratch is not.

#cy.data()

// Get all data
cy.data(): Record<string, unknown>

Read all graph-level data. Graph data is separate from element data. Binary serialization includes it; constructor loading restores it, while cy.add(buffer) leaves the destination graph's data unchanged.

Returns Record<string, unknown>

the graph's data object

Example

cy.data('title', 'Example graph');
console.log(cy.data().title); // 'Example graph'

Example graph and handle setup

#cy.data(key)

// Get data by key
cy.data(key: string): unknown

Read one graph-level data value.

Parameters
NameDescription
key: string

the application field to read or write

Returns unknown

the value, or undefined when the key is unset

Example

cy.data('title', 'Example graph');
console.log(cy.data('title')); // 'Example graph'

Example graph and handle setup

#cy.data(key, value)

// Set data by key
cy.data(key: string, value: unknown): this

Write one graph-level data value. Writes emit a data event.

Parameters
NameDescription
key: string

the application field to read or write

value: unknown

the value to store

Returns this

this core, for chaining

Example

const result = cy.data('title', 'Example graph');
console.log(result === cy); // true

Example graph and handle setup

#cy.data(patch)

// Set several data fields
cy.data(patch: Record<string, unknown>): this

Merge several graph-level data fields. Writes emit a data event.

Parameters
NameDescription
patch: Record<string, unknown>

the fields to merge; other fields stay unchanged

Returns this

this core, for chaining

Example

cy.data({ title: 'Example graph' });
console.log(cy.data('title')); // 'Example graph'

Example graph and handle setup

Also spelled cy.attr.

#cy.removeData()

// Remove all keys
cy.removeData(): this

Delete graph-level data keys. Emits a data event when anything was removed.

Returns this

this core, for chaining

Example

cy.data('temporary', 1);
cy.removeData();
console.log(cy.data('temporary')); // undefined

Example graph and handle setup

#cy.removeData(names)

// Remove the specified keys
cy.removeData(names: string): this

Delete graph-level data keys. Emits a data event when anything was removed.

Parameters
NameDescription
names: string

space-separated key names; omit to clear everything

Returns this

this core, for chaining

Example

cy.data('temporary', 1);
cy.removeData('temporary');
console.log(cy.data('temporary')); // undefined

Example graph and handle setup

Also spelled cy.removeAttr.

#cy.scratch()

// Get all scratch data
cy.scratch(): Record<string, unknown>

Read all graph-level scratch data. Namespace extension keys, for example '_myExtension'. Scratch is transient, never exported, and emits no events.

Returns Record<string, unknown>

the graph's scratch data object

Example

cy.scratch('title', 'Example graph');
console.log(cy.scratch().title); // 'Example graph'

Example graph and handle setup

#cy.scratch(key)

// Get scratch data by key
cy.scratch(key: string): unknown

Read one graph-level scratch data value.

Parameters
NameDescription
key: string

the application field to read or write

Returns unknown

the value, or undefined when the key is unset

Example

cy.scratch('title', 'Example graph');
console.log(cy.scratch('title')); // 'Example graph'

Example graph and handle setup

#cy.scratch(key, value)

// Set scratch data by key
cy.scratch(key: string, value: unknown): this

Write one graph-level scratch data value. Scratch writes do not emit events and are never exported.

Parameters
NameDescription
key: string

the application field to read or write

value: unknown

the value to store

Returns this

this core, for chaining

Example

const result = cy.scratch('title', 'Example graph');
console.log(result === cy); // true

Example graph and handle setup

#cy.scratch(patch)

// Set several scratch data fields
cy.scratch(patch: Record<string, unknown>): this

Merge several graph-level scratch data fields. Scratch writes do not emit events and are never exported.

Parameters
NameDescription
patch: Record<string, unknown>

the fields to merge; other fields stay unchanged

Returns this

this core, for chaining

Example

cy.scratch({ title: 'Example graph' });
console.log(cy.scratch('title')); // 'Example graph'

Example graph and handle setup

#cy.removeScratch()

// Remove all keys
cy.removeScratch(): this

Delete graph-level scratch keys.

Returns this

this core, for chaining

Example

cy.scratch('temporary', 1);
cy.removeScratch();
console.log(cy.scratch('temporary')); // undefined

Example graph and handle setup

#cy.removeScratch(names)

// Remove the specified keys
cy.removeScratch(names: string): this

Delete graph-level scratch keys.

Parameters
NameDescription
names: string

space-separated key names; omit to clear everything

Returns this

this core, for chaining

Example

cy.scratch('temporary', 1);
cy.removeScratch('temporary');
console.log(cy.scratch('temporary')); // undefined

Example graph and handle setup

#Metadata and environment

Core › Metadata and environment

Inspect core configuration, environment and graph metadata.

#cy.headless()

// Whether this instance has no container and therefore no GPU — the Node-testable mode, in which every model API works and the render, pick and image-export paths are no-ops or reject
cy.headless(): boolean

Whether this instance has no container and therefore no GPU — the Node-testable mode, in which every model API works and the render, pick and image-export paths are no-ops or reject.

Returns boolean

true when running headless

Example

console.log(cy.headless()); // true

Example graph and handle setup

#cy.styleEnabled()

// Check whether style is enabled
cy.styleEnabled(): boolean

Always true: there is no style-disabled mode, since the columnar model derives geometry from stored style channels rather than treating style as an optional layer. Use this to inspect the instance's style capability.

Returns boolean

true

Example

console.log(cy.styleEnabled()); // true

Example graph and handle setup

#cy.hasCompoundNodes()

// Whether any node currently has a parent
cy.hasCompoundNodes(): boolean

Whether any node currently has a parent. Worth checking because the compound tier changes paint evaluation and draw order; the renderer pays nothing for compounds while this is false.

Returns boolean

true when the graph has at least one parent/child relation

Example

console.log(cy.hasCompoundNodes()); // false

Example graph and handle setup

#cy.hasElementWithId(id)

// Whether an element with this id exists, via the O(1) id index — cheaper than getElementById( id).nonempty() because no handle is materialized
cy.hasElementWithId(id: string): boolean

Whether an element with this id exists, via the O(1) id index — cheaper than getElementById( id).nonempty() because no handle is materialized.

Parameters
NameDescription
id: string

the element id

Returns boolean

true when the graph holds that element

Example

console.log(cy.hasElementWithId('a')); // true

Example graph and handle setup

#cy.window()

// The window this instance renders into, or null when there is no DOM (Node)
cy.window(): (Window & typeof globalThis) | null

The window this instance renders into, or null when there is no DOM (Node). Useful for extensions that need the hosting realm.

Returns (Window & typeof globalThis) | null

the global window, or null outside a browser

Example

console.log(cy.window()); // null

Example graph and handle setup

#cy.options()

// The options the instance was constructed with
cy.options(): CytoscapeOptions<NodeData, EdgeData>

The options the instance was constructed with.

Returns CytoscapeOptions<NodeData, EdgeData>

the caller's own options object, held by reference — not a copy and not a defaults-resolved view, so an option the caller omitted reads back absent rather than as the default in force

Example

console.log(cy.options().headless); // true

Example graph and handle setup

#Events

Core › Events

Bind core listeners or delegate to elements using predicates.

#Core event methods

The core can listen, delegate by an element predicate, emit custom events and remove listeners. removeAllListeners() on the core also removes element-bound and delegated listeners. The event vocabulary and bubbling rules are described in events. Layout lifecycle events are raised on the core. Async algorithm runs and progressive loads also report their own events and can be cancelled through their returned handles.

#cy.on(events, callback)

// Bind a direct listener
cy.on(events: string, callback: EventHandler<NodeData, EdgeData>): this

Listen for core and bubbled element events: cy.on('tap', handler). For delegation, use cy.on('tap', ele => ele.isNode(), handler). Event names match literally; 'tap.ns' is different from 'tap'. Custom names are allowed and fire when your application emits them.

Parameters
NameDescription
events: string

one or more space-separated event names

callback: EventHandler<NodeData, EdgeData>

the event handler

Returns this

this core, for chaining

Example

const seen = [];
const handler = event => seen.push(event.type);
cy.on('example', handler);
cy.emit('example');
cy.off('example', handler);
console.log(seen); // ['example']

Example graph and handle setup

#cy.on(events, predicate, callback)

// Bind a delegated listener
cy.on(events: string, predicate: ElePredicate<NodeData, EdgeData>, callback: EventHandler<NodeData, EdgeData>): this

Listen for events on the core. Use cy.on('tap', handler) for core and bubbled element events. To delegate, use cy.on('tap', ele => ele.isNode(), handler).

Custom event names are accepted; a name the library never emits fires only when your application emits it. Event names match literally: 'tap.ns' is different from 'tap'. See the event reference for emitted names.

To remove a delegated listener, pass the same predicate and handler objects to off().

Parameters
NameDescription
events: string

one or more space-separated event names

predicate: ElePredicate<NodeData, EdgeData>

( ele) => boolean over the event target; only runs for element targets

callback: EventHandler<NodeData, EdgeData>

the handler

Returns this

this core, for chaining

Example

const seen = [];
const handler = event => seen.push(event.target.id());
cy.on('example', node => node.isNode(), handler);
cy.getElementById('a').emit('example');
console.log(seen); // ['a']

Example graph and handle setup

Also spelled cy.addListener.

See

Core#off — remove listeners using the same function objects

#cy.one(events, callback)

// Bind a direct listener
cy.one(events: string, callback: EventHandler<NodeData, EdgeData>): this

Like on(), but the handler runs at most once and then removes itself.

Parameters
NameDescription
events: string

one or more space-separated event names

callback: EventHandler<NodeData, EdgeData>

the handler, when delegating

Returns this

this core, for chaining

Example

let count = 0;
cy.one('example', () => count++);
cy.emit('example');
cy.emit('example');
console.log(count); // 1

Example graph and handle setup

#cy.one(events, predicate, callback)

// Bind a delegated listener
cy.one(events: string, predicate: ElePredicate<NodeData, EdgeData>, callback: EventHandler<NodeData, EdgeData>): this

Like on() with delegation, but the handler runs at most once.

Parameters
NameDescription
events: string

one or more space-separated event names

predicate: ElePredicate<NodeData, EdgeData>

( ele) => boolean over the event target

callback: EventHandler<NodeData, EdgeData>

the handler

Returns this

this core, for chaining

Example

const seen = [];
const handler = event => seen.push(event.target.id());
cy.one('example', node => node.isNode(), handler);
cy.getElementById('a').emit('example');
console.log(seen); // ['a']

Example graph and handle setup

Also spelled cy.once.

#cy.off(events, callback?)

// Remove a direct listener
cy.off(events: string, callback?: EventHandler<NodeData, EdgeData>): this

Stop listening. Removing a delegated handler takes the same ( events, predicate, handler) triple it was added with — predicates compare by function identity, so the predicate must be the same function object, not an equivalent one.

Parameters
NameDescription
events: string

one or more space-separated event names

callback: EventHandler<NodeData, EdgeData>?

the handler, when delegating

Returns this

this core, for chaining

Example

let count = 0;
const handler = () => count++;
cy.on('example', handler);
cy.off('example', handler);
cy.emit('example');
console.log(count); // 0

Example graph and handle setup

#cy.off(events, predicate, callback)

// Remove a delegated listener
cy.off(events: string, predicate: ElePredicate<NodeData, EdgeData>, callback: EventHandler<NodeData, EdgeData>): this

Remove a delegated handler. The predicate must be the same function object it was registered with — predicates compare by identity, not by structure.

Parameters
NameDescription
events: string

one or more space-separated event names

predicate: ElePredicate<NodeData, EdgeData>

the predicate the handler was added with

callback: EventHandler<NodeData, EdgeData>

the handler to remove

Returns this

this core, for chaining

Example

const seen = [];
const handler = event => seen.push(event.target.id());
cy.on('example', node => node.isNode(), handler);
const predicate = node => node.isNode();
cy.on('removed', predicate, handler);
cy.off('removed', predicate, handler);
cy.getElementById('a').emit('removed');
console.log(seen); // []

Example graph and handle setup

Also spelled cy.removeListener.

#cy.removeAllListeners()

// Remove all listeners
cy.removeAllListeners(): this

Remove every listener on the core, including element-bound and delegated ones.

Returns this

this core, for chaining

Example

let calls = 0;
cy.on('example', () => calls++);
cy.removeAllListeners();
cy.emit('example');
console.log(calls); // 0

Example graph and handle setup

#cy.emit(events, extraParams?)

// Emit an event on the core
cy.emit(events: string | EventProps, extraParams?: unknown[]): this

Emit an event on the core.

Custom event names are supported API, which is why on() validates none: cy.emit( 'myevent') runs handlers registered for 'myevent', and the same holds on elements. Names the library itself never emits are therefore legal to register and simply never fire — see on() for which those are.

Parameters
NameDescription
events: string | EventProps

one or more space-separated event names, or an event props object

extraParams: unknown[]?

extra arguments passed to each handler after the event object

Fields of events
NameDescription
type: string?
target: EventTarget?
cy: Core?
position: Position?

model-space position, for pointer-derived events

renderedPosition: Position?

rendered-space position; derived from position when omitted

originalEvent: NativeEvent?

the DOM event behind a gesture

layout: unknown?

the layout instance, on layoutstart/layoutready/layoutstop

cancelled: boolean?

on layoutstop: true when the run was abandoned by layout.cancel() or cy.destroy() rather than finished or stopped; on loadstop, when the load was cancelled

diff: PatchDiff?

on patch: what the patch added, removed and updated

progress: LoadProgress?

on loadstart/loadchunk/loadready/loadstop: how far the load has got

timeStamp: number?
Returns this

this core, for chaining

Example

let observed;
cy.one('example', event => { observed = event.type; });
cy.emit('example');
console.log(observed); // 'example'

Example graph and handle setup

Also spelled cy.trigger.

#cy.promiseOn(events, predicate?)

// Resolve once the next matching event fires — the promise form of one()
cy.promiseOn(events: string, predicate?: ElePredicate<NodeData, EdgeData>): Promise<Event<NodeData, EdgeData>>

Resolve once the next matching event fires — the promise form of one().

Parameters
NameDescription
events: string

one or more space-separated event names

predicate: ElePredicate<NodeData, EdgeData>?

an optional delegation predicate over the target

Returns Promise<Event<NodeData, EdgeData>>

a promise for the event object

Example

const next = cy.promiseOn('example');
cy.emit('example');
console.log((await next).type); // 'example'

Example graph and handle setup

Also spelled cy.pon.

#Viewport manipulation

Core › Viewport manipulation

Read and change the view without changing model positions.

#Pan, zoom, fit and bounds

Core › Viewport manipulation › Pan, zoom, fit and bounds

Move the viewport and read its model and rendered bounds.

The viewport is a zoom factor and pan offset. Programmatic pan()/zoom() respect the corresponding enabled flags, and user-gesture gates are separate controls. fit(), center(), and the extent readers use the renderer/model bounds contract rather than changing element positions.

#cy.zoom()
// Get the zoom level
cy.zoom(): number

Read the current zoom level.

Returns number

the current zoom level as a number

Example

cy.zoom(1);
console.log(cy.zoom()); // 1

Example graph and handle setup

#cy.zoom(level)
// Set the zoom level
cy.zoom(level: number): this

Set the zoom level, clamped to zoomRange(). Does nothing when zoomingEnabled() is false. A changed viewport emits a zoom event and a viewport event.

Parameters
NameDescription
level: number

the new zoom level

Returns this

this core, for chaining

Example

const result = cy.zoom(2);
console.log(result === cy); // true

Example graph and handle setup

#cy.zoom(options)
// Zoom about a position
cy.zoom(options: ZoomOptions): this

Zoom about a fixed model or rendered position. Does nothing when zoomingEnabled() is false. A changed viewport emits a zoom event and a viewport event.

Parameters
NameDescription
options: ZoomOptions

the level and the position to keep fixed

Fields of options
NameDescription
level: number

New zoom level, clamped to the graph's zoomRange().

position: Position?

model point to keep fixed while zooming

renderedPosition: Position?

rendered (on-screen) point to keep fixed while zooming

Returns this

this core, for chaining

Example

cy.zoom({ level: 2, renderedPosition: { x: 0, y: 0 } });
console.log(cy.zoom()); // 2

Example graph and handle setup

#cy.pan()
// Get the pan position
cy.pan(): Position

Read the current pan offset in rendered CSS pixels.

Returns Position

the rendered-space offset

Example

cy.pan({ x: 40, y: 20 });
console.log(cy.pan()); // { x: 40, y: 20 }

Example graph and handle setup

#cy.pan(pan)
// Set the pan position
cy.pan(pan: Position): this

// Set the pan position
cy.pan(pan: Position | undefined): Position | this

Set the pan offset. A no-op while panningEnabled() is false.

Parameters
NameDescription
pan: Position

the new rendered-space offset

Fields of pan
NameDescription
x: number
y: number
Returns this

this core, for chaining

Example

const result = cy.pan({ x: 40, y: 20 });
console.log(result === cy); // true

Example graph and handle setup

Get the pan offset, or set it. Setting is a no-op while panningEnabled() is false.

Parameters
NameDescription
pan: Position | undefined

the new rendered-space offset; omit to read

Fields of pan
NameDescription
x: number
y: number
Returns Position | this

the current pan when reading, this core when setting

Example

cy.pan({ x: 40, y: 20 });
console.log(cy.pan()); // { x: 40, y: 20 }

Example graph and handle setup

#cy.panBy(delta)
// Shift the pan by a delta
cy.panBy(delta: Position): this

Shift the pan by a delta. A no-op while panningEnabled() is false.

Parameters
NameDescription
delta: Position

the rendered-space offset to add

Fields of delta
NameDescription
x: number
y: number
Returns this

this core, for chaining

Example

cy.pan({ x: 0, y: 0 });
cy.panBy({ x: 10, y: 5 });
console.log(cy.pan()); // { x: 10, y: 5 }

Example graph and handle setup

#cy.fit(eles?, padding?)
// Pan and zoom so the given elements fill the viewport
cy.fit(eles?: Collection, padding?: number): this

Pan and zoom so the given elements fill the viewport.

Bounds include labels by default, so a fit never clips the text it was asked to show; edge-label terms are conservative, so a fit may slightly over-fit but never under-fits.

Parameters
NameDescription
eles: Collection?

the elements to fit; omit for the whole graph

padding: number?Default: 0

rendered-space padding around the box

Returns this

this core, for chaining

Example

cy.fit(cy.nodes(), 20);
console.log(cy.zoom() > 0); // true

Example graph and handle setup

#cy.center(eles?)
// Pan so the given elements are centred, leaving the zoom alone
cy.center(eles?: Collection): this

Pan so the given elements are centred, leaving the zoom alone. Bounds include labels, as in fit().

Parameters
NameDescription
eles: Collection?

the elements to centre on; omit for the whole graph

Returns this

this core, for chaining

Example

cy.center(cy.nodes());
console.log(Number.isFinite(cy.pan().x)); // true

Example graph and handle setup

Also spelled cy.centre.

#cy.extent()
// The model-space rectangle currently visible, as { x1, y1, x2, y2, w, h } — the inverse of the pan/zoom transform applied to the viewport box
cy.extent(): Extent

The model-space rectangle currently visible, as { x1, y1, x2, y2, w, h } — the inverse of the pan/zoom transform applied to the viewport box.

Returns Extent

the visible extent in model coordinates

Example

cy.zoom(1); cy.pan({ x: 0, y: 0 });
console.log(cy.extent().w); // 800

Example graph and handle setup

#cy.renderedExtent()
// The rendered (on-screen) viewport rectangle
cy.renderedExtent(): Extent

The rendered (on-screen) viewport rectangle.

Returns Extent

the container's box in rendered px, anchored at the origin — the rendered-space counterpart of extent(), which is the same box projected into model coordinates

Example

console.log(cy.renderedExtent().w); // 800

Example graph and handle setup

See

Core#extent for the model-coordinate form

#cy.size()
// Rendered dimensions as { width, height }
cy.size(): { width: number; height: number }

Rendered dimensions as { width, height }.

Returns { width: number; height: number }

Example

console.log(cy.size()); // { width: 800, height: 600 }

Example graph and handle setup

#cy.minZoom()
// Get the minimum zoom, or set it
cy.minZoom(): number

Get the minimum zoom, or set it. Setting re-clamps the current zoom.

Returns number

the current minZoom value

Example

console.log(cy.minZoom()); // 1e-50

Example graph and handle setup

#cy.minZoom(zoom)
// Get the minimum zoom, or set it
cy.minZoom(zoom: number): this

Get the minimum zoom, or set it. Setting re-clamps the current zoom.

Parameters
NameDescription
zoom: number

the new minimum

Returns this

this core, for chaining

Example

const result = cy.minZoom(1e-50);
console.log(result === cy); // true

Example graph and handle setup

#cy.maxZoom()
// Get the maximum zoom, or set it
cy.maxZoom(): number

Get the maximum zoom, or set it. Setting re-clamps the current zoom.

Returns number

the current maxZoom value

Example

console.log(cy.maxZoom()); // 1e+50

Example graph and handle setup

#cy.maxZoom(zoom)
// Get the maximum zoom, or set it
cy.maxZoom(zoom: number): this

Get the maximum zoom, or set it. Setting re-clamps the current zoom.

Parameters
NameDescription
zoom: number

the new maximum

Returns this

this core, for chaining

Example

const result = cy.maxZoom(1e+50);
console.log(result === cy); // true

Example graph and handle setup

#cy.zoomRange(min, max?)
// Set both zoom bounds; accepts (min, max) or { min, max }
cy.zoomRange(min: number | { min?: number; max?: number }, max?: number): this

Set both zoom bounds; accepts (min, max) or { min, max }.

Parameters
NameDescription
min: number | { min?: number; max?: number }

the minimum zoom, or an object carrying both bounds

max: number?

the maximum zoom, when min is a number

Fields of min
NameDescription
min: number?
max: number?
Returns this

this core, for chaining

Example

cy.zoomRange(0.5, 4);
console.log([cy.minZoom(), cy.maxZoom()]); // [0.5, 4]

Example graph and handle setup

#cy.viewport(opts)
// Set zoom and/or pan together, emitting once
cy.viewport(opts: { zoom?: number; pan?: Position }): this

Set zoom and/or pan together, emitting once.

Parameters
NameDescription
opts: { zoom?: number; pan?: Position }

the zoom and/or pan to apply; omitted keys are left as they are

Fields of opts
NameDescription
zoom: number?
pan: Position?
Returns this

this core, for chaining

Example

cy.viewport({ zoom: 2, pan: { x: 40, y: 20 } });
console.log(cy.zoom()); // 2

Example graph and handle setup

#cy.reset()
// Reset the viewport to zoom 1, pan (0, 0)
cy.reset(): this

Reset the viewport to zoom 1, pan (0, 0).

Returns this

Example

cy.pan({ x: 40, y: 20 });
cy.zoom(2);
cy.reset();
cy.zoom(1);
console.log(cy.zoom()); // 1

Example graph and handle setup

#cy.resize()
// Re-measure the container, redraw and emit 'resize' (the redraw is a no-op when headless; the event still fires)
cy.resize(): this

Re-measure the container, redraw and emit a resize event (the redraw is a no-op when headless; the event still fires).

Rarely needed: a ResizeObserver on the container re-measures on every size change and emits a resize event itself — once per change, and not again for a change this call already applied — so container size changes are handled automatically. Call it where no observer exists or none can see the change.

Returns this

this core

Example

// After the graph container changes size, refresh viewport dimensions.
cy.resize();
console.log(cy.width() > 0); // true

Example graph and handle setup

Also spelled cy.invalidateSize.

#cy.width()
// The rendered width in CSS px
cy.width(): number

The rendered width in CSS px. Headless instances report the configured headlessWidth (default 800), so viewport maths works without a DOM.

Returns number

the viewport width in CSS px

Example

console.log(cy.width()); // 800

Example graph and handle setup

#cy.height()
// The rendered height in CSS px
cy.height(): number

The rendered height in CSS px. Headless instances report the configured headlessHeight (default 600).

Returns number

the viewport height in CSS px

Example

console.log(cy.height()); // 600

Example graph and handle setup

#Picking and visible counts

Core › Viewport manipulation › Picking and visible counts

Query exact geometry and the visible graph.

#cy.pick(x, y)
// Async GPU pick at a rendered (CSS px) position; resolves with the element under the point or null (always null when headless — the sync, node-only cy.nodeAt() computes headless)
cy.pick(x: number, y: number): Promise<Collection<NodeData, EdgeData> | null>

Async GPU pick at a rendered (CSS px) position; resolves with the element under the point or null (always null when headless — the sync, node-only cy.nodeAt() computes headless).

Exact: a hit is a point on the drawn element. The pointer gestures additionally apply hit halos (8 rendered px around edges for a mouse, 24 for touch; 2/8 around nodes), so a press can land where this method answers null; the halo belongs to the gesture, not the API.

What wins when elements overlap, as contract: a non-parent node, then an edge, then a compound parent — the reverse of the drawing order in (parents, edges, leaves), so the answer is always the topmost thing drawn at that point. Nesting depth does not change it: a parent inside another parent still draws under every edge, and among parents the deepest wins. Drawing order is structural; there are no z-index or z-compound-depth properties.

Parameters
NameDescription
x: number

rendered (CSS px) x, relative to the container

y: number

rendered (CSS px) y

Returns Promise<Collection<NodeData, EdgeData> | null>

the element under the point, or null

Example

// Exact GPU picking returns null on a headless core.
console.log(await cy.pick(100, 100)); // null

Example graph and handle setup

#cy.nodeAt(x, y)
// Find the topmost node at a rendered position, measured in CSS pixels from the container's top-left corner
cy.nodeAt(x: number, y: number): Collection<NodeData, EdgeData, NodeData> | null

Find the topmost node at a rendered position, measured in CSS pixels from the container's top-left corner. Returns null when no node is hit. Use pick() to test both nodes and edges asynchronously.

Node visibility and level of detail affect the result. In a headless core, the calculation uses the viewport and default rendering thresholds at a device-pixel ratio of 1.

Parameters
NameDescription
x: number

rendered (CSS px) x, relative to the container

y: number

rendered (CSS px) y

Returns Collection<NodeData, EdgeData, NodeData> | null

the node under the point, or null (background, an edge only, or a destroyed instance)

Example

cy.zoom(1); cy.pan({ x: 0, y: 0 });
console.log(cy.nodeAt(0, 0)?.id()); // 'a'

Example graph and handle setup

Also spelled cy.pickNode.

See

Core#pick for edges and the full draw-order answer

#cy.viewportCounts()
// Count visible nodes and edges at each level of detail in the current viewport
cy.viewportCounts(): Promise<ViewportCounts | null>

Count visible nodes and edges at each level of detail in the current viewport. Resolves after the renderer computes the counts for a frame. Resolves null when headless, destroyed, or when the device is lost before that frame completes.

For synchronous geometric containment, use elementsInBox() with the bounds returned by extent(). That query includes elements regardless of whether they are large enough to draw.

Returns Promise<ViewportCounts | null>

{ nodes, edges } for the next frame drawn, or null

Example

// A headless core has no rendered frame to count.
console.log(await cy.viewportCounts()); // null

Example graph and handle setup

#Interaction controls

Core › Interaction controls

Control programmatic operations, user gestures and interaction defaults.

#cy.autolock()

// Read whether every node is locked (immovable) regardless of its own locked flag — the graph-wide override
cy.autolock(): boolean

Read whether every node is locked (immovable) regardless of its own locked flag — the graph-wide override. Turned on mid-tween, every running position tween holds where it got to, as a node locked mid-tween does.

Returns boolean

the current autolock value

Example

console.log(cy.autolock()); // false

Example graph and handle setup

#cy.autolock(bool)

// Set whether every node is locked (immovable) regardless of its own locked flag — the graph-wide override
cy.autolock(bool: boolean): this

Set whether every node is locked (immovable) regardless of its own locked flag — the graph-wide override. Turned on mid-tween, every running position tween holds where it got to, as a node locked mid-tween does.

Parameters
NameDescription
bool: boolean

the new setting

Returns this

this core, for chaining

Example

const result = cy.autolock(false);
console.log(result === cy); // true

Example graph and handle setup

Also spelled cy.autolockNodes.

#cy.autoungrabify()

// Read whether every node is ungrabbable regardless of its own grabbable flag
cy.autoungrabify(): boolean

Read whether every node is ungrabbable regardless of its own grabbable flag. Unlike autolock(), this blocks only user dragging; programmatic position writes still apply.

Returns boolean

the current autoungrabify value

Example

console.log(cy.autoungrabify()); // false

Example graph and handle setup

#cy.autoungrabify(bool)

// Set whether every node is ungrabbable regardless of its own grabbable flag
cy.autoungrabify(bool: boolean): this

Set whether every node is ungrabbable regardless of its own grabbable flag. Unlike autolock(), this blocks only user dragging; programmatic position writes still apply.

Parameters
NameDescription
bool: boolean

the new setting

Returns this

this core, for chaining

Example

const result = cy.autoungrabify(false);
console.log(result === cy); // true

Example graph and handle setup

Also spelled cy.autoungrabifyNodes.

#cy.autounselectify()

// Read whether every element is unselectable regardless of its own selectable flag
cy.autounselectify(): boolean

Read whether every element is unselectable regardless of its own selectable flag. Programmatic select() still applies.

Returns boolean

the current autounselectify value

Example

console.log(cy.autounselectify()); // false

Example graph and handle setup

#cy.autounselectify(bool)

// Set whether every element is unselectable regardless of its own selectable flag
cy.autounselectify(bool: boolean): this

Set whether every element is unselectable regardless of its own selectable flag. Programmatic select() still applies.

Parameters
NameDescription
bool: boolean

the new setting

Returns this

this core, for chaining

Example

const result = cy.autounselectify(false);
console.log(result === cy); // true

Example graph and handle setup

#cy.panningEnabled()

// Check whether panning is enabled
cy.panningEnabled(): boolean

Read whether panning is allowed at all — programmatic pan() included. Use userPanningEnabled() to block only the gesture.

Returns boolean

the current panningEnabled value

Example

console.log(cy.panningEnabled()); // true

Example graph and handle setup

#cy.panningEnabled(bool)

// Enable or disable panning
cy.panningEnabled(bool: boolean): this

Set whether panning is allowed at all — programmatic pan() included. Use userPanningEnabled() to block only the gesture.

Parameters
NameDescription
bool: boolean

the new setting

Returns this

this core, for chaining

Example

const result = cy.panningEnabled(true);
console.log(result === cy); // true

Example graph and handle setup

#cy.userPanningEnabled()

// Check whether user panning is enabled
cy.userPanningEnabled(): boolean

Read whether the user may pan by dragging. Programmatic pan() is unaffected.

Returns boolean

the current userPanningEnabled value

Example

console.log(cy.userPanningEnabled()); // true

Example graph and handle setup

#cy.userPanningEnabled(bool)

// Enable or disable user panning
cy.userPanningEnabled(bool: boolean): this

Set whether the user may pan by dragging. Programmatic pan() is unaffected.

Parameters
NameDescription
bool: boolean

the new setting

Returns this

this core, for chaining

Example

const result = cy.userPanningEnabled(true);
console.log(result === cy); // true

Example graph and handle setup

#cy.zoomingEnabled()

// Check whether zooming is enabled
cy.zoomingEnabled(): boolean

Read whether zooming is allowed at all — programmatic zoom() included. Use userZoomingEnabled() to block only the gesture.

Returns boolean

the current zoomingEnabled value

Example

console.log(cy.zoomingEnabled()); // true

Example graph and handle setup

#cy.zoomingEnabled(bool)

// Enable or disable zooming
cy.zoomingEnabled(bool: boolean): this

Set whether zooming is allowed at all — programmatic zoom() included. Use userZoomingEnabled() to block only the gesture.

Parameters
NameDescription
bool: boolean

the new setting

Returns this

this core, for chaining

Example

const result = cy.zoomingEnabled(true);
console.log(result === cy); // true

Example graph and handle setup

#cy.userZoomingEnabled()

// Check whether user zooming is enabled
cy.userZoomingEnabled(): boolean

Read whether the user may zoom by wheel or pinch. Programmatic zoom() is unaffected.

Returns boolean

the current userZoomingEnabled value

Example

console.log(cy.userZoomingEnabled()); // true

Example graph and handle setup

#cy.userZoomingEnabled(bool)

// Enable or disable user zooming
cy.userZoomingEnabled(bool: boolean): this

Set whether the user may zoom by wheel or pinch. Programmatic zoom() is unaffected.

Parameters
NameDescription
bool: boolean

the new setting

Returns this

this core, for chaining

Example

const result = cy.userZoomingEnabled(true);
console.log(result === cy); // true

Example graph and handle setup

#cy.boxSelectionIncludesLabels()

// Check whether box selection includes labels
cy.boxSelectionIncludesLabels(): boolean

Whether box selection considers label boxes as well as node bodies (default off). Its sense follows boxSelectionMode: under 'contain' the label box must also be inside the band, under 'overlap' a label that merely crosses the band is enough.

Returns boolean

the current boxSelectionIncludesLabels value

Example

console.log(cy.boxSelectionIncludesLabels()); // false

Example graph and handle setup

#cy.boxSelectionIncludesLabels(bool)

// Include or exclude labels in box selection
cy.boxSelectionIncludesLabels(bool: boolean): this

Whether box selection considers label boxes as well as node bodies (default off). Its sense follows boxSelectionMode: under 'contain' the label box must also be inside the band, under 'overlap' a label that merely crosses the band is enough.

Parameters
NameDescription
bool: boolean

the setting to apply

Returns this

this core, for chaining

Example

const result = cy.boxSelectionIncludesLabels(false);
console.log(result === cy); // true

Example graph and handle setup

#cy.boxSelectionMode()

// What the box-selection gesture counts as caught: 'contain' (default) selects only elements wholly inside the band; 'overlap' selects anything the band touches — a node whose box intersects it, an edge any part of whose drawn path crosses it.
cy.boxSelectionMode(): BoxSelectionMode

What the box-selection gesture counts as caught: 'contain' (default) selects only elements wholly inside the band; 'overlap' selects anything the band touches — a node whose box intersects it, an edge any part of whose drawn path crosses it..

Two notes on the boundary. This setting is read by the gesture only: cy.elementsInBox() stays the pure geometric containment query it has always been, so a programmatic caller's results do not change under this setting. And boxSelectionIncludesLabels reverses sense with the mode, because it can only mean one thing in each: under 'contain' the label box must also be inside, under 'overlap' a label that crosses the band is enough.

Returns BoxSelectionMode

the current boxSelectionMode value

Example

console.log(cy.boxSelectionMode()); // "contain"

Example graph and handle setup

#cy.boxSelectionMode(mode)

// What the box-selection gesture counts as caught: 'contain' (default) selects only elements wholly inside the band; 'overlap' selects anything the band touches — a node whose box intersects it, an edge any part of whose drawn path crosses it.
cy.boxSelectionMode(mode: BoxSelectionMode): this

What the box-selection gesture counts as caught: 'contain' (default) selects only elements wholly inside the band; 'overlap' selects anything the band touches — a node whose box intersects it, an edge any part of whose drawn path crosses it..

Two notes on the boundary. This setting is read by the gesture only: cy.elementsInBox() stays the pure geometric containment query it has always been, so a programmatic caller's results do not change under this setting. And boxSelectionIncludesLabels reverses sense with the mode, because it can only mean one thing in each: under 'contain' the label box must also be inside, under 'overlap' a label that crosses the band is enough.

Parameters
NameDescription
mode: BoxSelectionMode

the new mode

Returns this

this core, for chaining

Example

const result = cy.boxSelectionMode("contain");
console.log(result === cy); // true

Example graph and handle setup

Throws

if mode is neither 'contain' nor 'overlap'

#cy.boxSelectionEnabled()

// Check whether box selection is enabled
cy.boxSelectionEnabled(): boolean

Read whether the box-selection gesture is available.

Returns boolean

the current boxSelectionEnabled value

Example

console.log(cy.boxSelectionEnabled()); // true

Example graph and handle setup

#cy.boxSelectionEnabled(bool)

// Enable or disable box selection
cy.boxSelectionEnabled(bool: boolean): this

Set whether the box-selection gesture is available.

Parameters
NameDescription
bool: boolean

the new setting

Returns this

this core, for chaining

Example

const result = cy.boxSelectionEnabled(true);
console.log(result === cy); // true

Example graph and handle setup

#cy.pointerCursors()

// Get cursor settings
cy.pointerCursors(): boolean | Partial<CursorMap>

Read the pointer cursor settings.

Returns boolean | Partial<CursorMap>

true or false for built-in cursors, or the custom cursor configuration

Example

console.log(cy.pointerCursors()); // true

Example graph and handle setup

#cy.pointerCursors(cursors)

// Set cursor settings
cy.pointerCursors(cursors: boolean | Partial<CursorMap>): this

Set the pointer cursors used by gestures.

Parameters
NameDescription
cursors: boolean | Partial<CursorMap>

true for built-in cursors, false to disable, or custom cursors

Returns this

this core, for chaining

Example

const result = cy.pointerCursors(false);
console.log(result === cy); // true

Example graph and handle setup

#cy.selectionType()

// How user selection composes: 'single' (a tap or box replaces the selection) or 'additive' (taps toggle and boxes add, as if a multiple-select key were always held)
cy.selectionType(): 'single' | 'additive'

How user selection composes: 'single' (a tap or box replaces the selection) or 'additive' (taps toggle and boxes add, as if a multiple-select key were always held).

Returns 'single' | 'additive'

the current selectionType value

Example

console.log(cy.selectionType()); // "single"

Example graph and handle setup

Throws

if type is neither 'single' nor 'additive'

#cy.selectionType(type)

// How user selection composes: 'single' (a tap or box replaces the selection) or 'additive' (taps toggle and boxes add, as if a multiple-select key were always held)
cy.selectionType(type: 'single' | 'additive'): this

How user selection composes: 'single' (a tap or box replaces the selection) or 'additive' (taps toggle and boxes add, as if a multiple-select key were always held).

Parameters
NameDescription
type: 'single' | 'additive'

the new mode

Returns this

this core, for chaining

Example

const result = cy.selectionType("single");
console.log(result === cy); // true

Example graph and handle setup

Throws

if type is neither 'single' nor 'additive'

#cy.multiClickDebounceTime()

// The dbltap/onetap debounce window in ms (default 250)
cy.multiClickDebounceTime(): number

The dbltap/onetap debounce window in ms (default 250).

Returns number

the current multiClickDebounceTime value

Example

console.log(cy.multiClickDebounceTime()); // 250

Example graph and handle setup

#cy.multiClickDebounceTime(ms)

// The dbltap/onetap debounce window in ms (default 250)
cy.multiClickDebounceTime(ms: number): this

The dbltap/onetap debounce window in ms (default 250).

Parameters
NameDescription
ms: number

the window to set

Returns this

this core, for chaining

Example

const result = cy.multiClickDebounceTime(250);
console.log(result === cy); // true

Example graph and handle setup

Throws

if ms is not a finite non-negative number

#cy.wheelSensitivity()

// Wheel-zoom sensitivity: a multiplier on the zoom-per-wheel-tick exponent (default 1)
cy.wheelSensitivity(): number

Wheel-zoom sensitivity: a multiplier on the zoom-per-wheel-tick exponent (default 1). Non-default values warn once per instance — a custom sensitivity tuned on one mouse/OS zooms unnaturally on others.

Returns number

the current wheelSensitivity value

Example

console.log(cy.wheelSensitivity()); // 1

Example graph and handle setup

#cy.wheelSensitivity(mult)

// Wheel-zoom sensitivity: a multiplier on the zoom-per-wheel-tick exponent (default 1)
cy.wheelSensitivity(mult: number): this

Wheel-zoom sensitivity: a multiplier on the zoom-per-wheel-tick exponent (default 1). Non-default values warn once per instance — a custom sensitivity tuned on one mouse/OS zooms unnaturally on others.

Parameters
NameDescription
mult: number

the multiplier to set

Returns this

this core, for chaining

Example

const result = cy.wheelSensitivity(1);
console.log(result === cy); // true

Example graph and handle setup

Throws

if mult is not a finite positive number (0 would freeze the zoom, so the bound is strict where the threshold setters allow 0)

#cy.wheelBehavior()

// What a wheel over the canvas does: 'zoom' (the default) zooms about the cursor; 'pan' pans by the wheel's delta and emits scrollpan, while a ctrl- or meta-wheel — the encoding a trackpad pinch arrives in — still zooms; 'modifier-zoom' leaves the plain wheel to the page (it scrolls past the graph) and zooms only on a ctrl- or meta-wheel
cy.wheelBehavior(): WheelBehavior

What a wheel over the canvas does: 'zoom' (the default) zooms about the cursor; 'pan' pans by the wheel's delta and emits a scrollpan event, while a ctrl- or meta-wheel — the encoding a trackpad pinch arrives in — still zooms; 'modifier-zoom' leaves the plain wheel to the page (it scrolls past the graph) and zooms only on a ctrl- or meta-wheel. Every mode honours the toggles (userZoomingEnabled gates a zoom, userPanningEnabled a pan), and a wheel the settings leave inert is not preventDefault()ed, so the page scrolls in every mode.

Returns WheelBehavior

the current wheelBehavior value

Example

console.log(cy.wheelBehavior()); // "zoom"

Example graph and handle setup

Throws

if mode is not 'zoom', 'pan' or 'modifier-zoom'

#cy.wheelBehavior(mode)

// What a wheel over the canvas does: 'zoom' (the default) zooms about the cursor; 'pan' pans by the wheel's delta and emits scrollpan, while a ctrl- or meta-wheel — the encoding a trackpad pinch arrives in — still zooms; 'modifier-zoom' leaves the plain wheel to the page (it scrolls past the graph) and zooms only on a ctrl- or meta-wheel
cy.wheelBehavior(mode: WheelBehavior): this

What a wheel over the canvas does: 'zoom' (the default) zooms about the cursor; 'pan' pans by the wheel's delta and emits a scrollpan event, while a ctrl- or meta-wheel — the encoding a trackpad pinch arrives in — still zooms; 'modifier-zoom' leaves the plain wheel to the page (it scrolls past the graph) and zooms only on a ctrl- or meta-wheel. Every mode honours the toggles (userZoomingEnabled gates a zoom, userPanningEnabled a pan), and a wheel the settings leave inert is not preventDefault()ed, so the page scrolls in every mode.

Parameters
NameDescription
mode: WheelBehavior

the behaviour to set

Returns this

this core, for chaining

Example

const result = cy.wheelBehavior("zoom");
console.log(result === cy); // true

Example graph and handle setup

Throws

if mode is not 'zoom', 'pan' or 'modifier-zoom'

#cy.desktopTapThreshold()

// Css px a mouse/pen press may move and still count as a tap (default 4)
cy.desktopTapThreshold(): number

Css px a mouse/pen press may move and still count as a tap (default 4).

Returns number

the current desktopTapThreshold value

Example

console.log(cy.desktopTapThreshold()); // 4

Example graph and handle setup

#cy.desktopTapThreshold(px)

// Css px a mouse/pen press may move and still count as a tap (default 4)
cy.desktopTapThreshold(px: number): this

Css px a mouse/pen press may move and still count as a tap (default 4).

Parameters
NameDescription
px: number

the new threshold

Returns this

this core, for chaining

Example

const result = cy.desktopTapThreshold(4);
console.log(result === cy); // true

Example graph and handle setup

Throws

if px is not a finite non-negative number

#cy.touchTapThreshold()

// Css px a touch press may move and still count as a tap (default 8)
cy.touchTapThreshold(): number

Css px a touch press may move and still count as a tap (default 8).

Returns number

the current touchTapThreshold value

Example

console.log(cy.touchTapThreshold()); // 8

Example graph and handle setup

#cy.touchTapThreshold(px)

// Css px a touch press may move and still count as a tap (default 8)
cy.touchTapThreshold(px: number): this

Css px a touch press may move and still count as a tap (default 8).

Parameters
NameDescription
px: number

the new threshold

Returns this

this core, for chaining

Example

const result = cy.touchTapThreshold(8);
console.log(result === cy); // true

Example graph and handle setup

Throws

if px is not a finite non-negative number

#cy.tapholdDuration()

// Unmoved-press duration before 'taphold' fires, ms (default 500)
cy.tapholdDuration(): number

Unmoved-press duration before 'taphold' fires, ms (default 500).

Returns number

the current tapholdDuration value

Example

console.log(cy.tapholdDuration()); // 500

Example graph and handle setup

#cy.tapholdDuration(ms)

// Unmoved-press duration before 'taphold' fires, ms (default 500)
cy.tapholdDuration(ms: number): this

Unmoved-press duration before 'taphold' fires, ms (default 500).

Parameters
NameDescription
ms: number

the new duration

Returns this

this core, for chaining

Example

const result = cy.tapholdDuration(500);
console.log(result === cy); // true

Example graph and handle setup

Throws

if ms is not a finite non-negative number

#Emphasis

Core › Emphasis

Emphasize a neighbourhood through core-owned view state.

#cy.emphasize(eles)

// Emphasize the given elements and dim the rest of the graph
cy.emphasize(eles: Collection): this

Emphasize the given elements and dim the rest of the graph. Use a node's neighbourhood to highlight a local part of the network.

Emphasized elements match { emphasized: true } in queries and style conditions. The rest are composited using the core's dim-opacity (default 0.15), while emphasized elements appear above them at full opacity. Dimming does not change individual element style values.

Parameters
NameDescription
eles: Collection

the elements to emphasize, from this instance

Returns this

this core, for chaining

Example

cy.emphasize(cy.getElementById('a').closedNeighborhood());
console.log(cy.getElementById('b').emphasized()); // true

Example graph and handle setup

Throws

when eles is not a collection, or is one from another instance

#cy.unemphasize()

// End the emphasis: clear the emphasized set and stop dimming
cy.unemphasize(): this

End the emphasis: clear the emphasized set and stop dimming. A no-op when no emphasis is set.

Returns this

this core, for chaining

Example

cy.emphasize(cy.getElementById('a'));
cy.unemphasize();
console.log(cy.getElementById('a').emphasized()); // false

Example graph and handle setup

#Animation

Core › Animation

Animate viewport channels and control running core animations.

#cy.animate(opts)

// Animate the viewport (pan/zoom) over duration ms
cy.animate(opts: AnimateOptions): this

Animate the viewport (pan/zoom) over duration ms. Element animation is on the collection (eles.animate). Tweens are CPU-canonical; a data write / manual pan mid-animation is not prevented but will be overwritten by the next tick.

Parameters
NameDescription
opts: AnimateOptions

the viewport targets (pan, panBy, zoom, fit, center) plus duration, easing and complete; fit beats center beats panBy beats pan, and panBy with pan throws

Fields of opts
NameDescription
style: Record<string, string | number>?
position: Partial<Position>?
collapsed: boolean?

Target the collapsed state of compound parents. This is an element-only animation channel and may be combined with timing options, but not with other style, position, or viewport targets.

pan: Position?

viewport targets (core.animate)

panBy: Position?

viewport target: pan by a delta rather than to an absolute position. Resolved against the pan at creation time, so a manual pan afterwards does not move the target. Throws alongside pan — the two spell the same channel. Core-only: an element animation ignores it.

zoom: number?
fit: { eles?: unknown; boundingBox?: { x1: number; y1: number; x2?: number; y2?: number; w?: number; h?: number; }; padding?: number; }?

viewport target: animate to the viewport that fits the given elements (or an explicit model-space box). Resolved to pan/zoom when the animation is created.

center: { eles?: unknown }?

viewport target: animate the pan that centers the given elements

duration: number?
easing: string?

A named easing, cubic-bezier(), linear() or spring(bounce). For a spring, duration is the perceptual duration and the animation runs on past it to settle, so its total length is longer (see durationMs).

delay: number?
complete: () => void?
Returns this

this core, for chaining

Example

cy.animate({ pan: { x: 20, y: 10 }, duration: 100 });
cy.stop(true);
console.log(cy.pan().x); // 20

Example graph and handle setup

#cy.animation(opts)

// Like animate, but returns a handle with play/stop/promise — the viewport counterpart of eles.animation
cy.animation(opts: AnimateOptions): AnimationHandle

Like animate, but returns a handle with play/stop/promise — the viewport counterpart of eles.animation.

Parameters
NameDescription
opts: AnimateOptions

as animate; the animation does not start until play()

Fields of opts
NameDescription
style: Record<string, string | number>?
position: Partial<Position>?
collapsed: boolean?

Target the collapsed state of compound parents. This is an element-only animation channel and may be combined with timing options, but not with other style, position, or viewport targets.

pan: Position?

viewport targets (core.animate)

panBy: Position?

viewport target: pan by a delta rather than to an absolute position. Resolved against the pan at creation time, so a manual pan afterwards does not move the target. Throws alongside pan — the two spell the same channel. Core-only: an element animation ignores it.

zoom: number?
fit: { eles?: unknown; boundingBox?: { x1: number; y1: number; x2?: number; y2?: number; w?: number; h?: number; }; padding?: number; }?

viewport target: animate to the viewport that fits the given elements (or an explicit model-space box). Resolved to pan/zoom when the animation is created.

center: { eles?: unknown }?

viewport target: animate the pan that centers the given elements

duration: number?
easing: string?

A named easing, cubic-bezier(), linear() or spring(bounce). For a spring, duration is the perceptual duration and the animation runs on past it to settle, so its total length is longer (see durationMs).

delay: number?
complete: () => void?
Returns AnimationHandle

the handle

Example

const handle = cy.animation({ pan: { x: 20, y: 10 }, duration: 1 });
await handle.play();
console.log(handle.progress()); // 1

Example graph and handle setup

#cy.animated()

// True while the viewport is animating
cy.animated(): boolean

True while the viewport is animating.

Returns boolean

whether a viewport animation (pan/zoom/fit/center) is running; element animations do not count here — those are eles.animated()

Example

console.log(cy.animated()); // false

Example graph and handle setup

#cy.stop(jumpToEnd?)

// Stop every running viewport animation (animations have no queue)
cy.stop(jumpToEnd?: boolean): this

Stop every running viewport animation (animations have no queue).

Parameters
NameDescription
jumpToEnd: boolean?Default: false

apply each animation's final values instead of freezing the viewport where the tween reached

Returns this

this core, for chaining

Example

cy.animate({ pan: { x: 20, y: 10 }, duration: 100 });
cy.stop(true);
console.log(cy.animated()); // false

Example graph and handle setup

#Layout

Core › Layout

Create a whole-graph layout handle; run it explicitly.

#cy.layout(options)

// Make a layout over the whole graph
cy.layout(options: LayoutOptions): Layout

Make a layout over the whole graph. The layout does not run until you call .run() on it.

Built-ins: grid, preset, circle, concentric, breadthfirst, random, radial, pack, force (the GPU-capable spring–electric layout) and flow (the layered layout) — the set schemas/layout-options.schema.json describes. An external layout is passed directly rather than registered — without a string registry — by giving impl: a class or object implementing { run( ctx), stop?() } (see layout/contract.mts for the LayoutContext it receives).

Lifecycle events (layoutstart/layoutready/layoutstop) fire on the core, once per run; layout instances are not emitters.

Parameters
NameDescription
options: LayoutOptions

{ name } for a built-in or { impl } for an extension, plus that layout's own options and the shared layoutPositions plumbing (animate, spacingFactor, transform, fit, padding, …)

Fields of options
NameDescription
name: undefined?
avoidOverlap: boolean?

separate nodes by their extents (default true) — bodies, plus labels when nodeDimensionsIncludeLabels is true (114.6); false places points, nodeSep / rankSep then centre to centre

avoidOverlapPadding: number?

extra room around each body (default 0 — nodeSep and rankSep own the spacing)

condense: boolean?

size the rings by their nodes rather than by the box (125.3, grid's spelling): every ring takes the smallest radius that clears its own nodes and the ring inside it at avoidOverlapPadding, so the gap is the option and the viewport only centres. Off (the default), the rings start at an even share of the box's shorter side (or levelSpacing) and only grow from there. Implies avoidOverlap.

rows: number?
cols: number?
position: (node: unknown) => { row?: number; col?: number } | undefined?

returns a fixed { row, col } for a node handle

sort: LayoutSortMapping | ((a: unknown, b: unknown) => number)?

the order around the circle: a { data, order? } sort mapping (canonical, serializable — 85.3) or a comparator over node handles

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

packComponents: boolean?

lay each disconnected component out on its own — one ring, one grid, one tree per component — and shelf-pack the results largest first (default false: one drawing about one centre). Locked nodes are left out and the packed field is moved off their boxes.

componentSpacing: number?

the gap between packed disconnected components (default 40)

componentGroup: ( component: LayoutComponentInfo, ) => string | number | null | undefined?

group the packed components (121.1): called once per component with its description, and the components sharing a key pack on their own, the groups standing in a row left to right by key — numbers ascending, then strings, then the unkeyed.

componentOrder: (a: LayoutComponentInfo, b: LayoutComponentInfo) => number?

the order the pack lays components out in, a comparator over two descriptions ahead of largest-first (121.1).

groupSpacing: number?

the gap between the groups' packed boxes (default three componentSpacings)

positions: | Record<string, Position> | ((node: unknown) => Position | null | undefined)?

node id → position map, or a function of a node handle; absent nodes keep their position

radius: number?

the circle's radius (computed when omitted)

startAngle: number?

where the sweep begins, in radians (default 3π/2 — up)

sweep: number?

the total angle the trees share, in radians (default 2π)

clockwise: boolean?

wedge order runs clockwise (default true)

counterclockwise: boolean?
equidistant: boolean?

whether levels are an equal radial distance apart

minNodeSpacing: number?

min spacing between node outsides (radius adjustment)

height: number?

height/width of the layout area (override the container)

width: number?
concentric: LayoutScoreMapping | ((node: unknown) => number)?

the score deciding ring membership — higher sits closer to the center (default: degree). A { data, … } score mapping (canonical, serializable — 85.3) or a function of the node handle

levelWidth: (nodes: unknown) => number?

the variation of concentric values per level (default: maxDegree / 4)

directed: boolean?

whether the tree is directed downwards (default false)

direction: 'downward' | 'upward' | 'leftward' | 'rightward'?

drawing direction of the flow (default 'downward')

circle: boolean?

put depths in concentric circles instead of rows

grid: boolean?

place the DAG on an even grid (circle: false only)

roots: unknown?

the tree roots: a collection or an array of node ids (never a selector string); omitted, a component's roots are the nodes with no incoming edge (125.3 — radial is a hierarchy's picture), or its maximum-degree nodes when it has none (a cycle) — maximum degree alone before 125.3

depthSort: LayoutSortMapping | ((a: unknown, b: unknown) => number)?

the order within a depth: a { data, order? } sort mapping (canonical, serializable — 85.3) or a comparator over node handles

maximal: boolean?

shift nodes down to their maximal depths (DAGs only)

acyclic: boolean?

the graph is known acyclic: skip cycle removal (default false)

seed: number?
levelSpacing: number?

the ring gap in model px; derived from the bounding box unset. A floor under avoidOverlap: a ring grows past it when its nodes would otherwise touch

weight: 'leaves' | 'subtree'?

what sizes a subtree's wedge: its leaf count (default) or its whole node count

edgeLength: number | LayoutScoreMapping | ((edge: unknown) => number)?

ideal edge length: a number; a { data, scale?, range?, invert?, default? } score mapping (canonical, serializable — 85.3, e.g. { data: 'score', scale: 'log', range: [40, 200], invert: true } for large scores → short edges); or a plain fn of the edge handle. Resolved once at start either way

repulsion: number?
stiffness: number?
gravity: number?
decay: number?

alpha annealing rate per iteration

iterations: number?
threshold: number?

convergence: settled when max displacement stays under this

randomize: boolean?

fresh seeded scatter (default) vs relaxing current positions

animateLive: boolean?

stream the run: positions land per frame while the sim runs (the pre-114 animate: true); takes precedence over animate

infinite: boolean?

the run has no end of its own (118.3): it streams like animateLive and then ticks only while the field is moving — at rest it costs nothing, and a drag, a position() write or an added / removed element (whole-graph scope) heats it back up; the grabbed node is pinned for the gesture and its neighbourhood reflows around it. layout.stop() ends it, landing the positions as they stand — no separation pass, no re-pack, no fit and no tween. avoidOverlap therefore means the per-tick sweep ('sim'); iterations is ignored; layout.reheat() is the handle for a change the run cannot see

stepsPerFrame: number?

iterations per animation frame (animateLive: true; default 3)

executor: 'auto' | 'cpu' | 'gpu' | 'workers'?

where the simulation runs (default 'auto'): 'auto' takes the GPU integrator where the renderer offers one, else the CPU simulation on a worker that loaded this same bundle wherever one can be constructed — headless included, so a Node process keeps its event loop free as a page keeps its UI thread (the run is then asynchronous: positions at layoutstop / promise()) — else in-thread. 'cpu' is the in-thread reference (bit-reproducible; the worker answers the same bits) and the synchronous spelling; 'workers' asks for the worker and throws at start where none can be constructed; 'gpu' throws at start where no integrator is available

init: 'spectral' | 'scatter'?

what a fresh placement is (59.4): 'spectral' (the default — landmark-MDS per component, the global untangling) or 'scatter' (the plain seeded scatter). Ignored under randomize: false.

nestingFactor: number?

ideal-length multiplier per compound boundary an edge spans (length × levels × nestingFactor; default 1.2)

gravityCompound: number?

the compound centroid pull, as a multiple of gravity (59.5; the Bilkent line's gravityCompound — default 1.5)

alignment: { horizontal?: string[][]; vertical?: string[][] }?

alignment constraints (85.2, fcose's shape): horizontal groups share a y coordinate, vertical groups an x — id arrays, serializable; groups sharing a node merge. A locked member pins its group. Constrained runs take the CPU executor.

relativePlacement: ( | { left: string; right: string; gap?: number } | { top: string; bottom: string; gap?: number } )[]?

relative-placement constraints (85.2): keep left at least gap px left of right (top/bottom likewise vertically); gap defaults to the run's mean ideal edge length.

nodeSep: number?

px gap between adjacent nodes in a rank (default 50): between their boxes' facing sides, each node's own extent on that side (125.2 — a label hung to one side of its body extends that side alone), and along the rank's axis for the direction (a rightward rank is separated by heights)

rankSep: number?

px gap between rank rows (default 60): a row reaches as far from its centre line as its nodes' extents on each side, and a taxi edge's turn lands inside this band, which the layout keeps node-free

edgeSep: number?

px per taxi track a rank gap grows to hold (default 10, round 124.5): the gap below a rank becomes max(rankSep, tracks × edgeSep + 20), where tracks is how many of that rank's fan-outs overlap on one line — the lines taxi-turn: auto draws; 0 leaves every gap at rankSep

layering: 'network-simplex' | 'longest-path' | 'auto'?

rank assignment: 'network-simplex' (GKNV — fewest long edges, default), 'longest-path' (O(V+E), the huge-graph fast path), or 'auto' (simplex up to ~50k nodes, then longest-path)

thoroughness: number?

crossing-minimization effort, 1..10 (default 7): scales the sweep and transpose budgets

minLength: number | LayoutScoreMapping | ((edge: unknown) => number)?

minimum ranks an edge must span (default 1): a number, a { data, … } score mapping (85.3), or a fn of the edge handle

edgeWeight: number | LayoutScoreMapping | ((edge: unknown) => number)?

edge straightening weight (default 1): heavier edges pull straighter through crossing minimization and coordinates — a number, a score mapping, or a fn of the edge handle

cycleRemoval: 'greedy' | 'dfs'?

which arcs flip on cycles: 'greedy' (Eades–Lin–Smyth bound, default) or 'dfs' (input order dominates)

rankConstraints: { min?: string[]; max?: string[]; same?: string[][] }?

rank constraints as id lists (never selector strings): min pins to the first rank, max to the last, each same group to one shared rank

impl: unknown
Returns Layout

the layout instance, unstarted

Example

const handle = cy.layout({ name: 'grid', fit: false });
handle.run();
console.log(cy.nodes().length); // 3

Example graph and handle setup

Throws

if neither a known name nor an impl is given

Also spelled cy.makeLayout, cy.createLayout.

See

Collection#layout to lay out a subset

#Style and legends

Core › Style and legends

Apply a declarative stylesheet and inspect its legend.

#cy.style()

// Get the style engine
cy.style(): StyleEngine

Read the style engine for this graph.

Returns StyleEngine

this graph's style engine

Example

console.log(typeof cy.style().update); // 'function'

Example graph and handle setup

#cy.style(sheet)

// Install a stylesheet
cy.style(sheet: Stylesheet<NodeData, EdgeData>): StyleEngine

Get the style engine, or set the stylesheet and return it.

The sheet is a plain { nodes, edges, parents, core } object of prop objects — there are no selector blocks and no style functions. All per-element variation is declarative: mapper objects ({ data, scale, … }) and case conditionals, which is what keeps every value analyzable, serializable and GPU-evaluable.

Inside a batch the sheet is compiled and validated immediately (so errors still throw at the call site) but applied once at the outermost endBatch().

Parameters
NameDescription
sheet: Stylesheet<NodeData, EdgeData>

the stylesheet to install

Fields of sheet
NameDescription
nodes: StyleProps<NodeData>?

node props; typed, a mapper's field is a node field

edges: StyleProps<EdgeData>?

edge props; typed, a mapper's field is an edge field

parents: StyleProps<NodeData>?

Compound-parent overlay: node props that apply to parent nodes on top of the nodes group and the parent defaults (rectangle, #eee fill, 1px #ccc border, padding 10) — constants or mappers — plus the compound props padding, padding-relative-to, min-width, min-height and compound-sizing-wrt-labels (constants only; sizing is 'exclude' by default, or 'include' to add visible direct-child label bounds in model space before padding. A parent's own label never sizes itself, and zoom LOD does not affect the geometry).

core: StyleProps?

Core (viewport-level) theming props (A2), constants only: selection-box-color/-opacity/-border-color/-border-width (the DOM selection box) and active-bg-color/-opacity/-size (the background-grab indicator circle) — plus dim-opacity (the rest of the graph while cy.emphasize() is set) and label-declutter ('none', the default, or 'cull' — hide each node label that would overlap a higher-label-priority one).

bypasses: Record<string, StyleProps>?

Per-element bypasses: id → prop → constant. A bypass beats everything — the user's group blocks and the default sheet's state conditionals included — and is an id-keyed declaration rather than element state: it survives remove/re-add of its element, may name an id that does not exist yet (inert until it does), and round-trips through cy.json(). Values are constants only — mappers belong in the group blocks — and prop keys take dash-case or camelCase like every prop surface. A full cy.style( sheet) replaces the section like any other; the ele.style( name, value) / removeStyle() methods are sugar over it.

Returns StyleEngine

the style engine (also reachable as the return value when setting, so calls chain)

Example

cy.style({ nodes: { 'background-color': '#369', width: 40 } });
console.log(cy.nodes().first().numericStyle('width')); // 40

Example graph and handle setup

Throws

if the sheet references an unknown property or an invalid value

#cy.legend()

// Read the application's shared mapping and chart metadata
cy.legend(): Legend

Read the application's shared mapping and chart metadata. The returned JSON object is detached; changing it never alters this instance. Automatic domains expose their authored auto stops in the stylesheet and their current numeric stops here. legendchange fires after a committed snapshot changes, before batchend for a batch.

Returns Legend

detached legend entries in stylesheet definition/property order

Example

console.log(cy.legend().entries.length); // 0

Example graph and handle setup

#Export and snapshots

Core › Export and snapshots

Export graph payloads or render a raster image.

#Graph data and wire format

Core › Export and snapshots › Graph data and wire format

Inspect JSON or serialize graph payloads; snapshots do not contain all session state.

#Exports and independent views

cy.json() returns a plain inspection/export object. It is export-only; cy.json(object) is not a restore form. cy.serialize() writes the compact binary wire representation.

#cytoscape.toColumnarElements(defs, options?)
// Convert element definitions to a compact columnar payload for bulk loading or binary serialization
cytoscape.toColumnarElements(defs: ElementsDefinition | ElementDefinition, options?: ToColumnarOptions): ColumnarElements

Convert element definitions to a compact columnar payload for bulk loading or binary serialization. Node fields use typed arrays, and edge endpoints refer to indices in the payload's node list.

This form does not preserve locked, grabbable or pannable overrides. Pass definitions directly to the constructor when those flags must survive. Use the refs option to include references to nodes already in the graph.

Parameters
NameDescription
defs: ElementsDefinition | ElementDefinition

one element, an array, or { nodes, edges }

options: ToColumnarOptions?Default: {}

{ refs }: carry endpoints and parents the payload does not hold as node references rather than throwing

Fields of defs
NameDescription
group: GroupName?

inferred from data.source/data.target when omitted

data: DefinitionData<Data>?
position: Position?

nodes only

collapsed: boolean?

nodes only: persisted miniature-compound state

appliedCollapseScale: number?

nodes only: current applied factor when collapsed; omitted uses the configured collapse-scale

selected: boolean?
selectable: boolean?
grabbable: boolean?
locked: boolean?
pannable: boolean?

dragging this element pans the graph instead (default: true for edges, false for nodes)

nodes: ElementDefinition<NodeData>[]?
edges: ElementDefinition<EdgeData>[]?
Fields of options
NameDescription
refs: boolean?

Carry what the payload names but does not hold as node references instead of throwing: an edge endpoint or a node parent that is not a node in the payload goes into the result's refs, indexed past its own nodes, to be resolved against the graph the payload loads into. This is how a chunk of a progressive cy.load() carries its cut edges in the columnar and wire forms. Default false: the payload must be self-contained.

Returns ColumnarElements

the equivalent columnar payload — self-contained, or with refs when that option is on and something was referenced

Example

const columns = cytoscape.toColumnarElements([{ data: { id: 'new' } }]);
console.log(cy.add(columns).length); // 1

Example graph and handle setup

Throws

if an edge lacks a source or target; without refs, also if an edge names a source or target that is not a node in the same payload — columnar payloads are self-contained unless they carry references; and on an unknown option

#cytoscape.serializeElements(elements)
// Serialize elements (definition form or columnar form) into one transferable/fetchable ArrayBuffer
cytoscape.serializeElements(elements: ElementsDefinition | ElementDefinition | ColumnarElements): ArrayBuffer

Serialize elements (definition form or columnar form) into one transferable/fetchable ArrayBuffer. deserializeElements (or passing the buffer straight to options.elements/cy.add()) reverses it.

Parameters
NameDescription
elements: ElementsDefinition | ElementDefinition | ColumnarElements

the elements to serialize, in either accepted form; a definition-form payload is converted to columnar first. A columnar payload's optional graph-level data rides along; the definition form has nowhere to put it, so it carries none. Its node references (refs) ride too — convert definitions with toColumnarElements( defs, { refs: true }) first to carry cut edges

Fields of elements
NameDescription
columnar: true

discriminant so the loader can tell the forms apart

nodes: ElementDefinition<NodeData>[]?
edges: ElementDefinition<EdgeData>[]?
refs: string[] | PackedIds?

Node references (experimental with the wire format until 4.x): the ids of nodes this payload does not carry but indexes — an edge endpoint or a node parent nodes.count + i names refs[i]. Each must name a node already in the graph when the payload loads (an earlier chunk of a cy.load(), or anything cy.add() put there); one that does not throws before anything is added. Each id resolves once however many edges index it, which is what makes a chunk's cut edges as cheap as its own. The factory's options.elements loads into an empty graph, so a payload with refs cannot load there; cy.patch() refuses one. Build it from definitions with toColumnarElements( defs, { refs: true }).

data: DefinitionData<Data>?
group: GroupName?

inferred from data.source/data.target when omitted

position: Position?

nodes only

collapsed: boolean?

nodes only: persisted miniature-compound state

appliedCollapseScale: number?

nodes only: current applied factor when collapsed; omitted uses the configured collapse-scale

selected: boolean?
selectable: boolean?
grabbable: boolean?
locked: boolean?
pannable: boolean?

dragging this element pans the graph instead (default: true for edges, false for nodes)

Returns ArrayBuffer

one little-endian ArrayBuffer holding the whole payload — fixed header, columns, and ids as a UTF-8 blob with prefix offsets. Every section starts at an offset aligned to its element width (8 for f64 columns), and that alignment is the encoder's contract: deserializeElements returns views over the buffer rather than copies because of it (census measured the decode at zero copies), so a reader may rely on it and a future encoder must keep it

Example

const buffer = cytoscape.serializeElements([{ data: { id: 'new' } }]);
console.log(cy.add(buffer).length); // 1

Example graph and handle setup

Throws

if the platform is big-endian, or if a definition-form payload names an edge endpoint that is not a node in the same payload

#cytoscape.deserializeElements(input)
// Deserialize a serializeElements buffer (or a view over one) back into the columnar elements form
cytoscape.deserializeElements(input: ArrayBuffer | ArrayBufferView): ColumnarElements

Deserialize a serializeElements buffer (or a view over one) back into the columnar elements form. Numeric columns are zero-copy views into the given buffer; a misaligned view is copied once to realign.

Parameters
NameDescription
input: ArrayBuffer | ArrayBufferView

a serializeElements buffer, or a view over one

Returns ColumnarElements

the columnar form, whose numeric columns are views into the input rather than copies — so the buffer must outlive the result, and writing into either is visible through the other. Graph-level data is the exception in two ways: it is decoded from JSON rather than viewed, and cy.add() deliberately ignores it (see ColumnarElements.data)

Example

const payload = cytoscape.deserializeElements(cy.serialize());
console.log(payload.nodes.count); // 3

Example graph and handle setup

Throws

if the platform is big-endian, or the buffer is too short, truncated or of an unsupported format version

#cy.serialize()
// Export graph elements and graph-level data as a binary buffer
cy.serialize(): ArrayBuffer

Export graph elements and graph-level data as a binary buffer. Load it into a new instance with cytoscape({ elements: buffer }), or add its elements to an existing instance with cy.add(buffer).

The buffer carries element identity, positions, topology, selection and data. It excludes stylesheet, viewport and scratch. Constructor loading applies its graph-level data; add() leaves the destination's graph data unchanged.

Returns ArrayBuffer

a fresh little-endian buffer, self-contained (every edge endpoint indexes a node in the same payload) and directly loadable — derived geometry is flushed first, so parent boxes are the current ones rather than whatever was last materialized

Example

const buffer = cy.serialize();
const restored = cytoscape({ headless: true, elements: buffer });
console.log(restored.nodes().length); // 3
restored.destroy();

Example graph and handle setup

#cy.json(flat?)
// Export a plain-object snapshot containing elements, stylesheet, viewport, interaction settings and graph-level data
cy.json(flat?: boolean): Record<string, unknown>

Export a plain-object snapshot containing elements, stylesheet, viewport, interaction settings and graph-level data.

This method is export-only: json(object) is not supported. Use patch() to reconcile incoming element data, clone() to copy a live instance, or serialize() to save a compact element payload for later loading.

Parameters
NameDescription
flat: boolean?

when true, elements export as one flat array instead of { nodes, edges }

Returns Record<string, unknown>

the exported graph

Example

console.log(cy.json().elements.nodes.length); // 3

Example graph and handle setup

Throws

if given anything but a boolean — the guard that catches an attempted json( obj) import

#Image export

Core › Export and snapshots › Image export

Export PNG or JPEG from a rendered core.

#Raster image export

Rendered png() and jpg() exports are asynchronous GPU readbacks and reject on a headless core. Image export describes output encodings, viewport versus full-graph bounds, scaling and format-specific backgrounds. SVG export is unavailable.

Rendered cores export the currently displayed graph through cy.png() or cy.jpg(). Both return promises because the renderer draws to an offscreen GPU target and reads the pixels back asynchronously. Headless cores reject: they have no renderer to export. The exporter renders at native output resolution, independent of the on-screen adaptive render scale, and evaluates label visibility at the export scale.

const blob = await cy.png({ full: true, maxWidth: 1600, output: 'blob' });
const url = URL.createObjectURL(blob);
const image = document.createElement('img');
image.src = url;
document.body.append(image);
// Revoke the URL when the application no longer needs it.

The default output is 'base64uri', a PNG data URI. output: 'base64' returns only the base64 payload; 'blob' resolves to a Blob, and 'blob-promise' is an alias for 'blob'. JPEG uses the same options with cy.jpg() (or cy.jpeg()). Its default background is white because JPEG has no alpha channel; quality is a format-specific encoder hint from 0 to 1. PNG defaults to a transparent background. Set bg to a CSS color to paint behind either format.

Viewport export is the default: it captures the current container dimensions and viewport transform. scale multiplies rendered CSS pixels, default 1. With full: true, the exporter instead uses the model-space graph bounds and scale means output pixels per model unit. maxWidth and maxHeight replace scale; if both are set, the smaller resulting scale is used so the full image fits within both dimensions. These limits are output pixels.

An empty graph cannot be exported with full: true, and a viewport export requires a nonzero container size. The background color and scale are validated. Output larger than the GPU's maximum texture size rejects with guidance to reduce scale or set a dimension cap. Browser canvas encoding can also reject if it cannot produce the requested image.

The current APIs export PNG and JPEG. SVG export and its image/font options are unavailable; see feature availability. PDF export is unavailable.

#cy.png(options?)
// Export the rendered graph as a PNG
cy.png(options?: ExportOptions): Promise<string | Blob>

Export the rendered graph as a PNG. Async — the pixels live on the GPU (offscreen render + readback); every output form resolves through the returned promise. Options: bg, full, scale or maxWidth/maxHeight, output ('base64uri' default | 'base64' | 'blob'; 'blob-promise' is an accepted alias of 'blob'). Headless instances reject — there is no renderer to export from.

Parameters
NameDescription
options: ExportOptions?Default: {}

the export options named above

Fields of options
NameDescription
output: 'base64uri' | 'base64' | 'blob' | 'blob-promise'?

result form: a data-URI string (default), the raw base64 payload, or a Blob ('blob-promise' is accepted as an alias of 'blob' — every output form resolves through the returned promise)

bg: string?

background color under the graph (any CSS color). Default: transparent for png; white for jpg (JPEG has no alpha)

full: boolean?

export the whole graph's bounds instead of the current viewport (default false)

scale: number?

output pixels per rendered CSS px (viewport export) or per model unit (full export); default 1. Ignored when maxWidth/maxHeight are given

maxWidth: number?

cap the output width in px (the scale is computed to fit; overrides scale)

maxHeight: number?

cap the output height in px (the scale is computed to fit; overrides scale)

quality: number?

jpg only: encode quality in [0, 1] (default: the browser's)

Returns Promise<string | Blob>

the encoded image in the requested output form

Example

// Use a mounted, renderer-ready core.
await cy.ready;
const image = await cy.png({ output: 'blob' });
console.log(image.type); // image/png

Example graph and handle setup

#cy.jpg(options?)
// Export as JPEG: as {@link png}, plus quality (0..1) and a white default bg (JPEG has no alpha channel)
cy.jpg(options?: ExportOptions): Promise<string | Blob>

Export as JPEG: as png, plus quality (0..1) and a white default bg (JPEG has no alpha channel).

Parameters
NameDescription
options: ExportOptions?Default: {}

as png, plus quality

Fields of options
NameDescription
output: 'base64uri' | 'base64' | 'blob' | 'blob-promise'?

result form: a data-URI string (default), the raw base64 payload, or a Blob ('blob-promise' is accepted as an alias of 'blob' — every output form resolves through the returned promise)

bg: string?

background color under the graph (any CSS color). Default: transparent for png; white for jpg (JPEG has no alpha)

full: boolean?

export the whole graph's bounds instead of the current viewport (default false)

scale: number?

output pixels per rendered CSS px (viewport export) or per model unit (full export); default 1. Ignored when maxWidth/maxHeight are given

maxWidth: number?

cap the output width in px (the scale is computed to fit; overrides scale)

maxHeight: number?

cap the output height in px (the scale is computed to fit; overrides scale)

quality: number?

jpg only: encode quality in [0, 1] (default: the browser's)

Returns Promise<string | Blob>

the encoded image in the requested output form

Example

// Use a mounted, renderer-ready core.
await cy.ready;
const image = await cy.jpg({ output: 'blob' });
console.log(image.type); // image/jpeg

Example graph and handle setup

Also spelled cy.jpeg.

#Independent views

Core › Independent views

Clone into an independent core with its own renderer and interaction state.

cy.clone(options) builds another independent instance. It can override its container, stylesheet, zoom, pan or layout; optional follow mode syncs element payload changes by serialize-and-patch. The follower owns its own view and interaction state. Selection and hover do not become linked automatically; an application that needs linked brushing should connect the two cores' events. Scratch and active animations/layouts are not copied.

See the API reference for parameters, return values and errors. The notation page distinguishes JSON, columnar and wire forms; the getting-started page distinguishes rendered and headless entries.

#cy.clone(options?)

// Make an independent instance holding a copy of this graph — the way to show one graph in two places, e.g
cy.clone(options?: CloneOptions<NodeData, EdgeData>): Core<NodeData, EdgeData>

Make an independent instance holding a copy of this graph — the way to show one graph in two places, e.g. a minimap beside the main view. A second view is a second instance, never a second renderer over one model: each clone has its own sheet, viewport, selection, hover, listeners and png().

What is carried: every element through the wire format — ids, data, positions, parents, endpoints, selected/selectable — plus each element's locked/grabbable/pannable flags, graph-level data(), the stylesheet with its bypasses, the viewport (zoom, pan, limits), the gating flags and interaction settings, and the options this instance was built with. options overrides any of it: a container for the clone (never carried; one container, one renderer), a style (the minimap's simplified sheet — which replaces the bypasses too), a zoom or pan, a layout to run on the copy. What is not carried, by design: scratch, running animations and layouts, listeners, and the transient hover/active/grabbed state.

follow keeps the clone current: each sync is clone.patch( this.serialize()), driven by a dirty-stream consumer on this instance and throttled ({ throttle } ms, default 50, and never more often than the last sync took). A sync runs only after a change the payload carries — an add, remove, move, data write or reparent; a restyle, hover or selection here costs the clone nothing. The clone owns its state: patch never reads selection or flags for a surviving element, so selecting in one view does not select in the other (linked brushing is app wiring over the two instances' events). Positions are this instance's to set: a sync moves a clone's node even where the clone locks it (autolock, a locked node). Its own edits to elements are reconciled away at the next sync; its sheet, viewport, bypasses and graph data are never touched. Following stops when either instance is destroyed.

Parameters
NameDescription
options: CloneOptions<NodeData, EdgeData>?

construction options over the carried ones, plus follow (true or { throttle })

Fields of options
NameDescription
follow: boolean | FollowOptions?

Keep the clone current: true, or { throttle }. Each sync is clone.patch( source.serialize() ) — the source's elements, data, positions and hierarchy; never its sheet, viewport, selection or graph-level data. Stops when either instance is destroyed.

zoom: number?
pan: Position?
container: HTMLElement | null?

Where to render. When given, WebGPU is required: the factory throws synchronously if navigator.gpu is missing. When omitted, the instance is headless (works in Node, never throws for missing GPU).

renderer: RendererOptions?
pixelRatio: number | 'auto'?

device pixel ratio override; defaults to the window's

pointerCursors: boolean | Partial<CursorMap>?

whether the canvas writes CSS cursors for the gesture affordances — grab/grabbing around dragging, pointer over an element, crosshair while boxing (default true).

false means the interaction layer never touches style.cursor, for an app that sets its own; an object overrides individual entries ({ pan: 'move' }), where '' means inherit.

wheelSensitivity: number?

wheel-zoom rate multiplier (default 1; custom values warn once — a sensitivity tuned to one mouse/OS zooms unnaturally on others).

wheelBehavior: WheelBehavior?

what a wheel does: 'zoom' (default), 'pan' (ctrl/meta — the pinch — still zooms) or 'modifier-zoom' (only a ctrl/meta wheel zooms; a plain wheel scrolls the page).

desktopTapThreshold: number?

css px a mouse/pen press may move and still count as a tap (default 4).

touchTapThreshold: number?

css px a touch press may move and still count as a tap (default 8).

tapholdDuration: number?

unmoved-press duration before 'taphold' fires, in ms (default 500).

multiClickDebounceTime: number?

the dbltap/onetap debounce window in ms (default 250)

boxSelectionEnabled: boolean?

allow box selection (default true)

boxSelectionIncludesLabels: boolean?

box selection considers label boxes too (default false). Its sense follows boxSelectionMode: it narrows a 'contain' selection and widens an 'overlap' one.

boxSelectionMode: BoxSelectionMode?

what the box-selection gesture counts as selected: 'contain' (default) takes only elements wholly inside the band; 'overlap' takes anything the band touches.

userPanningEnabled: boolean?

allow user (pointer) panning (default true)

userZoomingEnabled: boolean?

allow user (wheel/pinch) zooming (default true)

style: Stylesheet<NodeData, EdgeData>?

the stylesheet — its field references typed likewise

layout: LayoutOptions?
minZoom: number?
maxZoom: number?
autolock: boolean?

disable node dragging globally (default false)

autoungrabify: boolean?

make all nodes ungrabbable globally (default false)

autounselectify: boolean?

disable selection globally (default false)

panningEnabled: boolean?

allow panning at all — programmatic and user (default true)

zoomingEnabled: boolean?

allow zooming at all — programmatic and user (default true)

selectionType: 'single' | 'additive'?

'single' (tap/box replaces the selection) or 'additive' (taps toggle, boxes add); default 'single'

headlessWidth: number?

rendered dimensions used when headless

headlessHeight: number?
Returns Core<NodeData, EdgeData>

the new instance, built by the same entry as this one

Example

const copy = cy.clone();
copy.getElementById('a').data('score', 99);
console.log(cy.getElementById('a').data('score')); // 1
copy.destroy();

Example graph and handle setup

Throws

if options carries elements (a clone's elements are this instance's), on a malformed follow, and wherever construction throws — a container in a build with no renderer, or without WebGPU

#Collection

Collections are ordered sets of handles tied to one core; scalar reads and bulk writes have distinct contracts.

The public collection abstraction represents an ordered set of handles tied to one core. cy.elements() returns all live elements with nodes first and edges second; cy.nodes() and cy.edges() narrow the result. An element lookup returns a collection of length zero or one, so the same methods work for a missing id, one element or a larger traversal result. Empty collections are valid values.

Collection APIs make the unit of work explicit. Methods such as forEach() visit length-one element collections. map() returns a plain array in collection order. first(), last() and eq(i) return collections, not unwrapped element objects. Scalar queries such as id(), position() and data() read from the first element; they answer undefined when there is no first element. Bulk mutators apply to every element and typically return the same collection for chaining.

const a = cy.getElementById('a');
const adjacentNodes = a.neighborhood().nodes();
const ids = adjacentNodes.map(node => node.id());
const totalWeight = cy.edges().reduce(
(sum, edge) => sum + edge.data('weight'),
0,
);

#Metadata and identity

Collection › Metadata and identity

Inspect identity and collection membership.

#eles.length

// How many elements this collection holds
eles.length: number

How many elements this collection holds.

Returns number

Example

console.log(eles.length); // 5

Example graph and handle setup

#eles.cy()

// The core this collection belongs to
eles.cy(): Core<NodeData, EdgeData>

The core this collection belongs to.

Returns Core<NodeData, EdgeData>

the instance that owns these elements — a collection cannot span two cores, so this is also the identity a set operation against a foreign collection would violate

Example

console.log(eles.cy() === cy); // true

Example graph and handle setup

#eles.collection()

// Create an empty collection bound to the same core
eles.collection(): Collection<NodeData, EdgeData, Data>

Create an empty collection bound to the same core. Takes no arguments. Use union() to build a set from existing elements, or filter() to select members of this collection.

Returns Collection<NodeData, EdgeData, Data>

a fresh empty collection bound to this core — the seed for building a set up by union

Example

console.log(eles.collection().map(ele => ele.id())); // []

Example graph and handle setup

Throws

if called with any argument — use cy.add() to insert definitions or set operations to build collections

#eles.hasElementWithId(id)

// Whether this collection contains an element with the given id
eles.hasElementWithId(id: string): boolean

Whether this collection contains an element with the given id.

Parameters
NameDescription
id: string

the element id

Returns boolean

true when a member has that id

Example

console.log(eles.hasElementWithId('a')); // true

Example graph and handle setup

#eles.indexOf(ele)

// Index of an element within this collection
eles.indexOf(ele: Collection): number

Index of an element within this collection.

Parameters
NameDescription
ele: Collection

the element to find; only its first element is used

Returns number

the index, or -1 when it is not in this collection

Example

console.log(eles.indexOf(cy.getElementById('a'))); // 0

Example graph and handle setup

#eles.indexOfId(id)

// Position of the element with this id within the collection
eles.indexOfId(id: string): number

Position of the element with this id within the collection.

Parameters
NameDescription
id: string

the element id

Returns number

the index, or -1 when absent

Example

console.log(eles.indexOfId('a')); // 0

Example graph and handle setup

#ele.id()

// The first element's id
ele.id(): string | undefined

The first element's id. Cached on the handle, so it stays readable after the element is removed.

Returns string | undefined

the id, or undefined when the collection is empty

Example

console.log(eles.id()); // "a"

Example graph and handle setup

#ele.group()

// The first element's group
ele.group(): GroupName | undefined

The first element's group. Cached on the handle, so it stays readable after removal.

Returns GroupName | undefined

'nodes' or 'edges', or undefined when empty

Example

console.log(eles.group()); // "nodes"

Example graph and handle setup

#ele.json()

// Plain-object form of the first element (undefined when empty)
ele.json(): Record<string, unknown> | undefined

Plain-object form of the first element (undefined when empty).

Returns Record<string, unknown> | undefined

the definition-form object for the first element, or undefined when the collection is empty; it round-trips through cy.add(), which is the supported restore path because cy.json() is export-only

Example

console.log(cy.getElementById('a').json().data.id); // 'a'

Example graph and handle setup

#eles.jsons()

// Plain-object form of every element
eles.jsons(): (Record<string, unknown> | undefined)[]

Plain-object form of every element.

Returns (Record<string, unknown> | undefined)[]

one object per element, in collection order — the plural of json(), not a graph-level export

Example

console.log(eles.jsons().map(def => def.data.id)); // ['a', 'b', 'c', 'ab', 'bc']

Example graph and handle setup

#ele.isNode()

// Whether the first element is a node
ele.isNode(): boolean

Whether the first element is a node.

Returns boolean

true for a node

Example

console.log(eles.isNode()); // true

Example graph and handle setup

#ele.isEdge()

// Whether the first element is an edge
ele.isEdge(): boolean

Whether the first element is an edge.

Returns boolean

true for an edge

Example

console.log(eles.isEdge()); // false

Example graph and handle setup

#ele.isLoop()

// Whether the first element is a self-loop — an edge whose source and target are the same node
ele.isLoop(): boolean

Whether the first element is a self-loop — an edge whose source and target are the same node.

Returns boolean

true for a loop edge; false for nodes and removed elements

Example

console.log(eles.isLoop()); // false

Example graph and handle setup

#ele.isSimple()

// Whether the first element is a non-loop edge
ele.isSimple(): boolean

Whether the first element is a non-loop edge.

Returns boolean

true for an edge between two distinct nodes

Example

console.log(eles.isSimple()); // false

Example graph and handle setup

#ele.removed()

// Whether the first element has been removed from the graph
ele.removed(): boolean

Whether the first element has been removed from the graph. A removed element's handle stays usable — reads are no-ops or undefined, and the cached id()/group() remain readable.

Returns boolean

true when the element is no longer in the graph

Example

console.log(eles.removed()); // false

Example graph and handle setup

#ele.inside()

// Whether the first element is still in the graph — the complement of removed()
ele.inside(): boolean

Whether the first element is still in the graph — the complement of removed().

Returns boolean

true when the element is live

Example

console.log(eles.inside()); // true

Example graph and handle setup

#Iteration and aggregation

Collection › Iteration and aggregation

Visit, map, reduce and aggregate elements in collection order.

#eles.size()

// The number of elements — the method form of length
eles.size(): number

The number of elements — the method form of length.

Returns number

the element count

Example

console.log(eles.size()); // 5

Example graph and handle setup

#eles.empty()

// Whether the collection holds no elements
eles.empty(): boolean

Whether the collection holds no elements.

Returns boolean

true when empty

Example

console.log(eles.empty()); // false

Example graph and handle setup

#eles.nonempty()

// Whether the collection holds at least one element
eles.nonempty(): boolean

Whether the collection holds at least one element.

Returns boolean

true when non-empty

Example

console.log(eles.nonempty()); // true

Example graph and handle setup

#eles.forEach(fn, thisArg?)

// Call fn for each element
eles.forEach(fn: ( ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => void | false, thisArg?: unknown): this

Call fn for each element. Returning false from the callback stops the iteration early.

With no thisArg the callback is plain-called, so this is undefined inside it — the callback receives each element as its first argument.

Parameters
NameDescription
fn: ( ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => void | false

( ele, i, eles); return false to stop

thisArg: unknown?

optional receiver for the callback

Returns this

this collection, for chaining

Example

const ids = [];
eles.forEach(ele => ids.push(ele.id()));
console.log(ids.length); // 5

Example graph and handle setup

Also spelled eles.each.

#eles.toArray()

// The elements as a plain array of length-1 collections
eles.toArray(): Collection<NodeData, EdgeData, Data>[]

The elements as a plain array of length-1 collections.

Returns Collection<NodeData, EdgeData, Data>[]

a new array of the members

Example

console.log(eles.toArray().map(ele => ele.id())); // ['a', 'b', 'c', 'ab', 'bc']

Example graph and handle setup

#eles.slice(start?, end?)

// A sub-range of the collection, with Array#slice semantics (negative indices count from the end)
eles.slice(start?: number, end?: number): Collection<NodeData, EdgeData, Data>

A sub-range of the collection, with Array#slice semantics (negative indices count from the end).

Parameters
NameDescription
start: number?Default: 0

first index, inclusive

end: number?Default: this.length

last index, exclusive

Returns Collection<NodeData, EdgeData, Data>

the sub-range as a new collection

Example

console.log(eles.slice().map(ele => ele.id())); // ["a","b","c","ab","bc"]

Example graph and handle setup

#eles.sort(sortFn)

// A copy sorted by a comparator
eles.sort(sortFn: ( a: Collection<NodeData, EdgeData, Data>, b: Collection<NodeData, EdgeData, Data>, ) => number): Collection<NodeData, EdgeData, Data>

A copy sorted by a comparator. Note that sort order is a property of the collection, not of drawing: draw order is structural and there is no z-index.

Parameters
NameDescription
sortFn: ( a: Collection<NodeData, EdgeData, Data>, b: Collection<NodeData, EdgeData, Data>, ) => number

( a, b) comparator over length-1 collections; a non-function is ignored and returns this collection unchanged

Returns Collection<NodeData, EdgeData, Data>

a new, sorted collection

Example

const sorted = eles.sort((a, b) => a.id().localeCompare(b.id()));
console.log(sorted.first().id()); // 'a'

Example graph and handle setup

#eles.eq(i)

// The element at an index, as a length-1 collection
eles.eq(i: number): Collection<NodeData, EdgeData, Data>

The element at an index, as a length-1 collection.

Parameters
NameDescription
i: number

the index

Returns Collection<NodeData, EdgeData, Data>

that element, or an empty collection when out of range

Example

console.log(eles.eq(0).id()); // 'a'

Example graph and handle setup

#eles.first()

// The first element, as a length-1 collection
eles.first(): Collection<NodeData, EdgeData, Data>

The first element, as a length-1 collection.

Returns Collection<NodeData, EdgeData, Data>

the first element, or an empty collection

Example

console.log(eles.first().map(ele => ele.id())); // ["a"]

Example graph and handle setup

#eles.last()

// The last element, as a length-1 collection
eles.last(): Collection<NodeData, EdgeData, Data>

The last element, as a length-1 collection.

Returns Collection<NodeData, EdgeData, Data>

the last element, or an empty collection

Example

console.log(eles.last().map(ele => ele.id())); // ["bc"]

Example graph and handle setup

#eles.map(fn, thisArg?)

// Map each element through fn into a plain array
eles.map<T>(fn: ( ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => T, thisArg?: unknown): T[]

Map each element through fn into a plain array.

Parameters
NameDescription
fn: ( ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => T

( ele, i, eles)

thisArg: unknown?

optional receiver for the callback

Returns T[]

an array of the results

Example

console.log(cy.nodes().map(node => node.id())); // ['a', 'b', 'c']

Example graph and handle setup

#eles.some(fn, thisArg?)

// Whether any element satisfies the predicate
eles.some(fn: EleFilterFn<NodeData, EdgeData, Data>, thisArg?: unknown): boolean

Whether any element satisfies the predicate. Short-circuits.

Parameters
NameDescription
fn: EleFilterFn<NodeData, EdgeData, Data>

( ele, i, eles) => boolean

thisArg: unknown?

optional receiver for the callback

Returns boolean

true when at least one element matches

Example

console.log(eles.some(ele => ele.isEdge())); // true

Example graph and handle setup

#eles.every(fn, thisArg?)

// Whether every element satisfies the predicate
eles.every(fn: EleFilterFn<NodeData, EdgeData, Data>, thisArg?: unknown): boolean

Whether every element satisfies the predicate. Short-circuits, and is vacuously true for an empty collection.

Parameters
NameDescription
fn: EleFilterFn<NodeData, EdgeData, Data>

( ele, i, eles) => boolean

thisArg: unknown?

optional receiver for the callback

Returns boolean

true when all elements match

Example

console.log(cy.nodes().every(ele => ele.isNode())); // true

Example graph and handle setup

#eles.reduce(fn, initial)

// Fold the collection into a single value
eles.reduce<T>(fn: ( acc: T, ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => T, initial: T): T

Fold the collection into a single value.

Parameters
NameDescription
fn: ( acc: T, ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => T

( accumulator, ele, i, eles)

initial: T

the starting accumulator (required, unlike Array#reduce)

Returns T

the final accumulator

Example

const count = eles.reduce((sum, ele) => sum + (ele.isNode() ? 1 : 0), 0);
console.log(count); // 3

Example graph and handle setup

#eles.max(valFn, thisArg?)

// The element maximizing valFn, with its value
eles.max(valFn: ( ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => number, thisArg?: unknown): { value: number; ele: Collection<NodeData, EdgeData, Data> | undefined }

The element maximizing valFn, with its value.

Parameters
NameDescription
valFn: ( ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => number

( ele, i, eles) => number

thisArg: unknown?

optional receiver for the callback

Returns { value: number; ele: Collection<NodeData, EdgeData, Data> | undefined }

{ value, ele }, or { value: -Infinity, ele: undefined } when the collection is empty

Example

const result = cy.nodes().max(node => node.data('score'));
console.log(result.value); // 3

Example graph and handle setup

#eles.min(valFn, thisArg?)

// The element minimizing valFn, with its value
eles.min(valFn: ( ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => number, thisArg?: unknown): { value: number; ele: Collection<NodeData, EdgeData, Data> | undefined }

The element minimizing valFn, with its value.

Parameters
NameDescription
valFn: ( ele: Collection<NodeData, EdgeData, Data>, i: number, eles: Collection<NodeData, EdgeData, Data>, ) => number

( ele, i, eles) => number

thisArg: unknown?

optional receiver for the callback

Returns { value: number; ele: Collection<NodeData, EdgeData, Data> | undefined }

{ value, ele }, or { value: Infinity, ele: undefined } when the collection is empty

Example

const result = cy.nodes().min(node => node.data('score'));
console.log(result.value); // 1

Example graph and handle setup

#Comparison

Collection › Comparison

Compare collections without mutating the graph.

#eles.same(other)

// Whether both collections hold exactly the same elements, ignoring order
eles.same(other: Collection): boolean

Whether both collections hold exactly the same elements, ignoring order.

Parameters
NameDescription
other: Collection

the collection to compare against

Returns boolean

true when the element sets are equal

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').same(other)); // false

Example graph and handle setup

Also spelled eles.equal, eles.equals.

#eles.anySame(other)

// Whether the two collections share at least one element
eles.anySame(other: Collection): boolean

Whether the two collections share at least one element.

Parameters
NameDescription
other: Collection

the collection to compare against

Returns boolean

true when the sets intersect

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').anySame(other)); // false

Example graph and handle setup

#eles.contains(other)

// Whether every element of other is also in this collection
eles.contains(other: Collection): boolean

Whether every element of other is also in this collection.

Parameters
NameDescription
other: Collection

the candidate subset

Returns boolean

true when other is contained

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').contains(other)); // false

Example graph and handle setup

Also spelled eles.has.

#eles.allAreNeighbors(other)

// Whether every element of other is in this collection's neighborhood
eles.allAreNeighbors(other: Collection): boolean

Whether every element of other is in this collection's neighborhood.

Parameters
NameDescription
other: Collection

the elements to test

Returns boolean

true when all of them are neighbors

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').allAreNeighbors(other)); // true

Example graph and handle setup

Also spelled eles.allAreNeighbours.

#eles.allAre(criterion)

// Whether every element matches the criterion
eles.allAre(criterion: FilterLike<NodeData, EdgeData, Data, NodeData | EdgeData>): boolean

Whether every element matches the criterion.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, Data, NodeData | EdgeData>

a query object or an ( ele) => boolean predicate (selector strings are not accepted)

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns boolean

true when all elements match

Example

console.log(cy.nodes().allAre(ele => ele.isNode())); // true

Example graph and handle setup

#eles.is(criterion)

// Whether any element matches the criterion
eles.is(criterion: FilterLike<NodeData, EdgeData, Data, NodeData | EdgeData>): boolean

Whether any element matches the criterion.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, Data, NodeData | EdgeData>

a query object or an ( ele) => boolean predicate

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns boolean

true when at least one element matches

Example

console.log(cy.getElementById('a').is(ele => ele.id() === 'a')); // true

Example graph and handle setup

#Building and filtering

Collection › Building and filtering

Build ordered sets and filter with queries or predicates.

#Set operations and filtering

Collections can be unioned, intersected, subtracted or compared. These operations return new collections and deduplicate elements by their identity; they do not mutate the graph. filter() accepts a query object or a predicate function. Query objects operate on state and data columns; predicates run once per element and can express application logic not included in the query form. Unknown query keys throw. See selectors for the supported query vocabulary.

#eles.union(other)

// The union of the two collections, deduped
eles.union<OtherData = Data>(other: Collection<NodeData, EdgeData, OtherData>): Collection<NodeData, EdgeData, Data | OtherData>

The union of the two collections, deduped.

Parameters
NameDescription
other: Collection<NodeData, EdgeData, OtherData>

the collection to add

Returns Collection<NodeData, EdgeData, Data | OtherData>

a new collection holding both sets

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').union(other).map(ele => ele.id())); // ["a","b"]

Example graph and handle setup

Also spelled eles.u, eles.or, eles.add, eles.merge.

#eles.difference(other)

// This collection's elements that are not in other
eles.difference(other: Collection): Collection<NodeData, EdgeData, Data>

This collection's elements that are not in other.

Parameters
NameDescription
other: Collection

the collection to subtract

Returns Collection<NodeData, EdgeData, Data>

a new collection

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').difference(other).map(ele => ele.id())); // ["a"]

Example graph and handle setup

Also spelled eles.not, eles.subtract, eles.unmerge, eles.relativeComplement.

#eles.intersection(other)

// The elements present in both collections
eles.intersection(other: Collection): Collection<NodeData, EdgeData, Data>

The elements present in both collections.

Parameters
NameDescription
other: Collection

the collection to intersect with

Returns Collection<NodeData, EdgeData, Data>

a new collection

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').intersection(other).map(ele => ele.id())); // []

Example graph and handle setup

Also spelled eles.intersect, eles.and.

#eles.symmetricDifference(other)

// The elements in exactly one of the two collections
eles.symmetricDifference<OtherData = Data>(other: Collection<NodeData, EdgeData, OtherData>): Collection<NodeData, EdgeData, Data | OtherData>

The elements in exactly one of the two collections.

Parameters
NameDescription
other: Collection<NodeData, EdgeData, OtherData>

the other collection

Returns Collection<NodeData, EdgeData, Data | OtherData>

a new collection

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').symmetricDifference(other).map(ele => ele.id())); // ["a","b"]

Example graph and handle setup

Also spelled eles.symdiff, eles.xor.

#eles.filter(criterion, thisArg?)

// The subset matching the criterion
eles.filter(criterion: FilterLike<NodeData, EdgeData, Data, NodeData | EdgeData>, thisArg?: unknown): Collection<NodeData, EdgeData, Data>

The subset matching the criterion.

A structured query object is answered directly off the flags column — no per-element handles and no closures — while a predicate function is called per element. Pass either of these two forms; selector strings are not accepted.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, Data, NodeData | EdgeData>

a query object ({ selected: true }, { data: { weight: { gt: 0.5 } } }, …) or an ( ele, i, eles) => boolean predicate

thisArg: unknown?

optional receiver, for the predicate form

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, Data>

a new collection of the matching elements

Example

cy.getElementById('a').select();
console.log(cy.nodes().filter({ selected: true }).map(node => node.id())); // ['a']

Example graph and handle setup

Throws

if a query object carries an unknown key — a typo must not silently match everything

#eles.nodes(criterion?)

// The nodes in this collection, optionally filtered
eles.nodes(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

The nodes in this collection, optionally filtered.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

a query object or predicate; omit for all nodes

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

a new collection of nodes

Example

console.log(eles.nodes().map(ele => ele.id())); // ["a","b","c"]

Example graph and handle setup

#eles.edges(criterion?)

// The edges in this collection, optionally filtered
eles.edges(criterion?: FilterLike<NodeData, EdgeData, EdgeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, EdgeData>

The edges in this collection, optionally filtered.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, EdgeData, NodeData | EdgeData>?

a query object or predicate; omit for all edges

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, EdgeData>

a new collection of edges

Example

console.log(eles.edges().map(ele => ele.id())); // ["ab","bc"]

Example graph and handle setup

#eles.getElementById(id)

// Find a member by id
eles.getElementById(id: string): Collection<NodeData, EdgeData, Data>

Find a member by id. This is a linear scan of the collection; use cy.$id( id) for the O(1) whole-graph index.

Parameters
NameDescription
id: string

the element id

Returns Collection<NodeData, EdgeData, Data>

a collection of one element, or an empty collection

Example

console.log(eles.getElementById('a').id()); // 'a'

Example graph and handle setup

#eles.absoluteComplement()

// All elements of the graph not in this collection
eles.absoluteComplement(): Collection<NodeData, EdgeData>

All elements of the graph not in this collection.

Returns Collection<NodeData, EdgeData>

the complement against the whole graph, not against any enclosing collection — which is what the absolute in the name is distinguishing

Example

console.log(eles.absoluteComplement().map(ele => ele.id())); // []

Example graph and handle setup

Also spelled eles.complement, eles.abscomp.

#eles.diff(other)

// Three-way set difference against another collection
eles.diff<OtherData = Data>(other: Collection<NodeData, EdgeData, OtherData>): { left: Collection<NodeData, EdgeData, Data>; right: Collection<NodeData, EdgeData, OtherData>; both: Collection<NodeData, EdgeData, Data>; }

Three-way set difference against another collection.

Parameters
NameDescription
other: Collection<NodeData, EdgeData, OtherData>

the collection to compare with

Returns { left: Collection<NodeData, EdgeData, Data>; right: Collection<NodeData, EdgeData, OtherData>; both: Collection<NodeData, EdgeData, Data>; }

{ left: only in this, right: only in other, both: in both }

Example

const result = cy.getElementById('a').diff(cy.getElementById('b'));
console.log(result.both.length); // 0

Example graph and handle setup

#Data and scratch

Collection › Data and scratch

Read and update application data or transient scratch on elements.

#ele.data()

// Get all data
ele.data(): IfTyped<NodeData, EdgeData, Data | undefined, unknown>

Read all application data from the first element. Returns undefined for an empty collection. To read a single key, use data(key); to update elements, use data(key, value) or data(object).

The returned object is a cached snapshot. Changing it does not update the graph. Use a data setter to emit events and update data-dependent styles.

id, source, target and parent can be read through data(), but identity and topology cannot be changed with a data setter. Use move() to change an edge's endpoints or a node's parent.

Typed instances check keys and values against the data shapes supplied to cytoscape<NodeData, EdgeData>(). Narrow a mixed collection with nodes() or edges() to access fields that are specific to one group.

Returns IfTyped<NodeData, EdgeData, Data | undefined, unknown>

the first element's data — the collection's shape when typed — or undefined when the collection is empty

Example

const node = cy.getElementById('a');
node.data('score', 9);
console.log(node.data().score); // 9

Example graph and handle setup

#ele.data(key)

// Get data by key — Built-in field
ele.data(key: FirstClassKey): IfTyped<NodeData, EdgeData, string | undefined, unknown>

// Get data by key — Application field
ele.data<K extends keyof Data & string>(key: K): IfTyped<NodeData, EdgeData, Data[K] | undefined, unknown>

Read a first-class field of the first element (see the whole-object form): 'id', 'source'/'target' on an edge, 'parent' on a child node.

Parameters
NameDescription
key: FirstClassKey

the first-class field to read

Returns IfTyped<NodeData, EdgeData, string | undefined, unknown>

the id it holds, or undefined when there is none or the collection is empty

Example

console.log(cy.getElementById('a').data('id')); // 'a'

Example graph and handle setup

Read one data key of the first element (see the whole-object form).

Parameters
NameDescription
key: K

the key to read; typed, one of the collection's fields (a mixed collection's common fields — narrow it with nodes() or edges() to read the rest)

Returns IfTyped<NodeData, EdgeData, Data[K] | undefined, unknown>

the value, or undefined when the key is unset or the collection is empty

Example

console.log(cy.getElementById('a').data('score')); // 1

Example graph and handle setup

#eles.data(key, value)

// Set data by key
eles.data<K extends keyof Data & string>(key: K, value: IfTyped<NodeData, EdgeData, Data[K], unknown>): this

Write one data key on every element. Writes emit a data event and update data-dependent styles and labels.

Parameters
NameDescription
key: K

the key to write

value: IfTyped<NodeData, EdgeData, Data[K], unknown>

the value; an explicit undefined clears the key

Returns this

this collection, for chaining

Example

const result = eles.data('score', 9);
console.log(result === eles); // true

Example graph and handle setup

Throws

when key is 'id', or 'source'/'target' on an edge — first-class fields are immutable (typed, not a key it accepts)

#eles.data(patch)

// Set several data fields
eles.data(patch: IfTyped<NodeData, EdgeData, Partial<Data>, Record<string, unknown>>): this

Set several application data fields on every element in this collection. Each supplied key replaces its value; other keys are unchanged. Writes emit a data event and update data-dependent styles and labels.

Parameters
NameDescription
patch: IfTyped<NodeData, EdgeData, Partial<Data>, Record<string, unknown>>

the keys to write

Returns this

this collection, for chaining

Example

eles.data({ score: 9 });
console.log(eles.first().data('score')); // 9

Example graph and handle setup

Throws

when the patch names 'id', or 'source'/'target' on an edge — first-class fields are immutable

Also spelled eles.attr.

#eles.removeData()

// Remove all keys
eles.removeData(): this

Remove application data keys.

Returns this

this collection, for chaining

Example

eles.data('temporary', 1);
eles.removeData();
console.log(eles.first().data('temporary')); // undefined

Example graph and handle setup

#eles.removeData(names)

// Remove the specified keys
eles.removeData(names: string): this

Remove application data keys.

Parameters
NameDescription
names: string

space-separated key names; omit to clear every key

Returns this

this collection, for chaining

Example

eles.data('temporary', 1);
eles.removeData('temporary');
console.log(eles.first().data('temporary')); // undefined

Example graph and handle setup

Also spelled eles.removeAttr.

#ele.scratch()

// Get all scratch data
ele.scratch(): Record<string, unknown> | undefined

Read all scratch data from the first element. Scratch is never exported and writes emit no events.

Returns Record<string, unknown> | undefined

the scratch object or value; undefined when empty or unset

Example

eles.scratch('ui', 1);
console.log(eles.first().scratch().ui); // 1

Example graph and handle setup

#ele.scratch(key)

// Get scratch data by key
ele.scratch(key: string): unknown

Read one scratch namespace from the first element. Scratch is never exported and writes emit no events.

Parameters
NameDescription
key: string

the namespace to read or write

Returns unknown

the scratch object or value; undefined when empty or unset

Example

eles.scratch('ui', 1);
console.log(eles.first().scratch('ui')); // 1

Example graph and handle setup

#eles.scratch(key, value)

// Set scratch data by key
eles.scratch(key: string, value: unknown): this

Write one scratch namespace on every element. Scratch is never exported and writes emit no events.

Parameters
NameDescription
key: string

the namespace to read or write

value: unknown

the transient value to store

Returns this

this collection, for chaining

Example

const result = eles.scratch('ui', 1);
console.log(result === eles); // true

Example graph and handle setup

#eles.scratch(patch)

// Set several scratch data fields
eles.scratch(patch: Record<string, unknown>): this

Merge scratch namespaces on every element. Scratch is never exported and writes emit no events.

Parameters
NameDescription
patch: Record<string, unknown>

the namespaces to merge

Returns this

this collection, for chaining

Example

eles.scratch({ ui: 1 });
console.log(eles.first().scratch('ui')); // 1

Example graph and handle setup

#eles.removeScratch()

// Remove all keys
eles.removeScratch(): this

Delete scratchpad keys from every element.

Returns this

this collection, for chaining

Example

eles.scratch('temporary', 1);
eles.removeScratch();
console.log(eles.first().scratch('temporary')); // undefined

Example graph and handle setup

#eles.removeScratch(namespace)

// Remove the specified keys
eles.removeScratch(namespace: string): this

Delete scratchpad keys from every element.

Parameters
NameDescription
namespace: string

the key to remove; omit to clear each element's whole scratchpad

Returns this

this collection, for chaining

Example

eles.scratch('temporary', 1);
eles.removeScratch('temporary');
console.log(eles.first().scratch('temporary')); // undefined

Example graph and handle setup

#Graph manipulation

Collection › Graph manipulation

Remove elements or change topology while respecting terminal removed handles.

#Graph changes and lifecycle

remove() deletes the receiver, cascading from a removed node to descendant elements and incident edges. It returns the closure actually removed. Those handles are terminal references; only cached identity methods such as id() and group() remain readable. cy.add() consumes element definitions, columnar input, wire buffers or an iterable of definitions. There is no restore() method and no element-level clone operation.

move() changes topology without replacing identity: { parent } reparents nodes, while { source, target } changes edge endpoints. The modes are exclusive and parent takes precedence if both are present. data() updates application fields; id, edge endpoints and parent are first-class immutable fields. A position write is in model units. positions(fn) maps a function over nodes and writes the resulting coordinates in bulk.

#eles.remove()

// Remove these elements from the graph; incident edges of removed nodes cascade
eles.remove(): Collection<NodeData, EdgeData, Data>

Remove these elements from the graph; incident edges of removed nodes cascade. Already-removed elements are skipped (no second remove event).

Returns Collection<NodeData, EdgeData, Data>

the elements actually removed — the closure, so it can be larger than the receiver: removing a parent brings its descendants, and removing a node brings its incident edges. The returned refs are dead by construction (removals are terminal), so only their cached id()/group() still read

Example

const removed = cy.getElementById('c').remove();
console.log(removed.removed()); // true
console.log(cy.hasElementWithId('c')); // false

Example graph and handle setup

#eles.move(opts)

// Set a node's parent or an edge's endpoints without changing its id or data
eles.move(opts: { source?: string; target?: string; parent?: string | null; }): this

Set a node's parent or an edge's endpoints without changing its id or data.

Use { parent: id } to reparent nodes, or { parent: null } to make them orphans. Use { source: id, target: id } to rewire edges. If parent is present it takes precedence over endpoint keys. A changed parent emits a moveout event before the change and move afterwards.

An unknown parent is ignored. Cyclic parent assignments warn and are ignored.

Parameters
NameDescription
opts: { source?: string; target?: string; parent?: string | null; }

{ parent } to re-parent nodes (null orphans them), or { source, target } to re-point edges; parent wins if both are given

Fields of opts
NameDescription
source: string?
target: string?
parent: string | null?
Returns this

this collection, for chaining

Example

cy.getElementById('ab').move({ target: 'c' });
console.log(cy.getElementById('ab').target().id()); // 'c'

Example graph and handle setup

#Position and dimensions

Collection › Position and dimensions

Read geometry and write node positions in the documented coordinate space.

#ele.position()

// Get the position
ele.position(): Position | undefined

Read the first element's position in model coordinates.

Returns Position | undefined

the first element's position, or undefined when empty

Example

console.log(cy.getElementById('a').position()); // { x: 0, y: 0 }

Example graph and handle setup

#ele.position(dim)

// Get one coordinate
ele.position(dim: string): number | undefined

Read one coordinate of the first element.

Parameters
NameDescription
dim: string

the coordinate, 'x' or 'y'

Returns number | undefined

the first element's coordinate, or undefined when empty

Example

console.log(cy.getElementById('a').position('x')); // 0

Example graph and handle setup

#eles.position(position)

// Set the position
eles.position(position: Position): this

Set the position on every unlocked node.

Parameters
NameDescription
position: Position

the coordinates to write

Fields of position
NameDescription
x: number
y: number
Returns this

this collection, for chaining

Example

const result = eles.position({ x: 20, y: 10 });
console.log(result === eles); // true

Example graph and handle setup

#eles.position(dim, value)

// Set one coordinate
eles.position(dim: string, value: number): this

Set one coordinate on every unlocked node.

Parameters
NameDescription
dim: string

the coordinate, 'x' or 'y'

value: number

the coordinate to write

Returns this

this collection, for chaining

Example

const result = eles.position('x', 20);
console.log(result === eles); // true

Example graph and handle setup

Also spelled eles.modelPosition, eles.point.

#eles.positions(pos)

// Set every node's position, from a constant or per-element function
eles.positions(pos: Position | ElePositionFn<NodeData, EdgeData, Data>): this

Set every node's position, from a constant or per-element function.

Parameters
NameDescription
pos: Position | ElePositionFn<NodeData, EdgeData, Data>

a { x, y } for all of them, or ( ele, i) => ( { x, y })

Fields of pos
NameDescription
x: number
y: number
Returns this

this collection, for chaining

Example

cy.nodes().positions((node, i) => ({ x: i * 50, y: 0 }));
console.log(cy.getElementById('b').position('x')); // 50

Example graph and handle setup

Also spelled eles.modelPositions, eles.points.

#eles.shift(dim, value?)

// Offset positions by a vector or along one axis
eles.shift(dim: string | Position, value?: number): this

Offset positions by a vector or along one axis.

Parameters
NameDescription
dim: string | Position

a { x, y } delta, or 'x' / 'y' with value

value: number?

the offset, when dim names an axis

Fields of dim
NameDescription
x: number
y: number
Returns this

this collection, for chaining

Example

cy.nodes().shift({ x: 10, y: 0 });
console.log(cy.getElementById('a').position('x')); // 10

Example graph and handle setup

#ele.relativePosition()

// Get the position
ele.relativePosition(): Position | undefined

Read the first element's position relative to its immediate compound parent. For orphans this equals the model position.

Returns Position | undefined

the first element's position, or undefined when empty

Example

console.log(cy.getElementById('a').relativePosition()); // { x: 0, y: 0 }

Example graph and handle setup

#ele.relativePosition(dim)

// Get one coordinate
ele.relativePosition(dim: string): number | undefined

Read one coordinate of the first element.

Parameters
NameDescription
dim: string

the coordinate, 'x' or 'y'

Returns number | undefined

the first element's coordinate, or undefined when empty

Example

console.log(cy.getElementById('a').relativePosition('x')); // 0

Example graph and handle setup

#eles.relativePosition(position)

// Set the position
eles.relativePosition(position: Position): this

Set the position on every unlocked node.

Parameters
NameDescription
position: Position

the coordinates to write

Fields of position
NameDescription
x: number
y: number
Returns this

this collection, for chaining

Example

const result = eles.relativePosition({ x: 20, y: 10 });
console.log(result === eles); // true

Example graph and handle setup

#eles.relativePosition(dim, value)

// Set one coordinate
eles.relativePosition(dim: string, value: number): this

Set one coordinate on every unlocked node.

Parameters
NameDescription
dim: string

the coordinate, 'x' or 'y'

value: number

the coordinate to write

Returns this

this collection, for chaining

Example

const result = eles.relativePosition('x', 20);
console.log(result === eles); // true

Example graph and handle setup

Also spelled eles.relativePoint.

#ele.renderedPosition()

// Get the position
ele.renderedPosition(): Position | undefined

Read the first element's position in rendered CSS pixels, after applying the graph's zoom and pan.

Returns Position | undefined

the first element's position, or undefined when empty

Example

cy.zoom(1); cy.pan({ x: 0, y: 0 });
console.log(cy.getElementById('a').renderedPosition()); // { x: 0, y: 0 }

Example graph and handle setup

#ele.renderedPosition(dim)

// Get one coordinate
ele.renderedPosition(dim: string): number | undefined

Read one coordinate of the first element.

Parameters
NameDescription
dim: string

the coordinate, 'x' or 'y'

Returns number | undefined

the first element's coordinate, or undefined when empty

Example

cy.zoom(1); cy.pan({ x: 0, y: 0 });
console.log(cy.getElementById('a').renderedPosition('x')); // 0

Example graph and handle setup

#eles.renderedPosition(position)

// Set the position
eles.renderedPosition(position: Position): this

Set the position on every unlocked node.

Parameters
NameDescription
position: Position

the coordinates to write

Fields of position
NameDescription
x: number
y: number
Returns this

this collection, for chaining

Example

const result = eles.renderedPosition({ x: 20, y: 10 });
console.log(result === eles); // true

Example graph and handle setup

#eles.renderedPosition(dim, value)

// Set one coordinate
eles.renderedPosition(dim: string, value: number): this

Set one coordinate on every unlocked node.

Parameters
NameDescription
dim: string

the coordinate, 'x' or 'y'

value: number

the coordinate to write

Returns this

this collection, for chaining

Example

const result = eles.renderedPosition('x', 20);
console.log(result === eles); // true

Example graph and handle setup

Also spelled eles.renderedPoint.

#ele.width()

// Read the first element's width in model pixels: a node's content width, excluding padding and border, or an edge's stroke width
ele.width(): number | undefined

Read the first element's width in model pixels: a node's content width, excluding padding and border, or an edge's stroke width. A compound parent's width is derived from its children. The read reflects the current value during size animations.

Returns number | undefined

the width, or undefined when empty or removed

Example

console.log(eles.width()); // 30

Example graph and handle setup

See

Collection#outerWidth to include the border

#ele.height()

// Read the first element's height in model pixels: a node's content height, excluding padding and border, or an edge's stroke width
ele.height(): number | undefined

Read the first element's height in model pixels: a node's content height, excluding padding and border, or an edge's stroke width. A compound parent's height is derived from its children. The read reflects the current value during size animations.

Returns number | undefined

the height, or undefined when empty or removed

Example

console.log(eles.height()); // 30

Example graph and handle setup

#ele.padding()

// Node padding
ele.padding(): number | undefined

Node padding. Leaves have no padding (no compound-free padding prop); parents answer the resolved auto-bounds padding.

Returns number | undefined

the resolved padding in model px — 0 for leaves and for any graph with no compounds at all, the derived value for a parent; undefined when the collection is empty

Example

console.log(eles.padding()); // 0

Example graph and handle setup

#ele.paddedWidth()

// The drawn box: core dims + 2 x padding
ele.paddedWidth(): number | undefined

The drawn box: core dims + 2 x padding.

Returns number | undefined

the padded width — identical to width() for leaves, which have no padding; undefined when empty or removed

Example

console.log(eles.paddedWidth()); // 30

Example graph and handle setup

#ele.paddedHeight()

// The drawn box height: content height plus twice the padding
ele.paddedHeight(): number | undefined

The drawn box height: content height plus twice the padding. Identical to height() for leaves, which have no padding.

Returns number | undefined

the padded height, or undefined when empty or removed

Example

console.log(eles.paddedHeight()); // 30

Example graph and handle setup

#ele.outerWidth()

// The full drawn width including the border — padded width plus the border width
ele.outerWidth(): number | undefined

The full drawn width including the border — padded width plus the border width. This is the box bounds and endpoint clipping use.

Returns number | undefined

the outer width, or undefined when empty or removed

Example

console.log(eles.outerWidth()); // 30

Example graph and handle setup

#ele.outerHeight()

// The full drawn height including the border
ele.outerHeight(): number | undefined

The full drawn height including the border.

Returns number | undefined

the outer height, or undefined when empty or removed

Example

console.log(eles.outerHeight()); // 30

Example graph and handle setup

#eles.boundingBox(options?)

// The model-space box enclosing every element of the collection
eles.boundingBox(options?: { includeLabels?: boolean }): { x1: number; y1: number; x2: number; y2: number; w: number; h: number; }

The model-space box enclosing every element of the collection.

Labels are included by default. Node label terms are exact (the laid text block at its anchor plus text-box padding); edge label terms are conservative (a rotation-safe radius about both endpoints), so a box may be slightly larger than the ink but never smaller. The box also covers ghost offsets, overlay/underlay padding and outlines.

Parameters
NameDescription
options: { includeLabels?: boolean }?

{ includeLabels } (default true)

Fields of options
NameDescription
includeLabels: boolean?
Returns { x1: number; y1: number; x2: number; y2: number; w: number; h: number; }

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

Example

console.log(cy.nodes().boundingBox().w); // 130

Example graph and handle setup

Throws

on an unknown option key — a typo must not silently change fit semantics

See

Collection#labelBoundingBox for the label box alone

#eles.labelBoundingBox()

// The exact laid label boxes of this collection's elements, unioned: node labels at their anchors, edge mid-labels at the drawn midpoint, end labels conservatively about their endpoint
eles.labelBoundingBox(): { x1: number; y1: number; x2: number; y2: number; w: number; h: number; }

The exact laid label boxes of this collection's elements, unioned: node labels at their anchors, edge mid-labels at the drawn midpoint, end labels conservatively about their endpoint. Empty (zero) when nothing is labelled. Headless dims are estimates (recorded).

Returns { x1: number; y1: number; x2: number; y2: number; w: number; h: number; }

Example

console.log(cy.nodes().labelBoundingBox().w); // 0

Example graph and handle setup

#eles.renderedBoundingBox(options?)

// boundingBox() transformed into rendered (on-screen) coordinates
eles.renderedBoundingBox(options?: { includeLabels?: boolean }): { x1: number; y1: number; x2: number; y2: number; w: number; h: number; }

boundingBox() transformed into rendered (on-screen) coordinates.

Parameters
NameDescription
options: { includeLabels?: boolean }?

as boundingBox(): { includeLabels }, default true; an unknown key throws

Fields of options
NameDescription
includeLabels: boolean?
Returns { x1: number; y1: number; x2: number; y2: number; w: number; h: number; }

the rendered-space box

Example

cy.zoom(1); cy.pan({ x: 0, y: 0 });
console.log(cy.nodes().renderedBoundingBox().w); // 130

Example graph and handle setup

Also spelled eles.renderedBoundingbox.

#ele.renderedWidth()

// width() scaled by the current zoom — the on-screen width in CSS px
ele.renderedWidth(): number | undefined

width() scaled by the current zoom — the on-screen width in CSS px.

Returns number | undefined

the rendered width, or undefined when empty or removed

Example

cy.zoom(2);
console.log(cy.getElementById('a').renderedWidth()); // 60

Example graph and handle setup

#ele.renderedHeight()

// height() scaled by the current zoom
ele.renderedHeight(): number | undefined

height() scaled by the current zoom.

Returns number | undefined

the rendered height, or undefined when empty or removed

Example

cy.zoom(2);
console.log(cy.getElementById('a').renderedHeight()); // 60

Example graph and handle setup

#ele.renderedOuterWidth()

// outerWidth() scaled by the current zoom
ele.renderedOuterWidth(): number | undefined

outerWidth() scaled by the current zoom.

Returns number | undefined

the rendered outer width, or undefined when empty or removed

Example

cy.zoom(2);
console.log(cy.getElementById('a').renderedOuterWidth()); // 60

Example graph and handle setup

#ele.renderedOuterHeight()

// outerHeight() scaled by the current zoom
ele.renderedOuterHeight(): number | undefined

outerHeight() scaled by the current zoom.

Returns number | undefined

the rendered outer height, or undefined when empty or removed

Example

cy.zoom(2);
console.log(cy.getElementById('a').renderedOuterHeight()); // 60

Example graph and handle setup

#Edge points

Collection › Edge points

Read rendered or model-space endpoints and route geometry.

#ele.midpoint()

// Midpoint of the edge: the curve/route midpoint for curved edges , the endpoint-center average for straight ones
ele.midpoint(): Position | undefined

Midpoint of the edge: the curve/route midpoint for curved edges , the endpoint-center average for straight ones.

Returns Position | undefined

the point a mid-label and a mid-arrow anchor at, in model space; undefined for non-edges. Mid-tween it inherits the position lease's staleness, like the endpoints it derives from

Example

const point = cy.getElementById('ab').midpoint();
console.log(Number.isFinite(point.x)); // true

Example graph and handle setup

#ele.renderedMidpoint()

// midpoint() in rendered (CSS px) space
ele.renderedMidpoint(): Position | undefined

midpoint() in rendered (CSS px) space.

Returns Position | undefined

the rendered midpoint, or undefined for non-edges

Example

const point = cy.getElementById('ab').renderedMidpoint();
console.log(Number.isFinite(point.x)); // true

Example graph and handle setup

#ele.sourceEndpoint()

// Get the first edge's source arrow position in model coordinates
ele.sourceEndpoint(): Position | undefined

Get the first edge's source arrow position in model coordinates. Straight edges meet the source node's boundary with the arrowhead's spacing applied. The line can end farther back to leave room for a hollow arrowhead.

Curved routes return the corresponding point along their computed geometry. Returns undefined when the first element is not an edge.

Returns Position | undefined

the endpoint, or undefined for non-edges

Example

const point = cy.getElementById('ab').sourceEndpoint();
console.log(Number.isFinite(point.x)); // true

Example graph and handle setup

#ele.targetEndpoint()

// Get the first edge's target arrow position in model coordinates
ele.targetEndpoint(): Position | undefined

Get the first edge's target arrow position in model coordinates. Straight edges meet the target node's boundary with the arrowhead's spacing applied. The line can end farther back to leave room for a hollow arrowhead.

Curved routes return the corresponding point along their computed geometry. Returns undefined when the first element is not an edge.

Returns Position | undefined

the endpoint, or undefined for non-edges

Example

const point = cy.getElementById('ab').targetEndpoint();
console.log(Number.isFinite(point.x)); // true

Example graph and handle setup

#ele.renderedSourceEndpoint()

// sourceEndpoint() in rendered (CSS px) space
ele.renderedSourceEndpoint(): Position | undefined

sourceEndpoint() in rendered (CSS px) space.

Returns Position | undefined

the rendered endpoint, or undefined for non-edges

Example

const point = cy.getElementById('ab').renderedSourceEndpoint();
console.log(Number.isFinite(point.x)); // true

Example graph and handle setup

#ele.renderedTargetEndpoint()

// targetEndpoint() in rendered (CSS px) space
ele.renderedTargetEndpoint(): Position | undefined

targetEndpoint() in rendered (CSS px) space.

Returns Position | undefined

the rendered endpoint, or undefined for non-edges

Example

const point = cy.getElementById('ab').renderedTargetEndpoint();
console.log(Number.isFinite(point.x)); // true

Example graph and handle setup

#ele.controlPoints()

// The edge's curve control points (model coords): one for a bundled bezier, two for a self-loop, the control list for an unbundled bezier, undefined otherwise (segments/taxi answer segmentPoints() instead)
ele.controlPoints(): Position[] | undefined

The edge's curve control points (model coords): one for a bundled bezier, two for a self-loop, the control list for an unbundled bezier, undefined otherwise (segments/taxi answer segmentPoints() instead).

Returns Position[] | undefined

the control points in model space, or undefined when the edge has none — which covers straight edges, segments/taxi routes, and a straight edge carrying manual endpoints (the 12c n = 0 chord)

Example

// Straight edges have no intermediate control points.
console.log(cy.getElementById('ab').controlPoints()); // undefined

Example graph and handle setup

#ele.renderedControlPoints()

// controlPoints() in rendered (CSS px) space
ele.renderedControlPoints(): Position[] | undefined

controlPoints() in rendered (CSS px) space.

Returns Position[] | undefined

the rendered control points, or undefined when the edge has none

Example

// Straight edges have no intermediate control points.
console.log(cy.getElementById('ab').renderedControlPoints()); // undefined

Example graph and handle setup

#ele.segmentPoints()

// The edge's segment points (model coords): defined for segments and taxi edges (taxi derives its points), undefined otherwise
ele.segmentPoints(): Position[] | undefined

The edge's segment points (model coords): defined for segments and taxi edges (taxi derives its points), undefined otherwise.

Returns Position[] | undefined

the interior route points in model space — derived ones for taxi, which computes rather than declares them — or undefined for every other family

Example

// Straight edges have no intermediate segment points.
console.log(cy.getElementById('ab').segmentPoints()); // undefined

Example graph and handle setup

#ele.renderedSegmentPoints()

// segmentPoints() in rendered (CSS px) space
ele.renderedSegmentPoints(): Position[] | undefined

segmentPoints() in rendered (CSS px) space.

Returns Position[] | undefined

the rendered segment points, or undefined when the edge has none

Example

// Straight edges have no intermediate segment points.
console.log(cy.getElementById('ab').renderedSegmentPoints()); // undefined

Example graph and handle setup

#Selection

Collection › Selection

Inspect and change element selection and selectability.

#ele.selected()

// Whether the first element is selected
ele.selected(): boolean

Whether the first element is selected.

Returns boolean

true when selected

Example

console.log(eles.selected()); // false

Example graph and handle setup

#ele.selectable()

// Whether the first element may be selected by the user
ele.selectable(): boolean

Whether the first element may be selected by the user. The graph-wide cy.autounselectify() overrides this for user gestures.

Returns boolean

true when selectable

Example

console.log(eles.selectable()); // true

Example graph and handle setup

#eles.select()

// Select every selectable element, emitting select for each one that changed
eles.select(): this

Select every selectable element, emitting a select event for each one that changed. Unselectable elements are skipped.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.select();
console.log(node.selected()); // true

Example graph and handle setup

#eles.unselect()

// Deselect every element, emitting unselect for each one that changed
eles.unselect(): this

Deselect every element, emitting an unselect event for each one that changed.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.unselect();
console.log(node.selected()); // false

Example graph and handle setup

Also spelled eles.deselect.

#eles.selectify()

// Make these elements selectable
eles.selectify(): this

Make these elements selectable.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.selectify();
console.log(node.selectable()); // true

Example graph and handle setup

#eles.unselectify()

// Make these elements unselectable
eles.unselectify(): this

Make these elements unselectable. Does not deselect them; call unselect() for that.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.unselectify();
console.log(node.selectable()); // false

Example graph and handle setup

#Grab, lock and pannability

Collection › Grab, lock and pannability

Inspect active state and control which elements can move through gestures.

#Selection and interaction state

Selections and interaction state (selected, locked, grabbable, pannable, emphasis and visibility) are element state. They can be queried and mutated through collection methods. Classes and class strings are unsupported. Use data, query predicates and declarative style conditions instead.

#ele.grabbable()

// Pannable elements are not draggable, so pannable overrides grabbable
ele.grabbable(): boolean

Pannable elements are not draggable, so pannable overrides grabbable .

Returns boolean

whether a drag gesture would move this element — the effective answer, so a grabbable-but-pannable element reads false here while json() reports the raw field

Example

console.log(eles.grabbable()); // true

Example graph and handle setup

#ele.grabbed()

// Whether the first element is currently held by a drag gesture
ele.grabbed(): boolean

Whether the first element is currently held by a drag gesture.

Returns boolean

true while grabbed

Example

console.log(eles.grabbed()); // false

Example graph and handle setup

#eles.grabify()

// Make these elements grabbable
eles.grabify(): this

Make these elements grabbable.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.grabify();
console.log(node.grabbable()); // true

Example graph and handle setup

#eles.ungrabify()

// Make these elements ungrabbable — the user can no longer drag them, while programmatic position writes still apply
eles.ungrabify(): this

Make these elements ungrabbable — the user can no longer drag them, while programmatic position writes still apply.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.ungrabify();
console.log(node.grabbable()); // false

Example graph and handle setup

#ele.locked()

// Whether the first element is locked — immovable, by layouts, position writes and position tweens alike (one rule every layout holds a locked node where it is and keeps it in the layout's structure; force treats it as an obstacle its settle separates the others from)
ele.locked(): boolean

Whether the first element is locked — immovable, by layouts, position writes and position tweens alike (one rule every layout holds a locked node where it is and keeps it in the layout's structure; force treats it as an obstacle its settle separates the others from). A locked child stays where it is when its compound parent is positioned, shifted or dragged — its own subtree with it — and the parent re-derives about the stayers and the movers. True for every node while cy.autolock( true) is set; the flag column alone is what { locked: true } filters read.

Returns boolean

true when locked

Example

console.log(eles.locked()); // false

Example graph and handle setup

#eles.lock()

// Lock these elements against movement
eles.lock(): this

Lock these elements against movement. A node locked mid-tween holds where its position tween got to; the rest of the animation — other nodes, and this node's paint channels — runs on, and unlocking does not resume it.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.lock();
console.log(node.locked()); // true

Example graph and handle setup

#eles.unlock()

// Unlock these elements
eles.unlock(): this

Unlock these elements.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.unlock();
console.log(node.locked()); // false

Example graph and handle setup

#ele.active()

// Whether the first element is in the transient pressed ("active") state
ele.active(): boolean

Whether the first element is in the transient pressed ("active") state.

Returns boolean

the pressed flag the pointer layer sets while a press is held — transient interaction state, not a persisted property

Example

console.log(eles.active()); // false

Example graph and handle setup

#ele.pannable()

// Whether dragging the first element pans the graph instead of grabbing it
ele.pannable(): boolean

Whether dragging the first element pans the graph instead of grabbing it.

Returns boolean

the raw pannable flag; because pannable overrides grabbable, a true here forces grabbable() false

Example

console.log(eles.pannable()); // false

Example graph and handle setup

#eles.panify()

// Make dragging these elements pan the viewport instead of moving them
eles.panify(): this

Make dragging these elements pan the viewport instead of moving them. Pannable overrides grabbable.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.panify();
console.log(node.pannable()); // true

Example graph and handle setup

#eles.unpanify()

// Stop these elements from panning the viewport when dragged, so a grabbable one becomes draggable again
eles.unpanify(): this

Stop these elements from panning the viewport when dragged, so a grabbable one becomes draggable again.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.unpanify();
console.log(node.pannable()); // false

Example graph and handle setup

#Visibility and emphasis

Collection › Visibility and emphasis

Inspect visibility and core-owned emphasis state.

#ele.visible()

// Whether the first element renders (the derived FLAGDRAWN — shown AND not visibility: 'hidden' on self or, for nodes, any ancestor; edges additionally fold their endpoints)
ele.visible(): boolean

Whether the first element renders (the derived FLAG_DRAWN — shown AND not visibility: 'hidden' on self or, for nodes, any ancestor; edges additionally fold their endpoints). The renderer's cull pass and CPU picking mask on the same bit, so an element that is not visible() neither draws nor picks. For space-tier state (in the bb, sizing its compound parent) see takesUpSpace() — an invisible element keeps its space.

Returns boolean

whether the element draws and picks; false for a removed element, for an edge either of whose endpoints is hidden, and for a node under a hidden or invisible ancestor

Example

console.log(eles.visible()); // true

Example graph and handle setup

#ele.hidden()

// The complement of visible()
ele.hidden(): boolean

The complement of visible().

Returns boolean

true when the first element does not draw

Example

console.log(eles.hidden()); // false

Example graph and handle setup

#eles.show()

// Show these elements — the display tier
eles.show(): this

Show these elements — the display tier. Shown elements take up space again, rejoin bounds and fit, and re-fan their bezier bundles.

For paint-only invisibility that keeps space and bundle ranks, use the visibility style property instead, and for a fade use an opacity transition.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.show();
console.log(node.visible()); // true

Example graph and handle setup

#eles.hide()

// Hide these elements structurally
eles.hide(): this

Hide these elements structurally. They stop drawing and picking, leave the bounding box and their ancestors' auto-bounds, and their bezier bundles re-fan without them. Descendants of a hidden node are gated too.

Returns this

this collection, for chaining

Example

const node = cy.getElementById('a');
node.hide();
console.log(node.hidden()); // true

Example graph and handle setup

#ele.emphasized()

// Whether the first element is in the current emphasis — the set the last cy.emphasize( eles) named
ele.emphasized(): boolean

Whether the first element is in the current emphasis — the set the last cy.emphasize( eles) named.

Returns boolean

the element's emphasized flag; false for a removed element and while no emphasis is set. An element outside a set emphasis is the one the renderer dims — derived, so there is no dimmed()

Example

console.log(eles.emphasized()); // false

Example graph and handle setup

#Style

Collection › Style

Read resolved styling and manage supported bypasses.

#ele.style()

// Get all style
ele.style(): unknown

Resolved style read off the stored channels — all of the first element's group props.

Returns unknown

the whole group's props (numbers for numeric props, rgb()/rgba() strings for colors, keywords otherwise), or undefined when the collection is empty

Example

console.log(cy.nodes().first().style()['background-color']); // "rgb(153,153,153)"

Example graph and handle setup

#ele.style(name)

// Get style by name
ele.style(name: string): unknown

Resolved style read off the stored channels — one value. A bypassed prop reads its bypass value, since a bypass writes stored truth.

Parameters
NameDescription
name: string

the property to read, dash-case or camelCase

Returns unknown

the resolved value, or undefined when the collection is empty or the prop belongs to the other group

Example

console.log(cy.nodes().first().style('background-color')); // "rgb(153,153,153)"

Example graph and handle setup

#eles.style(name, value)

// Set style by name
eles.style(name: string, value: unknown): this

Set a per-element style bypass on every element. Sugar over the stylesheet's bypasses section: the value must be a constant (mappers belong in the sheet's group blocks), the entry is keyed by the element's id and survives remove/re-add, it beats every sheet rule including the default sheet's selection color, and it exports from cy.json().

Parameters
NameDescription
name: string

the property to bypass, dash-case or camelCase

value: unknown

the constant value to pin

Returns this

this collection, for chaining

Example

const result = eles.style('width', 40);
console.log(result === eles); // true

Example graph and handle setup

Throws

on a mapper value, a global font prop, a transition config prop, a wrong-group prop, or an invalid value

#eles.style(props)

// Set several style fields
eles.style(props: Record<string, unknown>): this

Set several per-element style bypasses on every element. The object form of the setter: each key–value pair joins the element's bypass declaration.

Parameters
NameDescription
props: Record<string, unknown>

prop → constant value, dash-case or camelCase keys

Returns this

this collection, for chaining

Example

eles.style({ width: 40 });
console.log(eles.first().numericStyle('width')); // 40

Example graph and handle setup

Throws

as the name/value form does, per prop

Also spelled eles.css.

#eles.removeStyle()

// Remove all keys
eles.removeStyle(): this

Remove per-element style bypasses from every element. Values return to those supplied by the stylesheet, including any configured transitions.

Returns this

this collection, for chaining

Example

cy.style({ bypasses: { a: { width: 60 } } });
cy.getElementById('a').removeStyle();
console.log(cy.getElementById('a').width()); // 30

Example graph and handle setup

#eles.removeStyle(name)

// Remove the specified keys
eles.removeStyle(name: string): this

Remove per-element style bypasses from every element. Values return to those supplied by the stylesheet, including any configured transitions.

Parameters
NameDescription
name: string

the property to un-bypass, dash-case or camelCase; omit to clear each element's whole bypass declaration

Returns this

this collection, for chaining

Example

cy.style({ bypasses: { a: { width: 60 } } });
cy.getElementById('a').removeStyle('width');
console.log(cy.getElementById('a').width()); // 30

Example graph and handle setup

Also spelled eles.removeCss.

#ele.renderedStyle(name?)

// Like style(), but with length props (width, height, border-width, font-size) scaled into rendered (on-screen) px by the zoom
ele.renderedStyle(name?: string): unknown

Like style(), but with length props (width, height, border-width, font-size) scaled into rendered (on-screen) px by the zoom.

Parameters
NameDescription
name: string?

a property name; omit for the whole group

Returns unknown

the rendered-space value, or the whole group's props

Example

cy.zoom(2);
console.log(cy.getElementById('a').renderedStyle('width')); // 60

Example graph and handle setup

Also spelled eles.renderedCss.

#ele.numericStyle(name)

// The numeric value of a numeric style prop
ele.numericStyle(name: string): number | undefined

The numeric value of a numeric style prop.

Parameters
NameDescription
name: string

a numeric style property

Returns number | undefined

the number, or undefined when the collection is empty or the prop belongs to the other group

Example

console.log(cy.nodes().first().numericStyle('width')); // 30

Example graph and handle setup

Throws

if the prop resolves to a colour or a keyword rather than a number

#ele.effectiveOpacity()

// The rendered opacity: a node's own opacity times its ancestors' (the store keeps the folded value in the column); an edge's own opacity (edges have no parent)
ele.effectiveOpacity(): number | undefined

The rendered opacity: a node's own opacity times its ancestors' (the store keeps the folded value in the column); an edge's own opacity (edges have no parent).

Returns number | undefined

the opacity actually rendered, which is what transparent() tests against 0 — not the declared opacity style value, which style('opacity') reads; undefined when empty or removed

Example

console.log(eles.effectiveOpacity()); // 1

Example graph and handle setup

#ele.transparent()

// Whether the first element is fully transparent — its effective opacity, with compound ancestors folded in, is exactly 0
ele.transparent(): boolean

Whether the first element is fully transparent — its effective opacity, with compound ancestors folded in, is exactly 0.

Returns boolean

true when invisible through opacity

Example

console.log(eles.transparent()); // false

Example graph and handle setup

#ele.takesUpSpace()

// The space tier: shown elements occupy space — they join bb/fit and size their compound parents — even when visibility: 'hidden' keeps them from rendering
ele.takesUpSpace(): boolean

The space tier: shown elements occupy space — they join bb/fit and size their compound parents — even when visibility: 'hidden' keeps them from rendering. display-tier hide() clears it.

Returns boolean

whether the element occupies space — this can differ from visible(), which is the paint tier

Example

console.log(eles.takesUpSpace()); // true

Example graph and handle setup

#ele.interactive()

// Whether the element can be interacted with: visible and not pointer-transparent (events: 'no')
ele.interactive(): boolean

Whether the element can be interacted with: visible and not pointer-transparent (events: 'no').

Returns boolean

whether any pointer path will resolve to this element; it rides visible(), so an element hidden either way is inert

Example

console.log(eles.interactive()); // true

Example graph and handle setup

#ele.label()

// The node's resolved label text ('' when none)
ele.label(): string | undefined

The node's resolved label text ('' when none). To set the label, update the stylesheet or the data field it reads.

Returns string | undefined

the resolved text of the first element's label — '' when it has none (a labelled-but-empty label reads the same), and undefined when the collection is empty or the element was removed

Example

console.log(eles.label()); // ""

Example graph and handle setup

#Events

Collection › Events

Bind event handlers to each element in a collection.

#eles.on(events, callback?)

// Listen for events on each element of this collection
eles.on(events: string, callback?: EventHandler<NodeData, EdgeData>): this

Listen for events on each element of this collection. The handler is bound per element, and keeps firing across slot compaction — listeners repair with their elements rather than going stale.

Events bubble from an element through its compound ancestors to the core, with stopPropagation() honoured.

Any name registers, as on the core and for the same reason — custom events are supported API (ele.emit( 'foo')), so names cannot be gated. A name the library never emits fires only when your application emits it. Names match literally: 'data.ns' is distinct from 'data'. Raw mouse/touch names and vmouse* aliases are not emitted by the library. See Core#on.

Parameters
NameDescription
events: string

one or more space-separated event names

callback: EventHandler<NodeData, EdgeData>?

the handler

Returns this

this collection, for chaining

Example

const seen = [];
const handler = event => seen.push(event.type);
cy.getElementById('a').on('example', handler);
cy.getElementById('a').emit('example');
cy.getElementById('a').off('example', handler);
console.log(seen); // ['example']

Example graph and handle setup

Also spelled eles.addListener.

#eles.one(events, callback?)

// Like on(), but each element's handler runs at most once
eles.one(events: string, callback?: EventHandler<NodeData, EdgeData>): this

Like on(), but each element's handler runs at most once.

Parameters
NameDescription
events: string

one or more space-separated event names

callback: EventHandler<NodeData, EdgeData>?

the handler

Returns this

this collection, for chaining

Example

let count = 0;
cy.getElementById('a').one('example', () => count++);
cy.getElementById('a').emit('example');
cy.getElementById('a').emit('example');
console.log(count); // 1

Example graph and handle setup

Also spelled eles.once.

#eles.off(events, callback?)

// Stop listening on each element of this collection
eles.off(events: string, callback?: EventHandler<NodeData, EdgeData>): this

Stop listening on each element of this collection.

Parameters
NameDescription
events: string

one or more space-separated event names

callback: EventHandler<NodeData, EdgeData>?

the handler to remove; omit to remove every handler these elements have for events

Returns this

this collection, for chaining

Example

let count = 0;
const handler = () => count++;
cy.getElementById('a').on('example', handler);
cy.getElementById('a').off('example', handler);
cy.getElementById('a').emit('example');
console.log(count); // 0

Example graph and handle setup

Also spelled eles.removeListener.

#eles.emit(events, extraParams?)

// Emit an event on each element, bubbling through compound ancestors to the core
eles.emit(events: string, extraParams?: unknown[]): this

Emit an event on each element, bubbling through compound ancestors to the core.

Parameters
NameDescription
events: string

one or more space-separated event names

extraParams: unknown[]?

extra arguments passed to each handler after the event object

Returns this

this collection, for chaining

Example

cy.getElementById('a').one('example', event => console.log(event.type)); // "example"
cy.getElementById('a').emit('example'); // logs 'example'

Example graph and handle setup

Also spelled eles.trigger.

#eles.promiseOn(events)

// Resolve once the next matching event fires on any element of this collection — the promise form of one()
eles.promiseOn(events: string): Promise<Event<NodeData, EdgeData>>

Resolve once the next matching event fires on any element of this collection — the promise form of one().

Parameters
NameDescription
events: string

one or more space-separated event names

Returns Promise<Event<NodeData, EdgeData>>

a promise for the event object

Example

const next = cy.getElementById('a').promiseOn('example');
cy.getElementById('a').emit('example');
console.log((await next).type); // 'example'

Example graph and handle setup

Also spelled eles.pon.

#Animation

Collection › Animation

Animate model position and supported style channels, with promise-based sequencing.

#eles.animate(opts)

// Animate these elements' style and/or position to explicit targets over duration ms, easing the normalized time
eles.animate(opts: AnimateOptions): this

Animate these elements' style and/or position to explicit targets over duration ms, easing the normalized time.

There is no queue: the animation starts immediately, animations on disjoint channels run concurrently, and starting one that overlaps a running animation's channels stops the older one in place — its promise resolves, its values freeze, and the new animation captures from there. Sequence with await animation( …).play() rather than by queueing.

Animatable: position; opacity (both groups); node background-color/border-color/border-width, edge line-color; and the geometry numerics node width/height, edge width, compound padding and font-size. Colours interpolate in OKLab, matching the colour mappers.

Use named easings or cubic-bezier( …), CSS linear( …) and spring( bounce). A custom easing function is rejected — a closure cannot cross to the GPU, so accepting one would mean a curve that silently depended on whether the animation got offloaded.

Parameters
NameDescription
opts: AnimateOptions

targets (position, style, or collapsed for compound parents; viewport forms apply on cy.animate), duration, easing, delay, complete

Fields of opts
NameDescription
style: Record<string, string | number>?
position: Partial<Position>?
collapsed: boolean?

Target the collapsed state of compound parents. This is an element-only animation channel and may be combined with timing options, but not with other style, position, or viewport targets.

pan: Position?

viewport targets (core.animate)

panBy: Position?

viewport target: pan by a delta rather than to an absolute position. Resolved against the pan at creation time, so a manual pan afterwards does not move the target. Throws alongside pan — the two spell the same channel. Core-only: an element animation ignores it.

zoom: number?
fit: { eles?: unknown; boundingBox?: { x1: number; y1: number; x2?: number; y2?: number; w?: number; h?: number; }; padding?: number; }?

viewport target: animate to the viewport that fits the given elements (or an explicit model-space box). Resolved to pan/zoom when the animation is created.

center: { eles?: unknown }?

viewport target: animate the pan that centers the given elements

duration: number?
easing: string?

A named easing, cubic-bezier(), linear() or spring(bounce). For a spring, duration is the perceptual duration and the animation runs on past it to settle, so its total length is longer (see durationMs).

delay: number?
complete: () => void?
Returns this

this collection, for chaining; use animation() when you want the handle

Example

eles.animate({ position: { x: 20, y: 10 }, duration: 100 });
eles.stop(true);
console.log(cy.getElementById('a').position('x')); // 20

Example graph and handle setup

See

Collection#animation for the handle form with promise/pause/resume/reverse

#eles.animation(opts)

// Build an animation for these elements without starting it
eles.animation(opts: AnimateOptions): AnimationHandle

Build an animation for these elements without starting it.

Parameters
NameDescription
opts: AnimateOptions

the tween targets (position, style, or compound collapsed state) plus duration, delay, easing and complete

Fields of opts
NameDescription
style: Record<string, string | number>?
position: Partial<Position>?
collapsed: boolean?

Target the collapsed state of compound parents. This is an element-only animation channel and may be combined with timing options, but not with other style, position, or viewport targets.

pan: Position?

viewport targets (core.animate)

panBy: Position?

viewport target: pan by a delta rather than to an absolute position. Resolved against the pan at creation time, so a manual pan afterwards does not move the target. Throws alongside pan — the two spell the same channel. Core-only: an element animation ignores it.

zoom: number?
fit: { eles?: unknown; boundingBox?: { x1: number; y1: number; x2?: number; y2?: number; w?: number; h?: number; }; padding?: number; }?

viewport target: animate to the viewport that fits the given elements (or an explicit model-space box). Resolved to pan/zoom when the animation is created.

center: { eles?: unknown }?

viewport target: animate the pan that centers the given elements

duration: number?
easing: string?

A named easing, cubic-bezier(), linear() or spring(bounce). For a spring, duration is the perceptual duration and the animation runs on past it to settle, so its total length is longer (see durationMs).

delay: number?
complete: () => void?
Returns AnimationHandle

the handle; nothing runs until play()

Example

const handle = eles.animation({ position: { x: 20, y: 10 }, duration: 1 });
await handle.play();
console.log(handle.progress()); // 1

Example graph and handle setup

#eles.delay(duration, complete?)

// A no-op tween — a timed pause that touches no channels, so it composes with any running animation (use delayAnimation().play() + await to sequence)
eles.delay(duration: number, complete?: () => void): this

A no-op tween — a timed pause that touches no channels, so it composes with any running animation (use delayAnimation().play() + await to sequence).

Parameters
NameDescription
duration: number

the pause in ms

complete: () => void?

called when it elapses

Returns this

this collection, for chaining

Example

eles.delay(1);
eles.stop(true);
console.log(eles.animated()); // false

Example graph and handle setup

#eles.delayAnimation(duration, complete?)

// Like {@link delay}, but returns the handle instead of chaining
eles.delayAnimation(duration: number, complete?: () => void): AnimationHandle

Like delay, but returns the handle instead of chaining.

Parameters
NameDescription
duration: number

the pause in ms

complete: () => void?

called when it elapses

Returns AnimationHandle

the handle; nothing runs until play()

Example

const handle = eles.delayAnimation(1);
await handle.play();
console.log(handle.progress()); // 1

Example graph and handle setup

#eles.animated()

// True when any of these elements has a running animation
eles.animated(): boolean

True when any of these elements has a running animation.

Returns boolean

whether any element here is animating — not whether all are, and not whether the viewport is (that is cy.animated())

Example

console.log(eles.animated()); // false

Example graph and handle setup

#eles.stop(jumpToEnd?)

// Stop every running animation on these elements (animations have no queue)
eles.stop(jumpToEnd?: boolean): this

Stop every running animation on these elements (animations have no queue).

Parameters
NameDescription
jumpToEnd: boolean?Default: false

apply each animation's final values instead of freezing each channel where its tween reached

Returns this

this collection, for chaining

Example

eles.animate({ position: { x: 20, y: 10 }, duration: 100 });
eles.stop(true);
console.log(eles.animated()); // false

Example graph and handle setup

#Layout

Collection › Layout

Scope a layout to a collection and use shared placement helpers.

#Scoped layouts

A collection can scope a layout with eles.layout(options); the resulting handle uses the same run(), promise() and stop() lifecycle as a core layout.

#ele.layoutDimensions(options?)

// Node dimensions for layout spacing — the body, plus the label box under nodeDimensionsIncludeLabels: true (body-only by default)
ele.layoutDimensions(options?: { nodeDimensionsIncludeLabels?: boolean }): { w: number; h: number; }

Node dimensions for layout spacing — the body, plus the label box under nodeDimensionsIncludeLabels: true (body-only by default).

Parameters
NameDescription
options: { nodeDimensionsIncludeLabels?: boolean }?Default: {}

{ nodeDimensionsIncludeLabels: true } to include the label box

Fields of options
NameDescription
nodeDimensionsIncludeLabels: boolean?
Returns { w: number; h: number; }

the first element's { w, h }

Example

console.log(cy.nodes().first().layoutDimensions()); // { w: 30, h: 30 }

Example graph and handle setup

#eles.layoutPositions(layout, options, fn)

// Apply a layout's position function to this collection's nodes with the standard layout options (spacingFactor, transform, fit/zoom/pan, animate) and the layoutstart/layoutready/layoutstop event flow
eles.layoutPositions(layout: object, options: LayoutBaseOptions, fn: (node: Collection<NodeData, EdgeData, Data>, i: number) => Position): this

Apply a layout's position function to this collection's nodes with the standard layout options (spacingFactor, transform, fit/zoom/pan, animate) and the layoutstart/layoutready/layoutstop event flow. With animate: true the viewport animates concurrently (a fit targets the bounding box at the final positions).

Parameters
NameDescription
layout: object

the layout instance the lifecycle events carry as event.layout; it is not called back, only reported

options: LayoutBaseOptions

the standard layout options (spacingFactor, transform, fit/padding, zoom/pan, animate, animationDuration, animateFilter)

fn: (node: Collection<NodeData, EdgeData, Data>, i: number) => Position

( node, i) => position, evaluated once per positioned node; parents are excluded (auto-bounds derive them)

Fields of options
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 this

this collection, for chaining

Example

cy.layout({ impl: { run(ctx) {
ctx.eles.layoutPositions({}, { fit: false }, (node, i) => ({ x: i * 40, y: 0 }));
} } }).run();
console.log(cy.getElementById('b').position('x')); // 40

Example graph and handle setup

#eles.layout(options)

// A layout scoped to this collection
eles.layout(options: LayoutOptions): ReturnType<Core['layout']>

A layout scoped to this collection.

Parameters
NameDescription
options: LayoutOptions

the layout options, as cy.layout(); eles is set to this collection

Fields of options
NameDescription
name: undefined?
avoidOverlap: boolean?

separate nodes by their extents (default true) — bodies, plus labels when nodeDimensionsIncludeLabels is true (114.6); false places points, nodeSep / rankSep then centre to centre

avoidOverlapPadding: number?

extra room around each body (default 0 — nodeSep and rankSep own the spacing)

condense: boolean?

size the rings by their nodes rather than by the box (125.3, grid's spelling): every ring takes the smallest radius that clears its own nodes and the ring inside it at avoidOverlapPadding, so the gap is the option and the viewport only centres. Off (the default), the rings start at an even share of the box's shorter side (or levelSpacing) and only grow from there. Implies avoidOverlap.

rows: number?
cols: number?
position: (node: unknown) => { row?: number; col?: number } | undefined?

returns a fixed { row, col } for a node handle

sort: LayoutSortMapping | ((a: unknown, b: unknown) => number)?

the order around the circle: a { data, order? } sort mapping (canonical, serializable — 85.3) or a comparator over node handles

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

packComponents: boolean?

lay each disconnected component out on its own — one ring, one grid, one tree per component — and shelf-pack the results largest first (default false: one drawing about one centre). Locked nodes are left out and the packed field is moved off their boxes.

componentSpacing: number?

the gap between packed disconnected components (default 40)

componentGroup: ( component: LayoutComponentInfo, ) => string | number | null | undefined?

group the packed components (121.1): called once per component with its description, and the components sharing a key pack on their own, the groups standing in a row left to right by key — numbers ascending, then strings, then the unkeyed.

componentOrder: (a: LayoutComponentInfo, b: LayoutComponentInfo) => number?

the order the pack lays components out in, a comparator over two descriptions ahead of largest-first (121.1).

groupSpacing: number?

the gap between the groups' packed boxes (default three componentSpacings)

positions: | Record<string, Position> | ((node: unknown) => Position | null | undefined)?

node id → position map, or a function of a node handle; absent nodes keep their position

radius: number?

the circle's radius (computed when omitted)

startAngle: number?

where the sweep begins, in radians (default 3π/2 — up)

sweep: number?

the total angle the trees share, in radians (default 2π)

clockwise: boolean?

wedge order runs clockwise (default true)

counterclockwise: boolean?
equidistant: boolean?

whether levels are an equal radial distance apart

minNodeSpacing: number?

min spacing between node outsides (radius adjustment)

height: number?

height/width of the layout area (override the container)

width: number?
concentric: LayoutScoreMapping | ((node: unknown) => number)?

the score deciding ring membership — higher sits closer to the center (default: degree). A { data, … } score mapping (canonical, serializable — 85.3) or a function of the node handle

levelWidth: (nodes: unknown) => number?

the variation of concentric values per level (default: maxDegree / 4)

directed: boolean?

whether the tree is directed downwards (default false)

direction: 'downward' | 'upward' | 'leftward' | 'rightward'?

drawing direction of the flow (default 'downward')

circle: boolean?

put depths in concentric circles instead of rows

grid: boolean?

place the DAG on an even grid (circle: false only)

roots: unknown?

the tree roots: a collection or an array of node ids (never a selector string); omitted, a component's roots are the nodes with no incoming edge (125.3 — radial is a hierarchy's picture), or its maximum-degree nodes when it has none (a cycle) — maximum degree alone before 125.3

depthSort: LayoutSortMapping | ((a: unknown, b: unknown) => number)?

the order within a depth: a { data, order? } sort mapping (canonical, serializable — 85.3) or a comparator over node handles

maximal: boolean?

shift nodes down to their maximal depths (DAGs only)

acyclic: boolean?

the graph is known acyclic: skip cycle removal (default false)

seed: number?
levelSpacing: number?

the ring gap in model px; derived from the bounding box unset. A floor under avoidOverlap: a ring grows past it when its nodes would otherwise touch

weight: 'leaves' | 'subtree'?

what sizes a subtree's wedge: its leaf count (default) or its whole node count

edgeLength: number | LayoutScoreMapping | ((edge: unknown) => number)?

ideal edge length: a number; a { data, scale?, range?, invert?, default? } score mapping (canonical, serializable — 85.3, e.g. { data: 'score', scale: 'log', range: [40, 200], invert: true } for large scores → short edges); or a plain fn of the edge handle. Resolved once at start either way

repulsion: number?
stiffness: number?
gravity: number?
decay: number?

alpha annealing rate per iteration

iterations: number?
threshold: number?

convergence: settled when max displacement stays under this

randomize: boolean?

fresh seeded scatter (default) vs relaxing current positions

animateLive: boolean?

stream the run: positions land per frame while the sim runs (the pre-114 animate: true); takes precedence over animate

infinite: boolean?

the run has no end of its own (118.3): it streams like animateLive and then ticks only while the field is moving — at rest it costs nothing, and a drag, a position() write or an added / removed element (whole-graph scope) heats it back up; the grabbed node is pinned for the gesture and its neighbourhood reflows around it. layout.stop() ends it, landing the positions as they stand — no separation pass, no re-pack, no fit and no tween. avoidOverlap therefore means the per-tick sweep ('sim'); iterations is ignored; layout.reheat() is the handle for a change the run cannot see

stepsPerFrame: number?

iterations per animation frame (animateLive: true; default 3)

executor: 'auto' | 'cpu' | 'gpu' | 'workers'?

where the simulation runs (default 'auto'): 'auto' takes the GPU integrator where the renderer offers one, else the CPU simulation on a worker that loaded this same bundle wherever one can be constructed — headless included, so a Node process keeps its event loop free as a page keeps its UI thread (the run is then asynchronous: positions at layoutstop / promise()) — else in-thread. 'cpu' is the in-thread reference (bit-reproducible; the worker answers the same bits) and the synchronous spelling; 'workers' asks for the worker and throws at start where none can be constructed; 'gpu' throws at start where no integrator is available

init: 'spectral' | 'scatter'?

what a fresh placement is (59.4): 'spectral' (the default — landmark-MDS per component, the global untangling) or 'scatter' (the plain seeded scatter). Ignored under randomize: false.

nestingFactor: number?

ideal-length multiplier per compound boundary an edge spans (length × levels × nestingFactor; default 1.2)

gravityCompound: number?

the compound centroid pull, as a multiple of gravity (59.5; the Bilkent line's gravityCompound — default 1.5)

alignment: { horizontal?: string[][]; vertical?: string[][] }?

alignment constraints (85.2, fcose's shape): horizontal groups share a y coordinate, vertical groups an x — id arrays, serializable; groups sharing a node merge. A locked member pins its group. Constrained runs take the CPU executor.

relativePlacement: ( | { left: string; right: string; gap?: number } | { top: string; bottom: string; gap?: number } )[]?

relative-placement constraints (85.2): keep left at least gap px left of right (top/bottom likewise vertically); gap defaults to the run's mean ideal edge length.

nodeSep: number?

px gap between adjacent nodes in a rank (default 50): between their boxes' facing sides, each node's own extent on that side (125.2 — a label hung to one side of its body extends that side alone), and along the rank's axis for the direction (a rightward rank is separated by heights)

rankSep: number?

px gap between rank rows (default 60): a row reaches as far from its centre line as its nodes' extents on each side, and a taxi edge's turn lands inside this band, which the layout keeps node-free

edgeSep: number?

px per taxi track a rank gap grows to hold (default 10, round 124.5): the gap below a rank becomes max(rankSep, tracks × edgeSep + 20), where tracks is how many of that rank's fan-outs overlap on one line — the lines taxi-turn: auto draws; 0 leaves every gap at rankSep

layering: 'network-simplex' | 'longest-path' | 'auto'?

rank assignment: 'network-simplex' (GKNV — fewest long edges, default), 'longest-path' (O(V+E), the huge-graph fast path), or 'auto' (simplex up to ~50k nodes, then longest-path)

thoroughness: number?

crossing-minimization effort, 1..10 (default 7): scales the sweep and transpose budgets

minLength: number | LayoutScoreMapping | ((edge: unknown) => number)?

minimum ranks an edge must span (default 1): a number, a { data, … } score mapping (85.3), or a fn of the edge handle

edgeWeight: number | LayoutScoreMapping | ((edge: unknown) => number)?

edge straightening weight (default 1): heavier edges pull straighter through crossing minimization and coordinates — a number, a score mapping, or a fn of the edge handle

cycleRemoval: 'greedy' | 'dfs'?

which arcs flip on cycles: 'greedy' (Eades–Lin–Smyth bound, default) or 'dfs' (input order dominates)

rankConstraints: { min?: string[]; max?: string[]; same?: string[][] }?

rank constraints as id lists (never selector strings): min pins to the first rank, max to the last, each same group to one shared rank

impl: unknown
Returns ReturnType<Core['layout']>

the layout instance; nothing runs until run()

Example

const handle = cy.nodes().layout({ name: 'grid', fit: false });
handle.run();
console.log(cy.nodes().length); // 3

Example graph and handle setup

Also spelled eles.makeLayout, eles.createLayout.

#Traversing

Collection › Traversing

Follow incidence, directed reachability, edge relations and connectivity.

#Traversal, layouts and algorithms

Collections can traverse edge incidence (source, target, connectedNodes, connectedEdges, outgoers, incomers and neighborhood), compound containment (parent, parents, children, descendants and siblings) and directed reachability (successors, predecessors, roots, leaves). Compound ancestry remains distinct from graph connectivity.

#Incidence and neighbourhood

Collection › Traversing › Incidence and neighbourhood

Follow incident nodes, edges and immediate neighbours.

#ele.source()
// The source node of the first edge
ele.source(): Collection<NodeData, EdgeData, NodeData>

The source node of the first edge.

Returns Collection<NodeData, EdgeData, NodeData>

the source node, or an empty collection for a non-edge

Example

console.log(cy.getElementById('ab').source().id()); // 'a'

Example graph and handle setup

#ele.target()
// The target node of the first edge
ele.target(): Collection<NodeData, EdgeData, NodeData>

The target node of the first edge.

Returns Collection<NodeData, EdgeData, NodeData>

the target node, or an empty collection for a non-edge

Example

console.log(cy.getElementById('ab').target().id()); // 'b'

Example graph and handle setup

#eles.sources()
// The source nodes of every edge in the collection, deduped
eles.sources(): Collection<NodeData, EdgeData, NodeData>

The source nodes of every edge in the collection, deduped.

Returns Collection<NodeData, EdgeData, NodeData>

the source nodes

Example

console.log(eles.sources().map(ele => ele.id())); // ["a","b"]

Example graph and handle setup

#eles.targets()
// The target nodes of every edge in the collection, deduped
eles.targets(): Collection<NodeData, EdgeData, NodeData>

The target nodes of every edge in the collection, deduped.

Returns Collection<NodeData, EdgeData, NodeData>

the target nodes

Example

console.log(eles.targets().map(ele => ele.id())); // ["b","c"]

Example graph and handle setup

#eles.connectedEdges(criterion?)
// Every edge incident on the nodes in this collection, deduped — answered off the CSR adjacency index, so it is O(incident edges) rather than a scan
eles.connectedEdges(criterion?: FilterLike<NodeData, EdgeData, EdgeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, EdgeData>

Every edge incident on the nodes in this collection, deduped — answered off the CSR adjacency index, so it is O(incident edges) rather than a scan. Loops appear once.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, EdgeData, NodeData | EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, EdgeData>

the incident edges

Example

console.log(eles.connectedEdges().map(ele => ele.id())); // ["ab","bc"]

Example graph and handle setup

#eles.connectedNodes(criterion?)
// The endpoint nodes of every edge in this collection, deduped
eles.connectedNodes(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

The endpoint nodes of every edge in this collection, deduped.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the endpoint nodes

Example

console.log(eles.connectedNodes().map(ele => ele.id())); // ["a","b","c"]

Example graph and handle setup

#eles.outgoers(criterion?)
// The immediate outgoing neighbourhood: the edges leaving these nodes plus the nodes they point at
eles.outgoers(criterion?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>

The immediate outgoing neighbourhood: the edges leaving these nodes plus the nodes they point at. One hop only — use successors() for the transitive closure.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData>

the outgoing edges and their target nodes

Example

console.log(eles.outgoers().map(ele => ele.id())); // ["ab","b","bc","c"]

Example graph and handle setup

#eles.incomers(criterion?)
// The immediate incoming neighbourhood: the edges arriving at these nodes plus the nodes they come from
eles.incomers(criterion?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>

The immediate incoming neighbourhood: the edges arriving at these nodes plus the nodes they come from. One hop only — use predecessors() for the transitive closure.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData>

the incoming edges and their source nodes

Example

console.log(eles.incomers().map(ele => ele.id())); // ["ab","a","bc","b"]

Example graph and handle setup

#eles.neighborhood(criterion?)
// The open neighbourhood: the incident edges and the nodes on their far ends, ignoring edge direction, excluding the collection's own elements
eles.neighborhood(criterion?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>

The open neighbourhood: the incident edges and the nodes on their far ends, ignoring edge direction, excluding the collection's own elements.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData>

the neighbouring edges and nodes

Example

console.log(eles.neighborhood().map(ele => ele.id())); // []

Example graph and handle setup

Also spelled eles.openNeighborhood.

See

Collection#closedNeighborhood to include these nodes

#eles.closedNeighborhood(criterion?)
// The open neighbourhood plus this collection's own nodes
eles.closedNeighborhood(criterion?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>

The open neighbourhood plus this collection's own nodes.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData>

the closed neighbourhood

Example

console.log(eles.closedNeighborhood().map(ele => ele.id())); // ["a","b","c"]

Example graph and handle setup

#Directed reachability

Collection › Traversing › Directed reachability

Find roots, leaves, successors and predecessors.

#eles.roots(criterion?)
// Collection nodes with no non-loop incoming edge (whole-graph incidence)
eles.roots(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

Collection nodes with no non-loop incoming edge (whole-graph incidence).

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the source nodes

Example

console.log(eles.roots().map(ele => ele.id())); // ["a"]

Example graph and handle setup

#eles.leaves(criterion?)
// Collection nodes with no non-loop outgoing edge
eles.leaves(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

Collection nodes with no non-loop outgoing edge.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the sink nodes

Example

console.log(eles.leaves().map(ele => ele.id())); // ["c"]

Example graph and handle setup

#eles.successors(criterion?)
// Everything reachable by following outgoing edges, transitively — the edges and nodes of the forward closure, excluding these nodes themselves (unless a cycle reaches them)
eles.successors(criterion?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>

Everything reachable by following outgoing edges, transitively — the edges and nodes of the forward closure, excluding these nodes themselves (unless a cycle reaches them).

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData>

the reachable edges and nodes

Example

console.log(eles.successors().map(ele => ele.id())); // ["ab","b","bc","c"]

Example graph and handle setup

#eles.predecessors(criterion?)
// Everything that reaches these nodes by following incoming edges, transitively
eles.predecessors(criterion?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>

Everything that reaches these nodes by following incoming edges, transitively.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData>

the edges and nodes of the backward closure

Example

console.log(eles.predecessors().map(ele => ele.id())); // ["ab","a","bc","b"]

Example graph and handle setup

#Edge relations

Collection › Traversing › Edge relations

Find edges between collections and parallel or codirected edges.

#eles.edgesWith(others)
// The edges connecting this collection's nodes with others, in either direction
eles.edgesWith(others: Collection): Collection<NodeData, EdgeData, EdgeData>

The edges connecting this collection's nodes with others, in either direction.

Parameters
NameDescription
others: Collection

the nodes on the far side (a collection, never a selector string)

Returns Collection<NodeData, EdgeData, EdgeData>

the connecting edges

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').edgesWith(other).map(ele => ele.id())); // ["ab"]

Example graph and handle setup

#eles.edgesTo(others)
// The edges running from this collection's nodes to others — edgesWith() restricted by direction
eles.edgesTo(others: Collection): Collection<NodeData, EdgeData, EdgeData>

The edges running from this collection's nodes to others — edgesWith() restricted by direction.

Parameters
NameDescription
others: Collection

the target-side nodes

Returns Collection<NodeData, EdgeData, EdgeData>

the directed connecting edges

Example

const other = cy.getElementById('b');
console.log(cy.getElementById('a').edgesTo(other).map(ele => ele.id())); // ["ab"]

Example graph and handle setup

#eles.parallelEdges(criterion?)
// The edges sharing endpoints with these edges, in either direction — including each edge itself
eles.parallelEdges(criterion?: FilterLike<NodeData, EdgeData, EdgeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, EdgeData>

The edges sharing endpoints with these edges, in either direction — including each edge itself. These are the edges a bezier bundle fans apart.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, EdgeData, NodeData | EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, EdgeData>

the parallel edges

Example

console.log(eles.parallelEdges().map(ele => ele.id())); // ["ab","bc"]

Example graph and handle setup

#eles.codirectedEdges(criterion?)
// The parallel edges pointing the same way — same source and same target — including each edge itself
eles.codirectedEdges(criterion?: FilterLike<NodeData, EdgeData, EdgeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, EdgeData>

The parallel edges pointing the same way — same source and same target — including each edge itself.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, EdgeData, NodeData | EdgeData>?

an optional query object or predicate to filter the result

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, EdgeData>

the codirected edges

Example

console.log(eles.codirectedEdges().map(ele => ele.id())); // ["ab","bc"]

Example graph and handle setup

#Connected components

Collection › Traversing › Connected components

Split the graph into connected components.

#eles.components(root?)
// Connected components within this collection (undirected), each as a collection of the reached nodes plus the collection's edges internal to that component
eles.components(root?: Collection | null): Collection<NodeData, EdgeData>[]

Connected components within this collection (undirected), each as a collection of the reached nodes plus the collection's edges internal to that component.

Parameters
NameDescription
root: Collection | null?

restricts the seed nodes; omit to seed from every node

Returns Collection<NodeData, EdgeData>[]

one collection per component

Example

console.log(eles.components().length); // 1

Example graph and handle setup

Also spelled eles.componentsOf.

#ele.component()
// The whole-graph connected component containing the first element
ele.component(): Collection<NodeData, EdgeData>

The whole-graph connected component containing the first element.

Returns Collection<NodeData, EdgeData>

the component as nodes and their connecting edges, computed over the whole graph rather than within this collection; an empty collection when this one is empty

Example

console.log(eles.component().map(ele => ele.id())); // ["a","b","c","ab","bc"]

Example graph and handle setup

#Compound nodes

Collection › Compound nodes

Traverse compound containment and manage collapse state.

#eles.parent(criterion?)

// Immediate parents of every node in the collection (unique)
eles.parent(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

Immediate parents of every node in the collection (unique). Always returns a collection and applies the optional filter.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the immediate parents

Example

cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
cy.getElementById('b').move({ parent: 'parent' });
console.log(cy.getElementById('a').parent().map(node => node.id()).sort()); // ["parent"]

Example graph and handle setup

#eles.parents(criterion?)

// All ancestors, level by level: every nearest parent first, then the grandparents, and so on
eles.parents(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

All ancestors, level by level: every nearest parent first, then the grandparents, and so on.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the ancestors, nearest first

Example

cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
cy.getElementById('b').move({ parent: 'parent' });
console.log(cy.getElementById('a').parents().map(node => node.id()).sort()); // ["parent"]

Example graph and handle setup

Also spelled eles.ancestors.

#eles.children(criterion?)

// Direct children of every node, in link order per parent
eles.children(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

Direct children of every node, in link order per parent.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the children

Example

cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
cy.getElementById('b').move({ parent: 'parent' });
console.log(cy.getElementById('parent').children().map(node => node.id()).sort()); // ["a","b"]

Example graph and handle setup

#eles.descendants(criterion?)

// The subtree below every node in pre-order, excluding the nodes themselves
eles.descendants(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

The subtree below every node in pre-order, excluding the nodes themselves.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the descendants

Example

cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
cy.getElementById('b').move({ parent: 'parent' });
console.log(cy.getElementById('parent').descendants().map(node => node.id()).sort()); // ["a","b"]

Example graph and handle setup

#eles.collapse(timing?)

// Scale each compound parent’s descendants into a miniature around the parent’s current centre
eles.collapse(timing?: Pick<AnimateOptions, 'duration' | 'easing'>): this

Scale each compound parent’s descendants into a miniature around the parent’s current centre. Pass { duration, easing } to animate the scale; without options, the operation is immediate. The original nodes, edges and explicit visibility state remain unchanged.

Parameters
NameDescription
timing: Pick<AnimateOptions, 'duration' | 'easing'>?

optional animation duration and easing

Returns this

this collection, for chaining

Example

const parent = cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
parent.collapse();
console.log(parent.collapsed()); // true

Example graph and handle setup

#eles.expand(timing?)

// Restore each collapsed compound parent’s descendants by reversing its currently applied scale around the parent’s current centre
eles.expand(timing?: Pick<AnimateOptions, 'duration' | 'easing'>): this

Restore each collapsed compound parent’s descendants by reversing its currently applied scale around the parent’s current centre. Pass { duration, easing } to animate the restoration; without options, the operation is immediate.

Parameters
NameDescription
timing: Pick<AnimateOptions, 'duration' | 'easing'>?

optional animation duration and easing

Returns this

this collection, for chaining

Example

const parent = cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
parent.collapse();
parent.expand();
console.log(parent.collapsed()); // false

Example graph and handle setup

#eles.siblings(criterion?)

// Nodes sharing a parent with the collection's nodes, excluding them; orphans are nobody's siblings
eles.siblings(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

Nodes sharing a parent with the collection's nodes, excluding them; orphans are nobody's siblings.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the siblings

Example

cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
cy.getElementById('b').move({ parent: 'parent' });
console.log(cy.getElementById('a').siblings().map(node => node.id()).sort()); // ["b"]

Example graph and handle setup

#eles.orphans(criterion?)

// The collection's nodes without a parent
eles.orphans(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

The collection's nodes without a parent.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the parentless nodes

Example

console.log(eles.orphans().map(ele => ele.id())); // ["a","b","c"]

Example graph and handle setup

#eles.nonorphans(criterion?)

// The collection's nodes that have a parent
eles.nonorphans(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

The collection's nodes that have a parent.

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the parented nodes

Example

cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
cy.getElementById('b').move({ parent: 'parent' });
console.log(cy.getElementById('a').nonorphans().map(node => node.id()).sort()); // ["a"]

Example graph and handle setup

#eles.commonAncestors(criterion?)

// Ancestors common to every element, closest first (an edge in the collection has no ancestors, so it empties the result)
eles.commonAncestors(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>

Ancestors common to every element, closest first (an edge in the collection has no ancestors, so it empties the result).

Parameters
NameDescription
criterion: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>?

an optional query object or predicate applied to the result, exactly as filter() takes it

Fields of criterion
NameDescription
group: GroupName?

restrict to one group

selected: boolean?

require the element (not) to be selected

selectable: boolean?

whether the element may be selected by the user

locked: boolean?

whether the element is locked in place

grabbed: boolean?

whether the user is dragging the element

grabbable: boolean?

whether the element may be dragged

active: boolean?

whether the element is under an active press

hovered: boolean?

whether the pointer is over the element

emphasized: boolean?

whether the element is in the current emphasis (* cy.emphasize())

parent: boolean?

structural (nodes only): has at least one child

childless: boolean?

structural (nodes only): has no children — exactly { parent: false }

child: boolean?

structural (nodes only): has a parent

orphan: boolean?

structural (nodes only): has no parent — exactly { child: false }

collapsed: boolean?

whether this compound parent is in collapsed miniature state (nodes only)

data: QueryData<Data>?

data-sidecar conditions per key; a bare value means equality. Typed, the keys are the queried elements' fields.

Returns Collection<NodeData, EdgeData, NodeData>

the shared ancestors, closest first

Example

cy.add({ data: { id: 'parent' } });
cy.getElementById('a').move({ parent: 'parent' });
cy.getElementById('b').move({ parent: 'parent' });
console.log(cy.getElementById('a').commonAncestors().map(node => node.id()).sort()); // ["parent"]

Example graph and handle setup

#ele.isParent()

// Whether the first element is a node with at least one child
ele.isParent(): boolean

Whether the first element is a node with at least one child.

Returns boolean

true for a parent node; false for edges and for removed elements, which are nodes of no hierarchy

Example

console.log(eles.isParent()); // false

Example graph and handle setup

#ele.isChildless()

// Whether the first element is a node with no children
ele.isChildless(): boolean

Whether the first element is a node with no children.

Returns boolean

true for a node with no children; false for edges, so it is not the plain negation of isParent()

Example

console.log(eles.isChildless()); // true

Example graph and handle setup

#ele.isChild()

// Whether the first element is a node with a parent
ele.isChild(): boolean

Whether the first element is a node with a parent.

Returns boolean

true for a node with a parent; false for edges and removed elements

Example

console.log(eles.isChild()); // false

Example graph and handle setup

#ele.collapsed()

// Whether the first live node is a collapsed compound parent
ele.collapsed(): boolean

Whether the first live node is a collapsed compound parent.

Returns boolean

true from collapse start until expansion completes; false for leaves, edges and removed elements

Example

console.log(eles.collapsed()); // false

Example graph and handle setup

#ele.insideCollapsed()

// Whether the first live node has a collapsed strict ancestor
ele.insideCollapsed(): boolean

Whether the first live node has a collapsed strict ancestor. The collapsed parent itself answers false.

Returns boolean

true when the node is a descendant of a collapsed parent

Example

console.log(eles.insideCollapsed()); // false

Example graph and handle setup

#ele.isOrphan()

// Whether the first element is a node without a parent
ele.isOrphan(): boolean

Whether the first element is a node without a parent.

Returns boolean

true for a node with no parent; false for edges, so it is not the plain negation of isChild()

Example

console.log(eles.isOrphan()); // true

Example graph and handle setup

#Algorithms

Collection › Algorithms

Choose graph algorithms by task; read each executor and cancellation contract.

#Graph algorithms

The algorithm family includes synchronous searches and paths, spanning and cut algorithms, centrality measures and clustering, plus larger async whole-graph algorithms. For example:

const result = cy.elements().breadthFirstSearch({
roots: cy.getElementById('a'),
directed: true,
visit(node, edge, previous, index, depth) {
if (node.id() === 'goal') return true;
},
});
console.log(result.found, result.path);

The roots argument is a collection, not a selector string. The callback receives the visited node, incoming edge, node it came from, visit index and depth; returning true stops and records that node as found, while false stops without a found node. Search callbacks and result fields are documented on breadthFirstSearch() and depthFirstSearch(). Async whole-graph algorithms return a promise augmented with cancel(). Cancelling a pending run rejects that promise with CancelledError; a synchronous CPU run may already have settled before cancel() is called. Executor availability and failures are specific to each method. The API reference describes the full options, result shapes and errors.

Call forms use ele. when reading the first element and eles. for collection operations and writes. A single element is still a collection, so these methods can be called on either kind of handle.

#Spanning

Collection › Algorithms › Spanning

Compute a spanning forest.

#eles.kruskal(weight?)
// Build a minimum spanning forest of this collection, treating its edges as undirected
eles.kruskal(weight?: WeightFn): Collection<NodeData, EdgeData>

Build a minimum spanning forest of this collection, treating its edges as undirected. Equal-weight edges retain collection order. Disconnected input produces one tree per connected component.

Parameters
NameDescription
weight: WeightFn?

(edge) => number; defaults to unit weights

Returns Collection<NodeData, EdgeData>

a collection containing all input nodes and the accepted forest edges, in acceptance order

Example

const forest = eles.kruskal(edge => edge.data('weight'));
console.log(forest.edges().length); // 2

Example graph and handle setup

#Connectivity and Eulerian paths

Collection › Algorithms › Connectivity and Eulerian paths

Find strong or biconnected components and Eulerian traversals.

#eles.tarjanStronglyConnected()
// Partition this collection's directed subgraph into strongly connected components
eles.tarjanStronglyConnected(): TarjanStronglyConnectedResult

Partition this collection's directed subgraph into strongly connected components. Traversal follows edge direction; self-loops do not join otherwise separate nodes. The implementation is iterative, so deep graphs do not consume the JavaScript call stack.

Returns TarjanStronglyConnectedResult

{ components, cut }: each component collection contains its nodes and internal edges; cut contains edges between components

Example

console.log(eles.tarjanStronglyConnected().components.length); // 3

Example graph and handle setup

Also spelled eles.tsc, eles.tscc, eles.tarjanStronglyConnectedComponents.

#eles.hopcroftTarjanBiconnected()
// Find undirected biconnected components and articulation points in this collection's subgraph
eles.hopcroftTarjanBiconnected(): HopcroftTarjanBiconnectedResult

Find undirected biconnected components and articulation points in this collection's subgraph. The component partition follows the parent-edge rule: all edges back to the DFS parent are skipped, including parallel edges.

Returns HopcroftTarjanBiconnectedResult

{ components, cut }: each component is a collection of its nodes and edges, and cut contains articulation-point nodes. Each component also absorbs subgraph edges incident to its non-cut nodes, as this implementation defines its component sets.

Example

console.log(eles.hopcroftTarjanBiconnected().cut.map(node => node.id())); // ['b']

Example graph and handle setup

Also spelled eles.htbc, eles.htb, eles.hopcroftTarjanBiconnectedComponents.

#eles.hierholzer(rootOrOptions?, directed?)
// Find an Eulerian trail or circuit over this collection's edges
eles.hierholzer(rootOrOptions?: HierholzerOptions | Collection<any, any, any> | undefined, directed?: boolean | undefined): HierholzerResult

Find an Eulerian trail or circuit over this collection's edges. The directed mode checks directed degree balance; the default treats edges as undirected. A requested root must be a valid starting node for the trail.

Parameters
NameDescription
rootOrOptions: HierholzerOptions | Collection<any, any, any> | undefined?

Starting node or an options object; omit to choose an eligible node.

directed: boolean | undefined?

True to follow outgoing edges only; defaults to false.

Returns HierholzerResult

{ found, trail }; trail is undefined when no trail exists. Collections are sets, so a node visited more than once appears only once in the trail collection.

Example

const result = eles.hierholzer({ root: cy.getElementById('a'), directed: false });
console.log(result.found); // true

Example graph and handle setup

Throws

if a supplied root is a selector string

#Cut

Collection › Algorithms › Cut

Compute graph cuts.

#eles.kargerStein()
// Estimate an undirected global minimum cut with the randomized Karger–Stein contraction algorithm
eles.kargerStein(): KargerSteinResult

Estimate an undirected global minimum cut with the randomized Karger–Stein contraction algorithm. Connected input is required for its guarantee. Random choices mean repeated runs may produce different partitions; the minimum-cut result is probabilistic.

Returns KargerSteinResult

{ cut, components, partition1, partition2 }; cut contains crossing edges and the two partitions contain the corresponding nodes

Example

// The exact cut can vary; this path graph's minimum cut has one edge.
console.log(eles.kargerStein().cut.edges().length); // 1

Example graph and handle setup

Throws

if fewer than two nodes are present or a contraction reaches a graph with no edges

#Centrality

Collection › Algorithms › Centrality

Measure node importance under each algorithm’s definition.

#eles.pageRank(options?)
// PageRank over the subgraph
eles.pageRank(options?: PageRankOptions): AlgoRun<PageRankResult>

PageRank over the subgraph. Undirected by default — each edge is walked both ways, as NetworkX and igraph do — and directed: true follows source → target only. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the power method runs; 'cpu' is the reproducible reference.

Parameters
NameDescription
options: PageRankOptions?

{ dampingFactor, precision, iterations, weight, directed, executor }; dampingFactor is the textbook α in (0, 1], default 0.85

Fields of options
NameDescription
dampingFactor: number?

the probability of following an out-edge rather than teleporting — the textbook α, in (0, 1] (default 0.85)

precision: number?
iterations: number?
weight: WeightFn?
directed: boolean?

walk edges source → target only (default false: an undirected run walks each edge both ways, as NetworkX and igraph do)

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<PageRankResult>

a promise of { rank }, a per-node accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.pageRank({ executor: 'cpu' });
const result = await run;
console.log(result.rank(cy.getElementById('c')) > 0); // true

Example graph and handle setup

Throws

if executor or dampingFactor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.degreeCentrality(options?)
// Compute Opsahl's generalized degree for one node in this collection
eles.degreeCentrality(options?: DegreeCentralityOptions): DegreeCentralityResult

Compute Opsahl's generalized degree for one node in this collection. alpha interpolates between counting edges (0) and summing their weights (1); intermediate values combine both. Directed results separate incoming and outgoing degree.

Parameters
NameDescription
options: DegreeCentralityOptions?

{ root, weight, alpha, directed }; root is required, weight(edge) defaults to 1, alpha defaults to 0, and directed defaults to false

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
alpha: number?

0 = count degree, 1 = weight sum (Opsahl's generalized degree)

normalization: 'max' | 'size'?

read by degreeCentralityNormalized only: 'max' (default) divides by the largest degree, 'size' by n − 1 — NetworkX's degree_centrality and igraph's normalized = TRUE

Returns DegreeCentralityResult

{ degree }, or { indegree, outdegree } when directed

Example

const result = eles.degreeCentrality({ root: cy.getElementById('b') });
console.log(result.degree); // 2

Example graph and handle setup

Throws

if root is missing or does not contain a node

Also spelled eles.dc.

#eles.degreeCentralityNormalized(options?)
// Compute each node's Opsahl generalized degree and normalize against the maximum in this collection (default) or, under normalization: 'size', against n − 1 — NetworkX's degreecentrality and igraph's normalized = TRUE (a lone node scores 1, as in NetworkX)
eles.degreeCentralityNormalized(options?: DegreeCentralityOptions): DegreeCentralityNormalizedResult

Compute each node's Opsahl generalized degree and normalize against the maximum in this collection (default) or, under normalization: 'size', against n − 1 — NetworkX's degree_centrality and igraph's normalized = TRUE (a lone node scores 1, as in NetworkX). Directed in- and out-degree are normalized independently. Nodes outside the collection's captured subgraph read as zero.

Parameters
NameDescription
options: DegreeCentralityOptions?

{ weight, alpha, directed, normalization }; the shared option type also allows root, which this all-node method ignores. weight(edge) defaults to 1, alpha defaults to 0, directed defaults to false and normalization to 'max'

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
alpha: number?

0 = count degree, 1 = weight sum (Opsahl's generalized degree)

normalization: 'max' | 'size'?

read by degreeCentralityNormalized only: 'max' (default) divides by the largest degree, 'size' by n − 1 — NetworkX's degree_centrality and igraph's normalized = TRUE

Returns DegreeCentralityNormalizedResult

a degree(node) accessor, or indegree(node) and outdegree(node) accessors when directed. Each divides by its corresponding maximum or by n − 1; under 'max' results are in [0, 1] when weights and alpha produce nonnegative finite degrees. These numeric constraints are not validated.

Example

const result = eles.degreeCentralityNormalized();
console.log(result.degree(cy.getElementById('b'))); // 1

Example graph and handle setup

Throws

if normalization is neither 'max' nor 'size'

Also spelled eles.dcn, eles.degreeCentralityNormalised.

#eles.closenessCentrality(options?)
// Closeness centrality of one node — how near it is, by shortest path, to the rest of the collection
eles.closenessCentrality(options?: ClosenessCentralityOptions): number

Closeness centrality of one node — how near it is, by shortest path, to the rest of the collection. Harmonic (default): Σ 1/d, an unreachable node contributing 0. harmonic: false: the classic (n − 1)/Σd, and over r reachable nodes the Wasserman–Faust (r/Σd)·(r/(n − 1)) — NetworkX's definition. Directed runs sum distances from the node (direction: 'out', default, as R igraph and graph-tool) or to it ('in', as NetworkX and Neo4j GDS).

Parameters
NameDescription
options: ClosenessCentralityOptions?

{ root, weight, directed, direction, harmonic }

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
direction: 'out' | 'in'?

which distances a directed run sums: 'out' (default) from the node to the others — R igraph's mode = "out" and graph-tool's — or 'in', from the others to the node — NetworkX's, Neo4j GDS's and Boldi–Vigna's. Ignored when undirected.

harmonic: boolean?

Σ 1/d (default, tolerates disconnection), or the classic (n − 1)/Σd with the Wasserman–Faust correction: over the r nodes reachable, (r/Σd)·(r/(n − 1)), 0 when none is

normalization: 'max' | 'size'?

read by closenessCentralityNormalized only: 'max' (default) divides by the largest score; 'size' divides a harmonic score by n − 1 (igraph's and graph-tool's normalized harmonic centrality) and leaves a classic one as is, (n − 1) already being in its formula

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). Read by the whole-collection closenessCentralityNormalized only — the single-root closenessCentrality is a cheap Dijkstra walk and stays synchronous on the CPU. Unweighted runs walk a BFS per source on either executor (72.3); weighted runs relax Floyd–Warshall.

Returns number

the closeness score

Example

console.log(eles.closenessCentrality({ root: cy.getElementById('b') })); // 2

Example graph and handle setup

Throws

if root is not a node of the collection, or direction is neither 'out' nor 'in'

Also spelled eles.cc.

#eles.closenessCentralityNormalized(options?)
// Closeness centrality for every node, normalized to [0, 1]
eles.closenessCentralityNormalized(options?: ClosenessCentralityOptions): AlgoRun<ClosenessCentralityNormalizedResult>

Closeness centrality for every node, normalized to [0, 1]. Async: the whole-collection form is the all-pairs tier, so like floydWarshall it returns a promise and executor ('cpu' | 'gpu' | 'workers' | 'auto', default 'auto') picks where it runs; 'cpu' is the reproducible reference. Unweighted runs walk a BFS per source, O(n·(n+E)) — on the worker pool too (one source range per worker, bit-identical to 'cpu'; under 'auto' a sparse graph takes the pool first from 512 nodes, using workers for sparse graphs, and a dense one the GPU first); weighted runs relax Floyd–Warshall, O(n³), and take the offload lane (one pool worker). The single-root closenessCentrality stays synchronous.

Each score is closenessCentrality's for that node (the same harmonic and direction), divided by the largest.

normalization: 'size' divides a harmonic score by n − 1 instead, igraph's and graph-tool's normalized harmonic centrality, and leaves a classic score, which already carries n − 1, as is.

Parameters
NameDescription
options: ClosenessCentralityOptions?

{ weight, directed, direction, harmonic, normalization, executor }

Fields of options
NameDescription
root: Collection | null?
weight: WeightFn?
directed: boolean?
direction: 'out' | 'in'?

which distances a directed run sums: 'out' (default) from the node to the others — R igraph's mode = "out" and graph-tool's — or 'in', from the others to the node — NetworkX's, Neo4j GDS's and Boldi–Vigna's. Ignored when undirected.

harmonic: boolean?

Σ 1/d (default, tolerates disconnection), or the classic (n − 1)/Σd with the Wasserman–Faust correction: over the r nodes reachable, (r/Σd)·(r/(n − 1)), 0 when none is

normalization: 'max' | 'size'?

read by closenessCentralityNormalized only: 'max' (default) divides by the largest score; 'size' divides a harmonic score by n − 1 (igraph's and graph-tool's normalized harmonic centrality) and leaves a classic one as is, (n − 1) already being in its formula

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). Read by the whole-collection closenessCentralityNormalized only — the single-root closenessCentrality is a cheap Dijkstra walk and stays synchronous on the CPU. Unweighted runs walk a BFS per source on either executor (72.3); weighted runs relax Floyd–Warshall.

Returns AlgoRun<ClosenessCentralityNormalizedResult>

a promise of a closeness accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.closenessCentralityNormalized({ executor: 'cpu' });
const result = await run;
console.log(result.closeness(cy.getElementById('b')) > 0); // true

Example graph and handle setup

Throws

if executor, direction or normalization is invalid; rejects if executor: 'gpu' or 'workers' is unavailable in this environment, or 'workers' is asked of a weighted run

Also spelled eles.ccn, eles.closenessCentralityNormalised.

#eles.betweennessCentrality(options?)
// Betweenness centrality — how often each node lies on shortest paths between other pairs: the sum over pairs s ≠ v ≠ t of the share of shortest s–t paths through v, each unordered pair counted once when undirected (Freeman's definition, NetworkX's and igraph's unnormalized score)
eles.betweennessCentrality(options?: BetweennessCentralityOptions): AlgoRun<BetweennessCentralityResult>

Betweenness centrality — how often each node lies on shortest paths between other pairs: the sum over pairs s ≠ v ≠ t of the share of shortest s–t paths through v, each unordered pair counted once when undirected (Freeman's definition, NetworkX's and igraph's unnormalized score). betweennessNormalized divides by the largest score. Async: returns a promise, and executor ('cpu' | 'gpu' | 'workers' | 'auto', default 'auto') picks where the Brandes sweep runs. Weighted runs have no GPU path: 'auto' takes the worker pool (one source range per worker, f64-tight to 'cpu' and bit-stable across pool sizes) from 128 nodes and an explicit 'gpu' rejects; unweighted runs keep the GPU first under 'auto', then the pool from 256 nodes where no adapter fits.

betweennessNormalized divides by the largest score, or under normalization: 'size' by the pairs a node can sit between — (n − 1)(n − 2)/2 undirected, (n − 1)(n − 2) directed — as NetworkX's normalized=True and igraph's normalized = TRUE.

Parameters
NameDescription
options: BetweennessCentralityOptions?

{ weight, directed, normalization, executor }

Fields of options
NameDescription
weight: WeightFn | null?
directed: boolean?
normalization: 'max' | 'size'?

how betweennessNormalized scales: 'max' (default) divides by the largest score, 'size' by the number of pairs a node can sit between — (n − 1)(n − 2)/2 undirected, (n − 1)(n − 2) directed — as NetworkX's normalized=True and igraph's normalized = TRUE do

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). Weighted runs have no GPU path: 'auto' uses workers from 128 nodes when available, and an explicit 'gpu' rejects. Unweighted runs prefer a suitable GPU under 'auto', then workers where no adapter fits.

Returns AlgoRun<BetweennessCentralityResult>

a promise of the { betweenness, betweennessNormalized } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.betweennessCentrality({ executor: 'cpu' });
const result = await run;
console.log(result.betweenness(cy.getElementById('b')) > 0); // true

Example graph and handle setup

Throws

if executor or normalization is invalid; rejects if executor: 'gpu' is unavailable or the run is weighted

Also spelled eles.bc.

#eles.katzCentrality(options?)
// Katz centrality — attenuated walk counting, where a node is central when many short walks end at it and a walk of length k is worth alphaᵏ
eles.katzCentrality(options?: KatzCentralityOptions): AlgoRun<KatzCentralityResult>

Katz centrality — attenuated walk counting, where a node is central when many short walks end at it and a walk of length k is worth alphaᵏ. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the iteration runs; like pageRank, 'auto' always uses the sparse CPU iteration and the GPU path serves an explicit 'gpu'. katzNormalized divides by the largest score, or by the scores' Euclidean norm under normalization: 'l2' — NetworkX's normalized=True.

Parameters
NameDescription
options: KatzCentralityOptions?

{ alpha, beta, maxIterations, tolerance, directed, weight, normalization, executor }

Fields of options
NameDescription
alpha: number?

the walk attenuation per step (default 0.1); must be positive, and under 1/λ_max of the adjacency for the iteration to converge

beta: number?

the baseline every node starts each step with (default 1)

maxIterations: number?

iteration cap when the tolerance is never met (default 200)

tolerance: number?

stop once Σ|Δx| < n · tolerance (default 1e-6)

directed: boolean?

count incoming walks only

weight: WeightFn?
normalization: 'max' | 'l2'?

how katzNormalized scales: 'max' (default) divides by the largest score, 'l2' by the scores' Euclidean norm — NetworkX's katz_centrality(normalized=True)

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). Like pageRank, 'auto' stays on the sparse CPU iteration at every measured size (KATZ_GPU_MIN_N); the GPU path serves an explicit 'gpu'.

Returns AlgoRun<KatzCentralityResult>

a promise of the { katz, katzNormalized } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.katzCentrality({ executor: 'cpu' });
const result = await run;
console.log(result.katz(cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, alpha, beta or normalization is invalid; rejects if executor: 'gpu' is unavailable in this environment

#Similarity, diffusion and resistance

Collection › Algorithms › Similarity, diffusion and resistance

Compare neighbourhoods and compute diffusion, walks or resistance.

#eles.neighborhoodSimilarity(options?)
// Neighborhood similarity — pairwise Jaccard, cosine or overlap coefficients over neighbor sets (deduped; loops excluded; directed: true compares out-neighborhoods)
eles.neighborhoodSimilarity(options?: NeighborhoodSimilarityOptions): AlgoRun<NeighborhoodSimilarityResult>

Neighborhood similarity — pairwise Jaccard, cosine or overlap coefficients over neighbor sets (deduped; loops excluded; directed: true compares out-neighborhoods). The result is all-pairs, so it holds O(n²) counts like floydWarshall. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto') picks where the shared-neighbor counts are computed — under 'auto' the GPU's A·Aᵀ matmul is used only on graphs dense enough to beat the CPU's wedge walk (a mean degree of 64).

Parameters
NameDescription
options: NeighborhoodSimilarityOptions?

{ metric, directed, executor }

Fields of options
NameDescription
metric: SimilarityMetric?

the normalization (default 'jaccard')

directed: boolean?

compare out-neighborhoods instead of undirected ones

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). 'auto' routes to the GPU only on graphs dense enough that the O(n³) matmul beats the CPU's O(n² + Σ deg²) wedge walk.

Returns AlgoRun<NeighborhoodSimilarityResult>

a promise of the { similarity } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.neighborhoodSimilarity({ executor: 'cpu' });
const result = await run;
console.log(result.similarity(cy.getElementById('a'), cy.getElementById('a'))); // 1

Example graph and handle setup

Throws

if executor or metric is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.simRank(options?)
// SimRank — "two nodes are similar when their neighbors are similar", the Jeh–Widom recursive fixed point, iterated as dense products S′ = C·Q·S·Qᵀ
eles.simRank(options?: SimRankOptions): AlgoRun<SimRankResult>

SimRank — "two nodes are similar when their neighbors are similar", the Jeh–Widom recursive fixed point, iterated as dense products S′ = C·Q·S·Qᵀ. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the iteration runs — under 'auto' the GPU from 256 nodes at any density. The undirected default compares all neighbors; directed: true compares the classic in-neighborhoods. All-pairs (O(n²) memory).

Parameters
NameDescription
options: SimRankOptions?

{ dampingFactor, maxIterations, tolerance, directed, executor }

Fields of options
NameDescription
dampingFactor: number?

the decay per neighborhood step (default 0.8); must sit in (0, 1)

maxIterations: number?

iteration cap when the tolerance is never met (default 50)

tolerance: number?

stop once max |Δs| ≤ tolerance (default 1e-4)

directed: boolean?

compare in-neighborhoods (the classic form) instead of undirected ones

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). 'auto' takes the GPU from GPU_MIN_N nodes at any density (72.6: the products beat the per-pair CPU iteration everywhere).

Returns AlgoRun<SimRankResult>

a promise of the { similarity } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.simRank({ executor: 'cpu' });
const result = await run;
console.log(result.similarity(cy.getElementById('a'), cy.getElementById('a'))); // 1

Example graph and handle setup

Throws

if executor or dampingFactor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.randomWalkWithRestart(options?)
// Random walk with restart — network propagation from a seeds collection: a walker follows edges with probability 1−c and restarts at the seeds with probability c, and the stationary distribution scores every node by proximity to the seeds
eles.randomWalkWithRestart(options?: RandomWalkWithRestartOptions): AlgoRun<RandomWalkWithRestartResult>

Random walk with restart — network propagation from a seeds collection: a walker follows edges with probability 1−c and restarts at the seeds with probability c, and the stationary distribution scores every node by proximity to the seeds. Async; the vector iteration is O(E) per step on the CPU, so there is no GPU path — an explicit executor: 'gpu' rejects and points at randomWalkWithRestartProximity. A node with no out-edges sends the walker back to the seeds (dangling: 'restart', default — NetworkX's personalised PageRank), so scores sum to 1; dangling: 'absorb' ends the walk there instead, and scores can sum below 1.

Parameters
NameDescription
options: RandomWalkWithRestartOptions?

{ seeds, restartProbability, maxIterations, tolerance, directed, weight, dangling, executor }

Fields of options
NameDescription
seeds: Collection | null?

the nodes the walk restarts at (required for the seed form)

restartProbability: number?

the restart probability c (default 0.15); must sit in (0, 1)

maxIterations: number?

iteration cap when the tolerance is never met (default 200)

tolerance: number?

stop once the L1 step drops under tolerance (default 1e-6) — per column, for the proximity form

directed: boolean?

walk out-edges only

weight: WeightFn?
dangling: 'restart' | 'absorb'?

where a walker at a node with no out-edges goes: 'restart' (default) back to the seeds, as NetworkX's personalised PageRank does, so scores sum to 1; 'absorb' nowhere — the walk ends there and its mass is lost

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). The seed form has no GPU path; the proximity form takes the GPU from GPU_MIN_N nodes at any density (72.6).

Returns AlgoRun<RandomWalkWithRestartResult>

a promise of the { score } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.randomWalkWithRestart({ seeds: cy.getElementById('a'), executor: 'cpu' });
const result = await run;
console.log(result.score(cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, restartProbability or dangling is invalid, or if seeds holds no node of the collection

#eles.randomWalkWithRestartProximity(options?)
// All-pairs random-walk-with-restart proximity — the full matrix S = c·(I − (1−c)·W)⁻¹, whose column s is the walk restarting at s
eles.randomWalkWithRestartProximity(options?: RandomWalkWithRestartOptions): AlgoRun<RandomWalkWithRestartProximityResult>

All-pairs random-walk-with-restart proximity — the full matrix S = c·(I − (1−c)·W)⁻¹, whose column s is the walk restarting at s. Async: executor ('cpu' | 'gpu' | 'workers' | 'auto', default 'auto') picks between one sparse solve per column on the CPU, the same solves spread over the worker pool (matching 'cpu') and the dense Neumann iteration on the GPU — under 'auto' the GPU from 256 nodes at any density, else the pool from 128. All-pairs (O(n²) memory). dangling is the seed form's: dead ends restart at the column's node by default, or absorb.

Parameters
NameDescription
options: RandomWalkWithRestartOptions?

{ restartProbability, maxIterations, tolerance, directed, weight, dangling, executor }

Fields of options
NameDescription
seeds: Collection | null?

the nodes the walk restarts at (required for the seed form)

restartProbability: number?

the restart probability c (default 0.15); must sit in (0, 1)

maxIterations: number?

iteration cap when the tolerance is never met (default 200)

tolerance: number?

stop once the L1 step drops under tolerance (default 1e-6) — per column, for the proximity form

directed: boolean?

walk out-edges only

weight: WeightFn?
dangling: 'restart' | 'absorb'?

where a walker at a node with no out-edges goes: 'restart' (default) back to the seeds, as NetworkX's personalised PageRank does, so scores sum to 1; 'absorb' nowhere — the walk ends there and its mass is lost

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). The seed form has no GPU path; the proximity form takes the GPU from GPU_MIN_N nodes at any density (72.6).

Returns AlgoRun<RandomWalkWithRestartProximityResult>

a promise of the { proximity } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.randomWalkWithRestartProximity({ seeds: cy.getElementById('a'), executor: 'cpu' });
const result = await run;
console.log(result.proximity(cy.getElementById('a'), cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, restartProbability or dangling is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.heatDiffusion(options?)
// Heat diffusion from a seeds collection: unit heat spread over the seeds flows along edges for time, through the kernel exp(−t·L) of the weighted Laplacian
eles.heatDiffusion(options?: HeatDiffusionOptions): AlgoRun<HeatDiffusionResult>

Heat diffusion from a seeds collection: unit heat spread over the seeds flows along edges for time, through the kernel exp(−t·L) of the weighted Laplacian. Total heat is conserved under the default laplacian: 'combinatorial'; 'normalized' diffuses over I − D^{-½}AD^{-½} instead, whose spectrum is bounded whatever the degrees — hubs neither hoard nor flood — at the price of conservation. Async; the vector form is O(E) per series term on the CPU, so there is no GPU path — an explicit executor: 'gpu' rejects and points at heatKernel. Edges are read undirected with positive weights.

Parameters
NameDescription
options: HeatDiffusionOptions?

{ seeds, time, weight, laplacian, executor }

Fields of options
NameDescription
seeds: Collection | null?

the nodes the heat starts on (required for the seed form)

time: number?

how long the heat flows (default 0.1); must be positive

weight: WeightFn?
laplacian: HeatLaplacian?

which Laplacian drives the diffusion (default 'combinatorial', L = D − A, heat-conserving); 'normalized' is I − D^{-½}AD^{-½}, whose spectrum is bounded by 2 so the scaling exponent depends on time alone — heat is then not conserved

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). The seed form has no GPU path; the kernel form takes the GPU from GPU_MIN_N nodes at any density (72.6).

Returns AlgoRun<HeatDiffusionResult>

a promise of the { score } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.heatDiffusion({ seeds: cy.getElementById('a'), executor: 'cpu' });
const result = await run;
console.log(result.score(cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, time or laplacian is invalid, if seeds holds no node of the collection, or if an edge weight is not positive

#eles.heatKernel(options?)
// The all-pairs heat kernel exp(−t·L) — heat(from, to) is the heat at to after unit heat starts at from (symmetric)
eles.heatKernel(options?: HeatDiffusionOptions): AlgoRun<HeatKernelResult>

The all-pairs heat kernel exp(−t·L) — heat(from, to) is the heat at to after unit heat starts at from (symmetric). Async: executor ('cpu' | 'gpu' | 'workers' | 'auto', default 'auto') picks between per-column sparse series on the CPU, the same columns spread over the worker pool (bit-identical to 'cpu') and the dense scaling-and-squaring chain on the GPU — under 'auto' the GPU from 256 nodes at any density, else the pool from 256. laplacian ('combinatorial' | 'normalized', default 'combinatorial') picks L = D − A or I − D^{-½}AD^{-½}. All-pairs (O(n²) memory).

Parameters
NameDescription
options: HeatDiffusionOptions?

{ time, weight, laplacian, executor }

Fields of options
NameDescription
seeds: Collection | null?

the nodes the heat starts on (required for the seed form)

time: number?

how long the heat flows (default 0.1); must be positive

weight: WeightFn?
laplacian: HeatLaplacian?

which Laplacian drives the diffusion (default 'combinatorial', L = D − A, heat-conserving); 'normalized' is I − D^{-½}AD^{-½}, whose spectrum is bounded by 2 so the scaling exponent depends on time alone — heat is then not conserved

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). The seed form has no GPU path; the kernel form takes the GPU from GPU_MIN_N nodes at any density (72.6).

Returns AlgoRun<HeatKernelResult>

a promise of the { heat } accessor — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.heatKernel({ seeds: cy.getElementById('a'), executor: 'cpu' });
const result = await run;
console.log(result.heat(cy.getElementById('a'), cy.getElementById('a')) > 0); // true

Example graph and handle setup

Throws

if executor, time or laplacian is invalid, or if an edge weight is not positive

#eles.effectiveResistance(options?)
// Effective resistance and commute time — the graph as a resistor network
eles.effectiveResistance(options?: EffectiveResistanceOptions): AlgoRun<EffectiveResistanceResult>

Effective resistance and commute time — the graph as a resistor network. Weights are conductances by default, the convention of the papers that define the weighted measure; weightAs: 'resistance' reads them as resistances, NetworkX's default. resistance(a, b) comes from the Laplacian pseudo-inverse, commuteTime(a, b) the expected round-trip steps of the random walk (component volume × resistance). Pairs in different components answer Infinity. Async: executor ('cpu' | 'gpu' | 'auto', default 'auto') picks between dense f64 elimination on the CPU and Newton–Schulz matmul iteration on the GPU; both are O(n³), so 'auto' takes the GPU on size alone.

Parameters
NameDescription
options: EffectiveResistanceOptions?

{ weight, weightAs, executor }

Fields of options
NameDescription
weight: WeightFn?
weightAs: 'conductance' | 'resistance'?

what weight measures: 'conductance' (default, a heavier edge conducts more) or 'resistance' (a heavier edge resists more — NetworkX's invert_weight=True default)

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<EffectiveResistanceResult>

a promise of the { resistance, commuteTime } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.effectiveResistance({ executor: 'cpu' });
const result = await run;
console.log(result.resistance(cy.getElementById('a'), cy.getElementById('c')) > 0); // true

Example graph and handle setup

Throws

if executor or weightAs is invalid; rejects if an edge weight is not positive or executor: 'gpu' is unavailable

#Structural measures

Collection › Algorithms › Structural measures

Read degree and count local graph structures.

#eles.triangleCount(options?)
// Triangle counting: per-node triangle counts, local clustering coefficients, and the collection's transitivity, read over the simple undirected graph (direction ignored, parallel edges collapsed, loops excluded)
eles.triangleCount(options?: TriangleCountOptions): AlgoRun<TriangleCountResult>

Triangle counting: per-node triangle counts, local clustering coefficients, and the collection's transitivity, read over the simple undirected graph (direction ignored, parallel edges collapsed, loops excluded). Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the counting runs — under 'auto' the GPU's A²∘A matmul is used only on graphs dense enough to beat the CPU's sparse walk (a mean degree of 64).

Parameters
NameDescription
options: TriangleCountOptions?

{ executor }

Fields of options
NameDescription
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). 'auto' routes to the GPU only on graphs dense enough that the O(n³) matmul beats the CPU's O(Σ deg²) sparse walk.

Returns AlgoRun<TriangleCountResult>

a promise of { triangles, clusteringCoefficient, totalTriangles, transitivity } — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.triangleCount({ executor: 'cpu' });
const result = await run;
console.log(result.totalTriangles); // 0

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#eles.motifCensus(options?)
// The triad census — every three-node subgraph classified into the sixteen Holland–Leinhardt classes ('003' … '300'; '030T' is the feed-forward loop)
eles.motifCensus(options?: MotifCensusOptions): AlgoRun<MotifCensusResult>

The triad census — every three-node subgraph classified into the sixteen Holland–Leinhardt classes ('003' … '300'; '030T' is the feed-forward loop). The counts sum to C(n, 3). Async: executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks between sparse wedge walks on the CPU and matmul trace products on the GPU — under 'auto' the GPU only on dense graphs (a mean degree of 64). directed: false reads every edge as mutual, so only 003 / 102 / 201 / 300 (empty / one-edge / path / triangle) can be non-zero.

Parameters
NameDescription
options: MotifCensusOptions?

{ directed, executor }

Fields of options
NameDescription
directed: boolean?

read edge direction (default true — the census is a directed notion; false reads every edge as mutual, so only 003/102/201/ 300 can be non-zero)

executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto'). 'auto' routes to the GPU only on graphs dense enough that the O(n³) trace products beat the CPU's O(Σ deg²) wedge walks.

Returns AlgoRun<MotifCensusResult>

a promise of { counts } — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.motifCensus({ executor: 'cpu' });
const result = await run;
console.log(result.counts['021C']); // 1

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment

#ele.degree(includeLoops?)
// The first element's total degree, in + out, answered in O(1) off the adjacency index
ele.degree(includeLoops?: boolean): number | undefined

The first element's total degree, in + out, answered in O(1) off the adjacency index.

This is a singular accessor — it reports one node's degree, not a collection-wide figure. For the sum over the whole collection use totalDegree().

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count (each contributes 2)

Returns number | undefined

the degree, or undefined when the first element is not a live node

Example

console.log(eles.degree()); // 1

Example graph and handle setup

#ele.outdegree(includeLoops?)
// The first element's out-degree, in O(1)
ele.outdegree(includeLoops?: boolean): number | undefined

The first element's out-degree, in O(1). Singular, like degree().

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the out-degree, or undefined when not a live node

Example

console.log(eles.outdegree()); // 1

Example graph and handle setup

#ele.indegree(includeLoops?)
// The first element's in-degree, in O(1)
ele.indegree(includeLoops?: boolean): number | undefined

The first element's in-degree, in O(1). Singular, like degree().

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the in-degree, or undefined when not a live node

Example

console.log(eles.indegree()); // 0

Example graph and handle setup

#eles.minDegree(includeLoops?)
// The smallest total degree among the collection's nodes
eles.minDegree(includeLoops?: boolean): number | undefined

The smallest total degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the minimum degree, or undefined when there are no nodes

Example

console.log(eles.minDegree()); // 1

Example graph and handle setup

#eles.maxDegree(includeLoops?)
// The largest total degree among the collection's nodes
eles.maxDegree(includeLoops?: boolean): number | undefined

The largest total degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the maximum degree, or undefined when there are no nodes

Example

console.log(eles.maxDegree()); // 2

Example graph and handle setup

#eles.minIndegree(includeLoops?)
// The smallest in-degree among the collection's nodes
eles.minIndegree(includeLoops?: boolean): number | undefined

The smallest in-degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the minimum in-degree, or undefined when there are no nodes

Example

console.log(eles.minIndegree()); // 0

Example graph and handle setup

#eles.maxIndegree(includeLoops?)
// The largest in-degree among the collection's nodes
eles.maxIndegree(includeLoops?: boolean): number | undefined

The largest in-degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the maximum in-degree, or undefined when there are no nodes

Example

console.log(eles.maxIndegree()); // 1

Example graph and handle setup

#eles.minOutdegree(includeLoops?)
// The smallest out-degree among the collection's nodes
eles.minOutdegree(includeLoops?: boolean): number | undefined

The smallest out-degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the minimum out-degree, or undefined when there are no nodes

Example

console.log(eles.minOutdegree()); // 0

Example graph and handle setup

#eles.maxOutdegree(includeLoops?)
// The largest out-degree among the collection's nodes
eles.maxOutdegree(includeLoops?: boolean): number | undefined

The largest out-degree among the collection's nodes.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number | undefined

the maximum out-degree, or undefined when there are no nodes

Example

console.log(eles.maxOutdegree()); // 1

Example graph and handle setup

#eles.totalDegree(includeLoops?)
// The summed degree of every node in the collection — the whole-collection figure that degree() deliberately is not
eles.totalDegree(includeLoops?: boolean): number

The summed degree of every node in the collection — the whole-collection figure that degree() deliberately is not.

Parameters
NameDescription
includeLoops: boolean?Default: true

whether self-loops count

Returns number

the total degree (0 when there are no nodes)

Example

console.log(eles.totalDegree()); // 4

Example graph and handle setup

#Clustering

Collection › Algorithms › Clustering

Group elements using the documented distance and clustering contracts.

#eles.kMeans(options?)
// k-means clustering in attribute space
eles.kMeans(options?: KClusteringOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

k-means clustering in attribute space. Works on handles and attributes accessors rather than on graph structure.

Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker for a named distance) picks where the iteration runs; 'cpu' is the reproducible reference. A custom distance function is called inside the iteration, so it runs on the calling thread under 'cpu' and 'auto', and 'workers' rejects it.

Parameters
NameDescription
options: KClusteringOptions?

{ k, attributes, distance, maxIterations, sensitivityThreshold, executor }, with attributes as plain functions

Fields of options
NameDescription
k: number?
m: number?
sensitivityThreshold: number?
distance: DistanceMetric?
maxIterations: number?
attributes: KAttributeFn[]?
testMode: boolean?
testCentroids: number | FeatureCentroid[] | Collection[] | null?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.kMeans({ k: 2, attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment, or executor: 'workers' is given a custom distance function

#eles.kMedoids(options?)
// k-medoids clustering — like k-means, but cluster centres are actual elements, which makes it robust to outliers
eles.kMedoids(options?: KClusteringOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

k-medoids clustering — like k-means, but cluster centres are actual elements, which makes it robust to outliers. Async, with the same executor contract as kMeans.

Parameters
NameDescription
options: KClusteringOptions?

as kMeans

Fields of options
NameDescription
k: number?
m: number?
sensitivityThreshold: number?
distance: DistanceMetric?
maxIterations: number?
attributes: KAttributeFn[]?
testMode: boolean?
testCentroids: number | FeatureCentroid[] | Collection[] | null?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.kMedoids({ k: 2, attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable, if executor: 'workers' is given a custom distance function, or if k exceeds the node count

#eles.fuzzyCMeans(options?)
// Fuzzy c-means clustering: each element gets a degree of membership in every cluster rather than one hard assignment
eles.fuzzyCMeans(options?: KClusteringOptions): AlgoRun<FuzzyCMeansResult>

Fuzzy c-means clustering: each element gets a degree of membership in every cluster rather than one hard assignment. Async, with the same executor contract as kMeans.

Parameters
NameDescription
options: KClusteringOptions?

as kMeans, plus the fuzziness exponent

Fields of options
NameDescription
k: number?
m: number?
sensitivityThreshold: number?
distance: DistanceMetric?
maxIterations: number?
attributes: KAttributeFn[]?
testMode: boolean?
testCentroids: number | FeatureCentroid[] | Collection[] | null?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<FuzzyCMeansResult>

a promise of { clusters, degreeOfMembership } — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.fuzzyCMeans({ k: 2, attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.clusters.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment, or executor: 'workers' is given a custom distance function

Also spelled eles.fcm.

#eles.hierarchicalClustering(options?)
// Agglomerative hierarchical clustering
eles.hierarchicalClustering(options?: HierarchicalClusteringOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

Agglomerative hierarchical clustering. Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the distance matrix is built; the merge chain itself is sequential and runs with the reference — in-thread, or on the pool worker for a named distance and a 'min' / 'max' / 'mean' linkage. A custom distance function or a per-pair linkage consults the metric inside the run, on the calling thread, and 'workers' rejects them. Threshold mode merges every closest pair at most threshold apart, a merge at exactly threshold included, as SciPy's fcluster and R's cutree.

Parameters
NameDescription
options: HierarchicalClusteringOptions?

{ attributes, distance, linkage, mode, threshold, dendrogramDepth, executor }

Fields of options
NameDescription
distance: DistanceMetric?
linkage: string?

linkage criterion: 'min' (single), 'max' (complete), 'mean', or per-pair

mode: 'threshold' | 'dendrogram'?
threshold: number?

threshold mode merges pairs at most this far apart (default Infinity)

addDendrogram: boolean?
dendrogramDepth: number?
attributes: HierarchicalAttributeFn[]?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.hierarchicalClustering({ attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable in this environment, or executor: 'workers' is given a custom distance function or a per-pair linkage

Also spelled eles.hca.

#eles.markovClustering(options?)
// Markov clustering (MCL) — flow simulation over the graph, so unlike the attribute-space algorithms this one clusters by structure
eles.markovClustering(options?: MarkovClusteringOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

Markov clustering (MCL) — flow simulation over the graph, so unlike the attribute-space algorithms this one clusters by structure.

Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the expand/inflate iteration runs; 'cpu' is the reproducible reference. maxIterations defaults to 100 (as Python markov_clustering and R MCL), and pruneThreshold (default 0) drops each inflated matrix's entries under it, keeping each column's largest, as markov_clustering's pruning_threshold does.

Parameters
NameDescription
options: MarkovClusteringOptions?

{ attributes, expandFactor, inflateFactor, multFactor, maxIterations, pruneThreshold, executor }

Fields of options
NameDescription
expandFactor: number?
inflateFactor: number?
multFactor: number?
maxIterations: number?

the iteration cap (default 100, as Python markov_clustering and R MCL)

pruneThreshold: number?

after each inflation, drop entries under this to 0, keeping each column's largest (default 0: no pruning) — Python markov_clustering's pruning_threshold

attributes: MarkovAttributeFn[]?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = eles.markovClustering({ executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor or pruneThreshold is invalid; rejects if executor: 'gpu' is unavailable in this environment

Also spelled eles.mcl.

#eles.affinityPropagation(options?)
// Affinity propagation, which picks exemplars by message passing and so needs no target cluster count
eles.affinityPropagation(options?: AffinityPropagationOptions): AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

Affinity propagation, which picks exemplars by message passing and so needs no target cluster count.

Async: returns a promise, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the message passing runs; 'cpu' is the reproducible reference.

Parameters
NameDescription
options: AffinityPropagationOptions?

{ attributes, distance, preference, damping, minIterations, maxIterations, executor }

Fields of options
NameDescription
distance: DistanceMetric?
preference: AffinityPreference?
damping: number?
maxIterations: number?
minIterations: number?
attributes: AffinityAttributeFn[]?
executor: AlgoExecutor?

where the run executes; see AlgoExecutor (default 'auto')

Returns AlgoRun<Collection<NodeData, EdgeData, NodeData>[]>

a promise of one collection per cluster — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed

Example

const run = cy.nodes().affinityPropagation({ damping: 0.5, preference: 0, attributes: [node => node.data('score')], executor: 'cpu' });
const result = await run;
console.log(result.reduce((sum, cluster) => sum + cluster.length, 0)); // 3

Example graph and handle setup

Throws

if executor is invalid; rejects if executor: 'gpu' is unavailable, or if damping/preference are invalid

Also spelled eles.ap.

#Queries

Use query objects or predicates to select elements.

#Query objects and predicates

Queries › Query objects and predicates

Combine validated query terms or use a per-element predicate.

There is no selector-string grammar. Pass a structured query object or a predicate function to cy.elements(), cy.nodes(), cy.edges(), cy.filter() or eles.filter(). A query is validated and unknown keys throw; a predicate is called for each element and can contain arbitrary application logic.

const selectedHighScores = cy.nodes({
selected: true,
data: { score: { gte: 0.8 } },
});
const readyForLayout = cy.nodes(node =>
node.data('status') === 'ready' && !node.locked(),
);

#State, structure and data tests

Queries › State, structure and data tests

Match indexed state, structural flags and typed data comparisons.

Every supplied query term must hold. The group term can constrain a query to 'nodes' or 'edges'; the node- and edge-specific collection methods also restrict the search directly. State fields include selected, selectable, locked, grabbed, grabbable, active, hovered and emphasized.

Query term Meaning when true
group: 'nodes' or group: 'edges' Restrict the result to a group.
selected, selectable Selected now, or allowed to become selected.
locked, grabbed, grabbable Locked in place, being dragged, or allowed to be dragged.
active, hovered, emphasized Active pointer state, hover state, or emphasis membership.
parent, childless A node with children, or a node without children.
child, orphan A node with a parent, or a node without a parent.
collapsed A collapsed compound node.

Use false to request the opposite state, for example { selected: false }. Structural node flags include parent, childless, child, orphan and collapsed. These share state names with style conditionals so that the elements an application can style can also be queried.

Data values use a bare value for strict equality, or a condition object with exactly one operator: eq, ne, lt, lte, gt, gte or in. Missing data fails all comparisons, including ne. Numeric operators require a number. in requires a non-empty array. For a typed core, TypeScript restricts data keys to the element data shape.

Data condition Matches
{ kind: 'protein' } or { kind: { eq: 'protein' } } An existing value strictly equal to 'protein'.
{ kind: { ne: 'protein' } } An existing value other than 'protein'.
{ score: { gt: 2 } }, { score: { gte: 2 } } A numeric value greater than 2, or greater than or equal to 2.
{ score: { lt: 2 } }, { score: { lte: 2 } } A numeric value less than 2, or less than or equal to 2.
{ kind: { in: ['protein', 'gene'] } } An existing value equal to one of the listed values.

All data fields and state terms are combined with and. For or, a missing-field check or a calculation, use a predicate:

const interesting = cy.nodes(node =>
node.selected() || (node.data('score') ?? 0) > 0.8,
);
// Filter only the neighbours of a particular node.
const neighbours = cy.getElementById('a').neighborhood().nodes();
const highScores = neighbours.filter({ data: { score: { gte: 0.8 } } });

A query result is a snapshot of membership. Query again after data or state changes to obtain a new result; a previously returned collection does not automatically add newly matching elements.

const heavyEdges = cy.edges({
data: { weight: { gt: 2 }, kind: { in: ['activation', 'binding'] } },
});
const notSelectedParents = cy.nodes({
parent: true,
selected: false,
});

#Style

Use declarative stylesheet values, mappers and conditions.

Style a graph with one structured sheet, not a list of selector rules. The sheet is a plain object whose optional group blocks are nodes, edges, parents, core and bypasses. Node and edge blocks contain property/value pairs. A full cy.style(sheet) installs the sheet and replaces the previous user-authored sheet. Property names accept kebab-case or camelCase; unknown properties and invalid values throw at the call site.

cy.style({
nodes: {
label: 'data(label)',
'background-color': {
data: 'score',
scale: 'linear',
domain: [0, 1],
range: ['#fee08b', '#d73027'],
},
'border-width': {
case: [{ when: { selected: true }, then: 4 }],
else: 1,
},
},
edges: {
width: { data: 'weight', scale: 'sqrt', domain: [0, 9], range: [1, 6] },
},
});

#Constants, mappers and conditions

Style › Constants, mappers and conditions

Choose constant values, data mappers and conditional styles.

Property values are constants, scale mappers or case conditionals. A mapper reads one data field and can map it through linear, log, sqrt, pow, symlog, diverging, ordinal, threshold or quantize scales. A domain may be explicit or track the live data extent; missing or unmappable input uses fallback or the property's normal default. Color output interpolates in OKLab by default, with interpolate: 'srgb' as the explicit alternative. A label can read a data field with the string form 'data(label)' or the special passthrough object { data: 'label' }; both also support the first-class id field. Labels do not accept scale or case mappers, and that data-only object form does not make arbitrary properties data-mappable. There are no executable style functions. The supported scale/property combinations and complete mapper fields are listed in the style property reference.

A case mapper checks its clauses in order. A when can contain data tests, state such as selected, or structural conditions such as parent; an array of conditions is ANDed. The first matching then supplies the property, with else, fallback or the channel default as the final value. Missing data fails its comparisons. With this declarative form, values can be inspected, serialized, refreshed and evaluated on supported GPU paths without executing application closures per element.

Data writes refresh mapped channels for the affected elements. If an auto-domain extent changes, its mapped channel is re-derived. Selection does not run a full restyle: selected-state styling is a conditional in the default sheet. A custom definition for a property replaces that property's default selection condition as expected; include the condition explicitly when the custom color should still change on selection.

#Groups and compound parents

Style › Groups and compound parents

Understand group defaults and compound-parent styling.

#Group behavior and compound parents

nodes and edges describe the two element groups. parents is an overlay for compound parent nodes: it can override node properties and set compound padding and sizing behavior. It is separate from the ordinary node block so parent labels, child bounds and padding can be treated explicitly. core contains viewport-level theme properties such as selection-box colors, background interaction indicators, dim-opacity during emphasis and the label-declutter policy. These core values are constants; they do not map per element.

Styles support node geometry, fill/border, opacity, labels and typography, edge lines, arrows and route families, plus common overlay/underlay and text properties. Node shapes include standard geometric shapes, custom polygon points, and parent-only convex-hull, round-convex-hull and concave-hull. Hull contours follow child outer-body outlines, nested parents contribute their contours, and concave hulls form one connected region without holes or islands. An empty hull falls back to the parent's rectangle or rounded rectangle. The contour is shared by drawing, borders, edge endpoints, picking, bounds and layout dimensions. There is no public tightness or obstacle-avoidance control.

The exact supported property/group matrix, literal defaults and accepted values are in the style property reference. A property familiar from CSS is not necessarily accepted on every group. Node width, height, edge width, compound padding and font-size affect geometry; changing them updates dependent bounds and rendered geometry as part of style application.

Parent nodes also support miniature collapse. The parents overlay's collapse-scale is a finite number in (0, 1] (default 0.1). collapsed() reports the parent's own state and insideCollapsed() reports strict descendants. collapse() and expand() scale descendants around the parent's center while preserving the graph and hidden state. Style reads such as width() retain authored dimensions while geometry uses the effective scaled size. Decorations, images, charts, labels, hulls and shared internal-edge geometry follow the descendant scale; edges crossing out of the collapsed group keep their authored width.

Node charts are a paint-only family with kinds none, pie, stripes, heat-strip, radial-heat and bar. chart-values has up to 255 ordered slots; a data mapper can pass a per-node array through. Pie and stripe slots are fractions: values below one leave transparency and values above one clamp. Heat and bars preserve finite signed values; missing entries retain their positions and do not shift later slots. Heat charts require chart-scale with numeric bounds and a colour range. Bar geometry requires chart-domain and uses a zero baseline clamped to that domain; bar colors are configured separately. Missing heat values are transparent by default and missing bars leave gaps. Charts do not affect bounding boxes or pick results. cy.legend() returns mapping/chart metadata for an application-owned legend; it does not draw one.

Nodes can also draw up to four background images, in list order with later images composited on top. Image URLs or data URIs may be constant or mapped per node; opacity and color/tint can also be mapped, while fit, position, size, repeat, clipping, containment and smoothing use constant per-image lists. The default image mode draws decoded raster content; SVG sources can be rasterized again for zoom and export demand. Setting background-image-type to sdf-icon instead uses an alpha silhouette tinted by background-image-color for crisp monochrome icons. Failed URLs warn once and draw no image. Images are paint only: they do not extend element bounds or count as pick targets. Rendered cores supply the decoder; a headless core may retain the style data but cannot decode and display the image. The exact supported image property lists and defaults are in the style-property reference.

#Bypasses and reads

Style › Bypasses and reads

Read computed values and understand supported bypass behavior.

bypasses is an id-keyed object of constant overrides. A bypass wins over group definitions and defaults. It is a stylesheet declaration, not transient element state: it may refer to an id not yet present, survives removing and re-adding that id, and appears in cy.json(). A full sheet replacement replaces bypasses as well. Element style() and removeStyle() are convenience operations over those overrides; style functions are not accepted.

eles.style() reads resolved stored style for the first element (or a named property); it does not return the declaration object. numericStyle() gives the numeric value of a numeric property, while renderedStyle() accounts for the rendered coordinate scale where that property has one. These synchronous reads operate on stored channels and work headlessly. effectiveOpacity() includes compound ancestor opacity. During a batch, style reads can remain stale until the batch flush; see core batching.

#Property reference

Style › Property reference

Find supported style properties, groups and defaults.

Use these tables to choose style properties and their values. Properties are grouped by the elements they affect. Invalid names, values and group combinations throw when the sheet is compiled. The stylesheet schema describes its structure. For mapper examples and stylesheet usage, see Styling.

#Sheet shape and values

A sheet has optional props objects named nodes, edges, parents, core, and bypasses. Property names may be kebab-case or camelCase. Invalid property names, values, group combinations, and unknown sheet keys throw when the sheet is compiled. A full cy.style(sheet) replaces the user sheet, including bypasses. The stylesheet does not accept selector-rule arrays, selector strings as style rules, CSS string stylesheets, or a function for a whole group.

Colors accept CSS color names, #rgb/#rrggbb, rgb()/rgba(), hsl()/hsla(), and RGB(A) numeric arrays; they are stored as RGBA bytes. Numeric style lengths use model pixels; there is no general CSS unit conversion. Prefer finite numbers in JSON. The runtime numeric parser applies parseFloat to strings, so a numeric prefix such as "12px" is accepted even though style numbers do not have general CSS unit conversion. Unless specified otherwise, invalid enum keywords or malformed lists throw.

Mapper objects with scale or case behavior are available only for the channels listed in Mapper support. Labels and chart-values also accept a restricted { data: key } passthrough; it does not scale or branch. A scale mapper looks like:

{
data: 'score',
scale: 'linear',
domain: [0, 100], // or 'auto'
range: ['#fee08b', '#d73027'],
clamp: true,
fallback: '#999'
}

Supported scales are linear, log, sqrt, pow, symlog, diverging, ordinal, threshold, and quantize. A missing domain or domain: 'auto' tracks the live data extent. Continuous and quantize domains may use auto at either outer endpoint; diverging domains require an explicit midpoint. pow defaults to exponent 2, log to base 10, and symlog to constant 1. Ranges take numeric or color stops, or a named color scheme such as viridis, plasma, magma, inferno, ColorBrewer ramps, category10, or dark2. Colors interpolate in OKLab unless interpolate: 'srgb' is set. Missing or unmappable data uses fallback, then the channel default. Log scales use positive values only.

Conditional values use ordered case clauses. Each when is one condition or an array ANDed together; the first match wins. Conditions can compare data with eq, ne, lt, lte, gt, gte, or in, and can read state/structure such as selected, active, parent, child, collapsed, or emphasized. String and boolean data support equality and membership; numeric data supports all comparisons. Missing data never matches. The final value is else, then fallback, then the channel default.

#Groups and defaults

The defaults in the property tables are base channel defaults. The installed default sheet adds these ordinary conditional declarations:

Group Default sheet declarations
nodes background-color is #999 or #0169D9 when selected; active nodes get overlay-opacity: 0.25.
edges line-color and source, target, and mid-arrow colors are #999 or #0169D9 when selected; width is 3; active edges get overlay-opacity: 0.25.
parents Parent overlay defaults are rectangular shape, #eee fill, 1px #ccc border, and 10px padding. Selected parents use #CCE1F9 fill and #aec8e5 border. A user's nodes block overrides parent defaults; a user's parents block overrides both.

nodes applies to all nodes, including compound parents. edges applies to edges. parents overlays node styling for compound parents and owns the compound-sizing properties below. core affects viewport-level behavior and accepts constants only. A bypass is an id-keyed constant declaration; it beats group blocks and defaults, and can be declared before its element exists.

#Shared channels

Style › Property reference › Shared channels

Shared channels apply across element groups.

#Shared element channels

These channels apply to nodes and edges; parent channels use the node form.

Property Base default Accepted values
opacity 1 Finite number; mapped. The parser does not restrict it to [0, 1]; use that interval for conventional opacity values.
events yes yes/no or boolean; mapped. no/false makes the element pointer-transparent.
visibility visible visible or hidden; mapped. hidden suppresses paint without removing the element.

#Node geometry and paint

Style › Property reference › Node geometry and paint

Configure node body geometry and paint.

#Node and parent node properties

Unless a row says node-only or parent-only, the property is accepted in nodes and parents. A mapper can replace a constant only for properties named in the mapper inventory below. Lists and global font-face settings remain constants even where nearby values accept mappers.

#Body geometry and paint
Property Base default Accepted values
width 30 Finite model-pixel number; mapped. Also edge line width. Parent size is derived from children.
height 30 Finite model-pixel number; mapped. Parent size is derived from children.
shape ellipse Mapped keyword: ellipse, circle, rectangle, square, round-rectangle, triangle, pentagon, hexagon, heptagon, octagon, diamond, rhomboid, right-rhomboid, vee, star, tag, polygon, concave-hexagon, cut-rectangle, round-triangle, round-diamond, round-pentagon, round-hexagon, round-heptagon, round-octagon, round-tag, bottom-round-rectangle, barrel, convex-hull, round-convex-hull, or concave-hull. circle and square resolve to ellipse and rectangle. Hull shapes describe compound-parent contours.
shape-polygon-points [-1,-1, 1,-1, 1,1, -1,1] Constant array or whitespace-separated numeric string with an even number of values and at least 3 x/y pairs in [-1, 1]. Used with shape: polygon; values after the 32nd pair are truncated.
corner-radius auto Mapped non-negative model-pixel number or auto. auto is min(width/4, height/4, 8).
background-color #999 Color; mapped. The default sheet supplies the selected-state color.
background-opacity 1 Number in [0, 1]; mapped; folds into fill alpha.
background-fill solid Mapped keyword: solid, linear-gradient, radial-gradient.
background-gradient-stop-colors empty Constant color array or whitespace-separated string; at most 5 stops are drawn.
background-gradient-stop-positions evenly spread Constant array/string of percentages or numbers; clamps to [0, 100] and never decreases between stops.
background-gradient-direction to-bottom Mapped keyword: to-bottom, to-top, to-left, to-right, to-bottom-right, to-bottom-left, to-top-right, to-top-left.
border-color #000 Color; mapped.
border-width 0 Finite model-pixel number; mapped.
border-opacity 1 Number in [0, 1]; mapped and folded into border alpha.
border-position center Mapped keyword: center, inside, outside.
border-style solid Mapped keyword: solid, dashed, dotted, double.
border-dash-pattern [4, 2] Constant numeric array, number, or whitespace-separated string. Negative entries throw. It normalizes to two on/off pairs; odd lists repeat and longer lists truncate.
border-dash-offset 0 Finite model-pixel number; mapped.
outline-color #999 Color; mapped.
outline-opacity 1 Number in [0, 1]; mapped.
outline-width 0 Non-negative model-pixel number; mapped.
outline-offset 0 Non-negative model-pixel number; mapped.
outline-style solid Mapped keyword: solid, dashed, dotted, double. The current double outline path renders as a solid outline.

border-position: center places the border across the shape boundary. corner-radius only affects shapes that have rounded corners. Outlines sit outside the border and contribute to bounds; they are not pick targets.

#Labels and typography

Style › Property reference › Labels and typography

Configure node label typography and placement.

The common text properties also apply to edges. Edge endpoint-label properties are listed separately below.

Property Base default Accepted values
label '' Constant string, data(key) string form, or { data: key } passthrough object; id reads the first-class id in either mapper form. Scale/case mappers are rejected.
font-size 16 Finite model-pixel number; mapped.
font-family sans-serif Non-empty string, constant-only. The glyph atlas uses one font face.
font-style normal normal, italic, or oblique; constant-only.
font-weight normal normal, bold, bolder, lighter, or hundreds from 100 to 900; constant-only.
color #000 Label color; mapped.
text-opacity 1 Number in [0, 1]; mapped; folds into text, outline, and text-background alpha.
text-outline-width 0 Finite model-pixel number; mapped.
text-outline-color #000 Color; mapped.
text-outline-opacity 1 Finite number; mapped. Use [0, 1] for conventional opacity values; the parser accepts finite values outside that range.
text-background-color #000 Color; mapped.
text-background-opacity 0 Finite number; mapped. Use [0, 1] for conventional opacity values; the parser accepts finite values outside that range.
text-background-padding 0 Finite model-pixel number; mapped.
text-background-shape rectangle Mapped keyword: rectangle or round-rectangle.
text-border-width 0 Non-negative model-pixel number; mapped.
text-border-color #000 Color; mapped.
text-border-opacity 0 Number in [0, 1]; mapped.
text-border-style solid Mapped keyword: solid, dashed, dotted, double.
text-margin-x
text-margin-y
0 Finite model-pixel numbers; mapped.
min-zoomed-font-size 0 Non-negative device-pixel number; mapped. Zero disables the floor. The label hides below this zoomed, DPR-scaled size.
text-transform none Mapped keyword: none, uppercase, lowercase.
text-wrap none Mapped keyword: none, wrap, ellipsis.
text-max-width 9999 Non-negative model-pixel number; mapped.
line-height 1 Non-negative multiplier; mapped.
text-overflow-wrap whitespace Mapped keyword: whitespace or anywhere. anywhere allows long words to break.
text-justification auto Mapped keyword: auto, left, center, right. auto follows horizontal alignment.
text-halign center Node-only mapped keyword: left, center, right.
text-valign bottom Node-only mapped keyword: top, center, bottom.
text-rotation 0 (none) Mapped none, autorotate, or finite radians. autorotate is edge-only; nodes take numeric rotations.
text-events no Node-only mapped yes/no or boolean. When enabled, the label box can pick the node.
label-priority 0 Node-only mapped finite number. Higher values claim space first when core.label-declutter is cull.
*

Node labels align at the bottom by default. Use text-valign to change the alignment.

Wrapping preserves embedded newlines. whitespace leaves an unbreakable word overflowing; anywhere can break it. ellipsis truncates one line. A text border is drawn within the padded background box. Label dimensions join layout or fit geometry only where those operations request labels.

#Ghosts and overlays

Style › Property reference › Ghosts and overlays

Configure additional node paint layers.

Property Base default Accepted values
ghost no Node-only mapped yes/no or boolean; draws one extra copy of the basic node body.
ghost-offset-x
ghost-offset-y
0 Node-only finite model-pixel numbers; mapped.
ghost-opacity 0 Node-only number in [0, 1]; mapped.
overlay-color
underlay-color
#000 Node and edge colors; mapped. Node layers surround the body; edge layers stroke the edge path.
overlay-opacity
underlay-opacity
0 Number in [0, 1]; mapped. The default sheet sets overlay-opacity to 0.25 on active elements.
overlay-padding
underlay-padding
10 Non-negative model-pixel number; mapped.
overlay-shape
underlay-shape
round-rectangle Node-only round-rectangle or ellipse; constants only.
overlay-corner-radius
underlay-corner-radius
auto Node-only non-negative model-pixel number or auto; constants only.

Ghosts duplicate only the basic node body, not labels or decorations. They are not pickable and do not add extents to box selection. Node overlays draw above the body but below labels. Edge underlays sit beneath edges; edge overlays sit over edges and arrows. Edge layers do not accept node-only shape/radius props.

#Background images

Style › Property reference › Background images

Configure node background images.

These properties are node-only. Image settings may be scalars or arrays; arrays distribute by image index and repeat their last item for later images. At most four image layers are composited. Only background-image, background-image-opacity, and background-image-color take mapper objects; a mapped image represents one URL per node.

Property Base default Accepted values
background-image none none, URL, url(...) wrapper, or URL array; mapped single URL is allowed.
background-fit none Per-image none, contain, cover; scalar or non-empty array.
background-image-opacity 1 Per-image number in [0, 1]; scalar or non-empty array; mapped single value is allowed.
background-position-x
background-position-y
50% Per-image percentage, pixel number, Npx, or N%; scalar or non-empty array.
background-offset-x
background-offset-y
0 Per-image pixel number or percentage string; scalar or non-empty array.
background-width
background-height
auto Per-image auto, non-negative pixel number, Npx, or N%; scalar or non-empty array.
background-repeat no-repeat Per-image no-repeat, repeat-x, repeat-y, or repeat; scalar or non-empty array.
background-clip node Per-image node or none; scalar or non-empty array.
background-image-containment inside Per-image inside or over; scalar or non-empty array.
background-image-smoothing yes Per-image yes/no or boolean; scalar or non-empty array.
background-image-crossorigin anonymous anonymous, use-credentials, or null; constant-only.
background-image-type auto Per-image auto or sdf-icon; scalar or non-empty array.
background-image-color #999 SDF icon tint; color, mapped.

background-width-relative-to and background-height-relative-to are reserved names in the internal property vocabulary but throw as unsupported. They are not part of the accepted style surface.

#Node charts

Style › Property reference › Node charts

Configure supported data charts on nodes.

Charts are node paint decorations; they do not change bounds or picking. The chart kind and scalar channels accept mappers. List/config values are constant-only except chart-values, which can use a { data: key } passthrough to read a per-node array.

Property Base default Accepted values
chart none Mapped none, pie, stripes, heat-strip, radial-heat, or bar.
chart-values not set Numeric/null list or whitespace-separated numeric list; { data: key } passthrough may read a per-node array. First 255 slots are kept, preserving missing slots.
chart-colors category10 Color list or named palette; constant-only. Pie/stripe values cycle a shorter palette.
chart-scale not set Constant scale object with explicit domain and color range; only outer domain endpoints may be auto. Used by heat colors and optional bar colors.
chart-domain not set Constant two-number domain with min < max, or auto endpoint(s). Required for bars.
chart-missing-color transparent Color; constant-only; heat missing-value appearance.
chart-size 1 Fraction in [0, 1] or percentage string; mapped.
chart-hole 0 Fraction in [0, 1] or percentage string; mapped.
chart-start-angle 0 radians Number in radians or deg/rad string; mapped.
chart-direction vertical Mapped vertical or horizontal; stripe/bar axis.
chart-opacity 1 Number in [0, 1]; mapped.

Pie/stripe values represent fractions: a sum below 1 leaves a transparent remainder and values over 1 clamp. Heat and bar values can be signed. Missing and non-finite entries retain their positions but do not affect extents. Heat requires an explicit scale domain and color range. Bars require chart-domain, use a zero baseline clamped to that domain, and leave missing values empty. Categorical chart-colors and chart-scale cannot both color bars.

#Edge paint and arrows

Style › Property reference › Edge paint and arrows

Configure edge lines and arrow paint.

#Edge properties

All properties here belong in edges. The common text properties above also apply to edge labels unless marked node-only. Edges have a center label and source/target endpoint labels.

#Line paint and arrows
Property Base default Accepted values
width 3 from default sheet Finite model-pixel number; mapped.
opacity 1 Number; mapped. Also affects effective arrow alpha.
line-color #999 Color; mapped; selected color is supplied by the default sheet.
line-opacity 1 Number in [0, 1]; mapped; folds into line and arrow alpha.
line-style solid Mapped solid, dashed, or dotted.
line-cap butt Mapped butt, round, or square.
line-dash-pattern [6, 3] Constant numeric array/number/whitespace string; negative entries throw; normalized to two on/off pairs.
line-dash-offset 0 Finite model-pixel number; mapped.
line-outline-width 0 Non-negative model-pixel number; mapped; draws a casing under each edge line.
line-outline-color #000 Color; mapped.
line-fill solid Mapped solid, linear-gradient, or radial-gradient.
line-gradient-stop-colors empty Constant color list/string; at most 5 stops.
line-gradient-stop-positions evenly spread Constant percentages/numbers; clamped to [0, 100] and nondecreasing.
arrow-scale 1 Constant must be positive; mapped values are floored at 1/16.
source-arrow-shape
target-arrow-shape
none Mapped none, triangle, arrow (triangle alias), vee, chevron, circle, square, diamond, tee, triangle-tee, circle-triangle, triangle-backcurve.
source-arrow-color
target-arrow-color
#999 Color; mapped; selected color is supplied by the default sheet.
source-arrow-fill
target-arrow-fill
filled Mapped filled or hollow.
source-arrow-width
target-arrow-width
mid-source-arrow-width
mid-target-arrow-width
1 Non-negative model-pixel number, match-line, or percentage of edge width; constants only. These widths set hollow-head strokes; mid heads are currently always filled, so their width values do not change their drawing.
mid-source-arrow-shape
mid-target-arrow-shape
none Same arrow keywords; mapped.
mid-source-arrow-color
mid-target-arrow-color
#999 Color; mapped; selected color is supplied by the default sheet.

Gradient stops interpolate in sRGB. Linear edge stops follow the drawn span; curved/routed edges use path length. line-opacity folds into stored line and arrow color alpha. A zero-alpha arrow reads back as shape none because stored color alpha controls whether it draws. The casing is paired with each edge in draw order. Edge overlay/underlay layers are separate from the casing.

#Edge routes and endpoints

Style › Property reference › Edge routes and endpoints

Configure supported routes and endpoints.

*

Edges are straight by default. Set curve-style: 'bezier' for curved routes.

Property Base default Accepted values
curve-style straight Mapped straight, bezier, unbundled-bezier, segments, round-segments, taxi, round-taxi, haystack, or straight-triangle.
control-point-step-size 40 Finite model-pixel number; mapped.
control-point-weight 0.5 Finite number; mapped.
loop-direction -45° Angle in radians or deg/rad string; mapped.
loop-sweep -90° Angle in radians or deg/rad string; mapped.
control-point-distances not set Constant number, array, or whitespace-separated number string; mapper values are not supported.
control-point-weights [0.5] Constant number, array, or whitespace-separated number string; mappers are not supported.
segment-distances [20] Constant number, array, or whitespace-separated number string; mappers are not supported.
segment-weights [0.5] Constant number, array, or whitespace-separated number string; mappers are not supported.
segment-radii [15] Constant number, array, or whitespace-separated number string; mappers are not supported.
radius-type arc-radius One arc-radius or influence-radius keyword, or a constant array/whitespace-separated list; mappers are not supported.
edge-distances intersection Mapped intersection, node-position, or endpoints.
taxi-direction auto Mapped auto, vertical, horizontal, upward, downward, leftward, rightward.
taxi-turn 50% Constant accepts a finite pixel number, percentage string, or auto; negative pixel turns select from the target side. Mappers produce pixel numbers; use fallback: auto to select auto routing, since percentage strings are constants-only.
taxi-turn-min-distance 10 Finite model-pixel number; mapped.
taxi-radius 15 Finite model-pixel number; mapped.
taxi-track source Mapped source, target, or family.
taxi-track-spacing 10 Non-negative model-pixel number; mapped.
haystack-radius 0 Number in [0, 1]; mapped.
source-endpoint
target-endpoint
outside-to-node Constant keyword, point, or angle. Keywords: outside-to-node, inside-to-node, outside-to-line. Points have two components with optional % or px; angles are radians or deg/rad strings.
source-distance-from-node
target-distance-from-node
0 Non-negative model-pixel number; mapped.

The list-valued curve properties are constants-only: a mapper's scalar output is not an array. bezier is the parallel-edge bundle family; unbundled, taxi and segment families route per edge. taxi-turn: auto participates in the taxi track pass. Endpoint outside-to-node-or-label and outside-to-line-or-label forms throw because edge-to-label bounds are not available. This catalog does not imply other endpoint forms are supported.

#Edge labels

Style › Property reference › Edge labels

Configure labels on edges.

Properties Base default Accepted values
source-label
target-label
'' Constant string, data(key) string form, or { data: key } passthrough object; scale/case mappers are rejected.
source-text-offset
target-text-offset
0 Non-negative model-pixel number; mapped.
source-text-margin-x
source-text-margin-y
target-text-margin-x
target-text-margin-y
0 Finite model-pixel number; mapped.
source-text-rotation
target-text-rotation
0 (none) Mapped none, autorotate, or finite radians.
text-rotation 0 (none) Shared mapped rotation; edge labels also accept autorotate.

#Compound sizing and miniatures

Style › Property reference › Compound sizing and miniatures

Configure compound-parent sizing and miniature rendering.

#Compound-parent sizing and miniatures

Compound props are constants-only and valid only in parents. Putting them in nodes, edges, or core throws. Parent base sizing defaults are 10px padding, zero minimum inner dimensions, and compound-sizing-wrt-labels: exclude.

Property Default Accepted values and behavior
padding 10px Non-negative pixel number or percentage string such as 12%. Percent uses padding-relative-to.
padding-left
padding-right
padding-top
padding-bottom
unset; inherit padding Non-negative pixel number or percentage string; an authored side overrides uniform padding for that side.
padding-relative-to width width, height, average, min, or max; used only with percentage padding.
min-width
min-height
0 Non-negative model-pixel number; minimum inner dimension before padding.
compound-sizing-wrt-labels exclude exclude or include. Include visible direct-child label bounds in model space before parent padding; a parent's own label never sizes itself.
collapse-scale 0.1 Parent-only finite number in (0, 1]; mapper or bypass is allowed. Used as the configured miniature factor when a collapsed state has no separately applied factor.

convex-hull, round-convex-hull, and concave-hull are shape values for compound parents. Their contours follow visible direct-child outer body outlines; nested parents contribute their contours. Concave hulls remain a single connected region, may cover unrelated nodes, and have no public tightness or obstacle control. Empty hulls fall back to a rectangle, rounded for the round shapes. Child label bounds join sizing and hull inputs only with compound-sizing-wrt-labels: include. Collapse state itself is carried on node definitions and collections; collapsed: true is available as a node condition.

#Core properties

Style › Property reference › Core properties

Configure core-wide styling.

Every core value is a constant. Scale/case mapper objects are rejected.

Property Default Accepted values and behavior
selection-box-color #ddd Color for the DOM selection box.
selection-box-opacity 0.65 Number in [0, 1].
selection-box-border-color #aaa Color.
selection-box-border-width 1 Non-negative model-pixel number.
active-bg-color #000 Color for the background-grab indicator.
active-bg-opacity 0.15 Number in [0, 1].
active-bg-size 30 Non-negative model-pixel number.
dim-opacity 0.15 Number in [0, 1]; opacity outside the set passed to cy.emphasize().
label-declutter none none or cull; cull gives higher label-priority node labels first claim to space.

The selection box and background-grab indicator are DOM overlays and do not appear in graph image export.

#Transitions

Style › Property reference › Transitions

Configure supported stylesheet transition channels and timing.

#Style transitions and animation

The sheet's transition-property, transition-duration, transition-delay and transition-timing-function configure transitions when a style change updates a listed channel. The transitionable set matches animate()'s supported geometry and paint channels. Animations start immediately; there is no queue, and an overlapping animation replaces the older one on the same channels. Colors interpolate in OKLab. See animations for handles, easing and sequence patterns.

See the style property reference for all supported properties, defaults and values.

transition-property, transition-duration, transition-delay, and transition-timing-function are per-group settings accepted in nodes, edges, and parents. They are not channels; they cannot be mapped or bypassed. transition-property is a constant list/string of properties valid for the group. Duration and delay are non-negative milliseconds, defaulting to zero. Timing defaults to linear and must name a supported easing function.

The engine currently tweens node opacity, background-color, border-color, border-width, width, height, and font-size; edge opacity, line-color, width, and font-size; and parent padding together with its node channels. Other property names can pass group validation but do not become tweenable merely by appearing in transition-property; discrete style changes snap when the style update starts. A first style application is immediate. See animations for handle and channel behavior.

#Mapper support and rendering limits

Style › Mapper support and rendering limits

Check mapper coverage and current curved-edge limits.

#Mapper support

The following channels accept scale and conditional mappers. Every accepted property outside it takes constants only, with the restricted label/chart-values passthroughs and chart-scale configuration form noted above.

Group Mapper-capable properties
Nodes background-color, border-color, width, height, border-width, opacity, shape, font-size, min-zoomed-font-size, label-priority, text-halign, text-valign, color, text-outline-width/color/opacity, text-background-color/opacity/padding, text-margin-x/y, text-rotation (except autorotate), text-transform, text-background-shape, text-wrap, text-max-width, line-height, text-overflow-wrap, text-justification, text-border-width/color/opacity/style, background-fill, background-gradient-direction, background-opacity, events, visibility, text-events, ghost and its offsets/opacity, overlay/underlay color/opacity/padding, outline color/opacity/width/offset/style, corner-radius, border-position/style/dash-offset, chart kind/opacity/size/hole/start-angle/direction, background-image/image-opacity/image-color.
Parents Node channels above plus collapse-scale; parent channel values resolve only on parent slots.
Edges width, opacity, font-size, color, shared text outline/background/margin/wrap/rotation/transform/border channels, text-opacity, events, visibility, overlay/underlay color/opacity/padding, line-color/style/opacity/cap/dash-offset/outline/fill, arrow-scale, source/target/mid-arrow shape and color, source/target arrow-fill, curve-style, control-point step/weight, loop direction/sweep, edge-distances, taxi direction/turn/min-distance/radius/track/track-spacing, haystack-radius, endpoint distance, and endpoint-label offset/margin/rotation.
Core and bypasses None. Core properties are constants; bypass entries are constant-only.

Mapper use on a non-mappable property, on the wrong group, or on a global font property throws. collapse-scale belongs in parents, not the nodes block. Node-only properties such as charts, images, text-events, label-priority, and shape-polygon-points are rejected in edges; route and endpoint-label properties are edge-only.

#Curved edge limits

Edge endpoints use an approximation of the node's shape rather than exact per-shape intersection. On a 40×24 node, ellipse, circle and rectangle are exact; round-rectangle is off by up to 2.247 model pixels at a corner, and triangle by 8.453 at the leaf, the polygon tier's worst case. Multi-point curves take at most 8 controls and 11 segment points. Weights clamp to [-1, 2]. An unbundled-bezier loop uses control-point-distances[0] as its loop distance, falling back to the step size when unset, and segment- or taxi-styled loops render as loops.

#Events

Understand ownership, bubbling, vocabulary and event objects.

#Ownership, delegation and bubbling

Events › Ownership, delegation and bubbling

Choose the event owner and delegate with a stable predicate identity.

Core and element event methods use literal, space-separated event names. cy.on() and cy.one() bind to the core; with three arguments they delegate to elements using a predicate over the event target. eles.on() and eles.one() bind per element in the collection. Core removeAllListeners() clears core, element-bound and delegated listeners. Collection off(events, handler?) removes named event types from its elements; there is no collection-wide remove-every-type method. Keep your handler references so that you can remove the listeners your application installs.

const isNode = ele => ele.isNode();
const onNodeTap = event => {
const node = event.target;
console.log(node.id());
};
cy.on('tap', isNode, onNodeTap);
// Later, pass the same predicate and handler function objects.
cy.off('tap', isNode, onNodeTap);

Predicates compare by function identity when removing a delegated listener. Create the predicate once if it needs to be removed later. Collection event handlers are qualified to their element and continue to work when the store compacts slots, because the listener follows element identity rather than a slot number.

Events from an element bubble through its compound ancestors and then to the core. stopPropagation() stops later graph event phases and calls the underlying DOM event's stopPropagation() when available. Returning false from a handler has the same graph bubbling effect. preventDefault() only prevents the browser's default via originalEvent; it does not veto selection, grabbing or other Cytoscape gesture defaults. Use the dedicated options such as autounselectify, autoungrabify, boxSelectionEnabled, userPanningEnabled or userZoomingEnabled to control those interactions.

#Event vocabulary

Events › Event vocabulary

Use literal event names and distinguish pointer gestures from exact picking.

Event names are literal strings. The built-in interaction vocabulary includes these families:

  • Normalized press events: tapstart, tapdrag, tapend, tap, taphold, dbltap, tapselect, and tapunselect.
  • Drag state: grab, grabon, drag, free, freeon, dragfree, and dragfreeon. The -on forms target the directly grabbed element; the plain forms also reach selected companions moved with it.
  • Drag-hover and context interaction: tapdragover/tapdragout, cxttapstart, cxtdrag, cxttapend, cxttap, and cxtdragover/cxtdragout.
  • Pointer input: pointerdown, pointermove, pointerup, pointercancel, pointerover, and pointerout.
  • Viewport gestures: dragpan, scrollzoom, pinchzoom, and scrollpan. They are core events and carry model/rendered positions where available.
  • Selection and box selection: select, unselect, boxstart, box, boxend, and boxselect.
  • Viewport/model notifications: pan, zoom, viewport, and position.

Other emitted core events include element/data changes (add, remove, data, patch), style and batch changes (style, legendchange, batchstart, batchend), layout lifecycle (layoutstart, layoutready, layoutstop), progressive loading (loadstart, loadchunk, loadready, loadstop), resize/render, device lifecycle and errors, and destroy. Their payloads are described by the corresponding API entries.

The tapdragover/tapdragout and cxtdragover/cxtdragout pairs target nodes only. They use synchronous CPU node picking; they do not promise edge hover targets. Gesture hit-testing also applies the interaction halo used for easier edge and node targeting, while cy.pick() remains exact geometry. See the pick methods in the API reference when a query must match geometric API behavior instead of pointer behavior.

The raw mouse/touch re-emits and vmouse* aliases are not emitted; pointer* is the raw-input family. The older mouseover and mouseout names remain available too. The library accepts arbitrary custom names, so it does not reject a misspelling or a name that no implementation emits. Such a listener registers but never fires unless application code emits that exact name.

Namespaces are not parsed: 'tap.ns' is one literal type, not a tap listener with namespace metadata. emit('tap') does not reach a 'tap.ns' handler, while emit('tap.ns') reaches that exact name. The same rule governs off().

#Event object

Events › Event object

Inspect event payloads and control propagation or browser defaults.

#Payload and state

Events › Event object › Payload and state

Read the target, core, coordinates and lifecycle-specific payload.

#Event payload and state

Event exposes type, target, cy, timestamp, optional model and rendered positions, the original DOM event when one exists, and lifecycle payloads such as layout, cancelled, progress and diff when appropriate. Element event targets are one-element collections; core events target the core. The layout property identifies the layout instance for lifecycle events. Pointer positions are translated between model and rendered spaces using the current viewport.

#event.type
// the event type, e.g
event.type: string

the event type, e.g. 'tap' — never namespaced

Returns string

Example

console.log(event.type); // "example"

Example graph and handle setup

#event.cy
// the core the event was raised on
event.cy: Core<NodeData, EdgeData>

the core the event was raised on

Returns Core<NodeData, EdgeData>

Example

console.log(event.cy === cy); // true

Example graph and handle setup

#event.renderedPosition
// Get the position
event.renderedPosition: Position

rendered-space position; derived from position and the viewport

Returns Position

Example

console.log(event.renderedPosition); // undefined

Example graph and handle setup

#event.originalEvent
// the DOM event behind a gesture, when there was one
event.originalEvent: NativeEvent

the DOM event behind a gesture, when there was one

Returns NativeEvent

Example

console.log(event.originalEvent); // undefined

Example graph and handle setup

#event.layout
// the layout instance, on the layout lifecycle events
event.layout: unknown

the layout instance, on the layout lifecycle events

Returns unknown

Example

console.log(event.layout); // undefined

Example graph and handle setup

#event.cancelled
// on layoutstop, whether the run was cancelled; on loadstop, whether the load was
event.cancelled: boolean

on layoutstop, whether the run was cancelled; on loadstop, whether the load was

Returns boolean

Example

console.log(event.cancelled); // undefined

Example graph and handle setup

#event.diff
// on patch, what the patch added, removed and updated
event.diff: PatchDiff<NodeData, EdgeData>

on patch, what the patch added, removed and updated

Returns PatchDiff<NodeData, EdgeData>

Example

console.log(event.diff); // undefined

Example graph and handle setup

#event.timeStamp
// when the event was built, Date.now() unless the caller supplied one
event.timeStamp: number

when the event was built, Date.now() unless the caller supplied one

Returns number

Example

console.log(Number.isFinite(event.timeStamp)); // true

Example graph and handle setup

#event.isDefaultPrevented()
// Whether preventDefault() was called on this event
event.isDefaultPrevented(): boolean

Whether preventDefault() was called on this event. This flag concerns the browser's default behaviour, such as page scrolling. Use the core's interaction controls to disable graph selection, dragging or box selection.

Returns boolean

Example

console.log(event.isDefaultPrevented()); // false

Example graph and handle setup

#event.isPropagationStopped()
// Whether stopPropagation() has been called — read by the compound bubbling walk, where it halts the phase sequence
event.isPropagationStopped(): boolean

Whether stopPropagation() has been called — read by the compound bubbling walk, where it halts the phase sequence.

Returns boolean

Example

console.log(event.isPropagationStopped()); // false

Example graph and handle setup

#Propagation and browser defaults

Events › Event object › Propagation and browser defaults

Control bubbling and browser defaults; gesture options control graph interactions.

#Browser defaults and exact picking

The interaction vocabulary deliberately separates graph events from browser defaults. Pointer-derived gestures include hit tolerance and device-specific semantics; the exact geometric cy.pick() API does not apply the gesture halo. See the API reference for its contract and the core options for independent gesture controls.

#event.preventDefault()
// Prevent the original browser event's default behaviour when one is attached, for example page scrolling
event.preventDefault(): void

Prevent the original browser event's default behaviour when one is attached, for example page scrolling. This does not disable graph selection or dragging; use core controls such as autounselectify(), autoungrabify() and boxSelectionEnabled() for graph gestures.

Returns void

Example

event.preventDefault();
console.log(event.isDefaultPrevented()); // true

Example graph and handle setup

#event.stopPropagation()
// Stop the event bubbling to further phases: the remaining ancestors and the core do not see it
event.stopPropagation(): void

Stop the event bubbling to further phases: the remaining ancestors and the core do not see it. Returning false from a handler does the same. With originalEvent attached this also calls the DOM event's stopPropagation(), so an outer DOM listener stops seeing it too.

Returns void

Example

event.stopPropagation();
console.log(event.isPropagationStopped()); // true

Example graph and handle setup

#Layouts

Compute model-space node positions using built-ins or direct implementations.

A layout computes model-space node positions. The core supports whole-graph runs through cy.layout(options) and scoped runs through eles.layout(options). Creating a layout returns a handle; no positions change until run(). Await promise() to know that layoutstop has fired. The layoutstart, layoutready and layoutstop lifecycle events belong to the core, not the layout handle.

const layout = cy.layout({
name: 'flow',
direction: 'rightward',
nodeSep: 48,
rankSep: 72,
});
cy.on('layoutstop', event => {
if (event.layout === layout) console.log('positions are ready');
});
layout.run();
await layout.promise();

#Shared options

Layouts › Shared options

Configure finishing, scope, dimensions, packing and mapping.

This reference describes the ten built-in layouts and their current options. The type surface is in src/public-types.mts; defaults and behavior are checked against each implementation under src/layout/, including force-run.mts, flow.mts, layout-mapping.mts, and per-component.mts.

For lifecycle, scopes, extensions and the overview of each family, see Layouts. Layouts compute model-space node positions. Creating a layout does not run it:

const layout = cy.layout({
name: 'flow',
direction: 'rightward',
nodeSep: 48,
rankSep: 72,
});
layout.run();
await layout.promise();

All built-ins accept the common layout options below. Some fast paths apply them through the shared finisher only when needed; each implementation's option table calls out special cases. A collection call, eles.layout(options), sets the scope to that collection. Otherwise, the scope is the whole graph.

Option Default Contract
eles whole graph Element collection to lay out; set automatically by eles.layout().
fit true Fit the viewport after placement.
padding 30 Rendered-space/CSS-pixel margin around the fitted graph. It is passed to cy.fit(); it is not model-space layout spacing.
boundingBox omitted Explicit model-space bounds for layouts that use a box; accepts x1/y1 plus x2/y2 or w/h. Viewport-sized built-ins derive an omitted box from viewport dimensions. Force uses an explicit box only for its final scale-down; flow and pack also use this option only when supplied.
nodeDimensionsIncludeLabels false Include node label bounds in spacing/overlap boxes. Headless label bounds are estimates until a renderer reports measured dimensions.
spacingFactor omitted Dimensionless multiplier for overall spacing when the layout/finisher uses it; omitted leaves the layout's natural spacing.
transform omitted Function of (node, computedPosition) returning the final position; typically used to flip/rotate the result.
animate false Tween nodes from their old positions to computed positions.
animationDuration 500 ms Duration of a position tween when animation is enabled.
animationEasing omitted Easing name passed to the animation system.
animateFilter omitted Function of (node, index); true nodes animate and the rest jump. Omitted means all nodes animate.
ready omitted Callback after the layout-ready stage.
stop omitted Callback after layout-stop.
zoom omitted Set zoom when fit is false.
pan omitted Set pan when fit is false.

Layouts generally place unlocked leaves; compound parents derive from their children. Locked nodes hold their positions. Force treats locked nodes as pinned participants; discrete layouts leave them out of placement slots. There are layout-specific exceptions for a collapsed parent that has no descendants in scope, which can move as one unit.

#Score and sort mappings

Layouts › Shared options › Score and sort mappings

Map scores and sorting criteria for built-in options.

#Mappings for layout options

Two mapping forms accept serializable objects alongside functions. They resolve once when the layout starts; changing data during a run does not refresh the already computed scores or ordering.

#Score mapping

force.edgeLength, concentric.concentric, flow.minLength, and flow.edgeWeight accept a numeric constant, a function, or an object of this form:

{
data: 'score',
scale: 'log',
range: [40, 200],
invert: true,
default: 60
}

The column must exist and be numeric. Without range, { data } passes each numeric value through as the score. With range, the observed extent maps to [range[0], range[1]] using linear, log, or sqrt; invert reverses the result. scale or invert without range throws. Missing values use default, then the option's own fallback. Invalid values under log, such as non-positive values, also use that fallback. A constant-valued column maps to the range midpoint. Mapping errors name the option and key.

force.edgeLength defaults to 60. A mapped force edge length resolves once for all graph edges; edges outside the run's simulation scope do not contribute forces.

#Sort mapping

grid.sort, circle.sort, and breadthfirst.depthSort accept either a comparator function or a serializable { data, order? } object:

{ data: 'rank', order: 'descending' }

The node data column must exist and be numeric or string, not mixed. order is ascending by default or descending when requested. Missing values sort last in either direction; ties break by ascending node id.

#Component packing

Layouts › Shared options › Component packing

Configure packing without changing component-internal geometry.

#Component packing options

Grid, circle, concentric, breadthfirst, and radial accept packComponents, componentSpacing, componentGroup, componentOrder, and groupSpacing. packComponents defaults to false: each layout arranges one drawing over its whole scope. When true, each disconnected component is laid out separately, then the boxes are shelf-packed largest first. The component gap defaults to 40 model pixels. Locked nodes remain fixed and packed content is shifted away from their boxes where needed.

Option Default Contract
packComponents false Split geometric placement into one layout per disconnected component, then pack the results.
componentSpacing 40 Gap between packed component boxes, in model-space pixels.
componentGroup omitted Function of { nodes, size, width, height } returning a string/number key or nullish. Keyed groups are placed by key: numbers ascending, then strings lexically, then unkeyed.
componentOrder omitted Comparator over two component descriptions. Orders within a group before the largest-first tie-break.
groupSpacing 3 × componentSpacing Gap between grouped boxes, in model-space pixels.

componentGroup and componentOrder must be functions when supplied; otherwise the layout throws at start. Force uses componentSpacing, componentGroup, componentOrder, and groupSpacing for its settle re-pack, but it has no packComponents option. The pack layout always packs current component positions.

#Built-in layouts

Layouts › Built-in layouts

Choose among the ten current built-in layouts.

#Built-in families

The current built-ins are grid, preset, circle, concentric, breadthfirst, random, radial, pack, force and flow. Discrete geometric layouts place nodes in grids, rings, ranks, trees or a supplied position map. pack rearranges disconnected components without changing a component's internal coordinates. The seeded random layout can repeat a placement when given the same seed.

force is spring/electric and can relax current positions or initialize a fresh arrangement. It supports finite settle runs, streamed/infinite runs, overlap separation, component packing and optional placement constraints. Its executor can use a reproducible CPU reference, a worker or GPU integration where the selected build and environment support it. The GPU path is asynchronous and its live trajectory is not bit-for-bit stable between runs; the CPU path is the reproducible reference. During a live GPU force run, the GPU owns the position column and CPU position reads are stale until the run's readback. Read after layoutstop or promise() when final CPU-visible coordinates matter.

flow is a layered directed-graph layout. It computes node positions only; pair it with an edge routing style such as curve-style: 'taxi' or a Bezier route so edges remain routed when nodes move. The breadthfirst layout handles depth rows or circles; radial assigns hierarchy-aware angular wedges. The complete option table, with defaults and constraints for each built-in, is in layout options. It also records which controls are shared and which are specific to one algorithm.

Shared layout options control collection scope, animation/finishing, viewport fit, padding, spacing and transforms. A layout may use element collections for convenience or the slot-oriented context for lower allocation cost. Under headless builds, dimensions are available from configured headless width/height; text dimensions are estimates because no renderer has laid out glyphs.

The shared finishing path can apply transform(node, position), animate positions, filter which nodes are animated and fit the viewport once to the result. nodeDimensionsIncludeLabels opts into label-sized dimensions where a layout's geometry calculations support it. Flow-specific layer assignment uses directed edges, minimum edge lengths and optional cycle removal before assigning ranks; its result is positions, so edge paths remain a style/render concern. force offers fresh randomized initialization or relaxation from current coordinates, overlap resolution and component tidying. Its CPU mode is the reproducible reference. A live GPU run owns the position column until readback; CPU position reads can be stale until completion.

#Grid

Layouts › Built-in layouts › Grid

Options, defaults and constraints for grid.

Grid places movable leaf nodes in rows and columns sized to the viewport or an explicit boundingBox. Defaults are fit true, padding 30, avoidOverlap true, avoidOverlapPadding 10, condense false, and packComponents false. Rows and columns are inferred unless fixed.

Option Default Contract
rows, cols omitted Requested grid row/column counts.
avoidOverlap true Keep node boxes apart; may overflow an undersized boundingBox.
avoidOverlapPadding 10 Extra model-space pixel gap around nodes when avoiding overlap.
condense false false uses the available box; true uses a compact grid.
position omitted Function of a node returning zero-based { row?, col? }; takes precedence for that node's cell.
sort omitted Comparator or sort mapping; controls cell order.
packComponents false When true, lay out and pack each component independently.

The bare full-graph call can use the bulk slot path. Callback options, sorting, component packing, scoped runs, or finisher options use the handle path.

#Preset

Layouts › Built-in layouts › Preset

Options, defaults and constraints for preset.

Preset writes supplied node positions. Defaults are fit true and padding 30; positions, zoom, and pan are omitted.

Option Default Contract
positions omitted Map from node id to { x, y }, or function of a node returning a position or nullish. Missing nodes keep their current positions.
zoom, pan omitted Applied when fit is false.

Each provided x and y must be finite or the run throws. Unknown ids, edge ids, and null positions in a map are ignored. Locked nodes hold their positions.

#Circle

Layouts › Built-in layouts › Circle

Options, defaults and constraints for circle.

Circle places nodes evenly on one ring. Defaults are fit true, padding 30, avoidOverlap true, avoidOverlapPadding 10, condense false, startAngle 3π/2, clockwise true, and packComponents false.

Option Default Contract
radius omitted Explicit model-space ring radius; otherwise computed from the box and node dimensions. Overlap avoidance may grow it.
startAngle 3π/2 Starting angle in radians.
sweep omitted Angular distance from first to last node; omitted means a full circle.
clockwise, counterclockwise clockwise true Boolean direction flags. If counterclockwise is supplied, it determines the direction.
sort omitted Comparator or node data sort mapping for ring order.
avoidOverlap true Grow the ring to keep node boxes from overlapping.
avoidOverlapPadding 10 Extra model-space pixel gap between boxes.
condense false Size the ring from nodes and required gaps rather than filling the box. An explicit radius still sets the starting radius.
packComponents false Draw one ring per component and pack the rings.

For a one-node ring, the node is placed at the center. A singleton component under packComponents is a point.

#Concentric

Layouts › Built-in layouts › Concentric

Options, defaults and constraints for concentric.

Concentric bins nodes into score levels and lays the levels on rings, higher scores nearer the center. Defaults are fit true, padding 30, startAngle 3π/2, clockwise true, equidistant false, minNodeSpacing 10, avoidOverlap true, concentric by degree, levelWidth as maxDegree / 4, and packComponents false.

Option Default Contract
concentric degree function Function of node, or numeric score mapping. Higher score goes closer to the center.
levelWidth maxDegree / 4 Function of the nodes returning the score span for a ring.
startAngle 3π/2 First ring angle in radians.
sweep omitted Angular sweep; omitted means a full circle.
clockwise, counterclockwise clockwise true Boolean direction flags. If counterclockwise is supplied, it determines the direction.
equidistant false Use equal radial distance between ring levels.
minNodeSpacing 10 Minimum model-space gap between node outsides.
avoidOverlap true Increase ring radii as needed to avoid node-box overlap.
width, height omitted Explicit layout-area dimensions; otherwise use the bounding box.
packComponents false Lay out each disconnected component independently and pack the rings.

Score mappings for concentric resolve over the full scope; with component packing, level bins are formed inside each component. levelWidth receives that component's nodes for those per-component runs.

#Breadthfirst

Layouts › Built-in layouts › Breadthfirst

Options, defaults and constraints for breadthfirst.

Breadthfirst assigns breadth-first depth levels from roots. Defaults are directed false, direction downward, circle false, grid false, spacingFactor 1.75, avoidOverlap true, avoidOverlapPadding 0, maximal false, acyclic false, and packComponents false. Parents derive from placed descendants.

Option Default Contract
roots inferred Collection or array of node ids. Selector strings are not accepted.
directed false Traverse edge direction when finding depths.
direction downward downward, upward, rightward, or leftward.
circle false Place depth levels on rings instead of rows.
grid false Lay out a DAG on an even grid; applies when circle is false.
depthSort omitted Comparator or node data sort mapping within a depth.
maximal false Move nodes down to their maximal depths in a directed graph; a cycle triggers a bail-out.
acyclic false Assert a directed graph is acyclic. Enables maximal-depth shifting and skips its cycle bail-out; use only when the scope is a DAG.
avoidOverlap true Separate node extents per rank and axis; false places center points.
avoidOverlapPadding 0 Extra model-space gap per body; spacingFactor supplies the usual extra air.
spacingFactor 1.75 Additional spacing factor for the rows/grid.
packComponents false Lay out each component as its own tree and pack the results.

When roots are omitted, directed traversal uses graph roots; undirected traversal chooses maximum-degree nodes in each component. With supplied roots, breadth-first traversal assigns reached nodes their depths; nodes outside that traversal are placed together in a new top-level depth.

#Random

Layouts › Built-in layouts › Random

Options, defaults and constraints for random.

Random scatters nodes uniformly within the viewport or boundingBox. Defaults are fit true, padding 30, and no seed.

Option Default Contract
seed omitted Finite number; its low 32 bits seed the generator. Same seed and graph order produce the same placement. Without it, Math.random is used.

Random is a useful starting placement for other layouts. A non-finite seed throws before placement.

#Radial

Layouts › Built-in layouts › Radial

Options, defaults and constraints for radial.

Radial lays out breadth-first trees in hierarchy-aware angular wedges. Each subtree occupies a contiguous sector. Defaults are fit true, padding 30, startAngle 3π/2, sweep 2π, clockwise true, avoidOverlap true, avoidOverlapPadding 10, condense false, weight leaves, and packComponents false.

Option Default Contract
roots inferred Collection or array of node ids; selector strings are rejected. Unset, use nodes with no incoming edge in each component; if a component has none, use its maximum-degree nodes.
startAngle 3π/2 Where the shared sweep begins, in radians.
sweep 2π Total angular sweep shared by the trees.
clockwise true Direction in which wedge allocation proceeds.
levelSpacing derived Ring gap in model pixels; an explicit value sets the initial spacing.
avoidOverlap true Grow ring radii to clear boxes without changing wedge angles.
avoidOverlapPadding 10 Gap between neighboring boxes.
condense false Size rings from node extents and gaps instead of the box; implies overlap avoidance.
weight leaves leaves or subtree; controls subtree wedge weight.
packComponents false Lay each component as an independent radial tree and pack the trees.

With one root, the root sits at the center. Multiple roots occupy the first ring. Nodes not reached from the supplied roots seed additional trees in scope order.

#Pack

Layouts › Built-in layouts › Pack

Options, defaults and constraints for pack.

Pack is a translation-only component re-pack for a drawing whose internal layout is already set. Defaults are fit true, padding 30, and componentSpacing 40. The largest component's center stays fixed; other component boxes are shelf-packed. It does not rotate or reshape components.

Option Default Contract
componentSpacing 40 Gap between packed component boxes.
componentGroup omitted Group callback over component descriptions.
componentOrder omitted Comparator for components in each group; otherwise largest first.
groupSpacing 3 × componentSpacing Gap between groups.

Locked nodes are left in place, and components with locked members pack using their free members alone. componentGroup and componentOrder must be functions or the run throws.

#Force

Layouts › Built-in layouts › Force

Options, defaults and constraints for force.

Force is a spring/electric simulation with degree-normalized edge springs, inverse-square repulsion and component-aware gravity. Defaults are a 60 model-pixel ideal edge length, repulsion 1, stiffness 0.6, gravity 1, decay 0.015, 1000 iterations, seed 1, randomize true, spectral initialization, executor auto, and avoidOverlap settle. Unwatched one-shot runs use a threshold of 2% of mean ideal edge length; animateLive/infinite runs use 0.1px when threshold is omitted.

Option Default Contract
edgeLength 60 Number, per-edge function, or numeric score mapping; resolved once at start.
repulsion 1 Pairwise repulsion strength.
stiffness 0.6 Degree-normalized spring stiffness.
gravity 1 Constant-magnitude pull toward each component anchor.
decay 0.015 Alpha annealing rate per iteration.
iterations 1000 Hard iteration cap for a finite run; ignored by infinite.
threshold context-dependent Maximum model-pixel displacement for settling. Omitted finite silent runs use 0.02 × mean ideal edge length; live/infinite runs use 0.1px.
seed 1 Numeric seed for placement.
randomize true Start from seeded positions; false relaxes current positions.
init spectral spectral or scatter. Only matters on a fresh randomized placement.
executor auto auto, cpu, gpu, or workers. See executor behavior below.
animate false Tween from the old positions to the settled result; viewport fit can run alongside.
animateLive false Stream positions during the simulation; takes precedence over animate.
infinite false Keep running and reheat on interaction/topology changes. stop() lands current positions without settle separation, re-pack, fit, or tween.
stepsPerFrame 3 Iterations advanced per frame under animateLive or infinite.
avoidOverlap true / settle false, true or settle for final separation; sim for per-tick sweeps; both for both. Infinite converts any enabled mode to sim.
avoidOverlapPadding 10 Model-space gap around each node box in overlap handling.
nodeDimensionsIncludeLabels false Include labels in overlap boxes.
componentSpacing 40 Model-space gap between component boxes in the final re-pack. Re-pack is skipped when a node is pinned or constraints are set.
tidyComponents true Give small components canonical shapes at settle; skipped for infinite or constrained runs and components that cannot be translated safely.
componentGroup, componentOrder omitted Group callback and order comparator for the settle re-pack.
groupSpacing 3 × componentSpacing Model-space gap between grouped component boxes.
boundingBox omitted Explicitly fit the settled field down, never up, into this box. Skipped for pinned or constrained runs.
nestingFactor 1.2 Multiplier per compound-boundary level crossed by an edge's ideal length.
gravityCompound 1.5 Compound centroid pull as a multiple of gravity.
alignment omitted Horizontal groups of node ids share y; vertical groups share x. Groups merge when they share a node. A locked node pins its group.
relativePlacement omitted Entries { left, right, gap? } or { top, bottom, gap? }; keeps the first id at least gap pixels before the second. Default gap is mean ideal edge length.

Executor auto chooses the GPU integrator when available for a flat rendered graph without force constraints; otherwise it uses a worker when the platform can construct one, then the in-thread CPU simulation. Compound or constrained runs use the CPU or worker path. GPU and worker runs are asynchronous. cpu is the in-thread deterministic reference and synchronous spelling. workers throws at start if a worker cannot be constructed; gpu throws when the graph, constraints, build, renderer, or device cannot provide a GPU integrator. GPU trajectories are not bit-for-bit stable between runs.

Alignment/relative-placement ids must exist. Placement cycles, malformed entries, and conflicting locked alignment coordinates throw before movement. Constrained runs use the CPU executor. avoidOverlap accepts only false, true, settle, sim, or both; other values throw. A sim sweep alone may not open a field denser than its node boxes allow; both adds the final settle separation. During a live GPU run, CPU position reads can be stale until readback at layoutstop/promise().

#Flow

Layouts › Built-in layouts › Flow

Options, defaults and constraints for flow.

Flow is a layered directed-graph layout. It computes node positions; edges route from their style. Defaults are direction downward, nodeSep 50, rankSep 60, edgeSep 10, network-simplex layering, thoroughness 7, minLength 1, edgeWeight 1, acyclic false, greedy cycle removal, componentSpacing 40, avoidOverlap true, and avoidOverlapPadding 0.

Option Default Contract
direction downward downward, upward, leftward, rightward.
nodeSep 50 Positive model-space pixel gap between node box sides along a rank; zero or negative values throw.
rankSep 60 Positive model-space pixel gap between ranks; zero or negative values throw.
edgeSep 10 Non-negative model-space pixels per overlapping taxi track added to a rank gap; zero leaves rankSep unchanged. Negative values throw.
layering network-simplex network-simplex, longest-path, or auto. auto uses longest-path beyond about 50k nodes.
thoroughness 7 Crossing-minimization effort from 1 through 10; outside the range throws.
minLength 1 Minimum rank span per edge; number, numeric score mapping, or edge function. Resolved spans are at least one rank.
edgeWeight 1 Straightening weight per edge; number, numeric score mapping, or edge function.
acyclic false Declare the graph acyclic and skip cycle removal.
cycleRemoval greedy greedy or dfs; dfs makes input order more influential.
rankConstraints omitted Id lists min (first rank), max (last rank), and same (shared-rank groups). Unknown ids, selector strings, and contradictions throw.
componentSpacing 40 Model-space gap between disconnected component boxes.
avoidOverlap true Separate by node extents; false places points and makes nodeSep/rankSep center-to-center.
avoidOverlapPadding 0 Extra model-space gap around bodies; nodeSep and rankSep otherwise own the spacing.

flow rank constraints accept node ids only, never selector strings. Pair flow with a style route such as curve-style taxi when right-angle edges are wanted; the layout itself does not route edges.

#Layout handle

Layouts › Layout handle

Run, await, stop, cancel or reheat a layout.

#Stop, cancel and scope

stop() asks the implementation to stop and keeps the positions it reached. cancel() abandons a run; after the implementation settles, the wrapper restores the starting positions and rejects the run promise with CancelledError. Destroying the core cancels its active layout. A layout created from a collection receives that collection as its scope; whole-graph layouts see the current graph.

#layout.run()

// Start the layout
layout.run(): this

Start the layout. Emits a layoutstart event on the core, calls impl.run( ctx) and awaits it if it returns a promise (the shape a GPU-resident layout needs).

The lifecycle fires exactly once per run either way: an impl that finishes through ctx.layoutPositions() lets the finisher emit a layoutready event/layoutstop, and one that writes positions directly has them emitted here instead.

Returns this

this layout, for chaining; await promise() for completion

Example

layout.run();
await layout.promise();
console.log(cy.nodes().length); // 3

Example graph and handle setup

#layout.promise()

// Resolves at this run's layoutstop (immediately when never run); rejects with CancelledError when the run was cancelled — by cancel() or by cy.destroy()
layout.promise(): Promise<void>

Resolves at this run's layoutstop (immediately when never run); rejects with CancelledError when the run was cancelled — by cancel() or by cy.destroy().

Returns Promise<void>

the run's promise

Example

layout.run();
await layout.promise();
console.log(cy.getElementById('b').position('x')); // 40

Example graph and handle setup

#layout.stop()

// Ask the layout to stop early, by calling the impl's optional stop()
layout.stop(): this

Ask the layout to stop early, by calling the impl's optional stop(). An impl without one simply runs to completion. Once the impl has settled and only its finisher tween is in flight, the tween stops where it got to and layoutstop fires now, as a built-in's stop() does.

Returns this

this layout, for chaining

Example

layout.run();
layout.stop();
await layout.promise();
console.log(cy.nodes().length); // 3

Example graph and handle setup

#layout.cancel()

// Abandon the run in flight — the alternative to stop(), which keeps what stands
layout.cancel(): this

Abandon the run in flight — the alternative to stop(), which keeps what stands. The impl is asked to cancel() (or stop() when it has no cancel), and once its run settles the scope's nodes go back to where run() found them, a tween under way is dropped where it is, the viewport is left alone, layoutstop fires with cancelled: true, and promise() rejects with CancelledError. A layout that is not running is unchanged.

Returns this

this layout, for chaining

Example

const handle = cy.layout({ impl: { async run() { await Promise.resolve(); } } });
handle.run();
handle.cancel();
let cancelled = false;
try { await handle.promise(); }
catch (error) { cancelled = error instanceof cytoscape.CancelledError; }
console.log(cancelled); // true

Example graph and handle setup

#layout.reheat(alpha?)

// Heat a running layout back up (118.3), by calling the impl's optional reheat()
layout.reheat(alpha?: number): this

Heat a running layout back up (118.3), by calling the impl's optional reheat(). A force layout's infinite run ticks only while its field is moving and reheats itself on a drag, a moved node and an added or removed element; this is for a change it cannot see — an edge length that changed under a data mapping, a style that resized the boxes. An impl without one ignores it.

Parameters
NameDescription
alpha: number?

the temperature to restore; the force layout's default is 0.3, d3's drag convention

Returns this

this layout, for chaining

Example

const force = cy.layout({ name: 'force', infinite: true, executor: 'cpu' });
force.run();
force.reheat(0.5);
force.stop();
await force.promise();
console.log(cy.nodes().length); // 3

Example graph and handle setup

#Lifecycle events

Layouts › Lifecycle events

Observe layoutstart, layoutready and layoutstop on the core.

#Animations

Animations use immediate channels and handles rather than a queue.

#Channels, concurrency and sequencing

Animations › Channels, concurrency and sequencing

Sequence handles through promises and understand overlapping channels.

Animations start immediately and have no queue. Animations on disjoint channels can run together. When a new animation overlaps a running animation's channels, the older one stops in place, its values freeze, and the new tween captures from those values. To sequence work, wait for a handle's promise and then create or play the next handle.

const node = cy.getElementById('a');
const move = node.animation(
{ position: { x: 180, y: 60 } },
{ duration: 300, easing: 'ease-in-out' },
);
await move.play();
await node.animation(
{ style: { 'background-color': '#d73027' } },
{ duration: 180 },
).play();

#Targets and easing

Animations › Targets and easing

Choose supported element or viewport targets and declarative easing.

Collection animations target model-space position, the supported style channels and compound collapse state. Core animations target viewport state such as zoom and pan. Today the animatable style channels are opacity, selected node fills/borders, edge line color, node width/height, edge width, compound padding and font size, alongside position. Consult the API reference for the exact target shape and which channels apply to nodes, edges, parents or core.

Easing is declarative: use the documented named forms, a CSS cubic-bezier(… ) or linear(… ), or a spring( bounce ) specification. Easing callback functions are rejected so animation curves do not depend on whether a run is offloaded to a GPU. Colors interpolate in OKLab.

#Animation handle

Animations › Animation handle

Play, pause, resume, reverse and observe an animation handle.

#Animation handles

animate() is the chaining form and returns the core/collection. animation() builds a handle without starting it. Handles expose play(), stop(), promise(), playing(), pause(), resume(), reverse() and read-only progress(). promise() resolves when the animation completes or is stopped; it is not a boolean completion-state query. Progress cannot be assigned or scrubbed.

#ani.play()

// Start immediately
ani.play(): Promise<void>

Start immediately.

Returns Promise<void>

resolves when the animation completes (or is stopped)

Example

await ani.play();
console.log(ani.progress()); // 1

Example graph and handle setup

#ani.stop(jumpToEnd?)

// Stop in place, or at the targets with jumpToEnd — the whole animation, whatever elements it spans
ani.stop(jumpToEnd?: boolean): void

Stop in place, or at the targets with jumpToEnd — the whole animation, whatever elements it spans. Through the manager, so a GPU-driven one releases its batch.

Parameters
NameDescription
jumpToEnd: boolean?Default: false

apply the final values instead of freezing

Returns void

Example

ani.play();
ani.stop(true);
console.log(ani.playing()); // false

Example graph and handle setup

#ani.promise()

// The completion promise
ani.promise(): Promise<void>

The completion promise.

Returns Promise<void>

resolves when the animation completes (or is stopped)

Example

ani.play();
await ani.promise();
console.log(ani.progress()); // 1

Example graph and handle setup

#ani.playing()

// Whether the animation is running and not paused
ani.playing(): boolean

Whether the animation is running and not paused.

Returns boolean

true while playing

Example

console.log(ani.playing()); // false

Example graph and handle setup

#ani.pause()

// Pause: freeze in place; the paused span leaves the timeline
ani.pause(): AnimationHandle

Pause: freeze in place; the paused span leaves the timeline.

Returns AnimationHandle

this handle, for chaining

Example

ani.play();
ani.pause();
console.log(ani.paused()); // true
ani.stop();

Example graph and handle setup

#ani.resume()

// Resume a paused animation with the clock shifted
ani.resume(): AnimationHandle

Resume a paused animation with the clock shifted.

Returns AnimationHandle

this handle, for chaining

Example

ani.play();
ani.pause();
ani.resume();
await ani.promise();
console.log(ani.progress()); // 1

Example graph and handle setup

#ani.reverse()

// Swap the tween's ends with elapsed remapped
ani.reverse(): AnimationHandle

Swap the tween's ends with elapsed remapped.

Returns AnimationHandle

this handle, for chaining

Example

ani.reverse();
await ani.play();
console.log(ani.playing()); // false

Example graph and handle setup

#ani.progress()

// Elapsed fraction of the duration (read-only — no scrubbing)
ani.progress(): number

Elapsed fraction of the duration (read-only — no scrubbing).

Returns number

the fraction in [0, 1]

Example

console.log(ani.progress()); // 0

Example graph and handle setup

#ani.paused()

// Whether the animation is paused
ani.paused(): boolean

Whether the animation is paused.

Returns boolean

true while paused

Example

console.log(ani.paused()); // false

Example graph and handle setup

#Stylesheet transitions

Animations › Stylesheet transitions

Animate sheet changes with the supported transition properties.

Stylesheet transitions use transition-property, transition-duration, transition-delay and transition-timing-function. Their transitionable set matches the documented animated channels. A sheet update supplies the new target style and animates the listed properties; the same channel concurrency rules apply. See styling for how declarative styles are resolved.

#Extensions

The supported extension seam is direct layout implementation.

#Direct layout implementations

Extensions › Direct layout implementations

Pass a class or object with run(ctx); no global registry is needed.

#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

Extensions › Layout context

Read scoped graph data and write positions through the tracked helpers.

#Scope

Extensions › Layout context › Scope

Read the core, options and lazily materialized 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

#Columnar reads

Extensions › Layout context › Columnar reads

Read slots, positions, endpoints and topology without unnecessary collections.

#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

Extensions › Layout context › Bounds

Read layout bounds and node dimensions.

#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

Extensions › Layout context › Writing positions and finishing

Use tracked writes and finish to apply shared layout options.

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

Extensions › Supported extension scope

Layout context support does not promise core, collection or renderer registries.

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

#Performance

Choose efficient graph operations and understand measured scale and rendering limits.

The graph model is built around a CPU-canonical columnar model. Hot graph fields are stored in typed arrays, arbitrary data is kept in sidecars, and an id index supports direct lookup. This avoids creating and retaining one mutable JavaScript object per field access. Collections are the public convenience layer; APIs that consume or produce columns/slots can avoid materializing a handle for every element when operating on large graphs.

#Loading and mutation

Performance › Loading and mutation

Choose bulk input and mutation paths.

For bulk input, prefer the constructor's elements option, a columnar payload or streamed cy.load() chunks over a loop of one-element mutations. The classic object format is convenient at application boundaries; convert it to columnar form when allocation and transfer volume matter. load() applies chunks progressively and lets a rendered graph draw between them.

Use cy.batch() when several writes can share one stylesheet application. It defers style work to the outermost end of the batch; reads of derived style values may be stale inside it. cy.patch() can preserve the state of surviving elements during data refresh, but it still scans and applies a diff. Its cost depends on id overlap and on which fields changed, so compare it with recreation for the application's actual workload instead of treating it as a universal faster path.

At 100k elements, in milliseconds, with recreate rows that vary by ~40% run to run because of GC placement:

Id overlap Recreate (wire) App-side diff patch (wire)
90% 167.4 265.6 96.2
80% 236.5 314.4 145.2
70% 161.2 369.2 197.9
50% 168.1 498.4 310.6
10% 230.2 777.7 522.2

A payload equal to the state costs 18–24 ms, one scan. The crossover is about 70% id overlap: above it a patch is cheaper and keeps every survivor's state; below it, a refresh with no state worth keeping should reload (recreating is 1.8× cheaper at 50% and 2.3× at 10%). A diff written over the public API is slower than recreating at every overlap.

#Queries and collections

Performance › Queries and collections

Avoid unnecessary materialization and repeated scans.

Structured query objects test indexed flags and data columns without making a predicate closure and element handle for every candidate. Use getElementById() for a direct id lookup. Query objects are deliberately less expressive than an arbitrary function; predicates remain available when the application needs custom logic. A predicate pays the per-element callback and handle cost, so use the structured form for common state/data filtering when it expresses the rule.

The layout context exposes slot-oriented reads/writes for custom implementations. Built-ins use these paths where suitable, and setPositions() batches the tracked position updates. Directly modifying a public live column is not a supported optimization; it can skip renderer dirty notifications and leave the displayed graph stale.

#Algorithms and layouts

Performance › Algorithms and layouts

Choose execution lanes within each method’s limits.

Algorithm execution policy is per algorithm. Some algorithms are synchronous CPU routines; whole-graph routines may return a cancelable promise and select between CPU, worker and GPU executors. An explicit executor may reject when the build or environment does not provide it. 'cpu' is the reproducible reference for APIs that offer it. 'auto' is a policy choice, not a promise that the GPU always wins or that all algorithms have a GPU implementation. Read each method's API entry before relying on result timing or numerical details.

The force layout can move its simulation to a worker or GPU. During a live GPU force run, the position column is GPU-owned and CPU reads are stale until the layout's readback at completion. Its live stream also does not emit one CPU position event per node. Await the run or read at layoutstop when final positions or CPU-side persistence matter. GPU trajectories can vary in floating-point order; the CPU executor is the repeatable reference.

#Rendering costs and limits

Performance › Rendering costs and limits

Understand rendering costs and geometry limits.

Rendering uses the GPU for geometry, labels, visibility and edge picking. Labels, mapped styles, edge routes, arrows and compound bounds add work that a node-only graph does not have. Measure the features and graph shapes the application actually uses. Headless mode avoids the renderer entirely, but headless text dimensions are estimates; a rendered font atlas provides the glyph measurements used for exact label layout.

Avoid benchmarking only constructor time or total graph throughput. A useful profile separates conversion, first visible chunk, settled layout, interaction, dirty style updates, export/readback, memory and allocations. Profile on your users' target devices with representative graph data and styles.

#Scale limits

Performance › Scale limits

Plan graph sizes around rendering and device limits.

Measured on an RX 580 through Chromium, with n = m/4 and each scene in a fresh browser (benchmark/scale-ceiling.mjs):

Scene (nodes × edges) Init VRAM JS heap GPU frame Outcome
1,048,576 × 4,194,305 4.0 s 1,357 MB 2.47 GB 23.8 ms rendered
2M × 8M 7.9 s 1,466 MB 3.24 GB 48.4 ms rendered
4,194,240 × 16,776,960 17.9 s 2,926 MB 6.02 GB 106.2 ms rendered
4,194,240 × 16,776,961 17.9 s — 6.02 GB — cy.ready rejects with GpuUnfitError
1M × 3M, labelled 4.4 s 1,306 MB 1.81 GB 32.8 ms rendered
2.5M × 2.5M, labelled 8.3 s 1,247 MB 2.94 GB 30.2 ms rendered, labels degraded

The ceiling is 16,776,960 elements per group, and the same number of glyphs per label stream, which is about 2M labelled nodes. It is one dispatch's reach, 65,535 workgroups × 256, rather than a memory limit. A node slot costs 164 bytes and an edge slot 132. Custom polygons have no such guard: 8-point polygons reach their pool's limit at about 1M nodes.

What cannot fit or failed to allocate stops drawing once, with a gpuerror carrying degraded, and the frame stays valid. The order is:

  1. 'labels': a glyph stream past its limit stops uploading and every label is no longer drawn. Label dimensions remain available to graph operations.
  2. 'charts', 'images', 'curves': an oversized blob is replaced by a placeholder and its pass is skipped.
  3. 'gradients': gradients draw solid.

A refused core column has nothing to degrade to. The scene holds its last frame ('frames'), a pending pick or count answers null and an export rejects, until a re-mount.

#Diagnostics

Performance › Diagnostics

Read core statistics to inspect the current graph and renderer.

#cy.stats()

// The renderer's frame statistics, or null when headless
cy.stats(): RendererStats | null

The renderer's frame statistics, or null when headless. The snapshot carries the frame timings, cache hit rates and pass counters — note that cpuFrameMs is encode/submit cost only (submission is fire-and-forget), so reconcile fps against gpuFrameMs.

Returns RendererStats | null

a RendererStats snapshot, or null on a headless instance

Example

console.log(cy.stats()); // null

Example graph and handle setup

#Feature availability

Check which features are available and find alternatives for unsupported operations.

Use this page to check features that differ from other graph libraries or are not available in this version. Use the API reference for supported methods and options.

#Overlapping membership

Feature availability › Overlapping membership

Use compound parents for single-parent containment.

A node can have at most one compound parent. To represent membership in multiple groups, store group identifiers in application data or model the memberships as edges. They do not create additional compound parents.

#Annotations and editing

Feature availability › Annotations and editing

Use labels and compound nodes, with application-owned editing controls.

Use node labels and compound nodes to describe parts of a graph. There is no separate annotation collection for leaders, background regions, dividers or legends. Build editing controls and legends in your application.

#Rendering and styles

Feature availability › Rendering and styles

Find supported styles and edge routes.

Use the style property reference for supported label, font and line-breaking options. Additional label corner styling and CJK line breaking are not available.

Load page fonts with CSS @font-face and select the family with the stylesheet font-family property. When using renderer: { worker: true }, supply font faces through renderer.fonts; the worker does not inherit the page's font registrations.

Persistent edge bundles are not supported. Choose from the available edge routes to draw edges.

#Layout assessment and export

Feature availability › Layout assessment and export

Wait for layouts and export images as PNG or JPEG.

Await a layout's promise() or listen for layoutstop to know when it has finished. Completion does not include a constraint assessment report.

Image export supports PNG and JPEG. SVG export and export resource-warning reports are not available. See Image export for the supported options.

#Runtime scope

Feature availability › Runtime scope

Find supported runtimes and package installation instructions.

See Supported environments for runtime requirements. Bun supports headless graph work without WebGPU or browser rendering. Deno is not supported. To try this unreleased version, follow the local build instructions in Getting started.

#Migration

Port applications from earlier releases and find archived documentation.

Cytoscape.js 4 changes how applications query, style and render graphs. Rendering requires WebGPU, selector strings become query objects or predicates, and some v3 APIs have no replacement. This guide shows how to update a v3 application and which behaviour to re-check after porting.

v4 is not released yet. For production use cytoscape@3 and js.cytoscape.org.


#Contents

  1. Before you start
  2. The five changes that touch every app
  3. Selector recipes
  4. Style properties that moved
  5. Events
  6. Behaviour to re-check
  7. Constructor options
  8. Layouts and extensions
  9. Worth adopting once you have ported
  10. Not ported

#Before you start

Rendering requires WebGPU. With a container, the factory throws synchronously when navigator.gpu is missing, and cy.ready rejects when no adapter can be acquired. There is no canvas fallback — v4's renderer is a WebGPU pipeline, not a mode of v3's.

Use headless mode for analysis without a canvas. Omit container to use the graph model, styles, CPU layouts and algorithms in Node or another supported runtime. Rendering, image export and GPU execution have additional requirements.

Pick the entry for the job. The package ships three builds; each has TypeScript declarations. Choose according to whether your application needs rendering, GPU compute or CPU-only analysis:

// everything: the WebGPU renderer, the pointer, the GPU executors (browsers)
import cytoscape from 'cytoscape';
// headless and CPU-only: CI, Node services, edge isolates (a Cloudflare
// Worker) — no renderer or WebGPU code
import cytoscape from 'cytoscape/headless';
// headless with the GPU executors: compute-only hosts with WebGPU —
// the WGSL algorithm kernels and a device host for `executor: 'gpu'` force
// runs, no renderer
import cytoscape from 'cytoscape/headless-gpu';

The slim builds say so when asked for what they lack, never silently: a container (or cy.mount()) throws this build has no renderer — import 'cytoscape', and on cytoscape/headless an explicit executor: 'gpu' — algorithm or force layout — rejects this build has no GPU executors — import 'cytoscape/headless-gpu' or 'cytoscape' ('auto' just runs on the CPU). Their factories take HeadlessOptions, the options minus the renderer- and pointer-only fields.

cytoscape/gpu is gone. The pre-release alias of the full entry was removed before alpha, because beside cytoscape/headless-gpu it read as "the GPU build" while resolving to everything. Import cytoscape.

Types ship, and they are the fastest porting tool you have: a v3 app run through tsc against v4's declarations will surface most of this document as compile errors before you run anything. cy.on( 'tap', 'node', h ) is the exception worth knowing — the selector string is a runtime rejection.


#The five changes that touch every app

#1. There are no selector strings

v4 has no selector parser and no dialect of one. The language is replaced by three mechanisms, split by role:

// v3
cy.$( '#a' );
cy.nodes( ':selected' );
cy.filter( '[weight > 0.5]' );
cy.on( 'tap', 'node', handler );
// v4
cy.$id( 'a' ); // id -> the O(1) id index
cy.nodes( { selected: true } ); // query object -> a columnar scan
cy.nodes( { data: { weight: { gt: 0.5 } } } ); // data conditions, same scan
cy.on( 'tap', ele => ele.isNode(), handler ); // predicate delegation
  • Query objects answer whole-graph questions and compile to per-group flag tests answered in one pass over the columns. Keys: group, selected, parent, child, and data. An unknown key throws — a typo must not silently match everything.
  • Predicates are plain functions and cover everything richer. In off() they compare by identity, so removing a delegated handler takes the same ( events, predicate, handler ) triple that added it.
  • cy.$() works — over the new forms: it is a plain alias of cy.filter(), so cy.$( { selected: true } ) and cy.$( ele => … ) do what you expect, while cy.$( 'node' ) still throws with the replacement named. cy.$id() / cy.getElementById() / cy.byId() is the id lookup.
  • cy.collection() takes no arguments and throws if given any — v3's collection( eles ) building form is not supported. Build with union() over the empty accumulator, or query with cy.$( query ).

Passing a selector string anywhere throws with the replacement named — at the query compiler, at the twelve collection methods that take another collection, and at event delegation. Replace selectors at each call site.

#2. There are no classes

addClass/removeClass/toggleClass/hasClass/flashClass and class selectors are gone. The role classes played — user-defined state that drives filtering and styling — belongs to data() plus mappers:

// v3
node.addClass( 'highlighted' );
// style: { selector: '.highlighted', style: { 'background-color': 'red' } }
// v4
node.data( 'highlighted', true );
// style: { nodes: { 'background-color': {
// case: [ { when: { data: 'highlighted', eq: true }, then: 'red' } ],
// else: '#666'
// } } }

The style updates automatically: a data write re-derives exactly the mapped channels that depend on the written key.

The commonest class in v3 apps — the hover highlight, a .faded class on everything outside the hovered neighbourhood — is not a class or a data write in v4 but one call, because writing every element on each hover does not scale well on large graphs:

// v3
cy.on( 'mouseover', 'node', e => {
cy.elements().not( e.target.closedNeighborhood() ).addClass( 'faded' );
} );
cy.on( 'mouseout', 'node', () => cy.elements().removeClass( 'faded' ) );
// style: { selector: '.faded', style: { opacity: 0.15 } }
// v4
cy.on( 'mouseover', ele => ele.isNode(), e =>
cy.emphasize( e.target.closedNeighborhood() ) );
cy.on( 'mouseout', ele => ele.isNode(), () => cy.unemphasize() );
// style: { core: { 'dim-opacity': 0.15 } } — and, to style the set itself,
// { when: { emphasized: true } } on any prop

The rest is dimmed by the renderer as one composite, not by a style, so style( 'opacity' ) on a dimmed element reads its own value.

#3. The stylesheet is an object, not a list of selector blocks

// v3
style: [
{ selector: 'node', style: { 'background-color': '#666' } },
{ selector: 'edge', style: { width: 3 } },
{ selector: ':parent', style: { 'background-color': '#eee' } }
]
// v4
style: {
nodes: { 'background-color': '#666' },
edges: { width: 3 },
parents: { 'background-color': '#eee' },
core: { 'selection-box-color': '#ddd' }
}

Four groups, fixed: nodes, edges, parents (overlaying nodes for compound parents) and core (v3's core-selector props). Per-element variation is declarative — a mapper, not a block:

// v3: a style function
{ selector: 'node', style: { width: ele => ele.data( 'size' ) * 2 } }
// v4: a scale mapper
{ nodes: { width: { data: 'size', range: [ 10, 80 ] } } }
// v4: a conditional
{ nodes: { shape: { case: [ { when: { data: 'type', eq: 'gene' }, then: 'ellipse' } ],
else: 'rectangle' } } }

#Styling element state

v3 puts state in selectors — :selected, :active, :locked, :grabbed. v4 has no selectors, so state is a condition on the same case mapper:

// v3
{ selector: 'node:selected', style: { 'background-color': '#0169D9' } }
// v4
{ nodes: { 'background-color': {
case: [ { when: { selected: true }, then: '#0169D9' } ],
else: '#999',
} } }

The states are selected, selectable, locked, grabbed, grabbable, active, hovered, plus the structural parent, child, childless and orphan. Each takes a boolean, so v3's negative selectors — :unselected, :unlocked, :free, :ungrabbable, :unselectable, :inactive — are the same key with false. AND a state with a data condition through the array form: when: [ { selected: true }, { data: 'w', gt: 5 } ].

You get v3's affordances without writing any of this, and you replace them the same way you would in v3. v4's default stylesheet carries v3's :selected, :parent:selected and :active blocks, spread before your own — so a sheet that names background-color replaces the selection colour along with it, precisely as a v3 sheet does, and overlay-opacity: 0 turns the press highlight off.

Not carried over: :compound (its node meaning is exactly parent; its edge meaning has no v4 spelling), :loop / :simple, and :visible / :hidden / :transparent — those are computed from style, so a rule conditioned on one would be circular. :animated, :backgrounding, :removed and :inside have no styling form either.

A style group written as a function throws. Replace it with a group object whose properties use constants or declarative mappers.

The per-element bypass works, spelled as in v3: ele.style( name, value ), the object form and removeStyle( name? ) set and clear id-keyed constants that beat every sheet rule. Two differences from v3 worth knowing while porting: the canonical form is the stylesheet's bypasses section ({ bypasses: { id: { prop: value } } }), which exports from cy.json() where v3 silently drops bypasses on export — and a full cy.style( sheet ) replaces the live bypasses like any other section (v3's survive sheet swaps; spread the exported sheet to keep them). Values are constants only — mappers remain the per-element mechanism for anything data-driven. For the list-valued curve props (control-point-distances/-weights, segment-distances/-weights/-radii), which accept constants only and reject mappers, the bypass is the porting path for a v3 sheet that gave edges their own arrays — a per-edge array is a per-element constant, so for those props the bypass is the only per-edge spelling.

CSS-string stylesheets and cytoscape.stylesheet() are gone with the block form.

#4. Animations sequence by promise, not by queue

// v3
node.animate( { position: p1 } ).animate( { position: p2 } ); // queued
// v4
await node.animate( { position: p1 } ).promise();
node.animate( { position: p2 } );

Animations on disjoint channels run concurrently (a position tween and an opacity fade compose). Starting one that overlaps a running animation's channels stops the older one in place — its promise resolves, its values freeze, and the new one captures from there.

There is no queue option, and the spelling throws (there is no queue to opt out of). The v3 step callback is out too: use cy.on( 'render', … ) plus promises. stop() lost its clearQueue argument — it is stop( jumpToEnd ) now.

eles.animate() is one animation over the elements, where v3 made one per element: node.stop() on one of them stops the whole animation, and so does an overlapping animation started on one of them. An animated layout's tween is the exception: its nodes stay individually addressable as v3's per-node tweens were. node.stop(), a new position animation on the node, lock() and remove() detach that node alone and the rest of the tween runs on. Two answers differ from v3: a node locked mid-tween holds where it got to and unlock() does not resume it (v3's step skips a locked node and picks the tween up again on unlock), and a node mid-tween cannot be grabbed (v3 let the drag and the tween fight over it) — stop it first.

#5. Removed elements are terminally dead

remove() tombstones the slot, bumps its generation and returns it to the free list; the next add() may recycle those bytes. So a removed element is not readable and not restorable:

  • restore(), clone(), copy() — gone
  • cy.json( obj ) (the import form) — throws; cy.json() export works

Only the handle's cached id() and group() survive removal, which is what keeps remove handlers and predicates working. Re-adding from definitions you kept is the app's job — exported element JSON round-trips through cy.add().

If what you used cy.json( obj ) for was applying the next server response to the live graph, v4 has a call for exactly that: cy.patch( payload ) reconciles a fresh payload by id — adds what is new, removes what is gone (or keeps it, with { mode: 'merge' }), replaces the data of what survives — in one batch, and returns { added, removed, updated }. Selection, positions the payload does not carry, listeners, scratch and running animations survive on every element it keeps. It restores no session state: the viewport, the stylesheet and graph data are never touched.


#Selector recipes

v3 selector v4
cy.$( '#a' ) cy.$id( 'a' )
cy.$( 'node' ) cy.nodes()
cy.$( 'edge' ) cy.edges()
cy.$( '*' ) cy.elements()
cy.$( 'node:selected' ) cy.nodes( { selected: true } )
cy.$( ':unselected' ) cy.elements( { selected: false } )
cy.$( ':parent' ) cy.nodes( { parent: true } )
cy.$( ':childless' ) cy.nodes( { childless: true } ), or { parent: false }
cy.$( ':child' ) cy.nodes( { child: true } )
cy.$( ':orphan' ) cy.nodes( { orphan: true } ), or { child: false }
cy.$( ':locked' ), :unlocked cy.elements( { locked: true } ) / { locked: false }
cy.$( ':grabbed' ), :free cy.elements( { grabbed: true } ) / { grabbed: false }
cy.$( ':grabbable' ), :ungrabbable cy.elements( { grabbable: true } ) / { grabbable: false }
cy.$( ':selectable' ), :unselectable cy.elements( { selectable: true } ) / { selectable: false }
cy.$( ':active' ), :inactive cy.elements( { active: true } ) / { active: false }
cy.$( '[weight > 0.5]' ) cy.nodes( { data: { weight: { gt: 0.5 } } } )
cy.$( '[type = "gene"]' ) cy.nodes( { data: { type: 'gene' } } )
cy.$( '[type != "gene"]' ) cy.nodes( { data: { type: { ne: 'gene' } } } )
cy.$( '[^weight]' ), [?weight] a predicate: cy.nodes( n => n.data( 'weight' ) == null )
cy.$( '.cls' ) cy.nodes( { data: { cls: true } } ) — classes are data now
cy.$( 'node[x], edge[y]' ) (comma) two queries plus .union()
eles.filter( 'node' ) eles.filter( { group: 'nodes' } ) or eles.nodes()
node.neighborhood( '.foo' ) node.neighborhood().filter( pred )
cy.on( 'tap', 'node', h ) cy.on( 'tap', ele => ele.isNode(), h )

Data-condition operators: eq, ne, lt, lte, gt, gte, in. A bare value means eq; keys within one object are AND-ed; a missing value fails every operator, ne included.

The state keys are the same ones a case mapper's when takes — anything you can style on, you can query for. :visible, :hidden, :transparent, :animated, :backgrounding, :removed, :inside, :loop, :simple and :compound have no query form; use a predicate.


#Style properties that moved

v3 registers 291 property names (properties plus aliases). v4 accepts 164 of them — 7 only in the core group — and rejects 127. Of the rejections, 96 are v3's numbered pie-N-* / stripe-N-* props, which became one chart family. The remaining 31 are the table below.

A rejected property name throws at cy.style() with "The style property 'x' is unsupported".

v3 property v4
z-index, z-compound-depth, z-index-compare dropped outright. Draw order is structural: compound parents, then edges, then leaf nodes, then labels; slot order within a stream
pie-* (48), pie-size, pie-hole, pie-start-angle chart: 'pie' + chart-values, chart-colors, chart-size, chart-hole, chart-start-angle
stripe-* (48), stripe-size, stripe-direction chart: 'stripes' + the same family, plus chart-direction
Multivariate heat charts chart: 'heat-strip' or 'radial-heat', chart-values, and a required shared chart-scale with an explicit domain and colour range
Signed bar charts chart: 'bar', signed chart-values, required chart-domain, and optional independent chart-scale or chart-colors
content label
min-width-bias-left/-right, min-height-bias-top/-bottom dropped. min-width/min-height clamp centred — v3's default-bias behaviour
display show() / hide() for the structural tier; the visibility style prop for paint-only invisibility
position not a style property — use ele.position()
text-metrics eles.labelBoundingBox()
box-select-labels the core option boxSelectionIncludesLabels
box-selection the core option boxSelectionMode ('contain' | 'overlap'); its third value 'none' is the events property
edge-text-rotation text-rotation (a keyword autorotate, or a number of radians on any label)
control-point-distance control-point-distances (plural — v4 has no singular alias)
segment-distance, segment-weight, segment-radius segment-distances, segment-weights, segment-radii
background-blacken dropped. Compute the shade in a colour mapper's range
bounds-expansion dropped. Bounds are computed correctly instead
outside-texture-bg-color/-opacity dropped with textureOnViewport
mid-source-arrow-fill, mid-target-arrow-fill dropped. Mid arrows are always filled
border-cap, border-join dropped. Dash ends are perpendicular cuts by construction; border-style, border-dash-pattern and border-dash-offset all port

Chart data retains authored slot order up to 255 values. Pie and stripe values remain absolute fractions that clamp at 1; heat and bar values may be signed. Null and non-finite values keep their positions, do not contribute to shared automatic bounds, and render with chart-missing-color (transparent by default for heat, a gap for bars). chart-domain sets bar geometry bounds separately from a bar's optional colour scale. Shared auto endpoints use the supplying stylesheet definition's finite values; they do not normalize each node. Use cy.legend() for resolved colour and geometry domains, then render labels and axes in the application.

Also renamed or re-scoped without being rejected:

  • Gradients keep their property names: v3's background-fill (solid | linear-gradient | radial-gradient) with background-gradient-stop-colors/-stop-positions/-direction, and line-fill with line-gradient-stop-colors/-stop-positions, keep their names and values. What changes: at most 5 stops an element, and stop lists are constants-only (the fill kind and direction take mappers); stops interpolate in sRGB, as v3's canvas does.
  • padding-left/-right/-top/-bottom port — in the parents sheet group only, constants only, each a number of px or 'N%' resolved per padding-relative-to; an unset side takes the uniform padding. Naming one in a nodes or edges block throws the group rule ("belongs to the parents group"), not "unsupported".
  • font-family, font-style, font-weight are global constants. The glyph atlas holds one face, so these are effectively per-instance; a change resets the atlas and re-lays out every label. Per-element fonts are out of scope. Mappers on them throw.
  • The no-dash legacy shape spellings throw: roundrectangle, cutrectangle, concavehexagon. Use round-rectangle, cut-rectangle, concave-hexagon. This applies in all three enums that took them — the node shape, overlay-shape/underlay-shape, and text-background-shape.
  • Channel opacities fold at write time. background-opacity, border-opacity, line-opacity and text-opacity fold into the stored channel alpha; element opacity stays the master multiplier. Reading them back gives the folded value.

#Events

The vocabulary is curated. v4 emits the drag-state family (grab/grabon/drag/free/freeon/dragfree/dragfreeon), the device-normalized family (tapstart, tapdrag, tapend, tap, taphold, dbltap, onetap, tapselect/tapunselect, tapdragover/tapdragout, the cxt* family), the viewport gestures (dragpan, scrollzoom, pinchzoom, and scrollpan under wheelBehavior: 'pan'), the official pointer family (pointerdown/pointermove/ pointerup/pointercancel/pointerover/pointerout), and the model events (add, remove, data, position, select, unselect, style, layoutstart/layoutready/layoutstop, patch, batchstart/batchend, loadstart/loadchunk/loadready/loadstop, render, destroy, error, mouseover/mouseout, box/boxstart/boxend/boxselect, devicelost/devicerestored, gpuerror, move/moveout).

Dropped names register and then never fire, silently. This is the porting hazard worth reading twice:

cy.on( 'mousedown', h ); // registers fine. Never fires.
cy.on( 'click', h ); // registers fine. Never fires.
cy.on( 'vmousedown', h ); // registers fine. Never fires.
cy.on( 'touchstart', h ); // registers fine. Never fires.

They cannot be rejected, because custom events are supported API — ele.emit( 'myEvent' ) must keep working, so a name cannot be validated against a list. Port event names from the vocabulary, not by trying them. pointer* is the modern spelling of the raw mouse/touch re-emits; mouseover/mouseout do still fire.

There are no namespaces. A type is matched whole, so 'tap.ns' is one literal name that emit( 'tap' ) does not reach and off( 'tap.ns' ) removes on its own. Register and remove each literal name separately.

event.preventDefault() is browser-level only, by design. originalEvent is populated, so the call reaches the browser's default — but no v4 code reads isDefaultPrevented(), so it cannot stop a tap from selecting or a grab from starting. Gesture defaults are controlled by the explicit toggles (autounselectify, autoungrabify, boxSelectionEnabled, userPanningEnabled, …, and per-element ungrabify()/unselectify()) instead.

Bubbling works as in v3 for compounds: origin → ancestors → core, with event.target the originator and stopPropagation() (or returning false) halting the walk. The one deviation is within a phase, where listeners fire in plain registration order.


#Behaviour to re-check

These compile and run, but behave differently. They are the things a ported app trips on after everything else works.

Area v3 v4
Default curve-style bezier straight — opt into bezier explicitly. It is the perf-first default at v4's target scales
Default text-valign top bottom — v4 keeps its below-node placement
Draw order z-index, then a whole-scene comparator sort structural, permanently. A grabbed node does not pop above later-inserted nodes
cy.elements() order mixed insertion order nodes then edges
Position precision Float64 Float32 (~7 significant digits)
bezier bundling same same — a lone edge under curve-style: bezier still renders straight; only parallel edges fan
Colour animation per-channel sRGB OKLab, matching colour mappers
Edge overlay-padding / underlay-padding the band is 2 × padding wide — a padding under half the line width draws a halo narrower than the line, i.e. hidden width + 2 × padding, the edge's own extent plus the padding, as the node overlay reads it — so the halo always shows. To match a v3 sheet's band, set v4's padding to v3's minus half the edge width. The ends, corners and reach match v3: round caps, round joins that blend once, and an overlay that reaches over a hollow head
border-style: double under an edge erases to the page (destination-out) the stripe shows whatever the scene drew beneath the node — an edge passing under the border shows through the gap where v3 punches to the background
Label box (text-background-*, text-border-*) the border strokes even with text-background-opacity: 0; a round-rectangle box has a 2 px corner; the box's width is the text's measured width rounded up the box draws only when text-background-opacity > 0 (give a border-only box an opaque-enough background, or match the page colour); the round box keeps v4's auto radius (min(w, h) / 4, at most 8 px); the width is not rounded, so a box can be up to 1 px narrower. The border's placement, its dash patterns and double are v3's
spring() easing spring( tension, friction ) spring( bounce ) — one number; 0 is critically damped
Custom easing functions accepted throw. A closure cannot cross to the GPU; cubic-bezier() and linear() cover any drawable curve
Label bounding boxes opt-in boundingBox() includes labels by default; opt out with { includeLabels: false }
breadthfirst without a boundingBox spread over cy.extent() in model coordinates, so the drawing scaled with the zoom at the moment it ran spread over the viewport in pixels, as grid, circle, concentric and radial are; identical at zoom 1
Arrow sizing max( (13.37w)^0.9, 29 ) the same formula
triangle-cross arrowhead accepted as a separate edge-width bar throws as an unsupported arrow shape; migrate to triangle-tee, whose bar uses max(0.1 × arrowSize, edgeWidth) and keeps its front at -0.4 × arrowSize
Hollow triangle-tee / circle-triangle end arrows component outlines supported; their parts are outlined independently and coverage is combined once
outerWidth() with a border includes the miter overshoot plain border-inclusive outerHalf, so parent boxes can sit sub-pixel smaller
Compound auto-sizing can include labels reads child body extents by default; compound-sizing-wrt-labels: 'include' adds their labels
:selected / :parent:selected default-sheet blocks any later block beats the same rule, as a { when: { selected: true } } condition in v4's default stylesheet — so naming background-color yourself still replaces it, exactly as in v3
Comparing elements from two instances answered, inconsistently — same() was false but union() of 2 + 2 gave 2 and difference() gave 0 throws. Element identity is a slot in one store, so v4 refuses rather than inventing a cross-instance identity
The expensive whole-graph algorithms synchronous async — pageRank, floydWarshall, betweennessCentrality, closenessCentralityNormalized, markovClustering, affinityPropagation, kMeans, kMedoids, fuzzyCMeans and hierarchicalClustering return promises; await the call, then use the result exactly as in v3
pageRank's dampingFactor d, applied to the teleport only — it behaved as α = 1/(2 − d); default 0.8 the textbook α, as NetworkX's alpha; default 0.85. Ranks differ; pass 1 / (2 − d) to reproduce a v3 run. Outside (0, 1] throws
bellmanFord, undirected, with a negative edge no negative cycle — it never relaxed back over the edge that reached a node hasNegativeWeightCycle: true: the edge walked both ways is a 2-node cycle, as in NetworkX. Distances are then unbounded; positive-weight and directed runs are unchanged
Undirected betweennessCentrality counts each pair twice, so path a–b–c gives 2 for b counts each pair once, as NetworkX and igraph do: a v3 score is twice v4's. Directed scores and betweennessNormalized are unchanged
pageRank on an undirected graph always follows source → target, so ranks depend on how each edge is stored undirected by default: each edge is walked both ways, as in NetworkX and igraph. Ranks differ; pass directed: true to reproduce a v3 run
Classic closeness (harmonic: false) 1/Σd, and 0 for every node once any node is unreachable (n − 1)/Σd, with the Wasserman–Faust correction on a disconnected graph, as NetworkX's default. On a connected graph, divide by n − 1 to reproduce a v3 score. The harmonic default is unchanged
hierarchicalClustering threshold merges while the closest pair is strictly under it merges at exactly threshold too, as SciPy's fcluster and R's cutree. Results differ only when a merge distance equals the threshold, which is common on integer attributes
markovClustering maxIterations default 20 default 100, as Python markov_clustering and R MCL. Runs that converged sooner are unchanged; pass maxIterations: 20 for the old cap
A graph larger than the GPU can hold grows until the browser runs out of memory cy.add() throws cytoscape.GpuUnfitError when the mounted renderer's device could not bind or dispatch over the grown tables — before anything is added, so the graph is unchanged; cy.load() and cy.patch() refuse the same way, and cy.ready rejects with it for a graph built headless and mounted on a device too small for it. A buffer the device refuses, or one the renderer declines, fires gpuerror and degrades — labels first, then charts and images, then gradients — rather than blanking the canvas
Cancelling a whole-graph algorithm not possible — the call blocks the promise carries cancel(): a pending run rejects with cytoscape.CancelledError (error.name === 'CancelledError') and answers true once; a run that has already completed — every 'cpu' run has, inside the call — answers false and its result stands
layout.stop() ends the run where it is, keeping the positions unchanged: an animate: true tween stops where it stands and layoutstop fires immediately — and layout.cancel() is the other ending: the run is abandoned, a tween under way is dropped where it is, the nodes go back to where run() found them, the viewport is left alone, layoutstop still fires with cancelled: true, and layout.promise() rejects with CancelledError. cy.destroy() cancels every run still open the same way
Container resize call cy.resize() after resizing the container automatic: a ResizeObserver re-measures and emits a resize event once per change, so the call is only needed where no observer can see the change; an existing call is harmless (the observer finds the size applied and emits nothing more)
A wheel over a canvas that will not zoom the page scrolls (v3 prevents default only when panning and zooming are both enabled) the same — v4 prevents default only on a wheel it acts on, and wheelBehavior ('zoom', 'pan', 'modifier-zoom') says which wheels those are: 'modifier-zoom' is the embedded-map idiom — the page scrolls past the graph and ctrl/meta-wheel (or a trackpad pinch) zooms
Gesture event details an edge press emits tapstart on the edge; a right press can target an edge; a release emits tap and the selection events before freeon, free, dragfreeon, dragfree; dbltap fires on any second tap inside the debounce window; tapend goes to the element under the release point; a shift/ctrl/meta press on a node grabs it; a drag from a locked node does nothing; the first wheel ticks zoom slowly while v3 samples the device an edge press starts on the core (pointerdown, tapstart) and the edge takes the release and the tap once the GPU pick answers; a right press targets a node or the core; a release frees first (free, freeon, dragfree, dragfreeon), then taps; dbltap needs the same target; tapend goes to the pressed element; a multiple-select-key press boxes and grabs nothing; a drag from a locked node pans; every wheel tick zooms by the same factor.
Pointer cursors none — v3 set no CSS cursor at all, and apps wrote container.style.cursor from mouseover/mouseout the canvas writes them (grab/grabbing, pointer, crosshair). Idle over background stays '', so the v3 recipe still shows through where v4 is silent; an app whose own cursor code now fights the defaults passes pointerCursors: false
force with animate: false on a rendered flat graph synchronous — positions readable on the next line async — the run settles at layoutstop / promise(); executor choice is availability-driven (headless runs stay synchronous)
force on a rendered compound or constrained graph, or a rendered page without a WebGPU adapter synchronous async — the CPU simulation runs on a worker under the default executor: 'auto', so the main thread stays free; read positions at layoutstop / promise(), or say executor: 'cpu' for the in-thread run (bit-identical positions either way)
cose / force with animate: true v3 cose: 'during' streams the run, 'end' tweens to the result animate: true tweens to the result like every other layout; animateLive: true streams the run
cose nodeOverlap / nodeRepulsion multipliers on a point repulsion; overlap avoidance was a side effect of strength force separates the node boxes exactly at the settle under avoidOverlap (default true, labels on request); avoidOverlap: 'sim' makes the sim itself keep them apart with a separation sweep after every tick (opt-in; the settle's pass is cheaper for a one-shot run), 'both' does both
cose / force with boundingBox v3 cose stretched the node centres to fill the box, up or down, size-blind; bodies could overhang it force scales down only so every body lies inside, then centres the drawing (as in flow); a pinned node or constraints hold it back, as they hold the component re-pack
a locked node under position() / a layout v3: held by both held by writes, tweens and every layout, and treated as an obstacle for overlap avoidance
nodeDimensionsIncludeLabels default false default false; set true to keep labels apart in every built-in. Spacing uses each pair's dimensions rather than v3's largest-footprint-times-1.75
hierarchicalClustering mean linkage silently broken — an unset size field made the first mean merge write NaN distances, degenerating the clustering works: sizes are tracked, so mean is the weighted-average linkage both libraries always documented

The whole-graph tier is async, and executor picks where it runs. The ten algorithms above return promises because they can run on the GPU: { executor: 'auto' } (the default) uses the GPU where an adapter exists and the input is large enough to win, 'cpu' forces the bit-reproducible reference implementation, and 'gpu' forces the kernels (rejecting where WebGPU is unavailable, so a silent slow path cannot masquerade as a fast one). GPU results may differ from CPU results in float detail — WGSL is f32 — so a caller that needs run-to-run identical numbers says executor: 'cpu'. 'workers' is the fourth value: the per-source-parallel families — betweennessCentrality (weighted and not), unweighted closenessCentralityNormalized, heatKernel and randomWalkWithRestartProximity — run on a pool of plain workers (Node worker_threads, browser Workers; nothing to configure, the worker entry is inside the bundle), and 'auto' takes that pool wherever the GPU does not run — from 128 nodes for weighted betweenness and RWR, 256 for unweighted betweenness and the heat kernel, 512 for closeness, each a measured crossover — which in headless Node means every run of those families above its crossover now uses the pool; sparse closeness takes the pool even where a GPU is present, since it measured faster there. The pool's results are bit-stable across runs and pool sizes, and bit-identical to 'cpu' for closeness, heat and RWR; betweenness agrees with 'cpu' to f64 rounding but not to the bit, so a caller that compares betweenness scores bit-for-bit across versions says executor: 'cpu'. 'workers' also runs the families the pool cannot partition — pageRank, katzCentrality, floydWarshall, weighted closenessCentralityNormalized, triangleCount, neighborhoodSimilarity, motifCensus, simRank, effectiveResistance, markovClustering, affinityPropagation — on one worker, and 'auto' takes that lane wherever neither the GPU nor the pool runs, from a per-family size (32–32,768 nodes): the calling thread stays free for the run's whole length, and the answer is bit-identical to 'cpu' (the same kernel function runs on both sides). The same holds for kMeans, kMedoids, fuzzyCMeans and hierarchicalClustering given a named distance (and, for hierarchical, a 'min' / 'max' / 'mean' linkage); 'workers' rejects a custom distance function or a per-pair linkage, which is called inside the loop and so runs on the calling thread, and the one-column seed forms (heatDiffusion, randomWalkWithRestart). kMeans reads its testCentroids without writing the updated centroids back into the caller's arrays, as v3 did. The traversal tier (bfs, dfs, dijkstra, aStar, bellmanFord, kruskal, the components algorithms, degree centrality and the single-root closenessCentrality) stays synchronous: those run per-root in tight loops, and no GPU formulation would beat their slot-native CPU walks. Only the whole-collection closenessCentralityNormalized moved to the async tier — it is the O(n³) all-pairs computation, exactly what the tier exists for.

v4 also adds eight algorithm families v3 never had, on the same async executor contract: triangleCount() (per-node triangles, local clustering coefficients, transitivity), neighborhoodSimilarity() (pairwise Jaccard / cosine / overlap coefficients over neighbor sets), katzCentrality() (attenuated walk counting), randomWalkWithRestart() and randomWalkWithRestartProximity() (network propagation from a seed set, and the all-pairs proximity matrix), heatDiffusion() and heatKernel() (heat-kernel propagation, exp(−t·L)), effectiveResistance() (the graph as a resistor network, with commuteTime), simRank() (recursive neighborhood similarity) and motifCensus() (the sixteen-class triad census; '030T' is the feed-forward loop). Nothing to migrate — they are new surface — but note they read the collection as a simple graph: parallel edges collapse (summing weights where weights are read), loops are excluded, and the triangle/heat/resistance families ignore direction outright.

State is a condition, not a selector. See "Styling element state" above: :selected, :active, :locked and the rest are when conditions on a case mapper, and the affordances v3 gives you for free are entries in v4's default stylesheet that your own block replaces — the same precedence v3 has.


#Constructor options

Unknown options are ignored at runtime, deliberately. { motionBlur: true } and { totallyUnknownOption: 1 } both construct happily and round-trip through cy.options(). The typo guard is TypeScript's excess-property check against CytoscapeOptions — v4 does not replicate at runtime what the build already checks. (Note the boundary: excess-property checking applies to object literals, so options assembled into a variable first are widened and pass.)

Dropped, and therefore ignored: hideEdgesOnViewport, textureOnViewport, motionBlur, motionBlurOpacity — canvas-era degradation modes that compute culling and the adaptive render scale solve without degrading output.

New, and worth setting: boxSelectionMode, boxSelectionIncludesLabels, wheelSensitivity, wheelBehavior, desktopTapThreshold, touchTapThreshold, tapholdDuration, multiClickDebounceTime, pixelRatio, pointerCursors, and the renderer block (renderScaleMin/renderScaleMax, labelMinPx, imageMinPx, imageMaxSize).


#Layouts and extensions

Built in: grid, preset, circle, concentric, breadthfirst, random, radial — a hierarchy-aware radial tree (each subtree takes a contiguous angular wedge sized by its weight; new in v4) — pack — a re-pack of the disconnected components where they stand, grouped and ordered (new in v4) — force — a GPU-native force-directed layout that animates live at 100k nodes — and flow — a Sugiyama-class layered layout (dagre's use case: network-simplex ranking, weighted crossing minimization, Brandes–Köpf coordinates; new in v4). flow replaces the dagre extension for most uses: it emits node positions only, designed to pair with curve-style: taxi so edges route themselves and stay routed when nodes are dragged.

Choose a built-in when replacing these v3 layout extensions:

v3 extension or app engine v4 built-in
fcose, cose-bilkent, cola, euler, spread, d3-force, G6 gForce, Cosmos force — alignment and relative-placement constraints, locked nodes, edgeLength mapping, live simulation with infinite, and GPU execution where supported
dagre, elk (layered), klay, biological-flow flow — direction: 'rightward' for a left-to-right flow
G6 radial radial
layout-utilities separateComponents the pack layout (the components re-packed where they stand, grouped and ordered), packComponents: true on circle / concentric / grid / breadthfirst / radial (one drawing per component, packed), force's settle re-pack, or ctx.packComponents in an extension layout

cose is not ported. Its option surface and per-iteration structure are different from force; use force and review its options when porting. cy.layout({ name: 'cose' }) throws, listing the built-ins. The cose behaviours a compound app relies on have force counterparts: compound members cohere about their parent (gravityCompound), edges crossing compound boundaries take elevated ideal lengths (nestingFactor, v3's rule and default), and disconnected components are packed into rows at the end (componentSpacing, v3's option name). A fresh run also seeds from a spectral draft (init: 'spectral', the default — fCoSE's approach), which is what untangles chains and separates clusters at scale. force also supports these fcose constraints: alignment ({ horizontal, vertical } id-array groups; a locked node pins its group) and relativePlacement ([{ left, right, gap? } | { top, bottom, gap? }]), with fixed nodes spelled lock(). Constrained runs take the CPU executor, so at fcose-typical sizes they behave like fcose; validation throws at start on unknown ids, placement cycles, and contradictory locked members.

animate means the same thing on force as everywhere else: the sim settles silently, then the nodes tween into place with the viewport fitting alongside — v3 cose's animate: 'end'. The streaming run v3 spelled 'during' is animateLive: true. Executor choice is availability-driven either way: a flat rendered graph with a device hands integration to the GPU, so animate: false no longer runs synchronously on the main thread — the run settles at layoutstop / promise(), and a caller reading positions on the next line must await one of those. animate: false still shows nothing until convergence: the silent run integrates off-screen and lands the settle in one write. Headless instances remain the synchronous spelling. The settle also separates overlapping node bodies (avoidOverlap, default true; include labels with nodeDimensionsIncludeLabels: true), which v3 cose never did.

breadthfirst on a graph of several components draws its trees as blocks — each rank ordered tree-first, each tree a column band, the singletons a block of rows, the bands wrapped into shelves — where v3 interleaved the trees across the whole width; one component is v3's picture exactly. packComponents: true on the five discrete layouts lays each component out on its own and packs the drawings.

There is no extension registry. No cytoscape.use(), no string registration, no global state. An extension layout is an import you pass in:

import RowLayout from './row-layout.js';
cy.layout( { impl: RowLayout, ...options } ).run();

The implementation is a class or object with { run( ctx ), stop?() }, where ctx is a LayoutContext — columnar-first (nodeSlots(), live positions() views, O(1) degreeOf, bulk setPositions) with handles still reachable at ctx.eles. ctx.packComponents( spacing? ) is v3 layout-utilities' separateComponents in one call: it re-packs the laid-out disconnected components into non-overlapping rows, for any extension layout that positions components independently. LayoutContext, LayoutImpl and CustomLayout are exported types. Core, collection and renderer extension points stay out for 4.0.

Layout lifecycle events fire on the core, exactly once per run; layout instances are not emitters.


#Worth adopting once you have ported

  • Columnar and binary loading. cytoscape.toColumnarElements( json ) converts the definition form; cytoscape.serializeElements() produces one little-endian ArrayBuffer that options.elements and cy.add() accept directly. On a 19.6k-node / 465k-edge graph that is 9.2 MB and ~5 ms against 28.6 MB and a ~100 ms JSON parse.
  • cy.patch( payload ) for data refreshes — replaces the hand-written remove / add / data() diff an app runs on every re-query, in any of the three input forms. At 100k elements and 90% id overlap it is several times cheaper than destroy-and-recreate (see Performance for the numbers and the overlap below which recreating wins), and a payload equal to the state costs one scan and fires no element event.
  • cy.clone( { container, style, follow: true } ) for a second view — a minimap, an overview, a side-by-side comparison. v3 apps drew a navigator from exported images or ran a second instance kept in sync by hand; a v4 clone is a full instance of its own (its own sheet, viewport, selection and events) that follow keeps current by a throttled id-keyed patch. Selection is deliberately not synced — link the two instances' events if the app wants linked brushing.
  • Data-driven layout mappings. The five layout params that take per-element values accept serializable objects beside v3's function forms: { data, scale?, range?, invert?, default? } on force.edgeLength and concentric.concentric (the column's extent normalized through 'linear' | 'log' | 'sqrt' into the range; invert: true maps large scores to short edges), and { data, order? } on grid.sort, circle.sort and breadthfirst.depthSort (missing values last, ties on the id). Functions stay as escape hatches; the objects are the canonical spellings, resolved once at layout start.
  • taxi-turn: auto. Under curve-style: taxi every fan-out takes its own line in the rank gap, assigned from live positions, so a reader can follow an edge through the gap; taxi-track chooses the grouping (source, target, or family for a genealogy) and taxi-track-spacing the distance between lines. Pair it with a background-coloured line-outline-* casing: v4 draws the casing per edge in v3's order, so a crossing reads as a gap.
  • The JSON schemas — cytoscape/schemas/*.json, for a stored sheet, layout configuration or graph document: point an editor or a CI step at them. A v3 sheet fails stylesheet.schema.json on its first selector block, and a v3 property v4 dropped fails by name, so validating a store of saved sheets finds the ones still to port without loading any of them.
  • Iteration. Collections are iterable — for..of, spread and Array.from( eles ) — and cy.add() takes any iterable of definitions, so a generator can feed it directly. v3's collections were not iterable either; this is new surface, not a parity fix. cy.add( eles ), v3's restore idiom, throws (see "Removed elements are terminally dead").
  • Mapper domains. An explicit domain keeps a data write O(changed); 'auto' is a live extent and pays O(n) only when a write actually moves it. Pin domain when a stream grows its own extent.
  • Style transitions — transition-property/-duration/-delay/ -timing-function per sheet group, tweening whenever a restyle changes a stored channel.
  • cy.compact() (alias cy.gc()) after a big removal, though an automatic trigger already fires at safe boundaries.
  • cy.pick( x, y ), which resolves node hits synchronously on the CPU. It is exact — the pointer gestures additionally apply v3's findNearestElement hit halos (8/24 rendered px around edges and their arrowheads for mouse/touch, 2/8 around nodes), so a press can land where pick answers null; the halo belongs to the gesture, not the API. When elements overlap it answers leaf, then edge, then compound parent — the reverse of v4's structural draw order, and contract. v3 ordered the same three by z-index/z-compound-depth, neither of which v4 has, so an app that relied on a deeply nested v3 parent out-ranking a shallower edge will now get the edge.
  • cy.viewportCounts() — how many nodes and edges the renderer actually draws in the next frame, after culling, visibility and level of detail; async (a GPU readback), null headless. v3 had no equivalent (#2283); the geometric approximation apps used, cy.elementsInBox() over cy.extent(), still works and still ignores what is too small to draw.
  • cy.nodeAt( x, y ) (alias cy.pickNode) — the node under a rendered point, answered synchronously on the CPU, where cy.pick() is async because an edge hit is a GPU question. v3 never had a public form (#1209); apps reached into the renderer's findNearestElement. Nodes only, exact (no halo), the same leaf-over-parent order as pick; headless it computes from the viewport at a device-pixel ratio of 1 rather than answering null.

#Not ported

These v3 APIs are unavailable or have different replacements:

  • classes, selector strings, style functions
  • Removed methods: cy.forceRender(), cy.batchData() (a plain batch() over data() writes), cy.mutableElements() (it was elements() by another name), onRender/offRender (use cy.on( 'render', … )), and the bind/unbind/listen/unlisten listener aliases — the event surface follows Node's EventEmitter spellings (on/off/once/addListener/removeListener), plus pon
  • Internal methods, excluded from the public TypeScript API: cy.renderer(), instanceString() and the silentPosition(s)/silentShift writes still work but left the typed surface (@internal); cy.stats() is the public frame-stats snapshot that replaces cy.renderer().stats()
  • z-index and companions; sortByZIndex, zDepth
  • restore/clone/copy, cy.json() import
  • event namespaces; the vmouse* aliases and raw mouse/touch re-emits
  • cy.notify()/noNotifications() (the renderer is dirty-driven)
  • renderTo
  • per-element font-family; viewport-fixed labels
  • the canvas-era performance options

Also unavailable:

  • cytoscape.warnings() — v4 keeps its fail-loudly contract whole: errors throw, the few recoverable conditions warn on the console, and there is no toggle over either.
  • Functional preventDefault() for v4's own gesture defaults — the explicit toggles are the gesture-control surface; preventDefault() reaches the browser's default only.

See the v4 documentation for task guides and the complete API reference.

#Styling changes

Migration › Styling changes

Check styling exclusions.

#v3 properties outside this v4 surface

This is not a compatibility list for all v3 styling. v4 does not provide selector blocks, style functions, background-blacken, border-cap, border-join, image bounds-expansion, endpoint *-or-label forms, per-side min-width or min-height bias props, or per-element font faces. Some names throw as unsupported; others have no v4 property spelling. Use the tables above and the stylesheet schema for supported property names and values.

#Layout changes

Migration › Layout changes

Check layout exclusions.

#Options not carried forward from v3

The list above is the current v4 built-in surface. The v3 null layout and its layout-handle event-emitter methods are not among these built-ins. The direct custom-layout implementation contract is described in Layouts; this page does not add a registry, import name, or undocumented built-in.

#Animation changes

Migration › Animation changes

Replace animation queue controls.

#Differences from v3

delay(duration) is a no-op timed tween that composes with other channels; delayAnimation(duration) returns a handle for promise sequencing. These methods belong to collections. The v3 viewport members cy.delay() and cy.delayAnimation() are unavailable. Use collection delay methods only for elements. clearQueue() has no v4 counterpart because there is no queue. Use stop()/handle methods to stop work that is actually running.

#Query changes

Migration › Query changes

Replace selector strings with query objects or predicates.

#Migrating selector strings

*

Coming from v3? The cy.$ alias remains for symmetry and compatibility, but it takes the same query/predicate inputs as cy.filter(). A selector string such as 'node:selected' throws with a migration explanation. cy.getElementById(id) is the direct O(1) id lookup for a single id; it avoids building a query.

Core event delegation also uses a predicate, not a selector. For example, cy.on('tap', node => node.isNode(), handler) runs only for events whose target passes that function. Element collection events bind to each element in the receiver. See events for event ownership and removal.