view.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import Collection from '../collection.js';
  7. import Region from './region.js';
  8. import Template from './template.js';
  9. import CKEditorError from '../ckeditorerror.js';
  10. import DOMEmitterMixin from './domemittermixin.js';
  11. import utils from '../utils.js';
  12. import isPlainObject from '../lib/lodash/isPlainObject.js';
  13. const bindToSymbol = Symbol( 'bind-to' );
  14. const bindIfSymbol = Symbol( 'bind-if' );
  15. /**
  16. * Basic View class.
  17. *
  18. * @class View
  19. * @mixins DOMEmitterMixin
  20. */
  21. export default class View {
  22. /**
  23. * Creates an instance of the {@link View} class.
  24. *
  25. * @param {Model} model (View)Model of this View.
  26. * @constructor
  27. */
  28. constructor( model ) {
  29. /**
  30. * Model of this view.
  31. *
  32. * @property {Model}
  33. */
  34. this.model = model || null;
  35. /**
  36. * Regions of this view. See {@link #register}.
  37. *
  38. * @property {Collection}
  39. */
  40. this.regions = new Collection( {
  41. idProperty: 'name'
  42. } );
  43. /**
  44. * Template of this view.
  45. *
  46. * @property {Object}
  47. */
  48. this.template = null;
  49. /**
  50. * Region selectors of this view. See {@link #register}.
  51. *
  52. * @private
  53. * @property {Object}
  54. */
  55. this._regionsSelectors = {};
  56. /**
  57. * Element of this view.
  58. *
  59. * @private
  60. * @property {HTMLElement}
  61. */
  62. this._element = null;
  63. /**
  64. * An instance of Template to generate {@link #_el}.
  65. *
  66. * @private
  67. * @property {Template}
  68. */
  69. this._template = null;
  70. }
  71. /**
  72. * Element of this view. The element is rendered on first reference
  73. * using {@link #template} definition and {@link #_template} object.
  74. *
  75. * @property element
  76. */
  77. get element() {
  78. if ( this._element ) {
  79. return this._element;
  80. }
  81. if ( !this.template ) {
  82. /**
  83. * Attempting to access an element of a view, which has no `template`
  84. * property.
  85. *
  86. * @error ui-view-notemplate
  87. */
  88. throw new CKEditorError( 'ui-view-notemplate' );
  89. }
  90. // Prepare pre–defined listeners.
  91. this._extendTemplateWithListenerAttachers( this.template );
  92. // Prepare pre–defined attribute bindings.
  93. this._extendTemplateWithModelBinders( this.template );
  94. this._template = new Template( this.template );
  95. return ( this._element = this._template.render() );
  96. }
  97. set element( el ) {
  98. this._element = el;
  99. }
  100. /**
  101. * And entry point to the interface which allows binding attributes of {@link View#model}
  102. * to the DOM items like HTMLElement attributes or Text Node `textContent`, so their state
  103. * is synchronized with {@link View#model}.
  104. *
  105. * @readonly
  106. * @property attributeBinder
  107. */
  108. get attributeBinder() {
  109. if ( this._attributeBinder ) {
  110. return this._attributeBinder;
  111. }
  112. const model = this.model;
  113. const binder = {
  114. /**
  115. * Binds {@link View#model} to HTMLElement attribute or Text Node `textContent`
  116. * so remains in sync with the Model when it changes.
  117. *
  118. * this.template = {
  119. * tag: 'p',
  120. * attributes: {
  121. * // class="..." attribute gets bound to this.model.a
  122. * 'class': bind.to( 'a' )
  123. * },
  124. * children: [
  125. * // <p>...</p> gets bound to this.model.b; always `toUpperCase()`.
  126. * { text: bind.to( 'b', ( node, value ) => value.toUpperCase() ) }
  127. * ]
  128. * }
  129. *
  130. * @property {attributeBinder.to}
  131. * @param {String} attribute Name of {@link View#model} used in the binding.
  132. * @param {Function} [callback] Allows processing of the value. Accepts `Node` and `value` as arguments.
  133. * @return {ViewModelBinding}
  134. */
  135. to( attribute, callback ) {
  136. return {
  137. type: bindToSymbol,
  138. model: model,
  139. attribute,
  140. callback
  141. };
  142. },
  143. /**
  144. * Binds {@link View#model} to HTMLElement attribute or Text Node `textContent`
  145. * so remains in sync with the Model when it changes. Unlike {@link View#attributeBinder.to},
  146. * it controls the presence of the attribute/`textContent` depending on the "falseness" of
  147. * {@link View#model} attribute.
  148. *
  149. * this.template = {
  150. * tag: 'input',
  151. * attributes: {
  152. * // <input checked> this.model.a is not undefined/null/false/''
  153. * // <input> this.model.a is undefined/null/false
  154. * checked: bind.if( 'a' )
  155. * },
  156. * children: [
  157. * {
  158. * // <input>"b-is-not-set"</input> when this.model.b is undefined/null/false/''
  159. * // <input></input> when this.model.b is not "falsy"
  160. * text: bind.if( 'b', 'b-is-not-set', ( node, value ) => !value )
  161. * }
  162. * ]
  163. * }
  164. *
  165. * @property {attributeBinder.if}
  166. * @param {String} attribute Name of {@link View#model} used in the binding.
  167. * @param {String} [valueIfTrue] Value set when {@link View#model} attribute is not undefined/null/false/''.
  168. * @param {Function} [callback] Allows processing of the value. Accepts `Node` and `value` as arguments.
  169. * @return {ViewModelBinding}
  170. */
  171. if( attribute, valueIfTrue, callback ) {
  172. return {
  173. type: bindIfSymbol,
  174. model: model,
  175. attribute,
  176. valueIfTrue,
  177. callback
  178. };
  179. }
  180. };
  181. return ( this._attributeBinder = binder );
  182. }
  183. /**
  184. * Initializes the view.
  185. */
  186. init() {
  187. this._initRegions();
  188. }
  189. /**
  190. * Registers a region in {@link #regions}.
  191. *
  192. * let view = new View();
  193. *
  194. * // region.name == "foo", region.element == view.element.firstChild
  195. * view.register( 'foo', el => el.firstChild );
  196. *
  197. * // region.name == "bar", region.element == view.element.querySelector( 'span' )
  198. * view.register( new Region( 'bar' ), 'span' );
  199. *
  200. * // region.name == "bar", region.element == view.element.querySelector( '#div#id' )
  201. * view.register( 'bar', 'div#id', true );
  202. *
  203. * // region.name == "baz", region.element == null
  204. * view.register( 'baz', true );
  205. *
  206. * @param {String|Region} stringOrRegion The name or an instance of the Region
  207. * to be registered. If `String`, the region will be created on the fly.
  208. * @param {String|Function|true} regionSelector The selector to retrieve region's element
  209. * in DOM when the region instance is initialized (see {@link Region#init}, {@link #init}).
  210. * @param {Boolean} [override] When set `true` it will allow overriding of registered regions.
  211. */
  212. register( ...args ) {
  213. let region, regionName;
  214. if ( typeof args[ 0 ] === 'string' ) {
  215. regionName = args[ 0 ];
  216. region = this.regions.get( regionName ) || new Region( regionName );
  217. } else if ( args[ 0 ] instanceof Region ) {
  218. regionName = args[ 0 ].name;
  219. region = args[ 0 ];
  220. } else {
  221. /**
  222. * A name of the region or an instance of Region is required.
  223. *
  224. * @error ui-view-register-wrongtype
  225. */
  226. throw new CKEditorError( 'ui-view-register-wrongtype' );
  227. }
  228. const regionSelector = args[ 1 ];
  229. if ( !regionSelector || !isValidRegionSelector( regionSelector ) ) {
  230. /**
  231. * The selector must be String, Function or `true`.
  232. *
  233. * @error ui-view-register-badselector
  234. */
  235. throw new CKEditorError( 'ui-view-register-badselector' );
  236. }
  237. const registered = this.regions.get( regionName );
  238. if ( !registered ) {
  239. this.regions.add( region );
  240. } else {
  241. if ( registered !== region ) {
  242. if ( !args[ 2 ] ) {
  243. /**
  244. * Overriding is possible only when `override` flag is set.
  245. *
  246. * @error ui-view-register-override
  247. */
  248. throw new CKEditorError( 'ui-view-register-override' );
  249. }
  250. this.regions.remove( registered );
  251. this.regions.add( region );
  252. }
  253. }
  254. this._regionsSelectors[ regionName ] = regionSelector;
  255. }
  256. /**
  257. * Applies template to existing DOM element in the context of a View.
  258. *
  259. * const element = document.createElement( 'div' );
  260. * const view = new View( new Model( { divClass: 'my-div' } ) );
  261. *
  262. * view.applyTemplateToElement( element, {
  263. * attrs: {
  264. * id: 'first-div',
  265. * class: view.bindToAttribute( 'divClass' )
  266. * },
  267. * on: {
  268. * click: 'elementClicked' // Will be fired by the View instance.
  269. * }
  270. * children: [
  271. * 'Div text.'
  272. * ]
  273. * } );
  274. *
  275. * element.outerHTML == "<div id="first-div" class="my-div">Div text.</div>"
  276. *
  277. * See: {@link Template#apply}.
  278. *
  279. * @param {DOMElement} element DOM Element to initialize.
  280. * @param {TemplateDefinition} def Template definition to be applied.
  281. */
  282. applyTemplateToElement( element, def ) {
  283. // Prepare pre–defined listeners.
  284. this._extendTemplateWithListenerAttachers( def );
  285. // Prepare pre–defined attribute bindings.
  286. this._extendTemplateWithModelBinders( def );
  287. new Template( def ).apply( element );
  288. }
  289. /**
  290. * Destroys the view instance. The process includes:
  291. *
  292. * 1. Removal of child views from {@link #regions}.
  293. * 2. Destruction of the {@link #regions}.
  294. * 3. Removal of {#link #_el} from DOM.
  295. */
  296. destroy() {
  297. let childView;
  298. this.stopListening();
  299. for ( let region of this.regions ) {
  300. while ( ( childView = region.views.get( 0 ) ) ) {
  301. region.views.remove( childView );
  302. }
  303. this.regions.remove( region ).destroy();
  304. }
  305. if ( this.template ) {
  306. this.element.remove();
  307. }
  308. this.model = this.regions = this.template = this._regionsSelectors = this._element = this._template = null;
  309. }
  310. /**
  311. * Initializes {@link #regions} of this view by passing a DOM element
  312. * generated from {@link #_regionsSelectors} into {@link Region#init}.
  313. *
  314. * @protected
  315. */
  316. _initRegions() {
  317. let region, regionEl, regionSelector;
  318. for ( region of this.regions ) {
  319. regionSelector = this._regionsSelectors[ region.name ];
  320. if ( typeof regionSelector == 'string' ) {
  321. regionEl = this.element.querySelector( regionSelector );
  322. } else if ( typeof regionSelector == 'function' ) {
  323. regionEl = regionSelector( this.element );
  324. } else {
  325. regionEl = null;
  326. }
  327. region.init( regionEl );
  328. }
  329. }
  330. /**
  331. * For a given event name or callback, returns a function which,
  332. * once executed in a context of an element, attaches native DOM listener
  333. * to the element. The listener executes given callback or fires View's event
  334. * of given name.
  335. *
  336. * @protected
  337. * @param {String|Function} evtNameOrCallback Event name to be fired on View or callback to execute.
  338. * @returns {Function} A listener attacher function to be executed in the context of an element.
  339. */
  340. _getDOMListenerAttacher( evtNameOrCallback ) {
  341. /**
  342. * Attaches a native DOM listener to given element. The listener executes the
  343. * callback or fires View's event.
  344. *
  345. * Note: If the selector is supplied, it narrows the scope to relevant targets only.
  346. * So instead of
  347. *
  348. * children: [
  349. * { tag: 'span', on: { click: 'foo' } }
  350. * { tag: 'span', on: { click: 'foo' } }
  351. * ]
  352. *
  353. * a single, more efficient listener can be attached that uses **event delegation**:
  354. *
  355. * children: [
  356. * { tag: 'span' }
  357. * { tag: 'span' }
  358. * ],
  359. * on: {
  360. * 'click@span': 'foo',
  361. * }
  362. *
  363. * @param {HTMLElement} el Element, to which the native DOM Event listener is attached.
  364. * @param {String} domEventName The name of native DOM Event.
  365. * @param {String} [selector] If provided, the selector narrows the scope to relevant targets only.
  366. */
  367. return ( el, domEvtName, selector ) => {
  368. // Use View's listenTo, so the listener is detached, when the View dies.
  369. this.listenTo( el, domEvtName, ( evt, domEvt ) => {
  370. if ( !selector || domEvt.target.matches( selector ) ) {
  371. if ( typeof evtNameOrCallback == 'function' ) {
  372. evtNameOrCallback( domEvt );
  373. } else {
  374. this.fire( evtNameOrCallback, domEvt );
  375. }
  376. }
  377. } );
  378. };
  379. }
  380. /**
  381. * For given {@link TemplateValueSchema} found by (@link _extendTemplateWithModelBinders} containing
  382. * {@link ViewModelBinding} it returns a function, which when called by {@link Template#render}
  383. * or {@link Template#apply} activates the binding and sets its initial value.
  384. *
  385. * Note: {@link TemplateValueSchema} can be for HTMLElement attributes or Text Node `textContent`.
  386. *
  387. * @protected
  388. * @param {TemplateValueSchema}
  389. * @return {Function}
  390. */
  391. _getModelBinder( valueSchema ) {
  392. valueSchema = normalizeBinderValueSchema( valueSchema );
  393. /**
  394. * Assembles the value using {@link TemplateValueSchema} and stores it in a form of
  395. * an Array. Each entry of an Array corresponds to one of {@link TemplateValueSchema}
  396. * items.
  397. *
  398. * @private
  399. * @param {HTMLElement} el
  400. * @return {Array}
  401. */
  402. const getBoundValue = ( el ) => {
  403. let model, modelValue;
  404. return valueSchema.map( schemaItem => {
  405. model = schemaItem.model;
  406. if ( model ) {
  407. modelValue = model[ schemaItem.attribute ];
  408. if ( schemaItem.callback ) {
  409. modelValue = schemaItem.callback( el, modelValue );
  410. }
  411. return modelValue;
  412. } else {
  413. return schemaItem;
  414. }
  415. } );
  416. };
  417. /**
  418. * Attaches a listener to {@link View#model}, which updates DOM with a value constructed from
  419. * {@link TemplateValueSchema} when {@link View#model} attribute value changes.
  420. *
  421. * This function is called by {@link Template#render} or {@link Template#apply}.
  422. *
  423. * @param {HTMLElement} el DOM element to be updated when {@link View#model} changes.
  424. * @param {Function} domUpdater A function provided by {@link Template} which updates corresponding
  425. * DOM attribute or `textContent`.
  426. */
  427. return ( el, domUpdater ) => {
  428. // Check if valueSchema is a single bind.if, like:
  429. // { class: bind.if( 'foo' ) }
  430. const isPlainBindIf = valueSchema.length == 1 && valueSchema[ 0 ].type == bindIfSymbol;
  431. // A function executed each time bound model attribute changes.
  432. const onModelChange = () => {
  433. let value = getBoundValue( el );
  434. if ( isPlainBindIf ) {
  435. value = value[ 0 ];
  436. } else {
  437. value = value.reduce( binderValueReducer, '' );
  438. }
  439. const isSet = isPlainBindIf ? !!value : value;
  440. const valueToSet = isPlainBindIf ?
  441. ( valueSchema[ 0 ].valueIfTrue || '' ) : value;
  442. if ( isSet ) {
  443. domUpdater.set( valueToSet );
  444. } else {
  445. domUpdater.remove();
  446. }
  447. };
  448. valueSchema
  449. .filter( schemaItem => schemaItem.model )
  450. .forEach( schemaItem => {
  451. this.listenTo( schemaItem.model, 'change:' + schemaItem.attribute, onModelChange );
  452. } );
  453. // Set initial values.
  454. onModelChange();
  455. };
  456. }
  457. /**
  458. * Iterates over "attributes" and "text" properties in {@link TemplateDefinition} and
  459. * locates existing {@link ViewModelBinding} created by {@link #attributeBinder}.
  460. * Then, for each such a binding, it creates corresponding entry in {@link Template#_modelBinders},
  461. * which can be then activated by {@link Template#render} or {@link Template#apply}.
  462. *
  463. * @protected
  464. * @param {TemplateDefinition}
  465. */
  466. _extendTemplateWithModelBinders( def ) {
  467. const attributes = def.attributes;
  468. const text = def.text;
  469. let binders = def._modelBinders;
  470. let attrName, attrValue;
  471. if ( !binders && isPlainObject( def ) ) {
  472. Object.defineProperty( def, '_modelBinders', {
  473. enumerable: false,
  474. writable: true,
  475. value: {
  476. attributes: {}
  477. }
  478. } );
  479. binders = def._modelBinders;
  480. }
  481. if ( attributes ) {
  482. for ( attrName in attributes ) {
  483. attrValue = attributes[ attrName ];
  484. if ( hasModelBinding( attrValue ) ) {
  485. binders.attributes[ attrName ] = this._getModelBinder( attrValue );
  486. }
  487. }
  488. }
  489. if ( text && hasModelBinding( text ) ) {
  490. binders.text = this._getModelBinder( text );
  491. }
  492. // Repeat recursively for the children.
  493. if ( def.children ) {
  494. def.children.forEach( this._extendTemplateWithModelBinders, this );
  495. }
  496. }
  497. /**
  498. * Iterates over "on" property in {@link TemplateDefinition} to recursively
  499. * replace each listener declaration with a function which, once executed in a context
  500. * of an element, attaches native DOM listener to that element.
  501. *
  502. * @protected
  503. * @param {TemplateDefinition} def Template definition.
  504. */
  505. _extendTemplateWithListenerAttachers( def ) {
  506. const on = def.on;
  507. // Don't create attachers if they're already here or in the context of the same (this) View instance.
  508. if ( on && ( !on._listenerAttachers || on._listenerView != this ) ) {
  509. let domEvtName, evtNameOrCallback;
  510. Object.defineProperty( on, '_listenerAttachers', {
  511. enumerable: false,
  512. writable: true,
  513. value: {}
  514. } );
  515. for ( domEvtName in on ) {
  516. evtNameOrCallback = on[ domEvtName ];
  517. // Listeners allow definition with an array:
  518. //
  519. // on: {
  520. // 'DOMEventName@selector': [ 'event1', callback ],
  521. // 'DOMEventName': [ callback, 'event2', 'event3' ]
  522. // ...
  523. // }
  524. if ( Array.isArray( evtNameOrCallback ) ) {
  525. on._listenerAttachers[ domEvtName ] = on[ domEvtName ].map( this._getDOMListenerAttacher, this );
  526. }
  527. // Listeners allow definition with a string containing event name:
  528. //
  529. // on: {
  530. // 'DOMEventName@selector': 'event1',
  531. // 'DOMEventName': 'event2'
  532. // ...
  533. // }
  534. else {
  535. on._listenerAttachers[ domEvtName ] = this._getDOMListenerAttacher( evtNameOrCallback );
  536. }
  537. }
  538. // Set this property to be known that these attachers has already been created
  539. // in the context of this particular View instance.
  540. Object.defineProperty( on, '_listenerView', {
  541. enumerable: false,
  542. writable: true,
  543. value: this
  544. } );
  545. }
  546. // Repeat recursively for the children.
  547. if ( def.children ) {
  548. def.children.forEach( this._extendTemplateWithListenerAttachers, this );
  549. }
  550. }
  551. }
  552. utils.mix( View, DOMEmitterMixin );
  553. const validSelectorTypes = new Set( [ 'string', 'boolean', 'function' ] );
  554. /**
  555. * Check whether region selector is valid.
  556. *
  557. * @private
  558. * @param {*} selector Selector to be checked.
  559. * @returns {Boolean}
  560. */
  561. function isValidRegionSelector( selector ) {
  562. return validSelectorTypes.has( typeof selector ) && selector !== false;
  563. }
  564. /**
  565. * Normalizes given {@link TemplateValueSchema} it's always in an Array–like format:
  566. *
  567. * { attributeName/text: 'bar' } ->
  568. * { attributeName/text: [ 'bar' ] }
  569. *
  570. * { attributeName/text: { model: ..., modelAttributeName: ..., callback: ... } } ->
  571. * { attributeName/text: [ { model: ..., modelAttributeName: ..., callback: ... } ] }
  572. *
  573. * { attributeName/text: [ 'bar', { model: ..., modelAttributeName: ... }, 'baz' ] }
  574. *
  575. * @private
  576. * @param {TemplateValueSchema} valueSchema
  577. * @returns {Array}
  578. */
  579. function normalizeBinderValueSchema( valueSchema ) {
  580. return Array.isArray( valueSchema ) ? valueSchema : [ valueSchema ];
  581. }
  582. /**
  583. * Checks whether given {@link TemplateValueSchema} contains a
  584. * {@link ViewModelBinding}.
  585. *
  586. * @private
  587. * @param {TemplateValueSchema} valueSchema
  588. * @returns {Boolean}
  589. */
  590. function hasModelBinding( valueSchema ) {
  591. if ( Array.isArray( valueSchema ) ) {
  592. return valueSchema.some( hasModelBinding );
  593. } else if ( valueSchema.model ) {
  594. return true;
  595. }
  596. return false;
  597. }
  598. /**
  599. * A helper which concatenates the value avoiding unwanted
  600. * leading white spaces.
  601. *
  602. * @private
  603. * @param {String} prev
  604. * @param {String} cur
  605. * @returns {String}
  606. */
  607. function binderValueReducer( prev, cur ) {
  608. return prev === '' ? `${cur}` : `${prev} ${cur}`;
  609. }
  610. /**
  611. * Describes Model binding created by {@link View#attributeBinder}.
  612. *
  613. * @typedef ViewModelBinding
  614. * @type Object
  615. * @property {Symbol} type
  616. * @property {Model} model
  617. * @property {String} attribute
  618. * @property {String} [valueIfTrue]
  619. * @property {Funcion} [callback]
  620. */