8
0

model.js 12 KB

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