model.js 12 KB

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