upcast-converters.js 22 KB

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