All files / src/lib layout.js

100% Statements 22/22
100% Branches 4/4
100% Functions 10/10
100% Lines 22/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84            25x 25x   25x       25x 25x 25x       26x 26x 26x       26x 40x         26x 22x                       24x 36x 36x                         26x 26x 26x                         26x       16x 16x        
import { graphlib, layout } from 'dagre';
 
 
export default class Layout {
 
    static from(workflow, orientation) {
        const layout = new Layout(orientation);
        layout.setWorkflow(workflow);
 
        return layout;
    }
 
    constructor(orientation) {
        const rankdir = orientation === 'vertical' ? 'TB' : 'LR';
        this._graph = new graphlib.Graph();
        this._graph.setGraph({ rankdir });
    }
 
    setWorkflow(workflow) {
        this._setStates(workflow.states);
        this._setTransitions(workflow.transitions);
        layout(this._graph);
    }
 
    _setStates(states) {
        for (const { id, label, width, height, stylingClass } of states) {
            this._graph.setNode(id, { label, width, height, stylingClass });
        }
    }
 
    _setTransitions(transitions) {
        for (const transition of transitions) {
            this._graph.setEdge(transition.source, transition.target, {
                id: transition.id,
                label: transition.label ? transition.label : '',
                width: transition.width,
                height: transition.height,
                labelpos: 'c',
                stylingClass: transition.stylingClass,
            });
        }
    }
 
    get states() {
        return this._graph.nodes().map(id => {
            const node = this._graph.node(id);
            return {
                id,
                label: node.label,
                center: {
                    x: node.x,
                    y: node.y,
                },
                stylingClass: node.stylingClass,
            };
        });
    }
 
    get transitions() {
        const transitions = this._graph.edges().map(ids => {
            const data = this._graph.edge(ids);
            return {
                id: data.id,
                path: data.points,
                label: {
                    point: {
                        x: data.x,
                        y: data.y,
                    },
                    text: data.label,
                },
                stylingClass: data.stylingClass,
            };
        });
        return transitions;
    }
 
    get size() {
        const graph = this._graph.graph();
        return { width: graph.width, height: graph.height };
    }
 
}