Debian Codegraph @

packages/virtualdom/src/index.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 /*-----------------------------------------------------------------------------
4 | Copyright (c) 2014-2017, PhosphorJS Contributors
5 |
6 | Distributed under the terms of the BSD 3-Clause License.
7 |
8 | The full license is in the file LICENSE, distributed with this software.
9 |----------------------------------------------------------------------------*/
10 /**
11 * @packageDocumentation
12 * @module virtualdom
13 */
14 import { ArrayExt } from '@lumino/algorithm';
15
16 /**
17 * The names of the supported HTML5 DOM element attributes.
18 *
19 * This list is not all-encompassing, rather it attempts to define the
20 * attribute names which are relevant for use in a virtual DOM context.
21 * If a standardized or widely supported name is missing, please open
22 * an issue to have it added.
23 *
24 * The attribute names were collected from the following sources:
25 * - https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
26 * - https://www.w3.org/TR/html5/index.html#attributes-1
27 * - https://html.spec.whatwg.org/multipage/indices.html#attributes-3
28 */
29 export type ElementAttrNames =
30 | 'abbr'
31 | 'accept'
32 | 'accept-charset'
33 | 'accesskey'
34 | 'action'
35 | 'allowfullscreen'
36 | 'alt'
37 | 'autocomplete'
38 | 'autofocus'
39 | 'autoplay'
40 | 'autosave'
41 | 'checked'
42 | 'cite'
43 | 'cols'
44 | 'colspan'
45 | 'contenteditable'
46 | 'controls'
47 | 'coords'
48 | 'crossorigin'
49 | 'data'
50 | 'datetime'
51 | 'default'
52 | 'dir'
53 | 'dirname'
54 | 'disabled'
55 | 'download'
56 | 'draggable'
57 | 'dropzone'
58 | 'enctype'
59 | 'form'
60 | 'formaction'
61 | 'formenctype'
62 | 'formmethod'
63 | 'formnovalidate'
64 | 'formtarget'
65 | 'headers'
66 | 'height'
67 | 'hidden'
68 | 'high'
69 | 'href'
70 | 'hreflang'
71 | 'id'
72 | 'inputmode'
73 | 'integrity'
74 | 'ismap'
75 | 'kind'
76 | 'label'
77 | 'lang'
78 | 'list'
79 | 'loop'
80 | 'low'
81 | 'max'
82 | 'maxlength'
83 | 'media'
84 | 'mediagroup'
85 | 'method'
86 | 'min'
87 | 'minlength'
88 | 'multiple'
89 | 'muted'
90 | 'name'
91 | 'novalidate'
92 | 'optimum'
93 | 'pattern'
94 | 'placeholder'
95 | 'poster'
96 | 'preload'
97 | 'readonly'
98 | 'rel'
99 | 'required'
100 | 'reversed'
101 | 'rows'
102 | 'rowspan'
103 | 'sandbox'
104 | 'scope'
105 | 'selected'
106 | 'shape'
107 | 'size'
108 | 'sizes'
109 | 'span'
110 | 'spellcheck'
111 | 'src'
112 | 'srcdoc'
113 | 'srclang'
114 | 'srcset'
115 | 'start'
116 | 'step'
117 | 'tabindex'
118 | 'target'
119 | 'title'
120 | 'type'
121 | 'typemustmatch'
122 | 'usemap'
123 | 'value'
124 | 'width'
125 | 'wrap';
126
127 /**
128 * The names of ARIA attributes for HTML elements.
129 *
130 * The attribute names are collected from
131 * https://www.w3.org/TR/html5/infrastructure.html#element-attrdef-aria-role
132 */
133 export type ARIAAttrNames =
134 | 'aria-activedescendant'
135 | 'aria-atomic'
136 | 'aria-autocomplete'
137 | 'aria-busy'
138 | 'aria-checked'
139 | 'aria-colcount'
140 | 'aria-colindex'
141 | 'aria-colspan'
142 | 'aria-controls'
143 | 'aria-current'
144 | 'aria-describedby'
145 | 'aria-details'
146 | 'aria-dialog'
147 | 'aria-disabled'
148 | 'aria-dropeffect'
149 | 'aria-errormessage'
150 | 'aria-expanded'
151 | 'aria-flowto'
152 | 'aria-grabbed'
153 | 'aria-haspopup'
154 | 'aria-hidden'
155 | 'aria-invalid'
156 | 'aria-keyshortcuts'
157 | 'aria-label'
158 | 'aria-labelledby'
159 | 'aria-level'
160 | 'aria-live'
161 | 'aria-multiline'
162 | 'aria-multiselectable'
163 | 'aria-orientation'
164 | 'aria-owns'
165 | 'aria-placeholder'
166 | 'aria-posinset'
167 | 'aria-pressed'
168 | 'aria-readonly'
169 | 'aria-relevant'
170 | 'aria-required'
171 | 'aria-roledescription'
172 | 'aria-rowcount'
173 | 'aria-rowindex'
174 | 'aria-rowspan'
175 | 'aria-selected'
176 | 'aria-setsize'
177 | 'aria-sort'
178 | 'aria-valuemax'
179 | 'aria-valuemin'
180 | 'aria-valuenow'
181 | 'aria-valuetext'
182 | 'role';
183
184 /**
185 * The names of the supported HTML5 CSS property names.
186 *
187 * If a standardized or widely supported name is missing, please open
188 * an issue to have it added.
189 *
190 * The property names were collected from the following sources:
191 * - TypeScript's `lib.dom.d.ts` file
192 */
193 export type CSSPropertyNames =
194 | 'alignContent'
195 | 'alignItems'
196 | 'alignSelf'
197 | 'alignmentBaseline'
198 | 'animation'
199 | 'animationDelay'
200 | 'animationDirection'
201 | 'animationDuration'
202 | 'animationFillMode'
203 | 'animationIterationCount'
204 | 'animationName'
205 | 'animationPlayState'
206 | 'animationTimingFunction'
207 | 'backfaceVisibility'
208 | 'background'
209 | 'backgroundAttachment'
210 | 'backgroundClip'
211 | 'backgroundColor'
212 | 'backgroundImage'
213 | 'backgroundOrigin'
214 | 'backgroundPosition'
215 | 'backgroundPositionX'
216 | 'backgroundPositionY'
217 | 'backgroundRepeat'
218 | 'backgroundSize'
219 | 'baselineShift'
220 | 'border'
221 | 'borderBottom'
222 | 'borderBottomColor'
223 | 'borderBottomLeftRadius'
224 | 'borderBottomRightRadius'
225 | 'borderBottomStyle'
226 | 'borderBottomWidth'
227 | 'borderCollapse'
228 | 'borderColor'
229 | 'borderImage'
230 | 'borderImageOutset'
231 | 'borderImageRepeat'
232 | 'borderImageSlice'
233 | 'borderImageSource'
234 | 'borderImageWidth'
235 | 'borderLeft'
236 | 'borderLeftColor'
237 | 'borderLeftStyle'
238 | 'borderLeftWidth'
239 | 'borderRadius'
240 | 'borderRight'
241 | 'borderRightColor'
242 | 'borderRightStyle'
243 | 'borderRightWidth'
244 | 'borderSpacing'
245 | 'borderStyle'
246 | 'borderTop'
247 | 'borderTopColor'
248 | 'borderTopLeftRadius'
249 | 'borderTopRightRadius'
250 | 'borderTopStyle'
251 | 'borderTopWidth'
252 | 'borderWidth'
253 | 'bottom'
254 | 'boxShadow'
255 | 'boxSizing'
256 | 'breakAfter'
257 | 'breakBefore'
258 | 'breakInside'
259 | 'captionSide'
260 | 'clear'
261 | 'clip'
262 | 'clipPath'
263 | 'clipRule'
264 | 'color'
265 | 'colorInterpolationFilters'
266 | 'columnCount'
267 | 'columnFill'
268 | 'columnGap'
269 | 'columnRule'
270 | 'columnRuleColor'
271 | 'columnRuleStyle'
272 | 'columnRuleWidth'
273 | 'columnSpan'
274 | 'columnWidth'
275 | 'columns'
276 | 'content'
277 | 'counterIncrement'
278 | 'counterReset'
279 | 'cssFloat'
280 | 'cssText'
281 | 'cursor'
282 | 'direction'
283 | 'display'
284 | 'dominantBaseline'
285 | 'emptyCells'
286 | 'enableBackground'
287 | 'fill'
288 | 'fillOpacity'
289 | 'fillRule'
290 | 'filter'
291 | 'flex'
292 | 'flexBasis'
293 | 'flexDirection'
294 | 'flexFlow'
295 | 'flexGrow'
296 | 'flexShrink'
297 | 'flexWrap'
298 | 'floodColor'
299 | 'floodOpacity'
300 | 'font'
301 | 'fontFamily'
302 | 'fontFeatureSettings'
303 | 'fontSize'
304 | 'fontSizeAdjust'
305 | 'fontStretch'
306 | 'fontStyle'
307 | 'fontVariant'
308 | 'fontWeight'
309 | 'glyphOrientationHorizontal'
310 | 'glyphOrientationVertical'
311 | 'height'
312 | 'imeMode'
313 | 'justifyContent'
314 | 'kerning'
315 | 'left'
316 | 'letterSpacing'
317 | 'lightingColor'
318 | 'lineHeight'
319 | 'listStyle'
320 | 'listStyleImage'
321 | 'listStylePosition'
322 | 'listStyleType'
323 | 'margin'
324 | 'marginBottom'
325 | 'marginLeft'
326 | 'marginRight'
327 | 'marginTop'
328 | 'marker'
329 | 'markerEnd'
330 | 'markerMid'
331 | 'markerStart'
332 | 'mask'
333 | 'maxHeight'
334 | 'maxWidth'
335 | 'minHeight'
336 | 'minWidth'
337 | 'msContentZoomChaining'
338 | 'msContentZoomLimit'
339 | 'msContentZoomLimitMax'
340 | 'msContentZoomLimitMin'
341 | 'msContentZoomSnap'
342 | 'msContentZoomSnapPoints'
343 | 'msContentZoomSnapType'
344 | 'msContentZooming'
345 | 'msFlowFrom'
346 | 'msFlowInto'
347 | 'msFontFeatureSettings'
348 | 'msGridColumn'
349 | 'msGridColumnAlign'
350 | 'msGridColumnSpan'
351 | 'msGridColumns'
352 | 'msGridRow'
353 | 'msGridRowAlign'
354 | 'msGridRowSpan'
355 | 'msGridRows'
356 | 'msHighContrastAdjust'
357 | 'msHyphenateLimitChars'
358 | 'msHyphenateLimitLines'
359 | 'msHyphenateLimitZone'
360 | 'msHyphens'
361 | 'msImeAlign'
362 | 'msOverflowStyle'
363 | 'msScrollChaining'
364 | 'msScrollLimit'
365 | 'msScrollLimitXMax'
366 | 'msScrollLimitXMin'
367 | 'msScrollLimitYMax'
368 | 'msScrollLimitYMin'
369 | 'msScrollRails'
370 | 'msScrollSnapPointsX'
371 | 'msScrollSnapPointsY'
372 | 'msScrollSnapType'
373 | 'msScrollSnapX'
374 | 'msScrollSnapY'
375 | 'msScrollTranslation'
376 | 'msTextCombineHorizontal'
377 | 'msTextSizeAdjust'
378 | 'msTouchAction'
379 | 'msTouchSelect'
380 | 'msUserSelect'
381 | 'msWrapFlow'
382 | 'msWrapMargin'
383 | 'msWrapThrough'
384 | 'opacity'
385 | 'order'
386 | 'orphans'
387 | 'outline'
388 | 'outlineColor'
389 | 'outlineStyle'
390 | 'outlineWidth'
391 | 'overflow'
392 | 'overflowX'
393 | 'overflowY'
394 | 'padding'
395 | 'paddingBottom'
396 | 'paddingLeft'
397 | 'paddingRight'
398 | 'paddingTop'
399 | 'pageBreakAfter'
400 | 'pageBreakBefore'
401 | 'pageBreakInside'
402 | 'perspective'
403 | 'perspectiveOrigin'
404 | 'pointerEvents'
405 | 'position'
406 | 'quotes'
407 | 'resize'
408 | 'right'
409 | 'rubyAlign'
410 | 'rubyOverhang'
411 | 'rubyPosition'
412 | 'stopColor'
413 | 'stopOpacity'
414 | 'stroke'
415 | 'strokeDasharray'
416 | 'strokeDashoffset'
417 | 'strokeLinecap'
418 | 'strokeLinejoin'
419 | 'strokeMiterlimit'
420 | 'strokeOpacity'
421 | 'strokeWidth'
422 | 'tableLayout'
423 | 'textAlign'
424 | 'textAlignLast'
425 | 'textAnchor'
426 | 'textDecoration'
427 | 'textIndent'
428 | 'textJustify'
429 | 'textKashida'
430 | 'textKashidaSpace'
431 | 'textOverflow'
432 | 'textShadow'
433 | 'textTransform'
434 | 'textUnderlinePosition'
435 | 'top'
436 | 'touchAction'
437 | 'transform'
438 | 'transformOrigin'
439 | 'transformStyle'
440 | 'transition'
441 | 'transitionDelay'
442 | 'transitionDuration'
443 | 'transitionProperty'
444 | 'transitionTimingFunction'
445 | 'unicodeBidi'
446 | 'verticalAlign'
447 | 'visibility'
448 | 'webkitAlignContent'
449 | 'webkitAlignItems'
450 | 'webkitAlignSelf'
451 | 'webkitAnimation'
452 | 'webkitAnimationDelay'
453 | 'webkitAnimationDirection'
454 | 'webkitAnimationDuration'
455 | 'webkitAnimationFillMode'
456 | 'webkitAnimationIterationCount'
457 | 'webkitAnimationName'
458 | 'webkitAnimationPlayState'
459 | 'webkitAnimationTimingFunction'
460 | 'webkitAppearance'
461 | 'webkitBackfaceVisibility'
462 | 'webkitBackgroundClip'
463 | 'webkitBackgroundOrigin'
464 | 'webkitBackgroundSize'
465 | 'webkitBorderBottomLeftRadius'
466 | 'webkitBorderBottomRightRadius'
467 | 'webkitBorderImage'
468 | 'webkitBorderRadius'
469 | 'webkitBorderTopLeftRadius'
470 | 'webkitBorderTopRightRadius'
471 | 'webkitBoxAlign'
472 | 'webkitBoxDirection'
473 | 'webkitBoxFlex'
474 | 'webkitBoxOrdinalGroup'
475 | 'webkitBoxOrient'
476 | 'webkitBoxPack'
477 | 'webkitBoxSizing'
478 | 'webkitColumnBreakAfter'
479 | 'webkitColumnBreakBefore'
480 | 'webkitColumnBreakInside'
481 | 'webkitColumnCount'
482 | 'webkitColumnGap'
483 | 'webkitColumnRule'
484 | 'webkitColumnRuleColor'
485 | 'webkitColumnRuleStyle'
486 | 'webkitColumnRuleWidth'
487 | 'webkitColumnSpan'
488 | 'webkitColumnWidth'
489 | 'webkitColumns'
490 | 'webkitFilter'
491 | 'webkitFlex'
492 | 'webkitFlexBasis'
493 | 'webkitFlexDirection'
494 | 'webkitFlexFlow'
495 | 'webkitFlexGrow'
496 | 'webkitFlexShrink'
497 | 'webkitFlexWrap'
498 | 'webkitJustifyContent'
499 | 'webkitOrder'
500 | 'webkitPerspective'
501 | 'webkitPerspectiveOrigin'
502 | 'webkitTapHighlightColor'
503 | 'webkitTextFillColor'
504 | 'webkitTextSizeAdjust'
505 | 'webkitTransform'
506 | 'webkitTransformOrigin'
507 | 'webkitTransformStyle'
508 | 'webkitTransition'
509 | 'webkitTransitionDelay'
510 | 'webkitTransitionDuration'
511 | 'webkitTransitionProperty'
512 | 'webkitTransitionTimingFunction'
513 | 'webkitUserModify'
514 | 'webkitUserSelect'
515 | 'webkitWritingMode'
516 | 'whiteSpace'
517 | 'widows'
518 | 'width'
519 | 'wordBreak'
520 | 'wordSpacing'
521 | 'wordWrap'
522 | 'writingMode'
523 | 'zIndex'
524 | 'zoom';
525
526 /**
527 * A mapping of inline event name to event object type.
528 *
529 * This mapping is used to create the event listener properties for
530 * the virtual DOM element attributes object. If a standardized or
531 * widely supported name is missing, please open an issue to have it
532 * added.
533 *
534 * The event names were collected from the following sources:
535 * - TypeScript's `lib.dom.d.ts` file
536 * - https://www.w3.org/TR/html5/index.html#attributes-1
537 * - https://html.spec.whatwg.org/multipage/webappapis.html#idl-definitions
538 */
539 export type ElementEventMap = {
540 onabort: UIEvent;
541 onauxclick: MouseEvent;
542 onblur: FocusEvent;
543 oncanplay: Event;
544 oncanplaythrough: Event;
545 onchange: Event;
546 onclick: MouseEvent;
547 oncontextmenu: PointerEvent;
548 oncopy: ClipboardEvent;
549 oncuechange: Event;
550 oncut: ClipboardEvent;
551 ondblclick: MouseEvent;
552 ondrag: DragEvent;
553 ondragend: DragEvent;
554 ondragenter: DragEvent;
555 ondragexit: DragEvent;
556 ondragleave: DragEvent;
557 ondragover: DragEvent;
558 ondragstart: DragEvent;
559 ondrop: DragEvent;
560 ondurationchange: Event;
561 onemptied: Event;
562 onended: ErrorEvent;
563 onerror: ErrorEvent;
564 onfocus: FocusEvent;
565 oninput: Event;
566 oninvalid: Event;
567 onkeydown: KeyboardEvent;
568 onkeypress: KeyboardEvent;
569 onkeyup: KeyboardEvent;
570 onload: Event;
571 onloadeddata: Event;
572 onloadedmetadata: Event;
573 onloadend: Event;
574 onloadstart: Event;
575 onmousedown: MouseEvent;
576 onmouseenter: MouseEvent;
577 onmouseleave: MouseEvent;
578 onmousemove: MouseEvent;
579 onmouseout: MouseEvent;
580 onmouseover: MouseEvent;
581 onmouseup: MouseEvent;
582 onmousewheel: WheelEvent;
583 onpaste: ClipboardEvent;
584 onpause: Event;
585 onplay: Event;
586 onplaying: Event;
587 onpointercancel: PointerEvent;
588 onpointerdown: PointerEvent;
589 onpointerenter: PointerEvent;
590 onpointerleave: PointerEvent;
591 onpointermove: PointerEvent;
592 onpointerout: PointerEvent;
593 onpointerover: PointerEvent;
594 onpointerup: PointerEvent;
595 onprogress: ProgressEvent;
596 onratechange: Event;
597 onreset: Event;
598 onscroll: UIEvent;
599 onseeked: Event;
600 onseeking: Event;
601 onselect: UIEvent;
602 onselectstart: Event;
603 onstalled: Event;
604 onsubmit: Event;
605 onsuspend: Event;
606 ontimeupdate: Event;
607 onvolumechange: Event;
608 onwaiting: Event;
609 };
610
611 /**
612 * An object which represents a dataset for a virtual DOM element.
613 *
614 * The names of the dataset properties will be automatically prefixed
615 * with `data-` before being added to the node, e.g. `{ thing: '12' }`
616 * will be rendered as `data-thing='12'` in the DOM element.
617 *
618 * Dataset property names should not contain spaces.
619 */
620 export type ElementDataset = {
621 readonly [name: string]: string;
622 };
623
624 /**
625 * The inline style for for a virtual DOM element.
626 *
627 * Style attributes use the JS camel-cased property names instead of
628 * the CSS hyphenated names for performance and security.
629 */
630 export type ElementInlineStyle = {
631 readonly [T in CSSPropertyNames]?: string;
632 };
633
634 /**
635 * The ARIA attributes for a virtual element node.
636 *
637 * These are the attributes which are applied to a real DOM element via
638 * `element.setAttribute()`. The supported attribute names are defined
639 * by the `ARIAAttrNames` type.
640 */
641 export type ElementARIAAttrs = {
642 readonly [T in ARIAAttrNames]?: string;
643 };
644
645 /**
646 * The base attributes for a virtual element node.
647 *
648 * These are the attributes which are applied to a real DOM element via
649 * `element.setAttribute()`. The supported attribute names are defined
650 * by the `ElementAttrNames` type.
651 *
652 * Node attributes are specified using the lower-case HTML name instead
653 * of the camel-case JS name due to browser inconsistencies in handling
654 * the JS versions.
655 */
656 export type ElementBaseAttrs = {
657 readonly [T in ElementAttrNames]?: string;
658 };
659
660 /**
661 * The inline event listener attributes for a virtual element node.
662 *
663 * The supported listeners are defined by the `ElementEventMap` type.
664 */
665 export type ElementEventAttrs = {
666 readonly [T in keyof ElementEventMap]?: (
667 this: HTMLElement,
668 event: ElementEventMap[T]
669 ) => any;
670 };
671
672 /**
673 * The special-cased attributes for a virtual element node.
674 */
675 export type ElementSpecialAttrs = {
676 /**
677 * The key id for the virtual element node.
678 *
679 * If a node is given a key id, the generated DOM node will not be
680 * recreated during a rendering update if it only moves among its
681 * siblings in the render tree.
682 *
683 * In general, reordering child nodes will cause the nodes to be
684 * completely re-rendered. Keys allow this to be optimized away.
685 *
686 * If a key is provided, it must be unique among sibling nodes.
687 */
688 readonly key?: string;
689
690 /**
691 * The JS-safe name for the HTML `class` attribute.
692 */
693 readonly className?: string;
694
695 /**
696 * The JS-safe name for the HTML `for` attribute.
697 */
698 readonly htmlFor?: string;
699
700 /**
701 * The dataset for the rendered DOM element.
702 */
703 readonly dataset?: ElementDataset;
704
705 /**
706 * The inline style for the rendered DOM element.
707 */
708 readonly style?: ElementInlineStyle;
709 };
710
711 /**
712 * The full set of attributes supported by a virtual element node.
713 *
714 * This is the combination of the base element attributes, the the ARIA attributes,
715 * the inline element event listeners, and the special element attributes.
716 */
717 export type ElementAttrs = ElementBaseAttrs &
718 ElementARIAAttrs &
719 ElementEventAttrs &
720 ElementSpecialAttrs;
721
722 /**
723 * A virtual node which represents plain text content.
724 *
725 * #### Notes
726 * User code will not typically create a `VirtualText` node directly.
727 * Instead, the `h()` function will be used to create an element tree.
728 */
729 export class VirtualText {
730 /**
731 * The text content for the node.
732 */
733 readonly content: string;
734
735 /**
736 * The type of the node.
737 *
738 * This value can be used as a type guard for discriminating the
739 * `VirtualNode` union type.
740 */
741 readonly type = 'text' as const;
742
743 /**
744 * Construct a new virtual text node.
745 *
746 * @param content - The text content for the node.
747 */
748 constructor(content: string) {
749 this.content = content;
750 }
751 }
752
753 /**
754 * A virtual node which represents an HTML element.
755 *
756 * #### Notes
757 * User code will not typically create a `VirtualElement` node directly.
758 * Instead, the `h()` function will be used to create an element tree.
759 */
760 export class VirtualElement {
761 /**
762 * The tag name for the element.
763 */
764 readonly tag: string;
765
766 /**
767 * The attributes for the element.
768 */
769 readonly attrs: ElementAttrs;
770
771 /**
772 * The children for the element.
773 */
774 readonly children: ReadonlyArray<VirtualNode>;
775
776 /**
777 * An optional custom renderer for the element's children. If set, on render
778 * this element's DOM node and it's attrs will be created/updated as normal.
779 * At that point the DOM node is handed off to the renderer.
780 */
781 readonly renderer: VirtualElement.IRenderer | undefined;
782
783 /**
784 * The type of the node.
785 *
786 * This value can be used as a type guard for discriminating the
787 * `VirtualNode` union type.
788 */
789 readonly type = 'element' as const;
790
791 /**
792 * Construct a new virtual element node.
793 *
794 * @param tag - The element tag name.
795 *
796 * @param attrs - The element attributes.
797 *
798 * @param children - The element children.
799 *
800 * @param renderer - An optional custom renderer for the element.
801 */
802 constructor(
803 tag: string,
804 attrs: ElementAttrs,
805 children: ReadonlyArray<VirtualNode>,
806 renderer?: VirtualElement.IRenderer
807 ) {
808 this.tag = tag;
809 this.attrs = attrs;
810 this.children = children;
811
812 this.renderer = renderer;
813 }
814 }
815
816 export namespace VirtualElement {
817 /**
818 * A type describing a custom element renderer
819 */
820 export type IRenderer = {
821 /**
822 * Customize how a DOM node is rendered. If .renderer is set on a given
823 * instance of VirtualElement, this function will be called every time
824 * that VirtualElement is rendered.
825 *
826 * @param host - The actual DOM node created for a VirtualElement during
827 * rendering.
828 *
829 * On render, host is created and its attrs are set/updated via
830 * the standard routines in updateContent. host is then handed off to this
831 * function.
832 *
833 * The render function is free to modify host. The only restriction is
834 * is that render should not modify any attributes set by external
835 * routines (ie updateContent), as this may cause thrashing when the
836 * virtual element is next rendered.
837 *
838 * @param options - Will be populated with the .attrs and .children fields
839 * set on the VirtualElement being rendered.
840 */
841 render: (
842 host: HTMLElement,
843 options?: { attrs?: ElementAttrs; children?: ReadonlyArray<VirtualNode> }
844 ) => void;
845
846 /**
847 * Optional cleanup function for custom renderers. If the .renderer field
848 * of a VirtualELement is set, and if .renderer.unrender is defined, when
849 * the element is changed or removed its corresponding DOM element will be
850 * passed to this function immediately before it is removed from the DOM.
851 *
852 * unrender is not required for for simple renderers, such as those
853 * implemented using `document.createElement()`. However, for certain
854 * rendering techniques explicit cleanup is required in order to avoid
855 * resource leaks.
856 *
857 * For example, if render calls `ReactDOM.render(..., host)`, then
858 * there has to also be a corresponding implementation of unrender that
859 * calls `ReactDOM.unmountComponentAtNode(host)` in order to prevent
860 * a memory leak.
861 *
862 * @param host - the DOM element to be removed.
863 *
864 * @param options - Will be populated with the .attrs and .children fields
865 * set on the VirtualElement being unrendered.
866 */
867 unrender?: (
868 host: HTMLElement,
869 options?: { attrs?: ElementAttrs; children?: ReadonlyArray<VirtualNode> }
870 ) => void;
871 };
872 }
873
874 /**
875 * DEPRECATED - use VirtualElement with a defined renderer param instead.
876 * This class is provided as a backwards compatibility shim
877 *
878 * A "pass thru" virtual node whose children are managed by a render and an
879 * unrender callback. The intent of this flavor of virtual node is to make
880 * it easy to blend other kinds of virtualdom (eg React) into Phosphor's
881 * virtualdom.
882 *
883 * #### Notes
884 * User code will not typically create a `VirtualElementPass` node directly.
885 * Instead, the `hpass()` function will be used to create an element tree.
886 */
887 export class VirtualElementPass extends VirtualElement {
888 /**
889 * DEPRECATED - use VirtualElement with a defined renderer param instead
890 *
891 * Construct a new virtual element pass thru node.
892 *
893 * @param tag - the tag of the parent element of this node. Once the parent
894 * element is rendered, it will be passed as an argument to
895 * renderer.render
896 *
897 * @param attrs - attributes that will assigned to the
898 * parent element
899 *
900 * @param renderer - an object with render and unrender
901 * functions, each of which should take a single argument of type
902 * HTMLElement and return nothing. If null, the parent element
903 * will be rendered barren without any children.
904 */
905 constructor(
906 tag: string,
907 attrs: ElementAttrs,
908 renderer: VirtualElementPass.IRenderer | null
909 ) {
910 super(tag, attrs, [], renderer || undefined);
911 }
912 }
913
914 export namespace VirtualElementPass {
915 /**
916 * DEPRECATED - use VirtualElement.IRenderer instead
917 *
918 * A type describing a custom element renderer
919 */
920 export type IRenderer = VirtualElement.IRenderer;
921 }
922
923 /**
924 * A type alias for a general virtual node.
925 */
926 export type VirtualNode = VirtualElement | VirtualText;
927
928 /**
929 * Create a new virtual element node.
930 *
931 * @param tag - The tag name for the element.
932 *
933 * @param attrs - The attributes for the element, if any.
934 *
935 * @param renderer - An optional custom renderer for the element.
936 *
937 * @param children - The children for the element, if any.
938 *
939 * @returns A new virtual element node for the given parameters.
940 *
941 * #### Notes
942 * The children may be string literals, other virtual nodes, `null`, or
943 * an array of those things. Strings are converted into text nodes, and
944 * arrays are inlined as if the array contents were given as positional
945 * arguments. This makes it simple to build up an array of children by
946 * any desired means. `null` child values are simply ignored.
947 *
948 * A bound function for each HTML tag name is available as a static
949 * function attached to the `h()` function. E.g. `h('div', ...)` is
950 * equivalent to `h.div(...)`.
951 */
952 export function h(tag: string, ...children: h.Child[]): VirtualElement;
953 export function h(
954 tag: string,
955 attrs: ElementAttrs,
956 ...children: h.Child[]
957 ): VirtualElement;
958 export function h(
959 tag: string,
960 renderer: VirtualElement.IRenderer,
961 ...children: h.Child[]
962 ): VirtualElement;
963 export function h(
964 tag: string,
965 attrs: ElementAttrs,
966 renderer: VirtualElement.IRenderer,
967 ...children: h.Child[]
968 ): VirtualElement;
969 export function h(tag: string): VirtualElement {
970 let attrs: ElementAttrs = {};
971 let renderer: VirtualElement.IRenderer | undefined;
972 let children: VirtualNode[] = [];
973 for (let i = 1, n = arguments.length; i < n; ++i) {
974 // eslint-disable-next-line prefer-rest-params
975 let arg = arguments[i];
976 if (typeof arg === 'string') {
977 children.push(new VirtualText(arg));
978 } else if (arg instanceof VirtualText) {
979 children.push(arg);
980 } else if (arg instanceof VirtualElement) {
981 children.push(arg);
982 } else if (arg instanceof Array) {
983 extend(children, arg);
984 } else if ((i === 1 || i === 2) && arg && typeof arg === 'object') {
985 if ('render' in arg) {
986 renderer = arg;
987 } else {
988 attrs = arg;
989 }
990 }
991 }
992 return new VirtualElement(tag, attrs, children, renderer);
993
994 function extend(array: VirtualNode[], values: h.Child[]): void {
995 for (let child of values) {
996 if (typeof child === 'string') {
997 array.push(new VirtualText(child));
998 } else if (child instanceof VirtualText) {
999 array.push(child);
1000 } else if (child instanceof VirtualElement) {
1001 array.push(child);
1002 }
1003 }
1004 }
1005 }
1006
1007 /**
1008 * The namespace for the `h` function statics.
1009 */
1010 export namespace h {
1011 /**
1012 * A type alias for the supported child argument types.
1013 */
1014 export type Child =
1015 | (string | VirtualNode | null)
1016 | Array<string | VirtualNode | null>;
1017
1018 /**
1019 * A bound factory function for a specific `h()` tag.
1020 */
1021 export interface IFactory {
1022 (...children: Child[]): VirtualElement;
1023 (attrs: ElementAttrs, ...children: Child[]): VirtualElement;
1024 (
1025 renderer: VirtualElement.IRenderer,
1026 ...children: h.Child[]
1027 ): VirtualElement;
1028 (
1029 attrs: ElementAttrs,
1030 renderer: VirtualElement.IRenderer,
1031 ...children: h.Child[]
1032 ): VirtualElement;
1033 }
1034
1035 export const a: IFactory = h.bind(undefined, 'a');
1036 export const abbr: IFactory = h.bind(undefined, 'abbr');
1037 export const address: IFactory = h.bind(undefined, 'address');
1038 export const area: IFactory = h.bind(undefined, 'area');
1039 export const article: IFactory = h.bind(undefined, 'article');
1040 export const aside: IFactory = h.bind(undefined, 'aside');
1041 export const audio: IFactory = h.bind(undefined, 'audio');
1042 export const b: IFactory = h.bind(undefined, 'b');
1043 export const bdi: IFactory = h.bind(undefined, 'bdi');
1044 export const bdo: IFactory = h.bind(undefined, 'bdo');
1045 export const blockquote: IFactory = h.bind(undefined, 'blockquote');
1046 export const br: IFactory = h.bind(undefined, 'br');
1047 export const button: IFactory = h.bind(undefined, 'button');
1048 export const canvas: IFactory = h.bind(undefined, 'canvas');
1049 export const caption: IFactory = h.bind(undefined, 'caption');
1050 export const cite: IFactory = h.bind(undefined, 'cite');
1051 export const code: IFactory = h.bind(undefined, 'code');
1052 export const col: IFactory = h.bind(undefined, 'col');
1053 export const colgroup: IFactory = h.bind(undefined, 'colgroup');
1054 export const data: IFactory = h.bind(undefined, 'data');
1055 export const datalist: IFactory = h.bind(undefined, 'datalist');
1056 export const dd: IFactory = h.bind(undefined, 'dd');
1057 export const del: IFactory = h.bind(undefined, 'del');
1058 export const dfn: IFactory = h.bind(undefined, 'dfn');
1059 export const div: IFactory = h.bind(undefined, 'div');
1060 export const dl: IFactory = h.bind(undefined, 'dl');
1061 export const dt: IFactory = h.bind(undefined, 'dt');
1062 export const em: IFactory = h.bind(undefined, 'em');
1063 export const embed: IFactory = h.bind(undefined, 'embed');
1064 export const fieldset: IFactory = h.bind(undefined, 'fieldset');
1065 export const figcaption: IFactory = h.bind(undefined, 'figcaption');
1066 export const figure: IFactory = h.bind(undefined, 'figure');
1067 export const footer: IFactory = h.bind(undefined, 'footer');
1068 export const form: IFactory = h.bind(undefined, 'form');
1069 export const h1: IFactory = h.bind(undefined, 'h1');
1070 export const h2: IFactory = h.bind(undefined, 'h2');
1071 export const h3: IFactory = h.bind(undefined, 'h3');
1072 export const h4: IFactory = h.bind(undefined, 'h4');
1073 export const h5: IFactory = h.bind(undefined, 'h5');
1074 export const h6: IFactory = h.bind(undefined, 'h6');
1075 export const header: IFactory = h.bind(undefined, 'header');
1076 export const hr: IFactory = h.bind(undefined, 'hr');
1077 export const i: IFactory = h.bind(undefined, 'i');
1078 export const iframe: IFactory = h.bind(undefined, 'iframe');
1079 export const img: IFactory = h.bind(undefined, 'img');
1080 export const input: IFactory = h.bind(undefined, 'input');
1081 export const ins: IFactory = h.bind(undefined, 'ins');
1082 export const kbd: IFactory = h.bind(undefined, 'kbd');
1083 export const label: IFactory = h.bind(undefined, 'label');
1084 export const legend: IFactory = h.bind(undefined, 'legend');
1085 export const li: IFactory = h.bind(undefined, 'li');
1086 export const main: IFactory = h.bind(undefined, 'main');
1087 export const map: IFactory = h.bind(undefined, 'map');
1088 export const mark: IFactory = h.bind(undefined, 'mark');
1089 export const meter: IFactory = h.bind(undefined, 'meter');
1090 export const nav: IFactory = h.bind(undefined, 'nav');
1091 export const noscript: IFactory = h.bind(undefined, 'noscript');
1092 export const object: IFactory = h.bind(undefined, 'object');
1093 export const ol: IFactory = h.bind(undefined, 'ol');
1094 export const optgroup: IFactory = h.bind(undefined, 'optgroup');
1095 export const option: IFactory = h.bind(undefined, 'option');
1096 export const output: IFactory = h.bind(undefined, 'output');
1097 export const p: IFactory = h.bind(undefined, 'p');
1098 export const param: IFactory = h.bind(undefined, 'param');
1099 export const pre: IFactory = h.bind(undefined, 'pre');
1100 export const progress: IFactory = h.bind(undefined, 'progress');
1101 export const q: IFactory = h.bind(undefined, 'q');
1102 export const rp: IFactory = h.bind(undefined, 'rp');
1103 export const rt: IFactory = h.bind(undefined, 'rt');
1104 export const ruby: IFactory = h.bind(undefined, 'ruby');
1105 export const s: IFactory = h.bind(undefined, 's');
1106 export const samp: IFactory = h.bind(undefined, 'samp');
1107 export const section: IFactory = h.bind(undefined, 'section');
1108 export const select: IFactory = h.bind(undefined, 'select');
1109 export const small: IFactory = h.bind(undefined, 'small');
1110 export const source: IFactory = h.bind(undefined, 'source');
1111 export const span: IFactory = h.bind(undefined, 'span');
1112 export const strong: IFactory = h.bind(undefined, 'strong');
1113 export const sub: IFactory = h.bind(undefined, 'sub');
1114 export const summary: IFactory = h.bind(undefined, 'summary');
1115 export const sup: IFactory = h.bind(undefined, 'sup');
1116 export const table: IFactory = h.bind(undefined, 'table');
1117 export const tbody: IFactory = h.bind(undefined, 'tbody');
1118 export const td: IFactory = h.bind(undefined, 'td');
1119 export const textarea: IFactory = h.bind(undefined, 'textarea');
1120 export const tfoot: IFactory = h.bind(undefined, 'tfoot');
1121 export const th: IFactory = h.bind(undefined, 'th');
1122 export const thead: IFactory = h.bind(undefined, 'thead');
1123 export const time: IFactory = h.bind(undefined, 'time');
1124 export const title: IFactory = h.bind(undefined, 'title');
1125 export const tr: IFactory = h.bind(undefined, 'tr');
1126 export const track: IFactory = h.bind(undefined, 'track');
1127 export const u: IFactory = h.bind(undefined, 'u');
1128 export const ul: IFactory = h.bind(undefined, 'ul');
1129 export const var_: IFactory = h.bind(undefined, 'var');
1130 export const video: IFactory = h.bind(undefined, 'video');
1131 export const wbr: IFactory = h.bind(undefined, 'wbr');
1132 }
1133
1134 /**
1135 * DEPRECATED - pass the renderer arg to the h function instead
1136 *
1137 * Create a new "pass thru" virtual element node.
1138 *
1139 * @param tag - The tag name for the parent element.
1140 *
1141 * @param attrs - The attributes for the parent element, if any.
1142 *
1143 * @param renderer - an object with render and unrender functions, if any.
1144 *
1145 * @returns A new "pass thru" virtual element node for the given parameters.
1146 *
1147 */
1148 export function hpass(
1149 tag: string,
1150 renderer?: VirtualElementPass.IRenderer
1151 ): VirtualElementPass;
1152 export function hpass(
1153 tag: string,
1154 attrs: ElementAttrs,
1155 renderer?: VirtualElementPass.IRenderer
1156 ): VirtualElementPass;
1157 export function hpass(tag: string): VirtualElementPass {
1158 let attrs: ElementAttrs = {};
1159 let renderer: VirtualElementPass.IRenderer | null = null;
1160
1161 if (arguments.length === 2) {
1162 // eslint-disable-next-line prefer-rest-params
1163 const arg = arguments[1];
1164
1165 if ('render' in arg) {
1166 renderer = arg;
1167 } else {
1168 attrs = arg;
1169 }
1170 } else if (arguments.length === 3) {
1171 // eslint-disable-next-line prefer-rest-params
1172 attrs = arguments[1];
1173 // eslint-disable-next-line prefer-rest-params
1174 renderer = arguments[2];
1175 } else if (arguments.length > 3) {
1176 throw new Error('hpass() should be called with 1, 2, or 3 arguments');
1177 }
1178
1179 return new VirtualElementPass(tag, attrs, renderer);
1180 }
1181
1182 /**
1183 * The namespace for the virtual DOM rendering functions.
1184 */
1185 export namespace VirtualDOM {
1186 /**
1187 * Create a real DOM element from a virtual element node.
1188 *
1189 * @param node - The virtual element node to realize.
1190 *
1191 * @returns A new DOM element for the given virtual element node.
1192 *
1193 * #### Notes
1194 * This creates a brand new *real* DOM element with a structure which
1195 * matches the given virtual DOM node.
1196 *
1197 * If virtual diffing is desired, use the `render` function instead.
1198 */
1199 export function realize(node: VirtualText): Text;
1200 export function realize(node: VirtualElement): HTMLElement;
1201 export function realize(node: VirtualNode): HTMLElement | Text {
1202 return Private.createDOMNode(node);
1203 }
1204
1205 /**
1206 * Render virtual DOM content into a host element.
1207 *
1208 * @param content - The virtual DOM content to render.
1209 *
1210 * @param host - The host element for the rendered content.
1211 *
1212 * #### Notes
1213 * This renders the delta from the previous rendering. It assumes that
1214 * the content of the host element is not manipulated by external code.
1215 *
1216 * Providing `null` content will clear the rendering.
1217 *
1218 * Externally modifying the provided content or the host element will
1219 * result in undefined rendering behavior.
1220 */
1221 export function render(
1222 content: VirtualNode | ReadonlyArray<VirtualNode> | null,
1223 host: HTMLElement
1224 ): void {
1225 let oldContent = Private.hostMap.get(host) || [];
1226 let newContent = Private.asContentArray(content);
1227 Private.hostMap.set(host, newContent);
1228 Private.updateContent(host, oldContent, newContent);
1229 }
1230 }
1231
1232 /**
1233 * The namespace for the module implementation details.
1234 */
1235 namespace Private {
1236 /**
1237 * A weak mapping of host element to virtual DOM content.
1238 */
1239 export const hostMap = new WeakMap<HTMLElement, ReadonlyArray<VirtualNode>>();
1240
1241 /**
1242 * Cast a content value to a content array.
1243 */
1244 export function asContentArray(
1245 value: VirtualNode | ReadonlyArray<VirtualNode> | null
1246 ): ReadonlyArray<VirtualNode> {
1247 if (!value) {
1248 return [];
1249 }
1250 if (value instanceof Array) {
1251 return value as ReadonlyArray<VirtualNode>;
1252 }
1253 return [value as VirtualNode];
1254 }
1255
1256 /**
1257 * Create a new DOM element for a virtual node.
1258 */
1259 export function createDOMNode(node: VirtualText): Text;
1260 export function createDOMNode(node: VirtualElement): HTMLElement;
1261 export function createDOMNode(node: VirtualNode): HTMLElement | Text;
1262 export function createDOMNode(
1263 node: VirtualNode,
1264 host: HTMLElement | null
1265 ): HTMLElement | Text;
1266 export function createDOMNode(
1267 node: VirtualNode,
1268 host: HTMLElement | null,
1269 before: Node | null
1270 ): HTMLElement | Text;
1271 export function createDOMNode(node: VirtualNode): HTMLElement | Text {
1272 // eslint-disable-next-line prefer-rest-params
1273 let host = arguments[1] || null;
1274 // eslint-disable-next-line prefer-rest-params
1275 const before = arguments[2] || null;
1276
1277 if (host) {
1278 host.insertBefore(createDOMNode(node), before);
1279 } else {
1280 // Create a text node for a virtual text node.
1281 if (node.type === 'text') {
1282 return document.createTextNode(node.content);
1283 }
1284
1285 // Create the HTML element with the specified tag.
1286 host = document.createElement(node.tag);
1287
1288 // Add the attributes for the new element.
1289 addAttrs(host, node.attrs);
1290
1291 if (node.renderer) {
1292 node.renderer.render(host, {
1293 attrs: node.attrs,
1294 children: node.children
1295 });
1296 return host;
1297 }
1298
1299 // Recursively populate the element with child content.
1300 for (let i = 0, n = node.children.length; i < n; ++i) {
1301 createDOMNode(node.children[i], host);
1302 }
1303 }
1304
1305 return host;
1306 }
1307
1308 /**
1309 * Update a host element with the delta of the virtual content.
1310 *
1311 * This is the core "diff" algorithm. There is no explicit "patch"
1312 * phase. The host is patched at each step as the diff progresses.
1313 */
1314 export function updateContent(
1315 host: HTMLElement,
1316 oldContent: ReadonlyArray<VirtualNode>,
1317 newContent: ReadonlyArray<VirtualNode>
1318 ): void {
1319 // Bail early if the content is identical.
1320 if (oldContent === newContent) {
1321 return;
1322 }
1323
1324 // Collect the old keyed elems into a mapping.
1325 let oldKeyed = collectKeys(host, oldContent);
1326
1327 // Create a copy of the old content which can be modified in-place.
1328 let oldCopy = oldContent.slice();
1329
1330 // Update the host with the new content. The diff always proceeds
1331 // forward and never modifies a previously visited index. The old
1332 // copy array is modified in-place to reflect the changes made to
1333 // the host children. This causes the stale nodes to be pushed to
1334 // the end of the host node and removed at the end of the loop.
1335 let currElem = host.firstChild;
1336 let newCount = newContent.length;
1337 for (let i = 0; i < newCount; ++i) {
1338 // If the old content is exhausted, create a new node.
1339 if (i >= oldCopy.length) {
1340 createDOMNode(newContent[i], host);
1341 continue;
1342 }
1343
1344 // Lookup the old and new virtual nodes.
1345 let oldVNode = oldCopy[i];
1346 let newVNode = newContent[i];
1347
1348 // If both elements are identical, there is nothing to do.
1349 if (oldVNode === newVNode) {
1350 currElem = currElem!.nextSibling;
1351 continue;
1352 }
1353
1354 // Handle the simplest case of in-place text update first.
1355 if (oldVNode.type === 'text' && newVNode.type === 'text') {
1356 // Avoid spurious updates for performance.
1357 if (currElem!.textContent !== newVNode.content) {
1358 currElem!.textContent = newVNode.content;
1359 }
1360 currElem = currElem!.nextSibling;
1361 continue;
1362 }
1363
1364 // If the old or new node is a text node, the other node is now
1365 // known to be an element node, so create and insert a new node.
1366 if (oldVNode.type === 'text' || newVNode.type === 'text') {
1367 ArrayExt.insert(oldCopy, i, newVNode);
1368 createDOMNode(newVNode, host, currElem);
1369 continue;
1370 }
1371
1372 // If the old XOR new node has a custom renderer,
1373 // create and insert a new node.
1374 if (!oldVNode.renderer != !newVNode.renderer) {
1375 ArrayExt.insert(oldCopy, i, newVNode);
1376 createDOMNode(newVNode, host, currElem);
1377 continue;
1378 }
1379
1380 // At this point, both nodes are known to be element nodes.
1381
1382 // If the new elem is keyed, move an old keyed elem to the proper
1383 // location before proceeding with the diff. The search can start
1384 // at the current index, since the unmatched old keyed elems are
1385 // pushed forward in the old copy array.
1386 let newKey = newVNode.attrs.key;
1387 if (newKey && newKey in oldKeyed) {
1388 let pair = oldKeyed[newKey];
1389 if (pair.vNode !== oldVNode) {
1390 ArrayExt.move(oldCopy, oldCopy.indexOf(pair.vNode, i + 1), i);
1391 host.insertBefore(pair.element, currElem);
1392 oldVNode = pair.vNode;
1393 currElem = pair.element;
1394 }
1395 }
1396
1397 // If both elements are identical, there is nothing to do.
1398 if (oldVNode === newVNode) {
1399 currElem = currElem!.nextSibling;
1400 continue;
1401 }
1402
1403 // If the old elem is keyed and does not match the new elem key,
1404 // create a new node. This is necessary since the old keyed elem
1405 // may be matched at a later point in the diff.
1406 let oldKey = oldVNode.attrs.key;
1407 if (oldKey && oldKey !== newKey) {
1408 ArrayExt.insert(oldCopy, i, newVNode);
1409 createDOMNode(newVNode, host, currElem);
1410 continue;
1411 }
1412
1413 // If the tags are different, create a new node.
1414 if (oldVNode.tag !== newVNode.tag) {
1415 ArrayExt.insert(oldCopy, i, newVNode);
1416 createDOMNode(newVNode, host, currElem);
1417 continue;
1418 }
1419
1420 // At this point, the element can be updated in-place.
1421
1422 // Update the element attributes.
1423 updateAttrs(currElem as HTMLElement, oldVNode.attrs, newVNode.attrs);
1424
1425 // Update the element content.
1426 if (newVNode.renderer) {
1427 newVNode.renderer.render(currElem as HTMLElement, {
1428 attrs: newVNode.attrs,
1429 children: newVNode.children
1430 });
1431 } else {
1432 updateContent(
1433 currElem as HTMLElement,
1434 oldVNode.children,
1435 newVNode.children
1436 );
1437 }
1438
1439 // Step to the next sibling element.
1440 currElem = currElem!.nextSibling;
1441 }
1442
1443 // Cleanup stale DOM
1444 removeContent(host, oldCopy, newCount, true);
1445 }
1446
1447 /**
1448 * Handle cleanup of stale vdom and its associated DOM. The host node is
1449 * traversed recursively (in depth-first order), and any explicit cleanup
1450 * required by a child node is carried out when it is visited (eg if a node
1451 * has a custom renderer, the renderer.unrender function will be called).
1452 * Once the subtree beneath each child of host has been completely visited,
1453 * that child will be removed via a call to host.removeChild.
1454 */
1455 function removeContent(
1456 host: HTMLElement,
1457 oldContent: ReadonlyArray<VirtualNode>,
1458 newCount: number,
1459 _sentinel: boolean
1460 ) {
1461 // Dispose of the old nodes pushed to the end of the host.
1462 for (let i = oldContent.length - 1; i >= newCount; --i) {
1463 const oldNode = oldContent[i];
1464 const child = (
1465 _sentinel ? host.lastChild : host.childNodes[i]
1466 ) as HTMLElement;
1467
1468 // recursively clean up host children
1469 if (oldNode.type === 'text') {
1470 // pass
1471 } else if (oldNode.renderer && oldNode.renderer.unrender) {
1472 oldNode.renderer.unrender(child!, {
1473 attrs: oldNode.attrs,
1474 children: oldNode.children
1475 });
1476 } else {
1477 removeContent(child!, oldNode.children, 0, false);
1478 }
1479
1480 if (_sentinel) {
1481 host.removeChild(child!);
1482 }
1483 }
1484 }
1485
1486 /**
1487 * A set of special-cased attribute names.
1488 */
1489 const specialAttrs = {
1490 key: true,
1491 className: true,
1492 htmlFor: true,
1493 dataset: true,
1494 style: true
1495 };
1496
1497 /**
1498 * Add element attributes to a newly created HTML element.
1499 */
1500 function addAttrs(element: HTMLElement, attrs: ElementAttrs): void {
1501 // Add the inline event listeners and node attributes.
1502 for (let name in attrs) {
1503 if (name in specialAttrs) {
1504 continue;
1505 }
1506 if (name.substr(0, 2) === 'on') {
1507 (element as any)[name] = (attrs as any)[name];
1508 } else {
1509 element.setAttribute(name, (attrs as any)[name]);
1510 }
1511 }
1512
1513 // Add the element `class` attribute.
1514 if (attrs.className !== undefined) {
1515 element.setAttribute('class', attrs.className);
1516 }
1517
1518 // Add the element `for` attribute.
1519 if (attrs.htmlFor !== undefined) {
1520 element.setAttribute('for', attrs.htmlFor);
1521 }
1522
1523 // Add the dataset values.
1524 if (attrs.dataset) {
1525 addDataset(element, attrs.dataset);
1526 }
1527
1528 // Add the inline styles.
1529 if (attrs.style) {
1530 addStyle(element, attrs.style);
1531 }
1532 }
1533
1534 /**
1535 * Update the element attributes of an HTML element.
1536 */
1537 function updateAttrs(
1538 element: HTMLElement,
1539 oldAttrs: ElementAttrs,
1540 newAttrs: ElementAttrs
1541 ): void {
1542 // Do nothing if the attrs are the same object.
1543 if (oldAttrs === newAttrs) {
1544 return;
1545 }
1546
1547 // Setup the strongly typed loop variable.
1548 let name: keyof ElementAttrs;
1549
1550 // Remove attributes and listeners which no longer exist.
1551 for (name in oldAttrs) {
1552 if (name in specialAttrs || name in newAttrs) {
1553 continue;
1554 }
1555 if (name.substr(0, 2) === 'on') {
1556 (element as any)[name] = null;
1557 } else {
1558 element.removeAttribute(name);
1559 }
1560 }
1561
1562 // Add and update new and existing attributes and listeners.
1563 for (name in newAttrs) {
1564 if (name in specialAttrs || oldAttrs[name] === newAttrs[name]) {
1565 continue;
1566 }
1567 if (name.substr(0, 2) === 'on') {
1568 (element as any)[name] = (newAttrs as any)[name];
1569 } else {
1570 element.setAttribute(name, (newAttrs as any)[name]);
1571 }
1572 }
1573
1574 // Update the element `class` attribute.
1575 if (oldAttrs.className !== newAttrs.className) {
1576 if (newAttrs.className !== undefined) {
1577 element.setAttribute('class', newAttrs.className);
1578 } else {
1579 element.removeAttribute('class');
1580 }
1581 }
1582
1583 // Add the element `for` attribute.
1584 if (oldAttrs.htmlFor !== newAttrs.htmlFor) {
1585 if (newAttrs.htmlFor !== undefined) {
1586 element.setAttribute('for', newAttrs.htmlFor);
1587 } else {
1588 element.removeAttribute('for');
1589 }
1590 }
1591
1592 // Update the dataset values.
1593 if (oldAttrs.dataset !== newAttrs.dataset) {
1594 updateDataset(element, oldAttrs.dataset || {}, newAttrs.dataset || {});
1595 }
1596
1597 // Update the inline styles.
1598 if (oldAttrs.style !== newAttrs.style) {
1599 updateStyle(element, oldAttrs.style || {}, newAttrs.style || {});
1600 }
1601 }
1602
1603 /**
1604 * Add dataset values to a newly created HTML element.
1605 */
1606 function addDataset(element: HTMLElement, dataset: ElementDataset): void {
1607 for (let name in dataset) {
1608 element.setAttribute(`data-${name}`, dataset[name]);
1609 }
1610 }
1611
1612 /**
1613 * Update the dataset values of an HTML element.
1614 */
1615 function updateDataset(
1616 element: HTMLElement,
1617 oldDataset: ElementDataset,
1618 newDataset: ElementDataset
1619 ): void {
1620 for (let name in oldDataset) {
1621 if (!(name in newDataset)) {
1622 element.removeAttribute(`data-${name}`);
1623 }
1624 }
1625 for (let name in newDataset) {
1626 if (oldDataset[name] !== newDataset[name]) {
1627 element.setAttribute(`data-${name}`, newDataset[name]);
1628 }
1629 }
1630 }
1631
1632 /**
1633 * Add inline style values to a newly created HTML element.
1634 */
1635 function addStyle(element: HTMLElement, style: ElementInlineStyle): void {
1636 let elemStyle = element.style;
1637 let name: keyof ElementInlineStyle;
1638 for (name in style) {
1639 (elemStyle as any)[name] = style[name];
1640 }
1641 }
1642
1643 /**
1644 * Update the inline style values of an HTML element.
1645 */
1646 function updateStyle(
1647 element: HTMLElement,
1648 oldStyle: ElementInlineStyle,
1649 newStyle: ElementInlineStyle
1650 ): void {
1651 let elemStyle = element.style;
1652 let name: keyof ElementInlineStyle;
1653 for (name in oldStyle) {
1654 if (!(name in newStyle)) {
1655 (elemStyle as any)[name] = '';
1656 }
1657 }
1658 for (name in newStyle) {
1659 if (oldStyle[name] !== newStyle[name]) {
1660 (elemStyle as any)[name] = newStyle[name];
1661 }
1662 }
1663 }
1664
1665 /**
1666 * A mapping of string key to pair of element and rendered node.
1667 */
1668 type KeyMap = {
1669 [key: string]: { vNode: VirtualElement; element: HTMLElement };
1670 };
1671
1672 /**
1673 * Collect a mapping of keyed elements for the host content.
1674 */
1675 function collectKeys(
1676 host: HTMLElement,
1677 content: ReadonlyArray<VirtualNode>
1678 ): KeyMap {
1679 let node = host.firstChild;
1680 let keyMap: KeyMap = Object.create(null);
1681 for (let vNode of content) {
1682 if (vNode.type === 'element' && vNode.attrs.key) {
1683 keyMap[vNode.attrs.key] = { vNode, element: node as HTMLElement };
1684 }
1685 node = node!.nextSibling;
1686 }
1687 return keyMap;
1688 }
1689 }