model.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import Mapper from '/ckeditor5/engine/conversion/mapper.js';
  6. import Document from '/ckeditor5/engine/model/document.js';
  7. import Range from '/ckeditor5/engine/model/range.js';
  8. import Position from '/ckeditor5/engine/model/position.js';
  9. import RootElement from '/ckeditor5/engine/model/rootelement.js';
  10. import ModelConversionDispatcher from '/ckeditor5/engine/conversion/modelconversiondispatcher.js';
  11. import ModelSelection from '/ckeditor5/engine/model/selection.js';
  12. import ModelDocumentFragment from '/ckeditor5/engine/model/documentfragment.js';
  13. import ModelElement from '/ckeditor5/engine/model/element.js';
  14. import ModelText from '/ckeditor5/engine/model/text.js';
  15. import ViewConversionDispatcher from '/ckeditor5/engine/conversion/viewconversiondispatcher.js';
  16. import ViewSelection from '/ckeditor5/engine/view/selection.js';
  17. import ViewDocumentFragment from '/ckeditor5/engine/view/documentfragment.js';
  18. import ViewElement from '/ckeditor5/engine/view/containerelement.js';
  19. import ViewText from '/ckeditor5/engine/view/text.js';
  20. import viewWriter from '/ckeditor5/engine/view/writer.js';
  21. import { parse as viewParse, stringify as viewStringify } from '/tests/engine/_utils/view.js';
  22. import {
  23. convertRangeSelection,
  24. convertCollapsedSelection
  25. } from '/ckeditor5/engine/conversion/model-selection-to-view-converters.js';
  26. import { convertText, convertToModelFragment } from '/ckeditor5/engine/conversion/view-to-model-converters.js';
  27. // Test utils uses `<$text foo="bar">Lorem ipsum</$text>` notation to create text with attributes, but `$text` is not
  28. // valid XML element name, so needs to be parsed before conversion to view.
  29. const VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT = 'view-text-with-attributes';
  30. const DATA_STRING_TEXT_WITH_ATTRIBUTES_ELEMENT = '$text';
  31. /**
  32. * Writes the contents of the {@link engine.model.Document Document} to an HTML-like string.
  33. *
  34. * ** Note: ** {@link engine.model.Text text} node contains attributes will be represented as:
  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 Document ) ) {
  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. * <$text attribute="value">Text data</$text>
  64. *
  65. * @param {engine.model.Document} document
  66. * @param {String} data HTML-like string to write into Document.
  67. * @param {Object} options
  68. * @param {String} [options.rootName='main'] Root name where parsed data will be stored. If not provided, default `main`
  69. * name will be used.
  70. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to selection.
  71. * @param {String} [options.batchType='transparent'] Batch type used for inserting elements. See {@link engine.model.Batch#type}.
  72. */
  73. export function setData( document, data, options = {} ) {
  74. if ( !( document instanceof Document ) ) {
  75. throw new TypeError( 'Document needs to be an instance of engine.model.Document.' );
  76. }
  77. let modelDocumentFragment, selection;
  78. const mapper = new Mapper();
  79. const modelRoot = document.getRoot( options.rootName || 'main' );
  80. // Parse data string to model.
  81. const parsedResult = setData._parse( data, document.schema, mapper );
  82. // Retrieve DocumentFragment and Selection from parsed model.
  83. if ( parsedResult.model ) {
  84. modelDocumentFragment = parsedResult.model;
  85. selection = parsedResult.selection;
  86. } else {
  87. modelDocumentFragment = parsedResult;
  88. }
  89. document.enqueueChanges( () => {
  90. // Replace existing model in document by new one.
  91. document.batch( options.batchType || 'transparent' )
  92. .remove( Range.createFromElement( modelRoot ) )
  93. .insert( Position.createAt( modelRoot, 0 ), modelDocumentFragment );
  94. // Clear selection
  95. document.selection.clearAttributes();
  96. document.selection.removeAllRanges();
  97. // Set attributes to selection if specified.
  98. if ( options.selectionAttributes ) {
  99. document.selection.setAttributesTo( options.selectionAttributes );
  100. }
  101. // Convert view selection to model if selection is defined.
  102. if ( selection ) {
  103. const ranges = [];
  104. for ( let viewRange of selection.getRanges() ) {
  105. ranges.push( ( mapper.toModelRange( viewRange ) ) );
  106. }
  107. document.selection.setRanges( ranges, selection.isBackward );
  108. }
  109. } );
  110. }
  111. // Set parse as setData private method - needed for testing/spying.
  112. setData._parse = parse;
  113. /**
  114. * Converts model nodes to HTML-like string representation.
  115. *
  116. * ** Note: ** {@link engine.model.Text text} node contains attributes will be represented as:
  117. * <$text attribute="value">Text data</$text>
  118. *
  119. * @param {engine.model.RootElement|engine.model.Element|engine.model.Text|
  120. * engine.model.DocumentFragment} node Node to stringify.
  121. * @param {engine.model.Selection|engine.model.Position|engine.model.Range} [selectionOrPositionOrRange=null]
  122. * Selection instance which ranges will be included in returned string data. If Range instance is provided - it will be
  123. * converted to selection containing this range. If Position instance is provided - it will be converted to selection
  124. * containing one range collapsed at this position.
  125. * @returns {String} HTML-like string representing the model.
  126. */
  127. export function stringify( node, selectionOrPositionOrRange = null ) {
  128. const mapper = new Mapper();
  129. let selection, range;
  130. // Create a range wrapping passed node.
  131. if ( node instanceof RootElement || node instanceof ModelDocumentFragment ) {
  132. range = Range.createFromElement( node );
  133. } else {
  134. // Node is detached - create new document fragment.
  135. if ( !node.parent ) {
  136. const fragment = new ModelDocumentFragment( node );
  137. range = Range.createFromElement( fragment );
  138. } else {
  139. range = new Range(
  140. Position.createBefore( node ),
  141. Position.createAfter( node )
  142. );
  143. }
  144. }
  145. // Get selection from passed selection or position or range if at least one is specified.
  146. if ( selectionOrPositionOrRange instanceof ModelSelection ) {
  147. selection = selectionOrPositionOrRange;
  148. } else if ( selectionOrPositionOrRange instanceof Range ) {
  149. selection = new ModelSelection();
  150. selection.addRange( selectionOrPositionOrRange );
  151. } else if ( selectionOrPositionOrRange instanceof Position ) {
  152. selection = new ModelSelection();
  153. selection.addRange( new Range( selectionOrPositionOrRange, selectionOrPositionOrRange ) );
  154. }
  155. // Setup model -> view converter.
  156. const viewDocumentFragment = new ViewDocumentFragment();
  157. const viewSelection = new ViewSelection();
  158. const modelToView = new ModelConversionDispatcher( { mapper, viewSelection } );
  159. modelToView.on( 'insert:$text', insertText() );
  160. modelToView.on( 'insert', insertElement() );
  161. modelToView.on( 'selection', convertRangeSelection() );
  162. modelToView.on( 'selection', convertCollapsedSelection() );
  163. mapper.bindElements( node, viewDocumentFragment );
  164. // Convert view to model.
  165. modelToView.convertInsert( range );
  166. modelToView.convertSelection( selection );
  167. mapper.clearBindings();
  168. // Parse view to data string.
  169. let data = viewStringify( viewDocumentFragment, viewSelection );
  170. // Replace valid XML text element name to `$text`.
  171. return data.replace( new RegExp( VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT, 'g' ), DATA_STRING_TEXT_WITH_ATTRIBUTES_ELEMENT );
  172. }
  173. /**
  174. * Parses HTML-like string and returns model {@link engine.model.RootElement rootElement}.
  175. *
  176. * ** Note: ** To create {@link engine.model.Text text} node witch containing attributes use:
  177. * <$text attribute="value">Text data</$text>
  178. *
  179. * @param {String} data HTML-like string to be parsed.
  180. * @param {engine.model.schema} schema Schema instance uses by converters for validation. Element not registered
  181. * in schema won't be created.
  182. * @param {engine.model.mapper} [mapper=new Mapper()] Mapper instance uses mainly by `setData` method to map position
  183. * between {@link engine.view.document Document} and {@link engine.model.document Document}.
  184. * @returns {engine.model.Element|engine.model.Text|engine.model.DocumentFragment|Object} Returns parsed model node or
  185. * object with two fields `model` and `selection` when selection ranges were included in data to parse.
  186. */
  187. export function parse( data, schema, mapper = new Mapper() ) {
  188. // Replace not accepted by XML `$text` element by valid one.
  189. data = data.replace( new RegExp( '\\' + DATA_STRING_TEXT_WITH_ATTRIBUTES_ELEMENT, 'g' ), VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT );
  190. // Parse data to view using view utils.
  191. const parsedResult = viewParse( data );
  192. // Retrieve DocumentFragment and Selection from parsed view.
  193. let viewDocumentFragment, selection;
  194. if ( parsedResult.view && parsedResult.selection ) {
  195. viewDocumentFragment = parsedResult.view;
  196. selection = parsedResult.selection;
  197. } else {
  198. viewDocumentFragment = parsedResult;
  199. }
  200. viewDocumentFragment = viewDocumentFragment.parent ? viewDocumentFragment.parent : viewDocumentFragment;
  201. // Setup view -> model converter.
  202. const viewToModel = new ViewConversionDispatcher( { mapper, schema } );
  203. viewToModel.on( 'text', convertText() );
  204. viewToModel.on( `element:${ VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT }`, convertToModelTextWithAttributes(), null, 9999 );
  205. viewToModel.on( 'element', convertToModelElement(), null, 9999 );
  206. viewToModel.on( 'documentFragment', convertToModelFragment(), null, 9999 );
  207. // Convert view to model.
  208. let root = viewToModel.convert( viewDocumentFragment, { context: [ '$root' ] } );
  209. // If root DocumentFragment contains only one element - return that element.
  210. if ( root instanceof DocumentFragment && root.childCount == 1 ) {
  211. root = root.getChild( 0 );
  212. }
  213. // Return model end selection when selection was specified.
  214. if ( selection ) {
  215. return {
  216. model: root,
  217. selection: selection
  218. };
  219. }
  220. // Otherwise return model only.
  221. return root;
  222. }
  223. // -- converters view -> model -----------------------------------------------------
  224. function convertToModelElement() {
  225. return ( evt, data, consumable, conversionApi ) => {
  226. const schemaQuery = {
  227. name: data.input.name,
  228. inside: data.context
  229. };
  230. // `VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT` is handled in specified way by `convertToModelTextWithAttributes`.
  231. if ( data.input.name !== VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT ) {
  232. if ( !conversionApi.schema.check( schemaQuery ) ) {
  233. throw new Error( `Element '${ schemaQuery.name }' not allowed in context.` );
  234. }
  235. if ( consumable.consume( data.input, { name: true } ) ) {
  236. data.output = new ModelElement( data.input.name, data.input.getAttributes() );
  237. conversionApi.mapper.bindElements( data.output, data.input );
  238. data.context.push( data.output );
  239. data.output.appendChildren( conversionApi.convertChildren( data.input, consumable, data ) );
  240. data.context.pop();
  241. }
  242. }
  243. };
  244. }
  245. function convertToModelTextWithAttributes() {
  246. return ( evt, data, consumable, conversionApi ) => {
  247. const schemaQuery = {
  248. name: '$text',
  249. inside: data.context
  250. };
  251. if ( !conversionApi.schema.check( schemaQuery ) ) {
  252. throw new Error( `Element '${ schemaQuery.name }' not allowed in context.` );
  253. }
  254. if ( conversionApi.schema.check( schemaQuery ) ) {
  255. if ( consumable.consume( data.input, { name: true } ) ) {
  256. data.output = new ModelText( data.input.getChild( 0 ).data, data.input.getAttributes() );
  257. }
  258. }
  259. };
  260. }
  261. // -- converters model -> view -----------------------------------------------------
  262. function insertElement() {
  263. return ( evt, data, consumable, conversionApi ) => {
  264. consumable.consume( data.item, 'insert' );
  265. const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  266. const viewElement = new ViewElement( data.item.name, data.item.getAttributes() );
  267. conversionApi.mapper.bindElements( data.item, viewElement );
  268. viewWriter.insert( viewPosition, viewElement );
  269. };
  270. }
  271. function insertText() {
  272. return ( evt, data, consumable, conversionApi ) => {
  273. consumable.consume( data.item, 'insert' );
  274. const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  275. const textAttributes = data.item.getAttributes();
  276. let node;
  277. if ( textAttributes.length ) {
  278. node = new ViewElement( VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT, textAttributes );
  279. } else {
  280. node = new ViewText( data.item.data );
  281. }
  282. viewWriter.insert( viewPosition, node );
  283. evt.stop();
  284. };
  285. }