model.js 16 KB

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