Browse Source

Springy

master
Adrian Heine 4 years ago
parent
commit
c000218ecf
  1. 71
      img/weben.svg
  2. 1
      index.html
  3. 735
      springy.js
  4. 56
      src/display.js
  5. 2
      src/index.js
  6. 26
      style.css

71
img/weben.svg

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="210mm"
height="297mm"
viewBox="0 0 210 297"
version="1.1"
id="svg1041"
inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)"
sodipodi:docname="Weben.svg">
<defs
id="defs1035" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.35"
inkscape:cx="400"
inkscape:cy="560"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
inkscape:document-rotation="0"
showgrid="false"
inkscape:window-width="1920"
inkscape:window-height="1002"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1038">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1">
<g
id="g6841"
transform="matrix(0.76668646,0,0,0.76668646,13.027484,-16.666028)">
<path
id="path5699"
style="opacity:1;vector-effect:none;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.67028;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
d="m 146.56976,122.44709 v 6.34225 l -4.71083,0.007 -7.31893,75.85894 h 6.76238 v 10.20093 h 23.62181 v -10.20093 h 6.13606 l -7.2223,-75.89356 -4.80694,0.008 v -6.32261 z m 1.9358,1.9234 h 8.58965 v 4.40231 l -8.58965,0.0134 z m 13.30978,7.78815 0.64389,7.54579 -18.62626,-7.15666 0.031,-0.3576 z m -18.33118,4.42092 19.343,7.4321 1.10278,12.92118 -21.49223,-8.2579 z m -1.39578,16.12718 22.20949,8.53385 1.2759,14.94689 -24.69617,-9.48883 z m -1.5596,18.02319 25.4124,9.76426 1.10278,12.92118 -27.56162,-10.58954 z m -1.39526,16.12718 28.27838,10.86549 0.30179,3.53673 h -29.82661 z m 5.3175,18.36064 h 17.32401 v 6.66109 h -17.32401 z" />
<path
style="fill:none;stroke:#000000;stroke-width:2.665;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 165.94986,176.3015 c 0,0 8.41072,10.83689 13.26305,5.01408 4.85234,-5.8228 0.64698,-15.04224 0.64698,-15.04224 0,0 -4.04361,-10.83688 5.66106,-10.83688"
id="path6834" />
</g>
<path
id="path6843"
style="opacity:1;vector-effect:none;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.37296;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
d="m 74.450776,73.421724 a 39.215031,39.215031 0 0 0 -39.21466,39.215186 39.215031,39.215031 0 0 0 39.21466,39.21518 39.215031,39.215031 0 0 0 39.215184,-39.21518 39.215031,39.215031 0 0 0 -39.215184,-39.215186 z m 0,4.25246 a 34.962796,34.962796 0 0 1 34.963244,34.962726 34.962796,34.962796 0 0 1 -34.963244,34.96272 34.962796,34.962796 0 0 1 -34.96272,-34.96272 34.962796,34.962796 0 0 1 34.96272,-34.962726 z m 0,2.64583 a 32.316925,32.316925 0 0 0 -32.31689,32.316896 32.316925,32.316925 0 0 0 32.31689,32.31688 32.316925,32.316925 0 0 0 32.316894,-32.31688 32.316925,32.316925 0 0 0 -32.316894,-32.316896 z m -2.2133,3.58996 v 11.00502 a 17.859375,17.859375 0 0 0 -8.695079,3.58066 l -7.784531,-7.78454 a 28.812678,28.812678 0 0 1 16.47961,-6.80114 z m 4.427119,0 a 28.812678,28.812678 0 0 1 16.419672,6.7505 l -7.78764,7.78763 a 17.859375,17.859375 0 0 0 -8.632032,-3.5326 z m 19.566761,9.86452 a 28.812678,28.812678 0 0 1 6.923104,16.357656 H 92.132907 a 17.859375,17.859375 0 0 0 -3.67937,-8.57984 z m -43.6118,0.0594 7.77988,7.779876 a 17.859375,17.859375 0 0 0 -3.66747,8.78603 h -11.00657 a 28.812678,28.812678 0 0 1 6.89416,-16.565906 z m 21.83122,4.26795 a 14.534903,14.534903 0 0 1 14.535031,14.535026 14.534903,14.534903 0 0 1 -14.535031,14.53504 14.534903,14.534903 0 0 1 -14.53503,-14.53504 14.534903,14.534903 0 0 1 14.53503,-14.535026 z m 0,7.920446 a 6.6145836,6.6145836 0 0 0 -6.61458,6.61458 6.6145836,6.6145836 0 0 0 6.61458,6.61457 6.6145836,6.6145836 0 0 0 6.614581,-6.61457 6.6145836,6.6145836 0 0 0 -6.614581,-6.61458 z m 0,3.11816 a 3.4962798,3.4962798 0 0 1 3.49643,3.49642 3.4962798,3.4962798 0 0 1 -3.49643,3.49644 3.4962798,3.4962798 0 0 1 -3.49591,-3.49644 3.4962798,3.4962798 0 0 1 3.49591,-3.49642 z m 17.754989,5.4193 H 103.1989 a 28.812678,28.812678 0 0 1 -6.649213,16.56541 l -7.794871,-7.79486 a 17.859375,17.859375 0 0 0 3.450949,-8.77055 z m -46.484499,0.26718 h 11.00501 a 17.859375,17.859375 0 0 0 3.70107,8.86819 l -7.77834,7.77834 a 28.812678,28.812678 0 0 1 -6.92774,-16.64653 z m 39.96293,11.69386 7.77162,7.77162 a 28.812678,28.812678 0 0 1 -16.52405,7.05022 v -11.01951 a 17.859375,17.859375 0 0 0 8.75243,-3.80233 z m -22.10562,0.28473 a 17.859375,17.859375 0 0 0 8.926071,3.58427 v 10.99366 a 28.812678,28.812678 0 0 1 -16.712161,-6.79183 z" />
</g>
</svg>

