8
0

model.js 17 KB

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