model.js 16 KB

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