Migration
Port applications from earlier releases and find archived documentation.
Cytoscape.js 4 changes how applications query, style and render graphs. Rendering requires WebGPU, selector strings become query objects or predicates, and some v3 APIs have no replacement. This guide shows how to update a v3 application and which behaviour to re-check after porting.
v4 is not released yet. For production use
cytoscape@3and js.cytoscape.org.
#Contents
- Before you start
- The five changes that touch every app
- Selector recipes
- Style properties that moved
- Events
- Behaviour to re-check
- Constructor options
- Layouts and extensions
- Worth adopting once you have ported
- Not ported
#Before you start
Rendering requires WebGPU. With a container, the factory throws
synchronously when navigator.gpu is missing, and cy.ready rejects when no
adapter can be acquired. There is no canvas fallback — v4's renderer is a
WebGPU pipeline, not a mode of v3's.
Use headless mode for analysis without a canvas. Omit container to use
the graph model, styles, CPU layouts and algorithms in Node or another
supported runtime. Rendering, image export
and GPU execution have additional requirements.
Pick the entry for the job. The package ships three builds; each has TypeScript declarations. Choose according to whether your application needs rendering, GPU compute or CPU-only analysis:
// everything: the WebGPU renderer, the pointer, the GPU executors (browsers)import cytoscape from 'cytoscape';
// headless and CPU-only: CI, Node services, edge isolates (a Cloudflare// Worker) — no renderer or WebGPU codeimport 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 rendererimport cytoscape from 'cytoscape/headless-gpu';The slim builds say so when asked for what they lack, never silently: a
container (or cy.mount()) throws this build has no renderer — import 'cytoscape', and on cytoscape/headless an explicit executor: 'gpu' —
algorithm or force layout — rejects this build has no GPU executors — import 'cytoscape/headless-gpu' or 'cytoscape' ('auto' just runs on the
CPU). Their factories take HeadlessOptions, the options minus the
renderer- and pointer-only fields.
cytoscape/gpu is gone. The pre-release alias of the full entry was
removed before alpha, because beside cytoscape/headless-gpu it read as
"the GPU build" while resolving to everything. Import cytoscape.
Types ship, and they are the fastest porting tool you have: a v3 app run
through tsc against v4's declarations will surface most of this document as
compile errors before you run anything. cy.on( 'tap', 'node', h ) is the
exception worth knowing — the selector string is a runtime rejection.
#The five changes that touch every app
#1. There are no selector strings
v4 has no selector parser and no dialect of one. The language is replaced by three mechanisms, split by role:
// v3cy.$( '#a' );cy.nodes( ':selected' );cy.filter( '[weight > 0.5]' );cy.on( 'tap', 'node', handler );
// v4cy.$id( 'a' ); // id -> the O(1) id indexcy.nodes( { selected: true } ); // query object -> a columnar scancy.nodes( { data: { weight: { gt: 0.5 } } } ); // data conditions, same scancy.on( 'tap', ele => ele.isNode(), handler ); // predicate delegation- Query objects answer whole-graph questions and compile to per-group
flag tests answered in one pass over the columns. Keys:
group,selected,parent,child, anddata. 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 ofcy.filter(), socy.$( { selected: true } )andcy.$( ele => … )do what you expect, whilecy.$( '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'scollection( eles )building form is not supported. Build withunion()over the empty accumulator, or query withcy.$( query ).
Passing a selector string anywhere throws with the replacement named — at the query compiler, at the twelve collection methods that take another collection, and at event delegation. Replace selectors at each call site.
#2. There are no classes
addClass/removeClass/toggleClass/hasClass/flashClass and class
selectors are gone. The role classes played — user-defined state that drives
filtering and styling — belongs to data() plus mappers:
// v3node.addClass( 'highlighted' );// style: { selector: '.highlighted', style: { 'background-color': 'red' } }
// v4node.data( 'highlighted', true );// style: { nodes: { 'background-color': {// case: [ { when: { data: 'highlighted', eq: true }, then: 'red' } ],// else: '#666'// } } }The style updates automatically: a data write re-derives exactly the mapped channels that depend on the written key.
The commonest class in v3 apps — the hover highlight, a .faded class on
everything outside the hovered neighbourhood — is not a class or a data write
in v4 but one call, because writing every element on each hover does not
scale well on large graphs:
// v3cy.on( 'mouseover', 'node', e => { cy.elements().not( e.target.closedNeighborhood() ).addClass( 'faded' );} );cy.on( 'mouseout', 'node', () => cy.elements().removeClass( 'faded' ) );// style: { selector: '.faded', style: { opacity: 0.15 } }
// v4cy.on( 'mouseover', ele => ele.isNode(), e => cy.emphasize( e.target.closedNeighborhood() ) );cy.on( 'mouseout', ele => ele.isNode(), () => cy.unemphasize() );// style: { core: { 'dim-opacity': 0.15 } } — and, to style the set itself,// { when: { emphasized: true } } on any propThe rest is dimmed by the renderer as one composite, not by a style, so
style( 'opacity' ) on a dimmed element reads its own value.
#3. The stylesheet is an object, not a list of selector blocks
// v3style: [ { selector: 'node', style: { 'background-color': '#666' } }, { selector: 'edge', style: { width: 3 } }, { selector: ':parent', style: { 'background-color': '#eee' } }]
// v4style: { nodes: { 'background-color': '#666' }, edges: { width: 3 }, parents: { 'background-color': '#eee' }, core: { 'selection-box-color': '#ddd' }}Four groups, fixed: nodes, edges, parents (overlaying nodes for
compound parents) and core (v3's core-selector props). Per-element
variation is declarative — a mapper, not a block:
// v3: a style function{ selector: 'node', style: { width: ele => ele.data( 'size' ) * 2 } }
// v4: a scale mapper{ nodes: { width: { data: 'size', range: [ 10, 80 ] } } }
// v4: a conditional{ nodes: { shape: { case: [ { when: { data: 'type', eq: 'gene' }, then: 'ellipse' } ], else: 'rectangle' } } }#Styling element state
v3 puts state in selectors — :selected, :active, :locked, :grabbed.
v4 has no selectors, so state is a condition on the same case mapper:
// v3{ selector: 'node:selected', style: { 'background-color': '#0169D9' } }
// v4{ nodes: { 'background-color': { case: [ { when: { selected: true }, then: '#0169D9' } ], else: '#999',} } }The states are selected, selectable, locked, grabbed, grabbable,
active, hovered, plus the structural parent, child, childless and
orphan. Each takes a boolean, so v3's negative selectors — :unselected,
:unlocked, :free, :ungrabbable, :unselectable, :inactive — are the
same key with false. AND a state with a data condition through the array
form: when: [ { selected: true }, { data: 'w', gt: 5 } ].
You get v3's affordances without writing any of this, and you replace
them the same way you would in v3. v4's default stylesheet carries v3's
:selected, :parent:selected and :active blocks, spread before your
own — so a sheet that names background-color replaces the selection colour
along with it, precisely as a v3 sheet does, and overlay-opacity: 0 turns
the press highlight off.
Not carried over: :compound (its node meaning is exactly parent; its edge
meaning has no v4 spelling), :loop / :simple, and :visible / :hidden /
:transparent — those are computed from style, so a rule conditioned on one
would be circular. :animated, :backgrounding, :removed and :inside
have no styling form either.
A style group written as a function throws. Replace it with a group object whose properties use constants or declarative mappers.
The per-element bypass works, spelled as in v3:
ele.style( name, value ), the object form and removeStyle( name? )
set and clear id-keyed constants that beat every sheet rule. Two
differences from v3 worth knowing while porting: the canonical form is
the stylesheet's bypasses section ({ bypasses: { id: { prop: value } } }), which exports from cy.json() where v3 silently
drops bypasses on export — and a full cy.style( sheet ) replaces
the live bypasses like any other section (v3's survive sheet swaps;
spread the exported sheet to keep them). Values are constants only —
mappers remain the per-element mechanism for anything data-driven.
For the list-valued curve props (control-point-distances/-weights,
segment-distances/-weights/-radii), which accept constants only
and reject mappers, the bypass is the porting path for a v3 sheet that
gave edges their own arrays — a per-edge array is a per-element
constant, so for those props the bypass is the only per-edge spelling.
CSS-string stylesheets and cytoscape.stylesheet() are gone with the
block form.
#4. Animations sequence by promise, not by queue
// v3node.animate( { position: p1 } ).animate( { position: p2 } ); // queued
// v4await node.animate( { position: p1 } ).promise();node.animate( { position: p2 } );Animations on disjoint channels run concurrently (a position tween and an opacity fade compose). Starting one that overlaps a running animation's channels stops the older one in place — its promise resolves, its values freeze, and the new one captures from there.
There is no queue option, and the spelling throws (there is no queue to
opt out of). The v3 step callback is out too: use cy.on( 'render', … )
plus promises.
stop() lost its clearQueue argument — it is stop( jumpToEnd ) now.
eles.animate() is one animation over the elements, where v3 made one
per element: node.stop() on one of them stops the whole animation, and so
does an overlapping animation started on one of them. An animated layout's
tween is the exception: its nodes stay individually addressable as v3's
per-node tweens were. node.stop(), a new position
animation on the node, lock() and remove() detach that node alone and the
rest of the tween runs on. Two answers differ from v3: a node locked
mid-tween holds where it got to and unlock() does not resume it (v3's step
skips a locked node and picks the tween up again on unlock), and a node
mid-tween cannot be grabbed (v3 let the drag and the tween fight over it) —
stop it first.
#5. Removed elements are terminally dead
remove() tombstones the slot, bumps its generation and returns it to the
free list; the next add() may recycle those bytes. So a removed element is
not readable and not restorable:
restore(),clone(),copy()— gonecy.json( obj )(the import form) — throws;cy.json()export works
Only the handle's cached id() and group() survive removal, which is what
keeps remove handlers and predicates working. Re-adding from definitions
you kept is the app's job — exported element JSON round-trips through
cy.add().
If what you used cy.json( obj ) for was applying the next server
response to the live graph, v4 has a call for exactly that:
cy.patch( payload ) reconciles a fresh payload by id — adds what is new,
removes what is gone (or keeps it, with { mode: 'merge' }), replaces the
data of what survives — in one batch, and returns { added, removed, updated }. Selection, positions the payload does not carry, listeners,
scratch and running animations survive on every element it keeps. It
restores no session state: the viewport, the stylesheet and graph data are
never touched.
#Selector recipes
| v3 selector | v4 |
|---|---|
cy.$( '#a' ) |
cy.$id( 'a' ) |
cy.$( 'node' ) |
cy.nodes() |
cy.$( 'edge' ) |
cy.edges() |
cy.$( '*' ) |
cy.elements() |
cy.$( 'node:selected' ) |
cy.nodes( { selected: true } ) |
cy.$( ':unselected' ) |
cy.elements( { selected: false } ) |
cy.$( ':parent' ) |
cy.nodes( { parent: true } ) |
cy.$( ':childless' ) |
cy.nodes( { childless: true } ), or { parent: false } |
cy.$( ':child' ) |
cy.nodes( { child: true } ) |
cy.$( ':orphan' ) |
cy.nodes( { orphan: true } ), or { child: false } |
cy.$( ':locked' ), :unlocked |
cy.elements( { locked: true } ) / { locked: false } |
cy.$( ':grabbed' ), :free |
cy.elements( { grabbed: true } ) / { grabbed: false } |
cy.$( ':grabbable' ), :ungrabbable |
cy.elements( { grabbable: true } ) / { grabbable: false } |
cy.$( ':selectable' ), :unselectable |
cy.elements( { selectable: true } ) / { selectable: false } |
cy.$( ':active' ), :inactive |
cy.elements( { active: true } ) / { active: false } |
cy.$( '[weight > 0.5]' ) |
cy.nodes( { data: { weight: { gt: 0.5 } } } ) |
cy.$( '[type = "gene"]' ) |
cy.nodes( { data: { type: 'gene' } } ) |
cy.$( '[type != "gene"]' ) |
cy.nodes( { data: { type: { ne: 'gene' } } } ) |
cy.$( '[^weight]' ), [?weight] |
a predicate: cy.nodes( n => n.data( 'weight' ) == null ) |
cy.$( '.cls' ) |
cy.nodes( { data: { cls: true } } ) — classes are data now |
cy.$( 'node[x], edge[y]' ) (comma) |
two queries plus .union() |
eles.filter( 'node' ) |
eles.filter( { group: 'nodes' } ) or eles.nodes() |
node.neighborhood( '.foo' ) |
node.neighborhood().filter( pred ) |
cy.on( 'tap', 'node', h ) |
cy.on( 'tap', ele => ele.isNode(), h ) |
Data-condition operators: eq, ne, lt, lte, gt, gte, in. A bare
value means eq; keys within one object are AND-ed; a missing value fails
every operator, ne included.
The state keys are the same ones a case mapper's when takes — anything
you can style on, you can query for. :visible, :hidden, :transparent,
:animated, :backgrounding, :removed, :inside, :loop, :simple and
:compound have no query form; use a predicate.
#Style properties that moved
v3 registers 291 property names (properties plus aliases). v4 accepts
164 of them — 7 only in the core group — and rejects 127. Of the
rejections, 96 are v3's numbered pie-N-* / stripe-N-* props, which became
one chart family. The remaining 31 are the table below.
A rejected property name throws at cy.style() with
"The style property 'x' is unsupported".
| v3 property | v4 |
|---|---|
z-index, z-compound-depth, z-index-compare |
dropped outright. Draw order is structural: compound parents, then edges, then leaf nodes, then labels; slot order within a stream |
pie-* (48), pie-size, pie-hole, pie-start-angle |
chart: 'pie' + chart-values, chart-colors, chart-size, chart-hole, chart-start-angle |
stripe-* (48), stripe-size, stripe-direction |
chart: 'stripes' + the same family, plus chart-direction |
| Multivariate heat charts | chart: 'heat-strip' or 'radial-heat', chart-values, and a required shared chart-scale with an explicit domain and colour range |
| Signed bar charts | chart: 'bar', signed chart-values, required chart-domain, and optional independent chart-scale or chart-colors |
content |
label |
min-width-bias-left/-right, min-height-bias-top/-bottom |
dropped. min-width/min-height clamp centred — v3's default-bias behaviour |
display |
show() / hide() for the structural tier; the visibility style prop for paint-only invisibility |
position |
not a style property — use ele.position() |
text-metrics |
eles.labelBoundingBox() |
box-select-labels |
the core option boxSelectionIncludesLabels |
box-selection |
the core option boxSelectionMode ('contain' | 'overlap'); its third value 'none' is the events property |
edge-text-rotation |
text-rotation (a keyword autorotate, or a number of radians on any label) |
control-point-distance |
control-point-distances (plural — v4 has no singular alias) |
segment-distance, segment-weight, segment-radius |
segment-distances, segment-weights, segment-radii |
background-blacken |
dropped. Compute the shade in a colour mapper's range |
bounds-expansion |
dropped. Bounds are computed correctly instead |
outside-texture-bg-color/-opacity |
dropped with textureOnViewport |
mid-source-arrow-fill, mid-target-arrow-fill |
dropped. Mid arrows are always filled |
border-cap, border-join |
dropped. Dash ends are perpendicular cuts by construction; border-style, border-dash-pattern and border-dash-offset all port |
Chart data retains authored slot order up to 255 values. Pie and stripe values
remain absolute fractions that clamp at 1; heat and bar values may be signed.
Null and non-finite values keep their positions, do not contribute to shared
automatic bounds, and render with chart-missing-color (transparent by default
for heat, a gap for bars). chart-domain sets bar geometry bounds separately
from a bar's optional colour scale. Shared auto endpoints use the supplying
stylesheet definition's finite values; they do not normalize each node. Use
cy.legend() for resolved colour and geometry domains, then render labels and
axes in the application.
Also renamed or re-scoped without being rejected:
- Gradients keep their property names: v3's
background-fill(solid | linear-gradient | radial-gradient) withbackground-gradient-stop-colors/-stop-positions/-direction, andline-fillwithline-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/-bottomport — in theparentssheet group only, constants only, each a number of px or'N%'resolved perpadding-relative-to; an unset side takes the uniformpadding. Naming one in anodesoredgesblock throws the group rule ("belongs to the parents group"), not "unsupported".font-family,font-style,font-weightare 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. Useround-rectangle,cut-rectangle,concave-hexagon. This applies in all three enums that took them — the nodeshape,overlay-shape/underlay-shape, andtext-background-shape. - Channel opacities fold at write time.
background-opacity,border-opacity,line-opacityandtext-opacityfold into the stored channel alpha; elementopacitystays the master multiplier. Reading them back gives the folded value.
#Events
The vocabulary is curated. v4 emits the drag-state family
(grab/grabon/drag/free/freeon/dragfree/dragfreeon), the
device-normalized family (tapstart, tapdrag, tapend, tap, taphold,
dbltap, onetap, tapselect/tapunselect, tapdragover/tapdragout,
the cxt* family), the viewport gestures (dragpan, scrollzoom,
pinchzoom, and scrollpan under wheelBehavior: 'pan'), the official pointer family (pointerdown/pointermove/
pointerup/pointercancel/pointerover/pointerout), and the model events
(add, remove, data, position, select, unselect, style,
layoutstart/layoutready/layoutstop, patch, batchstart/batchend,
loadstart/loadchunk/loadready/loadstop, render, destroy, error,
mouseover/mouseout, box/boxstart/boxend/boxselect,
devicelost/devicerestored, gpuerror, move/moveout).
Dropped names register and then never fire, silently. This is the porting hazard worth reading twice:
cy.on( 'mousedown', h ); // registers fine. Never fires.cy.on( 'click', h ); // registers fine. Never fires.cy.on( 'vmousedown', h ); // registers fine. Never fires.cy.on( 'touchstart', h ); // registers fine. Never fires.They cannot be rejected, because custom events are supported API —
ele.emit( 'myEvent' ) must keep working, so a name cannot be validated
against a list. Port event names from the vocabulary, not by trying them.
pointer* is the modern spelling of the raw mouse/touch re-emits;
mouseover/mouseout do still fire.
There are no namespaces. A type is matched whole, so 'tap.ns' is one
literal name that emit( 'tap' ) does not reach and off( 'tap.ns' )
removes on its own. Register and remove each literal name separately.
event.preventDefault() is browser-level only, by design. originalEvent
is populated, so the call reaches the browser's default — but no v4 code reads
isDefaultPrevented(), so it cannot stop a tap from selecting or a grab from
starting. Gesture defaults are controlled by the explicit toggles
(autounselectify, autoungrabify, boxSelectionEnabled,
userPanningEnabled, …, and per-element ungrabify()/unselectify())
instead.
Bubbling works as in v3 for compounds: origin → ancestors → core, with
event.target the originator and stopPropagation() (or returning false)
halting the walk. The one deviation is within a phase, where listeners fire
in plain registration order.
#Behaviour to re-check
These compile and run, but behave differently. They are the things a ported app trips on after everything else works.
| Area | v3 | v4 |
|---|---|---|
Default curve-style |
bezier |
straight — opt into bezier explicitly. It is the perf-first default at v4's target scales |
Default text-valign |
top |
bottom — v4 keeps its below-node placement |
| Draw order | z-index, then a whole-scene comparator sort |
structural, permanently. A grabbed node does not pop above later-inserted nodes |
cy.elements() order |
mixed insertion order | nodes then edges |
| Position precision | Float64 | Float32 (~7 significant digits) |
bezier bundling |
same | same — a lone edge under curve-style: bezier still renders straight; only parallel edges fan |
| Colour animation | per-channel sRGB | OKLab, matching colour mappers |
Edge overlay-padding / underlay-padding |
the band is 2 × padding wide — a padding under half the line width draws a halo narrower than the line, i.e. hidden |
width + 2 × padding, the edge's own extent plus the padding, as the node overlay reads it — so the halo always shows. To match a v3 sheet's band, set v4's padding to v3's minus half the edge width. The ends, corners and reach match v3: round caps, round joins that blend once, and an overlay that reaches over a hollow head |
border-style: double under an edge |
erases to the page (destination-out) | the stripe shows whatever the scene drew beneath the node — an edge passing under the border shows through the gap where v3 punches to the background |
Label box (text-background-*, text-border-*) |
the border strokes even with text-background-opacity: 0; a round-rectangle box has a 2 px corner; the box's width is the text's measured width rounded up |
the box draws only when text-background-opacity > 0 (give a border-only box an opaque-enough background, or match the page colour); the round box keeps v4's auto radius (min(w, h) / 4, at most 8 px); the width is not rounded, so a box can be up to 1 px narrower. The border's placement, its dash patterns and double are v3's |
spring() easing |
spring( tension, friction ) |
spring( bounce ) — one number; 0 is critically damped |
| Custom easing functions | accepted | throw. A closure cannot cross to the GPU; cubic-bezier() and linear() cover any drawable curve |
| Label bounding boxes | opt-in | boundingBox() includes labels by default; opt out with { includeLabels: false } |
breadthfirst without a boundingBox |
spread over cy.extent() in model coordinates, so the drawing scaled with the zoom at the moment it ran |
spread over the viewport in pixels, as grid, circle, concentric and radial are; identical at zoom 1 |
| Arrow sizing | max( (13.37w)^0.9, 29 ) |
the same formula |
triangle-cross arrowhead |
accepted as a separate edge-width bar | throws as an unsupported arrow shape; migrate to triangle-tee, whose bar uses max(0.1 × arrowSize, edgeWidth) and keeps its front at -0.4 × arrowSize |
Hollow triangle-tee / circle-triangle end arrows |
component outlines | supported; their parts are outlined independently and coverage is combined once |
outerWidth() with a border |
includes the miter overshoot | plain border-inclusive outerHalf, so parent boxes can sit sub-pixel smaller |
| Compound auto-sizing | can include labels | reads child body extents by default; compound-sizing-wrt-labels: 'include' adds their labels |
:selected / :parent:selected |
default-sheet blocks any later block beats | the same rule, as a { when: { selected: true } } condition in v4's default stylesheet — so naming background-color yourself still replaces it, exactly as in v3 |
| Comparing elements from two instances | answered, inconsistently — same() was false but union() of 2 + 2 gave 2 and difference() gave 0 |
throws. Element identity is a slot in one store, so v4 refuses rather than inventing a cross-instance identity |
| The expensive whole-graph algorithms | synchronous | async — pageRank, floydWarshall, betweennessCentrality, closenessCentralityNormalized, markovClustering, affinityPropagation, kMeans, kMedoids, fuzzyCMeans and hierarchicalClustering return promises; await the call, then use the result exactly as in v3 |
pageRank's dampingFactor |
d, applied to the teleport only — it behaved as α = 1/(2 − d); default 0.8 | the textbook α, as NetworkX's alpha; default 0.85. Ranks differ; pass 1 / (2 − d) to reproduce a v3 run. Outside (0, 1] throws |
bellmanFord, undirected, with a negative edge |
no negative cycle — it never relaxed back over the edge that reached a node | hasNegativeWeightCycle: true: the edge walked both ways is a 2-node cycle, as in NetworkX. Distances are then unbounded; positive-weight and directed runs are unchanged |
Undirected betweennessCentrality |
counts each pair twice, so path a–b–c gives 2 for b | counts each pair once, as NetworkX and igraph do: a v3 score is twice v4's. Directed scores and betweennessNormalized are unchanged |
pageRank on an undirected graph |
always follows source → target, so ranks depend on how each edge is stored | undirected by default: each edge is walked both ways, as in NetworkX and igraph. Ranks differ; pass directed: true to reproduce a v3 run |
Classic closeness (harmonic: false) |
1/Σd, and 0 for every node once any node is unreachable | (n − 1)/Σd, with the Wasserman–Faust correction on a disconnected graph, as NetworkX's default. On a connected graph, divide by n − 1 to reproduce a v3 score. The harmonic default is unchanged |
hierarchicalClustering threshold |
merges while the closest pair is strictly under it | merges at exactly threshold too, as SciPy's fcluster and R's cutree. Results differ only when a merge distance equals the threshold, which is common on integer attributes |
markovClustering maxIterations |
default 20 | default 100, as Python markov_clustering and R MCL. Runs that converged sooner are unchanged; pass maxIterations: 20 for the old cap |
| A graph larger than the GPU can hold | grows until the browser runs out of memory | cy.add() throws cytoscape.GpuUnfitError when the mounted renderer's device could not bind or dispatch over the grown tables — before anything is added, so the graph is unchanged; cy.load() and cy.patch() refuse the same way, and cy.ready rejects with it for a graph built headless and mounted on a device too small for it. A buffer the device refuses, or one the renderer declines, fires gpuerror and degrades — labels first, then charts and images, then gradients — rather than blanking the canvas |
| Cancelling a whole-graph algorithm | not possible — the call blocks | the promise carries cancel(): a pending run rejects with cytoscape.CancelledError (error.name === 'CancelledError') and answers true once; a run that has already completed — every 'cpu' run has, inside the call — answers false and its result stands |
layout.stop() |
ends the run where it is, keeping the positions | unchanged: an animate: true tween stops where it stands and layoutstop fires immediately — and layout.cancel() is the other ending: the run is abandoned, a tween under way is dropped where it is, the nodes go back to where run() found them, the viewport is left alone, layoutstop still fires with cancelled: true, and layout.promise() rejects with CancelledError. cy.destroy() cancels every run still open the same way |
| Container resize | call cy.resize() after resizing the container |
automatic: a ResizeObserver re-measures and emits a resize event once per change, so the call is only needed where no observer can see the change; an existing call is harmless (the observer finds the size applied and emits nothing more) |
| A wheel over a canvas that will not zoom | the page scrolls (v3 prevents default only when panning and zooming are both enabled) | the same — v4 prevents default only on a wheel it acts on, and wheelBehavior ('zoom', 'pan', 'modifier-zoom') says which wheels those are: 'modifier-zoom' is the embedded-map idiom — the page scrolls past the graph and ctrl/meta-wheel (or a trackpad pinch) zooms |
| Gesture event details | an edge press emits tapstart on the edge; a right press can target an edge; a release emits tap and the selection events before freeon, free, dragfreeon, dragfree; dbltap fires on any second tap inside the debounce window; tapend goes to the element under the release point; a shift/ctrl/meta press on a node grabs it; a drag from a locked node does nothing; the first wheel ticks zoom slowly while v3 samples the device |
an edge press starts on the core (pointerdown, tapstart) and the edge takes the release and the tap once the GPU pick answers; a right press targets a node or the core; a release frees first (free, freeon, dragfree, dragfreeon), then taps; dbltap needs the same target; tapend goes to the pressed element; a multiple-select-key press boxes and grabs nothing; a drag from a locked node pans; every wheel tick zooms by the same factor. |
| Pointer cursors | none — v3 set no CSS cursor at all, and apps wrote container.style.cursor from mouseover/mouseout |
the canvas writes them (grab/grabbing, pointer, crosshair). Idle over background stays '', so the v3 recipe still shows through where v4 is silent; an app whose own cursor code now fights the defaults passes pointerCursors: false |
force with animate: false on a rendered flat graph |
synchronous — positions readable on the next line | async — the run settles at layoutstop / promise(); executor choice is availability-driven (headless runs stay synchronous) |
force on a rendered compound or constrained graph, or a rendered page without a WebGPU adapter |
synchronous | async — the CPU simulation runs on a worker under the default executor: 'auto', so the main thread stays free; read positions at layoutstop / promise(), or say executor: 'cpu' for the in-thread run (bit-identical positions either way) |
cose / force with animate: true |
v3 cose: 'during' streams the run, 'end' tweens to the result |
animate: true tweens to the result like every other layout; animateLive: true streams the run |
cose nodeOverlap / nodeRepulsion |
multipliers on a point repulsion; overlap avoidance was a side effect of strength | force separates the node boxes exactly at the settle under avoidOverlap (default true, labels on request); avoidOverlap: 'sim' makes the sim itself keep them apart with a separation sweep after every tick (opt-in; the settle's pass is cheaper for a one-shot run), 'both' does both |
cose / force with boundingBox |
v3 cose stretched the node centres to fill the box, up or down, size-blind; bodies could overhang it | force scales down only so every body lies inside, then centres the drawing (as in flow); a pinned node or constraints hold it back, as they hold the component re-pack |
a locked node under position() / a layout |
v3: held by both | held by writes, tweens and every layout, and treated as an obstacle for overlap avoidance |
nodeDimensionsIncludeLabels |
default false |
default false; set true to keep labels apart in every built-in. Spacing uses each pair's dimensions rather than v3's largest-footprint-times-1.75 |
hierarchicalClustering mean linkage |
silently broken — an unset size field made the first mean merge write NaN distances, degenerating the clustering | works: sizes are tracked, so mean is the weighted-average linkage both libraries always documented |
The whole-graph tier is async, and executor picks where it runs. The
ten algorithms above return promises because they can run on the GPU:
{ executor: 'auto' } (the default) uses the GPU where an adapter exists and
the input is large enough to win, 'cpu' forces the bit-reproducible
reference implementation, and 'gpu' forces the kernels (rejecting where
WebGPU is unavailable, so a silent slow path cannot masquerade as a fast
one). GPU results may differ from CPU results in float detail — WGSL is
f32 — so a caller that needs run-to-run identical numbers says
executor: 'cpu'. 'workers' is the fourth value: the
per-source-parallel families — betweennessCentrality (weighted and
not), unweighted closenessCentralityNormalized, heatKernel and
randomWalkWithRestartProximity — run on a pool of plain workers (Node
worker_threads, browser Workers; nothing to configure, the worker
entry is inside the bundle), and 'auto' takes that pool wherever the
GPU does not run — from 128 nodes for weighted betweenness and RWR, 256
for unweighted betweenness and the heat kernel, 512 for closeness, each
a measured crossover — which in headless Node means every run of those
families above its crossover now uses the pool; sparse closeness takes
the pool even where a GPU is present, since it measured faster there. The pool's results
are bit-stable across runs and pool sizes, and bit-identical to 'cpu'
for closeness, heat and RWR; betweenness agrees with 'cpu' to f64
rounding but not to the bit, so a caller that compares betweenness
scores bit-for-bit across versions says executor: 'cpu'. 'workers' also runs the families the pool cannot
partition — pageRank, katzCentrality, floydWarshall, weighted
closenessCentralityNormalized, triangleCount,
neighborhoodSimilarity, motifCensus, simRank,
effectiveResistance, markovClustering, affinityPropagation —
on one worker, and 'auto' takes that lane wherever neither the GPU
nor the pool runs, from a per-family size (32–32,768 nodes): the calling
thread stays free for the run's whole length, and the answer is
bit-identical to 'cpu' (the same kernel function runs on both
sides). The same holds for kMeans, kMedoids,
fuzzyCMeans and hierarchicalClustering given a named distance
(and, for hierarchical, a 'min' / 'max' / 'mean' linkage);
'workers' rejects a custom distance function or a per-pair linkage,
which is called inside the loop and so runs on the calling thread, and
the one-column seed forms (heatDiffusion, randomWalkWithRestart).
kMeans reads its testCentroids without writing the updated
centroids back into the caller's arrays, as v3 did. The traversal tier (bfs, dfs, dijkstra, aStar,
bellmanFord, kruskal, the components algorithms, degree centrality and
the single-root closenessCentrality) stays synchronous: those run
per-root in tight loops, and no GPU formulation would beat their
slot-native CPU walks. Only the whole-collection
closenessCentralityNormalized moved to the async tier — it is the O(n³)
all-pairs computation, exactly what the tier exists for.
v4 also adds eight algorithm families v3 never had, on the same async
executor contract: triangleCount() (per-node triangles, local
clustering coefficients, transitivity), neighborhoodSimilarity()
(pairwise Jaccard / cosine / overlap coefficients over neighbor sets),
katzCentrality() (attenuated walk counting), randomWalkWithRestart()
and randomWalkWithRestartProximity() (network propagation from a seed
set, and the all-pairs proximity matrix), heatDiffusion() and
heatKernel() (heat-kernel propagation, exp(−t·L)),
effectiveResistance() (the graph as a resistor network, with
commuteTime), simRank() (recursive neighborhood similarity) and
motifCensus() (the sixteen-class triad census; '030T' is the
feed-forward loop). Nothing to migrate — they are new surface — but
note they read the collection as a simple graph: parallel edges collapse
(summing weights where weights are read), loops are excluded, and the
triangle/heat/resistance families ignore direction outright.
State is a condition, not a selector. See "Styling element state" above:
:selected, :active, :locked and the rest are when conditions on a
case mapper, and the affordances v3 gives you for free are entries in v4's
default stylesheet that your own block replaces — the same precedence v3 has.
#Constructor options
Unknown options are ignored at runtime, deliberately. { motionBlur: true } and { totallyUnknownOption: 1 } both construct happily and
round-trip through cy.options(). The typo guard is TypeScript's
excess-property check against CytoscapeOptions — v4 does not replicate at
runtime what the build already checks. (Note the boundary: excess-property
checking applies to object literals, so options assembled into a variable
first are widened and pass.)
Dropped, and therefore ignored: hideEdgesOnViewport, textureOnViewport,
motionBlur, motionBlurOpacity — canvas-era degradation modes that compute
culling and the adaptive render scale solve without degrading output.
New, and worth setting: boxSelectionMode, boxSelectionIncludesLabels,
wheelSensitivity, wheelBehavior, desktopTapThreshold, touchTapThreshold,
tapholdDuration, multiClickDebounceTime, pixelRatio, pointerCursors,
and the renderer block (renderScaleMin/renderScaleMax, labelMinPx,
imageMinPx, imageMaxSize).
#Layouts and extensions
Built in: grid, preset, circle, concentric, breadthfirst,
random, radial — a hierarchy-aware radial tree (each subtree takes a
contiguous angular wedge sized by its weight; new in v4) —
pack — a re-pack of the disconnected components where they stand,
grouped and ordered (new in v4) —
force — a GPU-native force-directed layout that animates live at 100k
nodes — and flow — a Sugiyama-class layered layout (dagre's use case:
network-simplex ranking, weighted crossing minimization, Brandes–Köpf
coordinates; new in v4). flow replaces the dagre extension for most
uses: it emits node positions only, designed to pair with curve-style: taxi so edges route themselves and stay routed when nodes are dragged.
Choose a built-in when replacing these v3 layout extensions:
| v3 extension or app engine | v4 built-in |
|---|---|
| fcose, cose-bilkent, cola, euler, spread, d3-force, G6 gForce, Cosmos | force — alignment and relative-placement constraints, locked nodes, edgeLength mapping, live simulation with infinite, and GPU execution where supported |
| dagre, elk (layered), klay, biological-flow | flow — direction: 'rightward' for a left-to-right flow |
| G6 radial | radial |
layout-utilities separateComponents |
the pack layout (the components re-packed where they stand, grouped and ordered), packComponents: true on circle / concentric / grid / breadthfirst / radial (one drawing per component, packed), force's settle re-pack, or ctx.packComponents in an extension layout |
cose is not ported. Its option surface and per-iteration structure are
different from force; use force and review its options when porting.
cy.layout({ name: 'cose' }) throws, listing the built-ins. The cose behaviours a compound app relies
on have force counterparts: compound members cohere about their parent
(gravityCompound), edges crossing compound boundaries take elevated
ideal lengths (nestingFactor, v3's rule and default), and disconnected
components are packed into rows at the end (componentSpacing, v3's
option name). A fresh run also seeds from a spectral draft
(init: 'spectral', the default — fCoSE's approach), which is what
untangles chains and separates clusters at scale. force also supports
these fcose constraints: alignment ({ horizontal, vertical } id-array groups; a locked node pins its group) and
relativePlacement ([{ left, right, gap? } | { top, bottom, gap? }]),
with fixed nodes spelled lock(). Constrained runs take the CPU
executor, so at fcose-typical sizes they behave like fcose; validation
throws at start on unknown ids, placement cycles, and contradictory
locked members.
animate means the same thing on force as everywhere else: the sim
settles silently, then the nodes tween into place with the viewport fitting alongside — v3 cose's animate: 'end'. The
streaming run v3 spelled 'during' is animateLive: true. Executor
choice is availability-driven either way: a flat rendered graph with a
device hands integration to the GPU, so animate: false no longer runs
synchronously on the main thread — the run settles at layoutstop /
promise(), and a caller reading positions on the next line must await
one of those. animate: false still shows nothing until convergence:
the silent run integrates off-screen and lands the settle in one write.
Headless instances remain the synchronous spelling. The settle also
separates overlapping node bodies (avoidOverlap, default true; include labels with
nodeDimensionsIncludeLabels: true), which v3 cose never did.
breadthfirst on a graph of several components draws its trees as
blocks — each rank ordered tree-first, each tree a column band, the
singletons a block of rows, the bands wrapped into shelves — where v3
interleaved the trees across the whole width; one component is v3's
picture exactly. packComponents: true on the five discrete layouts
lays each component out on its own and packs the drawings.
There is no extension registry. No cytoscape.use(), no string
registration, no global state. An extension layout is an import you pass in:
import RowLayout from './row-layout.js';
cy.layout( { impl: RowLayout, ...options } ).run();The implementation is a class or object with { run( ctx ), stop?() }, where
ctx is a LayoutContext — columnar-first (nodeSlots(), live positions()
views, O(1) degreeOf, bulk setPositions) with handles still reachable at
ctx.eles. ctx.packComponents( spacing? ) is v3
layout-utilities' separateComponents in one call: it re-packs the laid-out
disconnected components into non-overlapping rows, for any extension layout
that positions components independently. LayoutContext, LayoutImpl and CustomLayout are exported
types. Core, collection and renderer extension points stay out for 4.0.
Layout lifecycle events fire on the core, exactly once per run; layout instances are not emitters.
#Worth adopting once you have ported
- Columnar and binary loading.
cytoscape.toColumnarElements( json )converts the definition form;cytoscape.serializeElements()produces one little-endianArrayBufferthatoptions.elementsandcy.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) thatfollowkeeps 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? }onforce.edgeLengthandconcentric.concentric(the column's extent normalized through'linear' | 'log' | 'sqrt'into the range;invert: truemaps large scores to short edges), and{ data, order? }ongrid.sort,circle.sortandbreadthfirst.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. Undercurve-style: taxievery 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-trackchooses the grouping (source,target, orfamilyfor a genealogy) andtaxi-track-spacingthe distance between lines. Pair it with a background-colouredline-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 failsstylesheet.schema.jsonon 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 andArray.from( eles )— andcy.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
domainkeeps a data write O(changed);'auto'is a live extent and pays O(n) only when a write actually moves it. Pindomainwhen a stream grows its own extent. - Style transitions —
transition-property/-duration/-delay/-timing-functionper sheet group, tweening whenever a restyle changes a stored channel. cy.compact()(aliascy.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'sfindNearestElementhit halos (8/24 rendered px around edges and their arrowheads for mouse/touch, 2/8 around nodes), so a press can land wherepickanswers 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 byz-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,visibilityand level of detail; async (a GPU readback), null headless. v3 had no equivalent (#2283); the geometric approximation apps used,cy.elementsInBox()overcy.extent(), still works and still ignores what is too small to draw.cy.nodeAt( x, y )(aliascy.pickNode) — the node under a rendered point, answered synchronously on the CPU, wherecy.pick()is async because an edge hit is a GPU question. v3 never had a public form (#1209); apps reached into the renderer'sfindNearestElement. Nodes only, exact (no halo), the same leaf-over-parent order aspick; headless it computes from the viewport at a device-pixel ratio of 1 rather than answering null.
#Not ported
These v3 APIs are unavailable or have different replacements:
- classes, selector strings, style functions
- Removed methods:
cy.forceRender(),cy.batchData()(a plainbatch()overdata()writes),cy.mutableElements()(it waselements()by another name),onRender/offRender(usecy.on( 'render', … )), and thebind/unbind/listen/unlistenlistener aliases — the event surface follows Node'sEventEmitterspellings (on/off/once/addListener/removeListener), pluspon - Internal methods, excluded from the public TypeScript API:
cy.renderer(),instanceString()and thesilentPosition(s)/silentShiftwrites still work but left the typed surface (@internal);cy.stats()is the public frame-stats snapshot that replacescy.renderer().stats() z-indexand companions;sortByZIndex,zDepthrestore/clone/copy,cy.json()import- event namespaces; the
vmouse*aliases and raw mouse/touch re-emits cy.notify()/noNotifications()(the renderer is dirty-driven)renderTo- per-element
font-family; viewport-fixed labels - the canvas-era performance options
Also unavailable:
cytoscape.warnings()— v4 keeps its fail-loudly contract whole: errors throw, the few recoverable conditions warn on the console, and there is no toggle over either.- Functional
preventDefault()for v4's own gesture defaults — the explicit toggles are the gesture-control surface;preventDefault()reaches the browser's default only.
See the v4 documentation for task guides and the complete API reference.
#v3 properties outside this v4 surface
This is not a compatibility list for all v3 styling. v4 does not provide selector blocks, style functions, background-blacken, border-cap, border-join, image bounds-expansion, endpoint *-or-label forms, per-side min-width or min-height bias props, or per-element font faces. Some names throw as unsupported; others have no v4 property spelling. Use the tables above and the stylesheet schema for supported property names and values.
#Options not carried forward from v3
The list above is the current v4 built-in surface. The v3 null layout and its layout-handle event-emitter methods are not among these built-ins. The direct custom-layout implementation contract is described in Layouts; this page does not add a registry, import name, or undocumented built-in.
#Differences from v3
delay(duration) is a no-op timed tween that composes with other channels;
delayAnimation(duration) returns a handle for promise sequencing. These
methods belong to collections. The v3 viewport members cy.delay() and
cy.delayAnimation() are unavailable. Use collection delay methods only for elements.
clearQueue() has no v4 counterpart because there is no queue. Use
stop()/handle methods to stop work that is actually running.
#Migrating selector strings
Coming from v3? The cy.$ alias remains for symmetry and compatibility, but it takes the
same query/predicate inputs as cy.filter(). A selector string such as
'node:selected' throws with a migration explanation. cy.getElementById(id)
is the direct O(1) id lookup for a single id; it avoids building a query.
Core event delegation also uses a predicate, not a selector. For example,
cy.on('tap', node => node.isNode(), handler) runs only for events whose
target passes that function. Element collection events bind to each element in
the receiver. See events for event ownership and removal.