mermaid/packages/mermaid/src/diagrams/sankey/sankeyDB.ts

82 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-06-18 00:32:45 +02:00
import * as configApi from '../../config.js';
import common from '../common/common.js';
import {
2023-06-18 00:32:45 +02:00
setAccTitle,
getAccTitle,
getAccDescription,
setAccDescription,
2023-06-18 00:32:45 +02:00
setDiagramTitle,
getDiagramTitle,
clear as commonClear,
} from '../../commonDb.js';
// Sankey diagram represented by nodes and links between those nodes
2023-06-24 23:42:06 +02:00
let links: SankeyLink[] = [];
2023-06-27 16:50:51 +02:00
// Array of nodes guarantees their order
2023-06-24 23:42:06 +02:00
let nodes: SankeyNode[] = [];
2023-06-27 16:50:51 +02:00
// We also have to track nodes uniqueness (by ID)
let nodesMap: Record<string, SankeyNode> = {};
2023-06-18 00:32:45 +02:00
const clear = (): void => {
2023-06-18 00:32:45 +02:00
links = [];
2023-06-18 00:32:45 +02:00
nodes = [];
nodesMap = {};
2023-06-18 00:32:45 +02:00
commonClear();
};
class SankeyLink {
constructor(public source: SankeyNode, public target: SankeyNode, public value: number = 0) {}
2023-06-18 00:32:45 +02:00
}
/**
2023-06-18 00:32:45 +02:00
* @param source - Node where the link starts
* @param target - Node where the link ends
2023-08-19 07:49:18 +02:00
* @param value - Describes the amount to be passed
*/
const addLink = (source: SankeyNode, target: SankeyNode, value: number): void => {
links.push(new SankeyLink(source, target, value));
};
2023-06-18 00:32:45 +02:00
class SankeyNode {
constructor(public ID: string) {}
2023-06-18 00:32:45 +02:00
}
const findOrCreateNode = (ID: string): SankeyNode => {
2023-06-18 00:32:45 +02:00
ID = common.sanitizeText(ID, configApi.getConfig());
2023-06-27 13:11:06 +02:00
2023-06-29 14:39:50 +02:00
if (!nodesMap[ID]) {
nodesMap[ID] = new SankeyNode(ID);
nodes.push(nodesMap[ID]);
}
2023-06-27 13:11:06 +02:00
return nodesMap[ID];
};
2023-06-18 00:32:45 +02:00
2023-06-18 03:33:20 +02:00
const getNodes = () => nodes;
const getLinks = () => links;
const getGraph = () => ({
nodes: nodes.map((node) => ({ id: node.ID })),
links: links.map((link) => ({
source: link.source.ID,
target: link.target.ID,
value: link.value,
})),
});
2023-06-18 00:32:45 +02:00
export default {
nodesMap,
2023-06-18 03:33:20 +02:00
getConfig: () => configApi.getConfig().sankey,
getNodes,
getLinks,
getGraph,
2023-06-18 00:32:45 +02:00
addLink,
findOrCreateNode,
2023-06-18 00:32:45 +02:00
getAccTitle,
setAccTitle,
getAccDescription,
setAccDescription,
2023-06-18 00:32:45 +02:00
getDiagramTitle,
setDiagramTitle,
clear,
2023-06-18 00:32:45 +02:00
};