forked from anthonyshort/deku
/
index.js
3068 lines (2605 loc) · 72.4 KB
/
index.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
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.deku=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _require=="function"&&_require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _require=="function"&&_require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_require,module,exports){
/**
* Module dependencies.
*/
var Emitter = _require('component-emitter')
/**
* Expose `scene`.
*/
module.exports = Application
/**
* Create a new `Application`.
*
* @param {Object} element Optional initial element
*/
function Application (element) {
if (!(this instanceof Application)) return new Application(element)
this.options = {}
this.sources = {}
this.element = element
}
/**
* Mixin `Emitter`.
*/
Emitter(Application.prototype)
/**
* Add a plugin
*
* @param {Function} plugin
*/
Application.prototype.use = function (plugin) {
plugin(this)
return this
}
/**
* Set an option
*
* @param {String} name
*/
Application.prototype.option = function (name, val) {
this.options[name] = val
return this
}
/**
* Set value used somewhere in the IO network.
*/
Application.prototype.set = function (name, data) {
this.sources[name] = data
this.emit('source', name, data)
return this
}
/**
* Mount a virtual element.
*
* @param {VirtualElement} element
*/
Application.prototype.mount = function (element) {
this.element = element
this.emit('mount', element)
return this
}
/**
* Remove the world. Unmount everything.
*/
Application.prototype.unmount = function () {
if (!this.element) return
this.element = null
this.emit('unmount')
return this
}
},{"component-emitter":10}],2:[function(_require,module,exports){
/**
* All of the events can bind to
*/
module.exports = {
onBlur: 'blur',
onChange: 'change',
onClick: 'click',
onContextMenu: 'contextmenu',
onCopy: 'copy',
onCut: 'cut',
onDoubleClick: 'dblclick',
onDrag: 'drag',
onDragEnd: 'dragend',
onDragEnter: 'dragenter',
onDragExit: 'dragexit',
onDragLeave: 'dragleave',
onDragOver: 'dragover',
onDragStart: 'dragstart',
onDrop: 'drop',
onFocus: 'focus',
onInput: 'input',
onKeyDown: 'keydown',
onKeyPress: 'keypress',
onKeyUp: 'keyup',
onMouseDown: 'mousedown',
onMouseEnter: 'mouseenter',
onMouseLeave: 'mouseleave',
onMouseMove: 'mousemove',
onMouseOut: 'mouseout',
onMouseOver: 'mouseover',
onMouseUp: 'mouseup',
onPaste: 'paste',
onScroll: 'scroll',
onSubmit: 'submit',
onTouchCancel: 'touchcancel',
onTouchEnd: 'touchend',
onTouchMove: 'touchmove',
onTouchStart: 'touchstart',
onWheel: 'wheel'
}
},{}],3:[function(_require,module,exports){
/**
* Create the application.
*/
exports.tree =
exports.scene =
exports.deku = _require('./application')
/**
* Render scenes to the DOM.
*/
if (typeof document !== 'undefined') {
exports.render = _require('./render')
}
/**
* Render scenes to a string
*/
exports.renderString = _require('./stringify')
/**
* Create virtual elements.
*/
exports.element =
exports.createElement =
exports.dom = _require('./virtual')
},{"./application":1,"./render":4,"./stringify":5,"./virtual":8}],4:[function(_require,module,exports){
/**
* Dependencies.
*/
var raf = _require('component-raf')
var Pool = _require('dom-pool')
var walk = _require('dom-walk')
var isDom = _require('is-dom')
var uid = _require('get-uid')
var keypath = _require('object-path')
var type = _require('component-type')
var utils = _require('./utils')
var svg = _require('./svg')
var events = _require('./events')
var defaults = utils.defaults
var forEach = _require('fast.js/forEach')
var assign = _require('fast.js/object/assign')
var reduce = _require('fast.js/reduce')
var isPromise = _require('is-promise')
/**
* These elements won't be pooled
*/
var avoidPooling = ['input', 'textarea', 'select', 'option'];
/**
* Expose `dom`.
*/
module.exports = render
/**
* Render an app to the DOM
*
* @param {Application} app
* @param {HTMLElement} container
* @param {Object} opts
*
* @return {Object}
*/
function render (app, container, opts) {
var frameId
var isRendering
var rootId = 'root'
var currentElement
var currentNativeElement
var connections = {}
var components = {}
var entities = {}
var pools = {}
var handlers = {}
var mountQueue = []
var children = {}
children[rootId] = {}
if (!isDom(container)) {
throw new Error('Container element must be a DOM element')
}
/**
* Rendering options. Batching is only ever really disabled
* when running tests, and pooling can be disabled if the user
* is doing something stupid with the DOM in their components.
*/
var options = defaults(assign({}, app.options || {}, opts || {}), {
pooling: true,
batching: true,
validateProps: false
})
/**
* Listen to DOM events
*/
addNativeEventListeners()
/**
* Watch for changes to the app so that we can update
* the DOM as needed.
*/
app.on('unmount', onunmount)
app.on('mount', onmount)
app.on('source', onupdate)
/**
* If the app has already mounted an element, we can just
* render that straight away.
*/
if (app.element) render()
/**
* Teardown the DOM rendering so that it stops
* rendering and everything can be garbage collected.
*/
function teardown () {
removeNativeEventListeners()
removeNativeElement()
app.off('unmount', onunmount)
app.off('mount', onmount)
app.off('source', onupdate)
}
/**
* Swap the current rendered node with a new one that is rendered
* from the new virtual element mounted on the app.
*
* @param {VirtualElement} element
*/
function onmount () {
invalidate()
}
/**
* If the app unmounts an element, we should clear out the current
* rendered element. This will remove all the entities.
*/
function onunmount () {
removeNativeElement()
currentElement = null
}
/**
* Update all components that are bound to the source
*
* @param {String} name
* @param {*} data
*/
function onupdate (name, data) {
if (!connections[name]) return;
connections[name].forEach(function(update) {
update(data)
})
}
/**
* Render and mount a component to the native dom.
*
* @param {Entity} entity
* @return {HTMLElement}
*/
function mountEntity (entity) {
register(entity)
setSources(entity)
children[entity.id] = {}
entities[entity.id] = entity
// commit initial state and props.
commit(entity)
// callback before mounting.
trigger('beforeMount', entity, [entity.context])
trigger('beforeRender', entity, [entity.context])
// render virtual element.
var virtualElement = renderEntity(entity)
// create native element.
var nativeElement = toNative(entity.id, '0', virtualElement)
entity.virtualElement = virtualElement
entity.nativeElement = nativeElement
// Fire afterRender and afterMount hooks at the end
// of the render cycle
mountQueue.push(entity.id)
return nativeElement
}
/**
* Remove a component from the native dom.
*
* @param {Entity} entity
*/
function unmountEntity (entityId) {
var entity = entities[entityId]
if (!entity) return
trigger('beforeUnmount', entity, [entity.context, entity.nativeElement])
unmountChildren(entityId)
removeAllEvents(entityId)
var componentEntities = components[entityId].entities;
delete componentEntities[entityId]
delete components[entityId]
delete entities[entityId]
delete children[entityId]
}
/**
* Render the entity and make sure it returns a node
*
* @param {Entity} entity
*
* @return {VirtualTree}
*/
function renderEntity (entity) {
var component = entity.component
if (!component.render) throw new Error('Component needs a render function')
var result = component.render(entity.context, setState(entity))
if (!result) throw new Error('Render function must return an element.')
return result
}
/**
* Whenever setState or setProps is called, we mark the entity
* as dirty in the renderer. This lets us optimize the re-rendering
* and skip components that definitely haven't changed.
*
* @param {Entity} entity
*
* @return {Function} A curried function for updating the state of an entity
*/
function setState (entity) {
return function (nextState) {
updateEntityStateAsync(entity, nextState)
}
}
/**
* Tell the app it's dirty and needs to re-render. If batching is disabled
* we can just trigger a render immediately, otherwise we'll wait until
* the next available frame.
*/
function invalidate () {
if (!options.batching) {
if (!isRendering) render()
} else {
if (!frameId) frameId = raf(render)
}
}
/**
* Update the DOM. If the update fails we stop the loop
* so we don't get errors on every frame.
*
* @api public
*/
function render () {
// If this is called synchronously we need to
// cancel any pending future updates
clearFrame()
// If the rendering from the previous frame is still going,
// we'll just wait until the next frame. Ideally renders should
// not take over 16ms to stay within a single frame, but this should
// catch it if it does.
if (isRendering) {
frameId = raf(render)
return
} else {
isRendering = true
}
// 1. If there isn't a native element rendered for the current mounted element
// then we need to create it from scratch.
// 2. If a new element has been mounted, we should diff them.
// 3. We should update check all child components for changes.
if (!currentNativeElement) {
currentElement = app.element
currentNativeElement = toNative(rootId, '0', currentElement)
if (container.children.length > 0) {
console.info('deku: The container element is not empty. These elements will be removed. Read more: http://cl.ly/b0Sr')
}
if (container === document.body) {
console.warn('deku: Using document.body is allowed but it can cause some issues. Read more: http://cl.ly/b0SC')
}
removeAllChildren(container);
container.appendChild(currentNativeElement)
} else if (currentElement !== app.element) {
currentNativeElement = patch(rootId, currentElement, app.element, currentNativeElement)
currentElement = app.element
updateChildren(rootId)
} else {
updateChildren(rootId)
}
// Call mount events on all new entities
flushMountQueue()
// Allow rendering again.
isRendering = false
}
/**
* Call hooks for all new entities that have been created in
* the last render from the bottom up.
*/
function flushMountQueue () {
var entityId
while (entityId = mountQueue.pop()) {
var entity = entities[entityId]
trigger('afterRender', entity, [entity.context, entity.nativeElement])
triggerUpdate('afterMount', entity, [entity.context, entity.nativeElement, setState(entity)])
}
}
/**
* Clear the current scheduled frame
*/
function clearFrame () {
if (!frameId) return
raf.cancel(frameId)
frameId = 0
}
/**
* Update a component.
*
* The entity is just the data object for a component instance.
*
* @param {String} id Component instance id.
*/
function updateEntity (entityId) {
var entity = entities[entityId]
setSources(entity)
if (!shouldUpdate(entity)) {
commit(entity)
return updateChildren(entityId)
}
var currentTree = entity.virtualElement
var nextProps = entity.pendingProps
var nextState = entity.pendingState
var previousState = entity.context.state
var previousProps = entity.context.props
// hook before rendering. could modify state just before the render occurs.
trigger('beforeUpdate', entity, [entity.context, nextProps, nextState])
trigger('beforeRender', entity, [entity.context])
// commit state and props.
commit(entity)
// re-render.
var nextTree = renderEntity(entity)
// if the tree is the same we can just skip this component
// but we should still check the children to see if they're dirty.
// This allows us to memoize the render function of components.
if (nextTree === currentTree) return updateChildren(entityId)
// apply new virtual tree to native dom.
entity.nativeElement = patch(entityId, currentTree, nextTree, entity.nativeElement)
entity.virtualElement = nextTree
updateChildren(entityId)
// trigger render hook
trigger('afterRender', entity, [entity.context, entity.nativeElement])
// trigger afterUpdate after all children have updated.
triggerUpdate('afterUpdate', entity, [entity.context, previousProps, previousState])
}
/**
* Update all the children of an entity.
*
* @param {String} id Component instance id.
*/
function updateChildren (entityId) {
forEach(children[entityId], function (childId) {
updateEntity(childId)
})
}
/**
* Remove all of the child entities of an entity
*
* @param {Entity} entity
*/
function unmountChildren (entityId) {
forEach(children[entityId], function (childId) {
unmountEntity(childId)
})
}
/**
* Remove the root element. If this is called synchronously we need to
* cancel any pending future updates.
*/
function removeNativeElement () {
clearFrame()
removeElement(rootId, '0', currentNativeElement)
currentNativeElement = null
}
/**
* Create a native element from a virtual element.
*
* @param {String} entityId
* @param {String} path
* @param {Object} vnode
*
* @return {HTMLDocumentFragment}
*/
function toNative (entityId, path, vnode) {
switch (vnode.type) {
case 'text': return toNativeText(vnode)
case 'element': return toNativeElement(entityId, path, vnode)
case 'component': return toNativeComponent(entityId, path, vnode)
}
}
/**
* Create a native text element from a virtual element.
*
* @param {Object} vnode
*/
function toNativeText (vnode) {
return document.createTextNode(vnode.data)
}
/**
* Create a native element from a virtual element.
*/
function toNativeElement (entityId, path, vnode) {
var attributes = vnode.attributes
var children = vnode.children
var tagName = vnode.tagName
var el
// create element either from pool or fresh.
if (!options.pooling || !canPool(tagName)) {
if (svg.isElement(tagName)) {
el = document.createElementNS(svg.namespace, tagName)
} else {
el = document.createElement(tagName)
}
} else {
var pool = getPool(tagName)
el = cleanup(pool.pop())
if (el.parentNode) el.parentNode.removeChild(el)
}
// set attributes.
forEach(attributes, function (value, name) {
setAttribute(entityId, path, el, name, value)
})
// store keys on the native element for fast event handling.
el.__entity__ = entityId
el.__path__ = path
// add children.
forEach(children, function (child, i) {
var childEl = toNative(entityId, path + '.' + i, child)
if (!childEl.parentNode) el.appendChild(childEl)
})
return el
}
/**
* Create a native element from a component.
*/
function toNativeComponent (entityId, path, vnode) {
var child = new Entity(vnode.component, vnode.props, entityId)
children[entityId][path] = child.id
return mountEntity(child)
}
/**
* Patch an element with the diff from two trees.
*/
function patch (entityId, prev, next, el) {
return diffNode('0', entityId, prev, next, el)
}
/**
* Create a diff between two trees of nodes.
*/
function diffNode (path, entityId, prev, next, el) {
// Type changed. This could be from element->text, text->ComponentA,
// ComponentA->ComponentB etc. But NOT div->span. These are the same type
// (ElementNode) but different tag name.
if (prev.type !== next.type) return replaceElement(entityId, path, el, next)
switch (next.type) {
case 'text': return diffText(prev, next, el)
case 'element': return diffElement(path, entityId, prev, next, el)
case 'component': return diffComponent(path, entityId, prev, next, el)
}
}
/**
* Diff two text nodes and update the element.
*/
function diffText (previous, current, el) {
if (current.data !== previous.data) el.data = current.data
return el
}
/**
* Diff the children of an ElementNode.
*/
function diffChildren (path, entityId, prev, next, el) {
var positions = []
var hasKeys = false
var childNodes = Array.prototype.slice.apply(el.childNodes)
var leftKeys = reduce(prev.children, keyMapReducer, {})
var rightKeys = reduce(next.children, keyMapReducer, {})
var currentChildren = assign({}, children[entityId])
function keyMapReducer (acc, child) {
if (child.key != null) {
acc[child.key] = child
hasKeys = true
}
return acc
}
// Diff all of the nodes that have keys. This lets us re-used elements
// instead of overriding them and lets us move them around.
if (hasKeys) {
// Removals
forEach(leftKeys, function (leftNode, key) {
if (rightKeys[key] == null) {
var leftPath = path + '.' + leftNode.index
removeElement(
entityId,
leftPath,
childNodes[leftNode.index]
)
}
})
// Update nodes
forEach(rightKeys, function (rightNode, key) {
var leftNode = leftKeys[key]
// We only want updates for now
if (leftNode == null) return
var leftPath = path + '.' + leftNode.index
// Updated
positions[rightNode.index] = diffNode(
leftPath,
entityId,
leftNode,
rightNode,
childNodes[leftNode.index]
)
})
// Update the positions of all child components and event handlers
forEach(rightKeys, function (rightNode, key) {
var leftNode = leftKeys[key]
// We just want elements that have moved around
if (leftNode == null || leftNode.index === rightNode.index) return
var rightPath = path + '.' + rightNode.index
var leftPath = path + '.' + leftNode.index
// Update all the child component path positions to match
// the latest positions if they've changed. This is a bit hacky.
forEach(currentChildren, function (childId, childPath) {
if (leftPath === childPath) {
delete children[entityId][childPath]
children[entityId][rightPath] = childId
}
})
})
// Now add all of the new nodes last in case their path
// would have conflicted with one of the previous paths.
forEach(rightKeys, function (rightNode, key) {
var rightPath = path + '.' + rightNode.index
if (leftKeys[key] == null) {
positions[rightNode.index] = toNative(
entityId,
rightPath,
rightNode
)
}
})
} else {
var maxLength = Math.max(prev.children.length, next.children.length)
// Now diff all of the nodes that don't have keys
for (var i = 0; i < maxLength; i++) {
var leftNode = prev.children[i]
var rightNode = next.children[i]
// Removals
if (rightNode == null) {
removeElement(
entityId,
path + '.' + leftNode.index,
childNodes[leftNode.index]
)
}
// New Node
if (leftNode == null) {
positions[rightNode.index] = toNative(
entityId,
path + '.' + rightNode.index,
rightNode
)
}
// Updated
if (leftNode && rightNode) {
positions[leftNode.index] = diffNode(
path + '.' + leftNode.index,
entityId,
leftNode,
rightNode,
childNodes[leftNode.index]
)
}
}
}
// Reposition all the elements
forEach(positions, function (childEl, newPosition) {
var target = el.childNodes[newPosition]
if (childEl !== target) {
if (target) {
el.insertBefore(childEl, target)
} else {
el.appendChild(childEl)
}
}
})
}
/**
* Diff the attributes and add/remove them.
*/
function diffAttributes (prev, next, el, entityId, path) {
var nextAttrs = next.attributes
var prevAttrs = prev.attributes
// add new attrs
forEach(nextAttrs, function (value, name) {
if (events[name] || !(name in prevAttrs) || prevAttrs[name] !== value) {
setAttribute(entityId, path, el, name, value)
}
})
// remove old attrs
forEach(prevAttrs, function (value, name) {
if (!(name in nextAttrs)) {
removeAttribute(entityId, path, el, name)
}
})
}
/**
* Update a component with the props from the next node. If
* the component type has changed, we'll just remove the old one
* and replace it with the new component.
*/
function diffComponent (path, entityId, prev, next, el) {
if (next.component !== prev.component) {
return replaceElement(entityId, path, el, next)
} else {
var targetId = children[entityId][path]
// This is a hack for now
if (targetId) {
updateEntityProps(targetId, next.props)
}
return el
}
}
/**
* Diff two element nodes.
*/
function diffElement (path, entityId, prev, next, el) {
if (next.tagName !== prev.tagName) return replaceElement(entityId, path, el, next)
diffAttributes(prev, next, el, entityId, path)
diffChildren(path, entityId, prev, next, el)
return el
}
/**
* Removes an element from the DOM and unmounts and components
* that are within that branch
*
* side effects:
* - removes element from the DOM
* - removes internal references
*
* @param {String} entityId
* @param {String} path
* @param {HTMLElement} el
*/
function removeElement (entityId, path, el) {
var childrenByPath = children[entityId]
var childId = childrenByPath[path]
var entityHandlers = handlers[entityId] || {}
var removals = []
// If the path points to a component we should use that
// components element instead, because it might have moved it.
if (childId) {
var child = entities[childId]
el = child.nativeElement
unmountEntity(childId)
removals.push(path)
} else {
// Just remove the text node
if (!isElement(el)) return el && el.parentNode.removeChild(el)
// Then we need to find any components within this
// branch and unmount them.
forEach(childrenByPath, function (childId, childPath) {
if (childPath === path || isWithinPath(path, childPath)) {
unmountEntity(childId)
removals.push(childPath)
}
})
// Remove all events at this path or below it
forEach(entityHandlers, function (fn, handlerPath) {
if (handlerPath === path || isWithinPath(path, handlerPath)) {
removeEvent(entityId, handlerPath)
}
})
}
// Remove the paths from the object without touching the
// old object. This keeps the object using fast properties.
forEach(removals, function (path) {
delete children[entityId][path]
})
// Remove it from the DOM
el.parentNode.removeChild(el)
// Return all of the elements in this node tree to the pool
// so that the elements can be re-used.
if (options.pooling) {
walk(el, function (node) {
if (!isElement(node) || !canPool(node.tagName)) return
getPool(node.tagName.toLowerCase()).push(node)
})
}
}
/**
* Replace an element in the DOM. Removing all components
* within that element and re-rendering the new virtual node.
*
* @param {Entity} entity
* @param {String} path
* @param {HTMLElement} el
* @param {Object} vnode
*
* @return {void}
*/
function replaceElement (entityId, path, el, vnode) {
var parent = el.parentNode
var index = Array.prototype.indexOf.call(parent.childNodes, el)
// remove the previous element and all nested components. This
// needs to happen before we create the new element so we don't
// get clashes on the component paths.
removeElement(entityId, path, el)
// then add the new element in there
var newEl = toNative(entityId, path, vnode)
var target = parent.childNodes[index]
if (target) {
parent.insertBefore(newEl, target)
} else {
parent.appendChild(newEl)
}
// walk up the tree and update all `entity.nativeElement` references.
if (entityId !== 'root' && path === '0') {
updateNativeElement(entityId, newEl)
}
return newEl
}
/**
* Update all entities in a branch that have the same nativeElement. This
* happens when a component has another component as it's root node.
*
* @param {String} entityId
* @param {HTMLElement} newEl
*
* @return {void}
*/
function updateNativeElement (entityId, newEl) {
var target = entities[entityId]
if (target.ownerId === 'root') return
if (children[target.ownerId]['0'] === entityId) {
entities[target.ownerId].nativeElement = newEl
updateNativeElement(target.ownerId, newEl)
}
}