Skip to content

Notation & glossary

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

#Graph theory basics

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

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

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

#Nodes, edges and compounds

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

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

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

#Model and rendered coordinates

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.

#Three element input forms

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

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

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

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

#What each form carries

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

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

#A session is more than its elements

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

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

#Where typing stops

Typed element data does not reach:

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

#JSON schemas

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

#Public type glossary

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

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

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

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

All guides · Alphabetical API index · Read continuously