model.js 17 KB

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