template.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /* global document */
  6. 'use strict';
  7. import CKEditorError from '../ckeditorerror.js';
  8. /**
  9. * Basic Template class.
  10. *
  11. * @class Template
  12. */
  13. export default class Template {
  14. /**
  15. * Creates an instance of the {@link Template} class.
  16. *
  17. * @param {TemplateDefinition} definition The definition of the template.
  18. * @constructor
  19. */
  20. constructor( def ) {
  21. /**
  22. * Definition of this template.
  23. *
  24. * @property {TemplateDefinition}
  25. */
  26. this.definition = def;
  27. }
  28. /**
  29. * Renders DOM Node using {@link #definition}.
  30. *
  31. * See: {@link #apply}.
  32. *
  33. * @returns {HTMLElement}
  34. */
  35. render() {
  36. return this._renderNode( this.definition, null, true );
  37. }
  38. /**
  39. * Applies template {@link #def} to existing DOM tree.
  40. *
  41. * **Note:** No new DOM nodes (elements, text nodes) will be created.
  42. *
  43. * See: {@link #render}, {@link View#applyTemplateToElement}.
  44. *
  45. * @param {Node} element Root element for template to apply.
  46. */
  47. apply( node ) {
  48. if ( !node ) {
  49. /**
  50. * No DOM Node specified.
  51. *
  52. * @error ui-template-wrong-syntax
  53. */
  54. throw new CKEditorError( 'ui-template-wrong-node' );
  55. }
  56. return this._renderNode( this.definition, node );
  57. }
  58. /**
  59. * Renders a DOM Node from definition.
  60. *
  61. * @protected
  62. * @param {TemplateDefinition} def Definition of a Node.
  63. * @param {Node} applyNode If specified, template `def` will be applied to existing DOM Node.
  64. * @param {Boolean} intoFragment If set, children are rendered into DocumentFragment.
  65. * @returns {HTMLElement} A rendered Node.
  66. */
  67. _renderNode( def, applyNode, intoFragment ) {
  68. const isText = def.text || typeof def == 'string';
  69. let isInvalid;
  70. if ( applyNode ) {
  71. // When applying, a definition cannot have "tag" and "text" at the same time.
  72. isInvalid = def.tag && isText;
  73. } else {
  74. // When rendering, a definition must have either "tag" or "text": XOR( def.tag, isText ).
  75. isInvalid = def.tag ? isText : !isText;
  76. }
  77. if ( isInvalid ) {
  78. /**
  79. * Node definition cannot have "tag" and "text" properties at the same time.
  80. * Node definition must have either "tag" or "text" when rendering new Node.
  81. *
  82. * @error ui-template-wrong-syntax
  83. */
  84. throw new CKEditorError( 'ui-template-wrong-syntax' );
  85. }
  86. return isText ?
  87. this._renderText( def, applyNode ) : this._renderElement( def, applyNode, intoFragment );
  88. }
  89. /**
  90. * Renders an HTMLElement from TemplateDefinition.
  91. *
  92. * @protected
  93. * @param {TemplateDefinition} def Definition of an element.
  94. * @param {HTMLElement} applyElement If specified, template `def` will be applied to existing HTMLElement.
  95. * @param {Boolean} intoFragment If set, children are rendered into DocumentFragment.
  96. * @returns {HTMLElement} A rendered element.
  97. */
  98. _renderElement( def, applyElement, intoFragment ) {
  99. const el = applyElement || document.createElement( def.tag );
  100. this._renderElementAttributes( def, el );
  101. // Invoke children recursively.
  102. if ( intoFragment ) {
  103. const docFragment = document.createDocumentFragment();
  104. this._renderElementChildren( def, docFragment );
  105. el.appendChild( docFragment );
  106. } else {
  107. this._renderElementChildren( def, el, !!applyElement );
  108. }
  109. // Activate DOM bindings for event listeners.
  110. this._activateElementListenerAttachers( def, el );
  111. return el;
  112. }
  113. /**
  114. * Renders a Text from TemplateDefinition or String.
  115. *
  116. * @protected
  117. * @param {TemplateDefinition|String} def Definition of Text or its value.
  118. * @param {HTMLElement} applyText If specified, template `def` will be applied to existing Text Node.
  119. * @returns {Text} A rendered Text.
  120. */
  121. _renderText( defOrText, applyText ) {
  122. const textNode = applyText || document.createTextNode( '' );
  123. // Check if there's a binder available for this Text Node.
  124. const binder = defOrText._modelBinders && defOrText._modelBinders.text;
  125. // Activate binder if one. Cases:
  126. // { text: bind.to( ... ) }
  127. // { text: [ 'foo', bind.to( ... ), ... ] }
  128. if ( binder ) {
  129. binder( textNode, getTextNodeUpdater( textNode ) );
  130. }
  131. // Simply set text. Cases:
  132. // { text: [ 'all', 'are', 'static' ] }
  133. // { text: 'foo' }
  134. // 'foo'
  135. else {
  136. textNode.textContent = defOrText.text || defOrText;
  137. }
  138. return textNode;
  139. }
  140. /**
  141. * Renders element attributes from definition.
  142. *
  143. * @protected
  144. * @param {TemplateDefinition} def Definition of an element.
  145. * @param {HTMLElement} el Element which is rendered.
  146. */
  147. _renderElementAttributes( def, el ) {
  148. const attributes = def.attributes;
  149. const binders = def._modelBinders && def._modelBinders.attributes;
  150. let binder, attrName, attrValue;
  151. if ( !attributes ) {
  152. return;
  153. }
  154. for ( attrName in attributes ) {
  155. // Check if there's a binder available for this attribute.
  156. binder = binders && binders[ attrName ];
  157. // Activate binder if one. Cases:
  158. // { class: [ 'bar', bind.to( ... ), 'baz' ] }
  159. // { class: bind.to( ... ) }
  160. if ( binder ) {
  161. binder( el, getElementAttributeUpdater( el, attrName ) );
  162. }
  163. // Otherwise simply set the attribute.
  164. // { class: [ 'all', 'are', 'static' ] }
  165. // { class: 'foo' }
  166. else {
  167. attrValue = attributes[ attrName ];
  168. // Attribute can be an array. Merge array elements:
  169. if ( Array.isArray( attrValue ) ) {
  170. attrValue = attrValue.reduce( function binderValueReducer( prev, cur ) {
  171. return prev === '' ? `${cur}` : `${prev} ${cur}`;
  172. } );
  173. }
  174. el.setAttribute( attrName, attrValue );
  175. }
  176. }
  177. }
  178. /**
  179. * Recursively renders element children from definition by
  180. * calling {@link #_renderElement}.
  181. *
  182. * @protected
  183. * @param {TemplateDefinition} def Definition of an element.
  184. * @param {HTMLElement} el Element which is rendered.
  185. * @param {Boolean} isApply Traverse existing DOM structure only, don't modify DOM.
  186. */
  187. _renderElementChildren( def, el, isApply ) {
  188. if ( def.children ) {
  189. def.children.forEach( ( childDef, index ) => {
  190. if ( isApply ) {
  191. this._renderNode( childDef, el.childNodes[ index ] );
  192. } else {
  193. el.appendChild( this._renderNode( childDef ) );
  194. }
  195. } );
  196. }
  197. }
  198. /**
  199. * Activates element `on` listeners passed in element definition.
  200. *
  201. * @protected
  202. * @param {TemplateDefinition} def Definition of an element.
  203. * @param {HTMLElement} el Element which is rendered.
  204. */
  205. _activateElementListenerAttachers( def, el ) {
  206. if ( !def.on ) {
  207. return;
  208. }
  209. const attachers = def.on._listenerAttachers;
  210. Object.keys( attachers )
  211. .map( name => [ name, ...name.split( '@' ) ] )
  212. .forEach( split => {
  213. // TODO: ES6 destructuring.
  214. const key = split[ 0 ];
  215. const evtName = split[ 1 ];
  216. const evtSelector = split[ 2 ] || null;
  217. if ( Array.isArray( attachers[ key ] ) ) {
  218. attachers[ key ].forEach( i => i( el, evtName, evtSelector ) );
  219. } else {
  220. attachers[ key ]( el, evtName, evtSelector );
  221. }
  222. } );
  223. }
  224. }
  225. /**
  226. * Returns an object consisting of `set` and `remove` functions, which
  227. * can be used in the context of DOM Node to set or reset `textContent`.
  228. * See {@link View#_getModelBinder}.
  229. *
  230. * @private
  231. * @param {Node} node DOM Node to be modified.
  232. * @returns {Object}
  233. */
  234. function getTextNodeUpdater( node ) {
  235. return {
  236. set( value ) {
  237. node.textContent = value;
  238. },
  239. remove() {
  240. node.textContent = '';
  241. }
  242. };
  243. }
  244. /**
  245. * Returns an object consisting of `set` and `remove` functions, which
  246. * can be used in the context of DOM Node to set or reset an attribute.
  247. * See {@link View#_getModelBinder}.
  248. *
  249. * @private
  250. * @param {Node} node DOM Node to be modified.
  251. * @param {String} attrName Name of the attribute to be modified.
  252. * @returns {Object}
  253. */
  254. function getElementAttributeUpdater( el, attrName ) {
  255. return {
  256. set( value ) {
  257. el.setAttribute( attrName, value );
  258. },
  259. remove() {
  260. el.removeAttribute( attrName );
  261. }
  262. };
  263. }
  264. /**
  265. * Definition of {@link Template}.
  266. * See: {@link TemplateValueSchema}.
  267. *
  268. * {
  269. * tag: 'p',
  270. * children: [
  271. * {
  272. * tag: 'span',
  273. * attributes: { ... },
  274. * children: [ ... ],
  275. * ...
  276. * },
  277. * {
  278. * text: 'static–text'
  279. * },
  280. * 'also-static–text',
  281. * ...
  282. * ],
  283. * attributes: {
  284. * 'class': [ 'class-a', 'class-b' ],
  285. * id: 'element-id',
  286. * style: callback,
  287. * ...
  288. * },
  289. * on: {
  290. * 'click': 'clicked'
  291. * 'mouseup': [ 'view-event-a', 'view-event-b', callback ],
  292. * 'keyup@selector': 'view-event',
  293. * 'focus@selector': [ 'view-event-a', 'view-event-b', callback ],
  294. * ...
  295. * }
  296. * }
  297. *
  298. * @typedef TemplateDefinition
  299. * @type Object
  300. * @property {String} tag
  301. * @property {Array} [children]
  302. * @property {Object} [attributes]
  303. * @property {String} [text]
  304. * @property {Object} [on]
  305. * @property {Object} _modelBinders
  306. */
  307. /**
  308. * Describes a value of HTMLElement attribute or `textContent`.
  309. * See: {@link TemplateDefinition}.
  310. *
  311. * {
  312. * tag: 'p',
  313. * attributes: {
  314. * // Plain String schema.
  315. * class: 'class-foo'
  316. *
  317. * // Object schema, a Model binding.
  318. * class: { model: m, attribute: 'foo', callback... }
  319. *
  320. * // Array schema, combines the above.
  321. * class: [ 'foo', { model: m, attribute: 'bar' }, 'baz' ]
  322. * }
  323. * }
  324. *
  325. * @typedef TemplateValueSchema
  326. * @type {Object|String|Array}
  327. */