8
0

model.js 16 KB

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