Skip to content

Graph manipulation

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

#Loading, mutation and batching

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

#cy.add(input)

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

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

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

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

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

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

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

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

Fields of input
NameDescription
columnar: true

discriminant so the loader can tell the forms apart

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

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

data: DefinitionData<Data>?
group: GroupName?

inferred from data.source/data.target when omitted

position: Position?

nodes only

collapsed: boolean?

nodes only: persisted miniature-compound state

appliedCollapseScale: number?

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

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

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

Returns Collection<NodeData, EdgeData>

a collection of the added elements

Example

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

Example graph and handle setup

Throws

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

#cy.remove(eles)

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

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

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

the elements to remove

Returns Collection<NodeData, EdgeData, Data>

the removed elements

Example

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

Example graph and handle setup

#cy.patch(input, options?)

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

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

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

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

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

Parameters
NameDescription
input: ElementsInput<NodeData, EdgeData>

the payload, in definition, columnar or wire form

options: PatchOptions?

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

Fields of input
NameDescription
columnar: true

discriminant so the loader can tell the forms apart

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

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

data: DefinitionData<Data>?
group: GroupName?

inferred from data.source/data.target when omitted

position: Position?

nodes only

collapsed: boolean?

nodes only: persisted miniature-compound state

appliedCollapseScale: number?

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

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

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

Fields of options
NameDescription
mode: PatchMode?

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

Returns PatchDiff<NodeData, EdgeData>

the diff: the added, removed and updated collections

Example

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

Example graph and handle setup

Throws

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

#Progressive loading

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

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

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

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

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

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

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

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

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

#Sizing a load

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

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

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

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

#cy.load(source, options?)

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

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

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

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

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

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

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

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

options: LoadOptions?

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

Fields of options
NameDescription
fit: boolean?

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

padding: number?

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

Returns LoadRun

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

Example

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

Example graph and handle setup

Throws

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

#Batching and compaction

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

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

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

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

#cy.compact()

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

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

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

Returns this

Example

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

Example graph and handle setup

Also spelled cy.gc.

#cy.startBatch()

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

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

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

Returns this

this core, for chaining

Example

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

Example graph and handle setup

#cy.endBatch()

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

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

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

Returns this

this core, for chaining

Example

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

Example graph and handle setup

#cy.batch(fn)

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

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

Parameters
NameDescription
fn: () => void

the mutations to batch; its return value is discarded

Returns this

this core, for chaining

Example

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

Example graph and handle setup

All guides · Alphabetical API index · Read continuously