modifyselection.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/utils/modifyselection
  7. */
  8. import Position from '../position';
  9. import TreeWalker from '../treewalker';
  10. import Range from '../range';
  11. import { isInsideSurrogatePair, isInsideCombinedSymbol } from '@ckeditor/ckeditor5-utils/src/unicode';
  12. import DocumentSelection from '../documentselection';
  13. const wordBoundaryCharacters = ' ,.?!:;"-()';
  14. /**
  15. * Modifies the selection. Currently, the supported modifications are:
  16. *
  17. * * Extending. The selection focus is moved in the specified `options.direction` with a step specified in `options.unit`.
  18. * Possible values for `unit` are:
  19. * * `'character'` (default) - moves selection by one user-perceived character. In most cases this means moving by one
  20. * character in `String` sense. However, unicode also defines "combing marks". These are special symbols, that combines
  21. * with a symbol before it ("base character") to create one user-perceived character. For example, `q̣̇` is a normal
  22. * letter `q` with two "combining marks": upper dot (`Ux0307`) and lower dot (`Ux0323`). For most actions, i.e. extending
  23. * selection by one position, it is correct to include both "base character" and all of it's "combining marks". That is
  24. * why `'character'` value is most natural and common method of modifying selection.
  25. * * `'codePoint'` - moves selection by one unicode code point. In contrary to, `'character'` unit, this will insert
  26. * selection between "base character" and "combining mark", because "combining marks" have their own unicode code points.
  27. * However, for technical reasons, unicode code points with values above `UxFFFF` are represented in native `String` by
  28. * two characters, called "surrogate pairs". Halves of "surrogate pairs" have a meaning only when placed next to each other.
  29. * For example `𨭎` is represented in `String` by `\uD862\uDF4E`. Both `\uD862` and `\uDF4E` do not have any meaning
  30. * outside the pair (are rendered as ? when alone). Position between them would be incorrect. In this case, selection
  31. * extension will include whole "surrogate pair".
  32. * * `'word'` - moves selection by a whole word.
  33. *
  34. * **Note:** if you extend a forward selection in a backward direction you will in fact shrink it.
  35. *
  36. * @param {module:engine/model/model~Model} model The model in context of which
  37. * the selection modification should be performed.
  38. * @param {module:engine/model/selection~Selection} selection The selection to modify.
  39. * @param {Object} [options]
  40. * @param {'forward'|'backward'} [options.direction='forward'] The direction in which the selection should be modified.
  41. * @param {'character'|'codePoint'|'word'} [options.unit='character'] The unit by which selection should be modified.
  42. */
  43. export default function modifySelection( model, selection, options = {} ) {
  44. const schema = model.schema;
  45. const isForward = options.direction != 'backward';
  46. const unit = options.unit ? options.unit : 'character';
  47. const focus = selection.focus;
  48. const walker = new TreeWalker( {
  49. boundaries: getSearchRange( focus, isForward ),
  50. singleCharacters: true,
  51. direction: isForward ? 'forward' : 'backward'
  52. } );
  53. const data = { walker, schema, isForward, unit };
  54. let next;
  55. while ( ( next = walker.next() ) ) {
  56. if ( next.done ) {
  57. return;
  58. }
  59. const position = tryExtendingTo( data, next.value );
  60. if ( position ) {
  61. if ( selection instanceof DocumentSelection ) {
  62. model.change( writer => {
  63. writer.setSelectionFocus( position );
  64. } );
  65. } else {
  66. selection.setFocus( position );
  67. }
  68. return;
  69. }
  70. }
  71. }
  72. // Checks whether the selection can be extended to the the walker's next value (next position).
  73. // @param {{ walker, unit, isForward, schema }} data
  74. // @param {module:engine/view/treewalker~TreeWalkerValue} value
  75. function tryExtendingTo( data, value ) {
  76. // If found text, we can certainly put the focus in it. Let's just find a correct position
  77. // based on the unit.
  78. if ( value.type == 'text' ) {
  79. if ( data.unit === 'word' ) {
  80. return getCorrectWordBreakPosition( data.walker, data.isForward );
  81. }
  82. return getCorrectPosition( data.walker, data.unit, data.isForward );
  83. }
  84. // Entering an element.
  85. if ( value.type == ( data.isForward ? 'elementStart' : 'elementEnd' ) ) {
  86. // If it's an object, we can select it now.
  87. if ( data.schema.isObject( value.item ) ) {
  88. return Position.createAt( value.item, data.isForward ? 'after' : 'before' );
  89. }
  90. // If text allowed on this position, extend to this place.
  91. if ( data.schema.checkChild( value.nextPosition, '$text' ) ) {
  92. return value.nextPosition;
  93. }
  94. }
  95. // Leaving an element.
  96. else {
  97. // If leaving a limit element, stop.
  98. if ( data.schema.isLimit( value.item ) ) {
  99. // NOTE: Fast-forward the walker until the end.
  100. data.walker.skip( () => true );
  101. return;
  102. }
  103. // If text allowed on this position, extend to this place.
  104. if ( data.schema.checkChild( value.nextPosition, '$text' ) ) {
  105. return value.nextPosition;
  106. }
  107. }
  108. }
  109. // Finds a correct position by walking in a text node and checking whether selection can be extended to given position
  110. // or should be extended further.
  111. //
  112. // @param {module:engine/model/treewalker~TreeWalker} walker
  113. // @param {String} unit The unit by which selection should be modified.
  114. function getCorrectPosition( walker, unit ) {
  115. const textNode = walker.position.textNode;
  116. if ( textNode ) {
  117. const data = textNode.data;
  118. let offset = walker.position.offset - textNode.startOffset;
  119. while ( isInsideSurrogatePair( data, offset ) || ( unit == 'character' && isInsideCombinedSymbol( data, offset ) ) ) {
  120. walker.next();
  121. offset = walker.position.offset - textNode.startOffset;
  122. }
  123. }
  124. return walker.position;
  125. }
  126. // Finds a correct position of a word break by walking in a text node and checking whether selection can be extended to given position
  127. // or should be extended further.
  128. //
  129. // @param {module:engine/model/treewalker~TreeWalker} walker
  130. // @param {Boolean} isForward Is the direction in which the selection should be modified is forward.
  131. function getCorrectWordBreakPosition( walker, isForward ) {
  132. let textNode = walker.position.textNode;
  133. if ( textNode ) {
  134. let offset = walker.position.offset - textNode.startOffset;
  135. while ( !isAtWordBoundary( textNode.data, offset, isForward ) && !isAtNodeBoundary( textNode, offset, isForward ) ) {
  136. walker.next();
  137. // Check of adjacent text nodes with different attributes (like BOLD).
  138. // Example : 'foofoo []bar<$text bold="true">bar</$text> bazbaz'
  139. // should expand to : 'foofoo [bar<$text bold="true">bar</$text>] bazbaz'.
  140. const nextNode = isForward ? walker.position.nodeAfter : walker.position.nodeBefore;
  141. if ( nextNode ) {
  142. // Check boundary char of an adjacent text node.
  143. const boundaryChar = nextNode.data.charAt( isForward ? 0 : nextNode.data.length - 1 );
  144. // Go to the next node if the character at the boundary of that node belongs to the same word.
  145. if ( !wordBoundaryCharacters.includes( boundaryChar ) ) {
  146. // If adjacent text node belongs to the same word go to it & reset values.
  147. walker.next();
  148. textNode = walker.position.textNode;
  149. }
  150. }
  151. offset = walker.position.offset - textNode.startOffset;
  152. }
  153. }
  154. return walker.position;
  155. }
  156. function getSearchRange( start, isForward ) {
  157. const root = start.root;
  158. const searchEnd = Position.createAt( root, isForward ? 'end' : 0 );
  159. if ( isForward ) {
  160. return new Range( start, searchEnd );
  161. } else {
  162. return new Range( searchEnd, start );
  163. }
  164. }
  165. // Checks if selection is on word boundary.
  166. //
  167. // @param {String} data The text node value to investigate.
  168. // @param {Number} offset Position offset.
  169. // @param {Boolean} isForward Is the direction in which the selection should be modified is forward.
  170. function isAtWordBoundary( data, offset, isForward ) {
  171. // The offset to check depends on direction.
  172. const offsetToCheck = offset + ( isForward ? 0 : -1 );
  173. return wordBoundaryCharacters.includes( data.charAt( offsetToCheck ) );
  174. }
  175. // Checks if selection is on node boundary.
  176. //
  177. // @param {module:engine/model/text~Text} textNode The text node to investigate.
  178. // @param {Number} offset Position offset.
  179. // @param {Boolean} isForward Is the direction in which the selection should be modified is forward.
  180. function isAtNodeBoundary( textNode, offset, isForward ) {
  181. return offset === ( isForward ? textNode.endOffset : 0 );
  182. }