8
0

model.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. * @param {engine.model.SchemaPath} [options.context=[ '$root' ]] The conversion context.
  229. * If not provided default `[ '$root' ]` will be used.
  230. * @returns {engine.model.Element|engine.model.Text|engine.model.DocumentFragment|Object} Returns parsed model node or
  231. * object with two fields `model` and `selection` when selection ranges were included in data to parse.
  232. */
  233. export function parse( data, schema, options = {} ) {
  234. const mapper = new Mapper();
  235. // Replace not accepted by XML `$text` tag name by valid one `model-text-with-attributes`.
  236. data = data.replace( new RegExp( '\\$text', 'g' ), 'model-text-with-attributes' );
  237. // Parse data to view using view utils.
  238. const parsedResult = viewParse( data, {
  239. sameSelectionCharacters: true,
  240. lastRangeBackward: !!options.lastRangeBackward
  241. } );
  242. // Retrieve DocumentFragment and Selection from parsed view.
  243. let viewDocumentFragment, viewSelection;
  244. if ( parsedResult.view && parsedResult.selection ) {
  245. viewDocumentFragment = parsedResult.view;
  246. viewSelection = parsedResult.selection;
  247. } else {
  248. viewDocumentFragment = parsedResult;
  249. }
  250. // Setup view to model converter.
  251. const viewToModel = new ViewConversionDispatcher( { schema, mapper } );
  252. viewToModel.on( 'documentFragment', convertToModelFragment() );
  253. viewToModel.on( `element:model-text-with-attributes`, convertToModelText( true ) );
  254. viewToModel.on( 'element', convertToModelElement() );
  255. viewToModel.on( 'text', convertToModelText() );
  256. // Convert view to model.
  257. let model = viewToModel.convert( viewDocumentFragment.root, { context: options.context || [ '$root' ] } );
  258. // If root DocumentFragment contains only one element - return that element.
  259. if ( model instanceof ModelDocumentFragment && model.childCount == 1 ) {
  260. model = model.getChild( 0 );
  261. }
  262. // Convert view selection to model selection.
  263. let selection;
  264. if ( viewSelection ) {
  265. const ranges = [];
  266. // Convert ranges.
  267. for ( let viewRange of viewSelection.getRanges() ) {
  268. ranges.push( ( mapper.toModelRange( viewRange ) ) );
  269. }
  270. // Create new selection.
  271. selection = new ModelSelection();
  272. selection.setRanges( ranges, viewSelection.isBackward );
  273. // Set attributes to selection if specified.
  274. if ( options.selectionAttributes ) {
  275. selection.setAttributesTo( options.selectionAttributes );
  276. }
  277. }
  278. // Return model end selection when selection was specified.
  279. if ( selection ) {
  280. return { model, selection };
  281. }
  282. // Otherwise return model only.
  283. return model;
  284. }
  285. // -- Converters view -> model -----------------------------------------------------
  286. function convertToModelFragment() {
  287. return ( evt, data, consumable, conversionApi ) => {
  288. const convertedChildren = conversionApi.convertChildren( data.input, consumable, data );
  289. data.output = new ModelDocumentFragment( modelWriter.normalizeNodes( convertedChildren ) );
  290. conversionApi.mapper.bindElements( data.output, data.input );
  291. evt.stop();
  292. };
  293. }
  294. function convertToModelElement() {
  295. return ( evt, data, consumable, conversionApi ) => {
  296. const schemaQuery = {
  297. name: data.input.name,
  298. attributes: Array.from( data.input.getAttributeKeys() ),
  299. inside: data.context
  300. };
  301. if ( !conversionApi.schema.check( schemaQuery ) ) {
  302. throw new Error( `Element '${ schemaQuery.name }' not allowed in context.` );
  303. }
  304. // View attribute value is a string so we want to typecast it to the original type.
  305. // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
  306. const attributes = convertAttributes( data.input.getAttributes(), parseAttributeValue );
  307. data.output = new ModelElement( data.input.name, attributes );
  308. conversionApi.mapper.bindElements( data.output, data.input );
  309. data.context.push( data.output );
  310. data.output.appendChildren( conversionApi.convertChildren( data.input, consumable, data ) );
  311. data.context.pop();
  312. evt.stop();
  313. };
  314. }
  315. function convertToModelText( withAttributes = false ) {
  316. return ( evt, data, consumable, conversionApi ) => {
  317. const schemaQuery = {
  318. name: '$text',
  319. inside: data.context
  320. };
  321. if ( !conversionApi.schema.check( schemaQuery ) ) {
  322. throw new Error( `Element '${ schemaQuery.name }' not allowed in context.` );
  323. }
  324. let node;
  325. if ( withAttributes ) {
  326. // View attribute value is a string so we want to typecast it to the original type.
  327. // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
  328. const attributes = convertAttributes( data.input.getAttributes(), parseAttributeValue );
  329. node = new ModelText( data.input.getChild( 0 ).data, attributes );
  330. } else {
  331. node = new ModelText( data.input.data );
  332. }
  333. data.output = node;
  334. evt.stop();
  335. };
  336. }
  337. // Tries to get original type of attribute value using JSON parsing:
  338. //
  339. // `'true'` => `true`
  340. // `'1'` => `1`
  341. // `'{"x":1,"y":2}'` => `{ x: 1, y: 2 }`
  342. //
  343. // Parse error means that value should be a string:
  344. //
  345. // `'foobar'` => `'foobar'`
  346. function parseAttributeValue( attribute ) {
  347. try {
  348. return JSON.parse( attribute );
  349. } catch ( e ) {
  350. return attribute;
  351. }
  352. }
  353. // When value is an Object stringify it.
  354. function stringifyAttributeValue( data ) {
  355. if ( isPlainObject( data ) ) {
  356. return JSON.stringify( data );
  357. }
  358. return data;
  359. }
  360. // Loop trough attributes map and converts each value by passed converter.
  361. function *convertAttributes( attributes, converter ) {
  362. for ( let [ key, value ] of attributes ) {
  363. yield [ key, converter( value ) ];
  364. }
  365. }