-
Notifications
You must be signed in to change notification settings - Fork 34
/
json-tree.js
508 lines (436 loc) · 25.6 KB
/
json-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/**************************************************************************
* JSON-tree, v0.1.5; MIT License
* http://krispo.github.io/json-tree
**************************************************************************/
(function(){
'use strict';
angular.module('json-tree', [])
.constant('jsonTreeConfig', {
templateUrl: null
})
.directive('jsonTree', ['$compile', '$q', '$http', '$templateCache', 'jsonTreeConfig', function($compile, $q, $http, $templateCache, jsonTreeConfig) {
var template =
'<span ng-bind="utils.wrap.start(node)"></span>' +
'<span ng-bind="node.isCollapsed ? utils.wrap.middle(node) : \' \'" ng-click="utils.clickNode(node)"></span>' +
'<ul ng-if="!node.isCollapsed">' +
'<li ng-repeat="key in utils.keys(json) track by key">' +
'<div draggable>' +
'<span class="key" ng-click="utils.clickNode(childs[key])" >{{ key }}: </span>' +
'<span ng-hide="childs[key].isObject()">' +
'<input ng-if="childs[key].type() === \'boolean\'" type="checkbox" ng-model="json[key]"/>' +
'<input ng-if="childs[key].type() === \'number\'" type="number" ng-model="json[key]"/>' +
'<textarea ng-if="childs[key].type() === \'function\'" ng-model="jsonFn[key]" ng-init="utils.textarea.init(key)" ng-change="utils.textarea.onChange(key)" ng-focus="utils.textarea.onFocus($event, key)" ng-blur="utils.textarea.onBlur(key)"></textarea>' +
'<input ng-if="childs[key].type() !== \'number\' && childs[key].type() !== \'function\'" type="text" ng-model="json[key]" ng-change="utils.validateNode(key)" placeholder="null"/>' +
'</span>' +
'<json-tree json="json[key]" edit-level="{{editLevel}}" collapsed-level="{{+collapsedLevel - 1}}" node="childs[key]" timeout="{{timeout}}" ng-show="childs[key].isObject()"></json-tree>' +
'<span class="reset" ng-dblclick="utils.resetNode(key)" ng-show="node.isHighEditLevel"> ~ </span>' +
'<span class="remove" ng-dblclick="utils.removeNode(key)" ng-show="node.isHighEditLevel">-</span>' +
'<span class="comma" ng-hide="utils.wrap.isLastIndex(node, $index + 1)">,</span>' +
'</div>' +
'</li>' +
'</ul>' +
'<span ng-bind="utils.wrap.end(node)"></span>' +
'<span class="add" ng-show="node.isHighEditLevel && node.isObject()" ng-click="addTpl = !addTpl; inputKey = null; inputValue = null"> + </span>' +
'<span class="add-item-block" ng-show="(addTpl && node.isHighEditLevel) || false">' +
'<span class="add-item-label" ng-show="node.type() === \'object\'">'+
'<input class="add-item-input-key" type="text" ng-model="inputKey" placeholder="key"/>: '+
'<input class="add-item-input-value" type="text" ng-model="inputValue" placeholder="value"/>'+
'</span>' +
'<span class="add-item-preview" ng-show="node.type() === \'array\'">'+
'<input class="add-value-preview-input" type="text" ng-model="inputValue" placeholder="value"/>'+
'</span>' +
'<button class="add-item-btn-add" ng-click="utils.addNode(inputKey, inputValue); addTpl = false">+</button>'+
'<button class="add-item-btn-cancel" ng-click="addTpl = false">c</button>' +
'</span>';
function getTemplatePromise() {
if(jsonTreeConfig.templateUrl) return $http.get(jsonTreeConfig.templateUrl, {
cache: $templateCache
}).then(function (result) {
return result.data;
});
return $q.when(template);
}
return {
restrict: 'EA',
scope: {
json: '=',
node: '=?',
childs: '=?',
editLevel: '@',
collapsedLevel: '@',
timeout: '@',
timeoutInit: '@'
},
controller: ['$scope', function($scope){
/* initialize container for child nodes */
$scope.childs = {};
/* initialize container for nodes with functions */
$scope.jsonFn = {};
/* define auxiliary functions */
$scope.utils = {
/* prettify json view */
wrap: {
start: function(node){
if (node === undefined || node === null) return '';
switch (node.type()){
case 'array': return '[';
case 'object': return '{';
default: return '';
}
},
middle: function(node){
if (node === undefined || node === null) return '';
switch (node.type()){
case 'array': return '...';
case 'object': return '...';
default: return '';
}
},
end: function(node){
if (node === undefined || node === null) return '';
switch (node.type()){
case 'array': return ']';
case 'object': return '}';
default: return '';
}
},
isLastIndex: function(node, index){
if (node === undefined || node === null) return true;
else return index >= node.length();
}
},
/* collapse/expand node by clicking */
clickNode: function(node){
node.isCollapsed = !node.isCollapsed;
},
/* add new node to the collection */
addNode: function(key, value){
var json = null;
try { json = JSON.parse(value); } catch (e){} //try get json
if (json === null) json = $scope.utils.tryGetFunction(value) || json; //try get function
/* add element to the object */
if ($scope.node.type() === 'object') {
if (json !== null){
$scope.json[key] = json
} else {
$scope.json[key] = value
}
}
/* add element(s) to the array */
else if ($scope.node.type() === 'array') {
if (json !== null) {
if (json.constructor === Array){
/* push new array elements to the array */
$scope.json.push.apply($scope.json, json);
} else {
/* push single element to the array */
$scope.json.push(json);
}
} else {
$scope.json.push(value);
}
}
$scope.refresh();
},
/* reset node value by key to default == null */
resetNode: function(key){
$scope.json[key] = null;
$scope.refresh();
},
/* remove node by key from json */
removeNode: function(key){
if ($scope.node.type() === 'object')
delete $scope.json[key];
else if ($scope.node.type() === 'array')
$scope.json.splice(key, 1);
$scope.refresh();
},
/* validate text if input to the form */
validateNode: function(key){
/* check if null */
if ($scope.json[key] === null);
/* check if undefined or "" */
else if ($scope.json[key] === undefined || $scope.json[key] === '') $scope.json[key] = null;
/* try to convert string to number */
else if (!isNaN(+$scope.json[key]) && isFinite($scope.json[key]))
$scope.json[key] = +$scope.json[key];
/* try parse to function */
else if ($scope.utils.tryGetFunction($scope.json[key])){
$scope.json[key] = $scope.utils.tryGetFunction($scope.json[key]);
$scope.utils.textarea.init(key);
}
/* try to parse string to json */
else {
if ($scope.node.isHighEditLevel){ /* if high editable level */
try {
var json = JSON.parse($scope.json[key]);
$scope.json[key] = json;
$scope.refresh();
} catch (e){}
} else { /* if low editable level */
/* check if boolean input -> then refresh */
if ($scope.json[key] === "true" || $scope.json[key] === "false") {
$scope.json[key] = JSON.parse($scope.json[key]);
$scope.refresh();
}
}
}
},
/* move node from position with index 'i' to position with index 'j' */
moveNode: function(i, j){
/* moving for object */
if ($scope.node.type() === 'object'){
var json = {},
keys = Object.keys($scope.json),
key1 = keys[i],
key2 = keys[j];
angular.forEach($scope.json, function(value, key){
if (key == key2) {
if (j > i){
json[key2] = $scope.json[key2];
json[key1] = $scope.json[key1];
} else {
json[key1] = $scope.json[key1];
json[key2] = $scope.json[key2];
}
}
else if (key != key1) json[key] = value;
});
$scope.json = json;
}
/* moving for array */
else if ($scope.node.type() === 'array'){
var temp = $scope.json[i];
$scope.json.splice(i, 1);
$scope.json.splice(j, 0, temp);
$scope.$apply($scope.refresh());
}
},
/* handle textarea fith functions */
textarea: {
/* define function value for textarea */
init: function(key){
if ($scope.json[key] !== null) $scope.jsonFn[key] = $scope.json[key].toString().trim();
},
/* validate if element value is function */
validate: function(key){
var func = $scope.utils.tryGetFunction($scope.jsonFn[key]);
func
? angular.element($scope.utils.textarea.element).removeClass('invalid').addClass('valid')
: angular.element($scope.utils.textarea.element).removeClass('valid').addClass('invalid');
},
/* onFocus event handler */
onFocus: function(e, key){
$scope.utils.textarea['valueBeforeEditing'] = angular.copy($scope.jsonFn[key]); //keep value before editing
$scope.utils.textarea['element'] = e.currentTarget;
$scope.utils.textarea.validate(key);
},
/* onChange event handler */
onChange: function(key){
$scope.utils.textarea.validate(key);
},
/* onBlur event handler */
onBlur: function(key){
//handle only if the field has been changed
if ($scope.utils.textarea.valueBeforeEditing !== $scope.jsonFn[key]) {
$scope.$emit('onFunctionChanged'); //emit onFunctionChange event if the function definition was changed.
var func = $scope.utils.tryGetFunction($scope.jsonFn[key]);
if (func) $scope.json[key] = func;
else { //if value is not a valid function
$scope.json[key] = $scope.jsonFn[key];
delete $scope.jsonFn[key];
$scope.utils.validateNode(key); //full validation for node
}
}
}
},
/* try to convert string to function */
/* it is important that function element MUST start with 'function' keyword */
tryGetFunction: function(str){
if (str.trim().substring(0, 8) === 'function'){
try {
var func = eval( '(' + str.trim() + ')' );
return func;
} catch(e){}
}
},
/* to skip ordering in ng-repeat */
keys: function(obj){
return (obj instanceof Object) ? Object.keys(obj) : [];
},
/* get type for variable val */
getType: function(val){
if (val === null) return 'null';
else if (val === undefined) return 'undefined';
else if (val.constructor === Array) return 'array';
else if (val.constructor === Object) return 'object';
else if (val.constructor === String) return 'string';
else if (val.constructor === Number) return 'number';
else if (val.constructor === Boolean) return 'boolean';
else if (val.constructor === Function) return 'function';
else return 'object'
}
};
/* define properties of the current node */
$scope.node = {
/* check node is collapsed */
isCollapsed: ($scope.collapsedLevel && +$scope.collapsedLevel) ? (+$scope.collapsedLevel <= 0) : true, /* set up isCollapsed properties, by default - true */
/* check editing level is high */
isHighEditLevel: $scope.editLevel !== "low",
/* if childs[key] is dragging now, dragChildKey matches to key */
dragChildKey: null,
/* used to get info such as coordinates (top, left, height, width, meanY) of draggable elements by key */
dragElements: {},
/* check current node is object or array */
isObject: function(){
return angular.isObject($scope.json)
},
/* get type for current node */
type: function(){
return $scope.utils.getType($scope.json);
},
/* calculate collection length for object or array */
length: function(){
return ($scope.json instanceof Object) ? (Object.keys($scope.json).length) : 1
},
/* refresh template view */
refresh: function(){
$scope.refresh();
}
};
}],
link: function(scope, element, attrs){
/* define child scope and template */
var childScope = scope.$new(),
templatePromise = getTemplatePromise();
/* define build template function */
scope.build = function(_scope){
if (scope.node.isObject()){
templatePromise.then(function(tpl) {
element.html('').append($compile(tpl)(_scope));
});
}
};
/* define refresh function */
scope.refresh = function(){
childScope.$destroy();
childScope = scope.$new();
scope.build(childScope);
};
// build template view
if (scope.timeoutInit) {
setTimeout(function(){
scope.build(childScope);
},scope.timeoutInit);
} else if (scope.timeout && +scope.timeout>=0) {
setTimeout(function(){
scope.build(childScope);
},scope.timeout);
} else {
scope.build(childScope);
}
}
}
}])
.directive('draggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
var startX, startY, deltaX, deltaY, emptyElement, keys, index;
/* Save information of the current draggable element to the parent json-tree scope.
* This would be done under initialization */
scope.node.dragElements[scope.key] = function(){
return element;
};
element.on('mousedown', function(event) {
/* Check if pressed Ctrl or Shift */
if (event.ctrlKey || event.shiftKey) {
scope.node.dragChildKey = scope.key; // tell parent scope what child element is draggable now
var rect = getRectangle(scope.node.dragElements[scope.key]()[0]);
/* If child element is not draggable, than make the current element draggable */
if (scope.childs[scope.key].dragChildKey == null) {
// Prevent default dragging of selected content
event.preventDefault();
startX = rect.left;
startY = rect.top;
deltaX = event.pageX - startX;
deltaY = event.pageY - startY;
/* Draggable element should have 'absolute' position style parameter */
element.addClass('drag');
element.css({
width: rect.width + 'px'
});
setPosition(startX, startY);
/* Add an empty element to fill the hole */
emptyElement = angular.element("<div class='empty'></div>");
emptyElement.css({
height: (rect.height - 2) + 'px',
width: (rect.width - 2) + 'px'
});
element.after(emptyElement);
/* Auxiliary array of json keys to retain the order of the current key's positions */
keys = Object.keys(scope.json);
index = scope.$index;
/* Subscribe on document mouse events */
$document.on('mousemove', mousemoveEventHandler);
$document.on('mouseup', mouseupEventHandler);
}
}
});
element.on('mouseup', function(event){
/* tell parent scope that the current element with his children are now not draggable */
scope.node.dragChildKey = null;
});
function mousemoveEventHandler(event) {
var rect = getRectangle(scope.node.dragElements[scope.key]()[0]),
meanBefore, meanAfter;
if (index >= keys.length - 1) meanAfter = Infinity;
else meanAfter = getRectangle(scope.node.dragElements[keys[index + 1]]()[0]).meanY;
if (index <= 0) meanBefore = -Infinity;
else meanBefore = getRectangle(scope.node.dragElements[keys[index - 1]]()[0]).meanY;
/* Check the criterion for swapping two sibling nodes */
if (rect.top + rect.height > meanAfter + 1) {
swapKeys(index, index + 1);
scope.node.dragElements[keys[index]]().parent().append(emptyElement);
index += 1;
}
else if (rect.top < meanBefore - 1){
swapKeys(index, index - 1);
scope.node.dragElements[keys[index]]().parent().prepend(emptyElement);
index -= 1;
}
setPosition(startX, event.pageY - deltaY)
}
function mouseupEventHandler() {
/* Fix position and update json and tree view */
scope.utils.moveNode(scope.$index, index);
scope.$apply();
element.removeClass('drag');
setPosition(startX, startY);
emptyElement.remove();
$document.unbind('mousemove', mousemoveEventHandler);
$document.unbind('mouseup', mouseupEventHandler);
}
function setPosition(x, y){
element.css({
top: y + 'px',
left: x + 'px'
});
}
function swapKeys(i, j){
var key = keys[i];
keys[i] = keys[j];
keys[j] = key;
}
/* Get coordinates of rectangle region for the element 'el' */
function getRectangle(el){
var box = el.getBoundingClientRect(),
top = Math.round(box.top + window.pageYOffset),
left = Math.round(box.left + window.pageXOffset),
height = typeof el.offsetHeight === 'undefined' ? 0 : el.offsetHeight,
width = typeof el.offsetWidth === 'undefined' ? 0 : el.offsetWidth;
return { top: top, left: left, height: height, width: width, meanY: top + height / 2}
}
}
}
}]);
})();