upcast-converters.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import Matcher from '../view/matcher';
  6. import ModelRange from '../model/range';
  7. import ModelPosition from '../model/position';
  8. import cloneDeep from '@ckeditor/ckeditor5-utils/src/lib/lodash/cloneDeep';
  9. /**
  10. * Contains {@link module:engine/view/view view} to {@link module:engine/model/model model} converters for
  11. * {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher}.
  12. *
  13. * @module engine/conversion/upcast-converters
  14. */
  15. /**
  16. * View element to model element conversion helper.
  17. *
  18. * This conversion results in creating a model element. For example, view `<p>Foo</p>` becomes `<paragraph>Foo</paragraph>` in the model.
  19. *
  20. * Keep in mind that the element will be inserted only if it is allowed by {@link module:engine/model/schema~Schema schema} configuration.
  21. *
  22. * upcastElementToElement( { view: 'p', model: 'paragraph' } );
  23. *
  24. * upcastElementToElement( { view: 'p', model: 'paragraph' }, 'high' );
  25. *
  26. * upcastElementToElement( {
  27. * view: {
  28. * name: 'p',
  29. * class: 'fancy'
  30. * },
  31. * model: 'fancyParagraph'
  32. * } );
  33. *
  34. * upcastElementToElement( {
  35. * view: {
  36. * name: 'p',
  37. * class: 'fancy'
  38. * },
  39. * model: new ModelElement( 'p', { fancy: true } )
  40. * } );
  41. *
  42. * upcastElementToElement( {
  43. * view: {
  44. * name: 'p',
  45. * class: 'heading'
  46. * },
  47. * model: viewElement => new ModelElement( 'heading', { level: viewElement.getAttribute( 'data-level' ) } )
  48. * } );
  49. *
  50. * See {@link module:engine/conversion/conversion~Conversion#for} to learn how to add converter to conversion process.
  51. *
  52. * @param {Object} config Conversion configuration.
  53. * @param {module:engine/view/matcher~MatcherPattern} config.view Pattern matching all view elements which should be converted.
  54. * @param {String|module:engine/model/element~Element|Function} config.model Name of the model element, a model element
  55. * instance or a function that takes a view element and returns a model element. The model element will be inserted in the model.
  56. * @param {module:utils/priorities~PriorityString} [priority='normal'] Converter priority.
  57. * @returns {Function} Conversion helper.
  58. */
  59. export function upcastElementToElement( config, priority = 'normal' ) {
  60. config = cloneDeep( config );
  61. const converter = _prepareToElementConverter( config );
  62. const elementName = _getViewElementNameFromConfig( config );
  63. const eventName = elementName ? 'element:' + elementName : 'element';
  64. return dispatcher => {
  65. dispatcher.on( eventName, converter, { priority } );
  66. };
  67. }
  68. /**
  69. * View element to model attribute conversion helper.
  70. *
  71. * This conversion results in setting an attribute on a model node. For example, view `<strong>Foo</strong>` becomes
  72. * `Foo` {@link module:engine/model/text~Text model text node} with `bold` attribute set to `true`.
  73. *
  74. * Keep in mind that the attribute will be set only if it is allowed by {@link module:engine/model/schema~Schema schema} configuration.
  75. *
  76. * upcastElementToAttribute( { view: 'strong', model: 'bold' } );
  77. *
  78. * upcastElementToAttribute( { view: 'strong', model: 'bold' }, 'normal' );
  79. *
  80. * upcastElementToAttribute( {
  81. * view: {
  82. * name: 'span',
  83. * class: 'bold'
  84. * },
  85. * model: 'bold'
  86. * } );
  87. *
  88. * upcastElementToAttribute( {
  89. * view: {
  90. * name: 'span',
  91. * class: [ 'styled', 'styled-dark' ]
  92. * },
  93. * model: {
  94. * key: 'styled',
  95. * value: 'dark'
  96. * }
  97. * } );
  98. *
  99. * upcastElementToAttribute( {
  100. * view: {
  101. * name: 'span',
  102. * style: {
  103. * 'font-size': /[\s\S]+/
  104. * }
  105. * },
  106. * model: {
  107. * key: 'fontSize',
  108. * value: viewElement => {
  109. * const fontSize = viewElement.getStyle( 'font-size' );
  110. * const value = fontSize.substr( 0, fontSize.length - 2 );
  111. *
  112. * if ( value <= 10 ) {
  113. * return 'small';
  114. * } else if ( value > 12 ) {
  115. * return 'big';
  116. * }
  117. *
  118. * return null;
  119. * }
  120. * }
  121. * } );
  122. *
  123. * See {@link module:engine/conversion/conversion~Conversion#for} to learn how to add converter to conversion process.
  124. *
  125. * @param {Object} config Conversion configuration.
  126. * @param {module:engine/view/matcher~MatcherPattern} config.view Pattern matching all view elements which should be converted.
  127. * @param {String|Object} config.model Model attribute key or an object with `key` and `value` properties, describing
  128. * the model attribute. `value` property may be set as a function that takes a view element and returns the value.
  129. * If `String` is given, the model attribute value will be set to `true`.
  130. * @param {module:utils/priorities~PriorityString} [priority='low'] Converter priority.
  131. * @returns {Function} Conversion helper.
  132. */
  133. export function upcastElementToAttribute( config, priority = 'low' ) {
  134. config = cloneDeep( config );
  135. _normalizeModelAttributeConfig( config );
  136. const converter = _prepareToAttributeConverter( config, true );
  137. const elementName = _getViewElementNameFromConfig( config );
  138. const eventName = elementName ? 'element:' + elementName : 'element';
  139. return dispatcher => {
  140. dispatcher.on( eventName, converter, { priority } );
  141. };
  142. }
  143. /**
  144. * View attribute to model attribute conversion helper.
  145. *
  146. * This conversion results in setting an attribute on a model node. For example, view `<img src="foo.jpg"></img>` becomes
  147. * `<image source="foo.jpg"></image>` in the model.
  148. *
  149. * Keep in mind that the attribute will be set only if it is allowed by {@link module:engine/model/schema~Schema schema} configuration.
  150. *
  151. * upcastAttributeToAttribute( { view: 'src', model: 'source' } );
  152. *
  153. * upcastAttributeToAttribute( { view: { key: 'src' }, model: 'source' } );
  154. *
  155. * upcastAttributeToAttribute( { view: { key: 'src' }, model: 'source' }, 'normal' );
  156. *
  157. * upcastAttributeToAttribute( {
  158. * view: {
  159. * key: 'data-style',
  160. * value: /[\s\S]+/
  161. * },
  162. * model: 'styled'
  163. * } );
  164. *
  165. * upcastAttributeToAttribute( {
  166. * view: {
  167. * name: 'span',
  168. * key: 'class',
  169. * value: 'styled-dark'
  170. * },
  171. * model: {
  172. * key: 'styled',
  173. * value: 'dark'
  174. * }
  175. * } );
  176. *
  177. * upcastAttributeToAttribute( {
  178. * view: {
  179. * key: 'class',
  180. * value: /styled-[\S]+/
  181. * },
  182. * model: {
  183. * key: 'styled'
  184. * value: viewElement => {
  185. * const regexp = /styled-([\S]+)/;
  186. * const match = viewElement.getAttribute( 'class' ).match( regexp );
  187. *
  188. * return match[ 1 ];
  189. * }
  190. * }
  191. * } );
  192. *
  193. * See {@link module:engine/conversion/conversion~Conversion#for} to learn how to add converter to conversion process.
  194. *
  195. * @param {String|Object} config Conversion configuration. If given as a `String`, the conversion will be set for a
  196. * view attribute with given key. The model attribute key and value will be same as view attribute key and value.
  197. * @param {String|Object} config.view Specifies which view attribute will be converted. If a `String` is passed,
  198. * attributes with given key will be converted. If an `Object` is passed, it must have a required `key` property,
  199. * specifying view attribute key, and may have an optional `value` property, specifying view attribute value and optional `name`
  200. * property specifying a view element name from/on which the attribute should be converted. `value` can be given as a `String`,
  201. * a `RegExp` or a function callback, that takes view attribute value as the only parameter and returns `Boolean`.
  202. * @param {String|Object} config.model Model attribute key or an object with `key` and `value` properties, describing
  203. * the model attribute. `value` property may be set as a function that takes a view element and returns the value.
  204. * If `String` is given, the model attribute value will be same as view attribute value.
  205. * @param {module:utils/priorities~PriorityString} [priority='low'] Converter priority.
  206. * @returns {Function} Conversion helper.
  207. */
  208. export function upcastAttributeToAttribute( config, priority = 'low' ) {
  209. config = cloneDeep( config );
  210. let viewKey = null;
  211. if ( typeof config.view == 'string' || config.view.key ) {
  212. viewKey = _normalizeViewAttributeKeyValueConfig( config );
  213. }
  214. _normalizeModelAttributeConfig( config, viewKey );
  215. const converter = _prepareToAttributeConverter( config, false );
  216. return dispatcher => {
  217. dispatcher.on( 'element', converter, { priority } );
  218. };
  219. }
  220. /**
  221. * View element to model marker conversion helper.
  222. *
  223. * This conversion results in creating a model marker. For example, if the marker was stored in a view as an element:
  224. * `<p>Fo<span data-marker="comment" data-comment-id="7"></span>o</p><p>B<span data-marker="comment" data-comment-id="7"></span>ar</p>`,
  225. * after the conversion is done, the marker will be available in
  226. * {@link module:engine/model/model~Model#markers model document markers}.
  227. *
  228. * upcastElementToMarker( { view: 'marker-search', model: 'search' } );
  229. *
  230. * upcastElementToMarker( { view: 'marker-search', model: 'search' }, 'high' );
  231. *
  232. * upcastElementToMarker( {
  233. * view: 'marker-search',
  234. * model: viewElement => 'comment:' + viewElement.getAttribute( 'data-comment-id' )
  235. * } );
  236. *
  237. * upcastElementToMarker( {
  238. * view: {
  239. * name: 'span',
  240. * attribute: {
  241. * 'data-marker': 'search'
  242. * }
  243. * },
  244. * model: 'search'
  245. * } );
  246. *
  247. * See {@link module:engine/conversion/conversion~Conversion#for} to learn how to add converter to conversion process.
  248. *
  249. * @param {Object} config Conversion configuration.
  250. * @param {module:engine/view/matcher~MatcherPattern} config.view Pattern matching all view elements which should be converted.
  251. * @param {String|Function} config.model Name of the model marker, or a function that takes a view element and returns
  252. * a model marker name.
  253. * @param {module:utils/priorities~PriorityString} [priority='normal'] Converter priority.
  254. * @returns {Function} Conversion helper.
  255. */
  256. export function upcastElementToMarker( config, priority = 'normal' ) {
  257. config = cloneDeep( config );
  258. _normalizeToMarkerConfig( config );
  259. return upcastElementToElement( config, priority );
  260. }
  261. // Helper function for from-view-element conversion. Checks if `config.view` directly specifies converted view element's name
  262. // and if so, returns it.
  263. //
  264. // @param {Object} config Conversion config.
  265. // @returns {String|null} View element name or `null` if name is not directly set.
  266. function _getViewElementNameFromConfig( config ) {
  267. if ( typeof config.view == 'string' ) {
  268. return config.view;
  269. }
  270. if ( typeof config.view == 'object' && typeof config.view.name == 'string' ) {
  271. return config.view.name;
  272. }
  273. return null;
  274. }
  275. // Helper for to-model-element conversion. Takes a config object and returns a proper converter function.
  276. //
  277. // @param {Object} config Conversion configuration.
  278. // @returns {Function} View to model converter.
  279. function _prepareToElementConverter( config ) {
  280. const matcher = new Matcher( config.view );
  281. return ( evt, data, conversionApi ) => {
  282. // This will be usually just one pattern but we support matchers with many patterns too.
  283. const match = matcher.match( data.viewItem );
  284. // If there is no match, this callback should not do anything.
  285. if ( !match ) {
  286. return;
  287. }
  288. // Create model element basing on config.
  289. const modelElement = _getModelElement( config.model, data.viewItem, conversionApi.writer );
  290. // Do not convert if element building function returned falsy value.
  291. if ( !modelElement ) {
  292. return;
  293. }
  294. // When element was already consumed then skip it.
  295. if ( !conversionApi.consumable.test( data.viewItem, match.match ) ) {
  296. return;
  297. }
  298. // Find allowed parent for element that we are going to insert.
  299. // If current parent does not allow to insert element but one of the ancestors does
  300. // then split nodes to allowed parent.
  301. const splitResult = conversionApi.splitToAllowedParent( modelElement, data.cursorPosition );
  302. // When there is no split result it means that we can't insert element to model tree, so let's skip it.
  303. if ( !splitResult ) {
  304. return;
  305. }
  306. // Insert element on allowed position.
  307. conversionApi.writer.insert( modelElement, splitResult.position );
  308. // Convert children and insert to element.
  309. const childrenResult = conversionApi.convertChildren( data.viewItem, ModelPosition.createAt( modelElement ) );
  310. // Consume appropriate value from consumable values list.
  311. conversionApi.consumable.consume( data.viewItem, match.match );
  312. // Set conversion result range.
  313. data.modelRange = new ModelRange(
  314. // Range should start before inserted element
  315. ModelPosition.createBefore( modelElement ),
  316. // Should end after but we need to take into consideration that children could split our
  317. // element, so we need to move range after parent of the last converted child.
  318. // before: <allowed>[]</allowed>
  319. // after: <allowed>[<converted><child></child></converted><child></child><converted>]</converted></allowed>
  320. ModelPosition.createAfter( childrenResult.cursorPosition.parent )
  321. );
  322. // Now we need to check where the cursorPosition should be.
  323. // If we had to split parent to insert our element then we want to continue conversion inside split parent.
  324. //
  325. // before: <allowed><notAllowed>[]</notAllowed></allowed>
  326. // after: <allowed><notAllowed></notAllowed><converted></converted><notAllowed>[]</notAllowed></allowed>
  327. if ( splitResult.cursorParent ) {
  328. data.cursorPosition = ModelPosition.createAt( splitResult.cursorParent );
  329. // Otherwise just continue after inserted element.
  330. } else {
  331. data.cursorPosition = data.modelRange.end;
  332. }
  333. };
  334. }
  335. // Helper function for upcasting-to-element converter. Takes the model configuration, the converted view element
  336. // and a writer instance and returns a model element instance to be inserted in the model.
  337. //
  338. // @param {String|Function|module:engine/model/element~Element} model Model conversion configuration.
  339. // @param {module:engine/view/node~Node} input The converted view node.
  340. // @param {module:engine/model/writer~Writer} writer A writer instance to use to create the model element.
  341. function _getModelElement( model, input, writer ) {
  342. if ( model instanceof Function ) {
  343. return model( input, writer );
  344. } else if ( typeof model == 'string' ) {
  345. return writer.createElement( model );
  346. } else {
  347. return model;
  348. }
  349. }
  350. // Helper function view-attribute-to-model-attribute helper. Normalizes `config.view` which was set as `String` or
  351. // as an `Object` with `key`, `value` and `name` properties. Normalized `config.view` has is compatible with
  352. // {@link module:engine/view/matcher~MatcherPattern}.
  353. //
  354. // @param {Object} config Conversion config.
  355. // @returns {String} Key of the converted view attribute.
  356. function _normalizeViewAttributeKeyValueConfig( config ) {
  357. if ( typeof config.view == 'string' ) {
  358. config.view = { key: config.view };
  359. }
  360. const key = config.view.key;
  361. const value = typeof config.view.value == 'undefined' ? /[\s\S]*/ : config.view.value;
  362. const normalized = {
  363. attribute: {
  364. [ key ]: value
  365. }
  366. };
  367. if ( config.view.name ) {
  368. normalized.name = config.view.name;
  369. }
  370. config.view = normalized;
  371. return key;
  372. }
  373. // Helper function that normalizes `config.model` in from-model-attribute conversion. `config.model` can be set
  374. // as a `String`, an `Object` with only `key` property or an `Object` with `key` and `value` properties. Normalized
  375. // `config.model` is an `Object` with `key` and `value` properties.
  376. //
  377. // @param {Object} config Conversion config.
  378. // @param {String} viewAttributeKeyToCopy Key of the converted view attribute. If it is set, model attribute value
  379. // will be equal to view attribute value.
  380. function _normalizeModelAttributeConfig( config, viewAttributeKeyToCopy = null ) {
  381. const defaultModelValue = viewAttributeKeyToCopy === null ? true : viewElement => viewElement.getAttribute( viewAttributeKeyToCopy );
  382. const key = typeof config.model != 'object' ? config.model : config.model.key;
  383. const value = typeof config.model != 'object' ? defaultModelValue : config.model.value;
  384. config.model = { key, value };
  385. }
  386. // Helper for to-model-attribute conversion. Takes the model attribute name and conversion configuration and returns
  387. // a proper converter function.
  388. //
  389. // @param {String} modelAttributeKey The key of the model attribute to set on a model node.
  390. // @param {Object|Array.<Object>} config Conversion configuration. It is possible to provide multiple configurations in an array.
  391. // @param {Boolean} consumeName If set to `true` converter will not consume element's name.
  392. function _prepareToAttributeConverter( config, consumeName ) {
  393. const matcher = new Matcher( config.view );
  394. return ( evt, data, conversionApi ) => {
  395. const match = matcher.match( data.viewItem );
  396. // If there is no match, this callback should not do anything.
  397. if ( !match ) {
  398. return;
  399. }
  400. const modelKey = config.model.key;
  401. const modelValue = typeof config.model.value == 'function' ? config.model.value( data.viewItem ) : config.model.value;
  402. // Do not convert if attribute building function returned falsy value.
  403. if ( modelValue === null ) {
  404. return;
  405. }
  406. if ( !consumeName ) {
  407. // Do not test or consume `name` consumable.
  408. delete match.match.name;
  409. }
  410. // Try to consume appropriate values from consumable values list.
  411. if ( !conversionApi.consumable.test( data.viewItem, match.match ) ) {
  412. return;
  413. }
  414. // Since we are converting to attribute we need an range on which we will set the attribute.
  415. // If the range is not created yet, we will create it.
  416. if ( !data.modelRange ) {
  417. // Convert children and set conversion result as a current data.
  418. data = Object.assign( data, conversionApi.convertChildren( data.viewItem, data.cursorPosition ) );
  419. }
  420. // Set attribute on current `output`. `Schema` is checked inside this helper function.
  421. const attributeWasSet = _setAttributeOn( data.modelRange, { key: modelKey, value: modelValue }, conversionApi );
  422. if ( attributeWasSet ) {
  423. conversionApi.consumable.consume( data.viewItem, match.match );
  424. }
  425. };
  426. }
  427. // Helper function for to-model-attribute converter. Sets model attribute on given range. Checks {@link module:engine/model/schema~Schema}
  428. // to ensure proper model structure.
  429. //
  430. // @param {module:engine/model/range~Range} modelRange Model range on which attribute should be set.
  431. // @param {Object} modelAttribute Model attribute to set.
  432. // @param {Object} conversionApi Conversion API.
  433. // @returns {Boolean} `true` if attribute was set on at least one node from given `modelRange`.
  434. function _setAttributeOn( modelRange, modelAttribute, conversionApi ) {
  435. let result = false;
  436. // Set attribute on each item in range according to Schema.
  437. for ( const node of Array.from( modelRange.getItems() ) ) {
  438. if ( conversionApi.schema.checkAttribute( node, modelAttribute.key ) ) {
  439. conversionApi.writer.setAttribute( modelAttribute.key, modelAttribute.value, node );
  440. result = true;
  441. }
  442. }
  443. return result;
  444. }
  445. // Helper function for upcasting-to-marker conversion. Takes the config in a format requested by `upcastElementToMarker()`
  446. // function and converts it to a format that is supported by `upcastElementToElement()` function.
  447. //
  448. // @param {Object} config Conversion configuration.
  449. function _normalizeToMarkerConfig( config ) {
  450. const oldModel = config.model;
  451. config.model = ( viewElement, writer ) => {
  452. const markerName = typeof oldModel == 'string' ? oldModel : oldModel( viewElement );
  453. return writer.createElement( '$marker', { 'data-name': markerName } );
  454. };
  455. }
  456. /**
  457. * Function factory, creates a converter that converts {@link module:engine/view/documentfragment~DocumentFragment view document fragment}
  458. * or all children of {@link module:engine/view/element~Element} into
  459. * {@link module:engine/model/documentfragment~DocumentFragment model document fragment}.
  460. * This is the "entry-point" converter for upcast (view to model conversion). This converter starts the conversion of all children
  461. * of passed view document fragment. Those children {@link module:engine/view/node~Node view nodes} are then handled by other converters.
  462. *
  463. * This also a "default", last resort converter for all view elements that has not been converted by other converters.
  464. * When a view element is being converted to the model but it does not have converter specified, that view element
  465. * will be converted to {@link module:engine/model/documentfragment~DocumentFragment model document fragment} and returned.
  466. *
  467. * @returns {Function} Universal converter for view {@link module:engine/view/documentfragment~DocumentFragment fragments} and
  468. * {@link module:engine/view/element~Element elements} that returns
  469. * {@link module:engine/model/documentfragment~DocumentFragment model fragment} with children of converted view item.
  470. */
  471. export function convertToModelFragment() {
  472. return ( evt, data, conversionApi ) => {
  473. // Second argument in `consumable.consume` is discarded for ViewDocumentFragment but is needed for ViewElement.
  474. if ( !data.modelRange && conversionApi.consumable.consume( data.viewItem, { name: true } ) ) {
  475. const { modelRange, modelCursor } = conversionApi.convertChildren( data.viewItem, data.modelCursor );
  476. data.modelRange = modelRange;
  477. data.modelCursor = modelCursor;
  478. }
  479. };
  480. }
  481. /**
  482. * Function factory, creates a converter that converts {@link module:engine/view/text~Text} to {@link module:engine/model/text~Text}.
  483. *
  484. * @returns {Function} {@link module:engine/view/text~Text View text} converter.
  485. */
  486. export function convertText() {
  487. return ( evt, data, conversionApi ) => {
  488. if ( conversionApi.schema.checkChild( data.modelCursor, '$text' ) ) {
  489. if ( conversionApi.consumable.consume( data.viewItem ) ) {
  490. const text = conversionApi.writer.createText( data.viewItem.data );
  491. conversionApi.writer.insert( text, data.modelCursor );
  492. data.modelRange = ModelRange.createFromPositionAndShift( data.modelCursor, text.offsetSize );
  493. data.modelCursor = data.modelRange.end;
  494. }
  495. }
  496. };
  497. }