focus.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * Manages focus when a presentation is embedded. This
  3. * helps us only capture keyboard from the presentation
  4. * a user is currently interacting with in a page where
  5. * multiple presentations are embedded.
  6. */
  7. const STATE_FOCUS = 'focus';
  8. const STATE_BLUR = 'blur';
  9. export default class Focus {
  10. constructor( Reveal ) {
  11. this.Reveal = Reveal;
  12. this.onRevealPointerDown = this.onRevealPointerDown.bind( this );
  13. this.onDocumentPointerDown = this.onDocumentPointerDown.bind( this );
  14. }
  15. /**
  16. * Called when the reveal.js config is updated.
  17. */
  18. configure( config, oldConfig ) {
  19. if( config.embedded ) {
  20. this.blur();
  21. }
  22. else {
  23. this.focus();
  24. this.unbind();
  25. }
  26. }
  27. bind() {
  28. if( this.Reveal.getConfig().embedded ) {
  29. this.Reveal.getRevealElement().addEventListener( 'pointerdown', this.onRevealPointerDown, false );
  30. }
  31. }
  32. unbind() {
  33. this.Reveal.getRevealElement().removeEventListener( 'pointerdown', this.onRevealPointerDown, false );
  34. document.removeEventListener( 'pointerdown', this.onDocumentPointerDown, false );
  35. }
  36. focus() {
  37. if( this.state !== STATE_FOCUS ) {
  38. this.Reveal.getRevealElement().classList.add( 'focused' );
  39. document.addEventListener( 'pointerdown', this.onDocumentPointerDown, false );
  40. }
  41. this.state = STATE_FOCUS;
  42. }
  43. blur() {
  44. if( this.state !== STATE_BLUR ) {
  45. this.Reveal.getRevealElement().classList.remove( 'focused' );
  46. document.removeEventListener( 'pointerdown', this.onDocumentPointerDown, false );
  47. }
  48. this.state = STATE_BLUR;
  49. }
  50. isFocused() {
  51. return this.state === STATE_FOCUS;
  52. }
  53. onRevealPointerDown( event ) {
  54. this.focus();
  55. }
  56. onDocumentPointerDown( event ) {
  57. let revealElement = event.target.closest( '.reveal' );
  58. if( !revealElement || revealElement !== this.Reveal.getRevealElement() ) {
  59. this.blur();
  60. }
  61. }
  62. }