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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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' →...`).
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)`.
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).
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.
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`.
One data() column, index-aligned with the payload: a plain array
(holes/undefined = absent), a Float64Array (NaN = absent), or a
dictionary-encoded string column.
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.
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.
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.
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.
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).
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.
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.
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()`.
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.
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`.
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'`.
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).
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.
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.
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.
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.
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.
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`.
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.
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).
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.
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.
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).
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.
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.
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
npminstall
npmrunbuild
npmrunbuild:types
Then install the local package in your application (replace the path):
Terminal window
npminstall/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.
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:
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:
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:
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.
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:
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.
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.
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.
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.
// 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 flightcytoscape.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.
// A graph or algorithm input exceeds the GPU device's limitscytoscape.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.
ReturnsGpuUnfitError
Example
// Catch an algorithm or layout error before choosing a CPU fallback.
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.
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 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.
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.
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.
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.
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.
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.
// Create a graph instance for queries, analysis, layouts and optional interactive rendering — Full entrycytoscape<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 entrycytoscape<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 entrycytoscape<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.
the instance options; every field is optional, and an omitted container is what selects headless mode
Fields of options
Name
Description
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).
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.
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).
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).
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
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.
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.
// 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.
// (Re)attach a renderer to a containercy.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.
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
// 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.
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.
// Add elements to the graph and return them as a collectioncy.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.
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 }).
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
// Remove elements from the graphcy.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().
// 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 didcy.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.
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 }).
'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.
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
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.
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).
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).
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.
// 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 arrivescy.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.
{ fit, padding }: fit once to the first chunk (default: on for an initial load), and that fit's padding
Fields of options
Name
Description
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())
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
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.
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.
// Reclaim unused storage after removing many elementscy.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.
// 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.
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.
// Run fn inside a startBatch()/endBatch() paircy.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
Name
Description
fn: () => void
the mutations to batch; its return value is discarded
// Get all nodes and edges, or only those matching a querycy.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.
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.
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.
// Live, visible elements contained in the model-coordinate box (corners in any order): the box-selection query, answered by one columnar scancy.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.)
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.
// 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 rejectcy.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.
// Check whether style is enabledcy.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.
// Whether any node currently has a parentcy.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.
Returnsboolean
true when the graph has at least one parent/child relation
// Whether an element with this id exists, via the O(1) id index — cheaper than getElementById( id).nonempty() because no handle is materializedcy.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.
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
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.
// Bind a direct listenercy.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.
// Bind a delegated listenercy.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().
// Remove a direct listenercy.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.
// Emit an event on the corecy.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.
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
// 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().
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.
// Zoom about a positioncy.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
Name
Description
options: ZoomOptions
the level and the position to keep fixed
Fields of options
Name
Description
level: number
New zoom level, clamped to the graph's zoomRange().
// Pan and zoom so the given elements fill the viewportcy.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.
// The model-space rectangle currently visible, as { x1, y1, x2, y2, w, h } — the inverse of the pan/zoom transform applied to the viewport boxcy.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.
// The rendered (on-screen) viewport rectanglecy.renderedExtent(): Extent
The rendered (on-screen) viewport rectangle.
ReturnsExtent
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
// 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.
Returnsthis
this core
Example
// After the graph container changes size, refresh viewport dimensions.
// 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.
// Find the topmost node at a rendered position, measured in CSS pixels from the container's top-left cornercy.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.
// Count visible nodes and edges at each level of detail in the current viewportcy.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.
// Read whether every node is locked (immovable) regardless of its own locked flag — the graph-wide overridecy.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.
// Set whether every node is locked (immovable) regardless of its own locked flag — the graph-wide overridecy.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.
// Read whether every node is ungrabbable regardless of its own grabbable flagcy.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.
// Set whether every node is ungrabbable regardless of its own grabbable flagcy.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.
// Check whether box selection includes labelscy.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.
// Include or exclude labels in box selectioncy.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.
// 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.
// 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.
// 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).
// 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).
// 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.
// 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.
// 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-wheelcy.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 notpreventDefault()ed, so the page scrolls in every 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-wheelcy.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 notpreventDefault()ed, so the page scrolls in every mode.
// Emphasize the given elements and dim the rest of the graphcy.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.
// Animate the viewport (pan/zoom) over duration mscy.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
Name
Description
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
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.
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.
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).
// Like animate, but returns a handle with play/stop/promise — the viewport counterpart of eles.animationcy.animation(opts: AnimateOptions): AnimationHandle
Like animate, but returns a handle with play/stop/promise — the viewport counterpart of eles.animation.
Parameters
Name
Description
opts: AnimateOptions
as animate; the animation does not start until play()
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.
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.
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).
// Make a layout over the whole graphcy.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.
{ 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
Name
Description
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.
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.
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)
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.
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)
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
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 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.
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
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
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)
// Install a stylesheetcy.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().
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 (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).
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.
ReturnsStyleEngine
the style engine (also reachable as the return value when setting, so calls chain)
// Read the application's shared mapping and chart metadatacy.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.
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.
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.
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.
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
// Serialize elements (definition form or columnar form) into one transferable/fetchable ArrayBuffercytoscape.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.
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
Name
Description
columnar: true
discriminant so the loader can tell the forms apart
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 }).
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)
ReturnsArrayBuffer
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
// Deserialize a serializeElements buffer (or a view over one) back into the columnar elements formcytoscape.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.
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)
// Export graph elements and graph-level data as a binary buffercy.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.
ReturnsArrayBuffer
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
// Export a plain-object snapshot containing elements, stylesheet, viewport, interaction settings and graph-level datacy.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
Name
Description
flat: boolean?
when true, elements export as one flat array instead of { nodes, edges }
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.
// 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.
// Export the rendered graph as a PNGcy.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.
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)
// 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).
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)
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.
// Make an independent instance holding a copy of this graph — the way to show one graph in two places, e.gcy.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.
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.
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).
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).
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.
what the box-selection gesture counts as selected: 'contain' (default)
takes only elements wholly inside the band; 'overlap' takes
anything the band touches.
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
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.
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
// Create an empty collection bound to the same coreeles.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.
// 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).
ReturnsRecord<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
// Whether the first element has been removed from the graphele.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.
// 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).
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.
// The union of the two collections, dedupedeles.union<OtherData = Data>(other: Collection<NodeData, EdgeData, OtherData>): Collection<NodeData, EdgeData, Data | OtherData>
// The elements in exactly one of the two collectionseles.symmetricDifference<OtherData = Data>(other: Collection<NodeData, EdgeData, OtherData>): Collection<NodeData, EdgeData, Data | OtherData>
The elements in exactly one of the two collections.
// The subset matching the criterioneles.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.
// Get all dataele.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.
ReturnsIfTyped<NodeData, EdgeData, Data | undefined, unknown>
the first element's data — the collection's shape when typed — or undefined when the collection is empty
// Get data by key — Built-in fieldele.data(key: FirstClassKey): IfTyped<NodeData, EdgeData, string | undefined, unknown>// Get data by key — Application fieldele.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.
// Set several data fieldseles.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.
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.
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
// Set a node's parent or an edge's endpoints without changing its id or dataeles.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.
// Read the first element's width in model pixels: a node's content width, excluding padding and border, or an edge's stroke widthele.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.
// Read the first element's height in model pixels: a node's content height, excluding padding and border, or an edge's stroke widthele.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.
Node padding. Leaves have no padding (no compound-free padding prop); parents answer the resolved auto-bounds padding.
Returnsnumber | 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
// The model-space box enclosing every element of the collectioneles.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.
// 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 endpointeles.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).
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
// Get the first edge's source arrow position in model coordinatesele.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.
// Get the first edge's target arrow position in model coordinatesele.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.
// 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).
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.
// The edge's segment points (model coords): defined for segments and taxi edges (taxi derives its points), undefined otherwiseele.segmentPoints(): Position[] | undefined
The edge's segment points (model coords): defined for segments and taxi edges (taxi derives its points), undefined otherwise.
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.
// Pannable elements are not draggable, so pannable overrides grabbableele.grabbable(): boolean
Pannable elements are not draggable, so pannable overrides grabbable .
Returnsboolean
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
// 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.
// Lock these elements against movementeles.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.
// 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.
Returnsboolean
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
// Hide these elements structurallyeles.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.
// Whether the first element is in the current emphasis — the set the last cy.emphasize( eles) namedele.emphasized(): boolean
Whether the first element is in the current emphasis — the set the last cy.emphasize( eles) named.
Returnsboolean
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()
// Set style by nameeles.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().
// Like style(), but with length props (width, height, border-width, font-size) scaled into rendered (on-screen) px by the zoomele.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
Name
Description
name: string?
a property name; omit for the whole group
Returnsunknown
the rendered-space value, or the whole group's props
// 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).
Returnsnumber | 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
// The space tier: shown elements occupy space — they join bb/fit and size their compound parents — even when visibility: 'hidden' keeps them from renderingele.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.
Returnsboolean
whether the element occupies space — this can differ from visible(), which is the paint tier
// 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.
Returnsstring | 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
// Listen for events on each element of this collectioneles.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.
// 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().
// Animate these elements' style and/or position to explicit targets over duration ms, easing the normalized timeeles.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
Name
Description
opts: AnimateOptions
targets (position, style, or collapsed for compound parents; viewport forms apply on cy.animate), duration, easing, delay, complete
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.
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.
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?
Returnsthis
this collection, for chaining; use animation() when you want the handle
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.
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.
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).
// 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).
// 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).
// 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 floweles.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
Name
Description
layout: object
the layout instance the lifecycle events carry as event.layout; it is not called back, only reported
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.
the layout options, as cy.layout(); eles is set to this collection
Fields of options
Name
Description
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.
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.
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)
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.
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)
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
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 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.
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
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
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)
// 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 scaneles.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.
// The endpoint nodes of every edge in this collection, dedupedeles.connectedNodes(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>
The endpoint nodes of every edge in this collection, deduped.
// The immediate outgoing neighbourhood: the edges leaving these nodes plus the nodes they point ateles.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.
// The immediate incoming neighbourhood: the edges arriving at these nodes plus the nodes they come fromeles.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.
// The open neighbourhood: the incident edges and the nodes on their far ends, ignoring edge direction, excluding the collection's own elementseles.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.
// The open neighbourhood plus this collection's own nodeseles.closedNeighborhood(criterion?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>
The open neighbourhood plus this collection's own nodes.
// 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).
// Everything that reaches these nodes by following incoming edges, transitivelyeles.predecessors(criterion?: FilterLike<NodeData, EdgeData>): Collection<NodeData, EdgeData>
Everything that reaches these nodes by following incoming edges, transitively.
// The edges connecting this collection's nodes with others, in either directioneles.edgesWith(others: Collection): Collection<NodeData, EdgeData, EdgeData>
The edges connecting this collection's nodes with others, in either direction.
// The edges running from this collection's nodes to others — edgesWith() restricted by directioneles.edgesTo(others: Collection): Collection<NodeData, EdgeData, EdgeData>
The edges running from this collection's nodes toothers — edgesWith() restricted by direction.
// The edges sharing endpoints with these edges, in either direction — including each edge itselfeles.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.
// The parallel edges pointing the same way — same source and same target — including each edge itselfeles.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.
// Connected components within this collection (undirected), each as a collection of the reached nodes plus the collection's edges internal to that componenteles.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.
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
// 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.
// All ancestors, level by level: every nearest parent first, then the grandparents, and so oneles.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.
// Direct children of every node, in link order per parenteles.children(criterion?: FilterLike<NodeData, EdgeData, NodeData, NodeData | EdgeData>): Collection<NodeData, EdgeData, NodeData>
Direct children of every node, in link order per parent.
// Scale each compound parent’s descendants into a miniature around the parent’s current centreeles.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.
// Restore each collapsed compound parent’s descendants by reversing its currently applied scale around the parent’s current centreeles.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.
// The collection's nodes that have a parenteles.nonorphans(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)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).
The algorithm family includes synchronous searches and paths, spanning and
cut algorithms, centrality measures and clustering, plus larger async
whole-graph algorithms. For example:
constresult= cy.elements().breadthFirstSearch({
roots: cy.getElementById('a'),
directed: true,
visit(node, edge, previous, index, depth) {
if (node.id() ==='goal') returntrue;
},
});
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.
Breadth-first search over this collection's subgraph. Roots are visited in breadth-first order. Multiple callback roots are visited in reverse input order because the initial queue prepends each root; with no roots, the result is empty.
Visit callback, or a direction flag when no callback is needed.
directed: boolean | undefined?
True to follow outgoing edges only; defaults to false.
ReturnsSearchResult
{ path, found }: path records roots in input order and discoveries in breadth-first insertion order, with each discovery edge before its node. It can include nodes queued but not visited when the callback stops early. found is the matched node or an empty collection when no callback returned true.
Depth-first search over this collection's subgraph. It shares the root, callback, direction and result contract of breadthFirstSearch, but explores the most recently discovered branch first.
// Compute single-source shortest paths from a root over this collection's subgraph using Dijkstra's algorithmeles.dijkstra(options: DijkstraOptions): DijkstraResult
Compute single-source shortest paths from a root over this collection's subgraph using Dijkstra's algorithm. The caller is responsible for using non-negative edge weights; the library does not validate the weight function's mathematical properties.
Parameters
Name
Description
options: DijkstraOptions
{ root, weight, directed }. The root must be a node in this collection. weight(edge) returns a number and defaults to 1; directed: true follows outgoing edges only.
Starting node in this collection; required at runtime.
weight: WeightFn?
Non-negative edge cost; defaults to 1 for each edge.
directed: boolean?
Follow outgoing edges only when true; defaults to false.
ReturnsDijkstraResult
{ distanceTo, pathTo }; an unreachable node has infinite distance and its pathTo() collection contains that node alone. A node outside this subgraph has undefined distance and an empty path.
// Find an A path between two nodes in this collection's subgrapheles.aStar(options?: AStarOptions): AStarResult
Find an A* path between two nodes in this collection's subgraph. The heuristic defaults to zero, reducing the search to Dijkstra's ordering. The search closes nodes without reopening them; shortest-path guarantees require non-negative costs and a consistent heuristic. The library does not validate those mathematical properties.
Parameters
Name
Description
options: AStarOptions?
{ root, goal, weight, heuristic, directed }. Root and goal must belong to this collection; weight(edge) defaults to 1, heuristic(node) defaults to 0, and directed: true follows outgoing edges only.
// Compute single-source shortest paths with Bellman–Fordeles.bellmanFord(options?: BellmanFordOptions): BellmanFordResult
Compute single-source shortest paths with Bellman–Ford. Unlike dijkstra(), this algorithm supports negative edge weights and reports reachable negative-weight cycles. Undirected, every edge is both arcs, so a negative edge reachable from the root is itself a negative cycle .
Parameters
Name
Description
options: BellmanFordOptions?
{ root, weight, directed, findNegativeWeightCycles }. The root must belong to this collection; weight(edge) defaults to 1 and directed: true follows outgoing edges only. Set findNegativeWeightCycles: false to stop after detecting a cycle without constructing cycle collections.
distance and path accessors, hasNegativeWeightCycle, and negativeWeightCycles (collections describing detected cycles); unreachable nodes have infinite distance and an empty path
Floyd–Warshall all-pairs shortest paths. O(n³) — for a single source prefer dijkstra/bellmanFord. Async: the expensive whole-graph tier returns promises, and executor ('cpu' | 'gpu' | 'auto', default 'auto'; 'workers' runs the reference on one pool worker) picks where the maths runs; 'cpu' is the reproducible reference.
Parameters
Name
Description
options: FloydWarshallOptions?
{ weight, directed, executor }
Fields of options
Name
Description
weight: WeightFn?
directed: boolean?
executor: AlgoExecutor?
where the run executes; see AlgoExecutor (default 'auto')
// Build a minimum spanning forest of this collection, treating its edges as undirectedeles.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.
// Partition this collection's directed subgraph into strongly connected componentseles.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.
ReturnsTarjanStronglyConnectedResult
{ components, cut }: each component collection contains its nodes and internal edges; cut contains edges between components
// Find undirected biconnected components and articulation points in this collection's subgrapheles.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.
ReturnsHopcroftTarjanBiconnectedResult
{ 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.
// Find an Eulerian trail or circuit over this collection's edgeseles.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.
Starting node or an options object; omit to choose an eligible node.
directed: boolean | undefined?
True to follow outgoing edges only; defaults to false.
ReturnsHierholzerResult
{ 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.
// Estimate an undirected global minimum cut with the randomized Karger–Stein contraction algorithmeles.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.
ReturnsKargerSteinResult
{ 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.
// PageRank over the subgrapheles.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
Name
Description
options: PageRankOptions?
{ dampingFactor, precision, iterations, weight, directed, executor }; dampingFactor is the textbook α in (0, 1], default 0.85
Fields of options
Name
Description
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')
// Compute Opsahl's generalized degree for one node in this collectioneles.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
Name
Description
options: DegreeCentralityOptions?
{ root, weight, alpha, directed }; root is required, weight(edge) defaults to 1, alpha defaults to 0, and directed defaults to false
read by degreeCentralityNormalized only: 'max'
(default) divides by the largest degree, 'size' by n − 1 —
NetworkX's degree_centrality and igraph's normalized = TRUE
ReturnsDegreeCentralityResult
{ degree }, or { indegree, outdegree } when directed
// 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
Name
Description
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'
read by degreeCentralityNormalized only: 'max'
(default) divides by the largest degree, 'size' by n − 1 —
NetworkX's degree_centrality and igraph's normalized = TRUE
ReturnsDegreeCentralityNormalizedResult
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.
// Closeness centrality of one node — how near it is, by shortest path, to the rest of the collectioneles.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).
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.
// 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.
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.
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.
// 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
Name
Description
options: BetweennessCentralityOptions?
{ weight, directed, normalization, executor }
Fields of options
Name
Description
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.
a promise of the { betweenness, betweennessNormalized } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed
// 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.
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'.
a promise of the { katz, katzNormalized } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed
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
Name
Description
options: NeighborhoodSimilarityOptions?
{ metric, directed, executor }
Fields of options
Name
Description
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.
// 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).
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).
// 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 seedseles.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.
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).
// All-pairs random-walk-with-restart proximity — the full matrix S = c·(I − (1−c)·W)⁻¹, whose column s is the walk restarting at seles.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.
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).
// 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 Laplacianeles.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.
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).
// 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).
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).
// Effective resistance and commute time — the graph as a resistor networkeles.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
Name
Description
options: EffectiveResistanceOptions?
{ weight, weightAs, executor }
Fields of options
Name
Description
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')
a promise of the { resistance, commuteTime } accessors — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed
// 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
Name
Description
options: TriangleCountOptions?
{ executor }
Fields of options
Name
Description
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.
a promise of { triangles, clusteringCoefficient, totalTriangles, transitivity } — with cancel() on it: a pending run rejects with CancelledError, a 'cpu' run has already completed
// 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
Name
Description
options: MotifCensusOptions?
{ directed, executor }
Fields of options
Name
Description
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.
// The summed degree of every node in the collection — the whole-collection figure that degree() deliberately is noteles.totalDegree(includeLoops?: boolean): number
The summed degree of every node in the collection — the whole-collection figure that degree() deliberately is not.
// k-means clustering in attribute spaceeles.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
Name
Description
options: KClusteringOptions?
{ k, attributes, distance, maxIterations, sensitivityThreshold, executor }, with attributes as plain functions
Fields of options
Name
Description
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')
// k-medoids clustering — like k-means, but cluster centres are actual elements, which makes it robust to outlierseles.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
Name
Description
options: KClusteringOptions?
as kMeans
Fields of options
Name
Description
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')
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
// Fuzzy c-means clustering: each element gets a degree of membership in every cluster rather than one hard assignmenteles.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
Name
Description
options: KClusteringOptions?
as kMeans, plus the fuzziness exponent
Fields of options
Name
Description
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')
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.
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
// Markov clustering (MCL) — flow simulation over the graph, so unlike the attribute-space algorithms this one clusters by structureeles.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.
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')
// Affinity propagation, which picks exemplars by message passing and so needs no target cluster counteles.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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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. Collectionoff(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.
constisNode=ele=> ele.isNode();
constonNodeTap=event=> {
constnode= 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.
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 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.
// Whether preventDefault() was called on this eventevent.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.
// Whether stopPropagation() has been called — read by the compound bubbling walk, where it halts the phase sequenceevent.isPropagationStopped(): boolean
Whether stopPropagation() has been called — read by the compound bubbling walk, where it halts the phase sequence.
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.
// Prevent the original browser event's default behaviour when one is attached, for example page scrollingevent.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.
// Stop the event bubbling to further phases: the remaining ancestors and the core do not see itevent.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.
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.
constlayout= cy.layout({
name: 'flow',
direction: 'rightward',
nodeSep: 48,
rankSep: 72,
});
cy.on('layoutstop', event=> {
if (event.layout === layout) console.log('positions are ready');
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:
constlayout= 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.
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.
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.
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.
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.
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 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 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 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 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.
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.
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 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 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 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.
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.
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.
Returnsthis
this layout, for chaining; await promise() for completion
// 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().
// 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.
// Abandon the run in flight — the alternative to stop(), which keeps what standslayout.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.
// 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
Name
Description
alpha: number?
the temperature to restore; the force layout's default is 0.3, d3's drag convention
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.
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.
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.
// Stop in place, or at the targets with jumpToEnd — the whole animation, whatever elements it spansani.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.
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.
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.
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.
// The elements included in this layoutctx.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.
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.
// 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 removectx.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.
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().
// The slots to lay out: the scope's unlocked leaves, plus a collapsed parent when no scoped node lies below itctx.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.
Returnsnumber[]
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.
// The live position column (x,y interleaved by slot) — read it, write through setPositionsctx.positions(): Float32Array
The live position column (x,y interleaved by slot) — read it, write through setPositions.
ReturnsFloat32Array
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
// 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 byctx.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.
// The viewport width in CSS px — what a layout sizing itself to the screen should usectx.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.
Returnsnumber
the viewport width
Example
// Inside a custom layout, ctx is supplied by the library.
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.
// Write model-space coordinates for the supplied node slotsctx.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
Name
Description
slots: number[]
the node slots to move
xy: number[] | Float32Array
the packed positions: xy[i*2], xy[i*2+1] land on slots[i]
Returnsvoid
Example
// Inside a custom layout, ctx is supplied by the library.
// 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().
ReturnsComponents
the component assignment, ids in first-seen node order
// Separate the scope's disconnected components: a one-call, translation-only post-passctx.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
Name
Description
spacing: number?Default: 40
the gap between packed component boxes (default 40, the force layout's componentSpacing 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
// 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 eventsctx.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).
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
Name
Description
eles: unknown?
the elements to lay out (set automatically by eles.layout()); defaults to the whole graph
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.
// 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 / panctx.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
Name
Description
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]
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.
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.
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.
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.
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 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.
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:
'labels': a glyph stream past its limit stops uploading and every label
is no longer drawn. Label dimensions remain available to graph operations.
'charts', 'images', 'curves': an oversized blob is replaced by a
placeholder and its pass is skipped.
'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.
// The renderer's frame statistics, or null when headlesscy.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.
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.
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.
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.
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 stylesheetfont-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.
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.
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.
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.
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.
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:
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:
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:
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.
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.
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.
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.
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
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.
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.
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 }
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
hierarchicalClusteringthreshold
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
markovClusteringmaxIterations
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
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
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: truetweens to the result like every other layout; animateLive: true streams the run
cosenodeOverlap / 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
forcescales 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
hierarchicalClusteringmean 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 nameddistance
(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.
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).
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:
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:
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.
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.
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()
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.
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.
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.
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.
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.