jumptoslide.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /**
  2. * Makes it possble to jump to a slide by entering its
  3. * slide number or id.
  4. */
  5. export default class JumpToSlide {
  6. constructor( Reveal ) {
  7. this.Reveal = Reveal;
  8. this.onInput = this.onInput.bind( this );
  9. this.onBlur = this.onBlur.bind( this );
  10. this.onKeyDown = this.onKeyDown.bind( this );
  11. }
  12. render() {
  13. this.element = document.createElement( 'div' );
  14. this.element.className = 'jump-to-slide';
  15. this.jumpInput = document.createElement( 'input' );
  16. this.jumpInput.type = 'text';
  17. this.jumpInput.className = 'jump-to-slide-input';
  18. this.jumpInput.placeholder = 'Jump to slide';
  19. this.jumpInput.addEventListener( 'input', this.onInput );
  20. this.jumpInput.addEventListener( 'keydown', this.onKeyDown );
  21. this.jumpInput.addEventListener( 'blur', this.onBlur );
  22. this.element.appendChild( this.jumpInput );
  23. }
  24. show() {
  25. this.indicesOnShow = this.Reveal.getIndices();
  26. this.Reveal.getRevealElement().appendChild( this.element );
  27. this.jumpInput.focus();
  28. }
  29. hide() {
  30. if( this.isVisible() ) {
  31. this.element.remove();
  32. this.jumpInput.value = '';
  33. }
  34. }
  35. isVisible() {
  36. return !!this.element.parentNode;
  37. }
  38. jump() {
  39. const value = this.jumpInput.value.trim( '' );
  40. const indices = this.Reveal.location.getIndicesFromHash( value );
  41. if( indices && value !== '' ) {
  42. this.Reveal.slide( indices.h, indices.v, indices.f );
  43. return true;
  44. }
  45. else {
  46. this.Reveal.slide( this.indicesOnShow.h, this.indicesOnShow.v, this.indicesOnShow.f );
  47. return false;
  48. }
  49. }
  50. /**
  51. * Reverts back to the slide we were on when jump to slide was
  52. * invoked.
  53. */
  54. cancel() {
  55. this.Reveal.slide( this.indicesOnShow.h, this.indicesOnShow.v, this.indicesOnShow.f );
  56. this.hide();
  57. }
  58. confirm() {
  59. this.hide();
  60. }
  61. destroy() {
  62. this.jumpInput.removeEventListener( 'input', this.onInput );
  63. this.jumpInput.removeEventListener( 'keydown', this.onKeyDown );
  64. this.jumpInput.removeEventListener( 'blur', this.onBlur );
  65. this.element.remove();
  66. }
  67. onKeyDown( event ) {
  68. if( event.keyCode === 13 ) {
  69. this.confirm();
  70. }
  71. else if( event.keyCode === 27 ) {
  72. this.cancel();
  73. event.stopImmediatePropagation();
  74. }
  75. }
  76. onInput( event ) {
  77. this.jump();
  78. }
  79. onBlur() {
  80. setTimeout( () => this.hide(), 1 );
  81. }
  82. }