template.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module ui/template
  7. */
  8. /* global document */
  9. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  10. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  11. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  12. import View from './view';
  13. import ViewCollection from './viewcollection';
  14. import cloneDeepWith from '@ckeditor/ckeditor5-utils/src/lib/lodash/cloneDeepWith';
  15. import isObject from '@ckeditor/ckeditor5-utils/src/lib/lodash/isObject';
  16. import isDomNode from '@ckeditor/ckeditor5-utils/src/dom/isdomnode';
  17. import log from '@ckeditor/ckeditor5-utils/src/log';
  18. const xhtmlNs = 'http://www.w3.org/1999/xhtml';
  19. /**
  20. * A basic Template class. It renders a DOM HTML element or text from a
  21. * {@link module:ui/template~TemplateDefinition definition} and supports element attributes, children,
  22. * bindings to {@link module:utils/observablemixin~Observable observables} and DOM event propagation.
  23. *
  24. * A simple template can look like this:
  25. *
  26. * const bind = Template.bind( observable, emitter );
  27. *
  28. * new Template( {
  29. * tag: 'p',
  30. * attributes: {
  31. * class: 'foo',
  32. * style: {
  33. * backgroundColor: 'yellow'
  34. * }
  35. * },
  36. * on: {
  37. * click: bind.to( 'clicked' )
  38. * }
  39. * children: [
  40. * 'A paragraph.'
  41. * ]
  42. * } ).render();
  43. *
  44. * and it will render the following HTML element:
  45. *
  46. * <p class="foo" style="background-color: yellow;">A paragraph.</p>
  47. *
  48. * Additionally, the `observable` will always fire `clicked` upon clicking `<p>` in the DOM.
  49. *
  50. * See {@link module:ui/template~TemplateDefinition} to know more about templates and complex
  51. * template definitions.
  52. *
  53. * @mixes module:utils/emittermixin~EmitterMixin
  54. */
  55. export default class Template {
  56. /**
  57. * Creates an instance of the {@link ~Template} class.
  58. *
  59. * @param {module:ui/template~TemplateDefinition} def The definition of the template.
  60. */
  61. constructor( def ) {
  62. Object.assign( this, normalize( clone( def ) ) );
  63. /**
  64. * Indicates whether this particular Template instance has been
  65. * {@link #render rendered}.
  66. *
  67. * @readonly
  68. * @protected
  69. * @member {Boolean}
  70. */
  71. this._isRendered = false;
  72. /**
  73. * The tag (`tagName`) of this template, e.g. `div`. It also indicates that the template
  74. * renders to an HTML element.
  75. *
  76. * @member {String} #tag
  77. */
  78. /**
  79. * The text of the template. It also indicates that the template renders to a DOM text node.
  80. *
  81. * @member {Array.<String|module:ui/template~TemplateValueSchema>} #text
  82. */
  83. /**
  84. * The attributes of the template, e.g. `{ id: [ 'ck-id' ] }`, corresponding with
  85. * the attributes of an HTML element.
  86. *
  87. * **Note**: This property only makes sense when {@link #tag} is defined.
  88. *
  89. * @member {Object} #attributes
  90. */
  91. /**
  92. * The children of the template. They can be either:
  93. * * independent instances of {@link ~Template} (sub–templates),
  94. * * native DOM Nodes.
  95. *
  96. * **Note**: This property only makes sense when {@link #tag} is defined.
  97. *
  98. * @member {Array.<module:ui/template~Template|Node>} #children
  99. */
  100. /**
  101. * The DOM event listeners of the template.
  102. *
  103. * @member {Object} #eventListeners
  104. */
  105. /**
  106. * The data used by the {@link #revert} method to restore a node to its original state.
  107. *
  108. * See: {@link #apply}.
  109. *
  110. * @readonly
  111. * @protected
  112. * @member {module:ui/template~RenderData}
  113. */
  114. this._revertData = null;
  115. }
  116. /**
  117. * Renders a DOM Node (an HTML element or text) out of the template.
  118. *
  119. * const domNode = new Template( { ... } ).render();
  120. *
  121. * See: {@link #apply}.
  122. *
  123. * @returns {HTMLElement|Text}
  124. */
  125. render() {
  126. const node = this._renderNode( {
  127. intoFragment: true
  128. } );
  129. this._isRendered = true;
  130. return node;
  131. }
  132. /**
  133. * Applies the template to an existing DOM Node, either HTML element or text.
  134. *
  135. * **Note:** No new DOM nodes will be created. Applying extends
  136. * {@link module:ui/template~TemplateDefinition attributes} and
  137. * {@link module:ui/template~TemplateDefinition event listeners} only.
  138. *
  139. * **Note:** Existing `class` and `style` attributes are extended when a template
  140. * is applied to an HTML element, while other attributes and `textContent` are overridden.
  141. *
  142. * **Note:** The process of applying a template can be easily reverted using the
  143. * {@link module:ui/template~Template#revert} method.
  144. *
  145. * const element = document.createElement( 'div' );
  146. * const bind = Template.bind( observable, emitter );
  147. *
  148. * new Template( {
  149. * attrs: {
  150. * id: 'first-div',
  151. * class: bind.to( 'divClass' )
  152. * },
  153. * on: {
  154. * click: bind( 'elementClicked' ) // Will be fired by the observable.
  155. * }
  156. * children: [
  157. * 'Div text.'
  158. * ]
  159. * } ).apply( element );
  160. *
  161. * element.outerHTML == "<div id="first-div" class="my-div">Div text.</div>"
  162. *
  163. * @see module:ui/template~Template#render
  164. * @see module:ui/template~Template#revert
  165. * @param {Node} node Root node for the template to apply.
  166. */
  167. apply( node ) {
  168. this._revertData = getEmptyRevertData();
  169. this._renderNode( {
  170. node,
  171. isApplying: true,
  172. revertData: this._revertData
  173. } );
  174. return node;
  175. }
  176. /**
  177. * Reverts a template {@link module:ui/template~Template#apply applied} to a DOM node.
  178. *
  179. * @param {Node} node The root node for the template to revert. In most of the cases, it is the
  180. * same node used by {@link module:ui/template~Template#apply}.
  181. */
  182. revert( node ) {
  183. if ( !this._revertData ) {
  184. /**
  185. * Attempting to revert a template which has not been applied yet.
  186. *
  187. * @error ui-template-revert-not-applied
  188. */
  189. throw new CKEditorError( 'ui-template-revert-not-applied: Attempting to revert a template which has not been applied yet.' );
  190. }
  191. this._revertTemplateFromNode( node, this._revertData );
  192. }
  193. /**
  194. * Returns an iterator which traverses the template in search of {@link module:ui/view~View}
  195. * instances and returns them one by one.
  196. *
  197. * const viewFoo = new View();
  198. * const viewBar = new View();
  199. * const viewBaz = new View();
  200. * const template = new Template( {
  201. * tag: 'div',
  202. * children: [
  203. * viewFoo,
  204. * {
  205. * tag: 'div',
  206. * children: [
  207. * viewBar
  208. * ]
  209. * },
  210. * viewBaz
  211. * ]
  212. * } );
  213. *
  214. * // Logs: viewFoo, viewBar, viewBaz
  215. * for ( const view of template.getViews() ) {
  216. * console.log( view );
  217. * }
  218. *
  219. * @returns {Iterable.<module:ui/view~View>}
  220. */
  221. * getViews() {
  222. function* search( def ) {
  223. if ( def.children ) {
  224. for ( const child of def.children ) {
  225. if ( isView( child ) ) {
  226. yield child;
  227. } else if ( isTemplate( child ) ) {
  228. yield* search( child );
  229. }
  230. }
  231. }
  232. }
  233. yield* search( this );
  234. }
  235. /**
  236. * An entry point to the interface which binds DOM nodes to
  237. * {@link module:utils/observablemixin~Observable observables}.
  238. * There are two types of bindings:
  239. *
  240. * * HTML element attributes or text `textContent` synchronized with attributes of an
  241. * {@link module:utils/observablemixin~Observable}. Learn more about {@link module:ui/template~BindChain#to}
  242. * and {@link module:ui/template~BindChain#if}.
  243. *
  244. * const bind = Template.bind( observable, emitter );
  245. *
  246. * new Template( {
  247. * attrs: {
  248. * // Binds the element "class" attribute to observable#classAttribute.
  249. * class: bind.to( 'classAttribute' )
  250. * }
  251. * } ).render();
  252. *
  253. * * DOM events fired on HTML element propagated through
  254. * {@link module:utils/observablemixin~Observable}. Learn more about {@link module:ui/template~BindChain#to}.
  255. *
  256. * const bind = Template.bind( observable, emitter );
  257. *
  258. * new Template( {
  259. * on: {
  260. * // Will be fired by the observable.
  261. * click: bind( 'elementClicked' )
  262. * }
  263. * } ).render();
  264. *
  265. * Also see {@link module:ui/view~View#bindTemplate}.
  266. *
  267. * @param {module:utils/observablemixin~Observable} observable An observable which provides boundable attributes.
  268. * @param {module:utils/emittermixin~Emitter} emitter An emitter that listens to observable attribute
  269. * changes or DOM Events (depending on the kind of the binding). Usually, a {@link module:ui/view~View} instance.
  270. * @returns {module:ui/template~BindChain}
  271. */
  272. static bind( observable, emitter ) {
  273. return {
  274. to( eventNameOrFunctionOrAttribute, callback ) {
  275. return new TemplateToBinding( {
  276. eventNameOrFunction: eventNameOrFunctionOrAttribute,
  277. attribute: eventNameOrFunctionOrAttribute,
  278. observable, emitter, callback
  279. } );
  280. },
  281. if( attribute, valueIfTrue, callback ) {
  282. return new TemplateIfBinding( {
  283. observable, emitter, attribute, valueIfTrue, callback
  284. } );
  285. }
  286. };
  287. }
  288. /**
  289. * Extends an existing {@link module:ui/template~Template} instance with some additional content
  290. * from another {@link module:ui/template~TemplateDefinition}.
  291. *
  292. * const bind = Template.bind( observable, emitter );
  293. *
  294. * const template = new Template( {
  295. * tag: 'p',
  296. * attributes: {
  297. * class: 'a',
  298. * data-x: bind.to( 'foo' )
  299. * },
  300. * children: [
  301. * {
  302. * tag: 'span',
  303. * attributes: {
  304. * class: 'b'
  305. * },
  306. * children: [
  307. * 'Span'
  308. * ]
  309. * }
  310. * ]
  311. * } );
  312. *
  313. * // Instance-level extension.
  314. * Template.extend( template, {
  315. * attributes: {
  316. * class: 'b',
  317. * data-x: bind.to( 'bar' )
  318. * },
  319. * children: [
  320. * {
  321. * attributes: {
  322. * class: 'c'
  323. * }
  324. * }
  325. * ]
  326. * } );
  327. *
  328. * // Child extension.
  329. * Template.extend( template.children[ 0 ], {
  330. * attributes: {
  331. * class: 'd'
  332. * }
  333. * } );
  334. *
  335. * the `outerHTML` of `template.render()` is:
  336. *
  337. * <p class="a b" data-x="{ observable.foo } { observable.bar }">
  338. * <span class="b c d">Span</span>
  339. * </p>
  340. *
  341. * @param {module:ui/template~Template} template An existing template instance to be extended.
  342. * @param {module:ui/template~TemplateDefinition} def Additional definition to be applied to a template.
  343. */
  344. static extend( template, def ) {
  345. if ( template._isRendered ) {
  346. /**
  347. * Extending a template after rendering may not work as expected. To make sure
  348. * the {@link module:ui/template~Template.extend extending} works for an element,
  349. * make sure it happens before {@link #render} is called.
  350. *
  351. * @error template-extend-render
  352. */
  353. log.warn( 'template-extend-render: Attempting to extend a template which has already been rendered.' );
  354. }
  355. extendTemplate( template, normalize( clone( def ) ) );
  356. }
  357. /**
  358. * Renders a DOM Node (either an HTML element or text) out of the template.
  359. *
  360. * @protected
  361. * @param {module:ui/template~RenderData} data Rendering data.
  362. */
  363. _renderNode( data ) {
  364. let isInvalid;
  365. if ( data.node ) {
  366. // When applying, a definition cannot have "tag" and "text" at the same time.
  367. isInvalid = this.tag && this.text;
  368. } else {
  369. // When rendering, a definition must have either "tag" or "text": XOR( this.tag, this.text ).
  370. isInvalid = this.tag ? this.text : !this.text;
  371. }
  372. if ( isInvalid ) {
  373. /**
  374. * Node definition cannot have the "tag" and "text" properties at the same time.
  375. * Node definition must have either "tag" or "text" when rendering a new Node.
  376. *
  377. * @error ui-template-wrong-syntax
  378. */
  379. throw new CKEditorError(
  380. 'ui-template-wrong-syntax: Node definition must have either "tag" or "text" when rendering a new Node.'
  381. );
  382. }
  383. if ( this.text ) {
  384. return this._renderText( data );
  385. } else {
  386. return this._renderElement( data );
  387. }
  388. }
  389. /**
  390. * Renders an HTML element out of the template.
  391. *
  392. * @protected
  393. * @param {module:ui/template~RenderData} data Rendering data.
  394. */
  395. _renderElement( data ) {
  396. let node = data.node;
  397. if ( !node ) {
  398. node = data.node = document.createElementNS( this.ns || xhtmlNs, this.tag );
  399. }
  400. this._renderAttributes( data );
  401. this._renderElementChildren( data );
  402. this._setUpListeners( data );
  403. return node;
  404. }
  405. /**
  406. * Renders a text node out of {@link module:ui/template~Template#text}.
  407. *
  408. * @protected
  409. * @param {module:ui/template~RenderData} data Rendering data.
  410. */
  411. _renderText( data ) {
  412. let node = data.node;
  413. // Save the original textContent to revert it in #revert().
  414. if ( node ) {
  415. data.revertData.text = node.textContent;
  416. } else {
  417. node = data.node = document.createTextNode( '' );
  418. }
  419. // Check if this Text Node is bound to Observable. Cases:
  420. //
  421. // text: [ Template.bind( ... ).to( ... ) ]
  422. //
  423. // text: [
  424. // 'foo',
  425. // Template.bind( ... ).to( ... ),
  426. // ...
  427. // ]
  428. //
  429. if ( hasTemplateBinding( this.text ) ) {
  430. this._bindToObservable( {
  431. schema: this.text,
  432. updater: getTextUpdater( node ),
  433. data
  434. } );
  435. }
  436. // Simply set text. Cases:
  437. //
  438. // text: [ 'all', 'are', 'static' ]
  439. //
  440. // text: [ 'foo' ]
  441. //
  442. else {
  443. node.textContent = this.text.join( '' );
  444. }
  445. return node;
  446. }
  447. /**
  448. * Renders HTML element attributes out of {@link module:ui/template~Template#attributes}.
  449. *
  450. * @protected
  451. * @param {module:ui/template~RenderData} data Rendering data.
  452. */
  453. _renderAttributes( data ) {
  454. let attrName, attrValue, domAttrValue, attrNs;
  455. if ( !this.attributes ) {
  456. return;
  457. }
  458. const node = data.node;
  459. const revertData = data.revertData;
  460. for ( attrName in this.attributes ) {
  461. // Current attribute value in DOM.
  462. domAttrValue = node.getAttribute( attrName );
  463. // The value to be set.
  464. attrValue = this.attributes[ attrName ];
  465. // Save revert data.
  466. if ( revertData ) {
  467. revertData.attributes[ attrName ] = domAttrValue;
  468. }
  469. // Detect custom namespace:
  470. //
  471. // class: {
  472. // ns: 'abc',
  473. // value: Template.bind( ... ).to( ... )
  474. // }
  475. //
  476. attrNs = ( isObject( attrValue[ 0 ] ) && attrValue[ 0 ].ns ) ? attrValue[ 0 ].ns : null;
  477. // Activate binding if one is found. Cases:
  478. //
  479. // class: [
  480. // Template.bind( ... ).to( ... )
  481. // ]
  482. //
  483. // class: [
  484. // 'bar',
  485. // Template.bind( ... ).to( ... ),
  486. // 'baz'
  487. // ]
  488. //
  489. // class: {
  490. // ns: 'abc',
  491. // value: Template.bind( ... ).to( ... )
  492. // }
  493. //
  494. if ( hasTemplateBinding( attrValue ) ) {
  495. // Normalize attributes with additional data like namespace:
  496. //
  497. // class: {
  498. // ns: 'abc',
  499. // value: [ ... ]
  500. // }
  501. //
  502. const valueToBind = attrNs ? attrValue[ 0 ].value : attrValue;
  503. // Extend the original value of attributes like "style" and "class",
  504. // don't override them.
  505. if ( revertData && shouldExtend( attrName ) ) {
  506. valueToBind.unshift( domAttrValue );
  507. }
  508. this._bindToObservable( {
  509. schema: valueToBind,
  510. updater: getAttributeUpdater( node, attrName, attrNs ),
  511. data
  512. } );
  513. }
  514. // Style attribute could be an Object so it needs to be parsed in a specific way.
  515. //
  516. // style: {
  517. // width: '100px',
  518. // height: Template.bind( ... ).to( ... )
  519. // }
  520. //
  521. else if ( attrName == 'style' && typeof attrValue[ 0 ] !== 'string' ) {
  522. this._renderStyleAttribute( attrValue[ 0 ], data );
  523. }
  524. // Otherwise simply set the static attribute:
  525. //
  526. // class: [ 'foo' ]
  527. //
  528. // class: [ 'all', 'are', 'static' ]
  529. //
  530. // class: [
  531. // {
  532. // ns: 'abc',
  533. // value: [ 'foo' ]
  534. // }
  535. // ]
  536. //
  537. else {
  538. // Extend the original value of attributes like "style" and "class",
  539. // don't override them.
  540. if ( revertData && domAttrValue && shouldExtend( attrName ) ) {
  541. attrValue.unshift( domAttrValue );
  542. }
  543. attrValue = attrValue
  544. // Retrieve "values" from:
  545. //
  546. // class: [
  547. // {
  548. // ns: 'abc',
  549. // value: [ ... ]
  550. // }
  551. // ]
  552. //
  553. .map( val => val ? ( val.value || val ) : val )
  554. // Flatten the array.
  555. .reduce( ( prev, next ) => prev.concat( next ), [] )
  556. // Convert into string.
  557. .reduce( arrayValueReducer, '' );
  558. if ( !isFalsy( attrValue ) ) {
  559. node.setAttributeNS( attrNs, attrName, attrValue );
  560. }
  561. }
  562. }
  563. }
  564. /**
  565. * Renders the `style` attribute of an HTML element based on
  566. * {@link module:ui/template~Template#attributes}.
  567. *
  568. * A style attribute is an {Object} with static values:
  569. *
  570. * attributes: {
  571. * style: {
  572. * color: 'red'
  573. * }
  574. * }
  575. *
  576. * or values bound to {@link module:ui/model~Model} properties:
  577. *
  578. * attributes: {
  579. * style: {
  580. * color: bind.to( ... )
  581. * }
  582. * }
  583. *
  584. * Note: The `style` attribute is rendered without setting the namespace. It does not seem to be
  585. * needed.
  586. *
  587. * @private
  588. * @param {Object} styles Styles located in `attributes.style` of {@link module:ui/template~TemplateDefinition}.
  589. * @param {module:ui/template~RenderData} data Rendering data.
  590. */
  591. _renderStyleAttribute( styles, data ) {
  592. const node = data.node;
  593. for ( const styleName in styles ) {
  594. const styleValue = styles[ styleName ];
  595. // Cases:
  596. //
  597. // style: {
  598. // color: bind.to( 'attribute' )
  599. // }
  600. //
  601. if ( hasTemplateBinding( styleValue ) ) {
  602. this._bindToObservable( {
  603. schema: [ styleValue ],
  604. updater: getStyleUpdater( node, styleName ),
  605. data
  606. } );
  607. }
  608. // Cases:
  609. //
  610. // style: {
  611. // color: 'red'
  612. // }
  613. //
  614. else {
  615. node.style[ styleName ] = styleValue;
  616. }
  617. }
  618. }
  619. /**
  620. * Recursively renders HTML element's children from {@link module:ui/template~Template#children}.
  621. *
  622. * @protected
  623. * @param {module:ui/template~RenderData} data Rendering data.
  624. */
  625. _renderElementChildren( data ) {
  626. const node = data.node;
  627. const container = data.intoFragment ? document.createDocumentFragment() : node;
  628. const isApplying = data.isApplying;
  629. let childIndex = 0;
  630. for ( const child of this.children ) {
  631. if ( isViewCollection( child ) ) {
  632. if ( !isApplying ) {
  633. child.setParent( node );
  634. // Note: ViewCollection renders its children.
  635. for ( const view of child ) {
  636. container.appendChild( view.element );
  637. }
  638. }
  639. } else if ( isView( child ) ) {
  640. if ( !isApplying ) {
  641. if ( !child.isRendered ) {
  642. child.render();
  643. }
  644. container.appendChild( child.element );
  645. }
  646. } else if ( isDomNode( child ) ) {
  647. container.appendChild( child );
  648. } else {
  649. if ( isApplying ) {
  650. const revertData = data.revertData;
  651. const childRevertData = getEmptyRevertData();
  652. revertData.children.push( childRevertData );
  653. child._renderNode( {
  654. node: container.childNodes[ childIndex++ ],
  655. isApplying: true,
  656. revertData: childRevertData
  657. } );
  658. } else {
  659. container.appendChild( child.render() );
  660. }
  661. }
  662. }
  663. if ( data.intoFragment ) {
  664. node.appendChild( container );
  665. }
  666. }
  667. /**
  668. * Activates `on` event listeners from the {@link module:ui/template~TemplateDefinition}
  669. * on an HTML element.
  670. *
  671. * @protected
  672. * @param {module:ui/template~RenderData} data Rendering data.
  673. */
  674. _setUpListeners( data ) {
  675. if ( !this.eventListeners ) {
  676. return;
  677. }
  678. for ( const key in this.eventListeners ) {
  679. const revertBindings = this.eventListeners[ key ].map( schemaItem => {
  680. const [ domEvtName, domSelector ] = key.split( '@' );
  681. return schemaItem.activateDomEventListener( domEvtName, domSelector, data );
  682. } );
  683. if ( data.revertData ) {
  684. data.revertData.bindings.push( revertBindings );
  685. }
  686. }
  687. }
  688. /**
  689. * For a given {@link module:ui/template~TemplateValueSchema} containing {@link module:ui/template~TemplateBinding}
  690. * activates the binding and sets its initial value.
  691. *
  692. * Note: {@link module:ui/template~TemplateValueSchema} can be for HTML element attributes or
  693. * text node `textContent`.
  694. *
  695. * @protected
  696. * @param {Object} options Binding options.
  697. * @param {module:ui/template~TemplateValueSchema} options.schema
  698. * @param {Function} options.updater A function which updates the DOM (like attribute or text).
  699. * @param {module:ui/template~RenderData} options.data Rendering data.
  700. */
  701. _bindToObservable( { schema, updater, data } ) {
  702. const revertData = data.revertData;
  703. // Set initial values.
  704. syncValueSchemaValue( schema, updater, data );
  705. const revertBindings = schema
  706. // Filter "falsy" (false, undefined, null, '') value schema components out.
  707. .filter( item => !isFalsy( item ) )
  708. // Filter inactive bindings from schema, like static strings ('foo'), numbers (42), etc.
  709. .filter( item => item.observable )
  710. // Once only the actual binding are left, let the emitter listen to observable change:attribute event.
  711. // TODO: Reduce the number of listeners attached as many bindings may listen
  712. // to the same observable attribute.
  713. .map( templateBinding => templateBinding.activateAttributeListener( schema, updater, data ) );
  714. if ( revertData ) {
  715. revertData.bindings.push( revertBindings );
  716. }
  717. }
  718. /**
  719. * Reverts {@link module:ui/template~RenderData#revertData template data} from a node to
  720. * return it to the original state.
  721. *
  722. * @protected
  723. * @param {HTMLElement|Text} node A node to be reverted.
  724. * @param {module:ui/template~RenderData#revertData} revertData Stores information about
  725. * what changes have been made by {@link #apply} to the node.
  726. */
  727. _revertTemplateFromNode( node, revertData ) {
  728. for ( const binding of revertData.bindings ) {
  729. // Each binding may consist of several observable+observable#attribute.
  730. // like the following has 2:
  731. //
  732. // class: [
  733. // 'x',
  734. // bind.to( 'foo' ),
  735. // 'y',
  736. // bind.to( 'bar' )
  737. // ]
  738. //
  739. for ( const revertBinding of binding ) {
  740. revertBinding();
  741. }
  742. }
  743. if ( revertData.text ) {
  744. node.textContent = revertData.text;
  745. return;
  746. }
  747. for ( const attrName in revertData.attributes ) {
  748. const attrValue = revertData.attributes[ attrName ];
  749. // When the attribute has **not** been set before #apply().
  750. if ( attrValue === null ) {
  751. node.removeAttribute( attrName );
  752. } else {
  753. node.setAttribute( attrName, attrValue );
  754. }
  755. }
  756. for ( let i = 0; i < revertData.children.length; ++i ) {
  757. this._revertTemplateFromNode( node.childNodes[ i ], revertData.children[ i ] );
  758. }
  759. }
  760. }
  761. mix( Template, EmitterMixin );
  762. /**
  763. * Describes a binding created by the {@link module:ui/template~Template.bind} interface.
  764. *
  765. * @protected
  766. */
  767. export class TemplateBinding {
  768. /**
  769. * Creates an instance of the {@link module:ui/template~TemplateBinding} class.
  770. *
  771. * @param {module:ui/template~TemplateDefinition} def The definition of the binding.
  772. */
  773. constructor( def ) {
  774. Object.assign( this, def );
  775. /**
  776. * An observable instance of the binding. It either:
  777. *
  778. * * provides the attribute with the value,
  779. * * or passes the event when a corresponding DOM event is fired.
  780. *
  781. * @member {module:utils/observablemixin~ObservableMixin} module:ui/template~TemplateBinding#observable
  782. */
  783. /**
  784. * An {@link module:utils/emittermixin~Emitter} used by the binding to:
  785. *
  786. * * listen to the attribute change in the {@link module:ui/template~TemplateBinding#observable},
  787. * * or listen to the event in the DOM.
  788. *
  789. * @member {module:utils/emittermixin~EmitterMixin} module:ui/template~TemplateBinding#emitter
  790. */
  791. /**
  792. * The name of the {@link module:ui/template~TemplateBinding#observable observed attribute}.
  793. *
  794. * @member {String} module:ui/template~TemplateBinding#attribute
  795. */
  796. /**
  797. * A custom function to process the value of the {@link module:ui/template~TemplateBinding#attribute}.
  798. *
  799. * @member {Function} [module:ui/template~TemplateBinding#callback]
  800. */
  801. }
  802. /**
  803. * Returns the value of the binding. It is the value of the {@link module:ui/template~TemplateBinding#attribute} in
  804. * {@link module:ui/template~TemplateBinding#observable}. The value may be processed by the
  805. * {@link module:ui/template~TemplateBinding#callback}, if such has been passed to the binding.
  806. *
  807. * @param {Node} [node] A native DOM node, passed to the custom {@link module:ui/template~TemplateBinding#callback}.
  808. * @returns {*} The value of {@link module:ui/template~TemplateBinding#attribute} in
  809. * {@link module:ui/template~TemplateBinding#observable}.
  810. */
  811. getValue( node ) {
  812. const value = this.observable[ this.attribute ];
  813. return this.callback ? this.callback( value, node ) : value;
  814. }
  815. /**
  816. * Activates the listener which waits for changes of the {@link module:ui/template~TemplateBinding#attribute} in
  817. * {@link module:ui/template~TemplateBinding#observable}, then updates the DOM with the aggregated
  818. * value of {@link module:ui/template~TemplateValueSchema}.
  819. *
  820. * @param {module:ui/template~TemplateValueSchema} schema A full schema to generate an attribute or text in the DOM.
  821. * @param {Function} updater A DOM updater function used to update the native DOM attribute or text.
  822. * @param {module:ui/template~RenderData} data Rendering data.
  823. * @returns {Function} A function to sever the listener binding.
  824. */
  825. activateAttributeListener( schema, updater, data ) {
  826. const callback = () => syncValueSchemaValue( schema, updater, data );
  827. this.emitter.listenTo( this.observable, 'change:' + this.attribute, callback );
  828. // Allows revert of the listener.
  829. return () => {
  830. this.emitter.stopListening( this.observable, 'change:' + this.attribute, callback );
  831. };
  832. }
  833. }
  834. /**
  835. * Describes either:
  836. *
  837. * * a binding to an {@link module:utils/observablemixin~Observable},
  838. * * or a native DOM event binding.
  839. *
  840. * It is created by the {@link module:ui/template~BindChain#to} method.
  841. *
  842. * @protected
  843. */
  844. export class TemplateToBinding extends TemplateBinding {
  845. /**
  846. * Activates the listener for the native DOM event, which when fired, is propagated by
  847. * the {@link module:ui/template~TemplateBinding#emitter}.
  848. *
  849. * @param {String} domEvtName The name of the native DOM event.
  850. * @param {String} domSelector The selector in the DOM to filter delegated events.
  851. * @param {module:ui/template~RenderData} data Rendering data.
  852. * @returns {Function} A function to sever the listener binding.
  853. */
  854. activateDomEventListener( domEvtName, domSelector, data ) {
  855. const callback = ( evt, domEvt ) => {
  856. if ( !domSelector || domEvt.target.matches( domSelector ) ) {
  857. if ( typeof this.eventNameOrFunction == 'function' ) {
  858. this.eventNameOrFunction( domEvt );
  859. } else {
  860. this.observable.fire( this.eventNameOrFunction, domEvt );
  861. }
  862. }
  863. };
  864. this.emitter.listenTo( data.node, domEvtName, callback );
  865. // Allows revert of the listener.
  866. return () => {
  867. this.emitter.stopListening( data.node, domEvtName, callback );
  868. };
  869. }
  870. }
  871. /**
  872. * Describes a binding to {@link module:utils/observablemixin~ObservableMixin} created by the {@link module:ui/template~BindChain#if}
  873. * method.
  874. *
  875. * @protected
  876. */
  877. export class TemplateIfBinding extends TemplateBinding {
  878. /**
  879. * @inheritDoc
  880. */
  881. getValue( node ) {
  882. const value = super.getValue( node );
  883. return isFalsy( value ) ? false : ( this.valueIfTrue || true );
  884. }
  885. /**
  886. * The value of the DOM attribute or text to be set if the {@link module:ui/template~TemplateBinding#attribute} in
  887. * {@link module:ui/template~TemplateBinding#observable} is `true`.
  888. *
  889. * @member {String} [module:ui/template~TemplateIfBinding#valueIfTrue]
  890. */
  891. }
  892. // Checks whether given {@link module:ui/template~TemplateValueSchema} contains a
  893. // {@link module:ui/template~TemplateBinding}.
  894. //
  895. // @param {module:ui/template~TemplateValueSchema} schema
  896. // @returns {Boolean}
  897. function hasTemplateBinding( schema ) {
  898. if ( !schema ) {
  899. return false;
  900. }
  901. // Normalize attributes with additional data like namespace:
  902. //
  903. // class: {
  904. // ns: 'abc',
  905. // value: [ ... ]
  906. // }
  907. //
  908. if ( schema.value ) {
  909. schema = schema.value;
  910. }
  911. if ( Array.isArray( schema ) ) {
  912. return schema.some( hasTemplateBinding );
  913. } else if ( schema instanceof TemplateBinding ) {
  914. return true;
  915. }
  916. return false;
  917. }
  918. // Assembles the value using {@link module:ui/template~TemplateValueSchema} and stores it in a form of
  919. // an Array. Each entry of the Array corresponds to one of {@link module:ui/template~TemplateValueSchema}
  920. // items.
  921. //
  922. // @param {module:ui/template~TemplateValueSchema} schema
  923. // @param {Node} node DOM Node updated when {@link module:utils/observablemixin~ObservableMixin} changes.
  924. // @return {Array}
  925. function getValueSchemaValue( schema, node ) {
  926. return schema.map( schemaItem => {
  927. // Process {@link module:ui/template~TemplateBinding} bindings.
  928. if ( schemaItem instanceof TemplateBinding ) {
  929. return schemaItem.getValue( node );
  930. }
  931. // All static values like strings, numbers, and "falsy" values (false, null, undefined, '', etc.) just pass.
  932. return schemaItem;
  933. } );
  934. }
  935. // A function executed each time the bound Observable attribute changes, which updates the DOM with a value
  936. // constructed from {@link module:ui/template~TemplateValueSchema}.
  937. //
  938. // @param {module:ui/template~TemplateValueSchema} schema
  939. // @param {Function} updater A function which updates the DOM (like attribute or text).
  940. // @param {Node} node DOM Node updated when {@link module:utils/observablemixin~ObservableMixin} changes.
  941. function syncValueSchemaValue( schema, updater, { node } ) {
  942. let value = getValueSchemaValue( schema, node );
  943. // Check if schema is a single Template.bind.if, like:
  944. //
  945. // class: Template.bind.if( 'foo' )
  946. //
  947. if ( schema.length == 1 && schema[ 0 ] instanceof TemplateIfBinding ) {
  948. value = value[ 0 ];
  949. } else {
  950. value = value.reduce( arrayValueReducer, '' );
  951. }
  952. if ( isFalsy( value ) ) {
  953. updater.remove();
  954. } else {
  955. updater.set( value );
  956. }
  957. }
  958. // Returns an object consisting of `set` and `remove` functions, which
  959. // can be used in the context of DOM Node to set or reset `textContent`.
  960. // @see module:ui/view~View#_bindToObservable
  961. //
  962. // @param {Node} node DOM Node to be modified.
  963. // @returns {Object}
  964. function getTextUpdater( node ) {
  965. return {
  966. set( value ) {
  967. node.textContent = value;
  968. },
  969. remove() {
  970. node.textContent = '';
  971. }
  972. };
  973. }
  974. // Returns an object consisting of `set` and `remove` functions, which
  975. // can be used in the context of DOM Node to set or reset an attribute.
  976. // @see module:ui/view~View#_bindToObservable
  977. //
  978. // @param {Node} node DOM Node to be modified.
  979. // @param {String} attrName Name of the attribute to be modified.
  980. // @param {String} [ns=null] Namespace to use.
  981. // @returns {Object}
  982. function getAttributeUpdater( el, attrName, ns ) {
  983. return {
  984. set( value ) {
  985. el.setAttributeNS( ns, attrName, value );
  986. },
  987. remove() {
  988. el.removeAttributeNS( ns, attrName );
  989. }
  990. };
  991. }
  992. // Returns an object consisting of `set` and `remove` functions, which
  993. // can be used in the context of CSSStyleDeclaration to set or remove a style.
  994. // @see module:ui/view~View#_bindToObservable
  995. //
  996. // @param {Node} node DOM Node to be modified.
  997. // @param {String} styleName Name of the style to be modified.
  998. // @returns {Object}
  999. function getStyleUpdater( el, styleName ) {
  1000. return {
  1001. set( value ) {
  1002. el.style[ styleName ] = value;
  1003. },
  1004. remove() {
  1005. el.style[ styleName ] = null;
  1006. }
  1007. };
  1008. }
  1009. // Clones definition of the template.
  1010. //
  1011. // @param {module:ui/template~TemplateDefinition} def
  1012. // @returns {module:ui/template~TemplateDefinition}
  1013. function clone( def ) {
  1014. const clone = cloneDeepWith( def, value => {
  1015. // Don't clone the `Template.bind`* bindings because of the references to Observable
  1016. // and DomEmitterMixin instances inside, which would also be traversed and cloned by greedy
  1017. // cloneDeepWith algorithm. There's no point in cloning Observable/DomEmitterMixins
  1018. // along with the definition.
  1019. //
  1020. // Don't clone Template instances if provided as a child. They're simply #render()ed
  1021. // and nothing should interfere.
  1022. //
  1023. // Also don't clone View instances if provided as a child of the Template. The template
  1024. // instance will be extracted from the View during the normalization and there's no need
  1025. // to clone it.
  1026. if ( value && ( value instanceof TemplateBinding || isTemplate( value ) || isView( value ) || isViewCollection( value ) ) ) {
  1027. return value;
  1028. }
  1029. } );
  1030. return clone;
  1031. }
  1032. // Normalizes given {@link module:ui/template~TemplateDefinition}.
  1033. //
  1034. // See:
  1035. // * {@link normalizeAttributes}
  1036. // * {@link normalizeListeners}
  1037. // * {@link normalizePlainTextDefinition}
  1038. // * {@link normalizeTextDefinition}
  1039. //
  1040. // @param {module:ui/template~TemplateDefinition} def
  1041. // @returns {module:ui/template~TemplateDefinition} Normalized definition.
  1042. function normalize( def ) {
  1043. if ( typeof def == 'string' ) {
  1044. def = normalizePlainTextDefinition( def );
  1045. } else if ( def.text ) {
  1046. normalizeTextDefinition( def );
  1047. }
  1048. if ( def.on ) {
  1049. def.eventListeners = normalizeListeners( def.on );
  1050. // Template mixes EmitterMixin, so delete #on to avoid collision.
  1051. delete def.on;
  1052. }
  1053. if ( !def.text ) {
  1054. if ( def.attributes ) {
  1055. normalizeAttributes( def.attributes );
  1056. }
  1057. const children = [];
  1058. if ( def.children ) {
  1059. if ( isViewCollection( def.children ) ) {
  1060. children.push( def.children );
  1061. } else {
  1062. for ( const child of def.children ) {
  1063. if ( isTemplate( child ) || isView( child ) || isDomNode( child ) ) {
  1064. children.push( child );
  1065. } else {
  1066. children.push( new Template( child ) );
  1067. }
  1068. }
  1069. }
  1070. }
  1071. def.children = children;
  1072. }
  1073. return def;
  1074. }
  1075. // Normalizes "attributes" section of {@link module:ui/template~TemplateDefinition}.
  1076. //
  1077. // attributes: {
  1078. // a: 'bar',
  1079. // b: {@link module:ui/template~TemplateBinding},
  1080. // c: {
  1081. // value: 'bar'
  1082. // }
  1083. // }
  1084. //
  1085. // becomes
  1086. //
  1087. // attributes: {
  1088. // a: [ 'bar' ],
  1089. // b: [ {@link module:ui/template~TemplateBinding} ],
  1090. // c: {
  1091. // value: [ 'bar' ]
  1092. // }
  1093. // }
  1094. //
  1095. // @param {Object} attrs
  1096. function normalizeAttributes( attrs ) {
  1097. for ( const a in attrs ) {
  1098. if ( attrs[ a ].value ) {
  1099. attrs[ a ].value = [].concat( attrs[ a ].value );
  1100. }
  1101. arrayify( attrs, a );
  1102. }
  1103. }
  1104. // Normalizes "on" section of {@link module:ui/template~TemplateDefinition}.
  1105. //
  1106. // on: {
  1107. // a: 'bar',
  1108. // b: {@link module:ui/template~TemplateBinding},
  1109. // c: [ {@link module:ui/template~TemplateBinding}, () => { ... } ]
  1110. // }
  1111. //
  1112. // becomes
  1113. //
  1114. // on: {
  1115. // a: [ 'bar' ],
  1116. // b: [ {@link module:ui/template~TemplateBinding} ],
  1117. // c: [ {@link module:ui/template~TemplateBinding}, () => { ... } ]
  1118. // }
  1119. //
  1120. // @param {Object} listeners
  1121. // @returns {Object} Object containing normalized listeners.
  1122. function normalizeListeners( listeners ) {
  1123. for ( const l in listeners ) {
  1124. arrayify( listeners, l );
  1125. }
  1126. return listeners;
  1127. }
  1128. // Normalizes "string" {@link module:ui/template~TemplateDefinition}.
  1129. //
  1130. // "foo"
  1131. //
  1132. // becomes
  1133. //
  1134. // { text: [ 'foo' ] },
  1135. //
  1136. // @param {String} def
  1137. // @returns {module:ui/template~TemplateDefinition} Normalized template definition.
  1138. function normalizePlainTextDefinition( def ) {
  1139. return {
  1140. text: [ def ]
  1141. };
  1142. }
  1143. // Normalizes text {@link module:ui/template~TemplateDefinition}.
  1144. //
  1145. // children: [
  1146. // { text: 'def' },
  1147. // { text: {@link module:ui/template~TemplateBinding} }
  1148. // ]
  1149. //
  1150. // becomes
  1151. //
  1152. // children: [
  1153. // { text: [ 'def' ] },
  1154. // { text: [ {@link module:ui/template~TemplateBinding} ] }
  1155. // ]
  1156. //
  1157. // @param {module:ui/template~TemplateDefinition} def
  1158. function normalizeTextDefinition( def ) {
  1159. if ( !Array.isArray( def.text ) ) {
  1160. def.text = [ def.text ];
  1161. }
  1162. }
  1163. // Wraps an entry in Object in an Array, if not already one.
  1164. //
  1165. // {
  1166. // x: 'y',
  1167. // a: [ 'b' ]
  1168. // }
  1169. //
  1170. // becomes
  1171. //
  1172. // {
  1173. // x: [ 'y' ],
  1174. // a: [ 'b' ]
  1175. // }
  1176. //
  1177. // @param {Object} obj
  1178. // @param {String} key
  1179. function arrayify( obj, key ) {
  1180. if ( !Array.isArray( obj[ key ] ) ) {
  1181. obj[ key ] = [ obj[ key ] ];
  1182. }
  1183. }
  1184. // A helper which concatenates the value avoiding unwanted
  1185. // leading white spaces.
  1186. //
  1187. // @param {String} prev
  1188. // @param {String} cur
  1189. // @returns {String}
  1190. function arrayValueReducer( prev, cur ) {
  1191. if ( isFalsy( cur ) ) {
  1192. return prev;
  1193. } else if ( isFalsy( prev ) ) {
  1194. return cur;
  1195. } else {
  1196. return `${ prev } ${ cur }`;
  1197. }
  1198. }
  1199. // Extends one object defined in the following format:
  1200. //
  1201. // {
  1202. // key1: [Array1],
  1203. // key2: [Array2],
  1204. // ...
  1205. // keyN: [ArrayN]
  1206. // }
  1207. //
  1208. // with another object of the same data format.
  1209. //
  1210. // @param {Object} obj Base object.
  1211. // @param {Object} ext Object extending base.
  1212. // @returns {String}
  1213. function extendObjectValueArray( obj, ext ) {
  1214. for ( const a in ext ) {
  1215. if ( obj[ a ] ) {
  1216. obj[ a ].push( ...ext[ a ] );
  1217. } else {
  1218. obj[ a ] = ext[ a ];
  1219. }
  1220. }
  1221. }
  1222. // A helper for {@link module:ui/template~Template#extend}. Recursively extends {@link module:ui/template~Template} instance
  1223. // with content from {module:ui/template~TemplateDefinition}. See {@link module:ui/template~Template#extend} to learn more.
  1224. //
  1225. // @param {module:ui/template~Template} def A template instance to be extended.
  1226. // @param {module:ui/template~TemplateDefinition} def A definition which is to extend the template instance.
  1227. function extendTemplate( template, def ) {
  1228. if ( def.attributes ) {
  1229. if ( !template.attributes ) {
  1230. template.attributes = {};
  1231. }
  1232. extendObjectValueArray( template.attributes, def.attributes );
  1233. }
  1234. if ( def.eventListeners ) {
  1235. if ( !template.eventListeners ) {
  1236. template.eventListeners = {};
  1237. }
  1238. extendObjectValueArray( template.eventListeners, def.eventListeners );
  1239. }
  1240. if ( def.text ) {
  1241. template.text.push( ...def.text );
  1242. }
  1243. if ( def.children && def.children.length ) {
  1244. if ( template.children.length != def.children.length ) {
  1245. /**
  1246. * The number of children in extended definition does not match.
  1247. *
  1248. * @error ui-template-extend-children-mismatch
  1249. */
  1250. throw new CKEditorError(
  1251. 'ui-template-extend-children-mismatch: The number of children in extended definition does not match.'
  1252. );
  1253. }
  1254. let childIndex = 0;
  1255. for ( const childDef of def.children ) {
  1256. extendTemplate( template.children[ childIndex++ ], childDef );
  1257. }
  1258. }
  1259. }
  1260. // Checks if value is "falsy".
  1261. // Note: 0 (Number) is not "falsy" in this context.
  1262. //
  1263. // @private
  1264. // @param {*} value Value to be checked.
  1265. function isFalsy( value ) {
  1266. return !value && value !== 0;
  1267. }
  1268. // Checks if the item is an instance of {@link module:ui/view~View}
  1269. //
  1270. // @private
  1271. // @param {*} value Value to be checked.
  1272. function isView( item ) {
  1273. return item instanceof View;
  1274. }
  1275. // Checks if the item is an instance of {@link module:ui/template~Template}
  1276. //
  1277. // @private
  1278. // @param {*} value Value to be checked.
  1279. function isTemplate( item ) {
  1280. return item instanceof Template;
  1281. }
  1282. // Checks if the item is an instance of {@link module:ui/viewcollection~ViewCollection}
  1283. //
  1284. // @private
  1285. // @param {*} value Value to be checked.
  1286. function isViewCollection( item ) {
  1287. return item instanceof ViewCollection;
  1288. }
  1289. // Creates an empty skeleton for {@link module:ui/template~Template#revert}
  1290. // data.
  1291. //
  1292. // @private
  1293. function getEmptyRevertData() {
  1294. return {
  1295. children: [],
  1296. bindings: [],
  1297. attributes: {}
  1298. };
  1299. }
  1300. // Checks whether an attribute should be extended when
  1301. // {@link module:ui/template~Template#apply} is called.
  1302. //
  1303. // @private
  1304. // @param {String} attrName Attribute name to check.
  1305. function shouldExtend( attrName ) {
  1306. return attrName == 'class' || attrName == 'style';
  1307. }
  1308. /**
  1309. * A definition of the {@link module:ui/template~Template}. It describes what kind of
  1310. * node a template will render (HTML element or text), attributes of an element, DOM event
  1311. * listeners and children.
  1312. *
  1313. * Also see:
  1314. * * {@link module:ui/template~TemplateValueSchema} to learn about HTML element attributes,
  1315. * * {@link module:ui/template~TemplateListenerSchema} to learn about DOM event listeners.
  1316. *
  1317. * A sample definition on an HTML element can look like this:
  1318. *
  1319. * new Template( {
  1320. * tag: 'p',
  1321. * children: [
  1322. * {
  1323. * tag: 'span',
  1324. * attributes: { ... },
  1325. * children: [ ... ],
  1326. * },
  1327. * {
  1328. * text: 'static–text'
  1329. * },
  1330. * 'also-static–text',
  1331. * ],
  1332. * attributes: {
  1333. * class: {@link module:ui/template~TemplateValueSchema},
  1334. * id: {@link module:ui/template~TemplateValueSchema},
  1335. * style: {@link module:ui/template~TemplateValueSchema}
  1336. *
  1337. * // ...
  1338. * },
  1339. * on: {
  1340. * 'click': {@link module:ui/template~TemplateListenerSchema}
  1341. *
  1342. * // Document.querySelector format is also accepted.
  1343. * 'keyup@a.some-class': {@link module:ui/template~TemplateListenerSchema}
  1344. *
  1345. * // ...
  1346. * }
  1347. * } );
  1348. *
  1349. * A {@link module:ui/view~View}, another {@link module:ui/template~Template} or a native DOM node
  1350. * can also become a child of a template. When a view is passed, its {@link module:ui/view~View#element} is used:
  1351. *
  1352. * const view = new SomeView();
  1353. * const childTemplate = new Template( { ... } );
  1354. * const childNode = document.createElement( 'b' );
  1355. *
  1356. * new Template( {
  1357. * tag: 'p',
  1358. *
  1359. * children: [
  1360. * // view#element will be added as a child of this <p>.
  1361. * view,
  1362. *
  1363. * // The output of childTemplate.render() will be added here.
  1364. * childTemplate,
  1365. *
  1366. * // Native DOM nodes are included directly in the rendered output.
  1367. * childNode
  1368. * ]
  1369. * } );
  1370. *
  1371. * An entire {@link module:ui/viewcollection~ViewCollection} can be used as a child in the definition:
  1372. *
  1373. * const collection = new ViewCollection();
  1374. * collection.add( someView );
  1375. *
  1376. * new Template( {
  1377. * tag: 'p',
  1378. *
  1379. * children: collection
  1380. * } );
  1381. *
  1382. * @typedef module:ui/template~TemplateDefinition
  1383. * @type Object
  1384. *
  1385. * @property {String} tag See the template {@link module:ui/template~Template#tag} property.
  1386. *
  1387. * @property {Array.<module:ui/template~TemplateDefinition>} [children]
  1388. * See the template {@link module:ui/template~Template#children} property.
  1389. *
  1390. * @property {Object.<String, module:ui/template~TemplateValueSchema>} [attributes]
  1391. * See the template {@link module:ui/template~Template#attributes} property.
  1392. *
  1393. * @property {String|module:ui/template~TemplateValueSchema|Array.<String|module:ui/template~TemplateValueSchema>} [text]
  1394. * See the template {@link module:ui/template~Template#text} property.
  1395. *
  1396. * @property {Object.<String, module:ui/template~TemplateListenerSchema>} [on]
  1397. * See the template {@link module:ui/template~Template#eventListeners} property.
  1398. */
  1399. /**
  1400. * Describes a value of an HTML element attribute or `textContent`. It allows combining multiple
  1401. * data sources like static values and {@link module:utils/observablemixin~Observable} attributes.
  1402. *
  1403. * Also see:
  1404. * * {@link module:ui/template~TemplateDefinition} to learn where to use it,
  1405. * * {@link module:ui/template~Template.bind} to learn how to configure
  1406. * {@link module:utils/observablemixin~Observable} attribute bindings,
  1407. * * {@link module:ui/template~Template#render} to learn how to render a template,
  1408. * * {@link module:ui/template~BindChain#to `to()`} and {@link module:ui/template~BindChain#if `if()`}
  1409. * methods to learn more about bindings.
  1410. *
  1411. * Attribute values can be described in many different ways:
  1412. *
  1413. * // Bind helper will create bindings to attributes of the observable.
  1414. * const bind = Template.bind( observable, emitter );
  1415. *
  1416. * new Template( {
  1417. * tag: 'p',
  1418. * attributes: {
  1419. * // A plain string schema.
  1420. * 'class': 'static-text',
  1421. *
  1422. * // An object schema, binds to the "foo" attribute of the
  1423. * // observable and follows its value.
  1424. * 'class': bind.to( 'foo' ),
  1425. *
  1426. * // An array schema, combines the above.
  1427. * 'class': [
  1428. * 'static-text',
  1429. * bind.to( 'bar', () => { ... } ),
  1430. *
  1431. * // Bindings can also be conditional.
  1432. * bind.if( 'baz', 'class-when-baz-is-true' )
  1433. * ],
  1434. *
  1435. * // An array schema, with a custom namespace, e.g. useful for creating SVGs.
  1436. * 'class': {
  1437. * ns: 'http://ns.url',
  1438. * value: [
  1439. * bind.if( 'baz', 'value-when-true' ),
  1440. * 'static-text'
  1441. * ]
  1442. * },
  1443. *
  1444. * // An object schema, specific for styles.
  1445. * style: {
  1446. * color: 'red',
  1447. * backgroundColor: bind.to( 'qux', () => { ... } )
  1448. * }
  1449. * }
  1450. * } );
  1451. *
  1452. * Text nodes can also have complex values:
  1453. *
  1454. * const bind = Template.bind( observable, emitter );
  1455. *
  1456. * // Will render a "foo" text node.
  1457. * new Template( {
  1458. * text: 'foo'
  1459. * } );
  1460. *
  1461. * // Will render a "static text: {observable.foo}" text node.
  1462. * // The text of the node will be updated as the "foo" attribute changes.
  1463. * new Template( {
  1464. * text: [
  1465. * 'static text: ',
  1466. * bind.to( 'foo', () => { ... } )
  1467. * ]
  1468. * } );
  1469. *
  1470. * @typedef module:ui/template~TemplateValueSchema
  1471. * @type {Object|String|Array}
  1472. */
  1473. /**
  1474. * Describes an event listener attached to an HTML element. Such listener can propagate DOM events
  1475. * through an {@link module:utils/observablemixin~Observable} instance, execute custom callbacks
  1476. * or both, if necessary.
  1477. *
  1478. * Also see:
  1479. * * {@link module:ui/template~TemplateDefinition} to learn more about template definitions,
  1480. * * {@link module:ui/template~BindChain#to `to()`} method to learn more about bindings.
  1481. *
  1482. * Check out different ways of attaching event listeners below:
  1483. *
  1484. * // Bind helper will propagate events through the observable.
  1485. * const bind = Template.bind( observable, emitter );
  1486. *
  1487. * new Template( {
  1488. * tag: 'p',
  1489. * on: {
  1490. * // An object schema. The observable will fire the "clicked" event upon DOM "click".
  1491. * click: bind.to( 'clicked' )
  1492. *
  1493. * // An object schema. It will work for "click" event on "a.foo" children only.
  1494. * 'click@a.foo': bind.to( 'clicked' )
  1495. *
  1496. * // An array schema, makes the observable propagate multiple events.
  1497. * click: [
  1498. * bind.to( 'clicked' ),
  1499. * bind.to( 'executed' )
  1500. * ],
  1501. *
  1502. * // An array schema with a custom callback.
  1503. * 'click@a.foo': {
  1504. * bind.to( 'clicked' ),
  1505. * bind.to( evt => {
  1506. * console.log( `${ evt.target } has been clicked!` );
  1507. * } }
  1508. * }
  1509. * }
  1510. * } );
  1511. *
  1512. * @typedef module:ui/template~TemplateListenerSchema
  1513. * @type {Object|String|Array}
  1514. */
  1515. /**
  1516. * The return value of {@link ~Template.bind `Template.bind()`}. It provides `to()` and `if()`
  1517. * methods to create the {@link module:utils/observablemixin~Observable observable} attribute and event bindings.
  1518. *
  1519. * @interface module:ui/template~BindChain
  1520. */
  1521. /**
  1522. * Binds an {@link module:utils/observablemixin~Observable observable} to either:
  1523. *
  1524. * * an HTML element attribute or a text node `textContent`, so it remains in sync with the observable
  1525. * attribute as it changes,
  1526. * * or an HTML element DOM event, so the DOM events are propagated through an observable.
  1527. *
  1528. * Some common use cases of `to()` bindings are presented below:
  1529. *
  1530. * const bind = Template.bind( observable, emitter );
  1531. *
  1532. * new Template( {
  1533. * tag: 'p',
  1534. * attributes: {
  1535. * // class="..." attribute gets bound to `observable#a`
  1536. * class: bind.to( 'a' )
  1537. * },
  1538. * children: [
  1539. * // <p>...</p> gets bound to observable#b; always `toUpperCase()`.
  1540. * {
  1541. * text: bind.to( 'b', ( value, node ) => value.toUpperCase() )
  1542. * }
  1543. * ],
  1544. * on: {
  1545. * click: [
  1546. * // An observable will fire "clicked" upon "click" in the DOM.
  1547. * bind.to( 'clicked' ),
  1548. *
  1549. * // A custom callback will be executed upon "click" in the DOM.
  1550. * bind.to( () => {
  1551. * ...
  1552. * } )
  1553. * ]
  1554. * }
  1555. * } ).render();
  1556. *
  1557. * Learn more about using `to()` in the {@link module:ui/template~TemplateValueSchema} and
  1558. * {@link module:ui/template~TemplateListenerSchema}.
  1559. *
  1560. * @method #to
  1561. * @param {String|Function} eventNameOrFunctionOrAttribute An attribute name of
  1562. * {@link module:utils/observablemixin~Observable} or a DOM event name or an event callback.
  1563. * @param {Function} [callback] Allows for processing of the value. Accepts `Node` and `value` as arguments.
  1564. * @return {module:ui/template~TemplateBinding}
  1565. */
  1566. /**
  1567. * Binds an {@link module:utils/observablemixin~Observable observable} to an HTML element attribute or a text
  1568. * node `textContent` so it remains in sync with the observable attribute as it changes.
  1569. *
  1570. * Unlike {@link module:ui/template~BindChain#to}, it controls the presence of the attribute or `textContent`
  1571. * depending on the "falseness" of an {@link module:utils/observablemixin~Observable} attribute.
  1572. *
  1573. * const bind = Template.bind( observable, emitter );
  1574. *
  1575. * new Template( {
  1576. * tag: 'input',
  1577. * attributes: {
  1578. * // <input checked> when `observable#a` is not undefined/null/false/''
  1579. * // <input> when `observable#a` is undefined/null/false
  1580. * checked: bind.if( 'a' )
  1581. * },
  1582. * children: [
  1583. * {
  1584. * // <input>"b-is-not-set"</input> when `observable#b` is undefined/null/false/''
  1585. * // <input></input> when `observable#b` is not "falsy"
  1586. * text: bind.if( 'b', 'b-is-not-set', ( value, node ) => !value )
  1587. * }
  1588. * ]
  1589. * } ).render();
  1590. *
  1591. * Learn more about using `if()` in the {@link module:ui/template~TemplateValueSchema}.
  1592. *
  1593. * @method #if
  1594. * @param {String} attribute An attribute name of {@link module:utils/observablemixin~Observable} used in the binding.
  1595. * @param {String} [valueIfTrue] Value set when the {@link module:utils/observablemixin~Observable} attribute is not
  1596. * undefined/null/false/'' (empty string).
  1597. * @param {Function} [callback] Allows for processing of the value. Accepts `Node` and `value` as arguments.
  1598. * @return {module:ui/template~TemplateBinding}
  1599. */
  1600. /**
  1601. * The {@link module:ui/template~Template#_renderNode} configuration.
  1602. *
  1603. * @private
  1604. * @interface module:ui/template~RenderData
  1605. */
  1606. /**
  1607. * Tells {@link module:ui/template~Template#_renderNode} to render
  1608. * children into `DocumentFragment` first and then append the fragment
  1609. * to the parent element. It is a speed optimization.
  1610. *
  1611. * @member {Boolean} #intoFragment
  1612. */
  1613. /**
  1614. * A node which is being rendered.
  1615. *
  1616. * @member {HTMLElement|Text} #node
  1617. */
  1618. /**
  1619. * Indicates whether the {@module:ui/template~RenderNodeOptions#node} has
  1620. * been provided by {@module:ui/template~Template#apply}.
  1621. *
  1622. * @member {Boolean} #isApplying
  1623. */
  1624. /**
  1625. * An object storing the data that helps {@module:ui/template~Template#revert}
  1626. * bringing back an element to its initial state, i.e. before
  1627. * {@module:ui/template~Template#apply} was called.
  1628. *
  1629. * @member {Object} #revertData
  1630. */