This repository has been archived by the owner on Jun 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
template.js
1602 lines (1452 loc) · 43.2 KB
/
template.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
/**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md.
*/
/**
* @module ui/template
*/
/* global document */
import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
import mix from '@ckeditor/ckeditor5-utils/src/mix';
import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
import Collection from '@ckeditor/ckeditor5-utils/src/collection';
import View from './view';
import ViewCollection from './viewcollection';
import cloneDeepWith from '@ckeditor/ckeditor5-utils/src/lib/lodash/cloneDeepWith';
import isObject from '@ckeditor/ckeditor5-utils/src/lib/lodash/isObject';
import log from '@ckeditor/ckeditor5-utils/src/log';
const xhtmlNs = 'http://www.w3.org/1999/xhtml';
/**
* A basic Template class. It renders DOM HTMLElement or Text from {@link module:ui/template~TemplateDefinition} and supports
* element attributes, children, bindings to {@link module:utils/observablemixin~ObservableMixin} instances and DOM events
* propagation. For example:
*
* new Template( {
* tag: 'p',
* attributes: {
* class: 'foo',
* style: {
* backgroundColor: 'yellow'
* }
* },
* children: [
* 'A paragraph.'
* ]
* } ).render();
*
* will render the following HTMLElement:
*
* <p class="foo" style="background-color: yellow;">A paragraph.</p>
*
* See {@link module:ui/template~TemplateDefinition} to know more about templates and complex template definitions.
*
* @mixes module:utils/emittermixin~EmitterMixin
*/
export default class Template {
/**
* Creates an instance of the {@link ~Template} class.
*
* @param {module:ui/template~TemplateDefinition} def The definition of the template.
*/
constructor( def ) {
Object.assign( this, normalize( clone( def ) ) );
/**
* Indicates whether this particular Template instance has been
* {@link #render rendered}.
*
* @readonly
* @protected
* @member {Boolean}
*/
this._isRendered = false;
/**
* Tag of this template, i.e. `div`, indicating that the instance will render
* to an HTMLElement.
*
* @member {String} #tag
*/
/**
* Text of this template, indicating that the instance will render to a DOM Text.
*
* @member {Array.<String|module:ui/template~TemplateValueSchema>} #text
*/
/**
* Attributes of this template, i.e. `{ id: [ 'ck-id' ] }`, corresponding with
* HTML attributes on HTMLElement.
*
* Note: Only when {@link #tag} is defined.
*
* @member {Object} #attributes
*/
/**
* Children of this template; sub–templates. Each one is an independent
* instance of {@link ~Template}.
*
* Note: Only when {@link #tag} is defined.
*
* @member {module:utils/collection~Collection.<module:ui/template~Template>} #children
*/
/**
* DOM event listeners of this template.
*
* @member {Object} #eventListeners
*/
/**
* Data used by {@link #revert} method to restore a node
* to its original state.
*
* See: {@link #apply}.
*
* @readonly
* @protected
* @member {module:ui/template~RenderData}
*/
this._revertData = null;
}
/**
* Renders a DOM Node (`HTMLElement` or `Text`) out of the template.
*
* @see #apply
*
* @returns {HTMLElement|Text}
*/
render() {
const node = this._renderNode( {
intoFragment: true
} );
this._isRendered = true;
return node;
}
/**
* Applies the template to an existing DOM Node, either `HTMLElement` or `Text`.
*
* **Note:** No new DOM nodes (HTMLElement or Text) will be created. Applying extends attributes
* ({@link module:ui/template~TemplateDefinition attributes}) and listeners ({@link module:ui/template~TemplateDefinition on}) only.
*
* **Note:** Existing "class" and "style" attributes are extended when a template
* is applied to a Node, while other attributes and `textContent` are overridden.
*
* **Note:** The process of applying a template can be easily reverted using
* {@link module:ui/template~Template#revert} method.
*
* const element = document.createElement( 'div' );
* const bind = Template.bind( observableInstance, emitterInstance );
*
* new Template( {
* attrs: {
* id: 'first-div',
* class: bind.to( 'divClass' )
* },
* on: {
* click: bind( 'elementClicked' ) // Will be fired by the observableInstance.
* }
* children: [
* 'Div text.'
* ]
* } ).apply( element );
*
* element.outerHTML == "<div id="first-div" class="my-div">Div text.</div>"
*
* @see module:ui/template~Template#render
* @see module:ui/template~Template#revert
* @param {Node} node Root node for the template to apply.
*/
apply( node ) {
this._revertData = getEmptyRevertData();
this._renderNode( {
node,
isApplying: true,
revertData: this._revertData
} );
return node;
}
/**
* Reverts a template {@link module:ui/template~Template#apply applied} to a DOM Node.
*
* @param {Node} node Root node for the template to revert. In most cases, it's the same node
* that {@link module:ui/template~Template#apply} has used.
*/
revert( node ) {
if ( !this._revertData ) {
/**
* Attempting reverting a template which has not been applied yet.
*
* @error ui-template-revert-not-applied
*/
throw new CKEditorError( 'ui-template-revert-not-applied: Attempting reverting a template which has not been applied yet.' );
}
this._revertTemplateFromNode( node, this._revertData );
}
/**
* An entry point to the interface which allows binding DOM nodes to {@link module:utils/observablemixin~ObservableMixin}.
* There are two types of bindings:
*
* * `HTMLElement` attributes or Text Node `textContent` can be synchronized with {@link module:utils/observablemixin~ObservableMixin}
* instance attributes. See {@link module:ui/template~BindChain#to} and {@link module:ui/template~BindChain#if}.
*
* * DOM events fired on `HTMLElement` can be propagated through {@link module:utils/observablemixin~ObservableMixin}.
* See {@link module:ui/template~BindChain#to}.
*
* @param {module:utils/observablemixin~ObservableMixin} observable An instance of ObservableMixin class.
* @param {module:utils/emittermixin~EmitterMixin} emitter An instance of `Emitter` class. It listens
* to `observable` attribute changes and DOM Events, depending on the binding. Usually {@link module:ui/view~View} instance.
* @returns {module:ui/template~BindChain}
*/
static bind( observable, emitter ) {
return {
to( eventNameOrFunctionOrAttribute, callback ) {
return new TemplateToBinding( {
eventNameOrFunction: eventNameOrFunctionOrAttribute,
attribute: eventNameOrFunctionOrAttribute,
observable, emitter, callback
} );
},
if( attribute, valueIfTrue, callback ) {
return new TemplateIfBinding( {
observable, emitter, attribute, valueIfTrue, callback
} );
}
};
}
/**
* Extends {@link module:ui/template~Template} instance with additional content from {@link module:ui/template~TemplateDefinition}.
*
* const bind = Template.bind( observable, emitterInstance );
* const instance = new Template( {
* tag: 'p',
* attributes: {
* class: 'a',
* data-x: bind.to( 'foo' )
* },
* children: [
* {
* tag: 'span',
* attributes: {
* class: 'b'
* },
* children: [
* 'Span'
* ]
* }
* ]
* } );
*
* // Instance-level extension.
* Template.extend( instance, {
* attributes: {
* class: 'b',
* data-x: bind.to( 'bar' )
* },
* children: [
* {
* attributes: {
* class: 'c'
* }
* }
* ]
* } );
*
* // Child extension.
* Template.extend( instance.children.get( 0 ), {
* attributes: {
* class: 'd'
* }
* } );
*
* the `instance.render().outerHTML` is
*
* <p class="a b" data-x="{ observable.foo } { observable.bar }">
* <span class="b c d">Span</span>
* </p>
*
* @param {module:ui/template~Template} template Existing Template instance to be extended.
* @param {module:ui/template~TemplateDefinition} def An extension to existing an template instance.
*/
static extend( template, def ) {
if ( template._isRendered ) {
/**
* Extending a template after rendering may not work as expected. To make sure
* the {@link #extend extending} works for the rendered element, perform it
* before {@link #render} is called.
*
* @error template-extend-render
*/
log.warn( 'template-extend-render: Attempting to extend a template which has already been rendered.' );
}
extendTemplate( template, normalize( clone( def ) ) );
}
/**
* Renders a DOM Node (either `HTMLElement` or `Text`) out of the template.
*
* @protected
* @param {module:ui/template~RenderData} data Rendering data.
*/
_renderNode( data ) {
let isInvalid;
if ( data.node ) {
// When applying, a definition cannot have "tag" and "text" at the same time.
isInvalid = this.tag && this.text;
} else {
// When rendering, a definition must have either "tag" or "text": XOR( this.tag, this.text ).
isInvalid = this.tag ? this.text : !this.text;
}
if ( isInvalid ) {
/**
* Node definition cannot have "tag" and "text" properties at the same time.
* Node definition must have either "tag" or "text" when rendering new Node.
*
* @error ui-template-wrong-syntax
*/
throw new CKEditorError(
'ui-template-wrong-syntax: Node definition must have either "tag" or "text" when rendering new Node.'
);
}
if ( this.text ) {
return this._renderText( data );
} else {
return this._renderElement( data );
}
}
/**
* Renders an `HTMLElement` out of the template.
*
* @protected
* @param {module:ui/template~RenderData} data Rendering data.
*/
_renderElement( data ) {
let node = data.node;
if ( !node ) {
node = data.node = document.createElementNS( this.ns || xhtmlNs, this.tag );
}
this._renderAttributes( data );
this._renderElementChildren( data );
this._setUpListeners( data );
return node;
}
/**
* Renders a `Text` node out of {@link module:ui/template~Template#text}.
*
* @protected
* @param {module:ui/template~RenderData} data Rendering data.
*/
_renderText( data ) {
let node = data.node;
// Save the original textContent to revert it in #revert().
if ( node ) {
data.revertData.text = node.textContent;
} else {
node = data.node = document.createTextNode( '' );
}
// Check if this Text Node is bound to Observable. Cases:
//
// text: [ Template.bind( ... ).to( ... ) ]
//
// text: [
// 'foo',
// Template.bind( ... ).to( ... ),
// ...
// ]
//
if ( hasTemplateBinding( this.text ) ) {
this._bindToObservable( {
schema: this.text,
updater: getTextUpdater( node ),
data
} );
}
// Simply set text. Cases:
//
// text: [ 'all', 'are', 'static' ]
//
// text: [ 'foo' ]
//
else {
node.textContent = this.text.join( '' );
}
return node;
}
/**
* Renders an `HTMLElement` attributes out of {@link module:ui/template~Template#attributes}.
*
* @protected
* @param {module:ui/template~RenderData} data Rendering data.
*/
_renderAttributes( data ) {
let attrName, attrValue, domAttrValue, attrNs;
if ( !this.attributes ) {
return;
}
const node = data.node;
const revertData = data.revertData;
for ( attrName in this.attributes ) {
// Current attribute value in DOM.
domAttrValue = node.getAttribute( attrName );
// The value to be set.
attrValue = this.attributes[ attrName ];
// Save revert data.
if ( revertData ) {
revertData.attributes[ attrName ] = domAttrValue;
}
// Detect custom namespace:
//
// class: {
// ns: 'abc',
// value: Template.bind( ... ).to( ... )
// }
//
attrNs = ( isObject( attrValue[ 0 ] ) && attrValue[ 0 ].ns ) ? attrValue[ 0 ].ns : null;
// Activate binding if one is found. Cases:
//
// class: [
// Template.bind( ... ).to( ... )
// ]
//
// class: [
// 'bar',
// Template.bind( ... ).to( ... ),
// 'baz'
// ]
//
// class: {
// ns: 'abc',
// value: Template.bind( ... ).to( ... )
// }
//
if ( hasTemplateBinding( attrValue ) ) {
// Normalize attributes with additional data like namespace:
//
// class: {
// ns: 'abc',
// value: [ ... ]
// }
//
const valueToBind = attrNs ? attrValue[ 0 ].value : attrValue;
// Extend the original value of attributes like "style" and "class",
// don't override them.
if ( revertData && shouldExtend( attrName ) ) {
valueToBind.unshift( domAttrValue );
}
this._bindToObservable( {
schema: valueToBind,
updater: getAttributeUpdater( node, attrName, attrNs ),
data
} );
}
// Style attribute could be an Object so it needs to be parsed in a specific way.
//
// style: {
// width: '100px',
// height: Template.bind( ... ).to( ... )
// }
//
else if ( attrName == 'style' && typeof attrValue[ 0 ] !== 'string' ) {
this._renderStyleAttribute( attrValue[ 0 ], data );
}
// Otherwise simply set the static attribute:
//
// class: [ 'foo' ]
//
// class: [ 'all', 'are', 'static' ]
//
// class: [
// {
// ns: 'abc',
// value: [ 'foo' ]
// }
// ]
//
else {
// Extend the original value of attributes like "style" and "class",
// don't override them.
if ( revertData && domAttrValue && shouldExtend( attrName ) ) {
attrValue.unshift( domAttrValue );
}
attrValue = attrValue
// Retrieve "values" from:
//
// class: [
// {
// ns: 'abc',
// value: [ ... ]
// }
// ]
//
.map( val => val ? ( val.value || val ) : val )
// Flatten the array.
.reduce( ( prev, next ) => prev.concat( next ), [] )
// Convert into string.
.reduce( arrayValueReducer, '' );
if ( !isFalsy( attrValue ) ) {
node.setAttributeNS( attrNs, attrName, attrValue );
}
}
}
}
/**
* Renders `style` attribute of an `HTMLElement` based on {@link module:ui/template~Template#attributes}.
*
* Style attribute is an {Object} with static values:
*
* attributes: {
* style: {
* color: 'red'
* }
* }
*
* or values bound to {@link module:ui/model~Model} properties:
*
* attributes: {
* style: {
* color: bind.to( ... )
* }
* }
*
* Note: `style` attribute is rendered without setting the namespace. It does not seem to be
* needed.
*
* @private
* @param {Object} styles Styles located in `attributes.style` of {@link module:ui/template~TemplateDefinition}.
* @param {module:ui/template~RenderData} data Rendering data.
*/
_renderStyleAttribute( styles, data ) {
const node = data.node;
for ( const styleName in styles ) {
const styleValue = styles[ styleName ];
// Cases:
//
// style: {
// color: bind.to( 'attribute' )
// }
//
if ( hasTemplateBinding( styleValue ) ) {
this._bindToObservable( {
schema: [ styleValue ],
updater: getStyleUpdater( node, styleName ),
data
} );
}
// Cases:
//
// style: {
// color: 'red'
// }
//
else {
node.style[ styleName ] = styleValue;
}
}
}
/**
* Recursively renders `HTMLElement` children from {@link module:ui/template~Template#children}.
*
* @protected
* @param {module:ui/template~RenderData} data Rendering data.
*/
_renderElementChildren( data ) {
const node = data.node;
const container = data.intoFragment ? document.createDocumentFragment() : node;
const isApplying = data.isApplying;
let childIndex = 0;
for ( const child of this.children ) {
if ( isViewCollection( child ) ) {
if ( !isApplying ) {
child.setParent( node );
for ( const view of child ) {
container.appendChild( view.element );
}
}
} else if ( isView( child ) ) {
if ( !isApplying ) {
container.appendChild( child.element );
}
} else {
if ( isApplying ) {
const revertData = data.revertData;
const childRevertData = getEmptyRevertData();
revertData.children.push( childRevertData );
child._renderNode( {
node: container.childNodes[ childIndex++ ],
isApplying: true,
revertData: childRevertData
} );
} else {
container.appendChild( child.render() );
}
}
}
if ( data.intoFragment ) {
node.appendChild( container );
}
}
/**
* Activates `on` listeners in the {@link module:ui/template~TemplateDefinition}
* on a passed `HTMLElement`.
*
* @protected
* @param {module:ui/template~RenderData} data Rendering data.
*/
_setUpListeners( data ) {
if ( !this.eventListeners ) {
return;
}
for ( const key in this.eventListeners ) {
const revertBindings = this.eventListeners[ key ].map( schemaItem => {
const [ domEvtName, domSelector ] = key.split( '@' );
return schemaItem.activateDomEventListener( domEvtName, domSelector, data );
} );
if ( data.revertData ) {
data.revertData.bindings.push( revertBindings );
}
}
}
/**
* For given {@link module:ui/template~TemplateValueSchema} containing {@link module:ui/template~TemplateBinding} it activates the
* binding and sets its initial value.
*
* Note: {@link module:ui/template~TemplateValueSchema} can be for HTMLElement attributes or Text Node `textContent`.
*
* @protected
* @param {Object} options Binding options.
* @param {module:ui/template~TemplateValueSchema} options.schema
* @param {Function} options.updater A function which updates DOM (like attribute or text).
* @param {module:ui/template~RenderData} options.data Rendering data.
*/
_bindToObservable( { schema, updater, data } ) {
const revertData = data.revertData;
// Set initial values.
syncValueSchemaValue( schema, updater, data );
const revertBindings = schema
// Filter "falsy" (false, undefined, null, '') value schema components out.
.filter( item => !isFalsy( item ) )
// Filter inactive bindings from schema, like static strings ('foo'), numbers (42), etc.
.filter( item => item.observable )
// Once only the actual binding are left, let the emitter listen to observable change:attribute event.
// TODO: Reduce the number of listeners attached as many bindings may listen
// to the same observable attribute.
.map( templateBinding => templateBinding.activateAttributeListener( schema, updater, data ) );
if ( revertData ) {
revertData.bindings.push( revertBindings );
}
}
/**
* Reverts {@link module:ui/template~RenderData#revertData template data} from a node to
* return it to the the original state.
*
* @protected
* @param {HTMLElement|Text} node A node to be reverted.
* @param {module:ui/template~RenderData#revertData} revertData Stores information about
* what changes have been made by {@link #apply} to the node.
*/
_revertTemplateFromNode( node, revertData ) {
for ( const binding of revertData.bindings ) {
// Each binding may consist of several observable+observable#attribute.
// like the following has 2:
//
// class: [
// 'x',
// bind.to( 'foo' ),
// 'y',
// bind.to( 'bar' )
// ]
//
for ( const revertBinding of binding ) {
revertBinding();
}
}
if ( revertData.text ) {
node.textContent = revertData.text;
return;
}
for ( const attrName in revertData.attributes ) {
const attrValue = revertData.attributes[ attrName ];
// When the attribute has **not** been set before #apply().
if ( attrValue === null ) {
node.removeAttribute( attrName );
} else {
node.setAttribute( attrName, attrValue );
}
}
for ( let i = 0; i < revertData.children.length; ++i ) {
this._revertTemplateFromNode( node.childNodes[ i ], revertData.children[ i ] );
}
}
}
mix( Template, EmitterMixin );
/**
* Describes a binding created by {@link module:ui/template~Template.bind} interface.
*
* @protected
*/
export class TemplateBinding {
/**
* Creates an instance of the {@link module:ui/template~TemplateBinding} class.
*
* @param {module:ui/template~TemplateDefinition} def The definition of the binding.
*/
constructor( def ) {
Object.assign( this, def );
/**
* An observable instance of the binding. It provides the attribute
* with the value or passes the event when a corresponding DOM event is fired.
*
* @member {module:utils/observablemixin~ObservableMixin} module:ui/template~TemplateBinding#observable
*/
/**
* An {@link module:utils/emittermixin~EmitterMixin} instance used by the binding
* to (either):
*
* * listen to the attribute change in the {@link module:ui/template~TemplateBinding#observable},
* * listen to the event in the DOM.
*
* @member {module:utils/emittermixin~EmitterMixin} module:ui/template~TemplateBinding#emitter
*/
/**
* The name of the attribute of {@link module:ui/template~TemplateBinding#observable} which is observed.
*
* @member {String} module:ui/template~TemplateBinding#attribute
*/
/**
* A custom function to process the value of {@link module:ui/template~TemplateBinding#attribute}.
*
* @member {Function} [module:ui/template~TemplateBinding#callback]
*/
}
/**
* Returns the value of the binding, which is the value of {@link module:ui/template~TemplateBinding#attribute} in
* {@link module:ui/template~TemplateBinding#observable}.
*
* @param {Node} [node] A native DOM node, passed to the custom {@link module:ui/template~TemplateBinding#callback}.
* @returns {*} The value of {@link module:ui/template~TemplateBinding#attribute} in
* {@link module:ui/template~TemplateBinding#observable}.
*/
getValue( node ) {
const value = this.observable[ this.attribute ];
return this.callback ? this.callback( value, node ) : value;
}
/**
* Activates the listener for the changes of {@link module:ui/template~TemplateBinding#attribute} in
* {@link module:ui/template~TemplateBinding#observable}, which then updates the DOM with the aggregated
* value of {@link module:ui/template~TemplateValueSchema}.
*
* For instance, the `class` attribute of the `Template` element can be be bound to
* the observable `foo` attribute in `ObservableMixin` instance.
*
* @param {module:ui/template~TemplateValueSchema} schema A full schema to generate an attribute or text in DOM.
* @param {Function} updater A DOM updater function used to update native DOM attribute or text.
* @param {module:ui/template~RenderData} data Rendering data.
* @returns {Function} A function to sever the listener binding.
*/
activateAttributeListener( schema, updater, data ) {
const callback = () => syncValueSchemaValue( schema, updater, data );
this.emitter.listenTo( this.observable, 'change:' + this.attribute, callback );
// Allows revert of the listener.
return () => {
this.emitter.stopListening( this.observable, 'change:' + this.attribute, callback );
};
}
}
/**
* Describes either:
*
* * a binding to {@link module:utils/observablemixin~ObservableMixin}
* * or a native DOM event binding
*
* created by {@link module:ui/template~BindChain#to} method.
*
* @protected
*/
export class TemplateToBinding extends TemplateBinding {
/**
* Activates the listener for the native DOM event, which when fired, is propagated by
* the {@link module:ui/template~TemplateBinding#emitter}.
*
* @param {String} domEvtName A name of the native DOM event.
* @param {String} domSelector A selector in DOM to filter delegated events.
* @param {module:ui/template~RenderData} data Rendering data.
* @returns {Function} A function to sever the listener binding.
*/
activateDomEventListener( domEvtName, domSelector, data ) {
const callback = ( evt, domEvt ) => {
if ( !domSelector || domEvt.target.matches( domSelector ) ) {
if ( typeof this.eventNameOrFunction == 'function' ) {
this.eventNameOrFunction( domEvt );
} else {
this.observable.fire( this.eventNameOrFunction, domEvt );
}
}
};
this.emitter.listenTo( data.node, domEvtName, callback );
// Allows revert of the listener.
return () => {
this.emitter.stopListening( data.node, domEvtName, callback );
};
}
}
/**
* Describes a binding to {@link module:utils/observablemixin~ObservableMixin} created by {@link module:ui/template~BindChain#if}
* method.
*
* @protected
*/
export class TemplateIfBinding extends TemplateBinding {
/**
* @inheritDoc
*/
getValue( node ) {
const value = super.getValue( node );
return isFalsy( value ) ? false : ( this.valueIfTrue || true );
}
/**
* The value of the DOM attribute/text to be set if the {@link module:ui/template~TemplateBinding#attribute} in
* {@link module:ui/template~TemplateBinding#observable} is `true`.
*
* @member {String} [module:ui/template~TemplateIfBinding#valueIfTrue]
*/
}
// Checks whether given {@link module:ui/template~TemplateValueSchema} contains a
// {@link module:ui/template~TemplateBinding}.
//
// @param {module:ui/template~TemplateValueSchema} schema
// @returns {Boolean}
function hasTemplateBinding( schema ) {
if ( !schema ) {
return false;
}
// Normalize attributes with additional data like namespace:
//
// class: {
// ns: 'abc',
// value: [ ... ]
// }
//
if ( schema.value ) {
schema = schema.value;
}
if ( Array.isArray( schema ) ) {
return schema.some( hasTemplateBinding );
} else if ( schema instanceof TemplateBinding ) {
return true;
}
return false;
}
// Assembles the value using {@link module:ui/template~TemplateValueSchema} and stores it in a form of
// an Array. Each entry of an Array corresponds to one of {@link module:ui/template~TemplateValueSchema}
// items.
//
// @param {module:ui/template~TemplateValueSchema} schema
// @param {Node} node DOM Node updated when {@link module:utils/observablemixin~ObservableMixin} changes.
// @return {Array}
function getValueSchemaValue( schema, node ) {
return schema.map( schemaItem => {
// Process {@link module:ui/template~TemplateBinding} bindings.
if ( schemaItem instanceof TemplateBinding ) {
return schemaItem.getValue( node );
}
// All static values like strings, numbers, and "falsy" values (false, null, undefined, '', etc.) just pass.
return schemaItem;
} );
}
// A function executed each time bound Observable attribute changes, which updates DOM with a value
// constructed from {@link module:ui/template~TemplateValueSchema}.
//
// @param {module:ui/template~TemplateValueSchema} schema
// @param {Function} updater A function which updates DOM (like attribute or text).
// @param {Node} node DOM Node updated when {@link module:utils/observablemixin~ObservableMixin} changes.
function syncValueSchemaValue( schema, updater, { node } ) {
let value = getValueSchemaValue( schema, node );
// Check if schema is a single Template.bind.if, like:
//
// class: Template.bind.if( 'foo' )
//
if ( schema.length == 1 && schema[ 0 ] instanceof TemplateIfBinding ) {
value = value[ 0 ];
} else {
value = value.reduce( arrayValueReducer, '' );
}
if ( isFalsy( value ) ) {
updater.remove();
} else {
updater.set( value );
}
}
// Returns an object consisting of `set` and `remove` functions, which
// can be used in the context of DOM Node to set or reset `textContent`.
// @see module:ui/view~View#_bindToObservable
//
// @param {Node} node DOM Node to be modified.
// @returns {Object}
function getTextUpdater( node ) {
return {
set( value ) {
node.textContent = value;
},
remove() {
node.textContent = '';
}
};
}
// Returns an object consisting of `set` and `remove` functions, which
// can be used in the context of DOM Node to set or reset an attribute.
// @see module:ui/view~View#_bindToObservable
//
// @param {Node} node DOM Node to be modified.
// @param {String} attrName Name of the attribute to be modified.
// @param {String} [ns=null] Namespace to use.
// @returns {Object}
function getAttributeUpdater( el, attrName, ns ) {
return {