1
index.html

@ -1,4 +1,5 @@
<meta charset=utf8> <meta charset=utf8>
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
<script src=diffDOM.js></script> <script src=diffDOM.js></script>
<script src=springy.js></script>
<script src=src/index.js type=module></script> <script src=src/index.js type=module></script>

735
springy.js

@ -0,0 +1,735 @@
/**
* 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.
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(function () {
return (root.returnExportsGlobal = factory());
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals
root.Springy = factory();
}
}(this, function() {
var Springy = {};
var Graph = Springy.Graph = function() {
this.nodeSet = {};
this.nodes = [];
this.edges = [];
this.adjacency = {};
this.nextNodeId = 0;
this.nextEdgeId = 0;
this.eventListeners = [];
};
var Node = Springy.Node = function(id, data) {
this.id = id;
this.data = (data !== undefined) ? data : {};
// Data fields used by layout algorithm in this file:
// this.data.mass
// Data used by default renderer in springyui.js
// this.data.label
};
var Edge = Springy.Edge = function(id, source, target, data) {
this.id = id;
this.source = source;
this.target = target;
this.data = (data !== undefined) ? data : {};
// Edge data field used by layout alorithm
// this.data.length
// this.data.type
};
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
for (var i = 0; i < arguments.length; i++) {
var name = arguments[i];
var node = new Node(name, {label:name});
this.addNode(node);
}
};
Graph.prototype.addEdge = function(edge) {
var exists = false;
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]
for (var i = 0; i < arguments.length; i++) {
var e = arguments[i];
var node1 = this.nodeSet[e[0]];
if (node1 == undefined) {
throw new TypeError("invalid node name: " + e[0]);
}
var node2 = this.nodeSet[e[1]];
if (node2 == undefined) {
throw new TypeError("invalid node name: " + e[1]);
}
var attr = e[2];
this.newEdge(node1, node2, attr);
}
};
Graph.prototype.newNode = function(data) {
var node = new Node(this.nextNodeId++, data);
this.addNode(node);
return node;
};
Graph.prototype.newEdge = function(source, target, data) {
var edge = new Edge(this.nextEdgeId++, source, target, data);
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']);
}
}
// 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];
}
for (var i = this.nodes.length - 1; i >= 0; i--) {
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) {
var tmpEdges = this.edges.slice();
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) {
for (var i = this.edges.length - 1; i >= 0; i--) {
if (this.edges[i].id === edge.id) {
this.edges.splice(i, 1);
}
}
for (var x in this.adjacency) {
for (var y in this.adjacency[x]) {
var edges = this.adjacency[x][y];
for (var j=edges.length - 1; j>=0; j--) {
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) {
var nodes = [];
data.nodes.forEach(function(n) {
nodes.push(this.addNode(new Node(n.id, n.data)));
}, this);
data.edges.forEach(function(e) {
var from = nodes[e.from];
var to = nodes[e.to];
var id = (e.directed)
? (id = e.type + "-" + from.id + "-" + to.id)
: (from.id < to.id) // normalise id for non-directed edges
? e.type + "-" + from.id + "-" + to.id
: e.type + "-" + to.id + "-" + from.id;
var edge = this.addEdge(new Edge(id, from, to, e.data));
edge.data.type = e.type;
}, this);
};
Graph.prototype.filterNodes = function(fn) {
var tmpNodes = this.nodes.slice();
tmpNodes.forEach(function(n) {
if (!fn(n)) {
this.removeNode(n);
}
}, this);
};
Graph.prototype.filterEdges = function(fn) {
var tmpEdges = this.edges.slice();
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();
});
};
// -----------
var Layout = Springy.Layout = {};
Layout.ForceDirected = function(graph, stiffness, repulsion, damping, minEnergyThreshold, maxSpeed) {
this.graph = graph;
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)) {
var mass = (node.data.mass !== undefined) ? node.data.mass : 1.0;
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)) {
var length = (edge.data.length !== undefined) ? edge.data.length : 1.0;
var existingSpring = false;
var from = this.graph.getEdges(edge.source, edge.target);
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);
}
var to = this.graph.getEdges(edge.target, edge.source);
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.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) {
var t = this;
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) {
var t = this;
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) {
var t = this;
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) {
if (point1 !== point2)
{
var d = point1.p.subtract(point2.p);
var distance = d.magnitude() + 0.1; // avoid massive forces at small distances (and divide by zero)
var direction = d.normalise();
// apply force to each end point
point1.applyForce(direction.multiply(this.repulsion).divide(distance * distance * 0.5));
point2.applyForce(direction.multiply(this.repulsion).divide(distance * distance * -0.5));
}
});
});
};
Layout.ForceDirected.prototype.applyHookesLaw = function() {
this.eachSpring(function(spring){
var d = spring.point2.p.subtract(spring.point1.p); // the direction of the spring
var displacement = spring.length - d.magnitude();
var direction = d.normalise();
// 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) {
var direction = point.p.multiply(-1.0);
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) {
var energy = 0.0;
this.eachNode(function(node, point) {
var speed = point.v.magnitude();
energy += 0.5 * point.m * speed * speed;
});
return energy;
};
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; // stolen from coffeescript, thanks jashkenas! ;-)
Springy.requestAnimationFrame = __bind(this.requestAnimationFrame ||
this.webkitRequestAnimationFrame ||
this.mozRequestAnimationFrame ||
this.oRequestAnimationFrame ||
this.msRequestAnimationFrame ||
(function(callback, element) {
this.setTimeout(callback, 10);
}), this);
/**
* 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(render, onRenderStop, onRenderStart) {
var t = this;
if (this._started) return;
this._started = true;
this._stop = false;
if (onRenderStart !== undefined) { onRenderStart(); }
Springy.requestAnimationFrame(function step() {
t.tick(0.03);
if (render !== undefined) {
render();
}
// stop simulation when energy of the system goes below a threshold
if (t._stop || t.totalEnergy() < t.minEnergyThreshold) {
t._started = false;
if (onRenderStop !== undefined) { onRenderStop(); }
} else {
Springy.requestAnimationFrame(step);
}
});
};
Layout.ForceDirected.prototype.stop = function() {
this._stop = true;
}
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) {
var min = {node: null, point: null, distance: null};
var t = this;
this.graph.nodes.forEach(function(n){
var point = t.point(n);
var distance = point.p.subtract(pos).magnitude();
if (min.distance === null || distance < min.distance) {
min = {node: n, point: point, distance: distance};
}
});
return min;
};
// returns [bottomleft, topright]
Layout.ForceDirected.prototype.getBoundingBox = function() {
var bottomleft = new Vector(-2,-2);
var topright = new Vector(2,2);
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;
}
});
var padding = topright.subtract(bottomleft).multiply(0.07); // ~5% padding
return {bottomleft: bottomleft.subtract(padding), topright: topright.add(padding)};
};
// Vector
var Vector = Springy.Vector = function(x, y) {
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
* @param onRenderStop optional callback function that gets executed whenever rendering stops.
* @param onRenderStart optional callback function that gets executed whenever rendering starts.
* @param onRenderFrame optional callback function that gets executed after each frame is rendered.
*/
var Renderer = Springy.Renderer = function(layout, clear, drawEdge, drawNode, onRenderStop, onRenderStart, onRenderFrame) {
this.layout = layout;
this.clear = clear;
this.drawEdge = drawEdge;
this.drawNode = drawNode;
this.onRenderStop = onRenderStop;
this.onRenderStart = onRenderStart;
this.onRenderFrame = onRenderFrame;
this.layout.graph.addGraphListener(this);
}
Renderer.prototype.graphChanged = function(e) {
this.start();
};
/**
* Starts the simulation of the layout in use.
*
* Note that in case the algorithm is still or already running then the layout that's in use
* might silently ignore the call, and your optional <code>done</code> callback is never executed.
* At least the built-in ForceDirected layout behaves in this way.
*
* @param done An optional callback function that gets executed when the springy algorithm stops,
* either because it ended or because stop() was called.
*/
Renderer.prototype.start = function(done) {
var t = this;
this.layout.start(function render() {
t.clear();
t.layout.eachEdge(function(edge, spring) {
t.drawEdge(edge, spring.point1.p, spring.point2.p);
});
t.layout.eachNode(function(node, point) {
t.drawNode(node, point.p);
});
if (t.onRenderFrame !== undefined) { t.onRenderFrame(); }
}, this.onRenderStop, this.onRenderStart);
};
Renderer.prototype.stop = function() {
this.layout.stop();
};
// Array.forEach implementation for IE support..
//https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function( callback, thisArg ) {
var T, k;
if ( this == null ) {
throw new TypeError( " this is null or not defined" );
}
var O = Object(this);
var len = O.length >>> 0; // Hack to convert O.length to a UInt32
if ( {}.toString.call(callback) != "[object Function]" ) {
throw new TypeError( callback + " is not a function" );
}
if ( thisArg ) {
T = thisArg;
}
k = 0;
while( k < len ) {
var kValue;
if ( k in O ) {
kValue = O[ k ];
callback.call( T, kValue, k, O );
}
k++;
}
};
}
var isEmpty = function(obj) {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
return false;
}
}
return true;
};
return Springy;
}));

