conversion.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/conversion/conversion
  7. */
  8. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  9. import {
  10. downcastElementToElement,
  11. downcastAttributeToElement,
  12. downcastAttributeToAttribute
  13. } from './downcast-converters';
  14. import {
  15. upcastElementToElement,
  16. upcastElementToAttribute,
  17. upcastAttributeToAttribute
  18. } from './upcast-converters';
  19. /**
  20. * An utility class that helps organizing dispatchers and adding converters to them.
  21. */
  22. export default class Conversion {
  23. /**
  24. * Creates new Conversion instance.
  25. */
  26. constructor() {
  27. this._dispatchersGroups = new Map();
  28. }
  29. /**
  30. * Registers one or more converters under given group name. Then, group name can be used to assign a converter
  31. * to multiple dispatchers at once.
  32. *
  33. * If given group name is used for a second time,
  34. * {@link module:utils/ckeditorerror~CKEditorError conversion-register-group-exists} error is thrown.
  35. *
  36. * @param {String} groupName A name for dispatchers group.
  37. * @param {Array.<module:engine/conversion/downcastdispatcher~DowncastDispatcher|
  38. * module:engine/conversion/upcastdispatcher~UpcastDispatcher>} dispatchers Dispatchers to register
  39. * under given name.
  40. */
  41. register( groupName, dispatchers ) {
  42. if ( this._dispatchersGroups.has( groupName ) ) {
  43. /**
  44. * Trying to register a group name that was already registered.
  45. *
  46. * @error conversion-register-group-exists
  47. */
  48. throw new CKEditorError( 'conversion-register-group-exists: Trying to register a group name that was already registered.' );
  49. }
  50. this._dispatchersGroups.set( groupName, dispatchers );
  51. }
  52. /**
  53. * Provides chainable API to assign converters to dispatchers registered under given group name. Converters are added
  54. * by calling `.add()` method of an object returned by this function.
  55. *
  56. * conversion.for( 'downcast' )
  57. * .add( conversionHelperA )
  58. * .add( conversionHelperB );
  59. *
  60. * In above example, `conversionHelperA` and `conversionHelperB` will be called for all dispatchers from `'model'` group.
  61. *
  62. * `.add()` takes exactly one parameter, which is a function. That function should accept one parameter, which
  63. * is a dispatcher instance. The function should add an actual converter to passed dispatcher instance.
  64. *
  65. * Conversion helpers for most common cases are already provided. They are flexible enough to cover most use cases.
  66. * See documentation to learn how they can be configured.
  67. *
  68. * For downcast (model to view conversion), these are:
  69. *
  70. * * {@link module:engine/conversion/downcast-converters~downcastElementToElement downcast element to element converter},
  71. * * {@link module:engine/conversion/downcast-converters~downcastAttributeToElement downcast attribute to element converter},
  72. * * {@link module:engine/conversion/downcast-converters~downcastAttributeToAttribute downcast attribute to attribute converter}.
  73. *
  74. * For upcast (view to model conversion), these are:
  75. *
  76. * * {@link module:engine/conversion/upcast-converters~upcastElementToElement upcast element to element converter},
  77. * * {@link module:engine/conversion/upcast-converters~upcastElementToAttribute upcast attribute to element converter},
  78. * * {@link module:engine/conversion/upcast-converters~upcastAttributeToAttribute upcast attribute to attribute converter}.
  79. *
  80. * An example of using conversion helpers to convert `paragraph` model element to `p` view element (and back):
  81. *
  82. * // Define conversion configuration - model element 'paragraph' should be converted to view element 'p'.
  83. * const config = { model: 'paragraph', view: 'p' };
  84. *
  85. * // Add converters to proper dispatchers using conversion helpers.
  86. * conversion.for( 'downcast' ).add( downcastElementToElement( config ) );
  87. * conversion.for( 'upcast' ).add( upcastElementToElement( config ) );
  88. *
  89. * An example of providing custom conversion helper that uses custom converter function:
  90. *
  91. * // Adding custom `myConverter` converter for 'paragraph' element insertion, with default priority ('normal').
  92. * conversion.for( 'downcast' ).add( conversion.customConverter( 'insert:paragraph', myConverter ) );
  93. *
  94. * @param {String} groupName Name of dispatchers group to add converters to.
  95. * @returns {Object} Object with `.add()` method, providing a way to add converters.
  96. */
  97. for( groupName ) {
  98. const dispatchers = this._getDispatchers( groupName );
  99. return {
  100. add( conversionHelper ) {
  101. _addToDispatchers( dispatchers, conversionHelper );
  102. return this;
  103. }
  104. };
  105. }
  106. /**
  107. * Sets up converters between the model and the view which convert a model element to a view element (and vice versa).
  108. * For example, model `<paragraph>Foo</paragraph>` is `<p>Foo</p>` in the view.
  109. *
  110. * // Simple conversion from `paragraph` model element to `<p>` view element (and vice versa).
  111. * conversion.elementToElement( { model: 'paragraph', view: 'p' } );
  112. *
  113. * // Override other converters by specifying converter definition with higher priority.
  114. * conversion.elementToElement( { model: 'paragraph', view: 'div', priority: 'high' } );
  115. *
  116. * // View specified as an object instead of a string.
  117. * conversion.elementToElement( {
  118. * model: 'fancyParagraph',
  119. * view: {
  120. * name: 'p',
  121. * class: 'fancy'
  122. * }
  123. * } );
  124. *
  125. * // Use `upcastAlso` to define other view elements that should be also converted to `paragraph` element.
  126. * conversion.elementToElement( {
  127. * model: 'paragraph',
  128. * view: 'p',
  129. * upcastAlso: [
  130. * 'div',
  131. * {
  132. * // Any element with `display: block` style.
  133. * style: {
  134. * display: 'block'
  135. * }
  136. * }
  137. * ]
  138. * } );
  139. *
  140. * // `upcastAlso` set as callback enables a conversion of a wide range of different view elements.
  141. * conversion.elementToElement( {
  142. * model: 'heading',
  143. * view: 'h2',
  144. * // Convert "headling-like" paragraphs to headings.
  145. * upcastAlso: viewElement => {
  146. * const fontSize = viewElement.getStyle( 'font-size' );
  147. *
  148. * if ( !fontSize ) {
  149. * return null;
  150. * }
  151. *
  152. * const match = fontSize.match( /(\d+)\s*px/ );
  153. *
  154. * if ( !match ) {
  155. * return null;
  156. * }
  157. *
  158. * const size = Number( match[ 1 ] );
  159. *
  160. * if ( size > 26 ) {
  161. * // Returned value be an object with the matched properties.
  162. * // Those properties will be "consumed" during conversion.
  163. * // See `engine.view.Matcher~MatcherPattern` and `engine.view.Matcher#match` for more.
  164. *
  165. * return { name: true, style: [ 'font-size' ] };
  166. * }
  167. *
  168. * return null;
  169. * }
  170. * } );
  171. *
  172. * `definition.model` is a `String` with a model element name to converter from/to.
  173. * See {@link module:engine/conversion/conversion~ConverterDefinition} to learn about other parameters.
  174. *
  175. * @param {module:engine/conversion/conversion~ConverterDefinition} definition Converter definition.
  176. */
  177. elementToElement( definition ) {
  178. // Set up downcast converter.
  179. this.for( 'downcast' ).add( downcastElementToElement( definition ) );
  180. // Set up upcast converter.
  181. for ( const { model, view } of _getAllUpcastDefinitions( definition ) ) {
  182. this.for( 'upcast' ).add(
  183. upcastElementToElement( {
  184. model,
  185. view,
  186. priority: definition.priority
  187. } )
  188. );
  189. }
  190. }
  191. /**
  192. * Sets up converters between the model and the view which convert a model attribute to a view element (and vice versa).
  193. * For example, model text node with data `"Foo"` and `bold` attribute is `<strong>Foo</strong>` in the view.
  194. *
  195. * // Simple conversion from `bold=true` attribute to `<strong>` view element (and vice versa).
  196. * conversion.attributeToElement( { model: 'bold', view: 'strong' } );
  197. *
  198. * // Override other converters by specifying converter definition with higher priority.
  199. * conversion.attributeToElement( { model: 'bold', view: 'b', priority: 'high' } );
  200. *
  201. * // View specified as an object instead of a string.
  202. * conversion.attributeToElement( {
  203. * model: 'bold',
  204. * view: {
  205. * name: 'span',
  206. * class: 'bold'
  207. * }
  208. * } );
  209. *
  210. * // Use `upcastAlso` to define other view elements that should be also converted to `bold` attribute.
  211. * conversion.attributeToElement( {
  212. * model: 'bold',
  213. * view: 'strong',
  214. * upcastAlso: [
  215. * 'b',
  216. * {
  217. * name: 'span',
  218. * class: 'bold'
  219. * },
  220. * {
  221. * name: 'span',
  222. * style: {
  223. * 'font-weight': 'bold'
  224. * }
  225. * },
  226. * viewElement => {
  227. * const fontWeight = viewElement.getStyle( 'font-weight' );
  228. *
  229. * if ( viewElement.is( 'span' ) && fontWeight && /\d+/.test() && Number( fontWeight ) > 500 ) {
  230. * // Returned value be an object with the matched properties.
  231. * // Those properties will be "consumed" during conversion.
  232. * // See `engine.view.Matcher~MatcherPattern` and `engine.view.Matcher#match` for more.
  233. *
  234. * return {
  235. * name: true,
  236. * style: [ 'font-weight' ]
  237. * };
  238. * }
  239. * }
  240. * ]
  241. * } );
  242. *
  243. * // Conversion from/to a model attribute key which value is an enum (`fontSize=big|small`).
  244. * // `upcastAlso` set as callback enables a conversion of a wide range of different view elements.
  245. * conversion.attributeToElement( {
  246. * model: {
  247. * key: 'fontSize',
  248. * values: [ 'big', 'small' ]
  249. * },
  250. * view: {
  251. * big: {
  252. * name: 'span',
  253. * style: {
  254. * 'font-size': '1.2em'
  255. * }
  256. * },
  257. * small: {
  258. * name: 'span',
  259. * style: {
  260. * 'font-size': '0.8em'
  261. * }
  262. * }
  263. * },
  264. * upcastAlso: {
  265. * big: viewElement => {
  266. * const fontSize = viewElement.getStyle( 'font-size' );
  267. *
  268. * if ( !fontSize ) {
  269. * return null;
  270. * }
  271. *
  272. * const match = fontSize.match( /(\d+)\s*px/ );
  273. *
  274. * if ( !match ) {
  275. * return null;
  276. * }
  277. *
  278. * const size = Number( match[ 1 ] );
  279. *
  280. * if ( viewElement.is( 'span' ) && size > 10 ) {
  281. * // Returned value be an object with the matched properties.
  282. * // Those properties will be "consumed" during conversion.
  283. * // See `engine.view.Matcher~MatcherPattern` and `engine.view.Matcher#match` for more.
  284. *
  285. * return { name: true, style: [ 'font-size' ] };
  286. * }
  287. *
  288. * return null;
  289. * },
  290. * small: viewElement => {
  291. * const fontSize = viewElement.getStyle( 'font-size' );
  292. *
  293. * if ( !fontSize ) {
  294. * return null;
  295. * }
  296. *
  297. * const match = fontSize.match( /(\d+)\s*px/ );
  298. *
  299. * if ( !match ) {
  300. * return null;
  301. * }
  302. *
  303. * const size = Number( match[ 1 ] );
  304. *
  305. * if ( viewElement.is( 'span' ) && size < 10 ) {
  306. * // Returned value be an object with the matched properties.
  307. * // Those properties will be "consumed" during conversion.
  308. * // See `engine.view.Matcher~MatcherPattern` and `engine.view.Matcher#match` for more.
  309. *
  310. * return { name: true, style: [ 'font-size' ] };
  311. * }
  312. *
  313. * return null;
  314. * }
  315. * }
  316. * } );
  317. *
  318. * `definition.model` parameter specifies what model attribute should be converted from/to. It can be a `{ key, value }` object
  319. * describing attribute key and value to convert or a `String` specifying just attribute key (then `value` is set to `true`).
  320. * See {@link module:engine/conversion/conversion~ConverterDefinition} to learn about other parameters.
  321. *
  322. * @param {module:engine/conversion/conversion~ConverterDefinition} definition Converter definition.
  323. */
  324. attributeToElement( definition ) {
  325. // Set up downcast converter.
  326. this.for( 'downcast' ).add( downcastAttributeToElement( definition ) );
  327. // Set up upcast converter.
  328. for ( const { model, view } of _getAllUpcastDefinitions( definition ) ) {
  329. this.for( 'upcast' ).add(
  330. upcastElementToAttribute( {
  331. view,
  332. model,
  333. priority: definition.priority
  334. } )
  335. );
  336. }
  337. }
  338. /**
  339. * Sets up converters between the model and the view which convert a model attribute to a view attribute (and vice versa).
  340. * For example, `<image src='foo.jpg'></image>` is converted to `<img src='foo.jpg'></img>` (same attribute key and value).
  341. *
  342. * // Simple conversion from `source` model attribute to `src` view attribute (and vice versa).
  343. * conversion.attributeToAttribute( { model: 'source', view: 'src' } );
  344. *
  345. * // Attributes values are strictly specified.
  346. * conversion.attributeToAttribute( {
  347. * model: {
  348. * name: 'image',
  349. * key: 'aside',
  350. * values: [ 'aside' ]
  351. * },
  352. * view: {
  353. * aside: {
  354. * name: 'img',
  355. * key: 'class',
  356. * value: [ 'aside', 'half-size' ]
  357. * }
  358. * }
  359. * } );
  360. *
  361. * // Set style attribute.
  362. * conversion.attributeToAttribute( {
  363. * model: {
  364. * name: 'image',
  365. * key: 'aside',
  366. * values: [ 'aside' ]
  367. * },
  368. * view: {
  369. * aside: {
  370. * name: 'img',
  371. * key: 'style',
  372. * value: {
  373. * float: 'right',
  374. * width: '50%',
  375. * margin: '5px'
  376. * }
  377. * }
  378. * }
  379. * } );
  380. *
  381. * // Conversion from/to a model attribute key which value is an enum (`align=right|center`).
  382. * // Use `upcastAlso` to define other view elements that should be also converted to `align=right` attribute.
  383. * conversion.attributeToAttribute( {
  384. * model: {
  385. * key: 'align',
  386. * values: [ 'right', 'center' ]
  387. * },
  388. * view: {
  389. * right: {
  390. * key: 'class',
  391. * value: 'align-right'
  392. * },
  393. * center: {
  394. * key: 'class',
  395. * value: 'align-center'
  396. * }
  397. * },
  398. * upcastAlso: {
  399. * right: {
  400. * style: {
  401. * 'text-align': 'right'
  402. * }
  403. * },
  404. * center: {
  405. * style: {
  406. * 'text-align': 'center'
  407. * }
  408. * }
  409. * }
  410. * } );
  411. *
  412. * `definition.model` parameter specifies what model attribute should be converted from/to.
  413. * It can be a `{ key, [ values ], [ name ] }` object or a `String`, which will be treated like `{ key: definition.model }`.
  414. * `key` property is the model attribute key to convert from/to.
  415. * `values` are the possible model attribute values. If `values` is not set, model attribute value will be the same as the
  416. * view attribute value.
  417. * If `name` is set, conversion will be set up only for model elements with the given name.
  418. *
  419. * `definition.view` parameter specifies what view attribute should be converted from/to.
  420. * It can be a `{ key, value, [ name ] }` object or a `String`, which will be treated like `{ key: definition.view }`.
  421. * `key` property is the view attribute key to convert from/to.
  422. * `value` is the view attribute value to convert from/to. If `definition.value` is not set, view attribute value will be
  423. * the same as the model attribute value.
  424. * If `key` is `'class'`, `value` can be a `String` or an array of `String`s.
  425. * If `key` is `'style'`, `value` is an object with key-value pairs.
  426. * In other cases, `value` is a `String`.
  427. * If `name` is set, conversion will be set up only for model elements with the given name.
  428. * If `definition.model.values` is set, `definition.view` is an object which assigns values from `definition.model.values`
  429. * to `{ key, value, [ name ] }` objects.
  430. *
  431. * `definition.upcastAlso` specifies which other matching view elements should be also upcast to given model configuration.
  432. * If `definition.model.values` is set, `definition.upcastAlso` should be an object assigning values from `definition.model.values`
  433. * to {@link module:engine/view/matcher~MatcherPattern}s or arrays of {@link module:engine/view/matcher~MatcherPattern}s.
  434. *
  435. * **Note:** `definition.model` and `definition.view` form should be mirrored, that is the same type of parameters should
  436. * be given in both parameters.
  437. *
  438. * @param {Object} definition Converter definition.
  439. * @param {String|Object} definition.model Model attribute to convert from/to.
  440. * @param {String|Object} definition.view View attribute to convert from/to.
  441. * @param {module:engine/view/matcher~MatcherPattern|Array.<module:engine/view/matcher~MatcherPattern>} [definition.upcastAlso]
  442. * Any view element matching `definition.upcastAlso` will also be converted to the given model attribute. `definition.upcastAlso`
  443. * is used only if `config.model.values` is specified.
  444. */
  445. attributeToAttribute( definition ) {
  446. // Set up downcast converter.
  447. this.for( 'downcast' ).add( downcastAttributeToAttribute( definition ) );
  448. // Set up upcast converter.
  449. for ( const { model, view } of _getAllUpcastDefinitions( definition ) ) {
  450. this.for( 'upcast' ).add(
  451. upcastAttributeToAttribute( {
  452. view,
  453. model
  454. } )
  455. );
  456. }
  457. }
  458. /**
  459. * Returns dispatchers registered under given group name.
  460. *
  461. * If given group name has not been registered,
  462. * {@link module:utils/ckeditorerror~CKEditorError conversion-for-unknown-group} error is thrown.
  463. *
  464. * @private
  465. * @param {String} groupName
  466. * @returns {Array.<module:engine/conversion/downcastdispatcher~DowncastDispatcher|
  467. * module:engine/conversion/upcastdispatcher~UpcastDispatcher>}
  468. */
  469. _getDispatchers( groupName ) {
  470. const dispatchers = this._dispatchersGroups.get( groupName );
  471. if ( !dispatchers ) {
  472. /**
  473. * Trying to add a converter to an unknown dispatchers group.
  474. *
  475. * @error conversion-for-unknown-group
  476. */
  477. throw new CKEditorError( 'conversion-for-unknown-group: Trying to add a converter to an unknown dispatchers group.' );
  478. }
  479. return dispatchers;
  480. }
  481. }
  482. /**
  483. * Defines how the model should be converted from/to the view.
  484. *
  485. * @typedef {Object} module:engine/conversion/conversion~ConverterDefinition
  486. *
  487. * @property {*} [model] Model conversion definition. Describes model element or model attribute to convert. This parameter differs
  488. * for different functions that accepts `ConverterDefinition`. See the description of a function to learn how to set it.
  489. * @property {module:engine/view/elementdefinition~ElementDefinition|Object} view Definition of a view element to convert from/to.
  490. * If `model` describes multiple values, `view` is an object that assigns those values (`view` object keys) to view element definitions
  491. * (`view` object values).
  492. * @property {module:engine/view/matcher~MatcherPattern|Array.<module:engine/view/matcher~MatcherPattern>} [upcastAlso]
  493. * Any view element matching `upcastAlso` will also be converted to model. If `model` describes multiple values, `upcastAlso`
  494. * is an object that assigns those values (`upcastAlso` object keys) to {@link module:engine/view/matcher~MatcherPattern}s
  495. * (`upcastAlso` object values).
  496. * @property {module:utils/priorities~PriorityString} [priority] Conversion priority.
  497. */
  498. // Helper function for `Conversion` `.add()` method.
  499. //
  500. // Calls `conversionHelper` on each dispatcher from the group specified earlier in `.for()` call, effectively
  501. // adding converters to all specified dispatchers.
  502. //
  503. // @private
  504. // @param {Array.<module:engine/conversion/downcastdispatcher~DowncastDispatcher|
  505. // module:engine/conversion/upcastdispatcher~UpcastDispatcher>} dispatchers
  506. // @param {Function} conversionHelper
  507. function _addToDispatchers( dispatchers, conversionHelper ) {
  508. for ( const dispatcher of dispatchers ) {
  509. conversionHelper( dispatcher );
  510. }
  511. }
  512. // Helper function that creates a joint array out of an item passed in `definition.view` and items passed in
  513. // `definition.upcastAlso`.
  514. //
  515. // @param {module:engine/conversion/conversion~ConverterDefinition} definition
  516. // @returns {Array} Array containing view definitions.
  517. function* _getAllUpcastDefinitions( definition ) {
  518. if ( definition.model.values ) {
  519. for ( const value of definition.model.values ) {
  520. const model = { key: definition.model.key, value };
  521. const view = definition.view[ value ];
  522. const upcastAlso = definition.upcastAlso ? definition.upcastAlso[ value ] : undefined;
  523. yield* _getUpcastDefinition( model, view, upcastAlso );
  524. }
  525. } else {
  526. yield* _getUpcastDefinition( definition.model, definition.view, definition.upcastAlso );
  527. }
  528. }
  529. function* _getUpcastDefinition( model, view, upcastAlso ) {
  530. yield { model, view };
  531. if ( upcastAlso ) {
  532. upcastAlso = Array.isArray( upcastAlso ) ? upcastAlso : [ upcastAlso ];
  533. for ( const upcastAlsoItem of upcastAlso ) {
  534. yield { model, view: upcastAlsoItem };
  535. }
  536. }
  537. }