modifyselection.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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 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 {{ item, nextPosition, type}} 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. return getCorrectPosition( data.walker, data.unit, data.isForward );
  80. }
  81. // Entering an element.
  82. if ( value.type == ( data.isForward ? 'elementStart' : 'elementEnd' ) ) {
  83. // If it's an object, we can select it now.
  84. if ( data.schema.isObject( value.item ) ) {
  85. return Position.createAt( value.item, data.isForward ? 'after' : 'before' );
  86. }
  87. // If text allowed on this position, extend to this place.
  88. if ( data.schema.checkChild( value.nextPosition, '$text' ) ) {
  89. return value.nextPosition;
  90. }
  91. }
  92. // Leaving an element.
  93. else {
  94. // If leaving a limit element, stop.
  95. if ( data.schema.isLimit( value.item ) ) {
  96. // NOTE: Fast-forward the walker until the end.
  97. data.walker.skip( () => true );
  98. return;
  99. }
  100. // If text allowed on this position, extend to this place.
  101. if ( data.schema.checkChild( value.nextPosition, '$text' ) ) {
  102. return value.nextPosition;
  103. }
  104. }
  105. }
  106. // Finds a correct position by walking in a text node and checking whether selection can be extended to given position
  107. // or should be extended further.
  108. //
  109. // @param {module:engine/model/treewalker~TreeWalker} walker
  110. // @param {String} unit The unit by which selection should be modified.
  111. // @param {Boolean} isForward Is the direction in which the selection should be modified is forward.
  112. function getCorrectPosition( walker, unit, isForward ) {
  113. let textNode = walker.position.textNode;
  114. if ( textNode ) {
  115. let data = textNode.data;
  116. let offset = walker.position.offset - textNode.startOffset;
  117. let isAtNodeBoundary = offset === ( isForward ? textNode.endOffset : 0 );
  118. while (
  119. isInsideSurrogatePair( data, offset ) ||
  120. ( unit == 'character' && isInsideCombinedSymbol( data, offset ) ) ||
  121. ( unit == 'word' && ( !( isAtNodeBoundary || isAtWordBoundary( textNode.data, offset, isForward ) ) ) )
  122. ) {
  123. walker.next();
  124. // Check of adjacent text nodes with different attributes (like BOLD).
  125. // Example : 'foofoo []bar<$text bold="true">bar</$text> bazbaz'
  126. // should expand to : 'foofoo [bar<$text bold="true">bar</$text>] bazbaz'.
  127. if ( unit == 'word' && !isAtNodeBoundary ) {
  128. const nextNode = isForward ? walker.position.nodeAfter : walker.position.nodeBefore;
  129. if ( nextNode ) {
  130. // Check boundary char of an adjacent text node.
  131. const boundaryChar = nextNode.data.charAt( isForward ? 0 : nextNode.data.length - 1 );
  132. // Go to the next node if the character at the boundary of that node belongs to the same word.
  133. if ( !wordBoundaryCharacters.includes( boundaryChar ) ) {
  134. // If adjacent text node belongs to the same word go to it & reset values.
  135. walker.next();
  136. textNode = walker.position.textNode;
  137. data = textNode.data;
  138. }
  139. }
  140. }
  141. offset = walker.position.offset - textNode.startOffset;
  142. isAtNodeBoundary = offset === ( isForward ? textNode.endOffset : 0 );
  143. }
  144. }
  145. return walker.position;
  146. }
  147. function getSearchRange( start, isForward ) {
  148. const root = start.root;
  149. const searchEnd = Position.createAt( root, isForward ? 'end' : 0 );
  150. if ( isForward ) {
  151. return new Range( start, searchEnd );
  152. } else {
  153. return new Range( searchEnd, start );
  154. }
  155. }
  156. // Checks if selection is on word boundary.
  157. //
  158. // @param {module:engine/view/text~Text} textNode The text node to investigate.
  159. // @param {Number} offset Position offset.
  160. // @param {Boolean} isForward Is the direction in which the selection should be modified is forward.
  161. function isAtWordBoundary( data, offset, isForward ) {
  162. // The offset to check depends on direction.
  163. const offsetToCheck = offset + ( isForward ? 0 : -1 );
  164. return wordBoundaryCharacters.includes( data.charAt( offsetToCheck ) );
  165. }