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 View from '../view/view';
  21. import ViewConversionDispatcher from '../conversion/viewconversiondispatcher';
  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. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  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/model~Model} model
  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 {String} [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( model, options = {} ) {
  50. if ( !( model instanceof Model ) ) {
  51. throw new TypeError( 'Model needs to be an instance of module:engine/model/model~Model.' );
  52. }
  53. const withoutSelection = !!options.withoutSelection;
  54. const rootName = options.rootName || 'main';
  55. const root = model.document.getRoot( rootName );
  56. return withoutSelection ? getData._stringify( root ) : getData._stringify( root, model.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. *
  63. * **Note:** Remember to register elements in {@link module:engine/model/model~Model#schema model's schema} before inserting them.
  64. *
  65. * **Note:** To create {@link module:engine/model/text~Text text} node witch containing attributes use:
  66. *
  67. * <$text attribute="value">Text data</$text>
  68. *
  69. * @param {module:engine/model/model~Model} model
  70. * @param {String} data HTML-like string to write into Document.
  71. * @param {Object} options
  72. * @param {String} [options.rootName='main'] Root name where parsed data will be stored. If not provided, default `main`
  73. * name will be used.
  74. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to the selection.
  75. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward.
  76. * @param {String} [options.batchType='transparent'] Batch type used for inserting elements.
  77. * See {@link module:engine/model/batch~Batch#type}.
  78. */
  79. export function setData( model, data, options = {} ) {
  80. if ( !( model instanceof Model ) ) {
  81. throw new TypeError( 'Model needs to be an instance of module:engine/model/model~Model.' );
  82. }
  83. let modelDocumentFragment, selection;
  84. const modelRoot = model.document.getRoot( options.rootName || 'main' );
  85. const batch = new Batch( options.batchType || 'transparent' );
  86. // Parse data string to model.
  87. const parsedResult = setData._parse( data, model.schema, {
  88. lastRangeBackward: options.lastRangeBackward,
  89. selectionAttributes: options.selectionAttributes,
  90. context: [ modelRoot.name ]
  91. } );
  92. // Retrieve DocumentFragment and Selection from parsed model.
  93. if ( parsedResult.model ) {
  94. modelDocumentFragment = parsedResult.model;
  95. selection = parsedResult.selection;
  96. } else {
  97. modelDocumentFragment = parsedResult;
  98. }
  99. model.enqueueChange( batch, writer => {
  100. // Replace existing model in document by new one.
  101. writer.remove( ModelRange.createIn( modelRoot ) );
  102. writer.insert( modelDocumentFragment, modelRoot );
  103. // Clean up previous document selection.
  104. writer.setSelection( null );
  105. writer.removeSelectionAttribute( model.document.selection.getAttributeKeys() );
  106. // Update document selection if specified.
  107. if ( selection ) {
  108. const ranges = [];
  109. for ( const range of selection.getRanges() ) {
  110. const start = new ModelPosition( modelRoot, range.start.path );
  111. const end = new ModelPosition( modelRoot, range.end.path );
  112. ranges.push( new ModelRange( start, end ) );
  113. }
  114. writer.setSelection( ranges, selection.isBackward );
  115. if ( options.selectionAttributes ) {
  116. writer.setSelectionAttribute( selection.getAttributes() );
  117. }
  118. }
  119. } );
  120. }
  121. // Set parse as setData private method - needed for testing/spying.
  122. setData._parse = parse;
  123. /**
  124. * Converts model nodes to HTML-like string representation.
  125. *
  126. * **Note:** {@link module:engine/model/text~Text text} node contains attributes will be represented as:
  127. *
  128. * <$text attribute="value">Text data</$text>
  129. *
  130. * @param {module:engine/model/rootelement~RootElement|module:engine/model/element~Element|module:engine/model/text~Text|
  131. * module:engine/model/documentfragment~DocumentFragment} node Node to stringify.
  132. * @param {module:engine/model/selection~Selection|module:engine/model/position~Position|
  133. * module:engine/model/range~Range} [selectionOrPositionOrRange=null]
  134. * Selection instance which ranges will be included in returned string data. If Range instance is provided - it will be
  135. * converted to selection containing this range. If Position instance is provided - it will be converted to selection
  136. * containing one range collapsed at this position.
  137. * @returns {String} HTML-like string representing the model.
  138. */
  139. export function stringify( node, selectionOrPositionOrRange = null ) {
  140. const model = new Model();
  141. const mapper = new Mapper();
  142. let selection, range;
  143. // Create a range witch wraps passed node.
  144. if ( node instanceof RootElement || node instanceof ModelDocumentFragment ) {
  145. range = ModelRange.createIn( node );
  146. } else {
  147. // Node is detached - create new document fragment.
  148. if ( !node.parent ) {
  149. const fragment = new ModelDocumentFragment( node );
  150. range = ModelRange.createIn( fragment );
  151. } else {
  152. range = new ModelRange(
  153. ModelPosition.createBefore( node ),
  154. ModelPosition.createAfter( node )
  155. );
  156. }
  157. }
  158. // Get selection from passed selection or position or range if at least one is specified.
  159. if ( selectionOrPositionOrRange instanceof ModelSelection ) {
  160. selection = selectionOrPositionOrRange;
  161. } else if ( selectionOrPositionOrRange instanceof DocumentSelection ) {
  162. selection = selectionOrPositionOrRange;
  163. } else if ( selectionOrPositionOrRange instanceof ModelRange ) {
  164. selection = new ModelSelection( selectionOrPositionOrRange );
  165. } else if ( selectionOrPositionOrRange instanceof ModelPosition ) {
  166. selection = new ModelSelection( selectionOrPositionOrRange );
  167. }
  168. // Setup model to view converter.
  169. const viewDocumentFragment = new ViewDocumentFragment();
  170. const view = new View();
  171. const viewSelection = view.document.selection;
  172. const modelToView = new ModelConversionDispatcher( model, { mapper } );
  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 instanceof DocumentSelection || 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.
  189. const writer = view._writer;
  190. modelToView.convertInsert( range, writer );
  191. // Convert model selection to view selection.
  192. if ( selection ) {
  193. modelToView.convertSelection( selection, writer );
  194. }
  195. // Parse view to data string.
  196. const data = viewStringify( viewDocumentFragment, viewSelection, { sameSelectionCharacters: true } );
  197. // Replace valid XML `model-text-with-attributes` element name to `$text`.
  198. return data.replace( new RegExp( 'model-text-with-attributes', 'g' ), '$text' );
  199. }
  200. /**
  201. * Parses HTML-like string and returns model {@link module:engine/model/rootelement~RootElement rootElement}.
  202. *
  203. * **Note:** To create {@link module:engine/model/text~Text text} node witch containing attributes use:
  204. *
  205. * <$text attribute="value">Text data</$text>
  206. *
  207. * @param {String} data HTML-like string to be parsed.
  208. * @param {module:engine/model/schema~Schema} schema Schema instance uses by converters for element validation.
  209. * @param {module:engine/model/batch~Batch} batch Batch used for conversion.
  210. * @param {Object} [options={}] Additional configuration.
  211. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to the selection.
  212. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward.
  213. * @param {module:engine/model/schema~SchemaContextDefinition} [options.context=[ '$root' ]] The conversion context.
  214. * If not provided default `[ '$root' ]` will be used.
  215. * @returns {module:engine/model/element~Element|module:engine/model/text~Text|
  216. * module:engine/model/documentfragment~DocumentFragment|Object} Returns parsed model node or
  217. * object with two fields `model` and `selection` when selection ranges were included in data to parse.
  218. */
  219. export function parse( data, schema, options = {} ) {
  220. const mapper = new Mapper();
  221. // Replace not accepted by XML `$text` tag name by valid one `model-text-with-attributes`.
  222. data = data.replace( new RegExp( '\\$text', 'g' ), 'model-text-with-attributes' );
  223. // Parse data to view using view utils.
  224. const parsedResult = viewParse( data, {
  225. sameSelectionCharacters: true,
  226. lastRangeBackward: !!options.lastRangeBackward
  227. } );
  228. // Retrieve DocumentFragment and Selection from parsed view.
  229. let viewDocumentFragment, viewSelection, selection;
  230. if ( parsedResult.view && parsedResult.selection ) {
  231. viewDocumentFragment = parsedResult.view;
  232. viewSelection = parsedResult.selection;
  233. } else {
  234. viewDocumentFragment = parsedResult;
  235. }
  236. // Setup view to model converter.
  237. const viewToModel = new ViewConversionDispatcher( new Model(), { schema, mapper } );
  238. viewToModel.on( 'documentFragment', convertToModelFragment() );
  239. viewToModel.on( 'element:model-text-with-attributes', convertToModelText( true ) );
  240. viewToModel.on( 'element', convertToModelElement() );
  241. viewToModel.on( 'text', convertToModelText() );
  242. // Convert view to model.
  243. let model = viewToModel.convert( viewDocumentFragment.root, { context: options.context || [ '$root' ] } );
  244. // If root DocumentFragment contains only one element - return that element.
  245. if ( model.childCount == 1 ) {
  246. model = model.getChild( 0 );
  247. }
  248. // Convert view selection to model selection.
  249. if ( viewSelection ) {
  250. const ranges = [];
  251. // Convert ranges.
  252. for ( const viewRange of viewSelection.getRanges() ) {
  253. ranges.push( mapper.toModelRange( viewRange ) );
  254. }
  255. // Create new selection.
  256. selection = new ModelSelection( ranges, viewSelection.isBackward );
  257. // Set attributes to selection if specified.
  258. for ( const [ key, value ] of toMap( options.selectionAttributes || [] ) ) {
  259. selection.setAttribute( key, value );
  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. }