selectionobserver.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /**
  2. * @license Copyright (c) 2003-2018, 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 createViewRoot from '../_utils/createroot';
  14. import { parse } from '../../../src/dev-utils/view';
  15. testUtils.createSinonSandbox();
  16. describe( 'SelectionObserver', () => {
  17. let viewDocument, viewRoot, selectionObserver, domRoot, domMain, domDocument;
  18. beforeEach( done => {
  19. domDocument = document;
  20. domRoot = domDocument.createElement( 'div' );
  21. domRoot.innerHTML = '<div contenteditable="true"></div><div contenteditable="true" id="additional"></div>';
  22. domMain = domRoot.childNodes[ 0 ];
  23. domDocument.body.appendChild( domRoot );
  24. viewDocument = new ViewDocument();
  25. createViewRoot( viewDocument );
  26. viewDocument.attachDomRoot( domMain );
  27. selectionObserver = viewDocument.getObserver( SelectionObserver );
  28. viewRoot = viewDocument.getRoot();
  29. viewRoot.appendChildren( parse(
  30. '<container:p>xxx<ui:span></ui:span></container:p>' +
  31. '<container:p>yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy</container:p>' ) );
  32. viewDocument.render();
  33. viewDocument.selection.setTo( null );
  34. domDocument.getSelection().removeAllRanges();
  35. viewDocument.isFocused = true;
  36. domMain.focus();
  37. selectionObserver.enable();
  38. // Ensure selectionchange will not be fired.
  39. setTimeout( () => done(), 100 );
  40. } );
  41. afterEach( () => {
  42. domRoot.parentElement.removeChild( domRoot );
  43. viewDocument.destroy();
  44. } );
  45. it( 'should fire selectionChange when it is the only change', done => {
  46. viewDocument.on( 'selectionChange', ( evt, data ) => {
  47. expect( data ).to.have.property( 'domSelection' ).that.equals( domDocument.getSelection() );
  48. expect( data ).to.have.property( 'oldSelection' ).that.is.instanceof( ViewSelection );
  49. expect( data.oldSelection.rangeCount ).to.equal( 0 );
  50. expect( data ).to.have.property( 'newSelection' ).that.is.instanceof( ViewSelection );
  51. expect( data.newSelection.rangeCount ).to.equal( 1 );
  52. const newViewRange = data.newSelection.getFirstRange();
  53. const viewFoo = viewDocument.getRoot().getChild( 1 ).getChild( 0 );
  54. expect( newViewRange.start.parent ).to.equal( viewFoo );
  55. expect( newViewRange.start.offset ).to.equal( 2 );
  56. expect( newViewRange.end.parent ).to.equal( viewFoo );
  57. expect( newViewRange.end.offset ).to.equal( 2 );
  58. done();
  59. } );
  60. changeDomSelection();
  61. } );
  62. it( 'should add only one listener to one document', done => {
  63. // Add second roots to ensure that listener is added once.
  64. createViewRoot( viewDocument, 'div', 'additional' );
  65. viewDocument.attachDomRoot( domDocument.getElementById( 'additional' ), 'additional' );
  66. viewDocument.on( 'selectionChange', () => {
  67. done();
  68. } );
  69. changeDomSelection();
  70. } );
  71. it( 'should not fire selectionChange on render', done => {
  72. viewDocument.on( 'selectionChange', () => {
  73. throw 'selectionChange on render';
  74. } );
  75. setTimeout( done, 70 );
  76. const viewBar = viewDocument.getRoot().getChild( 1 ).getChild( 0 );
  77. viewDocument.selection.addRange( ViewRange.createFromParentsAndOffsets( viewBar, 1, viewBar, 2 ) );
  78. viewDocument.render();
  79. } );
  80. it( 'should not fired if observer is disabled', done => {
  81. viewDocument.getObserver( SelectionObserver ).disable();
  82. viewDocument.on( 'selectionChange', () => {
  83. throw 'selectionChange on render';
  84. } );
  85. setTimeout( done, 70 );
  86. changeDomSelection();
  87. } );
  88. it( 'should not fired if there is no focus', done => {
  89. viewDocument.isFocused = false;
  90. // changeDomSelection() may focus the editable element (happens on Chrome)
  91. // so cancel this because it sets the isFocused flag.
  92. viewDocument.on( 'focus', evt => evt.stop(), { priority: 'highest' } );
  93. viewDocument.on( 'selectionChange', () => {
  94. // Validate the correctness of the test. May help tracking issue with this test.
  95. expect( viewDocument.isFocused ).to.be.false;
  96. throw 'selectionChange on render';
  97. } );
  98. setTimeout( done, 70 );
  99. changeDomSelection();
  100. } );
  101. it( 'should fired if there is no focus but document is read-only', done => {
  102. const spy = sinon.spy();
  103. viewDocument.isFocused = false;
  104. viewDocument.isReadOnly = true;
  105. // changeDomSelection() may focus the editable element (happens on Chrome)
  106. // so cancel this because it sets the isFocused flag.
  107. viewDocument.on( 'focus', evt => evt.stop(), { priority: 'highest' } );
  108. viewDocument.on( 'selectionChange', spy );
  109. setTimeout( () => {
  110. sinon.assert.called( spy );
  111. done();
  112. }, 70 );
  113. changeDomSelection();
  114. } );
  115. it( 'should warn and not enter infinite loop', () => {
  116. let counter = 70;
  117. const viewFoo = viewDocument.getRoot().getChild( 0 ).getChild( 0 );
  118. viewDocument.selection.addRange( ViewRange.createFromParentsAndOffsets( viewFoo, 0, viewFoo, 0 ) );
  119. return new Promise( ( resolve, reject ) => {
  120. testUtils.sinon.stub( log, 'warn' ).callsFake( msg => {
  121. expect( msg ).to.match( /^selectionchange-infinite-loop/ );
  122. resolve();
  123. } );
  124. viewDocument.on( 'selectionChangeDone', () => {
  125. if ( !counter ) {
  126. reject( new Error( 'Infinite loop warning was not logged.' ) );
  127. }
  128. } );
  129. while ( counter > 0 ) {
  130. changeDomSelection();
  131. counter--;
  132. }
  133. } );
  134. } );
  135. it( 'should not be treated as an infinite loop if selection is changed only few times', done => {
  136. const viewFoo = viewDocument.getRoot().getChild( 0 ).getChild( 0 );
  137. viewDocument.selection.addRange( ViewRange.createFromParentsAndOffsets( viewFoo, 0, viewFoo, 0 ) );
  138. const spy = testUtils.sinon.spy( log, 'warn' );
  139. viewDocument.on( 'selectionChangeDone', () => {
  140. expect( spy.called ).to.be.false;
  141. done();
  142. } );
  143. for ( let i = 0; i < 10; i++ ) {
  144. changeDomSelection();
  145. }
  146. } );
  147. it( 'should not be treated as an infinite loop if changes are not often', () => {
  148. const clock = testUtils.sinon.useFakeTimers( {
  149. toFake: [ 'setInterval', 'clearInterval' ]
  150. } );
  151. const stub = testUtils.sinon.stub( log, 'warn' );
  152. // We need to recreate SelectionObserver, so it will use mocked setInterval.
  153. selectionObserver.disable();
  154. selectionObserver.destroy();
  155. viewDocument._observers.delete( SelectionObserver );
  156. viewDocument.addObserver( SelectionObserver );
  157. return doChanges()
  158. .then( doChanges )
  159. .then( () => {
  160. sinon.assert.notCalled( stub );
  161. clock.restore();
  162. } );
  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 < 50; 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. const domParagraph = domMain.childNodes[ 0 ];
  231. const domText = domParagraph.childNodes[ 0 ];
  232. const domUI = domParagraph.childNodes[ 1 ];
  233. // Add rendering on selectionChange event to check this feature.
  234. viewDocument.on( 'selectionChange', () => {
  235. // Manually set selection because no handlers are set for selectionChange event in this test.
  236. // Normally this is handled by view -> model -> view selection converters chain.
  237. const viewSel = viewDocument.selection;
  238. const viewAnchor = viewDocument.domConverter.domPositionToView( sel.anchorNode, sel.anchorOffset );
  239. const viewFocus = viewDocument.domConverter.domPositionToView( sel.focusNode, sel.focusOffset );
  240. viewSel.setCollapsedAt( viewAnchor );
  241. viewSel.moveFocusTo( viewFocus );
  242. viewDocument.render();
  243. } );
  244. viewDocument.once( 'selectionChange', () => {
  245. // 2. Selection change has been handled.
  246. selectionObserver.listenTo( domDocument, 'selectionchange', () => {
  247. // 4. Check if view was re-rendered.
  248. expect( viewDocument.render.called ).to.be.true;
  249. done();
  250. }, { priority: 'lowest' } );
  251. // 3. Now, collapse selection in similar position, but in UI element.
  252. // Current and new selection position are similar in view (but not equal!).
  253. // Also add a spy to `viewDocument#render` to see if view will be re-rendered.
  254. sel.collapse( domUI, 0 );
  255. sinon.spy( viewDocument, 'render' );
  256. // Some browsers like Safari won't allow to put selection inside empty ui element.
  257. // In that situation selection should stay in correct place.
  258. if ( sel.anchorNode !== domUI ) {
  259. expect( sel.anchorNode ).to.equal( domText );
  260. expect( sel.anchorOffset ).to.equal( 3 );
  261. expect( sel.isCollapsed ).to.be.true;
  262. done();
  263. }
  264. }, { priority: 'lowest' } );
  265. // 1. Collapse in a text node, before ui element, and wait for async selectionchange to fire selection change handling.
  266. sel.collapse( domText, 3 );
  267. } );
  268. function changeDomSelection() {
  269. const domSelection = domDocument.getSelection();
  270. const domFoo = domMain.childNodes[ 1 ].childNodes[ 0 ];
  271. const offset = domSelection.anchorOffset;
  272. domSelection.collapse( domFoo, offset == 2 ? 3 : 2 );
  273. }
  274. } );