### Install Cytoscape.js via Package Manager
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/getting-started.md
Commands to install the Cytoscape.js library using common package managers.
```bash
npm install cytoscape
```
```bash
bower install cytoscape
```
--------------------------------
### Install Dependencies
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Install project dependencies using npm. This should be done when you first start working on the project.
```bash
npm install
```
--------------------------------
### Cytoscape.js - Node Styling Example
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/webgl.md
Provides a basic example of styling a node in Cytoscape.js, setting its background color and displaying its ID as a label.
```javascript
{
selector: 'node',
style: {
'background-color': '#666',
'label': 'data(id)'
}
}
```
--------------------------------
### Import Cytoscape.js in JavaScript Environments
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/getting-started.md
Demonstrates how to import the library using different module systems including ESM, CommonJS, and AMD.
```javascript
import cytoscape from 'cytoscape';
```
```javascript
var cytoscape = require('cytoscape');
```
```javascript
require(['cytoscape'], function(cytoscape){
// ...
});
```
--------------------------------
### Initialize Cytoscape Instance
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/getting-started.md
Initializes a new Cytoscape graph instance by providing a container element or running in headless mode.
```javascript
var cy = cytoscape({
container: document.getElementById('cy')
});
```
```javascript
var cy = cytoscape({
container: $('#cy')
});
```
--------------------------------
### Initialize Cytoscape.js with Basic Options
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/getting-started.md
Demonstrates how to initialize a Cytoscape.js instance with essential options such as the rendering container, graph elements, stylesheet, and layout. This is a fundamental step for creating a graph visualization.
```javascript
var cy = cytoscape({
container: document.getElementById('cy'), // container to render in
elements: [ // list of graph elements to start with
{ // node a
data: { id: 'a' }
},
{
data: { id: 'b' }
},
{
data: { id: 'ab', source: 'a', target: 'b' }
}
],
style: [ // the stylesheet for the graph
{
selector: 'node',
style: {
'background-color': '#666',
'label': 'data(id)'
}
},
{
selector: 'edge',
style: {
'width': 3,
'line-color': '#ccc',
'target-arrow-color': '#ccc',
'target-arrow-shape': 'triangle',
'curve-style': 'bezier'
}
}
],
layout: {
name: 'grid',
rows: 1
}
});
```
--------------------------------
### Install Playwright Browsers
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Install Playwright browsers before running browser coverage or the full test suite in a new environment.
```bash
npx playwright install --with-deps
```
--------------------------------
### Install Node Version Manager
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Use Node via `.nvmrc` when possible. Run `nvm use` or `mise en` to activate the correct Node.js version.
```bash
nvm use
```
```bash
mise en
```
--------------------------------
### Cytoscape.js - Edge Styling Example
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/webgl.md
Demonstrates basic styling for edges in Cytoscape.js, including line width, color, and arrow shape for directed graphs.
```javascript
{
selector: 'edge',
style: {
'width': 3,
'line-color': '#ccc',
'target-arrow-color': '#ccc',
'target-arrow-shape': 'triangle'
}
}
```
--------------------------------
### Include Cytoscape.js in HTML
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/getting-started.md
Methods for loading the Cytoscape.js library into a web page using standard script tags or ES6 modules.
```html
```
```html
```
--------------------------------
### Fit Elements to Viewport in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/animate.md
This example shows how to fit specific elements to the Cytoscape.js viewport using the animate function. It selects an element by ID and then applies the fit animation with specified padding.
```javascript
var j = cy.$('#j');
cy.animate({
fit: {
eles: j,
padding: 20
}
}, {
duration: 1000
});
```
--------------------------------
### Handle Tap Event with Promise in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/promiseOn.md
This example demonstrates how to handle a 'tap' event using a promise in Cytoscape.js. It logs a message to the console when the tap event promise is fulfilled. No external dependencies are required beyond the Cytoscape.js library itself.
```javascript
cy.pon('tap').then(function( event ){
console.log('tap promise fulfilled');
});
```
--------------------------------
### Initialize Cytoscape.js with Elements JSON
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/notation.md
Demonstrates how to configure a Cytoscape instance using either a flat array of elements or a group-keyed object structure. These examples define nodes, edges, positions, and styling properties required for graph initialization.
```javascript
cytoscape({
container: document.getElementById('cy'),
elements: [
{ data: { id: 'n1' }, position: { x: 100, y: 100 } },
{ data: { id: 'n2' }, renderedPosition: { x: 200, y: 200 } },
{ data: { id: 'e1', source: 'n1', target: 'n2' } }
],
layout: { name: 'preset' }
});
```
```javascript
cytoscape({
container: document.getElementById('cy'),
elements: {
nodes: [{ data: { id: 'a' } }, { data: { id: 'b' } }],
edges: [{ data: { id: 'ab', source: 'a', target: 'b' } }]
},
layout: { name: 'grid', rows: 1 }
});
```
--------------------------------
### String Style Format Example
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/style.md
Defines node background color using a simple string format. This format is useful for loading styles from a server.
```css
/* comments may be entered like this */
node {
background-color: green;
}
```
```javascript
cytoscape({
container: document.getElementById('cy'),
// ...
style: 'node { background-color: green; }' // probably previously loaded via ajax rather than hardcoded
// , ...
});
```
--------------------------------
### Select Elements and Check for Commonality in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/anySame.md
This example demonstrates how to select specific elements by ID and then check if any of the selected elements are common between two sets. It utilizes Cytoscape.js's selector engine and the `anySame` function.
```javascript
var j = cy.$('#j');
var guys = cy.$('#j, #g, #k');
console.log( 'any same ? ' + j.anySame(guys) );
```
--------------------------------
### Valid Background Image Styling
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/style.md
Example of how to style a node's background image using JSON. This includes specifying image URLs, background fit, and opacity.
```json
{
'background-image': [
'https://upload.wikimedia.org/wikipedia/commons/b/b4/High_above_the_Cloud_the_Sun_Stays_the_Same.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Pigeon_silhouette_4874.svg/1000px-Pigeon_silhouette_4874.svg.png'
],
'background-fit': 'cover cover',
'background-image-opacity': 0.5
}
```
--------------------------------
### Plain JSON Style Format Example
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/style.md
Defines node background color using the plain JSON format. This is a common and flexible way to define styles, especially when dynamic.
```javascript
cytoscape({
container: document.getElementById('cy'),
// ...
style: [
{
selector: 'node',
style: {
'background-color': 'red'
}
}
// , ...
]
// , ...
});
```
--------------------------------
### Animate Graph Element and Control Playback (JavaScript)
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/animation/reverse.md
This example shows how to animate a specific graph element ('#j') in Cytoscape.js. It demonstrates setting style changes, duration, playing the animation, and using promises to chain subsequent actions like reversing and replaying the animation. No external dependencies are required beyond Cytoscape.js itself.
```javascript
var jAni = cy.$('#j').animation({
style: {
'background-color': 'red',
'width': 75
},
duration: 1000
});
jAni
.play() // start
.promise('completed').then(function(){
jAni
.reverse() // switch animation direction
.rewind() // optional but makes intent clear
.play() // start again
;
})
;
```
--------------------------------
### Function Style Format Example
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/style.md
Defines node background color using the function stylesheet format. This provides a programmatic way to define styles.
```javascript
cytoscape({
container: document.getElementById('cy'),
// ...
style: cytoscape.stylesheet()
.selector('node')
.style({
'background-color': 'blue'
})
// ...
// , ...
});
```
--------------------------------
### Animate Pan and Zoom in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/animate.md
This example demonstrates how to manually pan and zoom the Cytoscape.js graph using the animate function. It takes target pan coordinates and zoom level, along with a duration for the animation.
```javascript
cy.animate({
pan: { x: 100, y: 100 },
zoom: 2
}, {
duration: 1000
});
```
--------------------------------
### Cytoscape.js Selector and Neighbor Check
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/allAreNeighbors.md
This example demonstrates how to select elements by ID and check if all selected elements are neighbors of another element using Cytoscape.js selectors. It logs the boolean result to the console. No external dependencies are required beyond the Cytoscape.js library.
```javascript
var j = cy.$('#j');
var gAndK = cy.$('#g, #k');
console.log( 'all neighbours ? ' + j.allAreNeighbors(gAndK) );
```
--------------------------------
### Animate Cytoscape.js Element and Pause Animation
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/animation/pause.md
This example demonstrates how to animate a specific Cytoscape.js element by changing its background color and width. It also shows how to pause the animation midway using setTimeout. This requires the Cytoscape.js library to be included in the project.
```javascript
var j = cy.$('#j');
var jAni = j.animation({
style: {
'background-color': 'red',
'width': 75
},
duration: 1000
});
jAni.play();
// pause about midway
setTimeout(function(){
jAni.pause();
}, 500);
```
--------------------------------
### Performing A* Pathfinding and Selecting the Path (JavaScript)
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/aStar.md
This example demonstrates how to initiate the A* pathfinding algorithm in Cytoscape.js using a root and goal selector. It then shows how to select the found path on the graph for visualization or further interaction. This is a common use case for pathfinding in graph visualizations.
```javascript
var aStar = cy.elements().aStar({ root: "#j", goal: "#e" });
aStar.path.select();
```
--------------------------------
### Select Elements and Check Condition in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/allAre.md
This example demonstrates how to select multiple elements by their IDs ('j' and 'e') using Cytoscape.js selectors. It then checks if all selected elements satisfy a given condition (weight > 50) using the `allAre` function. This is useful for filtering and validating graph elements based on their properties.
```javascript
var jAndE = cy.$('#j, #e');
console.log( 'j and e all have weight > 50 ? ' + jAndE.allAre('[weight > 50]') );
```
--------------------------------
### Example Usage of Degree Centrality Calculation - Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/degreeCentralityNormalized.md
This example demonstrates how to obtain and use the degree centrality calculation function from Cytoscape.js. It initializes the degree centrality calculation and logs the degree of a specific node ('#j') to the console.
```javascript
var dcn = cy.$().dcn();
console.log( 'dcn of j: ' + dcn.degree('#j') );
```
--------------------------------
### Handle and Emit Tap Events in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/emit.md
This snippet shows how to register a listener for 'tap' events and manually emit a 'tap' event. It demonstrates basic event interaction within the Cytoscape.js graph.
```javascript
cy.on('tap', function(evt, f, b){
console.log('tap', f, b);
});
cy.emit('tap', ['foo', 'bar']);
```
--------------------------------
### Animate Graph Element Background Color and Width with Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/animation/progress.md
This example shows how to animate a specific graph element ('#j') by changing its background color to red and its width to 75. The animation has a duration of 1000 milliseconds. It also demonstrates how to set the animation progress to 50% before playing it.
```javascript
var jAni = cy.$('#j').animation({
style: {
'background-color': 'red',
'width': 75
},
duration: 1000
});
// set animation to 50% and then play
jAni.progress(0.5).play();
```
--------------------------------
### Run Random Layout and Handle Layout Stop Event in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/layout/promiseOn.md
This snippet demonstrates how to initialize a 'random' layout for a Cytoscape.js graph, run the layout, and asynchronously handle the 'layoutstop' event using a Promise. It logs a message to the console when the layout has finished.
```javascript
var layout = cy.layout({
name: 'random'
});
layout.pon('layoutstop').then(function( event ){
console.log('layoutstop promise fulfilled');
});
layout.run();
```
--------------------------------
### Applying Karger-Stein Algorithm and Selecting Cut (JavaScript)
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/kargerStein.md
This example demonstrates how to apply the Karger-Stein algorithm using Cytoscape.js and then select the resulting cut edges. It first calls the `kargerStein()` method on the elements and then uses the `select()` method on the returned `cut` collection.
```javascript
var ks = cy.elements().kargerStein();
ks.cut.select();
```
--------------------------------
### Using Floyd-Warshall to Find and Select Shortest Path (JavaScript)
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/floydWarshall.md
Example demonstrating how to initialize the Floyd-Warshall algorithm on Cytoscape.js elements and then use the resulting object to find and select the shortest path between two specified nodes.
```javascript
var fw = cy.elements().floydWarshall();
fw.path('#k', '#g').select();
```
--------------------------------
### Manage element scratchpad data in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/scratch.md
Demonstrates how to set, get, and manipulate namespaced scratchpad data on a Cytoscape element. Using namespaces prevents collisions with extensions, and the underscore prefix is recommended for application-level data.
```javascript
var j = cy.$('#j');
// entire scratchpad:
// be careful, since you could clobber over someone else's namespace or forget to use one at all!
var fooScratch = j.scratch()._foo = {};
// ... now you can modify fooScratch all you want
// set namespaced scratchpad to ele:
// safer, recommended
var fooScratch = j.scratch('_foo', {});
// ... now you can modify fooScratch all you want
// get namespaced scratchpad from ele (assumes set before)
var fooScratch = j.scratch('_foo');
// ... now you can modify fooScratch all you want
```
--------------------------------
### Get Neighborhood Intersection in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/intersection.md
This example demonstrates how to get the neighborhood of two specific nodes ('j' and 'e') and then find the intersection of these neighborhoods using Cytoscape.js. It utilizes the neighborhood() and intersection() methods.
```javascript
var jNhd = cy.$('#j').neighborhood();
var eNhd = cy.$('#e').neighborhood();
jNhd.intersection( eNhd );
```
--------------------------------
### Run Full Test Suite
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Run the complete test suite. Use this if the change is broad or you are unsure which specific tests to run.
```bash
npm test
```
--------------------------------
### Cytoscape.js Betweenness Centrality Calculation Example
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/betweennessCentrality.md
This JavaScript example demonstrates how to calculate and log the betweenness centrality of a node using Cytoscape.js. It first gets the betweenness object for all nodes and then accesses the 'betweenness' method to retrieve the value for a specific node identified by '#j'.
```javascript
var bc = cy.$().bc();
console.log( 'bc of j: ' + bc.betweenness('#j') );
```
--------------------------------
### Build All Bundles
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Build all project bundles. This is typically only necessary if you are modifying the build system itself.
```bash
npm run build
```
--------------------------------
### Configure CSS for Cytoscape Container
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/getting-started.md
Defines the required CSS styles for the DOM element that will host the Cytoscape graph, ensuring proper rendering dimensions.
```css
#cy {
width: 300px;
height: 300px;
display: block;
}
```
--------------------------------
### Handle Animation Completion with Cytoscape.js Promises
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/animation/promise.md
This example shows how to execute a callback function after an animation in Cytoscape.js has finished playing. It defines an animation with a style change and duration, then uses the `play().promise()` method to get a promise that resolves when the animation is complete. A `then()` block is used to log a message indicating the animation has finished.
```javascript
var jAni = cy.$('#j').animation({
style: {
height: 60
},
duration: 1000
});
jAni.play().promise().then(function(){
console.log('animation done');
});
```
--------------------------------
### Cytoscape.js Initialization Options
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/init.md
Demonstrates the extensive initialization options available for Cytoscape.js, including container, elements, style, layout, viewport, and interaction settings. All options are optional.
```javascript
var cy = cytoscape({
// very commonly used options
container: undefined,
elements: [ /* ... */ ],
style: [ /* ... */ ],
layout: { name: 'grid' /* , ... */ },
data: { /* ... */ },
// initial viewport state:
zoom: 1,
pan: { x: 0, y: 0 },
// interaction options:
minZoom: 1e-50,
maxZoom: 1e50,
zoomingEnabled: true,
userZoomingEnabled: true,
panningEnabled: true,
userPanningEnabled: true,
boxSelectionEnabled: true,
selectionType: 'single',
touchTapThreshold: 8,
desktopTapThreshold: 4,
autolock: false,
autoungrabify: false,
autounselectify: false,
multiClickDebounceTime: 250,
// rendering options:
headless: false,
styleEnabled: true,
hideEdgesOnViewport: false,
textureOnViewport: false,
motionBlur: false,
motionBlurOpacity: 0.2,
wheelSensitivity: 1,
pixelRatio: 'auto'
});
```
--------------------------------
### Generate Documentation
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Generate project documentation. This command is relevant for changes affecting the documentation pipeline.
```bash
npm run docs
```
--------------------------------
### Basic Cytoscape.js Initialization
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/init.md
Initializes a Cytoscape.js instance with default options. This is useful for creating an empty graph.
```javascript
var cy = cytoscape({ /* options */ });
```
--------------------------------
### Get and Set Graph State with cy.json()
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/json.md
The cy.json() function can be used to get the entire graph state or to set specific parts of the graph's state, such as elements, style, or initialisation options.
```APIDOC
## GET /core/initialisation
### Description
Returns the entire graph state as a JSON object. This is useful for saving the current state of the graph.
### Method
GET
### Endpoint
`cy.json()`
### Parameters
None
### Request Example
```js
// No request body for GET
```
### Response
#### Success Response (200)
- **`elements`** (array) - An array of all nodes and edges in the graph.
- **`style`** (array) - The current stylesheet applied to the graph.
- **`zoom`** (number) - The current zoom level of the graph.
- **`pan`** (object) - The current pan position of the graph.
#### Response Example
```json
{
"elements": [
{ "data": { "id": "node1" } },
{ "data": { "id": "edge1", "source": "node1", "target": "node1" } }
],
"style": [
{ "selector": "node", "style": { "background-color": "red" } }
],
"zoom": 1,
"pan": { "x": 0, "y": 0 }
}
```
## POST /core/initialisation
### Description
Sets the graph state using a JSON object. This allows for declarative changes to the graph, including updating elements, style, zoom, and pan.
### Method
POST
### Endpoint
`cy.json( cyJson )`
### Parameters
#### Request Body
- **`cyJson`** (object) - A JSON object containing the state to set. Supports all mutable initialisation options.
- **`elements`** (array) - An array of elements to add, mutate, or remove. Elements without IDs will be ignored. Existing elements are mutated as specified, new elements are added, and elements not included are removed.
- **`style`** (array) - The entire stylesheet to replace the current one. This operation can be expensive.
- **`zoom`** (number) - The new zoom level for the graph.
- **`pan`** (object) - The new pan position for the graph.
### Request Example
```json
{
"zoom": 2,
"pan": { "x": 100, "y": 50 },
"elements": [
{ "data": { "id": "node2" } },
{ "data": { "id": "edge2", "source": "node1", "target": "node2" } }
],
"style": [
{ "selector": "node", "style": { "background-color": "blue" } }
]
}
```
### Response
#### Success Response (200)
No specific response body is returned on success, the graph state is updated.
#### Response Example
```json
// No response body
```
```
--------------------------------
### Initialization Options for Rendering
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/init.md
Configuration options for initializing Cytoscape.js instances, focusing on rendering behavior and performance.
```APIDOC
## Initialization Options for Rendering
### `headless`
A convenience option that initialises the instance to run headlessly. You do not need to set this in environments that are implicitly headless (e.g. Node.js). However, it is handy to set `headless: true` if you want a headless instance in a browser.
### `styleEnabled`
A boolean that indicates whether styling should be used. For headless (i.e. outside the browser) environments, display is not necessary and so neither is styling necessary --- thereby speeding up your code. You can manually enable styling in headless environments if you require it for a special case. Note that it does not make sense to disable style if you plan on rendering the graph. Also note that [`cy.destroy()`](#cy.destroy) must be called to clean up a style-enabled, headless instance.
### `hideEdgesOnViewport`
A rendering hint that when set to `true` makes the renderer not render edges while the viewport is being manipulated. This makes panning, zooming, dragging, et cetera more responsive for large graphs. This option is now largely moot, as a result of performance enhancements.
### `textureOnViewport`
A rendering hint that when set to `true` makes the renderer use a texture during panning and zooming instead of drawing the elements, making large graphs more responsive. This option is now largely moot, as a result of performance enhancements.
### `motionBlur`
A rendering hint that when set to `true` makes the renderer use a motion blur effect to make the transition between frames seem smoother. This can increase the perceived performance for a large graphs. This option is now largely moot, as a result of performance enhancements.
### `motionBlurOpacity`
When `motionBlur: true`, this value controls the opacity of motion blur frames. Higher values make the motion blur effect more pronounced. This option is now largely moot, as a result of performance enhancements.
### `wheelSensitivity`
Changes the scroll wheel sensitivity when zooming. This is a multiplicative modifier. So, a value between 0 and 1 reduces the sensitivity (zooms slower), and a value greater than 1 increases the sensitivity (zooms faster). This option is set to a sane value that works well for mainstream mice (Apple, Logitech, Microsoft) on Linux, Mac, and Windows. If the default value seems too fast or too slow on your particular system, you may have non-default mouse settings in your OS or a niche mouse. You should not change this value unless your app is meant to work only on specific hardware. Otherwise, you risk making zooming too slow or too fast for most users.
### `pixelRatio`
Overrides the screen pixel ratio with a manually set value (`1.0` recommended, if set). This can be used to increase performance on high density displays by reducing the effective area that needs to be rendered, though this is much less necessary on more recent browser releases. If you want to use the hardware's actual pixel ratio, you can set `pixelRatio: 'auto'` (default).
```
--------------------------------
### Watch for Changes and Debug
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Run the watch command for manual visual and interaction testing in the `debug/` directory. Useful for renderer, interaction, and gesture changes.
```bash
npm run watch
```
--------------------------------
### Initialize Cytoscape.js Graph
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/webgl.md
Demonstrates the basic initialization of a Cytoscape.js graph. It requires a container element and optionally accepts configuration options for layout, style, and data.
```javascript
var cy = cytoscape({
container: document.getElementById('cy'),
elements: [
{ data: { id: 'one' } },
{ data: { id: 'two' } },
{
data: {
source: 'one',
target: 'two'
}
}
],
style: [
{
selector: 'node',
style: {
'background-color': '#666',
'label': 'data(id)'
}
},
{
selector: 'edge',
style: {
'width': 3,
'line-color': '#ccc',
'target-arrow-color': '#ccc',
'target-arrow-shape': 'triangle'
}
}
],
layout: {
name: 'grid',
rows: 1
}
});
```
--------------------------------
### Set and Get Element Data in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/data.md
Demonstrates how to set and get data associated with a Cytoscape.js graph element. This includes setting single fields, multiple fields at once, and retrieving a specific field's value. Ensure data is JSON-serialisable.
```javascript
var j = cy.$('#j');
// set the weight field in data
j.data('weight', 60);
// set several fields at once
j.data({
name: 'Jerry Jerry Dingleberry',
height: 176
});
var weight = j.data('weight');
```
--------------------------------
### Initialize Hotjar Tracking
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/template.html
This code snippet initializes Hotjar for user behavior analysis. Include this in your HTML to enable session recordings and feedback polls.
```javascript
(function(h,o,t,j,a,r){
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
h._hjSettings={hjid:3578518,hjsv:6};
a=o.getElementsByTagName('head')[0];
r=o.createElement('script');r.async=1;
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
a.appendChild(r);
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
```
--------------------------------
### Initialize WebGL2 Context and Shaders for Upscaling
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/debug/webgl/upscaler.html
Sets up a WebGL2 rendering context, compiles vertex and fragment shaders, and configures vertex array objects (VAOs) for texture mapping. This is a prerequisite for applying post-processing effects like FXAA to canvas elements.
```javascript
function initWebGL() {
gl = webglCanvas.getContext('webgl2', { antialias: true });
if (!gl) { console.error('WebGL2 not supported'); return; }
const vertexShaderSource = `#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() { gl_Position = vec4(a_position, 0, 1); v_texCoord = a_texCoord; }`;
const fragmentShaderSource = `#version 300 es\nprecision mediump float;\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nout vec4 outColor;\nvoid main() { outColor = texture(u_texture, v_texCoord); }`;
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
webglProgram = createProgram(gl, vertexShader, fragmentShader);
// ... buffer and attribute setup code ...
}
```
--------------------------------
### Access Cytoscape Instance
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/template.html
This code snippet shows how to access the Cytoscape instance globally, typically available as `window.cy` after initialization.
```javascript
window.cy
```
--------------------------------
### Apply Mid-Animation Style Update with Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/animation/promise.md
This example demonstrates how to update an element's style during an animation in Cytoscape.js. It uses the `progress()` method to set the animation to a specific point (50%) and then applies the style changes. The `promise('frame')` is used to log a message once the style update at that frame is complete.
```javascript
var jAni = cy.$('#j').animation({
style: {
'background-color': 'red',
'width': 75
},
duration: 1000
});
jAni.progress(0.5).apply().promise('frame').then(function(){
console.log('j has now has its style at 50% of the animation');
});
```
--------------------------------
### Run JavaScript and Module Tests
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Run JavaScript and module tests. This is recommended for source or algorithm changes.
```bash
npm run test:js
```
```bash
npm run test:modules
```
--------------------------------
### Cytoscape.js Initialization with Container
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/init.md
Initializes Cytoscape.js and specifies a DOM element for rendering the graph. Ensure the container element exists and has defined dimensions.
```javascript
var cy = cytoscape({
container: document.getElementById('cy')
});
```
--------------------------------
### GET /degree-centrality
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/degreeCentrality.md
Calculates the degree centrality for a specified root node in the graph.
```APIDOC
## GET /degree-centrality
### Description
Calculates the degree centrality of a given root node. The return structure depends on whether the graph is treated as directed or undirected.
### Method
GET
### Endpoint
/degree-centrality
### Parameters
#### Query Parameters
- **root** (string) - Required - The selector for the root node.
- **directed** (boolean) - Optional - If true, returns indegree and outdegree; if false, returns degree.
### Request Example
{
"root": "#j",
"directed": false
}
### Response
#### Success Response (200)
- **degree** (number) - The degree centrality of the root node (returned if directed is false).
- **indegree** (number) - The indegree centrality of the root node (returned if directed is true).
- **outdegree** (number) - The outdegree centrality of the root node (returned if directed is true).
#### Response Example
{
"degree": 5
}
```
--------------------------------
### Initialize Cytoscape.js Graph
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/README.md
This is the basic initialization for Cytoscape.js. Ensure you have the 'cytoscape' library imported and a container element in your HTML.
```javascript
var cy = cytoscape({
elements: myElements,
container: myDiv
});
```
--------------------------------
### Initialize Cytoscape.js Graph
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/webgl.md
This snippet demonstrates how to initialize a Cytoscape.js graph instance. It requires a container element and optionally accepts configuration options for layout, style, and data.
```javascript
var cy = cytoscape({
container: document.getElementById('cy'),
elements: [
{ data: { id: 'one', label: 'Node 1' } },
{ data: { id: 'two', label: 'Node 2' } },
{ data: { source: 'one', target: 'two', label: 'Edge 1' } }
],
style: [
{
selector: 'node',
style: {
'background-color': '#666',
'label': 'data(id)'
}
},
{
selector: 'edge',
style: {
'width': 3,
'line-color': '#ccc',
'target-arrow-color': '#ccc',
'target-arrow-shape': 'triangle',
'curve-style': 'bezier'
}
}
],
layout: {
name: 'grid'
}
});
```
--------------------------------
### Get Elements from Cytoscape.js Graph
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/webgl.md
Demonstrates how to retrieve elements from a Cytoscape.js graph using selectors. This allows you to access specific nodes or edges for manipulation or inspection.
```javascript
var nodes = cy.nodes('[id = "one"]');
var edges = cy.edges();
```
--------------------------------
### Configure FXAA and Misc Upscaler Plugins
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/debug/webgl/upscaler.html
Demonstrates the instantiation of FXAA and custom upscaler plugins with specific quality parameters. These classes are designed to process input canvas data and output to a target canvas.
```javascript
import { FxaaUpscaler } from '../../src/extensions/renderer/canvas/webgl/fxaa-upscaler.mjs';
import { UpscalerPlugin } from '../../src/extensions/renderer/canvas/webgl/misc-upscaler.js';
let fxaaUpscaler = new FxaaUpscaler({
subpixelQuality: 0.75,
edgeThreshold: 0.166,
edgeThresholdMin: 0.0833
});
let miscUpscaler = new UpscalerPlugin({
useEdgeDetection: true,
scaleFactor: 2.0
});
miscUpscaler.init(inputCanvas, outputCanvas);
```
--------------------------------
### Get Element Data in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/webgl.md
This snippet shows how to retrieve data associated with nodes and edges in a Cytoscape.js graph. The `data()` method can access properties defined in the element's data object.
```javascript
var nodeId = cy.getElementById('one').data('id');
console.log(nodeId); // Output: 'one'
```
--------------------------------
### Disable Panning in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/panningEnabled.md
This snippet demonstrates how to disable panning for a Cytoscape.js graph. It uses the `panningEnabled` method with a boolean `false` argument. This is useful for preventing accidental graph movement.
```javascript
cy.panningEnabled( false );
```
--------------------------------
### Disable Box Selection in Cytoscape.js
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/core/boxSelectionEnabled.md
Disables the box selection functionality for Cytoscape.js graphs. This prevents users from selecting multiple elements by drawing a box. It takes a boolean argument.
```javascript
cy.boxSelectionEnabled( false );
```
--------------------------------
### Execute Bellman-Ford Algorithm
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/documentation/md/collection/bellmanFord.md
Demonstrates how to initialize the Bellman-Ford algorithm on a graph element collection and use the resulting object to select the shortest path to a target node.
```javascript
var bf = cy.elements().bellmanFord({ root: "#j" });
bf.pathTo('#g').select();
```
--------------------------------
### Lint Source Files
Source: https://github.com/cytoscape/cytoscape.js/blob/unstable/AGENTS.md
Lint source files to check for code style and potential issues.
```bash
npm run lint
```