model.js 12 KB

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