8
0

model.js 15 KB

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