selectionobserver.js 11 KB

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