conversion.js 20 KB

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