8
0

model.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 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 ViewText from '/ckeditor5/engine/view/text.js';
  21. import viewWriter from '/ckeditor5/engine/view/writer.js';
  22. import count from '/ckeditor5/utils/count.js';
  23. import { parse as viewParse, stringify as viewStringify } from '/tests/engine/_utils/view.js';
  24. import { convertRangeSelection, convertCollapsedSelection } from '/ckeditor5/engine/conversion/model-selection-to-view-converters.js';
  25. // Test utils uses `<$text foo="bar">Lorem ipsum</$text>` notation to create text with attributes, but `$text` is not
  26. // valid XML element name, so needs to be parsed before conversion to view.
  27. const VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT = 'view-text-with-attributes';
  28. const DATA_STRING_TEXT_WITH_ATTRIBUTES_ELEMENT = '$text';
  29. /**
  30. * Writes the contents of the {@link engine.model.Document Document} to an HTML-like string.
  31. *
  32. * ** Note: ** {@link engine.model.Text text} node contains attributes will be represented as:
  33. * <$text attribute="value">Text data</$text>
  34. *
  35. * @param {engine.model.Document} document
  36. * @param {Object} [options]
  37. * @param {Boolean} [options.withoutSelection=false] Whether to write the selection. When set to `true` selection will
  38. * be not included in returned string.
  39. * @param {Boolean} [options.rootName='main'] Name of the root from which data should be stringified. If not provided
  40. * default `main` name will be used.
  41. * @returns {String} The stringified data.
  42. */
  43. export function getData( document, options = {} ) {
  44. if ( !( document instanceof Document ) ) {
  45. throw new TypeError( 'Document needs to be an instance of engine.model.Document.' );
  46. }
  47. const withoutSelection = !!options.withoutSelection;
  48. const rootName = options.rootName || 'main';
  49. const root = document.getRoot( rootName );
  50. return withoutSelection ? getData._stringify( root ) : getData._stringify( root, document.selection );
  51. }
  52. // Set stringify as getData private method - needed for testing/spying.
  53. getData._stringify = stringify;
  54. /**
  55. * Sets the contents of the {@link engine.model.Document Document} provided as HTML-like string.
  56. * It uses {@link engine.model.Document#enqueueChanges enqueueChanges} method.
  57. *
  58. * ** Note: ** Remember to register elements in {@link engine.model.Document#schema document's schema} before inserting them.
  59. *
  60. * ** Note: ** To create {@link engine.model.Text text} node witch containing attributes use:
  61. * <$text attribute="value">Text data</$text>
  62. *
  63. * @param {engine.model.Document} document
  64. * @param {String} data HTML-like string to write into Document.
  65. * @param {Object} options
  66. * @param {String} [options.rootName='main'] Root name where parsed data will be stored. If not provided, default `main`
  67. * name will be used.
  68. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to the selection.
  69. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward.
  70. * @param {String} [options.batchType='transparent'] Batch type used for inserting elements. See {@link engine.model.Batch#type}.
  71. */
  72. export function setData( document, data, options = {} ) {
  73. if ( !( document instanceof Document ) ) {
  74. throw new TypeError( 'Document needs to be an instance of engine.model.Document.' );
  75. }
  76. let modelDocumentFragment, selection;
  77. const modelRoot = document.getRoot( options.rootName || 'main' );
  78. // Parse data string to model.
  79. const parsedResult = setData._parse( data, document.schema, {
  80. lastRangeBackward: options.lastRangeBackward,
  81. selectionAttributes: options.selectionAttributes
  82. } );
  83. // Retrieve DocumentFragment and Selection from parsed model.
  84. if ( parsedResult.model ) {
  85. modelDocumentFragment = parsedResult.model;
  86. selection = parsedResult.selection;
  87. } else {
  88. modelDocumentFragment = parsedResult;
  89. }
  90. document.enqueueChanges( () => {
  91. // Replace existing model in document by new one.
  92. document.batch( options.batchType || 'transparent' )
  93. .remove( Range.createIn( modelRoot ) )
  94. .insert( Position.createAt( modelRoot, 0 ), modelDocumentFragment );
  95. // Clean up previous document selection.
  96. document.selection.clearAttributes();
  97. document.selection.removeAllRanges();
  98. // Update document selection if specified.
  99. if ( selection ) {
  100. const ranges = [];
  101. for ( let range of selection.getRanges() ) {
  102. let start, end;
  103. // Each range returned from `parse()` method has its root placed in DocumentFragment.
  104. // Here we convert each range to have its root re-calculated properly and be placed inside
  105. // model document root.
  106. if ( range.start.parent instanceof ModelDocumentFragment ) {
  107. start = Position.createFromParentAndOffset( modelRoot, range.start.offset );
  108. } else {
  109. start = Position.createFromParentAndOffset( range.start.parent, range.start.offset );
  110. }
  111. if ( range.end.parent instanceof ModelDocumentFragment ) {
  112. end = Position.createFromParentAndOffset( modelRoot, range.end.offset );
  113. } else {
  114. end = Position.createFromParentAndOffset( range.end.parent, range.end.offset );
  115. }
  116. ranges.push( new Range( start, end ) );
  117. }
  118. document.selection.setRanges( ranges, selection.isBackward );
  119. document.selection.setAttributesTo( selection.getAttributes() );
  120. }
  121. } );
  122. }
  123. // Set parse as setData private method - needed for testing/spying.
  124. setData._parse = parse;
  125. /**
  126. * Converts model nodes to HTML-like string representation.
  127. *
  128. * ** Note: ** {@link engine.model.Text text} node contains attributes will be represented as:
  129. * <$text attribute="value">Text data</$text>
  130. *
  131. * @param {engine.model.RootElement|engine.model.Element|engine.model.Text|
  132. * engine.model.DocumentFragment} node Node to stringify.
  133. * @param {engine.model.Selection|engine.model.Position|engine.model.Range} [selectionOrPositionOrRange=null]
  134. * Selection instance which ranges will be included in returned string data. If Range instance is provided - it will be
  135. * converted to selection containing this range. If Position instance is provided - it will be converted to selection
  136. * containing one range collapsed at this position.
  137. * @returns {String} HTML-like string representing the model.
  138. */
  139. export function stringify( node, selectionOrPositionOrRange = null ) {
  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 = Range.createIn( node );
  145. } else {
  146. // Node is detached - create new document fragment.
  147. if ( !node.parent ) {
  148. const fragment = new ModelDocumentFragment( node );
  149. range = Range.createIn( fragment );
  150. } else {
  151. range = new Range(
  152. Position.createBefore( node ),
  153. Position.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 Range ) {
  161. selection = new ModelSelection();
  162. selection.addRange( selectionOrPositionOrRange );
  163. } else if ( selectionOrPositionOrRange instanceof Position ) {
  164. selection = new ModelSelection();
  165. selection.addRange( new Range( selectionOrPositionOrRange, selectionOrPositionOrRange ) );
  166. }
  167. // Setup model to view converter.
  168. const viewDocumentFragment = new ViewDocumentFragment();
  169. const viewSelection = new ViewSelection();
  170. const modelToView = new ModelConversionDispatcher( { mapper, viewSelection } );
  171. // Bind root elements.
  172. mapper.bindElements( node.root, viewDocumentFragment );
  173. modelToView.on( 'insert:$text', insertText() );
  174. modelToView.on( 'insert', insertElement() );
  175. modelToView.on( 'selection', convertRangeSelection() );
  176. modelToView.on( 'selection', convertCollapsedSelection() );
  177. // Convert model to view.
  178. modelToView.convertInsert( range );
  179. // Convert model selection to view selection.
  180. if ( selection ) {
  181. modelToView.convertSelection( selection );
  182. }
  183. // Parse view to data string.
  184. let data = viewStringify( viewDocumentFragment, viewSelection, { sameSelectionCharacters: true } );
  185. // Replace valid XML `model-test` element name to `$text`.
  186. return data.replace( new RegExp( VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT, 'g' ), DATA_STRING_TEXT_WITH_ATTRIBUTES_ELEMENT );
  187. }
  188. /**
  189. * Parses HTML-like string and returns model {@link engine.model.RootElement rootElement}.
  190. *
  191. * ** Note: ** To create {@link engine.model.Text text} node witch containing attributes use:
  192. * <$text attribute="value">Text data</$text>
  193. *
  194. * @param {String} data HTML-like string to be parsed.
  195. * @param {engine.model.schema} schema Schema instance uses by converters for element validation.
  196. * @param {Object} options Additional configuration.
  197. * @param {Array<Object>} [options.selectionAttributes] List of attributes which will be passed to the selection.
  198. * @param {Boolean} [options.lastRangeBackward=false] If set to true last range will be added as backward.
  199. * @returns {engine.model.Element|engine.model.Text|engine.model.DocumentFragment|Object} Returns parsed model node or
  200. * object with two fields `model` and `selection` when selection ranges were included in data to parse.
  201. */
  202. export function parse( data, schema, options = {} ) {
  203. const mapper = new Mapper();
  204. // Replace not accepted by XML `$text` tag name by valid one `model-text`.
  205. data = data.replace( new RegExp( '\\' + DATA_STRING_TEXT_WITH_ATTRIBUTES_ELEMENT, 'g' ), VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT );
  206. // Parse data to view using view utils.
  207. const parsedResult = viewParse( data, {
  208. sameSelectionCharacters: true,
  209. lastRangeBackward: !!options.lastRangeBackward
  210. } );
  211. // Retrieve DocumentFragment and Selection from parsed view.
  212. let viewDocumentFragment, viewSelection;
  213. if ( parsedResult.view && parsedResult.selection ) {
  214. viewDocumentFragment = parsedResult.view;
  215. viewSelection = parsedResult.selection;
  216. } else {
  217. viewDocumentFragment = parsedResult;
  218. }
  219. // Setup view to model converter.
  220. const viewToModel = new ViewConversionDispatcher( { schema, mapper } );
  221. viewToModel.on( 'text', convertToModelText() );
  222. viewToModel.on( `element:${ VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT }`, convertToModelText( true ), null, 9999 );
  223. viewToModel.on( 'element', convertToModelElement(), null, 9999 );
  224. viewToModel.on( 'documentFragment', convertToModelFragment(), null, 9999 );
  225. // Convert view to model.
  226. let model = viewToModel.convert( viewDocumentFragment.root, { context: [ '$root' ] } );
  227. // If root DocumentFragment contains only one element - return that element.
  228. if ( model instanceof ModelDocumentFragment && model.childCount == 1 ) {
  229. model = model.getChild( 0 );
  230. }
  231. // Convert view selection to model selection.
  232. let selection;
  233. if ( viewSelection ) {
  234. const ranges = [];
  235. // Convert ranges.
  236. for ( let viewRange of viewSelection.getRanges() ) {
  237. ranges.push( ( mapper.toModelRange( viewRange ) ) );
  238. }
  239. // Create new selection.
  240. selection = new ModelSelection();
  241. selection.setRanges( ranges, viewSelection.isBackward );
  242. // Set attributes to selection if specified.
  243. if ( options.selectionAttributes ) {
  244. selection.setAttributesTo( options.selectionAttributes );
  245. }
  246. }
  247. // Return model end selection when selection was specified.
  248. if ( selection ) {
  249. return { model, selection };
  250. }
  251. // Otherwise return model only.
  252. return model;
  253. }
  254. // -- converters view -> model -----------------------------------------------------
  255. function convertToModelFragment() {
  256. return ( evt, data, consumable, conversionApi ) => {
  257. // Second argument in `consumable.test` is discarded for ViewDocumentFragment but is needed for ViewElement.
  258. if ( !data.output && consumable.test( data.input, { name: true } ) ) {
  259. const convertedChildren = conversionApi.convertChildren( data.input, consumable, data );
  260. data.output = new ModelDocumentFragment( modelWriter.normalizeNodes( convertedChildren ) );
  261. conversionApi.mapper.bindElements( data.output, data.input );
  262. }
  263. };
  264. }
  265. function convertToModelElement() {
  266. return ( evt, data, consumable, conversionApi ) => {
  267. const schemaQuery = {
  268. name: data.input.name,
  269. inside: data.context
  270. };
  271. // `VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT` is handled in specified way by `convertToModelTextWithAttributes`.
  272. if ( data.input.name !== VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT ) {
  273. if ( !conversionApi.schema.check( schemaQuery ) ) {
  274. throw new Error( `Element '${ schemaQuery.name }' not allowed in context.` );
  275. }
  276. if ( consumable.consume( data.input, { name: true } ) ) {
  277. data.output = new ModelElement( data.input.name, data.input.getAttributes() );
  278. conversionApi.mapper.bindElements( data.output, data.input );
  279. data.context.push( data.output );
  280. data.output.appendChildren( conversionApi.convertChildren( data.input, consumable, data ) );
  281. data.context.pop();
  282. }
  283. }
  284. };
  285. }
  286. function convertToModelText( withAttributes = false ) {
  287. return ( evt, data, consumable, conversionApi ) => {
  288. const schemaQuery = {
  289. name: '$text',
  290. inside: data.context
  291. };
  292. if ( !conversionApi.schema.check( schemaQuery ) ) {
  293. throw new Error( `Element '${ schemaQuery.name }' not allowed in context.` );
  294. }
  295. if ( conversionApi.schema.check( schemaQuery ) ) {
  296. if ( consumable.consume( data.input, { name: true } ) ) {
  297. let node;
  298. if ( withAttributes ) {
  299. node = new ModelText( data.input.getChild( 0 ).data, data.input.getAttributes() );
  300. } else {
  301. node = new ModelText( data.input.data );
  302. }
  303. data.output = node;
  304. }
  305. }
  306. };
  307. }
  308. // -- converters model -> view -----------------------------------------------------
  309. function insertElement() {
  310. return ( evt, data, consumable, conversionApi ) => {
  311. consumable.consume( data.item, 'insert' );
  312. const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  313. const viewElement = new ViewElement( data.item.name, data.item.getAttributes() );
  314. conversionApi.mapper.bindElements( data.item, viewElement );
  315. viewWriter.insert( viewPosition, viewElement );
  316. };
  317. }
  318. function insertText() {
  319. return ( evt, data, consumable, conversionApi ) => {
  320. consumable.consume( data.item, 'insert' );
  321. const viewPosition = conversionApi.mapper.toViewPosition( data.range.start );
  322. const viewText = new ViewText( data.item.data );
  323. let node;
  324. if ( count( data.item.getAttributes() ) ) {
  325. node = new ViewElement( VIEW_TEXT_WITH_ATTRIBUTES_ELEMENT, data.item.getAttributes(), [ viewText ] );
  326. } else {
  327. node = viewText;
  328. }
  329. viewWriter.insert( viewPosition, node );
  330. evt.stop();
  331. };
  332. }