trilium/libraries/springy.js

657 lines
17 KiB
JavaScript
Raw Normal View History

2019-06-04 04:55:59 +08:00
/**
* Springy v2.7.1
*
* Copyright (c) 2010-2013 Dennis Hotson
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
2020-02-03 03:02:08 +08:00
window.Springy = function() {
const Springy = {};
const Graph = Springy.Graph = function () {
2019-06-04 04:55:59 +08:00
this.nodeSet = {};
this.nodes = [];
this.edges = [];
this.adjacency = {};
this.nextNodeId = 0;
this.nextEdgeId = 0;
this.eventListeners = [];
};
2020-02-03 03:02:08 +08:00
const Node = Springy.Node = function (id, data) {
2019-06-04 04:55:59 +08:00
this.id = id;
this.data = (data !== undefined) ? data : {};
2020-02-03 03:02:08 +08:00
// Data fields used by layout algorithm in this file:
// this.data.mass
// Data used by default renderer in springyui.js
// this.data.label
2019-06-04 04:55:59 +08:00
};
2020-02-03 03:02:08 +08:00
const Edge = Springy.Edge = function (id, source, target, data) {
2019-06-04 04:55:59 +08:00
this.id = id;
this.source = source;
this.target = target;
this.data = (data !== undefined) ? data : {};
2020-02-03 03:02:08 +08:00
// Edge data field used by layout alorithm
// this.data.length
// this.data.type
2019-06-04 04:55:59 +08:00
};
Graph.prototype.addNode = function(node) {
if (!(node.id in this.nodeSet)) {
this.nodes.push(node);
}
this.nodeSet[node.id] = node;
this.notify();
return node;
};
Graph.prototype.addNodes = function() {
// accepts variable number of arguments, where each argument
// is a string that becomes both node identifier and label
2020-02-03 03:02:08 +08:00
for (let i = 0; i < arguments.length; i++) {
const name = arguments[i];
const node = new Node(name, {label: name});
2019-06-04 04:55:59 +08:00
this.addNode(node);
}
};
Graph.prototype.addEdge = function(edge) {
2020-02-03 03:02:08 +08:00
let exists = false;
2019-06-04 04:55:59 +08:00
this.edges.forEach(function(e) {
if (edge.id === e.id) { exists = true; }
});
if (!exists) {
this.edges.push(edge);
}
if (!(edge.source.id in this.adjacency)) {
this.adjacency[edge.source.id] = {};
}
if (!(edge.target.id in this.adjacency[edge.source.id])) {
this.adjacency[edge.source.id][edge.target.id] = [];
}
exists = false;
this.adjacency[edge.source.id][edge.target.id].forEach(function(e) {
if (edge.id === e.id) { exists = true; }
});
if (!exists) {
this.adjacency[edge.source.id][edge.target.id].push(edge);
}
this.notify();
return edge;
};
Graph.prototype.addEdges = function() {
// accepts variable number of arguments, where each argument
// is a triple [nodeid1, nodeid2, attributes]
2020-02-03 03:02:08 +08:00
for (let i = 0; i < arguments.length; i++) {
const e = arguments[i];
const node1 = this.nodeSet[e[0]];
2019-06-04 04:55:59 +08:00
if (node1 == undefined) {
throw new TypeError("invalid node name: " + e[0]);
}
2020-02-03 03:02:08 +08:00
const node2 = this.nodeSet[e[1]];
2019-06-04 04:55:59 +08:00
if (node2 == undefined) {
throw new TypeError("invalid node name: " + e[1]);
}
2020-02-03 03:02:08 +08:00
const attr = e[2];
2019-06-04 04:55:59 +08:00
this.newEdge(node1, node2, attr);
}
};
Graph.prototype.newNode = function(data) {
2020-02-03 03:02:08 +08:00
const node = new Node(this.nextNodeId++, data);
2019-06-04 04:55:59 +08:00
this.addNode(node);
return node;
};
Graph.prototype.newEdge = function(source, target, data) {
2020-02-03 03:02:08 +08:00
const edge = new Edge(this.nextEdgeId++, source, target, data);
2019-06-04 04:55:59 +08:00
this.addEdge(edge);
return edge;
};
// add nodes and edges from JSON object
Graph.prototype.loadJSON = function(json) {
/**
Springy's simple JSON format for graphs.
historically, Springy uses separate lists
of nodes and edges:
{
"nodes": [
"center",
"left",
"right",
"up",
"satellite"
],
"edges": [
["center", "left"],
["center", "right"],
["center", "up"]
]
}
**/
// parse if a string is passed (EC5+ browsers)
if (typeof json == 'string' || json instanceof String) {
json = JSON.parse( json );
}
if ('nodes' in json || 'edges' in json) {
this.addNodes.apply(this, json['nodes']);
this.addEdges.apply(this, json['edges']);
}
};
2019-06-04 04:55:59 +08:00
// find the edges from node1 to node2
Graph.prototype.getEdges = function(node1, node2) {
if (node1.id in this.adjacency
&& node2.id in this.adjacency[node1.id]) {
return this.adjacency[node1.id][node2.id];
}
return [];
};
// remove a node and it's associated edges from the graph
Graph.prototype.removeNode = function(node) {
if (node.id in this.nodeSet) {
delete this.nodeSet[node.id];
}
2020-02-03 03:02:08 +08:00
for (let i = this.nodes.length - 1; i >= 0; i--) {
2019-06-04 04:55:59 +08:00
if (this.nodes[i].id === node.id) {
this.nodes.splice(i, 1);
}
}
this.detachNode(node);
};
// removes edges associated with a given node
Graph.prototype.detachNode = function(node) {
2020-02-03 03:02:08 +08:00
const tmpEdges = this.edges.slice();
2019-06-04 04:55:59 +08:00
tmpEdges.forEach(function(e) {
if (e.source.id === node.id || e.target.id === node.id) {
this.removeEdge(e);
}
}, this);
this.notify();
};
// remove a node and it's associated edges from the graph
Graph.prototype.removeEdge = function(edge) {
2020-02-03 03:02:08 +08:00
for (let i = this.edges.length - 1; i >= 0; i--) {
2019-06-04 04:55:59 +08:00
if (this.edges[i].id === edge.id) {
this.edges.splice(i, 1);
}
}
2020-02-03 03:02:08 +08:00
for (const x in this.adjacency) {
for (const y in this.adjacency[x]) {
const edges = this.adjacency[x][y];
2019-06-04 04:55:59 +08:00
2020-02-03 03:02:08 +08:00
for (let j = edges.length - 1; j >= 0; j--) {
2019-06-04 04:55:59 +08:00
if (this.adjacency[x][y][j].id === edge.id) {
this.adjacency[x][y].splice(j, 1);
}
}
// Clean up empty edge arrays
if (this.adjacency[x][y].length == 0) {
delete this.adjacency[x][y];
}
}
// Clean up empty objects
if (isEmpty(this.adjacency[x])) {
delete this.adjacency[x];
}
}
this.notify();
};
/* Merge a list of nodes and edges into the current graph. eg.
var o = {
nodes: [
{id: 123, data: {type: 'user', userid: 123, displayname: 'aaa'}},
{id: 234, data: {type: 'user', userid: 234, displayname: 'bbb'}}
],
edges: [
{from: 0, to: 1, type: 'submitted_design', directed: true, data: {weight: }}
]
}
*/
Graph.prototype.merge = function(data) {
2020-02-03 03:02:08 +08:00
const nodes = [];
2019-06-04 04:55:59 +08:00
data.nodes.forEach(function(n) {
nodes.push(this.addNode(new Node(n.id, n.data)));
}, this);
data.edges.forEach(function(e) {
2020-02-03 03:02:08 +08:00
const from = nodes[e.from];
const to = nodes[e.to];
2019-06-04 04:55:59 +08:00
2020-02-03 03:02:08 +08:00
let id = (e.directed)
? (e.type + "-" + from.id + "-" + to.id)
2019-06-04 04:55:59 +08:00
: (from.id < to.id) // normalise id for non-directed edges
? e.type + "-" + from.id + "-" + to.id
: e.type + "-" + to.id + "-" + from.id;
2020-02-03 03:02:08 +08:00
const edge = this.addEdge(new Edge(id, from, to, e.data));
2019-06-04 04:55:59 +08:00
edge.data.type = e.type;
}, this);
};
Graph.prototype.filterNodes = function(fn) {
2020-02-03 03:02:08 +08:00
const tmpNodes = this.nodes.slice();
2019-06-04 04:55:59 +08:00
tmpNodes.forEach(function(n) {
if (!fn(n)) {
this.removeNode(n);
}
}, this);
};
Graph.prototype.filterEdges = function(fn) {
2020-02-03 03:02:08 +08:00
const tmpEdges = this.edges.slice();
2019-06-04 04:55:59 +08:00
tmpEdges.forEach(function(e) {
if (!fn(e)) {
this.removeEdge(e);
}
}, this);
};
Graph.prototype.addGraphListener = function(obj) {
this.eventListeners.push(obj);
};
Graph.prototype.notify = function() {
this.eventListeners.forEach(function(obj){
obj.graphChanged();
});
};
// -----------
2020-02-03 03:02:08 +08:00
const Layout = Springy.Layout = {};
Layout.ForceDirected = function(graph, stopCheckerCallback, stiffness, repulsion, damping, minEnergyThreshold, maxSpeed) {
2019-06-04 04:55:59 +08:00
this.graph = graph;
2020-02-03 03:02:08 +08:00
this.stopCheckerCallback = stopCheckerCallback || (() => false);
2019-06-04 04:55:59 +08:00
this.stiffness = stiffness; // spring stiffness constant
this.repulsion = repulsion; // repulsion constant
this.damping = damping; // velocity damping factor
this.minEnergyThreshold = minEnergyThreshold || 0.01; //threshold used to determine render stop
this.maxSpeed = maxSpeed || Infinity; // nodes aren't allowed to exceed this speed
this.nodePoints = {}; // keep track of points associated with nodes
this.edgeSprings = {}; // keep track of springs associated with edges
};
Layout.ForceDirected.prototype.point = function(node) {
if (!(node.id in this.nodePoints)) {
2020-02-03 03:02:08 +08:00
const mass = (node.data.mass !== undefined) ? node.data.mass : 1.0;
2019-06-04 04:55:59 +08:00
this.nodePoints[node.id] = new Layout.ForceDirected.Point(Vector.random(), mass);
}
return this.nodePoints[node.id];
};
Layout.ForceDirected.prototype.spring = function(edge) {
if (!(edge.id in this.edgeSprings)) {
2020-02-03 03:02:08 +08:00
const length = (edge.data.length !== undefined) ? edge.data.length : 1.0;
2019-06-04 04:55:59 +08:00
2020-02-03 03:02:08 +08:00
let existingSpring = false;
2019-06-04 04:55:59 +08:00
2020-02-03 03:02:08 +08:00
const from = this.graph.getEdges(edge.source, edge.target);
2019-06-04 04:55:59 +08:00
from.forEach(function(e) {
if (existingSpring === false && e.id in this.edgeSprings) {
existingSpring = this.edgeSprings[e.id];
}
}, this);
if (existingSpring !== false) {
return new Layout.ForceDirected.Spring(existingSpring.point1, existingSpring.point2, 0.0, 0.0);
}
2020-02-03 03:02:08 +08:00
const to = this.graph.getEdges(edge.target, edge.source);
to.forEach(function(e){
2019-06-04 04:55:59 +08:00
if (existingSpring === false && e.id in this.edgeSprings) {
existingSpring = this.edgeSprings[e.id];
}
}, this);
if (existingSpring !== false) {
return new Layout.ForceDirected.Spring(existingSpring.point2, existingSpring.point1, 0.0, 0.0);
}
this.edgeSprings[edge.id] = new Layout.ForceDirected.Spring(
this.point(edge.source), this.point(edge.target), length, this.stiffness
);
}
return this.edgeSprings[edge.id];
};
// callback should accept two arguments: Node, Point
Layout.ForceDirected.prototype.eachNode = function(callback) {
2020-02-03 03:02:08 +08:00
const t = this;
2019-06-04 04:55:59 +08:00
this.graph.nodes.forEach(function(n){
callback.call(t, n, t.point(n));
});
};
// callback should accept two arguments: Edge, Spring
Layout.ForceDirected.prototype.eachEdge = function(callback) {
2020-02-03 03:02:08 +08:00
const t = this;
2019-06-04 04:55:59 +08:00
this.graph.edges.forEach(function(e){
callback.call(t, e, t.spring(e));
});
};
// callback should accept one argument: Spring
Layout.ForceDirected.prototype.eachSpring = function(callback) {
2020-02-03 03:02:08 +08:00
const t = this;
2019-06-04 04:55:59 +08:00
this.graph.edges.forEach(function(e){
callback.call(t, t.spring(e));
});
};
// Physics stuff
Layout.ForceDirected.prototype.applyCoulombsLaw = function() {
this.eachNode(function(n1, point1) {
this.eachNode(function(n2, point2) {
2020-02-03 03:02:08 +08:00
if (point1 !== point2) {
const d = point1.p.subtract(point2.p);
const distance = d.magnitude() + 0.1; // avoid massive forces at small distances (and divide by zero)
2020-02-03 03:02:08 +08:00
const direction = d.normalise();
2019-06-04 04:55:59 +08:00
// apply force to each end point
point1.applyForce(direction.multiply(this.repulsion).divide(distance * distance * distance * 0.5));
point2.applyForce(direction.multiply(this.repulsion).divide(distance * distance * distance * -0.5));
2019-06-04 04:55:59 +08:00
}
});
});
};
Layout.ForceDirected.prototype.applyHookesLaw = function() {
this.eachSpring(function(spring){
2020-02-03 03:02:08 +08:00
const d = spring.point2.p.subtract(spring.point1.p); // the direction of the spring
const displacement = spring.length - d.magnitude();
const direction = d.normalise();
2019-06-04 04:55:59 +08:00
// apply force to each end point
spring.point1.applyForce(direction.multiply(spring.k * displacement * -0.5));
spring.point2.applyForce(direction.multiply(spring.k * displacement * 0.5));
});
};
Layout.ForceDirected.prototype.attractToCentre = function() {
this.eachNode(function(node, point) {
2020-02-03 03:02:08 +08:00
const direction = point.p.multiply(-1.0);
2019-06-04 04:55:59 +08:00
point.applyForce(direction.multiply(this.repulsion / 50.0));
});
};
Layout.ForceDirected.prototype.updateVelocity = function(timestep) {
this.eachNode(function(node, point) {
// Is this, along with updatePosition below, the only places that your
// integration code exist?
point.v = point.v.add(point.a.multiply(timestep)).multiply(this.damping);
if (point.v.magnitude() > this.maxSpeed) {
point.v = point.v.normalise().multiply(this.maxSpeed);
}
point.a = new Vector(0,0);
});
};
Layout.ForceDirected.prototype.updatePosition = function(timestep) {
this.eachNode(function(node, point) {
// Same question as above; along with updateVelocity, is this all of
// your integration code?
point.p = point.p.add(point.v.multiply(timestep));
});
};
// Calculate the total kinetic energy of the system
Layout.ForceDirected.prototype.totalEnergy = function(timestep) {
2020-02-03 03:02:08 +08:00
let energy = 0.0;
2019-06-04 04:55:59 +08:00
this.eachNode(function(node, point) {
2020-02-03 03:02:08 +08:00
const speed = point.v.magnitude();
2019-06-04 04:55:59 +08:00
energy += 0.5 * point.m * speed * speed;
});
return energy;
};
/**
* Start simulation if it's not running already.
* In case it's running then the call is ignored, and none of the callbacks passed is ever executed.
*/
Layout.ForceDirected.prototype.start = function(onRenderStop) {
2020-02-03 03:02:08 +08:00
const t = this;
2019-06-04 04:55:59 +08:00
if (this._started) return;
this._started = true;
this._stop = false;
function step() {
2019-06-04 04:55:59 +08:00
t.tick(0.03);
2020-02-03 03:02:08 +08:00
if (t.stopCheckerCallback()) {
onRenderStop();
}
2019-06-04 04:55:59 +08:00
// stop simulation when energy of the system goes below a threshold
if (t._stop || t.totalEnergy() < t.minEnergyThreshold) {
t._started = false;
onRenderStop();
2019-06-04 04:55:59 +08:00
} else {
requestIdleCallback(step, { timeout: 30 });
2019-06-04 04:55:59 +08:00
}
}
step();
2019-06-04 04:55:59 +08:00
};
Layout.ForceDirected.prototype.stop = function() {
this._stop = true;
};
2019-06-04 04:55:59 +08:00
Layout.ForceDirected.prototype.tick = function(timestep) {
this.applyCoulombsLaw();
this.applyHookesLaw();
this.attractToCentre();
this.updateVelocity(timestep);
this.updatePosition(timestep);
};
// Find the nearest point to a particular position
Layout.ForceDirected.prototype.nearest = function(pos) {
2020-02-03 03:02:08 +08:00
let min = {node: null, point: null, distance: null};
const t = this;
2019-06-04 04:55:59 +08:00
this.graph.nodes.forEach(function(n){
2020-02-03 03:02:08 +08:00
const point = t.point(n);
const distance = point.p.subtract(pos).magnitude();
2019-06-04 04:55:59 +08:00
if (min.distance === null || distance < min.distance) {
min = {node: n, point: point, distance: distance};
}
});
return min;
};
// returns [bottomleft, topright]
Layout.ForceDirected.prototype.getBoundingBox = function() {
2020-02-03 03:02:08 +08:00
const bottomleft = new Vector(-2, -2);
const topright = new Vector(2, 2);
2019-06-04 04:55:59 +08:00
this.eachNode(function(n, point) {
if (point.p.x < bottomleft.x) {
bottomleft.x = point.p.x;
}
if (point.p.y < bottomleft.y) {
bottomleft.y = point.p.y;
}
if (point.p.x > topright.x) {
topright.x = point.p.x;
}
if (point.p.y > topright.y) {
topright.y = point.p.y;
}
});
2020-02-03 03:02:08 +08:00
const padding = topright.subtract(bottomleft).multiply(0.07); // ~5% padding
2019-06-04 04:55:59 +08:00
return {bottomleft: bottomleft.subtract(padding), topright: topright.add(padding)};
};
// Vector
2020-02-03 03:02:08 +08:00
const Vector = Springy.Vector = function(x, y) {
2019-06-04 04:55:59 +08:00
this.x = x;
this.y = y;
};
Vector.random = function() {
return new Vector(10.0 * (Math.random() - 0.5), 10.0 * (Math.random() - 0.5));
};
Vector.prototype.add = function(v2) {
return new Vector(this.x + v2.x, this.y + v2.y);
};
Vector.prototype.subtract = function(v2) {
return new Vector(this.x - v2.x, this.y - v2.y);
};
Vector.prototype.multiply = function(n) {
return new Vector(this.x * n, this.y * n);
};
Vector.prototype.divide = function(n) {
return new Vector((this.x / n) || 0, (this.y / n) || 0); // Avoid divide by zero errors..
};
Vector.prototype.magnitude = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
};
Vector.prototype.normal = function() {
return new Vector(-this.y, this.x);
};
Vector.prototype.normalise = function() {
return this.divide(this.magnitude());
};
// Point
Layout.ForceDirected.Point = function(position, mass) {
this.p = position; // position
this.m = mass; // mass
this.v = new Vector(0, 0); // velocity
this.a = new Vector(0, 0); // acceleration
};
Layout.ForceDirected.Point.prototype.applyForce = function(force) {
this.a = this.a.add(force.divide(this.m));
};
// Spring
Layout.ForceDirected.Spring = function(point1, point2, length, k) {
this.point1 = point1;
this.point2 = point2;
this.length = length; // spring length at rest
this.k = k; // spring constant (See Hooke's law) .. how stiff the spring is
};
// Layout.ForceDirected.Spring.prototype.distanceToPoint = function(point)
// {
// // hardcore vector arithmetic.. ohh yeah!
// // .. see http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment/865080#865080
// var n = this.point2.p.subtract(this.point1.p).normalise().normal();
// var ac = point.p.subtract(this.point1.p);
// return Math.abs(ac.x * n.x + ac.y * n.y);
// };
/**
* Renderer handles the layout rendering loop
*/
2020-02-03 03:02:08 +08:00
const Renderer = Springy.Renderer = function (layout) {
2019-06-04 04:55:59 +08:00
this.layout = layout;
this.layout.graph.addGraphListener(this);
};
2019-06-04 04:55:59 +08:00
Renderer.prototype.graphChanged = function() {
2019-06-04 04:55:59 +08:00
this.start();
};
/**
* Starts the simulation of the layout in use.
*/
Renderer.prototype.start = function(maxTime) {
if (maxTime) {
setTimeout(() => this.stop(), maxTime);
}
2019-06-04 04:55:59 +08:00
return new Promise((res, rej) => {
this.layout.start(res);
});
2019-06-04 04:55:59 +08:00
};
Renderer.prototype.stop = function() {
this.layout.stop();
};
2020-02-03 03:02:08 +08:00
const isEmpty = function(obj) {
for (const k in obj) {
2019-06-04 04:55:59 +08:00
if (obj.hasOwnProperty(k)) {
return false;
}
}
return true;
};
return Springy;
2020-02-03 03:02:08 +08:00
}();