/
Node.js
4710 lines (4180 loc) · 132 KB
/
Node.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
import naturalSort from 'javascript-natural-sort'
import { createAbsoluteAnchor } from './createAbsoluteAnchor'
import { ContextMenu } from './ContextMenu'
import { appendNodeFactory } from './appendNodeFactory'
import { showMoreNodeFactory } from './showMoreNodeFactory'
import { showSortModal } from './showSortModal'
import { showTransformModal } from './showTransformModal'
import {
addClassName,
addEventListener,
debounce,
escapeUnicodeChars,
findUniqueName,
getAbsoluteLeft,
getAbsoluteTop,
getInnerText,
getType,
isTimestamp,
isUrl,
isValidColor,
makeFieldTooltip,
parse,
parsePath,
parseString,
removeAllClassNames,
removeClassName,
removeEventListener,
selectContentEditable,
setEndOfContentEditable,
stripFormatting,
textDiff
} from './util'
import { translate } from './i18n'
import { DEFAULT_MODAL_ANCHOR } from './constants'
/**
* @constructor Node
* Create a new Node
* @param {./treemode} editor
* @param {Object} [params] Can contain parameters:
* {string} field
* {boolean} fieldEditable
* {*} value
* {String} type Can have values 'auto', 'array',
* 'object', or 'string'.
*/
export class Node {
constructor (editor, params) {
/** @type {./treemode} */
this.editor = editor
this.dom = {}
this.expanded = false
if (params && (params instanceof Object)) {
this.setField(params.field, params.fieldEditable)
if ('value' in params) {
this.setValue(params.value, params.type)
}
if ('internalValue' in params) {
this.setInternalValue(params.internalValue)
}
} else {
this.setField('')
this.setValue(null)
}
this._debouncedOnChangeValue = debounce(this._onChangeValue.bind(this), Node.prototype.DEBOUNCE_INTERVAL)
this._debouncedOnChangeField = debounce(this._onChangeField.bind(this), Node.prototype.DEBOUNCE_INTERVAL)
// starting value for visible children
this.visibleChilds = this.getMaxVisibleChilds()
}
getMaxVisibleChilds () {
return (this.editor && this.editor.options && this.editor.options.maxVisibleChilds)
? this.editor.options.maxVisibleChilds
: DEFAULT_MAX_VISIBLE_CHILDS
}
/**
* Determine whether the field and/or value of this node are editable
* @private
*/
_updateEditability () {
this.editable = {
field: true,
value: true
}
if (this.editor) {
this.editable.field = this.editor.options.mode === 'tree'
this.editable.value = this.editor.options.mode !== 'view'
if ((this.editor.options.mode === 'tree' || this.editor.options.mode === 'form') &&
(typeof this.editor.options.onEditable === 'function')) {
const editable = this.editor.options.onEditable({
field: this.field,
value: this.value,
path: this.getPath()
})
if (typeof editable === 'boolean') {
this.editable.field = editable
this.editable.value = editable
} else if (typeof editable === 'object' && editable !== null) {
if (typeof editable.field === 'boolean') this.editable.field = editable.field
if (typeof editable.value === 'boolean') this.editable.value = editable.value
} else {
console.error(
'Invalid return value for function onEditable.',
'Actual value:', editable, '.',
'Either a boolean or object { field: boolean, value: boolean } expected.')
this.editable.field = false
this.editable.value = false
}
}
}
}
/**
* Get the path of this node
* @return {{string|number}[]} Array containing the path to this node.
* Element is a number if is the index of an array, a string otherwise.
*/
getPath () {
let node = this
const path = []
while (node) {
const field = node.getName()
if (field !== undefined) {
path.unshift(field)
}
node = node.parent
}
return path
}
/**
* Get the internal path of this node, a list with the child indexes.
* @return {String[]} Array containing the internal path to this node
*/
getInternalPath () {
let node = this
const internalPath = []
while (node) {
if (node.parent) {
internalPath.unshift(node.getIndex())
}
node = node.parent
}
return internalPath
}
/**
* Get node serializable name
* @returns {String|Number}
*/
getName () {
return !this.parent
? undefined // do not add an (optional) field name of the root node
: (this.parent.type !== 'array')
? this.field
: this.index
}
/**
* Find child node by serializable path
* @param {Array<String>} path
*/
findNodeByPath (path) {
if (!path) {
return
}
if (path.length === 0) {
return this
}
if (path.length && this.childs && this.childs.length) {
for (let i = 0; i < this.childs.length; ++i) {
if (('' + path[0]) === ('' + this.childs[i].getName())) {
return this.childs[i].findNodeByPath(path.slice(1))
}
}
}
}
/**
* Find child node by an internal path: the indexes of the childs nodes
* @param {Array<String>} internalPath
* @return {Node | undefined} Returns the node if the path exists.
* Returns undefined otherwise.
*/
findNodeByInternalPath (internalPath) {
if (!internalPath) {
return undefined
}
let node = this
for (let i = 0; i < internalPath.length && node; i++) {
const childIndex = internalPath[i]
node = node.childs[childIndex]
}
return node
}
/**
* @typedef {{value: String|Object|Number|Boolean, path: Array.<String|Number>}} SerializableNode
*
* Returns serializable representation for the node
* @return {SerializableNode}
*/
serialize () {
return {
value: this.getValue(),
path: this.getPath()
}
}
/**
* Find a Node from a JSON path like '.items[3].name'
* @param {string} jsonPath
* @return {Node | null} Returns the Node when found, returns null if not found
*/
findNode (jsonPath) {
const path = parsePath(jsonPath)
let node = this
while (node && path.length > 0) {
const prop = path.shift()
if (typeof prop === 'number') {
if (node.type !== 'array') {
throw new Error('Cannot get child node at index ' + prop + ': node is no array')
}
node = node.childs[prop]
} else { // string
if (node.type !== 'object') {
throw new Error('Cannot get child node ' + prop + ': node is no object')
}
node = node.childs.filter(child => child.field === prop)[0]
}
}
return node
}
/**
* Find all parents of this node. The parents are ordered from root node towards
* the original node.
* @return {Array.<Node>}
*/
findParents () {
const parents = []
let parent = this.parent
while (parent) {
parents.unshift(parent)
parent = parent.parent
}
return parents
}
/**
*
* @param {{dataPath: string, keyword: string, message: string, params: Object, schemaPath: string} | null} error
* @param {Node} [child] When this is the error of a parent node, pointing
* to an invalid child node, the child node itself
* can be provided. If provided, clicking the error
* icon will set focus to the invalid child node.
*/
setError (error, child) {
this.error = error
this.errorChild = child
if (this.dom && this.dom.tr) {
this.updateError()
}
}
/**
* Render the error
*/
updateError () {
const error = this.fieldError || this.valueError || this.error
let tdError = this.dom.tdError
if (error && this.dom && this.dom.tr) {
addClassName(this.dom.tr, 'jsoneditor-validation-error')
if (!tdError) {
tdError = document.createElement('td')
this.dom.tdError = tdError
this.dom.tdValue.parentNode.appendChild(tdError)
}
const button = document.createElement('button')
button.type = 'button'
button.className = 'jsoneditor-button jsoneditor-schema-error'
const destroy = () => {
if (this.dom.popupAnchor) {
this.dom.popupAnchor.destroy() // this will trigger the onDestroy callback
}
}
const onDestroy = () => {
delete this.dom.popupAnchor
}
const createPopup = (destroyOnMouseOut) => {
const frame = this.editor.frame
this.dom.popupAnchor = createAbsoluteAnchor(button, this.editor.getPopupAnchor(), onDestroy, destroyOnMouseOut)
const popupWidth = 200 // must correspond to what's configured in the CSS
const buttonRect = button.getBoundingClientRect()
const frameRect = frame.getBoundingClientRect()
const position = (frameRect.width - buttonRect.x > (popupWidth / 2 + 20))
? 'jsoneditor-above'
: 'jsoneditor-left'
const popover = document.createElement('div')
popover.className = 'jsoneditor-popover ' + position
popover.appendChild(document.createTextNode(error.message))
this.dom.popupAnchor.appendChild(popover)
}
button.onmouseover = () => {
if (!this.dom.popupAnchor) {
createPopup(true)
}
}
button.onfocus = () => {
destroy()
createPopup(false)
}
button.onblur = () => {
destroy()
}
// when clicking the error icon, expand all nodes towards the invalid
// child node, and set focus to the child node
const child = this.errorChild
if (child) {
button.onclick = function showInvalidNode () {
child.findParents().forEach(parent => {
parent.expand(false)
})
child.scrollTo(() => {
child.focus()
})
}
}
// apply the error message to the node
while (tdError.firstChild) {
tdError.removeChild(tdError.firstChild)
}
tdError.appendChild(button)
} else {
if (this.dom.tr) {
removeClassName(this.dom.tr, 'jsoneditor-validation-error')
}
if (tdError) {
this.dom.tdError.parentNode.removeChild(this.dom.tdError)
delete this.dom.tdError
}
}
}
/**
* Get the index of this node: the index in the list of childs where this
* node is part of
* @return {number | null} Returns the index, or null if this is the root node
*/
getIndex () {
if (this.parent) {
const index = this.parent.childs.indexOf(this)
return index !== -1 ? index : null
} else {
return -1
}
}
/**
* Set parent node
* @param {Node} parent
*/
setParent (parent) {
this.parent = parent
}
/**
* Set field
* @param {String} field
* @param {boolean} [fieldEditable]
*/
setField (field, fieldEditable) {
this.field = field
this.previousField = field
this.fieldEditable = (fieldEditable === true)
}
/**
* Get field
* @return {String}
*/
getField () {
if (this.field === undefined) {
this._getDomField()
}
return this.field
}
/**
* Set value. Value is a JSON structure or an element String, Boolean, etc.
* @param {*} value
* @param {String} [type] Specify the type of the value. Can be 'auto',
* 'array', 'object', or 'string'
*/
setValue (value, type) {
let childValue, child
let i, j
const updateDom = false
const previousChilds = this.childs
this.type = this._getType(value)
// check if type corresponds with the provided type
if (type && type !== this.type) {
if (type === 'string' && this.type === 'auto') {
this.type = type
} else {
throw new Error('Type mismatch: ' +
'cannot cast value of type "' + this.type +
' to the specified type "' + type + '"')
}
}
if (this.type === 'array') {
// array
if (!this.childs) {
this.childs = []
}
for (i = 0; i < value.length; i++) {
childValue = value[i]
if (childValue !== undefined && !(childValue instanceof Function)) {
if (i < this.childs.length) {
// reuse existing child, keep its state
child = this.childs[i]
child.fieldEditable = false
child.index = i
child.setValue(childValue)
} else {
// create a new child
child = new Node(this.editor, {
value: childValue
})
const visible = i < this.getMaxVisibleChilds()
this.appendChild(child, visible, updateDom)
}
}
}
// cleanup redundant childs
// we loop backward to prevent issues with shifting index numbers
for (j = this.childs.length; j >= value.length; j--) {
this.removeChild(this.childs[j], updateDom)
}
} else if (this.type === 'object') {
// object
if (!this.childs) {
this.childs = []
}
// cleanup redundant childs
// we loop backward to prevent issues with shifting index numbers
for (j = this.childs.length - 1; j >= 0; j--) {
if (!hasOwnProperty(value, this.childs[j].field)) {
this.removeChild(this.childs[j], updateDom)
}
}
i = 0
for (const childField in value) {
if (hasOwnProperty(value, childField)) {
childValue = value[childField]
if (childValue !== undefined && !(childValue instanceof Function)) {
const child = this.findChildByProperty(childField)
if (child) {
// reuse existing child, keep its state
child.setField(childField, true)
child.setValue(childValue)
} else {
// create a new child, append to the end
const newChild = new Node(this.editor, {
field: childField,
value: childValue
})
const visible = i < this.getMaxVisibleChilds()
this.appendChild(newChild, visible, updateDom)
}
}
i++
}
}
this.value = ''
// sort object keys during initialization. Must not trigger an onChange action
if (this.editor.options.sortObjectKeys === true) {
const triggerAction = false
this.sort([], 'asc', triggerAction)
}
} else {
// value
this.hideChilds()
delete this.append
delete this.showMore
delete this.expanded
delete this.childs
this.value = value
}
// recreate the DOM if switching from an object/array to auto/string or vice versa
// needed to recreated the expand button for example
if (Array.isArray(previousChilds) !== Array.isArray(this.childs)) {
this.recreateDom()
}
this.updateDom({ updateIndexes: true })
this.previousValue = this.value // used only to check for changes in DOM vs JS model
}
/**
* Set internal value
* @param {*} internalValue Internal value structure keeping type,
* order and duplicates in objects
*/
setInternalValue (internalValue) {
let childValue, child, visible
let i, j
const notUpdateDom = false
const previousChilds = this.childs
this.type = internalValue.type
if (internalValue.type === 'array') {
// array
if (!this.childs) {
this.childs = []
}
for (i = 0; i < internalValue.childs.length; i++) {
childValue = internalValue.childs[i]
if (childValue !== undefined && !(childValue instanceof Function)) {
if (i < this.childs.length) {
// reuse existing child, keep its state
child = this.childs[i]
child.fieldEditable = false
child.index = i
child.setInternalValue(childValue)
} else {
// create a new child
child = new Node(this.editor, {
internalValue: childValue
})
visible = i < this.getMaxVisibleChilds()
this.appendChild(child, visible, notUpdateDom)
}
}
}
// cleanup redundant childs
// we loop backward to prevent issues with shifting index numbers
for (j = this.childs.length; j >= internalValue.childs.length; j--) {
this.removeChild(this.childs[j], notUpdateDom)
}
} else if (internalValue.type === 'object') {
// object
if (!this.childs) {
this.childs = []
}
for (i = 0; i < internalValue.childs.length; i++) {
childValue = internalValue.childs[i]
if (childValue !== undefined && !(childValue instanceof Function)) {
if (i < this.childs.length) {
// reuse existing child, keep its state
child = this.childs[i]
delete child.index
child.setField(childValue.field, true)
child.setInternalValue(childValue.value)
} else {
// create a new child
child = new Node(this.editor, {
field: childValue.field,
internalValue: childValue.value
})
visible = i < this.getMaxVisibleChilds()
this.appendChild(child, visible, notUpdateDom)
}
}
}
// cleanup redundant childs
// we loop backward to prevent issues with shifting index numbers
for (j = this.childs.length; j >= internalValue.childs.length; j--) {
this.removeChild(this.childs[j], notUpdateDom)
}
} else {
// value
this.hideChilds()
delete this.append
delete this.showMore
delete this.expanded
delete this.childs
this.value = internalValue.value
}
// recreate the DOM if switching from an object/array to auto/string or vice versa
// needed to recreated the expand button for example
if (Array.isArray(previousChilds) !== Array.isArray(this.childs)) {
this.recreateDom()
}
this.updateDom({ updateIndexes: true })
this.previousValue = this.value // used only to check for changes in DOM vs JS model
}
/**
* Remove the DOM of this node and it's childs and recreate it again
*/
recreateDom () {
if (this.dom && this.dom.tr && this.dom.tr.parentNode) {
const domAnchor = this._detachFromDom()
this.clearDom()
this._attachToDom(domAnchor)
} else {
this.clearDom()
}
}
/**
* Get value. Value is a JSON structure
* @return {*} value
*/
getValue () {
if (this.type === 'array') {
const arr = []
this.childs.forEach(child => {
arr.push(child.getValue())
})
return arr
} else if (this.type === 'object') {
const obj = {}
this.childs.forEach(child => {
obj[child.getField()] = child.getValue()
})
return obj
} else {
if (this.value === undefined) {
this._getDomValue()
}
return this.value
}
}
/**
* Get internal value, a structure which maintains ordering and duplicates in objects
* @return {*} value
*/
getInternalValue () {
if (this.type === 'array') {
return {
type: this.type,
childs: this.childs.map(child => child.getInternalValue())
}
} else if (this.type === 'object') {
return {
type: this.type,
childs: this.childs.map(child => ({
field: child.getField(),
value: child.getInternalValue()
}))
}
} else {
if (this.value === undefined) {
this._getDomValue()
}
return {
type: this.type,
value: this.value
}
}
}
/**
* Get the nesting level of this node
* @return {Number} level
*/
getLevel () {
return (this.parent ? this.parent.getLevel() + 1 : 0)
}
/**
* Get jsonpath of the current node
* @return {Node[]} Returns an array with nodes
*/
getNodePath () {
const path = this.parent ? this.parent.getNodePath() : []
path.push(this)
return path
}
/**
* Create a clone of a node
* The complete state of a clone is copied, including whether it is expanded or
* not. The DOM elements are not cloned.
* @return {Node} clone
*/
clone () {
const clone = new Node(this.editor)
clone.type = this.type
clone.field = this.field
clone.fieldInnerText = this.fieldInnerText
clone.fieldEditable = this.fieldEditable
clone.previousField = this.previousField
clone.value = this.value
clone.valueInnerText = this.valueInnerText
clone.previousValue = this.previousValue
clone.expanded = this.expanded
clone.visibleChilds = this.visibleChilds
if (this.childs) {
// an object or array
const cloneChilds = []
this.childs.forEach(child => {
const childClone = child.clone()
childClone.setParent(clone)
cloneChilds.push(childClone)
})
clone.childs = cloneChilds
} else {
// a value
clone.childs = undefined
}
return clone
}
/**
* Expand this node and optionally its childs.
* @param {boolean} [recurse] Optional recursion, true by default. When
* true, all childs will be expanded recursively
*/
expand (recurse) {
if (!this.childs) {
return
}
// set this node expanded
this.expanded = true
if (this.dom.expand) {
this.dom.expand.className = 'jsoneditor-button jsoneditor-expanded'
}
this.showChilds()
if (recurse !== false) {
this.childs.forEach(child => {
child.expand(recurse)
})
}
// update the css classes of table row, and fire onClassName etc
this.updateDom({ recurse: false })
}
/**
* Collapse this node and optionally its childs.
* @param {boolean} [recurse] Optional recursion, true by default. When
* true, all childs will be collapsed recursively
*/
collapse (recurse) {
if (!this.childs) {
return
}
this.hideChilds()
// collapse childs in case of recurse
if (recurse !== false) {
this.childs.forEach(child => {
child.collapse(recurse)
})
}
// make this node collapsed
if (this.dom.expand) {
this.dom.expand.className = 'jsoneditor-button jsoneditor-collapsed'
}
this.expanded = false
// update the css classes of table row, and fire onClassName etc
this.updateDom({ recurse: false })
}
/**
* Recursively show all childs when they are expanded
*/
showChilds () {
const childs = this.childs
if (!childs) {
return
}
if (!this.expanded) {
return
}
const tr = this.dom.tr
let nextTr
const table = tr ? tr.parentNode : undefined
if (table) {
// show row with append button
const append = this.getAppendDom()
if (!append.parentNode) {
nextTr = tr.nextSibling
if (nextTr) {
table.insertBefore(append, nextTr)
} else {
table.appendChild(append)
}
}
// show childs
const iMax = Math.min(this.childs.length, this.visibleChilds)
nextTr = this._getNextTr()
for (let i = 0; i < iMax; i++) {
const child = this.childs[i]
if (!child.getDom().parentNode) {
table.insertBefore(child.getDom(), nextTr)
}
child.showChilds()
}
// show "show more childs" if limited
const showMore = this.getShowMoreDom()
nextTr = this._getNextTr()
if (!showMore.parentNode) {
table.insertBefore(showMore, nextTr)
}
this.showMore.updateDom() // to update the counter
}
}
_getNextTr () {
if (this.showMore && this.showMore.getDom().parentNode) {
return this.showMore.getDom()
}
if (this.append && this.append.getDom().parentNode) {
return this.append.getDom()
}
}
/**
* Hide the node with all its childs
* @param {{resetVisibleChilds: boolean}} [options]
*/
hide (options) {
const tr = this.dom.tr
const table = tr ? tr.parentNode : undefined
if (table) {
table.removeChild(tr)
}
if (this.dom.popupAnchor) {
this.dom.popupAnchor.destroy()
}
this.hideChilds(options)
}
/**
* Recursively hide all childs
* @param {{resetVisibleChilds: boolean}} [options]
*/
hideChilds (options) {
const childs = this.childs
if (!childs) {
return
}
if (!this.expanded) {
return
}
// hide append row
const append = this.getAppendDom()
if (append.parentNode) {
append.parentNode.removeChild(append)
}
// hide childs
this.childs.forEach(child => {
child.hide()
})
// hide "show more" row
const showMore = this.getShowMoreDom()
if (showMore.parentNode) {
showMore.parentNode.removeChild(showMore)
}
// reset max visible childs
if (!options || options.resetVisibleChilds) {
this.visibleChilds = this.getMaxVisibleChilds()
}
}
/**
* set custom css classes on a node
*/
_updateCssClassName () {
if (this.dom.field &&
this.editor &&
this.editor.options &&
typeof this.editor.options.onClassName === 'function' &&
this.dom.tree) {
removeAllClassNames(this.dom.tree)
const addClasses = this.editor.options.onClassName({ path: this.getPath(), field: this.field, value: this.value }) || ''
addClassName(this.dom.tree, 'jsoneditor-values ' + addClasses)
}
}
recursivelyUpdateCssClassesOnNodes () {
this._updateCssClassName()
if (Array.isArray(this.childs)) {
for (let i = 0; i < this.childs.length; i++) {
this.childs[i].recursivelyUpdateCssClassesOnNodes()
}
}
}
/**
* Goes through the path from the node to the root and ensures that it is expanded
*/
expandTo () {
let currentNode = this.parent
while (currentNode) {
if (!currentNode.expanded) {
currentNode.expand()
}
currentNode = currentNode.parent
}
}
/**
* Add a new child to the node.
* Only applicable when Node value is of type array or object
* @param {Node} node
* @param {boolean} [visible] If true (default), the child will be rendered
* @param {boolean} [updateDom] If true (default), the DOM of both parent
* node and appended node will be updated
* (child count, indexes)
*/
appendChild (node, visible, updateDom) {
if (this._hasChilds()) {
// adjust the link to the parent
node.setParent(this)
node.fieldEditable = (this.type === 'object')
if (this.type === 'array') {
node.index = this.childs.length
}
if (this.type === 'object' && node.field === undefined) {
// initialize field value if needed
node.setField('')
}
this.childs.push(node)
if (this.expanded && visible !== false) {
// insert into the DOM, before the appendRow
const newTr = node.getDom()
const nextTr = this._getNextTr()