model.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /**
  2. * @license Copyright (c) 2003-20'INSERT'6, 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 Element from '/ckeditor5/engine/treemodel/element.js';
  11. /**
  12. * Writes the contents of the document to an HTML-like string.
  13. *
  14. * @param {engine.treeModel.Document} document
  15. * @param {String} rootName
  16. * @param {Object} [options]
  17. * @param {Boolean} [options.selection] Whether to write the selection.
  18. */
  19. export function getData( document, rootName, options ) {
  20. const walker = new TreeWalker( {
  21. boundaries: Range.createFromElement( document.getRoot( rootName ) )
  22. } );
  23. let ret = '';
  24. let lastPosition;
  25. const selection = document.selection;
  26. options = options || {};
  27. for ( let value of walker ) {
  28. if ( options.selection ) {
  29. ret += writeSelection( value.previousPosition, selection );
  30. }
  31. ret += writeItem( value, selection, options );
  32. lastPosition = value.nextPosition;
  33. }
  34. if ( options.selection ) {
  35. ret += writeSelection( lastPosition, selection );
  36. }
  37. return ret;
  38. }
  39. export function setData( document, rootName, data ) {
  40. let appendTo = document.getRoot( rootName );
  41. const path = [];
  42. for ( let token of tokenize( data ) ) {
  43. if ( token.type == 'text' ) {
  44. appendTo.appendChildren( new Text( token.text, token.attributes ) );
  45. } else if ( token.type == 'openingTag' ) {
  46. let el = new Element( token.name, token.attributes );
  47. appendTo.appendChildren( el );
  48. appendTo = el;
  49. path.push( token.name );
  50. } else {
  51. if ( path.pop() != token.name ) {
  52. throw new Error( 'Parse error - unexpected closing tag.' );
  53. }
  54. appendTo = appendTo.parent;
  55. }
  56. }
  57. if ( path.length ) {
  58. throw new Error( 'Parse error - missing closing tags: ' + path.join( ', ' ) + '.' );
  59. }
  60. }
  61. // -- getData helpers ---------------------------------------------------------
  62. function writeItem( walkerValue, selection, options ) {
  63. const type = walkerValue.type;
  64. const item = walkerValue.item;
  65. if ( type == 'ELEMENT_START' ) {
  66. let attrs = writeAttributes( item.getAttributes() );
  67. if ( attrs ) {
  68. return `<${ item.name } ${ attrs }>`;
  69. }
  70. return `<${ item.name }>`;
  71. }
  72. if ( type == 'ELEMENT_END' ) {
  73. return `</${ item.name }>`;
  74. }
  75. return writeText( walkerValue, selection, options );
  76. }
  77. function writeText( walkerValue, selection, options ) {
  78. const item = walkerValue.item;
  79. const attrs = writeAttributes( item.getAttributes() );
  80. let text = Array.from( item.text );
  81. if ( options.selection ) {
  82. const startIndex = walkerValue.previousPosition.offset + 1;
  83. const endIndex = walkerValue.nextPosition.offset - 1;
  84. let index = startIndex;
  85. while ( index <= endIndex ) {
  86. // Add the selection marker without changing any indexes, so if second marker must be added
  87. // in the same loop it does not blow up.
  88. text[ index - startIndex ] +=
  89. writeSelection( Position.createFromParentAndOffset( item.commonParent, index ), selection );
  90. index++;
  91. }
  92. }
  93. text = text.join( '' );
  94. if ( attrs ) {
  95. return `<$text ${ attrs }>${ text }</$text>`;
  96. }
  97. return text;
  98. }
  99. function writeAttributes( attrs ) {
  100. attrs = Array.from( attrs );
  101. return attrs.map( attr => attr[ 0 ] + '=' + JSON.stringify( attr[ 1 ] ) ).sort().join( ' ' );
  102. }
  103. function writeSelection( currentPosition, selection ) {
  104. // TODO: This function obviously handles only the first range.
  105. const range = selection.getFirstRange();
  106. // Handle end of the selection.
  107. if ( !selection.isCollapsed && range.end.compareWith( currentPosition ) == 'SAME' ) {
  108. return '</selection>';
  109. }
  110. // Handle no match.
  111. if ( range.start.compareWith( currentPosition ) != 'SAME' ) {
  112. return '';
  113. }
  114. // Handle beginning of the selection.
  115. let ret = '<selection';
  116. const attrs = writeAttributes( selection.getAttributes() );
  117. // TODO: Once we'll support multiple ranges this will need to check which range it is.
  118. if ( selection.isBackward ) {
  119. ret += ' backward';
  120. }
  121. if ( attrs ) {
  122. ret += ' ' + attrs;
  123. }
  124. ret += ( selection.isCollapsed ? ' />' : '>' );
  125. return ret;
  126. }
  127. // -- setData helpers ---------------------------------------------------------
  128. const patterns = {
  129. textTag: /^<\$text ([^>]+)>([\s\S]+?)<\/\$text>/,
  130. tag: /^<([^>]+)>/,
  131. text: /^[^<]+/
  132. };
  133. const handlers = {
  134. textTag( match ) {
  135. return {
  136. type: 'text',
  137. attributes: parseAttributes( match[ 1 ] ),
  138. text: match[ 2 ]
  139. };
  140. },
  141. tag( match ) {
  142. const tagContents = match[ 1 ].split( /\s+/ );
  143. const tagName = tagContents.shift();
  144. const attrs = tagContents.join( ' ' );
  145. if ( tagName[ 0 ] == '/' ) {
  146. return {
  147. type: 'closingTag',
  148. name: tagName.slice( 1 )
  149. };
  150. }
  151. return {
  152. type: 'openingTag',
  153. name: tagName,
  154. attributes: parseAttributes( attrs )
  155. };
  156. },
  157. text( match ) {
  158. return {
  159. type: 'text',
  160. text: match[ 0 ]
  161. };
  162. }
  163. };
  164. function *tokenize( data ) {
  165. while ( data ) {
  166. const consumed = consumeNextToken( data );
  167. data = consumed.data;
  168. yield consumed.token;
  169. }
  170. }
  171. function consumeNextToken( data ) {
  172. let match;
  173. for ( let patternName in patterns ) {
  174. match = data.match( patterns[ patternName ] );
  175. if ( match ) {
  176. data = data.slice( match[ 0 ].length );
  177. return {
  178. token: handlers[ patternName ]( match ),
  179. data
  180. };
  181. }
  182. }
  183. throw new Error( 'Parse error - unpexpected token: ' + data + '.' );
  184. }
  185. function parseAttributes( attrsString ) {
  186. if ( !attrsString ) {
  187. return {};
  188. }
  189. const pattern = /(\w+)=("[^"]+"|[^\s]+)\s*/;
  190. const attrs = {};
  191. while ( attrsString ) {
  192. let match = attrsString.match( pattern );
  193. if ( !match ) {
  194. throw new Error( 'Parse error - unexpected token: ' + attrsString + '.' );
  195. }
  196. attrs[ match[ 1 ] ] = JSON.parse( match[ 2 ] );
  197. attrsString = attrsString.slice( match[ 0 ].length );
  198. }
  199. return attrs;
  200. }