8
0

view.js 19 KB

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