model.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import RootElement from '/ckeditor5/engine/model/rootelement.js';
  6. import ModelDocument from '/ckeditor5/engine/model/document.js';
  7. import ModelRange from '/ckeditor5/engine/model/range.js';
  8. import ModelPosition from '/ckeditor5/engine/model/position.js';
  9. import ModelConversionDispatcher from '/ckeditor5/engine/conversion/modelconversiondispatcher.js';
  10. import ModelSelection from '/ckeditor5/engine/model/selection.js';
  11. import ModelDocumentFragment from '/ckeditor5/engine/model/documentfragment.js';
  12. import ModelElement from '/ckeditor5/engine/model/element.js';
  13. import ModelText from '/ckeditor5/engine/model/text.js';
  14. import ModelTextProxy from '/ckeditor5/engine/model/textproxy.js';
  15. import modelWriter from '/ckeditor5/engine/model/writer.js';
  16. import ViewConversionDispatcher from '/ckeditor5/engine/conversion/viewconversiondispatcher.js';
  17. import ViewSelection from '/ckeditor5/engine/view/selection.js';
  18. import ViewDocumentFragment from '/ckeditor5/engine/view/documentfragment.js';
  19. import ViewElement from '/ckeditor5/engine/view/containerelement.js';
  20. import ViewAttributeElement from '/ckeditor5/engine/view/attributeelement.js';
  21. import Mapper from '/ckeditor5/engine/conversion/mapper.js';
  22. import { parse as viewParse, stringify as viewStringify } from '/tests/engine/_utils/view.js';
  23. import {
  24. convertRangeSelection,
  25. convertCollapsedSelection,
  26. convertSelectionAttribute
  27. } from '/ckeditor5/engine/conversion/model-selection-to-view-converters.js';
  28. import { insertText, insertElement, wrap } from '/ckeditor5/engine/conversion/model-to-view-converters.js';
  29. import isPlainObject from '/ckeditor5/utils/lib/lodash/isplainobject.js';
  30. /**
  31. * Writes the contents of the {@link engine.model.Document Document} to an HTML-like string.
  32. *
  33. * **Note:** {@link engine.model.Text text} node contains attributes will be represented as:
  34. *
  35. * <$text attribute="value">Text data</$text>
  36. *
  37. * @param {engine.model.Document} document
  38. * @param {Object} [options]
  39. * @param {Boolean} [options.withoutSelection=false] Whether to write the selection. When set to `true` selection will
  40. * be not included in returned string.
  41. * @param {Boolean} [options.rootName='main'] Name of the root from which data should be stringified. If not provided
  42. * default `main` name will be used.
  43. * @returns {String} The stringified data.
  44. */
  45. export function getData( document, options = {} ) {
  46. if ( !( document instanceof ModelDocument ) ) {
  47. throw new TypeError( 'Document needs to be an instance of engine.model.Document.' );
  48. }
  49. const withoutSelection = !!options.withoutSelection;
  50. const rootName = options.rootName || 'main';
  51. const root = document.getRoot( rootName );
  52. return withoutSelection ? getData._stringify( root ) : getData._stringify( root, document.selection );
  53. }
  54. // Set stringify as getData private method - needed for testing/spying.
  55. getData._stringify = stringify;
  56. /**
  57. * Sets the contents of the {@link engine.model.Document Document} provided as HTML-like string.
  58. * It uses {@link engine.model.Document#enqueueChanges enqueueChanges} method.
  59. *
  60. * **Note:** Remember to register elements in {@link engine.model.Document#schema document's schema} before inserting them.
  61. *
  62. * **Note:** To create {@link engine.model.Text text} node witch containing attributes use:
  63. *
  64. * <$text attribute="value">Text data</$text>
  65. *
  66. * @param {engine.model.Document} document
  67. * @param {String} data HTML-like string to write into Document.
  68. * @param {Object} options
  69. * @param {String} [options.rootName='main'] Root name where parsed data will be stored. If not provided, default `main`
  70. * name will be used.
  71. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to the selection.
  72. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward.
  73. * @param {String} [options.batchType='transparent'] Batch type used for inserting elements. See {@link engine.model.Batch#type}.
  74. */
  75. export function setData( document, data, options = {} ) {
  76. if ( !( document instanceof ModelDocument ) ) {
  77. throw new TypeError( 'Document needs to be an instance of engine.model.Document.' );
  78. }
  79. let modelDocumentFragment, selection;
  80. const modelRoot = document.getRoot( options.rootName || 'main' );
  81. // Parse data string to model.
  82. const parsedResult = setData._parse( data, document.schema, {
  83. lastRangeBackward: options.lastRangeBackward,
  84. selectionAttributes: options.selectionAttributes
  85. } );
  86. // Retrieve DocumentFragment and Selection from parsed model.
  87. if ( parsedResult.model ) {
  88. modelDocumentFragment = parsedResult.model;
  89. selection = parsedResult.selection;
  90. } else {
  91. modelDocumentFragment = parsedResult;
  92. }
  93. document.enqueueChanges( () => {
  94. // Replace existing model in document by new one.
  95. document.batch( options.batchType || 'transparent' )
  96. .remove( ModelRange.createIn( modelRoot ) )
  97. .insert( ModelPosition.createAt( modelRoot, 0 ), modelDocumentFragment );
  98. // Clean up previous document selection.
  99. document.selection.clearAttributes();
  100. document.selection.removeAllRanges();
  101. // Update document selection if specified.
  102. if ( selection ) {
  103. const ranges = [];
  104. for ( let range of selection.getRanges() ) {
  105. let start, end;
  106. // Each range returned from `parse()` method has its root placed in DocumentFragment.
  107. // Here we convert each range to have its root re-calculated properly and be placed inside
  108. // model document root.
  109. if ( range.start.parent instanceof ModelDocumentFragment ) {
  110. start = ModelPosition.createFromParentAndOffset( modelRoot, range.start.offset );
  111. } else {
  112. start = ModelPosition.createFromParentAndOffset( range.start.parent, range.start.offset );
  113. }
  114. if ( range.end.parent instanceof ModelDocumentFragment ) {
  115. end = ModelPosition.createFromParentAndOffset( modelRoot, range.end.offset );
  116. } else {
  117. end = ModelPosition.createFromParentAndOffset( range.end.parent, range.end.offset );
  118. }
  119. ranges.push( new ModelRange( start, end ) );
  120. }
  121. document.selection.setRanges( ranges, selection.isBackward );
  122. document.selection.setAttributesTo( selection.getAttributes() );
  123. }
  124. } );
  125. }
  126. // Set parse as setData private method - needed for testing/spying.
  127. setData._parse = parse;
  128. /**
  129. * Converts model nodes to HTML-like string representation.
  130. *
  131. * **Note:** {@link engine.model.Text text} node contains attributes will be represented as:
  132. *
  133. * <$text attribute="value">Text data</$text>
  134. *
  135. * @param {engine.model.RootElement|engine.model.Element|engine.model.Text|
  136. * engine.model.DocumentFragment} node Node to stringify.
  137. * @param {engine.model.Selection|engine.model.Position|engine.model.Range} [selectionOrPositionOrRange=null]
  138. * Selection instance which ranges will be included in returned string data. If Range instance is provided - it will be
  139. * converted to selection containing this range. If Position instance is provided - it will be converted to selection
  140. * containing one range collapsed at this position.
  141. * @returns {String} HTML-like string representing the model.
  142. */
  143. export function stringify( node, selectionOrPositionOrRange = null ) {
  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 = ModelRange.createIn( node );
  149. } else {
  150. // Node is detached - create new document fragment.
  151. if ( !node.parent ) {
  152. const fragment = new ModelDocumentFragment( node );
  153. range = ModelRange.createIn( fragment );
  154. } else {
  155. range = new ModelRange(
  156. ModelPosition.createBefore( node ),
  157. ModelPosition.createAfter( 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 ModelRange ) {
  165. selection = new ModelSelection();
  166. selection.addRange( selectionOrPositionOrRange );
  167. } else if ( selectionOrPositionOrRange instanceof ModelPosition ) {
  168. selection = new ModelSelection();
  169. selection.addRange( new ModelRange( selectionOrPositionOrRange, selectionOrPositionOrRange ) );
  170. }
  171. // Setup model to view converter.
  172. const viewDocumentFragment = new ViewDocumentFragment();
  173. const viewSelection = new ViewSelection();
  174. const modelToView = new ModelConversionDispatcher( { mapper, viewSelection } );
  175. // Bind root elements.
  176. mapper.bindElements( node.root, viewDocumentFragment );
  177. modelToView.on( 'insert:$text', insertText() );
  178. modelToView.on( 'addAttribute', wrap( ( value, data ) => {
  179. if ( data.item instanceof ModelTextProxy ) {
  180. return new ViewAttributeElement( 'model-text-with-attributes', { [ data.attributeKey ]: stringifyAttributeValue( value ) } );
  181. }
  182. } ) );
  183. modelToView.on( 'insert', insertElement( ( data ) => {
  184. // Stringify object types values for properly display as an output string.
  185. const attributes = convertAttributes( data.item.getAttributes(), stringifyAttributeValue );
  186. return new ViewElement( data.item.name, attributes );
  187. } ) );
  188. modelToView.on( 'selection', convertRangeSelection() );
  189. modelToView.on( 'selection', convertCollapsedSelection() );
  190. modelToView.on( 'selectionAttribute', convertSelectionAttribute( ( value, data ) => {
  191. return new ViewAttributeElement( 'model-text-with-attributes', { [ data.key ]: value } );
  192. } ) );
  193. // Convert model to view.
  194. modelToView.convertInsertion( range );
  195. // Convert model selection to view selection.
  196. if ( selection ) {
  197. modelToView.convertSelection( selection );
  198. }
  199. // Parse view to data string.
  200. let data = viewStringify( viewDocumentFragment, viewSelection, { sameSelectionCharacters: true } );
  201. // Replace valid XML `model-text-with-attributes` element name to `$text`.
  202. return data.replace( new RegExp( 'model-text-with-attributes', 'g' ), '$text' );
  203. }
  204. /**
  205. * Parses HTML-like string and returns model {@link engine.model.RootElement rootElement}.
  206. *
  207. * **Note:** To create {@link engine.model.Text text} node witch containing attributes use:
  208. *
  209. * <$text attribute="value">Text data</$text>
  210. *
  211. * @param {String} data HTML-like string to be parsed.
  212. * @param {engine.model.schema} schema Schema instance uses by converters for element validation.
  213. * @param {Object} options Additional configuration.
  214. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to the selection.
  215. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward.
  216. * @returns {engine.model.Element|engine.model.Text|engine.model.DocumentFragment|Object} Returns parsed model node or
  217. * object with two fields `model` and `selection` when selection ranges were included in data to parse.
  218. */
  219. export function parse( data, schema, options = {} ) {
  220. const mapper = new Mapper();
  221. // Replace not accepted by XML `$text` tag name by valid one `model-text-with-attributes`.
  222. data = data.replace( new RegExp( '\\$text', 'g' ), 'model-text-with-attributes' );
  223. // Parse data to view using view utils.
  224. const parsedResult = viewParse( data, {
  225. sameSelectionCharacters: true,
  226. lastRangeBackward: !!options.lastRangeBackward
  227. } );
  228. // Retrieve DocumentFragment and Selection from parsed view.
  229. let viewDocumentFragment, viewSelection;
  230. if ( parsedResult.view && parsedResult.selection ) {
  231. viewDocumentFragment = parsedResult.view;
  232. viewSelection = parsedResult.selection;
  233. } else {
  234. viewDocumentFragment = parsedResult;
  235. }
  236. // Setup view to model converter.
  237. const viewToModel = new ViewConversionDispatcher( { schema, mapper } );
  238. viewToModel.on( 'documentFragment', convertToModelFragment() );
  239. viewToModel.on( `element:model-text-with-attributes`, convertToModelText( true ) );
  240. viewToModel.on( 'element', convertToModelElement() );
  241. viewToModel.on( 'text', convertToModelText() );
  242. // Convert view to model.
  243. let model = viewToModel.convert( viewDocumentFragment.root, { context: [ '$root' ] } );
  244. // If root DocumentFragment contains only one element - return that element.
  245. if ( model instanceof ModelDocumentFragment && model.childCount == 1 ) {
  246. model = model.getChild( 0 );
  247. }
  248. // Convert view selection to model selection.
  249. let selection;
  250. if ( viewSelection ) {
  251. const ranges = [];
  252. // Convert ranges.
  253. for ( let viewRange of viewSelection.getRanges() ) {
  254. ranges.push( ( mapper.toModelRange( viewRange ) ) );
  255. }
  256. // Create new selection.
  257. selection = new ModelSelection();
  258. selection.setRanges( ranges, viewSelection.isBackward );
  259. // Set attributes to selection if specified.
  260. if ( options.selectionAttributes ) {
  261. selection.setAttributesTo( options.selectionAttributes );
  262. }
  263. }
  264. // Return model end selection when selection was specified.
  265. if ( selection ) {
  266. return { model, selection };
  267. }
  268. // Otherwise return model only.
  269. return model;
  270. }
  271. // -- Converters view -> model -----------------------------------------------------
  272. function convertToModelFragment() {
  273. return ( evt, data, consumable, conversionApi ) => {
  274. const convertedChildren = conversionApi.convertChildren( data.input, consumable, data );
  275. data.output = new ModelDocumentFragment( modelWriter.normalizeNodes( convertedChildren ) );
  276. conversionApi.mapper.bindElements( data.output, data.input );
  277. evt.stop();
  278. };
  279. }
  280. function convertToModelElement() {
  281. return ( evt, data, consumable, conversionApi ) => {
  282. const schemaQuery = {
  283. name: data.input.name,
  284. inside: data.context
  285. };
  286. if ( !conversionApi.schema.check( schemaQuery ) ) {
  287. throw new Error( `Element '${ schemaQuery.name }' not allowed in context.` );
  288. }
  289. // View attribute value is a string so we want to typecast it to the original type.
  290. // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
  291. const attributes = convertAttributes( data.input.getAttributes(), parseAttributeValue );
  292. data.output = new ModelElement( data.input.name, attributes );
  293. conversionApi.mapper.bindElements( data.output, data.input );
  294. data.context.push( data.output );
  295. data.output.appendChildren( conversionApi.convertChildren( data.input, consumable, data ) );
  296. data.context.pop();
  297. evt.stop();
  298. };
  299. }
  300. function convertToModelText( withAttributes = false ) {
  301. return ( evt, data, consumable, conversionApi ) => {
  302. const schemaQuery = {
  303. name: '$text',
  304. inside: data.context
  305. };
  306. if ( !conversionApi.schema.check( schemaQuery ) ) {
  307. throw new Error( `Element '${ schemaQuery.name }' not allowed in context.` );
  308. }
  309. let node;
  310. if ( withAttributes ) {
  311. // View attribute value is a string so we want to typecast it to the original type.
  312. // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
  313. const attributes = convertAttributes( data.input.getAttributes(), parseAttributeValue );
  314. node = new ModelText( data.input.getChild( 0 ).data, attributes );
  315. } else {
  316. node = new ModelText( data.input.data );
  317. }
  318. data.output = node;
  319. evt.stop();
  320. };
  321. }
  322. // Tries to get original type of attribute value using JSON parsing:
  323. //
  324. // `'true'` => `true`
  325. // `'1'` => `1`
  326. // `'{"x":1,"y":2}'` => `{ x: 1, y: 2 }`
  327. //
  328. // Parse error means that value should be a string:
  329. //
  330. // `'foobar'` => `'foobar'`
  331. function parseAttributeValue( attribute ) {
  332. try {
  333. return JSON.parse( attribute );
  334. } catch ( e ) {
  335. return attribute;
  336. }
  337. }
  338. // When value is an Object stringify it.
  339. function stringifyAttributeValue( data ) {
  340. if ( isPlainObject( data ) ) {
  341. return JSON.stringify( data );
  342. }
  343. return data;
  344. }
  345. // Loop trough attributes map and converts each value by passed converter.
  346. function *convertAttributes( attributes, converter ) {
  347. for ( let [ key, value ] of attributes ) {
  348. yield [ key, converter( value ) ];
  349. }
  350. }