* Displays a mindmap type layout.
* Loads basic information from FreeMind Mind Map format (*.mm).
* Shows moving nodes from one side to another, adding nodes, and switching out data.
* The basics are all in place, needs cleanup and a way to edit node text.
* Need a way to select a node to edit, maybe change click from toggle to select?
* Need a way to update the node text, once selected start typing and you get an edit to change the text?
* You can expand and collapse the nodes by clcking on them.
Last active
November 6, 2023 16:03
-
-
Save jdarling/2d4e84460d5f5df9c0ff to your computer and use it in GitHub Desktop.
D3 MindMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "Root", | |
"children": [ | |
{ | |
"name": "Branch 1", | |
"children": [ | |
{"name": "Leaf 3"}, | |
{"name": "Leaf 4"} | |
] | |
}, | |
{"name": "Branch 2"} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "flare", | |
"children": [ | |
{ | |
"name": "analytics", | |
"children": [ | |
{ | |
"name": "cluster", | |
"children": [ | |
{"name": "AgglomerativeCluster", "size": 3938}, | |
{"name": "CommunityStructure", "size": 3812}, | |
{"name": "HierarchicalCluster", "size": 6714}, | |
{"name": "MergeEdge", "size": 743} | |
] | |
}, | |
{ | |
"name": "graph", | |
"children": [ | |
{"name": "BetweennessCentrality", "size": 3534}, | |
{"name": "LinkDistance", "size": 5731}, | |
{"name": "MaxFlowMinCut", "size": 7840}, | |
{"name": "ShortestPaths", "size": 5914}, | |
{"name": "SpanningTree", "size": 3416} | |
] | |
}, | |
{ | |
"name": "optimization", | |
"children": [ | |
{"name": "AspectRatioBanker", "size": 7074} | |
] | |
} | |
] | |
}, | |
{ | |
"name": "animate", | |
"children": [ | |
{"name": "Easing", "size": 17010}, | |
{"name": "FunctionSequence", "size": 5842}, | |
{ | |
"name": "interpolate", | |
"children": [ | |
{"name": "ArrayInterpolator", "size": 1983}, | |
{"name": "ColorInterpolator", "size": 2047}, | |
{"name": "DateInterpolator", "size": 1375}, | |
{"name": "Interpolator", "size": 8746}, | |
{"name": "MatrixInterpolator", "size": 2202}, | |
{"name": "NumberInterpolator", "size": 1382}, | |
{"name": "ObjectInterpolator", "size": 1629}, | |
{"name": "PointInterpolator", "size": 1675}, | |
{"name": "RectangleInterpolator", "size": 2042} | |
] | |
}, | |
{"name": "ISchedulable", "size": 1041}, | |
{"name": "Parallel", "size": 5176}, | |
{"name": "Pause", "size": 449}, | |
{"name": "Scheduler", "size": 5593}, | |
{"name": "Sequence", "size": 5534}, | |
{"name": "Transition", "size": 9201}, | |
{"name": "Transitioner", "size": 19975}, | |
{"name": "TransitionEvent", "size": 1116}, | |
{"name": "Tween", "size": 6006} | |
] | |
}, | |
{ | |
"name": "data", | |
"children": [ | |
{ | |
"name": "converters", | |
"children": [ | |
{"name": "Converters", "size": 721}, | |
{"name": "DelimitedTextConverter", "size": 4294}, | |
{"name": "GraphMLConverter", "size": 9800}, | |
{"name": "IDataConverter", "size": 1314}, | |
{"name": "JSONConverter", "size": 2220} | |
] | |
}, | |
{"name": "DataField", "size": 1759}, | |
{"name": "DataSchema", "size": 2165}, | |
{"name": "DataSet", "size": 586}, | |
{"name": "DataSource", "size": 3331}, | |
{"name": "DataTable", "size": 772}, | |
{"name": "DataUtil", "size": 3322} | |
] | |
}, | |
{ | |
"name": "display", | |
"children": [ | |
{"name": "DirtySprite", "size": 8833}, | |
{"name": "LineSprite", "size": 1732}, | |
{"name": "RectSprite", "size": 3623}, | |
{"name": "TextSprite", "size": 10066} | |
] | |
}, | |
{ | |
"name": "flex", | |
"children": [ | |
{"name": "FlareVis", "size": 4116} | |
] | |
}, | |
{ | |
"name": "physics", | |
"children": [ | |
{"name": "DragForce", "size": 1082}, | |
{"name": "GravityForce", "size": 1336}, | |
{"name": "IForce", "size": 319}, | |
{"name": "NBodyForce", "size": 10498}, | |
{"name": "Particle", "size": 2822}, | |
{"name": "Simulation", "size": 9983}, | |
{"name": "Spring", "size": 2213}, | |
{"name": "SpringForce", "size": 1681} | |
] | |
}, | |
{ | |
"name": "query", | |
"children": [ | |
{"name": "AggregateExpression", "size": 1616}, | |
{"name": "And", "size": 1027}, | |
{"name": "Arithmetic", "size": 3891}, | |
{"name": "Average", "size": 891}, | |
{"name": "BinaryExpression", "size": 2893}, | |
{"name": "Comparison", "size": 5103}, | |
{"name": "CompositeExpression", "size": 3677}, | |
{"name": "Count", "size": 781}, | |
{"name": "DateUtil", "size": 4141}, | |
{"name": "Distinct", "size": 933}, | |
{"name": "Expression", "size": 5130}, | |
{"name": "ExpressionIterator", "size": 3617}, | |
{"name": "Fn", "size": 3240}, | |
{"name": "If", "size": 2732}, | |
{"name": "IsA", "size": 2039}, | |
{"name": "Literal", "size": 1214}, | |
{"name": "Match", "size": 3748}, | |
{"name": "Maximum", "size": 843}, | |
{ | |
"name": "methods", | |
"children": [ | |
{"name": "add", "size": 593}, | |
{"name": "and", "size": 330}, | |
{"name": "average", "size": 287}, | |
{"name": "count", "size": 277}, | |
{"name": "distinct", "size": 292}, | |
{"name": "div", "size": 595}, | |
{"name": "eq", "size": 594}, | |
{"name": "fn", "size": 460}, | |
{"name": "gt", "size": 603}, | |
{"name": "gte", "size": 625}, | |
{"name": "iff", "size": 748}, | |
{"name": "isa", "size": 461}, | |
{"name": "lt", "size": 597}, | |
{"name": "lte", "size": 619}, | |
{"name": "max", "size": 283}, | |
{"name": "min", "size": 283}, | |
{"name": "mod", "size": 591}, | |
{"name": "mul", "size": 603}, | |
{"name": "neq", "size": 599}, | |
{"name": "not", "size": 386}, | |
{"name": "or", "size": 323}, | |
{"name": "orderby", "size": 307}, | |
{"name": "range", "size": 772}, | |
{"name": "select", "size": 296}, | |
{"name": "stddev", "size": 363}, | |
{"name": "sub", "size": 600}, | |
{"name": "sum", "size": 280}, | |
{"name": "update", "size": 307}, | |
{"name": "variance", "size": 335}, | |
{"name": "where", "size": 299}, | |
{"name": "xor", "size": 354}, | |
{"name": "_", "size": 264} | |
] | |
}, | |
{"name": "Minimum", "size": 843}, | |
{"name": "Not", "size": 1554}, | |
{"name": "Or", "size": 970}, | |
{"name": "Query", "size": 13896}, | |
{"name": "Range", "size": 1594}, | |
{"name": "StringUtil", "size": 4130}, | |
{"name": "Sum", "size": 791}, | |
{"name": "Variable", "size": 1124}, | |
{"name": "Variance", "size": 1876}, | |
{"name": "Xor", "size": 1101} | |
] | |
}, | |
{ | |
"name": "scale", | |
"children": [ | |
{"name": "IScaleMap", "size": 2105}, | |
{"name": "LinearScale", "size": 1316}, | |
{"name": "LogScale", "size": 3151}, | |
{"name": "OrdinalScale", "size": 3770}, | |
{"name": "QuantileScale", "size": 2435}, | |
{"name": "QuantitativeScale", "size": 4839}, | |
{"name": "RootScale", "size": 1756}, | |
{"name": "Scale", "size": 4268}, | |
{"name": "ScaleType", "size": 1821}, | |
{"name": "TimeScale", "size": 5833} | |
] | |
}, | |
{ | |
"name": "util", | |
"children": [ | |
{"name": "Arrays", "size": 8258}, | |
{"name": "Colors", "size": 10001}, | |
{"name": "Dates", "size": 8217}, | |
{"name": "Displays", "size": 12555}, | |
{"name": "Filter", "size": 2324}, | |
{"name": "Geometry", "size": 10993}, | |
{ | |
"name": "heap", | |
"children": [ | |
{"name": "FibonacciHeap", "size": 9354}, | |
{"name": "HeapNode", "size": 1233} | |
] | |
}, | |
{"name": "IEvaluable", "size": 335}, | |
{"name": "IPredicate", "size": 383}, | |
{"name": "IValueProxy", "size": 874}, | |
{ | |
"name": "math", | |
"children": [ | |
{"name": "DenseMatrix", "size": 3165}, | |
{"name": "IMatrix", "size": 2815}, | |
{"name": "SparseMatrix", "size": 3366} | |
] | |
}, | |
{"name": "Maths", "size": 17705}, | |
{"name": "Orientation", "size": 1486}, | |
{ | |
"name": "palette", | |
"children": [ | |
{"name": "ColorPalette", "size": 6367}, | |
{"name": "Palette", "size": 1229}, | |
{"name": "ShapePalette", "size": 2059}, | |
{"name": "SizePalette", "size": 2291} | |
] | |
}, | |
{"name": "Property", "size": 5559}, | |
{"name": "Shapes", "size": 19118}, | |
{"name": "Sort", "size": 6887}, | |
{"name": "Stats", "size": 6557}, | |
{"name": "Strings", "size": 22026} | |
] | |
}, | |
{ | |
"name": "vis", | |
"children": [ | |
{ | |
"name": "axis", | |
"children": [ | |
{"name": "Axes", "size": 1302}, | |
{"name": "Axis", "size": 24593}, | |
{"name": "AxisGridLine", "size": 652}, | |
{"name": "AxisLabel", "size": 636}, | |
{"name": "CartesianAxes", "size": 6703} | |
] | |
}, | |
{ | |
"name": "controls", | |
"children": [ | |
{"name": "AnchorControl", "size": 2138}, | |
{"name": "ClickControl", "size": 3824}, | |
{"name": "Control", "size": 1353}, | |
{"name": "ControlList", "size": 4665}, | |
{"name": "DragControl", "size": 2649}, | |
{"name": "ExpandControl", "size": 2832}, | |
{"name": "HoverControl", "size": 4896}, | |
{"name": "IControl", "size": 763}, | |
{"name": "PanZoomControl", "size": 5222}, | |
{"name": "SelectionControl", "size": 7862}, | |
{"name": "TooltipControl", "size": 8435} | |
] | |
}, | |
{ | |
"name": "data", | |
"children": [ | |
{"name": "Data", "size": 20544}, | |
{"name": "DataList", "size": 19788}, | |
{"name": "DataSprite", "size": 10349}, | |
{"name": "EdgeSprite", "size": 3301}, | |
{"name": "NodeSprite", "size": 19382}, | |
{ | |
"name": "render", | |
"children": [ | |
{"name": "ArrowType", "size": 698}, | |
{"name": "EdgeRenderer", "size": 5569}, | |
{"name": "IRenderer", "size": 353}, | |
{"name": "ShapeRenderer", "size": 2247} | |
] | |
}, | |
{"name": "ScaleBinding", "size": 11275}, | |
{"name": "Tree", "size": 7147}, | |
{"name": "TreeBuilder", "size": 9930} | |
] | |
}, | |
{ | |
"name": "events", | |
"children": [ | |
{"name": "DataEvent", "size": 2313}, | |
{"name": "SelectionEvent", "size": 1880}, | |
{"name": "TooltipEvent", "size": 1701}, | |
{"name": "VisualizationEvent", "size": 1117} | |
] | |
}, | |
{ | |
"name": "legend", | |
"children": [ | |
{"name": "Legend", "size": 20859}, | |
{"name": "LegendItem", "size": 4614}, | |
{"name": "LegendRange", "size": 10530} | |
] | |
}, | |
{ | |
"name": "operator", | |
"children": [ | |
{ | |
"name": "distortion", | |
"children": [ | |
{"name": "BifocalDistortion", "size": 4461}, | |
{"name": "Distortion", "size": 6314}, | |
{"name": "FisheyeDistortion", "size": 3444} | |
] | |
}, | |
{ | |
"name": "encoder", | |
"children": [ | |
{"name": "ColorEncoder", "size": 3179}, | |
{"name": "Encoder", "size": 4060}, | |
{"name": "PropertyEncoder", "size": 4138}, | |
{"name": "ShapeEncoder", "size": 1690}, | |
{"name": "SizeEncoder", "size": 1830} | |
] | |
}, | |
{ | |
"name": "filter", | |
"children": [ | |
{"name": "FisheyeTreeFilter", "size": 5219}, | |
{"name": "GraphDistanceFilter", "size": 3165}, | |
{"name": "VisibilityFilter", "size": 3509} | |
] | |
}, | |
{"name": "IOperator", "size": 1286}, | |
{ | |
"name": "label", | |
"children": [ | |
{"name": "Labeler", "size": 9956}, | |
{"name": "RadialLabeler", "size": 3899}, | |
{"name": "StackedAreaLabeler", "size": 3202} | |
] | |
}, | |
{ | |
"name": "layout", | |
"children": [ | |
{"name": "AxisLayout", "size": 6725}, | |
{"name": "BundledEdgeRouter", "size": 3727}, | |
{"name": "CircleLayout", "size": 9317}, | |
{"name": "CirclePackingLayout", "size": 12003}, | |
{"name": "DendrogramLayout", "size": 4853}, | |
{"name": "ForceDirectedLayout", "size": 8411}, | |
{"name": "IcicleTreeLayout", "size": 4864}, | |
{"name": "IndentedTreeLayout", "size": 3174}, | |
{"name": "Layout", "size": 7881}, | |
{"name": "NodeLinkTreeLayout", "size": 12870}, | |
{"name": "PieLayout", "size": 2728}, | |
{"name": "RadialTreeLayout", "size": 12348}, | |
{"name": "RandomLayout", "size": 870}, | |
{"name": "StackedAreaLayout", "size": 9121}, | |
{"name": "TreeMapLayout", "size": 9191} | |
] | |
}, | |
{"name": "Operator", "size": 2490}, | |
{"name": "OperatorList", "size": 5248}, | |
{"name": "OperatorSequence", "size": 4190}, | |
{"name": "OperatorSwitch", "size": 2581}, | |
{"name": "SortOperator", "size": 2023} | |
] | |
}, | |
{"name": "Visualization", "size": 16540} | |
] | |
} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> | |
<link type="text/css" rel="stylesheet" href="style.css"/> | |
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script> | |
<script type="text/javascript" src="mousetrap.js"></script> | |
<style type="text/css"> | |
.node circle { | |
cursor: pointer; | |
fill: #fff; | |
stroke: steelblue; | |
stroke-width: 1.5px; | |
} | |
.node text { | |
font-size: 11px; | |
} | |
path.link { | |
fill: none; | |
stroke: #ccc; | |
stroke-width: 1.5px; | |
} | |
.node.selected circle { | |
fill: green; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="body"> | |
<div id="toolbar"> | |
<button onclick="createNew(); return false;">New</button> | |
<button onclick="loadFreeMind('test.mm'); return false;">FreeMind (test.mm)</button> | |
<button onclick="loadJSON('flare.json'); return false;">Flare (flare.json)</button> | |
<button onclick="loadJSON('data.json'); return false;">JSON (test.json)</button> | |
<button onclick="addNodes('right'); return false;">Add nodes right</button> | |
<button onclick="addNodes('left'); return false;">Add nodes left</button> | |
<button onclick="moveNodes('right', 'left'); return false;">Move right to left</button> | |
<button onclick="moveNodes('left', 'right'); return false;">Move left to right</button> | |
<button onclick="setConnector('diagonal'); return false;">Diagonal connector</button> | |
<button onclick="setConnector('elbow'); return false;">Elbow connector</button> | |
</div> | |
<div id="footer">[Enter] Change name, [Left] Move select left, [Right] Move selection right, [Up] Move selection up, [Down] Move selection down, [Ins] Add new node, [Del] Delete selected node</div> | |
</div> | |
<script type="text/javascript"> | |
/* | |
// Add a new item | |
root.right.push({name: 'bar'}, {name: 'none'}, {name: 'some'}, {name: 'value'}); | |
update(root); | |
// Move from the first to the last | |
root.right.push(root.right.shift()); | |
update(root); | |
// Move from right to left | |
var tmp = root.right.shift(); | |
tmp.position = 'left'; | |
root.left.push(tmp); | |
update(root); | |
// Move from left to right | |
var tmp = root.left.shift(); | |
tmp.position = 'right'; | |
root.right.push(tmp); | |
update(root); | |
// Switch connector type | |
connector = diagonal; | |
update(root); | |
*/ | |
var m = [20, 120, 20, 120], | |
//w = 1280 - m[1] - m[3], | |
w = 900 - m[1] - m[3], | |
h = 500 - m[0] - m[2], | |
i = 0, | |
root; | |
var getDirection = function(data){ | |
if(!data){ | |
return 'root'; | |
} | |
if(data.position){ | |
return data.position; | |
} | |
return getDirection(data.parent); | |
}; | |
var selectNode = function(target){ | |
if(target){ | |
var sel = d3.selectAll('#body svg .node').filter(function(d){return d.id==target.id})[0][0]; | |
if(sel){ | |
select(sel); | |
} | |
} | |
}; | |
Mousetrap.bind('left', function(){ | |
// left key pressed | |
var selection = d3.select(".node.selected")[0][0]; | |
if(selection){ | |
var data = selection.__data__; | |
var dir = getDirection(data); | |
switch(dir){ | |
case('right'): | |
case('root'): | |
selectNode(data.parent || data.left[0]); | |
break; | |
case('left'): | |
selectNode((data.children||[])[0]); | |
break; | |
default: | |
break; | |
} | |
} | |
}); | |
Mousetrap.bind('right', function(){ | |
// right key pressed | |
var selection = d3.select(".node.selected")[0][0]; | |
if(selection){ | |
var data = selection.__data__; | |
var dir = getDirection(data); | |
switch(dir){ | |
case('left'): | |
case('root'): | |
selectNode(data.parent || data.right[0]); | |
break; | |
case('right'): | |
selectNode((data.children||[])[0]); | |
break; | |
default: | |
break; | |
} | |
} | |
}); | |
Mousetrap.bind('up', function(){ | |
// up key pressed | |
var selection = d3.select(".node.selected")[0][0]; | |
if(selection){ | |
var data = selection.__data__; | |
var dir = getDirection(data); | |
switch(dir){ | |
case('root'): | |
break; | |
case('left'): | |
case('right'): | |
var p = data.parent, nl = p.children || [], i=1; | |
if(p[dir]){ | |
nl = p[dir]; | |
} | |
l = nl.length; | |
for(; i<l; i++){ | |
if(nl[i].id === data.id){ | |
selectNode(nl[i-1]); | |
break; | |
} | |
} | |
break; | |
} | |
} | |
return false; | |
}); | |
Mousetrap.bind('down', function(){ | |
// down key pressed | |
// up key pressed | |
var selection = d3.select(".node.selected")[0][0]; | |
if(selection){ | |
var data = selection.__data__; | |
var dir = getDirection(data); | |
switch(dir){ | |
case('root'): | |
break; | |
case('left'): | |
case('right'): | |
var p = data.parent, nl = p.children || [], i=0; | |
if(p[dir]){ | |
nl = p[dir]; | |
} | |
l = nl.length; | |
for(; i<l-1; i++){ | |
if(nl[i].id === data.id){ | |
selectNode(nl[i+1]); | |
break; | |
} | |
} | |
break; | |
} | |
} | |
return false; | |
}); | |
Mousetrap.bind('ins', function(){ | |
var selection = d3.select(".node.selected")[0][0]; | |
if(selection){ | |
var data = selection.__data__; | |
var dir = getDirection(data); | |
var name = prompt('New name'); | |
if(name){ | |
if(dir==='root'){ | |
dir = data.right.length>data.left.length?'left':'right'; | |
} | |
var cl = data[dir] || data.children || data._children; | |
if(!cl){ | |
cl = data.children = []; | |
} | |
cl.push({name: name, position: dir}); | |
update(root); | |
} | |
} | |
}); | |
Mousetrap.bind('del', function(){ | |
var selection = d3.select(".node.selected")[0][0]; | |
if(selection){ | |
var data = selection.__data__; | |
var dir = getDirection(data); | |
if(dir==='root'){ | |
alert('Can\'t delete root'); | |
return; | |
} | |
var cl = data.parent[dir] || data.parent.children; | |
if(!cl){ | |
alert('Could not locate children'); | |
return; | |
} | |
var i = 0, l = cl.length; | |
for(; i<l; i++){ | |
if(cl[i].id === data.id){ | |
if(confirm('Sure you want to delete '+data.name+'?') === true){ | |
cl.splice(i, 1); | |
} | |
break; | |
} | |
} | |
selectNode(root); | |
update(root); | |
} | |
}); | |
Mousetrap.bind('enter', function(){ | |
var selection = d3.select(".node.selected")[0][0]; | |
if(selection){ | |
var data = selection.__data__; | |
data.name = prompt('New text:', data.name) || data.name; | |
update(root); | |
} | |
}); | |
var addNodes = function(dir){ | |
root[dir].push({name: 'bar', position: dir}, {name: 'none', position: dir}, {name: 'some', position: dir}, {name: 'value', position: dir}); | |
update(root); | |
}; | |
var moveNodes = function(from, to){ | |
var tmp = root[from].shift(); | |
tmp.position = to; | |
root[to].push(tmp); | |
update(root); | |
}; | |
var setConnector = function(type){ | |
connector = window[type]; | |
update(root); | |
}; | |
var select = function(node){ | |
// Find previously selected, unselect | |
d3.select(".selected").classed("selected", false); | |
// Select current item | |
d3.select(node).classed("selected", true); | |
}; | |
var createNew = function(){ | |
root = {name: 'Root', children: [], left: [], right: []}; | |
update(root, true); | |
selectNode(root); | |
}; | |
var handleClick = function(d, index){ | |
select(this); | |
update(d); | |
}; | |
var tree = d3.layout.tree() | |
.size([h, w]); | |
var calcLeft = function(d){ | |
var l = d.y; | |
if(d.position==='left'){ | |
l = (d.y)-w/2; | |
l = (w/2) + l; | |
} | |
return {x : d.x, y : l}; | |
}; | |
var diagonal = d3.svg.diagonal() | |
.projection(function(d) { return [d.y, d.x]; }); | |
var elbow = function (d, i){ | |
var source = calcLeft(d.source); | |
var target = calcLeft(d.target); | |
var hy = (target.y-source.y)/2; | |
return "M" + source.y + "," + source.x | |
+ "H" + (source.y+hy) | |
+ "V" + target.x + "H" + target.y; | |
}; | |
var connector = elbow; | |
var vis = d3.select("#body") | |
.append("svg:svg") | |
.attr("width", w | |
+ m[1] + m[3]) | |
.attr("height", h + m[0] + m[2]) | |
.append("svg:g") | |
//.attr("transform", "translate(" + m[3] + "," + m[0] + ")") | |
.attr("transform", "translate(" + (w/2+m[3]) + "," + m[0] + ")") | |
; | |
//* | |
var loadJSON = function(fileName){ | |
//d3.json("/data/data.json", function(json) { | |
d3.json(fileName, function(json) { | |
var i=0, l=json.children.length; | |
window.data = root = json; | |
root.x0 = h / 2; | |
root.y0 = 0; | |
json.left = []; | |
json.right = []; | |
for(; i<l; i++){ | |
if(i%2){ | |
json.left.push(json.children[i]); | |
json.children[i].position = 'left'; | |
}else{ | |
json.right.push(json.children[i]); | |
json.children[i].position = 'right'; | |
} | |
} | |
update(root, true); | |
selectNode(root); | |
}); | |
}; | |
//*/ | |
//* | |
var loadFreeMind = function(fileName){ | |
d3.xml(fileName, 'application/xml', function(err, xml){ | |
// Changes XML to JSON | |
function xmlToJson(xml) { | |
// Create the return object | |
var obj = {}; | |
if (xml.nodeType == 1) { // element | |
// do attributes | |
if (xml.attributes.length > 0) { | |
obj["@attributes"] = {}; | |
for (var j = 0; j < xml.attributes.length; j++) { | |
var attribute = xml.attributes.item(j); | |
obj["@attributes"][attribute.nodeName] = attribute.nodeValue; | |
} | |
} | |
} else if (xml.nodeType == 3) { // text | |
obj = xml.nodeValue; | |
} | |
// do children | |
if (xml.hasChildNodes()) { | |
for(var i = 0; i < xml.childNodes.length; i++) { | |
var item = xml.childNodes.item(i); | |
var nodeName = item.nodeName; | |
if (typeof(obj[nodeName]) == "undefined") { | |
obj[nodeName] = xmlToJson(item); | |
} else { | |
if (typeof(obj[nodeName].push) == "undefined") { | |
var old = obj[nodeName]; | |
obj[nodeName] = []; | |
obj[nodeName].push(old); | |
} | |
obj[nodeName].push(xmlToJson(item)); | |
} | |
} | |
} | |
return obj; | |
}; | |
var js = xmlToJson(xml); | |
var data = js.map.node; | |
var parseData = function(data, direction){ | |
var key, i, l, dir = direction, node = {}, child; | |
for(key in data['@attributes']){ | |
node[key.toLowerCase()] = data['@attributes'][key]; | |
} | |
node.direction = node.direction || dir; | |
l = (data.node || []).length; | |
if(l){ | |
node.children = []; | |
for(i=0; i<l; i++){ | |
dir = data.node[i]['@attributes'].POSITION || dir; | |
child = parseData(data.node[i], {}, dir); | |
(node[dir] = node[dir] || []).push(child); | |
node.children.push(child); | |
} | |
} | |
return node; | |
}; | |
root = parseData(data, 'right'); | |
root.x0 = h / 2; | |
root.y0 = w / 2; | |
update(root, true); | |
selectNode(root); | |
}); | |
}; | |
//*/ | |
var toArray = function(item, arr, d){ | |
arr = arr || []; | |
var dr = d || 1; | |
var i = 0, l = item.children?item.children.length:0; | |
arr.push(item); | |
if(item.position && item.position==='left'){ | |
dr = -1; | |
} | |
item.y = dr * item.y; | |
for(; i < l; i++){ | |
toArray(item.children[i], arr, dr); | |
} | |
return arr; | |
}; | |
function update(source, slow) { | |
var duration = (d3.event && d3.event.altKey) || slow ? 1000 : 100; | |
// Compute the new tree layout. | |
var nodesLeft = tree | |
.size([h, (w/2)-20]) | |
.children(function(d){ | |
return (d.depth===0)?d.left:d.children; | |
}) | |
.nodes(root) | |
.reverse(); | |
var nodesRight = tree | |
.size([h, w/2]) | |
.children(function(d){ | |
return (d.depth===0)?d.right:d.children; | |
}) | |
.nodes(root) | |
.reverse(); | |
root.children = root.left.concat(root.right); | |
root._children = null; | |
var nodes = toArray(root); | |
// Normalize for fixed-depth. | |
//nodes.forEach(function(d) { d.y = d.depth * 180; }); | |
// Update the nodes… | |
var node = vis.selectAll("g.node") | |
.data(nodes, function(d) { return d.id || (d.id = ++i); }); | |
// Enter any new nodes at the parent's previous position. | |
var nodeEnter = node.enter().append("svg:g") | |
.attr("class", function(d){ return d.selected?"node selected":"node"; }) | |
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) | |
.on("click", handleClick); | |
nodeEnter.append("svg:circle") | |
.attr("r", 1e-6); | |
//.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); | |
nodeEnter.append("svg:text") | |
.attr("x", function(d) { return d.children || d._children ? -10 : 10; }) | |
// .attr("dy", ".35em") | |
// .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) | |
.attr("dy", 14) | |
.attr("text-anchor", "middle") | |
.text(function(d) { return (d.name || d.text); }) | |
.style("fill-opacity", 1); | |
// Transition nodes to their new position. | |
var nodeUpdate = node.transition() | |
//.attr("class", function(d){ return d.selected?"node selected":"node"; }) | |
.duration(duration) | |
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }); | |
nodeUpdate.select("text") | |
.text(function(d) { return (d.name || d.text); }); | |
nodeUpdate.select("circle") | |
.attr("r", 4.5); | |
//.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); | |
/* | |
nodeUpdate.select("text") | |
.attr("dy", 14) | |
.attr("text-anchor", "middle") | |
.style("fill-opacity", 1); | |
*/ | |
// Transition exiting nodes to the parent's new position. | |
var nodeExit = node.exit().transition() | |
.duration(duration) | |
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; }) | |
.remove(); | |
nodeExit.select("circle") | |
.attr("r", 1e-6); | |
nodeExit.select("text") | |
.style("fill-opacity", 1e-6); | |
// Update the links… | |
var link = vis.selectAll("path.link") | |
.data(tree.links(nodes), function(d) { return d.target.id; }); | |
// Enter any new links at the parent's previous position. | |
link.enter().insert("svg:path", "g") | |
.attr("class", "link") | |
.attr("d", function(d) { | |
var o = {x: source.x0, y: source.y0}; | |
return connector({source: o, target: o}); | |
}) | |
.transition() | |
.duration(duration) | |
.attr("d", connector); | |
// Transition links to their new position. | |
link.transition() | |
.duration(duration) | |
.attr("d", connector); | |
// Transition exiting nodes to the parent's new position. | |
link.exit().transition() | |
.duration(duration) | |
.attr("d", function(d) { | |
var o = {x: source.x, y: source.y}; | |
return connector({source: o, target: o}); | |
}) | |
.remove(); | |
// Stash the old positions for transition. | |
nodes.forEach(function(d) { | |
d.x0 = d.x; | |
d.y0 = d.y; | |
}); | |
} | |
// Toggle children. | |
function toggle(d) { | |
if (d.children) { | |
d._children = d.children; | |
d.children = null; | |
} else { | |
d.children = d._children; | |
d._children = null; | |
} | |
} | |
loadJSON('data.json'); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*global define:false */ | |
/** | |
* Copyright 2013 Craig Campbell | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
* | |
* Mousetrap is a simple keyboard shortcut library for Javascript with | |
* no external dependencies | |
* | |
* @version 1.4.6 | |
* @url craig.is/killing/mice | |
*/ | |
(function(window, document, undefined) { | |
/** | |
* mapping of special keycodes to their corresponding keys | |
* | |
* everything in this dictionary cannot use keypress events | |
* so it has to be here to map to the correct keycodes for | |
* keyup/keydown events | |
* | |
* @type {Object} | |
*/ | |
var _MAP = { | |
8: 'backspace', | |
9: 'tab', | |
13: 'enter', | |
16: 'shift', | |
17: 'ctrl', | |
18: 'alt', | |
20: 'capslock', | |
27: 'esc', | |
32: 'space', | |
33: 'pageup', | |
34: 'pagedown', | |
35: 'end', | |
36: 'home', | |
37: 'left', | |
38: 'up', | |
39: 'right', | |
40: 'down', | |
45: 'ins', | |
46: 'del', | |
91: 'meta', | |
93: 'meta', | |
224: 'meta' | |
}, | |
/** | |
* mapping for special characters so they can support | |
* | |
* this dictionary is only used incase you want to bind a | |
* keyup or keydown event to one of these keys | |
* | |
* @type {Object} | |
*/ | |
_KEYCODE_MAP = { | |
106: '*', | |
107: '+', | |
109: '-', | |
110: '.', | |
111 : '/', | |
186: ';', | |
187: '=', | |
188: ',', | |
189: '-', | |
190: '.', | |
191: '/', | |
192: '`', | |
219: '[', | |
220: '\\', | |
221: ']', | |
222: '\'' | |
}, | |
/** | |
* this is a mapping of keys that require shift on a US keypad | |
* back to the non shift equivelents | |
* | |
* this is so you can use keyup events with these keys | |
* | |
* note that this will only work reliably on US keyboards | |
* | |
* @type {Object} | |
*/ | |
_SHIFT_MAP = { | |
'~': '`', | |
'!': '1', | |
'@': '2', | |
'#': '3', | |
'$': '4', | |
'%': '5', | |
'^': '6', | |
'&': '7', | |
'*': '8', | |
'(': '9', | |
')': '0', | |
'_': '-', | |
'+': '=', | |
':': ';', | |
'\"': '\'', | |
'<': ',', | |
'>': '.', | |
'?': '/', | |
'|': '\\' | |
}, | |
/** | |
* this is a list of special strings you can use to map | |
* to modifier keys when you specify your keyboard shortcuts | |
* | |
* @type {Object} | |
*/ | |
_SPECIAL_ALIASES = { | |
'option': 'alt', | |
'command': 'meta', | |
'return': 'enter', | |
'escape': 'esc', | |
'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl' | |
}, | |
/** | |
* variable to store the flipped version of _MAP from above | |
* needed to check if we should use keypress or not when no action | |
* is specified | |
* | |
* @type {Object|undefined} | |
*/ | |
_REVERSE_MAP, | |
/** | |
* a list of all the callbacks setup via Mousetrap.bind() | |
* | |
* @type {Object} | |
*/ | |
_callbacks = {}, | |
/** | |
* direct map of string combinations to callbacks used for trigger() | |
* | |
* @type {Object} | |
*/ | |
_directMap = {}, | |
/** | |
* keeps track of what level each sequence is at since multiple | |
* sequences can start out with the same sequence | |
* | |
* @type {Object} | |
*/ | |
_sequenceLevels = {}, | |
/** | |
* variable to store the setTimeout call | |
* | |
* @type {null|number} | |
*/ | |
_resetTimer, | |
/** | |
* temporary state where we will ignore the next keyup | |
* | |
* @type {boolean|string} | |
*/ | |
_ignoreNextKeyup = false, | |
/** | |
* temporary state where we will ignore the next keypress | |
* | |
* @type {boolean} | |
*/ | |
_ignoreNextKeypress = false, | |
/** | |
* are we currently inside of a sequence? | |
* type of action ("keyup" or "keydown" or "keypress") or false | |
* | |
* @type {boolean|string} | |
*/ | |
_nextExpectedAction = false; | |
/** | |
* loop through the f keys, f1 to f19 and add them to the map | |
* programatically | |
*/ | |
for (var i = 1; i < 20; ++i) { | |
_MAP[111 + i] = 'f' + i; | |
} | |
/** | |
* loop through to map numbers on the numeric keypad | |
*/ | |
for (i = 0; i <= 9; ++i) { | |
_MAP[i + 96] = i; | |
} | |
/** | |
* cross browser add event method | |
* | |
* @param {Element|HTMLDocument} object | |
* @param {string} type | |
* @param {Function} callback | |
* @returns void | |
*/ | |
function _addEvent(object, type, callback) { | |
if (object.addEventListener) { | |
object.addEventListener(type, callback, false); | |
return; | |
} | |
object.attachEvent('on' + type, callback); | |
} | |
/** | |
* takes the event and returns the key character | |
* | |
* @param {Event} e | |
* @return {string} | |
*/ | |
function _characterFromEvent(e) { | |
// for keypress events we should return the character as is | |
if (e.type == 'keypress') { | |
var character = String.fromCharCode(e.which); | |
// if the shift key is not pressed then it is safe to assume | |
// that we want the character to be lowercase. this means if | |
// you accidentally have caps lock on then your key bindings | |
// will continue to work | |
// | |
// the only side effect that might not be desired is if you | |
// bind something like 'A' cause you want to trigger an | |
// event when capital A is pressed caps lock will no longer | |
// trigger the event. shift+a will though. | |
if (!e.shiftKey) { | |
character = character.toLowerCase(); | |
} | |
return character; | |
} | |
// for non keypress events the special maps are needed | |
if (_MAP[e.which]) { | |
return _MAP[e.which]; | |
} | |
if (_KEYCODE_MAP[e.which]) { | |
return _KEYCODE_MAP[e.which]; | |
} | |
// if it is not in the special map | |
// with keydown and keyup events the character seems to always | |
// come in as an uppercase character whether you are pressing shift | |
// or not. we should make sure it is always lowercase for comparisons | |
return String.fromCharCode(e.which).toLowerCase(); | |
} | |
/** | |
* checks if two arrays are equal | |
* | |
* @param {Array} modifiers1 | |
* @param {Array} modifiers2 | |
* @returns {boolean} | |
*/ | |
function _modifiersMatch(modifiers1, modifiers2) { | |
return modifiers1.sort().join(',') === modifiers2.sort().join(','); | |
} | |
/** | |
* resets all sequence counters except for the ones passed in | |
* | |
* @param {Object} doNotReset | |
* @returns void | |
*/ | |
function _resetSequences(doNotReset) { | |
doNotReset = doNotReset || {}; | |
var activeSequences = false, | |
key; | |
for (key in _sequenceLevels) { | |
if (doNotReset[key]) { | |
activeSequences = true; | |
continue; | |
} | |
_sequenceLevels[key] = 0; | |
} | |
if (!activeSequences) { | |
_nextExpectedAction = false; | |
} | |
} | |
/** | |
* finds all callbacks that match based on the keycode, modifiers, | |
* and action | |
* | |
* @param {string} character | |
* @param {Array} modifiers | |
* @param {Event|Object} e | |
* @param {string=} sequenceName - name of the sequence we are looking for | |
* @param {string=} combination | |
* @param {number=} level | |
* @returns {Array} | |
*/ | |
function _getMatches(character, modifiers, e, sequenceName, combination, level) { | |
var i, | |
callback, | |
matches = [], | |
action = e.type; | |
// if there are no events related to this keycode | |
if (!_callbacks[character]) { | |
return []; | |
} | |
// if a modifier key is coming up on its own we should allow it | |
if (action == 'keyup' && _isModifier(character)) { | |
modifiers = [character]; | |
} | |
// loop through all callbacks for the key that was pressed | |
// and see if any of them match | |
for (i = 0; i < _callbacks[character].length; ++i) { | |
callback = _callbacks[character][i]; | |
// if a sequence name is not specified, but this is a sequence at | |
// the wrong level then move onto the next match | |
if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) { | |
continue; | |
} | |
// if the action we are looking for doesn't match the action we got | |
// then we should keep going | |
if (action != callback.action) { | |
continue; | |
} | |
// if this is a keypress event and the meta key and control key | |
// are not pressed that means that we need to only look at the | |
// character, otherwise check the modifiers as well | |
// | |
// chrome will not fire a keypress if meta or control is down | |
// safari will fire a keypress if meta or meta+shift is down | |
// firefox will fire a keypress if meta or control is down | |
if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { | |
// when you bind a combination or sequence a second time it | |
// should overwrite the first one. if a sequenceName or | |
// combination is specified in this call it does just that | |
// | |
// @todo make deleting its own method? | |
var deleteCombo = !sequenceName && callback.combo == combination; | |
var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level; | |
if (deleteCombo || deleteSequence) { | |
_callbacks[character].splice(i, 1); | |
} | |
matches.push(callback); | |
} | |
} | |
return matches; | |
} | |
/** | |
* takes a key event and figures out what the modifiers are | |
* | |
* @param {Event} e | |
* @returns {Array} | |
*/ | |
function _eventModifiers(e) { | |
var modifiers = []; | |
if (e.shiftKey) { | |
modifiers.push('shift'); | |
} | |
if (e.altKey) { | |
modifiers.push('alt'); | |
} | |
if (e.ctrlKey) { | |
modifiers.push('ctrl'); | |
} | |
if (e.metaKey) { | |
modifiers.push('meta'); | |
} | |
return modifiers; | |
} | |
/** | |
* prevents default for this event | |
* | |
* @param {Event} e | |
* @returns void | |
*/ | |
function _preventDefault(e) { | |
if (e.preventDefault) { | |
e.preventDefault(); | |
return; | |
} | |
e.returnValue = false; | |
} | |
/** | |
* stops propogation for this event | |
* | |
* @param {Event} e | |
* @returns void | |
*/ | |
function _stopPropagation(e) { | |
if (e.stopPropagation) { | |
e.stopPropagation(); | |
return; | |
} | |
e.cancelBubble = true; | |
} | |
/** | |
* actually calls the callback function | |
* | |
* if your callback function returns false this will use the jquery | |
* convention - prevent default and stop propogation on the event | |
* | |
* @param {Function} callback | |
* @param {Event} e | |
* @returns void | |
*/ | |
function _fireCallback(callback, e, combo, sequence) { | |
// if this event should not happen stop here | |
if (Mousetrap.stopCallback(e, e.target || e.srcElement, combo, sequence)) { | |
return; | |
} | |
if (callback(e, combo) === false) { | |
_preventDefault(e); | |
_stopPropagation(e); | |
} | |
} | |
/** | |
* handles a character key event | |
* | |
* @param {string} character | |
* @param {Array} modifiers | |
* @param {Event} e | |
* @returns void | |
*/ | |
function _handleKey(character, modifiers, e) { | |
var callbacks = _getMatches(character, modifiers, e), | |
i, | |
doNotReset = {}, | |
maxLevel = 0, | |
processedSequenceCallback = false; | |
// Calculate the maxLevel for sequences so we can only execute the longest callback sequence | |
for (i = 0; i < callbacks.length; ++i) { | |
if (callbacks[i].seq) { | |
maxLevel = Math.max(maxLevel, callbacks[i].level); | |
} | |
} | |
// loop through matching callbacks for this key event | |
for (i = 0; i < callbacks.length; ++i) { | |
// fire for all sequence callbacks | |
// this is because if for example you have multiple sequences | |
// bound such as "g i" and "g t" they both need to fire the | |
// callback for matching g cause otherwise you can only ever | |
// match the first one | |
if (callbacks[i].seq) { | |
// only fire callbacks for the maxLevel to prevent | |
// subsequences from also firing | |
// | |
// for example 'a option b' should not cause 'option b' to fire | |
// even though 'option b' is part of the other sequence | |
// | |
// any sequences that do not match here will be discarded | |
// below by the _resetSequences call | |
if (callbacks[i].level != maxLevel) { | |
continue; | |
} | |
processedSequenceCallback = true; | |
// keep a list of which sequences were matches for later | |
doNotReset[callbacks[i].seq] = 1; | |
_fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq); | |
continue; | |
} | |
// if there were no sequence matches but we are still here | |
// that means this is a regular match so we should fire that | |
if (!processedSequenceCallback) { | |
_fireCallback(callbacks[i].callback, e, callbacks[i].combo); | |
} | |
} | |
// if the key you pressed matches the type of sequence without | |
// being a modifier (ie "keyup" or "keypress") then we should | |
// reset all sequences that were not matched by this event | |
// | |
// this is so, for example, if you have the sequence "h a t" and you | |
// type "h e a r t" it does not match. in this case the "e" will | |
// cause the sequence to reset | |
// | |
// modifier keys are ignored because you can have a sequence | |
// that contains modifiers such as "enter ctrl+space" and in most | |
// cases the modifier key will be pressed before the next key | |
// | |
// also if you have a sequence such as "ctrl+b a" then pressing the | |
// "b" key will trigger a "keypress" and a "keydown" | |
// | |
// the "keydown" is expected when there is a modifier, but the | |
// "keypress" ends up matching the _nextExpectedAction since it occurs | |
// after and that causes the sequence to reset | |
// | |
// we ignore keypresses in a sequence that directly follow a keydown | |
// for the same character | |
var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress; | |
if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) { | |
_resetSequences(doNotReset); | |
} | |
_ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown'; | |
} | |
/** | |
* handles a keydown event | |
* | |
* @param {Event} e | |
* @returns void | |
*/ | |
function _handleKeyEvent(e) { | |
// normalize e.which for key events | |
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion | |
if (typeof e.which !== 'number') { | |
e.which = e.keyCode; | |
} | |
var character = _characterFromEvent(e); | |
// no character found then stop | |
if (!character) { | |
return; | |
} | |
// need to use === for the character check because the character can be 0 | |
if (e.type == 'keyup' && _ignoreNextKeyup === character) { | |
_ignoreNextKeyup = false; | |
return; | |
} | |
Mousetrap.handleKey(character, _eventModifiers(e), e); | |
} | |
/** | |
* determines if the keycode specified is a modifier key or not | |
* | |
* @param {string} key | |
* @returns {boolean} | |
*/ | |
function _isModifier(key) { | |
return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; | |
} | |
/** | |
* called to set a 1 second timeout on the specified sequence | |
* | |
* this is so after each key press in the sequence you have 1 second | |
* to press the next key before you have to start over | |
* | |
* @returns void | |
*/ | |
function _resetSequenceTimer() { | |
clearTimeout(_resetTimer); | |
_resetTimer = setTimeout(_resetSequences, 1000); | |
} | |
/** | |
* reverses the map lookup so that we can look for specific keys | |
* to see what can and can't use keypress | |
* | |
* @return {Object} | |
*/ | |
function _getReverseMap() { | |
if (!_REVERSE_MAP) { | |
_REVERSE_MAP = {}; | |
for (var key in _MAP) { | |
// pull out the numeric keypad from here cause keypress should | |
// be able to detect the keys from the character | |
if (key > 95 && key < 112) { | |
continue; | |
} | |
if (_MAP.hasOwnProperty(key)) { | |
_REVERSE_MAP[_MAP[key]] = key; | |
} | |
} | |
} | |
return _REVERSE_MAP; | |
} | |
/** | |
* picks the best action based on the key combination | |
* | |
* @param {string} key - character for key | |
* @param {Array} modifiers | |
* @param {string=} action passed in | |
*/ | |
function _pickBestAction(key, modifiers, action) { | |
// if no action was picked in we should try to pick the one | |
// that we think would work best for this key | |
if (!action) { | |
action = _getReverseMap()[key] ? 'keydown' : 'keypress'; | |
} | |
// modifier keys don't work as expected with keypress, | |
// switch to keydown | |
if (action == 'keypress' && modifiers.length) { | |
action = 'keydown'; | |
} | |
return action; | |
} | |
/** | |
* binds a key sequence to an event | |
* | |
* @param {string} combo - combo specified in bind call | |
* @param {Array} keys | |
* @param {Function} callback | |
* @param {string=} action | |
* @returns void | |
*/ | |
function _bindSequence(combo, keys, callback, action) { | |
// start off by adding a sequence level record for this combination | |
// and setting the level to 0 | |
_sequenceLevels[combo] = 0; | |
/** | |
* callback to increase the sequence level for this sequence and reset | |
* all other sequences that were active | |
* | |
* @param {string} nextAction | |
* @returns {Function} | |
*/ | |
function _increaseSequence(nextAction) { | |
return function() { | |
_nextExpectedAction = nextAction; | |
++_sequenceLevels[combo]; | |
_resetSequenceTimer(); | |
}; | |
} | |
/** | |
* wraps the specified callback inside of another function in order | |
* to reset all sequence counters as soon as this sequence is done | |
* | |
* @param {Event} e | |
* @returns void | |
*/ | |
function _callbackAndReset(e) { | |
_fireCallback(callback, e, combo); | |
// we should ignore the next key up if the action is key down | |
// or keypress. this is so if you finish a sequence and | |
// release the key the final key will not trigger a keyup | |
if (action !== 'keyup') { | |
_ignoreNextKeyup = _characterFromEvent(e); | |
} | |
// weird race condition if a sequence ends with the key | |
// another sequence begins with | |
setTimeout(_resetSequences, 10); | |
} | |
// loop through keys one at a time and bind the appropriate callback | |
// function. for any key leading up to the final one it should | |
// increase the sequence. after the final, it should reset all sequences | |
// | |
// if an action is specified in the original bind call then that will | |
// be used throughout. otherwise we will pass the action that the | |
// next key in the sequence should match. this allows a sequence | |
// to mix and match keypress and keydown events depending on which | |
// ones are better suited to the key provided | |
for (var i = 0; i < keys.length; ++i) { | |
var isFinal = i + 1 === keys.length; | |
var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action); | |
_bindSingle(keys[i], wrappedCallback, action, combo, i); | |
} | |
} | |
/** | |
* Converts from a string key combination to an array | |
* | |
* @param {string} combination like "command+shift+l" | |
* @return {Array} | |
*/ | |
function _keysFromString(combination) { | |
if (combination === '+') { | |
return ['+']; | |
} | |
return combination.split('+'); | |
} | |
/** | |
* Gets info for a specific key combination | |
* | |
* @param {string} combination key combination ("command+s" or "a" or "*") | |
* @param {string=} action | |
* @returns {Object} | |
*/ | |
function _getKeyInfo(combination, action) { | |
var keys, | |
key, | |
i, | |
modifiers = []; | |
// take the keys from this pattern and figure out what the actual | |
// pattern is all about | |
keys = _keysFromString(combination); | |
for (i = 0; i < keys.length; ++i) { | |
key = keys[i]; | |
// normalize key names | |
if (_SPECIAL_ALIASES[key]) { | |
key = _SPECIAL_ALIASES[key]; | |
} | |
// if this is not a keypress event then we should | |
// be smart about using shift keys | |
// this will only work for US keyboards however | |
if (action && action != 'keypress' && _SHIFT_MAP[key]) { | |
key = _SHIFT_MAP[key]; | |
modifiers.push('shift'); | |
} | |
// if this key is a modifier then add it to the list of modifiers | |
if (_isModifier(key)) { | |
modifiers.push(key); | |
} | |
} | |
// depending on what the key combination is | |
// we will try to pick the best event for it | |
action = _pickBestAction(key, modifiers, action); | |
return { | |
key: key, | |
modifiers: modifiers, | |
action: action | |
}; | |
} | |
/** | |
* binds a single keyboard combination | |
* | |
* @param {string} combination | |
* @param {Function} callback | |
* @param {string=} action | |
* @param {string=} sequenceName - name of sequence if part of sequence | |
* @param {number=} level - what part of the sequence the command is | |
* @returns void | |
*/ | |
function _bindSingle(combination, callback, action, sequenceName, level) { | |
// store a direct mapped reference for use with Mousetrap.trigger | |
_directMap[combination + ':' + action] = callback; | |
// make sure multiple spaces in a row become a single space | |
combination = combination.replace(/\s+/g, ' '); | |
var sequence = combination.split(' '), | |
info; | |
// if this pattern is a sequence of keys then run through this method | |
// to reprocess each pattern one key at a time | |
if (sequence.length > 1) { | |
_bindSequence(combination, sequence, callback, action); | |
return; | |
} | |
info = _getKeyInfo(combination, action); | |
// make sure to initialize array if this is the first time | |
// a callback is added for this key | |
_callbacks[info.key] = _callbacks[info.key] || []; | |
// remove an existing match if there is one | |
_getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level); | |
// add this call back to the array | |
// if it is a sequence put it at the beginning | |
// if not put it at the end | |
// | |
// this is important because the way these are processed expects | |
// the sequence ones to come first | |
_callbacks[info.key][sequenceName ? 'unshift' : 'push']({ | |
callback: callback, | |
modifiers: info.modifiers, | |
action: info.action, | |
seq: sequenceName, | |
level: level, | |
combo: combination | |
}); | |
} | |
/** | |
* binds multiple combinations to the same callback | |
* | |
* @param {Array} combinations | |
* @param {Function} callback | |
* @param {string|undefined} action | |
* @returns void | |
*/ | |
function _bindMultiple(combinations, callback, action) { | |
for (var i = 0; i < combinations.length; ++i) { | |
_bindSingle(combinations[i], callback, action); | |
} | |
} | |
// start! | |
_addEvent(document, 'keypress', _handleKeyEvent); | |
_addEvent(document, 'keydown', _handleKeyEvent); | |
_addEvent(document, 'keyup', _handleKeyEvent); | |
var Mousetrap = { | |
/** | |
* binds an event to mousetrap | |
* | |
* can be a single key, a combination of keys separated with +, | |
* an array of keys, or a sequence of keys separated by spaces | |
* | |
* be sure to list the modifier keys first to make sure that the | |
* correct key ends up getting bound (the last key in the pattern) | |
* | |
* @param {string|Array} keys | |
* @param {Function} callback | |
* @param {string=} action - 'keypress', 'keydown', or 'keyup' | |
* @returns void | |
*/ | |
bind: function(keys, callback, action) { | |
keys = keys instanceof Array ? keys : [keys]; | |
_bindMultiple(keys, callback, action); | |
return this; | |
}, | |
/** | |
* unbinds an event to mousetrap | |
* | |
* the unbinding sets the callback function of the specified key combo | |
* to an empty function and deletes the corresponding key in the | |
* _directMap dict. | |
* | |
* TODO: actually remove this from the _callbacks dictionary instead | |
* of binding an empty function | |
* | |
* the keycombo+action has to be exactly the same as | |
* it was defined in the bind method | |
* | |
* @param {string|Array} keys | |
* @param {string} action | |
* @returns void | |
*/ | |
unbind: function(keys, action) { | |
return Mousetrap.bind(keys, function() {}, action); | |
}, | |
/** | |
* triggers an event that has already been bound | |
* | |
* @param {string} keys | |
* @param {string=} action | |
* @returns void | |
*/ | |
trigger: function(keys, action) { | |
if (_directMap[keys + ':' + action]) { | |
_directMap[keys + ':' + action]({}, keys); | |
} | |
return this; | |
}, | |
/** | |
* resets the library back to its initial state. this is useful | |
* if you want to clear out the current keyboard shortcuts and bind | |
* new ones - for example if you switch to another page | |
* | |
* @returns void | |
*/ | |
reset: function() { | |
_callbacks = {}; | |
_directMap = {}; | |
return this; | |
}, | |
/** | |
* should we stop this event before firing off callbacks | |
* | |
* @param {Event} e | |
* @param {Element} element | |
* @return {boolean} | |
*/ | |
stopCallback: function(e, element) { | |
// if the element has the class "mousetrap" then no need to stop | |
if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { | |
return false; | |
} | |
// stop for input, select, and textarea | |
return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable; | |
}, | |
/** | |
* exposes _handleKey publicly so it can be overwritten by extensions | |
*/ | |
handleKey: _handleKey | |
}; | |
// expose mousetrap to the global object | |
window.Mousetrap = Mousetrap; | |
// expose mousetrap as an AMD module | |
if (typeof define === 'function' && define.amd) { | |
define(Mousetrap); | |
} | |
}) (window, document); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#body { | |
background: white; | |
margin: 0; | |
font-size: 14px; | |
font-family: "Helvetica Neue", Helvetica; | |
} | |
#chart { | |
position: absolute; | |
top: 0; | |
} | |
rect { | |
fill: none; | |
pointer-events: all; | |
} | |
pre { | |
font-size: 18px; | |
} | |
line { | |
stroke: #000; | |
stroke-width: 1.5px; | |
} | |
.string, .regexp { | |
color: #f39; | |
} | |
.keyword { | |
color: #00c; | |
} | |
.comment { | |
color: #777; | |
font-style: oblique; | |
} | |
.number { | |
color: #369; | |
} | |
.class, .special { | |
color: #1181B8; | |
} | |
a:link, a:visited { | |
color: #000; | |
text-decoration: none; | |
} | |
a:hover { | |
color: #666; | |
} | |
.hint { | |
position: absolute; | |
right: 0; | |
width: 1280px; | |
font-size: 12px; | |
color: #999; | |
} | |
#toolbar{ | |
position: fixed; | |
top: 0; | |
left: 0; | |
width: 100%; | |
} | |
#footer{ | |
position: fixed; | |
bottom: 0; | |
left: 0; | |
width: 100%; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<map version="1.0.1"> | |
<!-- To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net --> | |
<node CREATED="1400771016814" ID="ID_1425716387" MODIFIED="1400771026053" TEXT="Mindmap"> | |
<node CREATED="1400771027265" ID="ID_846682469" MODIFIED="1400771029816" POSITION="right" TEXT="From Freemind"> | |
<node CREATED="1400771032900" ID="ID_827918588" MODIFIED="1400771037791" TEXT="Stored as .mm"/> | |
<node CREATED="1400771038772" ID="ID_1158944789" MODIFIED="1400771044688" TEXT="Really its an xml file"/> | |
</node> | |
<node CREATED="1400771048651" ID="ID_895287109" MODIFIED="1400771056767" POSITION="left" TEXT="Just the basics"> | |
<node CREATED="1400771105555" ID="ID_420969231" MODIFIED="1400771114341" TEXT="bold"> | |
<font BOLD="true" NAME="SansSerif" SIZE="12"/> | |
</node> | |
<node CREATED="1400771107260" ID="ID_1006485332" MODIFIED="1400771115614" TEXT="italic"> | |
<font ITALIC="true" NAME="SansSerif" SIZE="12"/> | |
</node> | |
<node CREATED="1400771116050" ID="ID_660540640" MODIFIED="1400771123415" TEXT="Cloud"> | |
<cloud/> | |
</node> | |
</node> | |
<node CREATED="1400771057531" ID="ID_1127763371" MODIFIED="1400771066263" POSITION="left" TEXT="Maybe a few icons"> | |
<node CREATED="1400771067555" ID="ID_850944552" MODIFIED="1400771073088" TEXT="1"> | |
<icon BUILTIN="full-1"/> | |
</node> | |
<node CREATED="1400771074490" ID="ID_1208594920" MODIFIED="1400771080110" TEXT="2"> | |
<icon BUILTIN="full-2"/> | |
</node> | |
<node CREATED="1400771076659" ID="ID_1278721112" MODIFIED="1400771082280" TEXT="3"> | |
<icon BUILTIN="full-3"/> | |
</node> | |
<node CREATED="1400771089739" ID="ID_544883255" MODIFIED="1400771093502" TEXT="idea"> | |
<icon BUILTIN="idea"/> | |
</node> | |
</node> | |
<node CREATED="1400771143034" ID="ID_1094518542" MODIFIED="1400771185233" POSITION="right" STYLE="fork" TEXT="Large text"> | |
<font NAME="SansSerif" SIZE="19"/> | |
</node> | |
<node CREATED="1400771186530" ID="ID_25862265" MODIFIED="1400771223153" POSITION="right" STYLE="fork" TEXT="Outline Formats"> | |
<node CREATED="1400771197723" ID="ID_514062041" MODIFIED="1400771223153" STYLE="bubble" TEXT="Bubble"/> | |
<node CREATED="1400771199834" ID="ID_1161671026" MODIFIED="1400771223153" STYLE="fork" TEXT="Fork"/> | |
</node> | |
</node> | |
</map> |
Cool, thanks
Awesome! very good job! keep to enrich more! I'll support you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks really useful- are you ok with reuse/what license are you intending to use for this?