add() inserts new definitions, columnar data or wire data. Edges in a payload
can refer to nodes supplied alongside them. patch() reconciles a fresh view
of the same graph by id: it updates surviving elements, removes absent ones in
reconcile mode and returns added/removed/updated collections. Reconciliation
keeps the surviving element's session state such as listeners and selection;
the payload replaces data fields rather than deep-merging them. Rewiring an
edge is a removal/addition, not an update to its identity.
// Add elements to the graph and return them as a collectioncy.add(input: | ElementsInput<NodeData, EdgeData> | Iterable<ElementDefinition<NodeData | EdgeData>>): Collection<NodeData, EdgeData>
Add elements to the graph and return them as a collection.
Takes all three input forms: the element-definition form (one object, an array, or { nodes, edges }), the columnar bulk form (typed-array columns with edge endpoints as node indices), and the binary wire buffer produced by serializeElements/cy.serialize(). Nodes are added before edges, so an edge may reference a node added in the same call. Wire and columnar inputs may carry miniature state with current positions; adding them does not rescale those coordinates.
Fires an add event per element. Inside a batch the first style application of the new elements defers to the outermost endBatch(), so style-derived reads (width(), label()) may be stale until then.
Graph-level data() in a wire buffer is ignored here, where options.elements applies it: adding elements to a populated graph must not overwrite that graph's own data(). Apply it explicitly with cy.data( deserializeElements( buf).data) if that is what you want.
Any iterable of element definitions is accepted too — a generator, a Set, a Map's values() — and is read once into an array, then added exactly as that array would be. A wire buffer's typed-array view is iterable as well, and is decoded as a wire payload, never walked as definitions.
Node references (experimental with the wire format until 4.x): the
ids of nodes this payload does not carry but indexes — an edge endpoint
or a node parent nodes.count + i names refs[i]. Each must name a node
already in the graph when the payload loads (an earlier chunk of a
cy.load(), or anything cy.add() put there); one that does not throws
before anything is added. Each id resolves once however many edges index
it, which is what makes a chunk's cut edges as cheap as its own. The
factory's options.elements loads into an empty graph, so a payload with
refs cannot load there; cy.patch() refuses one. Build it from
definitions with toColumnarElements( defs, { refs: true }).
if input is a collection: removed elements cannot be restored (MIGRATING.md, "Removed elements are terminally dead") — add the definitions you kept, e.g. from eles.jsons() taken before the removal
// Remove elements from the graphcy.remove<Data>(eles: Collection<NodeData, EdgeData, Data>): Collection<NodeData, EdgeData, Data>
Remove elements from the graph. Removing a node removes its connected edges, and removing a compound parent removes its descendants. Equivalent to eles.remove().
// Reconcile a fresh payload into the live graph by id: the payload is the next state of the same graph — the next query result, a server's refresh — and the patch computes what to add, remove and update, applies it as one batch, and returns what it didcy.patch(input: ElementsInput<NodeData, EdgeData>, options?: PatchOptions): PatchDiff<NodeData, EdgeData>
Reconcile a fresh payload into the live graph by id: the payload is the next state of the same graph — the next query result, a server's refresh — and the patch computes what to add, remove and update, applies it as one batch, and returns what it did. A surviving element keeps selection, bypasses, running animations, listeners and scratch. Position follows the payload when carried; miniature state and its applied factor are adopted together with those current positions. The sheet, viewport and graph-level data() are never touched — elements only.
cy.json() is export-only; use a fresh core to restore a serialized session. patch() updates an existing graph. It reconciles a data refresh, and it takes all three input forms — definition, columnar and wire — through the load path's one funnel.
The rules, per payload element, keyed on its id: - Survives when the graph holds the id in the same group (and, for an edge, the same source and target). Its data record is replaced, not deep-merged: a key the payload element lacks is cleared, and a value compares structurally, so a fresh payload equal to the state changes nothing. Its position is written when the payload carries one and kept when it does not — except that a locked node (or every node, under autolock) holds its position and a compound parent's derives from its children, as at load. Its parent follows the payload (none means an orphan). Its miniature state follows when carried; the payload's applied factor is installed without rescaling its already-current positions. Its selection and selectable/locked/grabbable/pannable flags are session state and are never read from the payload. - Added when the id is new, and when the payload element has no id — exactly as cy.add() would add it, flags included. - Removed and re-added when an edge's source or target changed identity (rewiring is not a patch), or when the id changed group. - Removed when the graph holds an id the payload does not name — in 'reconcile' mode, the default. In 'merge' mode it is kept, and a definition-form payload may name kept nodes as endpoints and parents. Removal cascades as remove() does.
Events: remove, add, moveout + move (a reparented survivor), data, position, and committed collapse/expand state changes fire once per element, inside the batch and after every mutation has landed; then one core-level patch event carries the diff as event.diff — for an app that only wants the summary. A patch whose payload equals the state fires no element event, writes nothing and returns an empty diff (its patch event still fires). The patch is one transaction: batchstart, the element events, patch, then batchend; inside an app's batch it joins that one, and patch fires before the app's batchend.
Node references (experimental with the wire format until 4.x): the
ids of nodes this payload does not carry but indexes — an edge endpoint
or a node parent nodes.count + i names refs[i]. Each must name a node
already in the graph when the payload loads (an earlier chunk of a
cy.load(), or anything cy.add() put there); one that does not throws
before anything is added. Each id resolves once however many edges index
it, which is what makes a chunk's cut edges as cheap as its own. The
factory's options.elements loads into an empty graph, so a payload with
refs cannot load there; cy.patch() refuses one. Build it from
definitions with toColumnarElements( defs, { refs: true }).
'reconcile' (the default): the payload is the new state, and a live
element it does not name is removed. 'merge': the payload is a set
of upserts, and a live element it does not name is kept — a
definition-form payload may then name kept nodes as endpoints and
parents.
before anything is mutated, if the payload names an id twice, if an edge lacks a source or target or names one that is not a node (in the payload, or — merge mode — in the graph), if a column does not fit the payload's counts, or on an unknown option or mode
load() progressively consumes an iterable or async iterable of chunks. It
bulk-applies each chunk and gives the renderer a frame between chunks, so a
partial graph can appear while a stream continues. Its promise resolves with
progress counts and can be cancelled. Cancellation stops pulling the source
but keeps already loaded chunks. A layout should start after the load promise
resolves. See progressive loading for readiness, fit, event and
failure details. cy.destroy() cancels active work owned by the core and
disposes its renderer.
cy.load() ingests an iterable or async iterable whose values are graph
chunks. Each chunk may use the standard element-definition array, a columnar
payload or serialized wire data. It goes through the bulk ingest path, and the
renderer gets a turn between chunks. The first chunk is drawn before the
loader requests the next one, so the page can show correct partial state while
the remaining data arrives.
An initial load starts while the core has no elements. It keeps cy.ready
pending until the first chunk is drawn (or ingested in headless mode), and fits
once to that first chunk by default. A load into a populated graph behaves
like streamed add(): it does not replace existing elements, re-fit the
viewport or apply chunk graph-level data. fit controls the one initial fit;
padding supplies its rendered-pixel padding. No later chunk changes the
viewport. Read cy.ready after calling load(), since an initial load replaces
the promise with one that resolves after the first chunk is drawn.
Each chunk emits a loadchunk event after ingestion. loadstart fires before the
source is first read, loadready follows the first drawn chunk, and loadstop
closes a completed, failed or cancelled run. These events carry a progress
snapshot { chunks, nodes, edges }. Bulk add events are also emitted for
inserted elements when listeners are registered. No loadready event is
emitted for a source that yields no chunks.
load() returns a promise with a required cancel() method. Cancelling stops
the iterator, calls its return() when available, preserves chunks already
ingested and rejects the promise with CancelledError. The loadstop event
has cancelled: true; normal completion and input failure have cancelled: false. A failed chunk rejects the promise and earlier chunks remain. A chunk
that refers to a node not yet present fails before adding any part of that
chunk. Only one load may run on a core at a time. Start a layout after the
load promise settles, so it sees the final intended graph.
load() consumes iterable values as chunks. A top-level array of element
definitions is therefore a sequence of single-definition chunks; to load the
whole array as one chunk, nest it: cy.load([[nodeA, nodeB]]). A lone
definition object is not iterable and is rejected. A columnar or wire payload
is also rejected as the source itself because its own iterable shape is not a
chunk stream; wrap that payload in a one-item iterable such as
cy.load([columnarPayload]). For a single addition, prefer cy.add(payload).
fit fits once to the first chunk (default on for an initial load, off into a populated graph); padding is rendered-pixel padding for that fit (default 0).
Use 5–20 chunks, with a small first chunk. A chunk costs about 1.5 ms of fixed
overhead headless, plus a frame in a page. Node references repeat ids across
chunks: +6% vertex-closed and +12% nodes-first at 10 chunks. Choose a small first chunk to show useful content early, then adjust later
chunk sizes for your network and graph.
For ndex-x-large (19.6k nodes, 465k edges) from a wire payload, in milliseconds
to the first frame and to the whole graph:
Link
Scene
First
Whole
none
monolithic
902
902
none
vertex-closed, 10 chunks
374
1,107
100 Mbit/s
monolithic
1,960
1,960
100 Mbit/s
vertex-closed, 10 chunks
110
1,210
20 Mbit/s
monolithic
6,176
6,176
20 Mbit/s
vertex-closed, 10 chunks
350
5,667
With the whole payload in hand, the first frame comes about 2× sooner and the
whole graph about 23% later. Over a link, progressive loading wins both,
because ingest overlaps the transfer.
// Progressive ingest: load the graph chunk by chunk from an async iterable — a streamed response, a server's pages — and show a correct partial graph before the last byte arrivescy.load(source: | AsyncIterable<ElementsInput<NodeData, EdgeData>> | Iterable<ElementsInput<NodeData, EdgeData>>, options?: LoadOptions): LoadRun
Progressive ingest: load the graph chunk by chunk from an async iterable — a streamed response, a server's pages — and show a correct partial graph before the last byte arrives. Each chunk is any input form (definition, columnar or wire); a chunk may name nodes an earlier chunk loaded — by id in the definition form, and through node references (refs) in the columnar and wire forms, which is what keeps a chunk's cut edges as cheap as its own. A plain iterable (an array of chunks) works too.
Every chunk lands through the bulk load path — one bulk style pass, no per-element handle — and the renderer gets a turn between chunks, even when the source hands them over synchronously; the second chunk is not asked for until the first is drawn. Every element drawn is correct; completeness arrives — a frame may show some of the graph, never a wrong piece of it.
An initial load — one that starts on an instance holding no elements, the streamed counterpart of options.elements — holds cy.ready until its first chunk is drawn (headless: until it is in the model), fits the viewport once to that chunk and then holds it (never a re-fit per chunk; fit: false keeps the viewport as it is), and applies the graph-level data() a wire chunk carries. The load re-points cy.ready, so read it after calling load() — a reference taken before resolves on the renderer alone. A load into a populated graph is a streamed cy.add(): cy.ready, the viewport and data() are left alone. Positions are the payload's (the preset layout case); a layout cannot start while a load runs — run it once the promise resolves.
Events: loadstart; loadchunk after each chunk (with add per element while anyone listens for it, as the bulk path emits them); loadready once the first chunk is drawn; loadstop when the load ends — completed, failed or cancelled (event.cancelled). Each carries event.progress: { chunks, nodes, edges } so far.
Completion is the returned promise, resolving with the final progress; it carries cancel() (contract): cancelling stops pulling chunks, closes the source's iterator, keeps what has landed, and rejects with a CancelledError. cy.destroy() cancels a running load. A chunk that fails to ingest rejects the load; the chunks before it stay, and a node reference that names no node fails its chunk before anything of it is added.
{ fit, padding }: fit once to the first chunk (default: on for an initial load), and that fit's padding
Fields of options
Name
Description
fit: boolean?
Fit the viewport once, to the first chunk, and then hold it —
a load never re-fits per chunk, so the screen does not jump as the
graph fills in. Default: true for an initial load (one that starts
on an instance holding no elements), false for a load into a
populated graph.
padding: number?
the rendered-space padding of that fit, in px (default 0, as cy.fit())
synchronously, when source is not an (async) iterable of chunks (a single payload is refused — pass [ payload ]), on an unknown option, while another load is running on this instance, or on a destroyed instance
Use cy.batch(fn) when multiple writes should defer style application to one
outermost flush. Batches nest; the close happens even if the callback throws.
Inside a batch, the model writes have landed but style-derived reads such as
width() and label() can be stale until endBatch(). This is different from
deferred graph writes. Sheet parsing and validation still occur at the
cy.style(sheet) call site, while the style application waits for the batch
flush.
A cy.load() is not a transaction: it spans macrotasks and has its own
lifecycle. Layouts, animations and gestures write outside any batch unless the
app wraps them. cy.style(sheet) in a batch applies at the flush, but the wire
format carries no style, so an app undoing sheet changes keeps its own sheet
history.
To build undo, listen for batchstart and batchend around application
changes. Save element payloads with serialize() and reconcile them with
patch() when appropriate. Keep stylesheet, viewport and selection history
separately if your undo operation must restore them: an element patch does
not restore those parts of the session.
// Reclaim unused storage after removing many elementscy.compact(): this
Reclaim unused storage after removing many elements. Existing element handles, listeners and drawing order are preserved.
Compaction normally happens automatically. Call this method to choose when its work occurs, for example after a bulk removal. It throws during a batch and defers with a warning while a GPU force layout is running.
// Open a batch: defer style application until the matching endBatch()cy.startBatch(): this
Open a batch: defer style application until the matching endBatch(). Pairs nest — only the outermost endBatch() flushes. Prefer batch( fn), which cannot leak a depth on an exception.
The outermost open is a transaction and fires batchstart on the core — before any of the batch's mutations, with batching() already true, so a listener sees the state the transaction starts from (the place to take an undo snapshot) and anything it mutates belongs to the transaction. A nested open fires nothing.
Close a batch. Only the outermost close applies deferred styles and fires a batchend event. After that event, style reads reflect the completed batch. Nested closes and calls without an open batch do nothing.
batchend follows all element events and any patch summary produced by the batch. It carries no diff: listen to the events between batchstart and batchend to collect the changes.
// Run fn inside a startBatch()/endBatch() paircy.batch(fn: () =>void): this
Run fn inside a startBatch()/endBatch() pair. The batch closes even if fn throws, so this is the form to prefer. As the outermost pair it is one transaction, batchstart … batchend; there is no rollback, so a throwing fn still ends in batchend, with the mutations that landed before the throw.
Parameters
Name
Description
fn: () => void
the mutations to batch; its return value is discarded