template.js 49 KB

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