elkjs

repository·master·Indexed 25 days ago

https://github.com/kieler/elkjs

A JavaScript port of the Eclipse Layout Kernel (ELK) providing automatic layout algorithms for node-link diagrams, specialized for data flow diagrams and ports. It computes positions for diagram elements using Sugiyama's algorithm and other registered algorithms like stress, mrtree, radial, force, and disco, but does not handle rendering or styling. Supports Node.js and browser environments with optional Web Worker integration for heavy computations.

Tokens
2K
Snippets
6
Records
15
Agent score
82%

What's inside elkjs

  1. Build elkjs from source

    master

    To build elkjs, you must have a checkout of the ELK repository located in the same directory as the elkjs repository.

    Directory structure requirement:

    some_dir/
     ├── elkjs
     └── elk

    Run the following commands to build:

    npm install
    npm run build
  2. Install elkjs via npm

    master

    To install the latest stable version of elkjs, use the standard npm install command. For the development version based on ELK's master branch, use the @next tag.

    npm install elkjs
    
    # For development version
    npm install elkjs@next
  3. Use elkjs with TypeScript

    master

    You can import elkjs in TypeScript projects using either the bundled version or the API-only version with a manual worker configuration.

    // Option 1: Bundled version
    import ELK from 'elkjs/lib/elk.bundled.js'
    const elk = new ELK()
    
    // Option 2: API version with worker
    import ELK from 'elkjs/lib/elk-api'
    const elk = new ELK({
      workerUrl: './elk-worker.min.js'
    })
  4. Use Web Workers with elkjs

    master

    To prevent blocking the UI during heavy layout computations, you can use Web Workers.

    In Node.js, you must install the web-worker package to provide a wrapper around Node's worker_threads that is compatible with the Web Worker API. If the package is missing, elkjs falls back to the non-worker version.

    In the Browser, provide the path to the worker script via the workerUrl option in the ELK constructor.

  5. Configure layout options

    master

    Layout options can be configured at three levels:

    1. Element level: Attach a layoutOptions object directly to a graph element (e.g., the root node).
    2. Method level: Pass a configuration object as the second argument to layout(graph, options). The options.layoutOptions property allows you to set global options applied to all elements unless overridden.
    3. Constructor level: Pass defaultLayoutOptions to the ELK constructor to set defaults for every layout call.

    Note: While you can use suffixes (e.g., algorithm instead of org.eclipse.elk.layered), it is safer to use the full key starting with elk. to avoid ambiguity.

  6. Debug elkjs with non-minified workers

    master

    If you need proper stack traces during debugging, use the non-minified versions of the API and worker files by providing a custom workerFactory to the ELK constructor.

    const ELK = require('elkjs/lib/elk-api.js')
    const elk = new ELK({
        workerFactory: function(url) {
            const { Worker } = require('elkjs/lib/elk-worker.js') // non-minified
            return new Worker(url)
        }
    })
  7. Basic usage of elkjs in Node.js

    master

    To perform a layout in Node.js, require elkjs, instantiate the ELK class, and call the .layout() method with a graph object following the ELK JSON format. The method returns a Promise that resolves with the laid-out graph.

    const ELK = require('elkjs')
    const elk = new ELK()
    
    const graph = {
      id: "root",
      layoutOptions: { 'elk.algorithm': 'layered' },
      children: [
        { id: "n1", width: 30, height: 30 },
        { id: "n2", width: 30, height: 30 },
        { id: "n3", width: 30, height: 30 }
      ],
      edges: [
        { id: "e1", sources: [ "n1" ], targets: [ "n2" ] },
        { id: "e2", sources: [ "n1" ], targets: [ "n3" ] }
      ]
    }
    
    elk.layout(graph)
       .then(console.log)
       .catch(console.error)
  8. ELK Class API Reference

    master

    The ELK class is the primary interface for the library.

    Constructor

    new ELK(options)

    • defaultLayoutOptions (Object): Default key/value pairs for layout options. Default: {}.
    • algorithms (Array<string>): Array of algorithm IDs (suffixes). Default: [ 'layered', 'stress', 'mrtree', 'radial', 'force', 'disco' ]. Note: box, fixed, and random are always included.
    • workerUrl (string): Path to the elk-worker.js script to enable Web Worker execution.

    Methods

    • layout(graph, options): Returns a Promise that resolves with the laid-out graph or rejects with an error.
      • graph (Object): Mandatory. The graph in ELK JSON format.
      • options (Object): Optional configuration.
        • layoutOptions (Object): Global layout options applied to all elements.
        • logging (boolean): Whether to include logging info in the result. Default: false.
        • measureExecutionTime (boolean): Whether to include execution time in the result. Default: false.
    • knownLayoutOptions(): Returns an array of known layout options (including id and group).
    • knownLayoutAlgorithms(): Returns an array of registered layout algorithms.
    • knownLayoutCategories(): Returns an array of registered layout categories.
    • terminateWorker(): Terminates the Web Worker if one is in use.
  9. Enable logging and execution time measurement

    master

    You can debug layout algorithms and measure performance by passing logging: true and measureExecutionTime: true in the options object of the elk.layout() call.

    Note that execution times are returned in seconds. For very small graphs, the reported execution time may appear as 0 due to the precision of milliseconds used in the elkjs implementation.

    elk.layout(simpleGraph, {
        layoutOptions: {
            'algorithm': 'layered'
        },
        logging: true,
        measureExecutionTime: true
    })
  10. Use the ELK class as the primary entrypoint

    master
    The ELK class is the main entrypoint for running layout algorithms in elkjs. It is exported as the default export of the module. You can require it in Node.js environments or import it in ESM environments to access the layout engine's API.
  11. Initialize the ELK class

    master

    To use ELK, instantiate the ELK class. You must provide either a workerUrl (which uses the default Web Worker constructor) or a custom workerFactory.

    Supported algorithms that can be registered during initialization include: layered, stress, mrtree, radial, force, disco, sporeOverlap, sporeCompaction, and rectpacking.