8
0

model.js 17 KB

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