model.js 16 KB

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