56
src/display.js

@ -12,6 +12,13 @@ export class Display {
dispatch(target.getAttribute('href')) dispatch(target.getAttribute('href'))
e.preventDefault() e.preventDefault()
}) })
this.graph = new Springy.Graph()
this.layout = new Springy.Layout.ForceDirected(
this.graph,
400.0, // Spring stiffness
400.0, // Node repulsion
0.5 // Damping
)
} }
render(state) { render(state) {
const target = document.createElement('div') const target = document.createElement('div')
@ -19,15 +26,58 @@ export class Display {
const field = document.createElement('ul') const field = document.createElement('ul')
field.className = 'items' field.className = 'items'
const graph = this.graph
for (const item of state.items) { for (const item of state.items) {
graph.addNode(new Springy.Node(item.id, item))
}
let currentBB = this.layout.getBoundingBox()
let width = this.target.scrollWidth || 100
let height = this.target.scrollHeight || 100
var toScreen = function(p) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * (width - 100);
var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * (height - 100);
return new Springy.Vector(sx, sy);
};
var fromScreen = function(s) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
return new Springy.Vector(px, py);
};
var renderer = new Springy.Renderer(
this.layout,
() => {
currentBB = this.layout.getBoundingBox()
width = this.target.scrollWidth
height = this.target.scrollHeight
field.innerHTML = ''
},
function drawEdge(edge, p1, p2) {
// draw an edge
},
function drawNode(item, p) {
const target = toScreen(p)
const dom = document.createElement('li') const dom = document.createElement('li')
const a = document.createElement('a') const a = document.createElement('a')
const action = item.state == 'face-down' ? 'flip' : 'show'
const action = item.data.state == 'face-down' ? 'flip' : 'show'
a.href = `/${item.id}/${action}` a.href = `/${item.id}/${action}`
dom.className = item.state
a.style.backgroundImage = `url(img/${item.data.img})`
dom.className = item.data.state
dom.style.position = 'absolute'
dom.style.left = target.x + 'px'
dom.style.top = target.y + 'px'
dom.appendChild(a) dom.appendChild(a)
field.appendChild(dom) field.appendChild(dom)
}, undefined, undefined,
() => {
const dd = new diffDOM.DiffDOM()
const diff = dd.diff(this.target.children[0], field)
dd.apply(this.target.children[0], diff)
} }
);
target.appendChild(field) target.appendChild(field)
if (state.show !== null) { if (state.show !== null) {
const wrapper = document.createElement('a') const wrapper = document.createElement('a')
@ -41,5 +91,7 @@ export class Display {
const dd = new diffDOM.DiffDOM() const dd = new diffDOM.DiffDOM()
const diff = dd.diff(this.target, target) const diff = dd.diff(this.target, target)
dd.apply(this.target, diff) dd.apply(this.target, diff)
renderer.start();
} }
} }

