model.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import TreeWalker from '/ckeditor5/engine/model/treewalker.js';
  7. import Range from '/ckeditor5/engine/model/range.js';
  8. import Position from '/ckeditor5/engine/model/position.js';
  9. import Text from '/ckeditor5/engine/model/text.js';
  10. import RootElement from '/ckeditor5/engine/model/rootelement.js';
  11. import Element from '/ckeditor5/engine/model/element.js';
  12. import DocumentFragment from '/ckeditor5/engine/model/documentfragment.js';
  13. import Selection from '/ckeditor5/engine/model/selection.js';
  14. import Document from '/ckeditor5/engine/model/document.js';
  15. /**
  16. * Writes the contents of the {@link engine.model.Document Document} to an HTML-like string.
  17. *
  18. * @param {engine.model.Document} document
  19. * @param {Object} [options]
  20. * @param {Boolean} [options.withoutSelection=false] Whether to write the selection. When set to `true` selection will
  21. * be not included in returned string.
  22. * @param {Boolean} [options.rootName='main'] Name of the root from which data should be stringified. If not provided
  23. * default `main` name will be used.
  24. * @returns {String} The stringified data.
  25. */
  26. export function getData( document, options = {} ) {
  27. const withoutSelection = !!options.withoutSelection;
  28. const rootName = options.rootName || 'main';
  29. const root = document.getRoot( rootName );
  30. return withoutSelection ? getData._stringify( root ) : getData._stringify( root, document.selection );
  31. }
  32. // Set stringify as getData private method - needed for testing/spying.
  33. getData._stringify = stringify;
  34. /**
  35. * Sets the contents of the {@link engine.model.Document Document} provided as HTML-like string.
  36. *
  37. * @param {engine.model.Document} document
  38. * @param {String} data HTML-like string to write into Document.
  39. * @param {Object} options
  40. * @param {String} [options.rootName] Root name where parsed data will be stored. If not provided, default `main` name will be
  41. * used.
  42. */
  43. export function setData( document, data, options = {} ) {
  44. setData._parse( data, {
  45. document: document,
  46. rootName: options.rootName
  47. } );
  48. }
  49. // Set parse as setData private method - needed for testing/spying.
  50. setData._parse = parse;
  51. /**
  52. * Converts model nodes to HTML-like string representation.
  53. *
  54. * @param {engine.model.RootElement|engine.model.Element|engine.model.Text|
  55. * engine.model.DocumentFragment} node Node to stringify.
  56. * @param {engine.model.Selection|engine.model.Position|engine.model.Range} [selectionOrPositionOrRange = null ]
  57. * Selection instance which ranges will be included in returned string data. If Range instance is provided - it will be
  58. * converted to selection containing this range. If Position instance is provided - it will be converted to selection
  59. * containing one range collapsed at this position.
  60. * @returns {String} HTML-like string representing the model.
  61. */
  62. export function stringify( node, selectionOrPositionOrRange = null ) {
  63. let selection;
  64. let document;
  65. if ( node instanceof RootElement ) {
  66. document = node.document;
  67. } else if ( node instanceof Element || node instanceof Text ) {
  68. // If root is Element or Text - wrap it with DocumentFragment.
  69. node = new DocumentFragment( node );
  70. }
  71. document = document || new Document();
  72. const walker = new TreeWalker( {
  73. boundaries: Range.createFromElement( node )
  74. } );
  75. if ( selectionOrPositionOrRange instanceof Selection ) {
  76. selection = selectionOrPositionOrRange;
  77. } else if ( selectionOrPositionOrRange instanceof Range ) {
  78. selection = document.selection;
  79. selection.addRange( selectionOrPositionOrRange );
  80. } else if ( selectionOrPositionOrRange instanceof Position ) {
  81. selection = document.selection;
  82. selection.addRange( new Range( selectionOrPositionOrRange, selectionOrPositionOrRange ) );
  83. }
  84. let ret = '';
  85. let lastPosition = Position.createFromParentAndOffset( node, 0 );
  86. const withSelection = !!selection;
  87. for ( let value of walker ) {
  88. if ( withSelection ) {
  89. ret += writeSelection( value.previousPosition, selection );
  90. }
  91. ret += writeItem( value, selection, { selection: withSelection } );
  92. lastPosition = value.nextPosition;
  93. }
  94. if ( withSelection ) {
  95. ret += writeSelection( lastPosition, selection );
  96. }
  97. return ret;
  98. }
  99. /**
  100. * Parses HTML-like string and returns model {@link engine.model.RootElement rootElement}.
  101. *
  102. * @param {String} data HTML-like string to be parsed.
  103. * @param {Object} options
  104. * @param {engine.model.Document} [options.document] Document from which root element and selection will be used. If
  105. * not provided new {engine.model.Document document} instance will be created.
  106. * @param {String} [options.rootName='main'] When `document` option is provided this root name will be used to create
  107. * {engine.model.RootElement RootElement} instance.
  108. * @returns {engine.model.RootElement|Object} Returns parsed RootElement or object with two fields `model`
  109. * and `selection` when selection ranges were included in data to parse.
  110. */
  111. export function parse( data, options = {} ) {
  112. let document, root;
  113. let withSelection = false;
  114. const rootName = options.rootName || 'main';
  115. if ( options.document ) {
  116. document = options.document;
  117. root = document.getRoot( rootName );
  118. root.removeChildren( 0, root.getChildCount() );
  119. } else {
  120. document = new Document();
  121. root = document.createRoot( rootName );
  122. }
  123. const path = [];
  124. let selectionStart, selectionEnd, selectionAttributes, textAttributes;
  125. const handlers = {
  126. text( token ) {
  127. root.appendChildren( new Text( token.text, textAttributes ) );
  128. },
  129. textStart( token ) {
  130. textAttributes = token.attributes;
  131. path.push( '$text' );
  132. },
  133. textEnd() {
  134. if ( path.pop() != '$text' ) {
  135. throw new Error( 'Parse error - unexpected closing tag.' );
  136. }
  137. textAttributes = null;
  138. },
  139. openingTag( token ) {
  140. let el = new Element( token.name, token.attributes );
  141. root.appendChildren( el );
  142. root = el;
  143. path.push( token.name );
  144. },
  145. closingTag( token ) {
  146. if ( path.pop() != token.name ) {
  147. throw new Error( 'Parse error - unexpected closing tag.' );
  148. }
  149. root = root.parent;
  150. },
  151. collapsedSelection( token ) {
  152. withSelection = true;
  153. document.selection.collapse( root, 'END' );
  154. document.selection.setAttributesTo( token.attributes );
  155. },
  156. selectionStart( token ) {
  157. selectionStart = Position.createFromParentAndOffset( root, root.getChildCount() );
  158. selectionAttributes = token.attributes;
  159. },
  160. selectionEnd() {
  161. if ( !selectionStart ) {
  162. throw new Error( 'Parse error - missing selection start.' );
  163. }
  164. withSelection = true;
  165. selectionEnd = Position.createFromParentAndOffset( root, root.getChildCount() );
  166. document.selection.setRanges(
  167. [ new Range( selectionStart, selectionEnd ) ],
  168. selectionAttributes.backward
  169. );
  170. delete selectionAttributes.backward;
  171. document.selection.setAttributesTo( selectionAttributes );
  172. }
  173. };
  174. for ( let token of tokenize( data ) ) {
  175. handlers[ token.type ]( token );
  176. }
  177. if ( path.length ) {
  178. throw new Error( 'Parse error - missing closing tags: ' + path.join( ', ' ) + '.' );
  179. }
  180. if ( selectionStart && !selectionEnd ) {
  181. throw new Error( 'Parse error - missing selection end.' );
  182. }
  183. if ( withSelection ) {
  184. return {
  185. model: root,
  186. selection: document.selection
  187. };
  188. }
  189. return root;
  190. }
  191. // -- getData helpers ---------------------------------------------------------
  192. function writeItem( walkerValue, selection, options ) {
  193. const type = walkerValue.type;
  194. const item = walkerValue.item;
  195. if ( type == 'ELEMENT_START' ) {
  196. let attrs = writeAttributes( item.getAttributes() );
  197. if ( attrs ) {
  198. return `<${ item.name } ${ attrs }>`;
  199. }
  200. return `<${ item.name }>`;
  201. }
  202. if ( type == 'ELEMENT_END' ) {
  203. return `</${ item.name }>`;
  204. }
  205. return writeText( walkerValue, selection, options );
  206. }
  207. function writeText( walkerValue, selection, options ) {
  208. const item = walkerValue.item;
  209. const attrs = writeAttributes( item.getAttributes() );
  210. let text = Array.from( item.text );
  211. if ( options.selection ) {
  212. const startIndex = walkerValue.previousPosition.offset + 1;
  213. const endIndex = walkerValue.nextPosition.offset - 1;
  214. let index = startIndex;
  215. while ( index <= endIndex ) {
  216. // Add the selection marker without changing any indexes, so if second marker must be added
  217. // in the same loop it does not blow up.
  218. text[ index - startIndex ] +=
  219. writeSelection( Position.createFromParentAndOffset( item.commonParent, index ), selection );
  220. index++;
  221. }
  222. }
  223. text = text.join( '' );
  224. if ( attrs ) {
  225. return `<$text ${ attrs }>${ text }</$text>`;
  226. }
  227. return text;
  228. }
  229. function writeAttributes( attrs ) {
  230. attrs = Array.from( attrs );
  231. return attrs.map( attr => attr[ 0 ] + '=' + JSON.stringify( attr[ 1 ] ) ).sort().join( ' ' );
  232. }
  233. function writeSelection( currentPosition, selection ) {
  234. // TODO: This function obviously handles only the first range.
  235. const range = selection.getFirstRange();
  236. // Handle end of the selection.
  237. if ( !selection.isCollapsed && range.end.compareWith( currentPosition ) == 'SAME' ) {
  238. return '</selection>';
  239. }
  240. // Handle no match.
  241. if ( range.start.compareWith( currentPosition ) != 'SAME' ) {
  242. return '';
  243. }
  244. // Handle beginning of the selection.
  245. let ret = '<selection';
  246. const attrs = writeAttributes( selection.getAttributes() );
  247. // TODO: Once we'll support multiple ranges this will need to check which range it is.
  248. if ( selection.isBackward ) {
  249. ret += ' backward';
  250. }
  251. if ( attrs ) {
  252. ret += ' ' + attrs;
  253. }
  254. ret += ( selection.isCollapsed ? ' />' : '>' );
  255. return ret;
  256. }
  257. // -- setData helpers ---------------------------------------------------------
  258. const patterns = {
  259. selection: /^<(\/?selection)( [^>]*)?>/,
  260. tag: /^<([^>]+)>/,
  261. text: /^[^<]+/
  262. };
  263. const handlers = {
  264. selection( match ) {
  265. const tagName = match[ 1 ];
  266. const tagExtension = match[ 2 ] || '';
  267. if ( tagName[ 0 ] == '/' ) {
  268. return {
  269. type: 'selectionEnd'
  270. };
  271. }
  272. if ( tagExtension.endsWith( ' /' ) ) {
  273. return {
  274. type: 'collapsedSelection',
  275. attributes: parseAttributes( tagExtension.slice( 1, -2 ) )
  276. };
  277. }
  278. return {
  279. type: 'selectionStart',
  280. attributes: parseAttributes( tagExtension.slice( 1 ) )
  281. };
  282. },
  283. tag( match ) {
  284. const tagContents = match[ 1 ].split( /\s+/ );
  285. const tagName = tagContents.shift();
  286. const attrs = tagContents.join( ' ' );
  287. if ( tagName == '/$text' ) {
  288. return {
  289. type: 'textEnd'
  290. };
  291. }
  292. if ( tagName == '$text' ) {
  293. return {
  294. type: 'textStart',
  295. attributes: parseAttributes( attrs )
  296. };
  297. }
  298. if ( tagName[ 0 ] == '/' ) {
  299. return {
  300. type: 'closingTag',
  301. name: tagName.slice( 1 )
  302. };
  303. }
  304. return {
  305. type: 'openingTag',
  306. name: tagName,
  307. attributes: parseAttributes( attrs )
  308. };
  309. },
  310. text( match ) {
  311. return {
  312. type: 'text',
  313. text: match[ 0 ]
  314. };
  315. }
  316. };
  317. function *tokenize( data ) {
  318. while ( data ) {
  319. const consumed = consumeNextToken( data );
  320. data = consumed.data;
  321. yield consumed.token;
  322. }
  323. }
  324. function consumeNextToken( data ) {
  325. let match;
  326. for ( let patternName in patterns ) {
  327. match = data.match( patterns[ patternName ] );
  328. if ( match ) {
  329. data = data.slice( match[ 0 ].length );
  330. return {
  331. token: handlers[ patternName ]( match ),
  332. data
  333. };
  334. }
  335. }
  336. throw new Error( 'Parse error - unexpected token: ' + data + '.' );
  337. }
  338. function parseAttributes( attrsString ) {
  339. attrsString = attrsString.trim();
  340. if ( !attrsString ) {
  341. return {};
  342. }
  343. const pattern = /(?:backward|(\w+)=("[^"]+"|[^\s]+))\s*/;
  344. const attrs = {};
  345. while ( attrsString ) {
  346. let match = attrsString.match( pattern );
  347. if ( !match ) {
  348. throw new Error( 'Parse error - unexpected token: ' + attrsString + '.' );
  349. }
  350. if ( match[ 0 ].trim() == 'backward' ) {
  351. attrs.backward = true;
  352. } else {
  353. attrs[ match[ 1 ] ] = JSON.parse( match[ 2 ] );
  354. }
  355. attrsString = attrsString.slice( match[ 0 ].length );
  356. }
  357. return attrs;
  358. }