selectionobserver.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /* globals setTimeout, document */
  6. import ViewRange from '../../../src/view/range';
  7. import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils';
  8. import ViewSelection from '../../../src/view/selection';
  9. import ViewDocument from '../../../src/view/document';
  10. import SelectionObserver from '../../../src/view/observer/selectionobserver';
  11. import FocusObserver from '../../../src/view/observer/focusobserver';
  12. import log from '@ckeditor/ckeditor5-utils/src/log';
  13. import { parse } from '../../../src/dev-utils/view';
  14. testUtils.createSinonSandbox();
  15. describe( 'SelectionObserver', () => {
  16. let viewDocument, viewRoot, selectionObserver, domRoot, domMain, domDocument;
  17. beforeEach( done => {
  18. domDocument = document;
  19. domRoot = domDocument.createElement( 'div' );
  20. domRoot.innerHTML = '<div contenteditable="true"></div><div contenteditable="true" id="additional"></div>';
  21. domMain = domRoot.childNodes[ 0 ];
  22. domDocument.body.appendChild( domRoot );
  23. viewDocument = new ViewDocument();
  24. viewDocument.createRoot( domMain );
  25. selectionObserver = viewDocument.getObserver( SelectionObserver );
  26. viewRoot = viewDocument.getRoot();
  27. viewRoot.appendChildren( parse(
  28. '<container:p>xxx<ui:span></ui:span></container:p>' +
  29. '<container:p>yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy</container:p>' ) );
  30. viewDocument.render();
  31. viewDocument.selection.removeAllRanges();
  32. domDocument.getSelection().removeAllRanges();
  33. viewDocument.isFocused = true;
  34. domMain.focus();
  35. selectionObserver.enable();
  36. // Ensure selectionchange will not be fired.
  37. setTimeout( () => done(), 100 );
  38. } );
  39. afterEach( () => {
  40. domRoot.parentElement.removeChild( domRoot );
  41. viewDocument.destroy();
  42. } );
  43. it( 'should fire selectionChange when it is the only change', done => {
  44. viewDocument.on( 'selectionChange', ( evt, data ) => {
  45. expect( data ).to.have.property( 'domSelection' ).that.equals( domDocument.getSelection() );
  46. expect( data ).to.have.property( 'oldSelection' ).that.is.instanceof( ViewSelection );
  47. expect( data.oldSelection.rangeCount ).to.equal( 0 );
  48. expect( data ).to.have.property( 'newSelection' ).that.is.instanceof( ViewSelection );
  49. expect( data.newSelection.rangeCount ).to.equal( 1 );
  50. const newViewRange = data.newSelection.getFirstRange();
  51. const viewFoo = viewDocument.getRoot().getChild( 1 ).getChild( 0 );
  52. expect( newViewRange.start.parent ).to.equal( viewFoo );
  53. expect( newViewRange.start.offset ).to.equal( 2 );
  54. expect( newViewRange.end.parent ).to.equal( viewFoo );
  55. expect( newViewRange.end.offset ).to.equal( 2 );
  56. done();
  57. } );
  58. changeDomSelection();
  59. } );
  60. it( 'should add only one listener to one document', done => {
  61. // Add second roots to ensure that listener is added once.
  62. viewDocument.createRoot( domDocument.getElementById( 'additional' ), 'additional' );
  63. viewDocument.on( 'selectionChange', () => {
  64. done();
  65. } );
  66. changeDomSelection();
  67. } );
  68. it( 'should not fire selectionChange on render', done => {
  69. viewDocument.on( 'selectionChange', () => {
  70. throw 'selectionChange on render';
  71. } );
  72. setTimeout( done, 70 );
  73. const viewBar = viewDocument.getRoot().getChild( 1 ).getChild( 0 );
  74. viewDocument.selection.addRange( ViewRange.createFromParentsAndOffsets( viewBar, 1, viewBar, 2 ) );
  75. viewDocument.render();
  76. } );
  77. it( 'should not fired if observer is disabled', done => {
  78. viewDocument.getObserver( SelectionObserver ).disable();
  79. viewDocument.on( 'selectionChange', () => {
  80. throw 'selectionChange on render';
  81. } );
  82. setTimeout( done, 70 );
  83. changeDomSelection();
  84. } );
  85. it( 'should not fired if there is no focus', done => {
  86. viewDocument.isFocused = false;
  87. // changeDomSelection() may focus the editable element (happens on Chrome)
  88. // so cancel this because it sets the isFocused flag.
  89. viewDocument.on( 'focus', evt => evt.stop(), { priority: 'highest' } );
  90. viewDocument.on( 'selectionChange', () => {
  91. // Validate the correctness of the test. May help tracking issue with this test.
  92. expect( viewDocument.isFocused ).to.be.false;
  93. throw 'selectionChange on render';
  94. } );
  95. setTimeout( done, 70 );
  96. changeDomSelection();
  97. } );
  98. it( 'should fired if there is no focus but document is read-only', done => {
  99. const spy = sinon.spy();
  100. viewDocument.isFocused = false;
  101. viewDocument.isReadOnly = true;
  102. // changeDomSelection() may focus the editable element (happens on Chrome)
  103. // so cancel this because it sets the isFocused flag.
  104. viewDocument.on( 'focus', evt => evt.stop(), { priority: 'highest' } );
  105. viewDocument.on( 'selectionChange', spy );
  106. setTimeout( () => {
  107. sinon.assert.called( spy );
  108. done();
  109. }, 70 );
  110. changeDomSelection();
  111. } );
  112. it( 'should warn and not enter infinite loop', () => {
  113. // Selectionchange event is called twice per `changeDomSelection()` execution.
  114. let counter = 70;
  115. const viewFoo = viewDocument.getRoot().getChild( 0 ).getChild( 0 );
  116. viewDocument.selection.addRange( ViewRange.createFromParentsAndOffsets( viewFoo, 0, viewFoo, 0 ) );
  117. return new Promise( ( resolve, reject ) => {
  118. testUtils.sinon.stub( log, 'warn' ).callsFake( msg => {
  119. expect( msg ).to.match( /^selectionchange-infinite-loop/ );
  120. resolve();
  121. } );
  122. viewDocument.on( 'selectionChangeDone', () => {
  123. if ( !counter ) {
  124. reject( new Error( 'Infinite loop warning was not logged.' ) );
  125. }
  126. } );
  127. while ( counter > 0 ) {
  128. changeDomSelection();
  129. counter--;
  130. }
  131. } );
  132. } );
  133. it( 'should not be treated as an infinite loop if selection is changed only few times', done => {
  134. const viewFoo = viewDocument.getRoot().getChild( 0 ).getChild( 0 );
  135. viewDocument.selection.addRange( ViewRange.createFromParentsAndOffsets( viewFoo, 0, viewFoo, 0 ) );
  136. const spy = testUtils.sinon.spy( log, 'warn' );
  137. viewDocument.on( 'selectionChangeDone', () => {
  138. expect( spy.called ).to.be.false;
  139. done();
  140. } );
  141. for ( let i = 0; i < 10; i++ ) {
  142. changeDomSelection();
  143. }
  144. } );
  145. it( 'should not be treated as an infinite loop if changes are not often', () => {
  146. const clock = testUtils.sinon.useFakeTimers( {
  147. toFake: [ 'setInterval', 'clearInterval' ]
  148. } );
  149. const stub = testUtils.sinon.stub( log, 'warn' );
  150. // We need to recreate SelectionObserver, so it will use mocked setInterval.
  151. selectionObserver.disable();
  152. selectionObserver.destroy();
  153. viewDocument._observers.delete( SelectionObserver );
  154. viewDocument.addObserver( SelectionObserver );
  155. return doChanges()
  156. .then( doChanges )
  157. .then( () => {
  158. sinon.assert.notCalled( stub );
  159. clock.restore();
  160. } );
  161. // Selectionchange event is called twice per `changeDomSelection()` execution. We call it 25 times to get
  162. // 50 events. Infinite loop counter is reset, so calling this method twice should not show any warning.
  163. function doChanges() {
  164. return new Promise( resolve => {
  165. viewDocument.once( 'selectionChangeDone', () => {
  166. clock.tick( 1100 );
  167. resolve();
  168. } );
  169. for ( let i = 0; i < 30; i++ ) {
  170. changeDomSelection();
  171. }
  172. } );
  173. }
  174. } );
  175. it( 'should fire `selectionChangeDone` event after selection stop changing', done => {
  176. const spy = sinon.spy();
  177. viewDocument.on( 'selectionChangeDone', spy );
  178. // Disable focus observer to not re-render view on each focus.
  179. viewDocument.getObserver( FocusObserver ).disable();
  180. // Change selection.
  181. changeDomSelection();
  182. // Wait 100ms.
  183. // Note that it's difficult/not possible to test lodash#debounce with sinon fake timers.
  184. // See: https://github.com/lodash/lodash/issues/304
  185. setTimeout( () => {
  186. // Check if spy was called.
  187. expect( spy.notCalled ).to.true;
  188. // Change selection one more time.
  189. changeDomSelection();
  190. // Wait 210ms (debounced function should be called).
  191. setTimeout( () => {
  192. const data = spy.firstCall.args[ 1 ];
  193. expect( spy.calledOnce ).to.true;
  194. expect( data ).to.have.property( 'domSelection' ).to.equal( domDocument.getSelection() );
  195. expect( data ).to.have.property( 'oldSelection' ).to.instanceof( ViewSelection );
  196. expect( data.oldSelection.rangeCount ).to.equal( 0 );
  197. expect( data ).to.have.property( 'newSelection' ).to.instanceof( ViewSelection );
  198. expect( data.newSelection.rangeCount ).to.equal( 1 );
  199. const newViewRange = data.newSelection.getFirstRange();
  200. const viewFoo = viewDocument.getRoot().getChild( 1 ).getChild( 0 );
  201. expect( newViewRange.start.parent ).to.equal( viewFoo );
  202. expect( newViewRange.start.offset ).to.equal( 3 );
  203. expect( newViewRange.end.parent ).to.equal( viewFoo );
  204. expect( newViewRange.end.offset ).to.equal( 3 );
  205. done();
  206. }, 210 );
  207. }, 100 );
  208. } );
  209. it( 'should not fire `selectionChangeDone` event when observer will be destroyed', done => {
  210. const spy = sinon.spy();
  211. viewDocument.on( 'selectionChangeDone', spy );
  212. // Change selection.
  213. changeDomSelection();
  214. // Wait 100ms.
  215. // Note that it's difficult/not possible to test lodash#debounce with sinon fake timers.
  216. // See: https://github.com/lodash/lodash/issues/304
  217. setTimeout( () => {
  218. // And destroy observer.
  219. selectionObserver.destroy();
  220. // Wait another 110ms.
  221. setTimeout( () => {
  222. // Check that event won't be called.
  223. expect( spy.notCalled ).to.true;
  224. done();
  225. }, 110 );
  226. }, 100 );
  227. } );
  228. it( 'should re-render view if selections are similar if DOM selection is in incorrect place', done => {
  229. const sel = domDocument.getSelection();
  230. // Add rendering on selectionChange event to check this feature.
  231. viewDocument.on( 'selectionChange', () => {
  232. // Manually set selection because no handlers are set for selectionChange event in this test.
  233. // Normally this is handled by view -> model -> view selection converters chain.
  234. const viewSel = viewDocument.selection;
  235. const viewAnchor = viewDocument.domConverter.domPositionToView( sel.anchorNode, sel.anchorOffset );
  236. const viewFocus = viewDocument.domConverter.domPositionToView( sel.focusNode, sel.focusOffset );
  237. viewSel.setCollapsedAt( viewAnchor );
  238. viewSel.moveFocusTo( viewFocus );
  239. viewDocument.render();
  240. } );
  241. viewDocument.once( 'selectionChange', () => {
  242. // 2. Selection change has been handled.
  243. selectionObserver.listenTo( domDocument, 'selectionchange', () => {
  244. // 4. Check if view was re-rendered.
  245. expect( viewDocument.render.called ).to.be.true;
  246. done();
  247. }, { priority: 'lowest' } );
  248. // 3. Now, collapse selection in similar position, but in UI element.
  249. // Current and new selection position are similar in view (but not equal!).
  250. // Also add a spy to `viewDocument#render` to see if view will be re-rendered.
  251. sel.collapse( domMain.childNodes[ 0 ].childNodes[ 1 ], 0 );
  252. sinon.spy( viewDocument, 'render' );
  253. }, { priority: 'lowest' } );
  254. // 1. Collapse in a text node, before ui element, and wait for async selectionchange to fire selection change handling.
  255. sel.collapse( domMain.childNodes[ 0 ].childNodes[ 0 ], 3 );
  256. } );
  257. function changeDomSelection() {
  258. const domSelection = domDocument.getSelection();
  259. const domFoo = domMain.childNodes[ 1 ].childNodes[ 0 ];
  260. const offset = domSelection.anchorOffset;
  261. domSelection.collapse( domFoo, offset == 2 ? 3 : 2 );
  262. }
  263. } );