model.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/dev-utils/model
  7. */
  8. /**
  9. * Collection of methods for manipulating {@link module:engine/model/model model} for testing purposes.
  10. */
  11. import RootElement from '../model/rootelement';
  12. import ModelDocument from '../model/document';
  13. import ModelRange from '../model/range';
  14. import ModelPosition from '../model/position';
  15. import ModelConversionDispatcher from '../conversion/modelconversiondispatcher';
  16. import ModelSelection from '../model/selection';
  17. import ModelDocumentFragment from '../model/documentfragment';
  18. import ModelElement from '../model/element';
  19. import ModelText from '../model/text';
  20. import modelWriter from '../model/writer';
  21. import ViewConversionDispatcher from '../conversion/viewconversiondispatcher';
  22. import ViewSelection from '../view/selection';
  23. import ViewDocumentFragment from '../view/documentfragment';
  24. import ViewContainerElement from '../view/containerelement';
  25. import ViewAttributeElement from '../view/attributeelement';
  26. import Mapper from '../conversion/mapper';
  27. import { parse as viewParse, stringify as viewStringify } from '../../src/dev-utils/view';
  28. import {
  29. convertRangeSelection,
  30. convertCollapsedSelection,
  31. convertSelectionAttribute
  32. } from '../conversion/model-selection-to-view-converters';
  33. import { insertText, insertElement, wrapItem } from '../conversion/model-to-view-converters';
  34. import isPlainObject from '@ckeditor/ckeditor5-utils/src/lib/lodash/isPlainObject';
  35. /**
  36. * Writes the contents of the {@link module:engine/model/document~Document Document} to an HTML-like string.
  37. *
  38. * **Note:** {@link module:engine/model/text~Text text} node contains attributes will be represented as:
  39. *
  40. * <$text attribute="value">Text data</$text>
  41. *
  42. * @param {module:engine/model/document~Document} document
  43. * @param {Object} [options]
  44. * @param {Boolean} [options.withoutSelection=false] Whether to write the selection. When set to `true` selection will
  45. * be not included in returned string.
  46. * @param {Boolean} [options.rootName='main'] Name of the root from which data should be stringified. If not provided
  47. * default `main` name will be used.
  48. * @returns {String} The stringified data.
  49. */
  50. export function getData( document, options = {} ) {
  51. if ( !( document instanceof ModelDocument ) ) {
  52. throw new TypeError( 'Document needs to be an instance of module:engine/model/document~Document.' );
  53. }
  54. const withoutSelection = !!options.withoutSelection;
  55. const rootName = options.rootName || 'main';
  56. const root = document.getRoot( rootName );
  57. return withoutSelection ? getData._stringify( root ) : getData._stringify( root, document.selection );
  58. }
  59. // Set stringify as getData private method - needed for testing/spying.
  60. getData._stringify = stringify;
  61. /**
  62. * Sets the contents of the {@link module:engine/model/document~Document Document} provided as HTML-like string.
  63. * It uses {@link module:engine/model/document~Document#enqueueChanges enqueueChanges} method.
  64. *
  65. * **Note:** Remember to register elements in {@link module:engine/model/document~Document#schema document's schema} before inserting them.
  66. *
  67. * **Note:** To create {@link module:engine/model/text~Text text} node witch containing attributes use:
  68. *
  69. * <$text attribute="value">Text data</$text>
  70. *
  71. * @param {module:engine/model/document~Document} document
  72. * @param {String} data HTML-like string to write into Document.
  73. * @param {Object} options
  74. * @param {String} [options.rootName='main'] Root name where parsed data will be stored. If not provided, default `main`
  75. * name will be used.
  76. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to the selection.
  77. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward.
  78. * @param {String} [options.batchType='transparent'] Batch type used for inserting elements.
  79. * See {@link module:engine/model/batch~Batch#type}.
  80. */
  81. export function setData( document, data, options = {} ) {
  82. if ( !( document instanceof ModelDocument ) ) {
  83. throw new TypeError( 'Document needs to be an instance of module:engine/model/document~Document.' );
  84. }
  85. let modelDocumentFragment, selection;
  86. const modelRoot = document.getRoot( options.rootName || 'main' );
  87. // Parse data string to model.
  88. const parsedResult = setData._parse( data, document.schema, {
  89. lastRangeBackward: options.lastRangeBackward,
  90. selectionAttributes: options.selectionAttributes,
  91. context: [ modelRoot.name ]
  92. } );
  93. // Retrieve DocumentFragment and Selection from parsed model.
  94. if ( parsedResult.model ) {
  95. modelDocumentFragment = parsedResult.model;
  96. selection = parsedResult.selection;
  97. } else {
  98. modelDocumentFragment = parsedResult;
  99. }
  100. document.enqueueChanges( () => {
  101. // Replace existing model in document by new one.
  102. document.batch( options.batchType || 'transparent' )
  103. .remove( ModelRange.createIn( modelRoot ) )
  104. .insert( ModelPosition.createAt( modelRoot, 0 ), modelDocumentFragment );
  105. // Clean up previous document selection.
  106. document.selection.clearAttributes();
  107. document.selection.removeAllRanges();
  108. // Update document selection if specified.
  109. if ( selection ) {
  110. const ranges = [];
  111. for ( let range of selection.getRanges() ) {
  112. let start, end;
  113. // Each range returned from `parse()` method has its root placed in DocumentFragment.
  114. // Here we convert each range to have its root re-calculated properly and be placed inside
  115. // model document root.
  116. if ( range.start.parent.is( 'documentFragment' ) ) {
  117. start = ModelPosition.createFromParentAndOffset( modelRoot, range.start.offset );
  118. } else {
  119. start = ModelPosition.createFromParentAndOffset( range.start.parent, range.start.offset );
  120. }
  121. if ( range.end.parent.is( 'documentFragment' ) ) {
  122. end = ModelPosition.createFromParentAndOffset( modelRoot, range.end.offset );
  123. } else {
  124. end = ModelPosition.createFromParentAndOffset( range.end.parent, range.end.offset );
  125. }
  126. ranges.push( new ModelRange( start, end ) );
  127. }
  128. document.selection.setRanges( ranges, selection.isBackward );
  129. if ( options.selectionAttributes ) {
  130. document.selection.setAttributesTo( selection.getAttributes() );
  131. }
  132. }
  133. } );
  134. }
  135. // Set parse as setData private method - needed for testing/spying.
  136. setData._parse = parse;
  137. /**
  138. * Converts model nodes to HTML-like string representation.
  139. *
  140. * **Note:** {@link module:engine/model/text~Text text} node contains attributes will be represented as:
  141. *
  142. * <$text attribute="value">Text data</$text>
  143. *
  144. * @param {module:engine/model/rootelement~RootElement|module:engine/model/element~Element|module:engine/model/text~Text|
  145. * module:engine/model/documentfragment~DocumentFragment} node Node to stringify.
  146. * @param {module:engine/model/selection~Selection|module:engine/model/position~Position|
  147. * module:engine/model/range~Range} [selectionOrPositionOrRange=null]
  148. * Selection instance which ranges will be included in returned string data. If Range instance is provided - it will be
  149. * converted to selection containing this range. If Position instance is provided - it will be converted to selection
  150. * containing one range collapsed at this position.
  151. * @returns {String} HTML-like string representing the model.
  152. */
  153. export function stringify( node, selectionOrPositionOrRange = null ) {
  154. const modelDoc = new ModelDocument();
  155. const mapper = new Mapper();
  156. let selection, range;
  157. // Create a range witch wraps passed node.
  158. if ( node instanceof RootElement || node instanceof ModelDocumentFragment ) {
  159. range = ModelRange.createIn( node );
  160. } else {
  161. // Node is detached - create new document fragment.
  162. if ( !node.parent ) {
  163. const fragment = new ModelDocumentFragment( node );
  164. range = ModelRange.createIn( fragment );
  165. } else {
  166. range = new ModelRange(
  167. ModelPosition.createBefore( node ),
  168. ModelPosition.createAfter( node )
  169. );
  170. }
  171. }
  172. // Get selection from passed selection or position or range if at least one is specified.
  173. if ( selectionOrPositionOrRange instanceof ModelSelection ) {
  174. selection = selectionOrPositionOrRange;
  175. } else if ( selectionOrPositionOrRange instanceof ModelRange ) {
  176. selection = new ModelSelection();
  177. selection.addRange( selectionOrPositionOrRange );
  178. } else if ( selectionOrPositionOrRange instanceof ModelPosition ) {
  179. selection = new ModelSelection();
  180. selection.addRange( new ModelRange( selectionOrPositionOrRange, selectionOrPositionOrRange ) );
  181. }
  182. // Setup model to view converter.
  183. const viewDocumentFragment = new ViewDocumentFragment();
  184. const viewSelection = new ViewSelection();
  185. const modelToView = new ModelConversionDispatcher( modelDoc, { mapper, viewSelection } );
  186. // Bind root elements.
  187. mapper.bindElements( node.root, viewDocumentFragment );
  188. modelToView.on( 'insert:$text', insertText() );
  189. modelToView.on( 'addAttribute', wrapItem( ( value, data ) => {
  190. if ( data.item.is( 'textProxy' ) ) {
  191. return new ViewAttributeElement( 'model-text-with-attributes', { [ data.attributeKey ]: stringifyAttributeValue( value ) } );
  192. }
  193. } ) );
  194. modelToView.on( 'insert', insertElement( ( data ) => {
  195. // Stringify object types values for properly display as an output string.
  196. const attributes = convertAttributes( data.item.getAttributes(), stringifyAttributeValue );
  197. return new ViewContainerElement( data.item.name, attributes );
  198. } ) );
  199. modelToView.on( 'selection', convertRangeSelection() );
  200. modelToView.on( 'selection', convertCollapsedSelection() );
  201. modelToView.on( 'selectionAttribute', convertSelectionAttribute( ( value, data ) => {
  202. return new ViewAttributeElement( 'model-text-with-attributes', { [ data.key ]: value } );
  203. } ) );
  204. // Convert model to view.
  205. modelToView.convertInsertion( range );
  206. // Convert model selection to view selection.
  207. if ( selection ) {
  208. modelToView.convertSelection( selection, [] );
  209. }
  210. // Parse view to data string.
  211. let data = viewStringify( viewDocumentFragment, viewSelection, { sameSelectionCharacters: true } );
  212. // Replace valid XML `model-text-with-attributes` element name to `$text`.
  213. return data.replace( new RegExp( 'model-text-with-attributes', 'g' ), '$text' );
  214. }
  215. /**
  216. * Parses HTML-like string and returns model {@link module:engine/model/rootelement~RootElement rootElement}.
  217. *
  218. * **Note:** To create {@link module:engine/model/text~Text text} node witch containing attributes use:
  219. *
  220. * <$text attribute="value">Text data</$text>
  221. *
  222. * @param {String} data HTML-like string to be parsed.
  223. * @param {module:engine/model/schema~Schema} schema Schema instance uses by converters for element validation.
  224. * @param {Object} options Additional configuration.
  225. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to the selection.
  226. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward.
  227. * @param {module:engine/model/schema~SchemaPath} [options.context=[ '$root' ]] The conversion context.
  228. * If not provided default `[ '$root' ]` will be used.
  229. * @returns {module:engine/model/element~Element|module:engine/model/text~Text|
  230. * module:engine/model/documentfragment~DocumentFragment|Object} Returns parsed model node or
  231. * object with two fields `model` and `selection` when selection ranges were included in data to parse.
  232. */
  233. export function parse( data, schema, options = {} ) {
  234. const mapper = new Mapper();
  235. // Replace not accepted by XML `$text` tag name by valid one `model-text-with-attributes`.
  236. data = data.replace( new RegExp( '\\$text', 'g' ), 'model-text-with-attributes' );
  237. // Parse data to view using view utils.
  238. const parsedResult = viewParse( data, {
  239. sameSelectionCharacters: true,
  240. lastRangeBackward: !!options.lastRangeBackward
  241. } );
  242. // Retrieve DocumentFragment and Selection from parsed view.
  243. let viewDocumentFragment, viewSelection;
  244. if ( parsedResult.view && parsedResult.selection ) {
  245. viewDocumentFragment = parsedResult.view;
  246. viewSelection = parsedResult.selection;
  247. } else {
  248. viewDocumentFragment = parsedResult;
  249. }
  250. // Setup view to model converter.
  251. const viewToModel = new ViewConversionDispatcher( { schema, mapper } );
  252. viewToModel.on( 'documentFragment', convertToModelFragment() );
  253. viewToModel.on( `element:model-text-with-attributes`, convertToModelText( true ) );
  254. viewToModel.on( 'element', convertToModelElement() );
  255. viewToModel.on( 'text', convertToModelText() );
  256. // Convert view to model.
  257. let model = viewToModel.convert( viewDocumentFragment.root, { context: options.context || [ '$root' ] } );
  258. // If root DocumentFragment contains only one element - return that element.
  259. if ( model.is( 'documentFragment' ) && model.childCount == 1 ) {
  260. model = model.getChild( 0 );
  261. }
  262. // Convert view selection to model selection.
  263. let selection;
  264. if ( viewSelection ) {
  265. const ranges = [];
  266. // Convert ranges.
  267. for ( let viewRange of viewSelection.getRanges() ) {
  268. ranges.push( ( mapper.toModelRange( viewRange ) ) );
  269. }
  270. // Create new selection.
  271. selection = new ModelSelection();
  272. selection.setRanges( ranges, viewSelection.isBackward );
  273. // Set attributes to selection if specified.
  274. if ( options.selectionAttributes ) {
  275. selection.setAttributesTo( options.selectionAttributes );
  276. }
  277. }
  278. // Return model end selection when selection was specified.
  279. if ( selection ) {
  280. return { model, selection };
  281. }
  282. // Otherwise return model only.
  283. return model;
  284. }
  285. // -- Converters view -> model -----------------------------------------------------
  286. function convertToModelFragment() {
  287. return ( evt, data, consumable, conversionApi ) => {
  288. const convertedChildren = conversionApi.convertChildren( data.input, consumable, data );
  289. data.output = new ModelDocumentFragment( modelWriter.normalizeNodes( convertedChildren ) );
  290. conversionApi.mapper.bindElements( data.output, data.input );
  291. evt.stop();
  292. };
  293. }
  294. function convertToModelElement() {
  295. return ( evt, data, consumable, conversionApi ) => {
  296. const schemaQuery = {
  297. name: data.input.name,
  298. attributes: Array.from( data.input.getAttributeKeys() ),
  299. inside: data.context
  300. };
  301. if ( !conversionApi.schema.check( schemaQuery ) ) {
  302. throw new Error( `Element '${ schemaQuery.name }' not allowed in context ${ JSON.stringify( data.context ) }.` );
  303. }
  304. // View attribute value is a string so we want to typecast it to the original type.
  305. // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
  306. const attributes = convertAttributes( data.input.getAttributes(), parseAttributeValue );
  307. data.output = new ModelElement( data.input.name, attributes );
  308. conversionApi.mapper.bindElements( data.output, data.input );
  309. data.context.push( data.output );
  310. data.output.appendChildren( conversionApi.convertChildren( data.input, consumable, data ) );
  311. data.context.pop();
  312. evt.stop();
  313. };
  314. }
  315. function convertToModelText( withAttributes = false ) {
  316. return ( evt, data, consumable, conversionApi ) => {
  317. const schemaQuery = {
  318. name: '$text',
  319. inside: data.context
  320. };
  321. if ( !conversionApi.schema.check( schemaQuery ) ) {
  322. throw new Error( `Element '${ schemaQuery.name }' not allowed in context ${ JSON.stringify( data.context ) }.` );
  323. }
  324. let node;
  325. if ( withAttributes ) {
  326. // View attribute value is a string so we want to typecast it to the original type.
  327. // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
  328. const attributes = convertAttributes( data.input.getAttributes(), parseAttributeValue );
  329. node = new ModelText( data.input.getChild( 0 ).data, attributes );
  330. } else {
  331. node = new ModelText( data.input.data );
  332. }
  333. data.output = node;
  334. evt.stop();
  335. };
  336. }
  337. // Tries to get original type of attribute value using JSON parsing:
  338. //
  339. // `'true'` => `true`
  340. // `'1'` => `1`
  341. // `'{"x":1,"y":2}'` => `{ x: 1, y: 2 }`
  342. //
  343. // Parse error means that value should be a string:
  344. //
  345. // `'foobar'` => `'foobar'`
  346. function parseAttributeValue( attribute ) {
  347. try {
  348. return JSON.parse( attribute );
  349. } catch ( e ) {
  350. return attribute;
  351. }
  352. }
  353. // When value is an Object stringify it.
  354. function stringifyAttributeValue( data ) {
  355. if ( isPlainObject( data ) ) {
  356. return JSON.stringify( data );
  357. }
  358. return data;
  359. }
  360. // Loop trough attributes map and converts each value by passed converter.
  361. function *convertAttributes( attributes, converter ) {
  362. for ( let [ key, value ] of attributes ) {
  363. yield [ key, converter( value ) ];
  364. }
  365. }