model.js 11 KB

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