view.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. /* jshint latedef:false */
  7. import ViewDocumentFragment from '/ckeditor5/engine/treeview/documentfragment.js';
  8. import HtmlDataProcessor from '/ckeditor5/engine/dataprocessor/htmldataprocessor.js';
  9. import ViewElement from '/ckeditor5/engine/treeview/element.js';
  10. import Selection from '/ckeditor5/engine/treeview/selection.js';
  11. import Range from '/ckeditor5/engine/treeview/range.js';
  12. import Position from '/ckeditor5/engine/treeview/position.js';
  13. import AttributeElement from '/ckeditor5/engine/treeview/attributeelement.js';
  14. import ContainerElement from '/ckeditor5/engine/treeview/containerelement.js';
  15. import ViewText from '/ckeditor5/engine/treeview/text.js';
  16. const DomDocumentFragment = window.DocumentFragment;
  17. const DomText = window.Text;
  18. const DomElement = window.Element;
  19. const ELEMENT_RANGE_START_TOKEN = '[';
  20. const ELEMENT_RANGE_END_TOKEN = ']';
  21. const TEXT_RANGE_START_TOKEN = '{';
  22. const TEXT_RANGE_END_TOKEN = '}';
  23. /**
  24. * Converts view elements to its string representation, an HTML-like string.
  25. * Root element can be provided as {@link engine.treeView.Element Element} or
  26. * {@link engine.treeView.DocumentFragment DocumentFragment}.
  27. *
  28. * const text = new Text( 'foobar' );
  29. * const b = new Element( 'b', { name: 'test' }, text );
  30. * const p = new Element( 'p', { style: 'color:red;' }, b );
  31. *
  32. * getData( p ); // <p style="color:red;"><b name="test">foobar</b></p>
  33. *
  34. * Additionally {@link engine.treeView.Selection Selection}
  35. * instance can be provided, then ranges from that selection will be converted too. If range position is placed inside
  36. * element node `[` and `]` will be used there.
  37. *
  38. * const text = new Text( 'foobar' );
  39. * const b = new Element( 'b', null, text );
  40. * const p = new Element( 'p', null, b );
  41. * const selection = new Selection();
  42. * selection.addRange( Range.createFromParentsAndOffsets( p, 0, p, 1 ) );
  43. *
  44. * getData( p, selection ); // <p>[<b>foobar</b>]</p>
  45. *
  46. * If range is placed inside text node `{` and `}` will be used there.
  47. *
  48. * const text = new Text( 'foobar' );
  49. * const b = new Element( 'b', null, text );
  50. * const p = new Element( 'p', null, b );
  51. * const selection = new Selection();
  52. * selection.addRange( Range.createFromParentsAndOffsets( text, 1, text, 5 ) );
  53. *
  54. * getData( p, selection ); // <p><b>f{ooba}r</b></p>
  55. *
  56. * Additional options object can be provided.
  57. * If `options.showType` property is set to `true` element types will be
  58. * presented for {@link engine.treeView.AttributeElement AttributeElements} and {@link engine.treeView.ContainerElement
  59. * ContainerElements}.
  60. *
  61. * const attribute = new AttributeElement( 'b' );
  62. * const container = new ContainerElement( 'p' );
  63. * getData( attribute, null, { showType: true } ); // <attribute:b></attribute:b>
  64. * getData( container, null, { showType: true } ); // <container:p></container:p>
  65. *
  66. * if `options.showPriority` property is set to `true`, priority will be displayed for all
  67. * {@link engine.treeView.AttributeElement AttributeElements}.
  68. *
  69. * const attribute = new AttributeElement( 'b' );
  70. * attribute.priority = 20;
  71. * getData( attribute, null, { showPriority: true } ); // <b priority=20></b>
  72. *
  73. * @param {engine.treeView.Node} node
  74. * @param {engine.treeView.Selection} [selection]
  75. * @param {Object} [options]
  76. * @param {Boolean} [options.showType=false] When set to `true` type of elements will be printed ( `<container:p>`
  77. * instead of `<p>` and `<attribute:b>` instead of `<b>`.
  78. * @param {Boolean} [options.showPriority=false] When set to `true` AttributeElement's priority will be printed.
  79. * @returns {String}
  80. */
  81. export function stringify( node, selection, options = {} ) {
  82. const viewStringify = new ViewStringify( node, selection, options );
  83. return viewStringify.stringify();
  84. }
  85. export function parse( data, options = { } ) {
  86. options.order = options.order || [];
  87. const viewParser = new ViewParser();
  88. const rangeParser = new RangeParser();
  89. const view = viewParser.parse( data );
  90. const ranges = rangeParser.parse( view, options.order );
  91. // When ranges are present - return object containing view, and selection.
  92. if ( ranges.length ) {
  93. const selection = new Selection();
  94. selection.setRanges( ranges, !!options.lastRangeBackward );
  95. return {
  96. view: view,
  97. selection: selection
  98. };
  99. }
  100. return view;
  101. }
  102. class RangeParser {
  103. constructor() {
  104. // Todo - set in parse method.
  105. this._positions = [];
  106. }
  107. parse( node, order ) {
  108. this._getPositions( node );
  109. let ranges = this._createRanges();
  110. // Sort ranges if needed.
  111. if ( order.length ) {
  112. if ( order.length != ranges.length ) {
  113. throw new Error( `There are ${ ranges.length} ranges found, but ranges order contain ${ order.length } elements.` );
  114. }
  115. ranges = this._sortRanges( ranges, order );
  116. }
  117. return ranges;
  118. }
  119. _sortRanges( ranges, rangesOrder ) {
  120. const sortedRanges = [];
  121. for ( let index in rangesOrder ) {
  122. if ( ranges[ index ] === undefined ) {
  123. throw new Error( 'Provided ranges order is invalid.' );
  124. }
  125. sortedRanges.push( ranges[ index ] );
  126. }
  127. return sortedRanges;
  128. }
  129. _getPositions( node ) {
  130. if ( node instanceof ViewDocumentFragment || node instanceof ViewElement ) {
  131. // Copy elements into the array, when items will be removed from node this array will still have all the
  132. // items needed for iteration.
  133. const children = Array.from( node.getChildren() );
  134. for ( let child of children ) {
  135. this._getPositions( child );
  136. }
  137. }
  138. if ( node instanceof ViewText ) {
  139. const regexp = new RegExp(
  140. `[ ${TEXT_RANGE_START_TOKEN}${TEXT_RANGE_END_TOKEN}\\${ELEMENT_RANGE_END_TOKEN}\\${ELEMENT_RANGE_START_TOKEN} ]`,
  141. 'g'
  142. );
  143. let text = node.data;
  144. let match;
  145. let offset = 0;
  146. const brackets = [];
  147. // Remove brackets from text and store info about offset inside text node.
  148. while ( ( match = regexp.exec( text ) ) ) {
  149. const index = match.index;
  150. const bracket = match[ 0 ];
  151. brackets.push( {
  152. bracket: bracket,
  153. textOffset: index - offset
  154. } );
  155. offset++;
  156. }
  157. text = text.replace( regexp, '' );
  158. node.data = text;
  159. const index = node.getIndex();
  160. const parent = node.parent;
  161. // Remove empty text nodes.
  162. if ( !text ) {
  163. node.remove();
  164. }
  165. for ( let item of brackets ) {
  166. // Non-empty text node.
  167. if ( text ) {
  168. if ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) {
  169. // Store information about text range delimiter.
  170. this._positions.push( {
  171. bracket: item.bracket,
  172. position: new Position( node, item.textOffset )
  173. } );
  174. } else {
  175. // Check if element range delimiter is not placed inside text node.
  176. if ( item.textOffset !== 0 && item.textOffset !== text.length ) {
  177. throw new Error( `Range delimiter '${ item.bracket }' is placed inside text node.` );
  178. }
  179. // If bracket is placed at the end of the text node - it should be positioned after it.
  180. const offset = ( item.textOffset === 0 ? index : index + 1 );
  181. // Store information about element range delimiter.
  182. this._positions.push( {
  183. bracket: item.bracket,
  184. position: new Position( parent, offset )
  185. } );
  186. }
  187. } else {
  188. if ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) {
  189. throw new Error( `Text range delimiter '${ item.bracket }' is placed inside empty text node. ` );
  190. }
  191. // Store information about element range delimiter.
  192. this._positions.push( {
  193. bracket: item.bracket,
  194. position: new Position( parent, index )
  195. } );
  196. }
  197. }
  198. }
  199. }
  200. _createRanges() {
  201. const ranges = [];
  202. let range = null;
  203. for ( let item of this._positions ) {
  204. // When end of range is found without opening.
  205. if ( !range && ( item.bracket == ELEMENT_RANGE_END_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) ) {
  206. throw new Error( `End of range was found '${ item.bracket }' but range was not started before.` );
  207. }
  208. // When second start of range is found when one is already opened - selection does not allow intersecting
  209. // ranges.
  210. if ( range && ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) ) {
  211. throw new Error( `Start of range was found '${ item.bracket }' but one range is already started.` );
  212. }
  213. if ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) {
  214. range = new Range( item.position, item.position );
  215. } else {
  216. range.end = item.position;
  217. ranges.push( range );
  218. range = null;
  219. }
  220. }
  221. // Check if all ranges have proper ending.
  222. if ( range !== null ) {
  223. throw new Error( 'Range was started but no end delimiter was found.' );
  224. }
  225. return ranges;
  226. }
  227. }
  228. class ViewParser {
  229. parse( data ) {
  230. const htmlProcessor = new HtmlDataProcessor();
  231. const domRoot = htmlProcessor.toDom( data );
  232. return this._walkDom( domRoot );
  233. }
  234. _walkDom( domNode ) {
  235. const isDomElement = domNode instanceof DomElement;
  236. if ( isDomElement || domNode instanceof DomDocumentFragment ) {
  237. const children = domNode.childNodes;
  238. const length = children.length;
  239. // If there is only one element inside DOM DocumentFragment - use it as root.
  240. if ( !isDomElement && length == 1 ) {
  241. return this._walkDom( domNode.childNodes[ 0 ] );
  242. }
  243. let viewElement;
  244. if ( isDomElement ) {
  245. viewElement = this._convertElement( domNode );
  246. } else {
  247. viewElement = new ViewDocumentFragment();
  248. }
  249. for ( let i = 0; i < children.length; i++ ) {
  250. const child = children[ i ];
  251. viewElement.appendChildren( this._walkDom( child ) );
  252. }
  253. return viewElement;
  254. }
  255. if ( domNode instanceof DomText ) {
  256. return new ViewText( domNode.textContent );
  257. }
  258. }
  259. _convertElement( domElement ) {
  260. const info = this._convertElementName( domElement );
  261. let viewElement;
  262. if ( info.type == 'attribute' ) {
  263. viewElement = new AttributeElement( info.name );
  264. if ( info.priority !== null ) {
  265. viewElement.priority = info.priority;
  266. }
  267. } else if ( info.type == 'container' ) {
  268. viewElement = new ContainerElement( info.name );
  269. } else {
  270. viewElement = new ViewElement( info.name );
  271. }
  272. const attributes = domElement.attributes;
  273. const attributesCount = attributes.length;
  274. for ( let i = 0; i < attributesCount; i++ ) {
  275. const attribute = attributes[ i ];
  276. viewElement.setAttribute( attribute.name, attribute.value );
  277. }
  278. return viewElement;
  279. }
  280. _convertElementName( element ) {
  281. const parts = element.tagName.toLowerCase().split( ':' );
  282. if ( parts.length == 1 ) {
  283. return {
  284. name: parts[ 0 ],
  285. type: null,
  286. priority: null
  287. };
  288. }
  289. if ( parts.length == 2 ) {
  290. // Check if type and name: container:div.
  291. const type = this._convertType( parts[ 0 ] );
  292. if ( type ) {
  293. return {
  294. name: parts[ 1 ],
  295. type: type,
  296. priority: null
  297. };
  298. }
  299. // Check if name and priority: span:10.
  300. const priority = this._convertPriority( parts[ 1 ] );
  301. if ( priority !== null ) {
  302. return {
  303. name: parts[ 0 ],
  304. type: 'attribute',
  305. priority: priority
  306. };
  307. }
  308. throw new Error( `Cannot parse element's tag name: ${ element.tagName.toLowerCase() }.` );
  309. }
  310. // Check if name is in format type:name:priority.
  311. if ( parts.length === 3 ) {
  312. const type = this._convertType( parts[ 0 ] );
  313. const priority = this._convertPriority( parts[ 2 ] );
  314. if ( type && priority !== null ) {
  315. return {
  316. name: parts[ 1 ],
  317. type: type,
  318. priority: priority
  319. };
  320. }
  321. }
  322. throw new Error( `Cannot parse element's tag name: ${ element.tagName.toLowerCase() }.` );
  323. }
  324. _convertType( type ) {
  325. if ( type == 'container' || type == 'attribute' ) {
  326. return type;
  327. }
  328. return null;
  329. }
  330. _convertPriority( priorityString ) {
  331. const priority = parseInt( priorityString, 10 );
  332. if ( !isNaN( priority ) ) {
  333. return priority;
  334. }
  335. return null;
  336. }
  337. }
  338. /**
  339. * Private helper class used for converting view tree to string.
  340. *
  341. * @private
  342. */
  343. class ViewStringify {
  344. /**
  345. * Creates ViewStringify instance.
  346. * @param root
  347. * @param {engine.treeView.Selection} [selection=null] Selection which ranges should be also converted to string.
  348. * @param {Object} [options] Options object.
  349. * @param {Boolean} [options.showType=false] When set to `true` type of elements will be printed ( `<container:p>`
  350. * instead of `<p>` and `<attribute:b>` instead of `<b>`.
  351. * @param {Boolean} [options.showPriority=false] When set to `true` AttributeElement's priority will be printed.
  352. */
  353. constructor( root, selection = null, options = {} ) {
  354. this.root = root;
  355. this.selection = selection;
  356. this.ranges = [];
  357. if ( this.selection ) {
  358. this.ranges = [ ...selection.getRanges() ];
  359. }
  360. this.showType = !!options.showType;
  361. this.showPriority = !!options.showPriority;
  362. }
  363. /**
  364. * Converts view to string.
  365. *
  366. * @returns {string} String representation of the view elements.
  367. */
  368. stringify() {
  369. let result = '';
  370. this._walkView( this.root, ( chunk ) => {
  371. result += chunk;
  372. } );
  373. return result;
  374. }
  375. /**
  376. * Executes simple walker that iterates over all elements in the view tree starting from root element.
  377. * Calls `callback` with parsed chunks of string data.
  378. *
  379. * @private
  380. * @param {engine.treeView.DocumentFragment|engine.treeView.Element|engine.treeView.Text} root
  381. * @param {Function} callback
  382. */
  383. _walkView( root, callback ) {
  384. const isElement = root instanceof ViewElement;
  385. if ( isElement || root instanceof ViewDocumentFragment ) {
  386. if ( isElement ) {
  387. callback( this._stringifyElementOpen( root ) );
  388. }
  389. let offset = 0;
  390. callback( this._stringifyElementRanges( root, offset ) );
  391. for ( let child of root.getChildren() ) {
  392. this._walkView( child, callback );
  393. offset++;
  394. callback( this._stringifyElementRanges( root, offset ) );
  395. }
  396. if ( isElement ) {
  397. callback( this._stringifyElementClose( root ) );
  398. }
  399. }
  400. if ( root instanceof ViewText ) {
  401. callback( this._stringifyTextRanges( root ) );
  402. }
  403. }
  404. /**
  405. * Checks if given {@link engine.treeView.Element Element} has {@link engine.treeView.Range#start range start} or
  406. * {@link engine.treeView.Range#start range end} placed at given offset and returns its string representation.
  407. *
  408. * @private
  409. * @param {engine.treeView.Element} element
  410. * @param {Number} offset
  411. */
  412. _stringifyElementRanges( element, offset ) {
  413. let start = '';
  414. let end = '';
  415. let collapsed = '';
  416. for ( let range of this.ranges ) {
  417. if ( range.start.parent == element && range.start.offset === offset ) {
  418. if ( range.isCollapsed ) {
  419. collapsed += ELEMENT_RANGE_START_TOKEN + ELEMENT_RANGE_END_TOKEN;
  420. } else {
  421. start += ELEMENT_RANGE_START_TOKEN;
  422. }
  423. }
  424. if ( range.end.parent === element && range.end.offset === offset && !range.isCollapsed ) {
  425. end += ELEMENT_RANGE_END_TOKEN;
  426. }
  427. }
  428. return end + collapsed + start;
  429. }
  430. /**
  431. * Checks if given {@link engine.treeView.Element Text node} has {@link engine.treeView.Range#start range start} or
  432. * {@link engine.treeView.Range#start range end} placed somewhere inside. Returns string representation of text
  433. * with range delimiters placed inside.
  434. *
  435. * @private
  436. * @param {engine.treeView.Text} node
  437. */
  438. _stringifyTextRanges( node ) {
  439. const length = node.data.length;
  440. let result = node.data.split( '' );
  441. // Add one more element for ranges ending after last character in text.
  442. result[ length ] = '';
  443. // Represent each letter as object with information about opening/closing ranges at each offset.
  444. result = result.map( ( letter ) => {
  445. return {
  446. letter: letter,
  447. start: '',
  448. end: '',
  449. collapsed: ''
  450. };
  451. } );
  452. for ( let range of this.ranges ) {
  453. const start = range.start;
  454. const end = range.end;
  455. if ( start.parent == node && start.offset >= 0 && start.offset <= length ) {
  456. if ( range.isCollapsed ) {
  457. result[ end.offset ].collapsed += TEXT_RANGE_START_TOKEN + TEXT_RANGE_END_TOKEN;
  458. } else {
  459. result[ start.offset ].start += TEXT_RANGE_START_TOKEN;
  460. }
  461. }
  462. if ( end.parent == node && end.offset >= 0 && end.offset <= length && !range.isCollapsed ) {
  463. result[ end.offset ].end += TEXT_RANGE_END_TOKEN;
  464. }
  465. }
  466. return result.map( item => item.end + item.collapsed + item.start + item.letter ).join( '' );
  467. }
  468. /**
  469. * Converts passed {@link engine.treeView.Element Element} to opening tag.
  470. * Depending on current configuration opening tag can be simple (`<a>`), contain type prefix (`<container:p>` or
  471. * `<attribute:a>`), contain priority information ( `<attribute:a priority=20>` ). Element's attributes also
  472. * will be included (`<a href="http://ckeditor.com" name="foobar">`).
  473. *
  474. * @private
  475. * @param {engine.treeView.Element} element
  476. * @returns {string}
  477. */
  478. _stringifyElementOpen( element ) {
  479. const priority = this._stringifyElementPriority( element );
  480. const type = this._stringifyElementType( element );
  481. const name = [ type, element.name, priority ].filter( i=> i !== '' ).join( ':' );
  482. const attributes = this._stringifyElementAttributes( element );
  483. const parts = [ name, attributes ];
  484. return `<${ parts.filter( i => i !== '' ).join( ' ' ) }>`;
  485. }
  486. /**
  487. * Converts passed {@link engine.treeView.Element Element} to closing tag.
  488. * Depending on current configuration opening tag can be simple (`</a>`) or contain type prefix (`</container:p>` or
  489. * `</attribute:a>`).
  490. *
  491. * @private
  492. * @param {engine.treeView.Element} element
  493. * @returns {string}
  494. */
  495. _stringifyElementClose( element ) {
  496. const priority = this._stringifyElementPriority( element );
  497. const type = this._stringifyElementType( element );
  498. const name = [ type, element.name, priority ].filter( i=> i !== '' ).join( ':' );
  499. return `</${ name }>`;
  500. }
  501. /**
  502. * Converts passed {@link engine.treeView.Element Element's} type to its string representation
  503. * Returns 'attribute' for {@link engine.treeView.AttributeElement AttributeElements} and
  504. * 'container' for {@link engine.treeView.ContainerElement ContainerElements}. Returns empty string when current
  505. * configuration is preventing showing elements' types.
  506. *
  507. * @private
  508. * @param {engine.treeView.Element} element
  509. * @returns {string}
  510. */
  511. _stringifyElementType( element ) {
  512. if ( this.showType ) {
  513. if ( element instanceof AttributeElement ) {
  514. return 'attribute';
  515. }
  516. if ( element instanceof ContainerElement ) {
  517. return 'container';
  518. }
  519. }
  520. return '';
  521. }
  522. /**
  523. * Converts passed {@link engine.treeView.Element Element} to its priority representation.
  524. * Priority string representation will be returned when passed element is an instance of
  525. * {@link engine.treeView.AttributeElement AttributeElement} and current configuration allow to show priority.
  526. * Otherwise returns empty string.
  527. *
  528. * @private
  529. * @param {engine.treeView.Element} element
  530. * @returns {string}
  531. */
  532. _stringifyElementPriority( element ) {
  533. if ( this.showPriority && element instanceof AttributeElement ) {
  534. return element.priority;
  535. }
  536. return '';
  537. }
  538. /**
  539. * Converts passed {@link engine.treeView.Element Element} attributes to their string representation.
  540. * If element has no attributes - empty string is returned.
  541. *
  542. * @private
  543. * @param {engine.treeView.Element} element
  544. * @returns {string}
  545. */
  546. _stringifyElementAttributes( element ) {
  547. const attributes = [];
  548. // TODO: Maybe attributes should be put in alphabetical order, it might be easier to write expected string.
  549. for ( let attribute of element.getAttributeKeys() ) {
  550. attributes.push( `${ attribute }="${ element.getAttribute( attribute ) }"` );
  551. }
  552. return attributes.join( ' ' );
  553. }
  554. }