position.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* global document, setTimeout */
  6. import { getOptimalPosition } from '../../../src/dom/position';
  7. const boxes = document.querySelectorAll( '.test-box' );
  8. const sources = document.querySelectorAll( '.source' );
  9. const target = document.querySelector( '.target' );
  10. target.scrollIntoView();
  11. const positions = {
  12. nw: targetRect => ( {
  13. top: targetRect.top,
  14. left: targetRect.left,
  15. name: 'nw'
  16. } ),
  17. ne: ( targetRect, sourceRect ) => ( {
  18. top: targetRect.top,
  19. left: targetRect.right - sourceRect.width,
  20. name: 'ne'
  21. } ),
  22. sw: ( targetRect, sourceRect ) => ( {
  23. top: targetRect.bottom - sourceRect.height,
  24. left: targetRect.left,
  25. name: 'sw'
  26. } ),
  27. se: ( targetRect, sourceRect ) => ( {
  28. top: targetRect.bottom - sourceRect.height,
  29. left: targetRect.right - sourceRect.width,
  30. name: 'se'
  31. } )
  32. };
  33. for ( const box of boxes ) {
  34. box.scrollTop = box.scrollHeight;
  35. box.scrollLeft = box.scrollWidth;
  36. }
  37. // Wait for the scroll to stabilize.
  38. setTimeout( () => {
  39. for ( const source of sources ) {
  40. const position = getOptimalPosition( {
  41. element: source,
  42. target,
  43. positions: [
  44. positions[ source.className.split( '-' )[ 1 ] ]
  45. ],
  46. limiter: document.body
  47. } );
  48. source.style.top = position.top + 'px';
  49. source.style.left = position.left + 'px';
  50. }
  51. }, 100 );