Christophe Dervieux | e1893ae | 2021-10-07 17:09:02 +0200 | [diff] [blame^] | 1 | import { closest } from '../utils/util.js' |
| 2 | |
| 3 | /** |
| 4 | * Manages focus when a presentation is embedded. This |
| 5 | * helps us only capture keyboard from the presentation |
| 6 | * a user is currently interacting with in a page where |
| 7 | * multiple presentations are embedded. |
| 8 | */ |
| 9 | |
| 10 | const STATE_FOCUS = 'focus'; |
| 11 | const STATE_BLUR = 'blur'; |
| 12 | |
| 13 | export default class Focus { |
| 14 | |
| 15 | constructor( Reveal ) { |
| 16 | |
| 17 | this.Reveal = Reveal; |
| 18 | |
| 19 | this.onRevealPointerDown = this.onRevealPointerDown.bind( this ); |
| 20 | this.onDocumentPointerDown = this.onDocumentPointerDown.bind( this ); |
| 21 | |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Called when the reveal.js config is updated. |
| 26 | */ |
| 27 | configure( config, oldConfig ) { |
| 28 | |
| 29 | if( config.embedded ) { |
| 30 | this.blur(); |
| 31 | } |
| 32 | else { |
| 33 | this.focus(); |
| 34 | this.unbind(); |
| 35 | } |
| 36 | |
| 37 | } |
| 38 | |
| 39 | bind() { |
| 40 | |
| 41 | if( this.Reveal.getConfig().embedded ) { |
| 42 | this.Reveal.getRevealElement().addEventListener( 'pointerdown', this.onRevealPointerDown, false ); |
| 43 | } |
| 44 | |
| 45 | } |
| 46 | |
| 47 | unbind() { |
| 48 | |
| 49 | this.Reveal.getRevealElement().removeEventListener( 'pointerdown', this.onRevealPointerDown, false ); |
| 50 | document.removeEventListener( 'pointerdown', this.onDocumentPointerDown, false ); |
| 51 | |
| 52 | } |
| 53 | |
| 54 | focus() { |
| 55 | |
| 56 | if( this.state !== STATE_FOCUS ) { |
| 57 | this.Reveal.getRevealElement().classList.add( 'focused' ); |
| 58 | document.addEventListener( 'pointerdown', this.onDocumentPointerDown, false ); |
| 59 | } |
| 60 | |
| 61 | this.state = STATE_FOCUS; |
| 62 | |
| 63 | } |
| 64 | |
| 65 | blur() { |
| 66 | |
| 67 | if( this.state !== STATE_BLUR ) { |
| 68 | this.Reveal.getRevealElement().classList.remove( 'focused' ); |
| 69 | document.removeEventListener( 'pointerdown', this.onDocumentPointerDown, false ); |
| 70 | } |
| 71 | |
| 72 | this.state = STATE_BLUR; |
| 73 | |
| 74 | } |
| 75 | |
| 76 | isFocused() { |
| 77 | |
| 78 | return this.state === STATE_FOCUS; |
| 79 | |
| 80 | } |
| 81 | |
| 82 | onRevealPointerDown( event ) { |
| 83 | |
| 84 | this.focus(); |
| 85 | |
| 86 | } |
| 87 | |
| 88 | onDocumentPointerDown( event ) { |
| 89 | |
| 90 | let revealElement = closest( event.target, '.reveal' ); |
| 91 | if( !revealElement || revealElement !== this.Reveal.getRevealElement() ) { |
| 92 | this.blur(); |
| 93 | } |
| 94 | |
| 95 | } |
| 96 | |
| 97 | } |