Skip to content

Task recipes

Combine reference methods into common application tasks.

These recipes combine small operations into application tasks. The reference's short examples use the three-node path below unless they say they require a browser, an event handler, an animation handle or a layout handle. Start each example with a fresh graph; examples that remove or destroy objects are deliberately independent.

#Example graph

import cytoscape from 'cytoscape/headless';
const cy = cytoscape({
headless: true,
styleEnabled: true,
layout: { name: 'preset' },
elements: [
{ data: { id: 'a', score: 1 }, position: { x: 0, y: 0 } },
{ data: { id: 'b', score: 2 }, position: { x: 50, y: 0 } },
{ data: { id: 'c', score: 3 }, position: { x: 100, y: 0 } },
{ data: { id: 'ab', source: 'a', target: 'b', weight: 2 } },
{ data: { id: 'bc', source: 'b', target: 'c', weight: 3 } },
],
});
const eles = cy.elements();

cy owns the graph; eles initially contains five elements. An event in an example is the argument supplied to an event handler. An ani is obtained with cy.animation({ pan: { x: 10, y: 10 }, duration: 1 }); layout is obtained with cy.layout({ impl: { run(ctx) { ctx.layoutPositions((node, i) => ({ x: i * 40, y: 0 }), { fit: false }); } } }). A ctx is supplied to a custom layout's run(ctx) method. Call cy.destroy() when the task ends.

#Add and style a neighbourhood

Add nodes before using their ids in subsequent calls. A single payload may contain both new nodes and their edges. Use one batch for related data writes; style-derived reads belong after the batch ends.

const added = cy.add([
{ data: { id: 'd', score: 4 } },
{ data: { id: 'cd', source: 'c', target: 'd', weight: 1 } },
]);
cy.batch(() => {
added.nodes().data('reviewed', true);
cy.getElementById('c').data('reviewed', true);
});
cy.style({ nodes: { 'background-color': '#369', width: 30 } });
console.log(cy.getElementById('d').data('reviewed')); // true

Reference: add, batch, element data, stylesheet.

#Trace a weighted route

Choose the graph scope, direction and weight explicitly. On the example path, the cost from a to c is 2 + 3 = 5. Dijkstra is synchronous for this execution form; methods that return an AlgoRun require await run.

const result = eles.dijkstra({
root: cy.getElementById('a'),
directed: true,
weight: edge => edge.data('weight'),
});
const destination = cy.getElementById('c');
console.log(result.distanceTo(destination)); // 5
console.log(result.pathTo(destination).nodes().map(node => node.id()));
// ['a', 'b', 'c']

Reference: Dijkstra, lookup by id, mapping collections.

#Attach and remove a delegated listener

Store the predicate and handler so cleanup uses the same function objects. Delegation follows targets added after the listener was attached. Event names match literally; an application event named review is independent of review.ui.

const isNode = ele => ele.isNode();
const reviewed = [];
const onReview = event => reviewed.push(event.target.id());
cy.on('review', isNode, onReview);
cy.getElementById('a').emit('review');
cy.off('review', isNode, onReview);
cy.getElementById('b').emit('review');
console.log(reviewed); // ['a']

Reference: listen, remove listener, emit, event target.

#Save graph data and recreate a core

The compact wire payload carries graph data and element state covered by its contract. Keep stylesheet, viewport and other application state separately. Adding a wire payload into an existing graph deliberately ignores graph-level data; constructor loading applies it.

cy.data('title', 'Three-node path');
const buffer = cy.serialize();
const restored = cytoscape({ headless: true, elements: buffer });
console.log(restored.nodes().length); // 3
console.log(restored.data('title')); // 'Three-node path'
restored.destroy();

Reference: serialize, construct a core, graph data.

All guides · Alphabetical API index · Read continuously