model.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 the {@link module:engine/model/model model} for testing purposes.
  10. */
  11. import RootElement from '../model/rootelement';
  12. import Model from '../model/model';
  13. import ModelRange from '../model/range';
  14. import ModelPosition from '../model/position';
  15. import ModelSelection from '../model/selection';
  16. import ModelDocumentFragment from '../model/documentfragment';
  17. import DocumentSelection from '../model/documentselection';
  18. import View from '../view/view';
  19. import ViewContainerElement from '../view/containerelement';
  20. import ViewRootEditableElement from '../view/rooteditableelement';
  21. import { parse as viewParse, stringify as viewStringify } from '../../src/dev-utils/view';
  22. import DowncastDispatcher from '../conversion/downcastdispatcher';
  23. import UpcastDispatcher from '../conversion/upcastdispatcher';
  24. import Mapper from '../conversion/mapper';
  25. import {
  26. convertRangeSelection,
  27. convertCollapsedSelection,
  28. } from '../conversion/downcast-selection-converters';
  29. import { insertText, insertElement, wrap, insertUIElement } from '../conversion/downcast-converters';
  30. import { isPlainObject } from 'lodash-es';
  31. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  32. /**
  33. * Writes the content of a model {@link module:engine/model/document~Document document} to an HTML-like string.
  34. *
  35. * **Note:** A {@link module:engine/model/text~Text text} node that contains attributes will be represented as:
  36. *
  37. * <$text attribute="value">Text data</$text>
  38. *
  39. * @param {module:engine/model/model~Model} model
  40. * @param {Object} [options]
  41. * @param {Boolean} [options.withoutSelection=false] Whether to write the selection. When set to `true`, the selection will
  42. * not be included in the returned string.
  43. * @param {String} [options.rootName='main'] The name of the root from which the data should be stringified. If not provided,
  44. * the default `main` name will be used.
  45. * @param {Boolean} [options.convertMarkers=false] Whether to include markers in the returned string.
  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 rootName = options.rootName || 'main';
  53. const root = model.document.getRoot( rootName );
  54. return getData._stringify(
  55. root,
  56. options.withoutSelection ? null : model.document.selection,
  57. options.convertMarkers ? model.markers : null
  58. );
  59. }
  60. // Set stringify as getData private method - needed for testing/spying.
  61. getData._stringify = stringify;
  62. /**
  63. * Sets the content of a model {@link module:engine/model/document~Document document} provided as an HTML-like string.
  64. *
  65. * **Note:** Remember to register elements in the {@link module:engine/model/model~Model#schema model's schema} before
  66. * trying to use them.
  67. *
  68. * **Note:** To create a {@link module:engine/model/text~Text text} node that contains attributes use:
  69. *
  70. * <$text attribute="value">Text data</$text>
  71. *
  72. * @param {module:engine/model/model~Model} model
  73. * @param {String} data HTML-like string to write into the document.
  74. * @param {Object} options
  75. * @param {String} [options.rootName='main'] Root name where parsed data will be stored. If not provided, the default `main`
  76. * name will be used.
  77. * @param {Array<Object>} [options.selectionAttributes] A list of attributes which will be passed to the selection.
  78. * @param {Boolean} [options.lastRangeBackward=false] If set to `true`, the 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( model, data, options = {} ) {
  83. if ( !( model instanceof Model ) ) {
  84. throw new TypeError( 'Model needs to be an instance of module:engine/model/model~Model.' );
  85. }
  86. let modelDocumentFragment, selection;
  87. const modelRoot = model.document.getRoot( options.rootName || 'main' );
  88. // Parse data string to model.
  89. const parsedResult = setData._parse( data, model.schema, {
  90. lastRangeBackward: options.lastRangeBackward,
  91. selectionAttributes: options.selectionAttributes,
  92. context: [ modelRoot.name ]
  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. model.change( writer => {
  102. // Replace existing model in document by new one.
  103. writer.remove( writer.createRangeIn( modelRoot ) );
  104. writer.insert( modelDocumentFragment, modelRoot );
  105. // Clean up previous document selection.
  106. writer.setSelection( null );
  107. writer.removeSelectionAttribute( model.document.selection.getAttributeKeys() );
  108. // Update document selection if specified.
  109. if ( selection ) {
  110. const ranges = [];
  111. for ( const range of selection.getRanges() ) {
  112. const start = new ModelPosition( modelRoot, range.start.path );
  113. const end = new ModelPosition( modelRoot, range.end.path );
  114. ranges.push( new ModelRange( start, end ) );
  115. }
  116. writer.setSelection( ranges, { backward: selection.isBackward } );
  117. if ( options.selectionAttributes ) {
  118. writer.setSelectionAttribute( selection.getAttributes() );
  119. }
  120. }
  121. } );
  122. }
  123. // Set parse as setData private method - needed for testing/spying.
  124. setData._parse = parse;
  125. /**
  126. * Converts model nodes to HTML-like string representation.
  127. *
  128. * **Note:** A {@link module:engine/model/text~Text text} node that contains attributes will be represented as:
  129. *
  130. * <$text attribute="value">Text data</$text>
  131. *
  132. * @param {module:engine/model/rootelement~RootElement|module:engine/model/element~Element|module:engine/model/text~Text|
  133. * module:engine/model/documentfragment~DocumentFragment} node A node to stringify.
  134. * @param {module:engine/model/selection~Selection|module:engine/model/position~Position|
  135. * module:engine/model/range~Range} [selectionOrPositionOrRange=null]
  136. * A selection instance whose ranges will be included in the returned string data. If a range instance is provided, it will be
  137. * converted to a selection containing this range. If a position instance is provided, it will be converted to a selection
  138. * containing one range collapsed at this position.
  139. * @param {Iterable.<module:engine/model/markercollection~Marker>|null} markers Markers to include.
  140. * @returns {String} An HTML-like string representing the model.
  141. */
  142. export function stringify( node, selectionOrPositionOrRange = null, markers = null ) {
  143. const model = new Model();
  144. const mapper = new Mapper();
  145. let selection, range;
  146. // Create a range witch wraps passed node.
  147. if ( node instanceof RootElement || node instanceof ModelDocumentFragment ) {
  148. range = model.createRangeIn( node );
  149. } else {
  150. // Node is detached - create new document fragment.
  151. if ( !node.parent ) {
  152. const fragment = new ModelDocumentFragment( node );
  153. range = model.createRangeIn( fragment );
  154. } else {
  155. range = new ModelRange(
  156. model.createPositionBefore( node ),
  157. model.createPositionAfter( node )
  158. );
  159. }
  160. }
  161. // Get selection from passed selection or position or range if at least one is specified.
  162. if ( selectionOrPositionOrRange instanceof ModelSelection ) {
  163. selection = selectionOrPositionOrRange;
  164. } else if ( selectionOrPositionOrRange instanceof DocumentSelection ) {
  165. selection = selectionOrPositionOrRange;
  166. } else if ( selectionOrPositionOrRange instanceof ModelRange ) {
  167. selection = new ModelSelection( selectionOrPositionOrRange );
  168. } else if ( selectionOrPositionOrRange instanceof ModelPosition ) {
  169. selection = new ModelSelection( selectionOrPositionOrRange );
  170. }
  171. // Set up conversion.
  172. // Create a temporary view controller.
  173. const view = new View();
  174. const viewDocument = view.document;
  175. const viewRoot = new ViewRootEditableElement( 'div' );
  176. // Create a temporary root element in view document.
  177. viewRoot._document = view.document;
  178. viewRoot.rootName = 'main';
  179. viewDocument.roots.add( viewRoot );
  180. // Create and setup downcast dispatcher.
  181. const downcastDispatcher = new DowncastDispatcher( { mapper } );
  182. // Bind root elements.
  183. mapper.bindElements( node.root, viewRoot );
  184. downcastDispatcher.on( 'insert:$text', insertText() );
  185. downcastDispatcher.on( 'attribute', ( evt, data, conversionApi ) => {
  186. if ( data.item instanceof ModelSelection || data.item instanceof DocumentSelection || data.item.is( 'textProxy' ) ) {
  187. const converter = wrap( ( modelAttributeValue, viewWriter ) => {
  188. return viewWriter.createAttributeElement(
  189. 'model-text-with-attributes',
  190. { [ data.attributeKey ]: stringifyAttributeValue( modelAttributeValue ) }
  191. );
  192. } );
  193. converter( evt, data, conversionApi );
  194. }
  195. } );
  196. downcastDispatcher.on( 'insert', insertElement( modelItem => {
  197. // Stringify object types values for properly display as an output string.
  198. const attributes = convertAttributes( modelItem.getAttributes(), stringifyAttributeValue );
  199. return new ViewContainerElement( modelItem.name, attributes );
  200. } ) );
  201. downcastDispatcher.on( 'selection', convertRangeSelection() );
  202. downcastDispatcher.on( 'selection', convertCollapsedSelection() );
  203. downcastDispatcher.on( 'addMarker', insertUIElement( ( data, writer ) => {
  204. const name = data.markerName + ':' + ( data.isOpening ? 'start' : 'end' );
  205. return writer.createUIElement( name );
  206. } ) );
  207. // Convert model to view.
  208. const writer = view._writer;
  209. downcastDispatcher.convertInsert( range, writer );
  210. // Convert model selection to view selection.
  211. if ( selection ) {
  212. downcastDispatcher.convertSelection( selection, markers || model.markers, writer );
  213. }
  214. if ( markers ) {
  215. // To provide stable results, sort markers by name.
  216. markers = Array.from( markers ).sort( ( a, b ) => a.name < b.name ? 1 : -1 );
  217. for ( const marker of markers ) {
  218. downcastDispatcher.convertMarkerAdd( marker.name, marker.getRange(), writer );
  219. }
  220. }
  221. // Parse view to data string.
  222. let data = viewStringify( viewRoot, viewDocument.selection, { sameSelectionCharacters: true } );
  223. // Removing unneccessary <div> and </div> added because `viewRoot` was also stringified alongside input data.
  224. data = data.substr( 5, data.length - 11 );
  225. view.destroy();
  226. // Replace valid XML `model-text-with-attributes` element name to `$text`.
  227. return data.replace( new RegExp( 'model-text-with-attributes', 'g' ), '$text' );
  228. }
  229. /**
  230. * Parses an HTML-like string and returns the model {@link module:engine/model/rootelement~RootElement rootElement}.
  231. *
  232. * **Note:** To create a {@link module:engine/model/text~Text text} node that contains attributes use:
  233. *
  234. * <$text attribute="value">Text data</$text>
  235. *
  236. * @param {String} data HTML-like string to be parsed.
  237. * @param {module:engine/model/schema~Schema} schema A schema instance used by converters for element validation.
  238. * @param {module:engine/model/batch~Batch} batch A batch used for conversion.
  239. * @param {Object} [options={}] Additional configuration.
  240. * @param {Array<Object>} [options.selectionAttributes] A list of attributes which will be passed to the selection.
  241. * @param {Boolean} [options.lastRangeBackward=false] If set to `true`, the last range will be added as backward.
  242. * @param {module:engine/model/schema~SchemaContextDefinition} [options.context='$root'] The conversion context.
  243. * If not provided, the default `'$root'` will be used.
  244. * @returns {module:engine/model/element~Element|module:engine/model/text~Text|
  245. * module:engine/model/documentfragment~DocumentFragment|Object} Returns the parsed model node or
  246. * an object with two fields: `model` and `selection`, when selection ranges were included in the data to parse.
  247. */
  248. export function parse( data, schema, options = {} ) {
  249. const mapper = new Mapper();
  250. // Replace not accepted by XML `$text` tag name by valid one `model-text-with-attributes`.
  251. data = data.replace( new RegExp( '\\$text', 'g' ), 'model-text-with-attributes' );
  252. // Parse data to view using view utils.
  253. const parsedResult = viewParse( data, {
  254. sameSelectionCharacters: true,
  255. lastRangeBackward: !!options.lastRangeBackward
  256. } );
  257. // Retrieve DocumentFragment and Selection from parsed view.
  258. let viewDocumentFragment, viewSelection, selection;
  259. if ( parsedResult.view && parsedResult.selection ) {
  260. viewDocumentFragment = parsedResult.view;
  261. viewSelection = parsedResult.selection;
  262. } else {
  263. viewDocumentFragment = parsedResult;
  264. }
  265. // Set up upcast dispatcher.
  266. const modelController = new Model();
  267. const upcastDispatcher = new UpcastDispatcher( { schema, mapper } );
  268. upcastDispatcher.on( 'documentFragment', convertToModelFragment() );
  269. upcastDispatcher.on( 'element:model-text-with-attributes', convertToModelText( true ) );
  270. upcastDispatcher.on( 'element', convertToModelElement() );
  271. upcastDispatcher.on( 'text', convertToModelText() );
  272. upcastDispatcher.isDebug = true;
  273. // Convert view to model.
  274. let model = modelController.change(
  275. writer => upcastDispatcher.convert( viewDocumentFragment.root, writer, options.context || '$root' )
  276. );
  277. mapper.bindElements( model, viewDocumentFragment.root );
  278. // If root DocumentFragment contains only one element - return that element.
  279. if ( model.childCount == 1 ) {
  280. model = model.getChild( 0 );
  281. }
  282. // Convert view selection to model selection.
  283. if ( viewSelection ) {
  284. const ranges = [];
  285. // Convert ranges.
  286. for ( const viewRange of viewSelection.getRanges() ) {
  287. ranges.push( mapper.toModelRange( viewRange ) );
  288. }
  289. // Create new selection.
  290. selection = new ModelSelection( ranges, { backward: viewSelection.isBackward } );
  291. // Set attributes to selection if specified.
  292. for ( const [ key, value ] of toMap( options.selectionAttributes || [] ) ) {
  293. selection.setAttribute( key, value );
  294. }
  295. }
  296. // Return model end selection when selection was specified.
  297. if ( selection ) {
  298. return { model, selection };
  299. }
  300. // Otherwise return model only.
  301. return model;
  302. }
  303. // -- Converters view -> model -----------------------------------------------------
  304. function convertToModelFragment() {
  305. return ( evt, data, conversionApi ) => {
  306. const childrenResult = conversionApi.convertChildren( data.viewItem, data.modelCursor );
  307. conversionApi.mapper.bindElements( data.modelCursor.parent, data.viewItem );
  308. data = Object.assign( data, childrenResult );
  309. evt.stop();
  310. };
  311. }
  312. function convertToModelElement() {
  313. return ( evt, data, conversionApi ) => {
  314. const elementName = data.viewItem.name;
  315. if ( !conversionApi.schema.checkChild( data.modelCursor, elementName ) ) {
  316. throw new Error( `Element '${ elementName }' was not allowed in given position.` );
  317. }
  318. // View attribute value is a string so we want to typecast it to the original type.
  319. // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
  320. const attributes = convertAttributes( data.viewItem.getAttributes(), parseAttributeValue );
  321. const element = conversionApi.writer.createElement( data.viewItem.name, attributes );
  322. conversionApi.writer.insert( element, data.modelCursor );
  323. conversionApi.mapper.bindElements( element, data.viewItem );
  324. conversionApi.convertChildren( data.viewItem, ModelPosition._createAt( element, 0 ) );
  325. data.modelRange = ModelRange._createOn( element );
  326. data.modelCursor = data.modelRange.end;
  327. evt.stop();
  328. };
  329. }
  330. function convertToModelText( withAttributes = false ) {
  331. return ( evt, data, conversionApi ) => {
  332. if ( !conversionApi.schema.checkChild( data.modelCursor, '$text' ) ) {
  333. throw new Error( 'Text was not allowed in given position.' );
  334. }
  335. let node;
  336. if ( withAttributes ) {
  337. // View attribute value is a string so we want to typecast it to the original type.
  338. // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
  339. const attributes = convertAttributes( data.viewItem.getAttributes(), parseAttributeValue );
  340. node = conversionApi.writer.createText( data.viewItem.getChild( 0 ).data, attributes );
  341. } else {
  342. node = conversionApi.writer.createText( data.viewItem.data );
  343. }
  344. conversionApi.writer.insert( node, data.modelCursor );
  345. data.modelRange = ModelRange._createFromPositionAndShift( data.modelCursor, node.offsetSize );
  346. data.modelCursor = data.modelRange.end;
  347. evt.stop();
  348. };
  349. }
  350. // Tries to get original type of attribute value using JSON parsing:
  351. //
  352. // `'true'` => `true`
  353. // `'1'` => `1`
  354. // `'{"x":1,"y":2}'` => `{ x: 1, y: 2 }`
  355. //
  356. // Parse error means that value should be a string:
  357. //
  358. // `'foobar'` => `'foobar'`
  359. function parseAttributeValue( attribute ) {
  360. try {
  361. return JSON.parse( attribute );
  362. } catch ( e ) {
  363. return attribute;
  364. }
  365. }
  366. // When value is an Object stringify it.
  367. function stringifyAttributeValue( data ) {
  368. if ( isPlainObject( data ) ) {
  369. return JSON.stringify( data );
  370. }
  371. return data;
  372. }
  373. // Loop trough attributes map and converts each value by passed converter.
  374. function* convertAttributes( attributes, converter ) {
  375. for ( const [ key, value ] of attributes ) {
  376. yield [ key, converter( value ) ];
  377. }
  378. }