2
src/index.js

@ -4,7 +4,7 @@ const target = document.createElement('div')
const state = {items: [], show: null } const state = {items: [], show: null }
for (let i = 0; i < 16; ++i) { for (let i = 0; i < 16; ++i) {
state.items.push({id: i, state: 'face-down'})
state.items.push({id: i, state: 'face-down', img: 'weben.svg'})
} }
class Actions { class Actions {

26
style.css

@ -5,13 +5,18 @@ body {
.wrapper { .wrapper {
max-width: 70em; max-width: 70em;
height: 100%;
margin: 0 auto; margin: 0 auto;
background-color: #FFC63F; background-color: #FFC63F;
position: relative;
box-sizing: border-box;
padding: 20px;
} }
.items { .items {
list-style: none; list-style: none;
margin: 0; margin: 0;
padding: 0;
} }
.items > li { .items > li {
@ -19,19 +24,20 @@ body {
} }
.items > li a { .items > li a {
width: 8em;
height: 8em;
width: 120px;
height: 120px;
background: #D66C00; background: #D66C00;
margin: 2em;
border-radius: 4em;
border-radius: 60px;
display: block; display: block;
} }
.items > li a:hover { .items > li a:hover {
background: #f39a3f;
background-color: #f39a3f;
z-index: 1;
} }
.items > li.face-up a { .items > li.face-up a {
background-size: cover;
background-color: #ed8112; background-color: #ed8112;
} }
@ -48,8 +54,10 @@ body {
} }
.fullview > div { .fullview > div {
background-color: #858c8f; background-color: #858c8f;
width: 20em;
margin: 5em auto;
position: relative;
height: 30em;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
min-width: 40em;
min-height: 30em;
} }
Loading…
Cancel
Save