Cytoscape.js

repository·unstable·Indexed 11 days ago

https://github.com/cytoscape/cytoscape.js

A comprehensive graph theory library for the analysis and visualization of relational data, such as social networks or biological data. Version 3.35.0-unstable provides a graph theory model and an optional interactive renderer for web applications, featuring an event-driven architecture and a robust API for element animation, collection manipulation, and clustering algorithms like affinity propagation.

Tokens
83.1K
Snippets
281
Records
411
Agent score
92%

What's inside Cytoscape.js

  1. Overview of Cytoscape.js capabilities

    unstable

    Cytoscape.js is an open-source JavaScript library designed for graph theory (network) analysis and visualization.

    Key features include:

    • Interactive Visualization: Easily display and manipulate rich, interactive graphs in desktop and mobile browsers (including support for gestures like pinch-to-zoom, box selection, and panning).
    • Graph Analysis: Includes many useful functions for graph theory.
    • Headless Support: Can be run headlessly on Node.js for performing graph analysis in a terminal or on a web server without a browser environment.
    • Extensibility: Allows developers to hook into user events for deep integration into applications.
  2. WebGL Renderer Implementation Details

    unstable

    The WebGL renderer is organized into several core modules that handle different stages of the rendering pipeline:

    • renderer/canvas/index.mjs: Responsible for the initialization of the canvas and the underlying WebGL context.
    • drawing-redraw-webgl.mjs: Manages the logic for triggering redraws and the continuous drawing loop.
    • drawing-elements-webgl.mjs: Handles the specific logic for translating graph elements into WebGL draw calls.

    Developers looking to extend or debug the rendering engine should refer to these specific modules to understand how the lifecycle of a frame is managed from initialization to the final draw call.

  3. Cytoscape.js Core Features and Capabilities

    unstable

    Cytoscape.js is a highly optimized, pure JavaScript graph library designed for both front-facing applications and developer use cases. Key capabilities include:

    • Graph Manipulation & Querying: Supports selectors for terse filtering and graph querying, and set theory operations.
    • Visuals & Layout: Uses layouts for automatic or manual node positioning and stylesheets to separate presentation from data in a rendering-agnostic manner.
    • Algorithms: Includes built-in graph theory algorithms ranging from BFS to PageRank.
    • Interactivity: Provides abstracted and unified touch events with built-in support for standard gestures on both desktop and touch devices. Elements and the viewport are animatable.
    • Data Handling: Fully serializable and deserializable via JSON.
    • Extensibility: Fully extendable with support for first-party extensions and autoscaffolding for new extensions.
    • Programming Patterns: Supports functional programming patterns and provides a chainable API for convenience.
  4. What is layoutPositions() and when to use it

    unstable

    The layoutPositions() function is a core mechanism used by discrete (synchronous) layout extensions to apply new node positions to a graph.

    Important: This function is intended for use only by layout extensions. Application developers should not call layoutPositions() directly. Instead, a layout extension's run() method should calculate new positions and then allow the system to call layoutPositions() at the end of the execution to handle the actual application of those positions, animations, viewport adjustments, and zoom levels.

  5. Understand control points for bezier edges

    unstable

    In Cytoscape.js, bezier edges are composed of one or more quadratic bezier curves. Each curve is defined by three points: a start point (P0), a center control point (P1), and an end point (P2).

    When using functions to retrieve control points, Cytoscape.js specifically returns the center control point (P1). Other points, such as the endpoints, can be retrieved using other methods like edge.targetEndpoint().

    The number of control points returned depends on the curve-style:

    • curve-style: bezier (simple edge): Returns 1 point.
    • curve-style: bezier (loop): Returns 2 points.
    • curve-style: unbundled-bezier: Returns n points, where $n$ is determined by the control-point-distances and control-point-weights settings.

    Key Behaviors

    • Absolute Positions: Even if control points are defined relatively in your CSS, the returned values are the absolute model positions.
    • Directionality: Points are returned in the order of the source-to-target direction.
    • Bundled Beziers: This logic applies to the bezier curves within a bundle, but does not apply to the straight-line edge in the middle of a bundle.
    • Unbundled Bezier Join Points: For unbundled beziers, the point where two successive curves meet is the midpoint (mean) of the two control points. This join point acts as the end point (P2) for the first curve and the start point (P0) for the second curve.
  6. How Texture Garbage Collection works

    unstable

    To prevent memory leaks when styles (like fonts) change dynamically, Cytoscape.js implements a two-part garbage collection (GC) and compaction algorithm:

    1. Style Key Invalidation

    • A listener is registered via r.onUpdateEleCalcs().
    • Elements are passed to AtlasManager.invalidate(), which identifies old Style Keys no longer in use.
    • Note: For nodes with asynchronous background images, use the forceRedraw option to ensure the texture is recreated once the image loads.

    2. Garbage Collection & Compaction

    • GC is triggered by a timer and runs on the next frame if the flag is set.
    • If an Atlas contains marked keys and the OffscreenCanvas is available: A new Atlas is created, valid textures are copied over (compacting them to remove gaps), and the old one is replaced.
    • If the OffscreenCanvas has been freed: The Atlas is removed from the AtlasCollection, and the style key mappings are cleared. Unmapped keys will be redrawn on the next frame.
  7. Understand how the edge midpoint is calculated

    unstable

    The midpoint of an edge is used by default as the center for edge labels and as the target position for mid-arrows. The calculation of this point depends on the curve-style used for the edge:

    • Default/Standard edges: The midpoint is the geometric center of the edge.
    • curve-style: unbundled-bezier:
      • If the number of control points is odd, the midpoint is the middle extremum.
      • If the number of control points is even, the midpoint is the location where the two middle-most control points meet.
    • curve-style: segments:
      • If the number of segment points is odd, the midpoint is the middle segment point.
      • If the number of segment points is even, the midpoint is the mean of the middle two segment points (the midpoint of the middle-most line segment).
  8. WebGL Renderer Architecture Overview

    unstable

    The WebGL renderer in Cytoscape.js is structured around a modular design to handle high-performance graph rendering. The core logic is split into initialization, the drawing loop, and element processing.

    Core Modules

    • Canvas Initialization (renderer/canvas/index.mjs): Responsible for the initial setup of the WebGL canvas and context.
    • Drawing & Redraw Logic (drawing-redraw-webgl.mjs): Manages the timing and execution of the render loop, ensuring efficient updates when the graph state changes.
    • Element Drawing (drawing-elements-webgl.mjs): Handles the specific logic of translating Cytoscape elements (nodes, edges) into WebGL draw calls.
  9. Understand pannable elements in Cytoscape.js

    unstable

    A pannable element enables 'passthrough panning', meaning that when a user drags on that specific element, the graph itself pans instead of the element being selected or moved.

    Because the drag action is intercepted to pan the viewport, a pannable element is inherently ungrabbable (it cannot be moved via dragging).

    Default Behavior:

    • Edges are pannable by default.
    • Nodes are NOT pannable by default.
  10. Choose a stylesheet format for Cytoscape.js

    unstable

    Cytoscape.js supports three ways to define styles during initialization. Note that specificity rules are ignored: for any given style property, the last matching selector wins.

    1. String format: A CSS-like string. This is useful for styles loaded from an external server via AJAX. Mandatory: Trailing semicolons are required for every property except the last one.
    2. Plain JSON format: An array of objects where each object contains a selector and a style object. You can also use the key css instead of style.
    3. Function format: Uses the cytoscape.stylesheet() builder API for a chained, programmatic approach. You can also use .css() instead of .style() in the builder.

    Use the JSON or Function formats if you need to use dynamic function values for properties.

    // String format
    cytoscape({
      container: document.getElementById('cy'),
      style: 'node { background-color: green; }'
    });
    
    // Plain JSON format
    cytoscape({
      container: document.getElementById('cy'),
      style: [
        {
          selector: 'node',
          style: {
            'background-color': 'red'
          }
        }
      ]
    });
    
    // Function format
    cytoscape({
      container: document.getElementById('cy'),
      style: cytoscape.stylesheet()
        .selector('node')
          .style({
            'background-color': 'blue'
          })
    });