ToggleFullscreen.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // FULLSCREEN
  2. // -----------------------------------
  3. import React, { Component } from 'react';
  4. import PropTypes from 'prop-types';
  5. import screenfull from 'screenfull';
  6. const FULLSCREEN_ON_ICON = 'fa fa-expand';
  7. const FULLSCREEN_OFF_ICON = 'fa fa-compress';
  8. /**
  9. * Wrapper for screenfull plugin
  10. * Wraps child element and toggles
  11. * fullscreen mode on click
  12. */
  13. export default class ToggleFullscreen extends Component {
  14. static propTypes = {
  15. /** tag to use, defaults to A */
  16. tag: PropTypes.string
  17. };
  18. static defaultProps = {
  19. tag: 'a'
  20. };
  21. state = {
  22. iconClass: FULLSCREEN_ON_ICON
  23. };
  24. componentDidMount() {
  25. this.fsToggler = this.element;
  26. // Not supported under IE
  27. const ua = window.navigator.userAgent;
  28. if (ua.indexOf('MSIE ') > 0 || !!ua.match(/Trident.*rv:11\./)) {
  29. this.fsToggler.style.display = 'none';
  30. return; // and abort
  31. }
  32. this.fsToggler.addEventListener('click', this.handleClisk);
  33. if (screenfull.raw && screenfull.raw.fullscreenchange)
  34. document.addEventListener(screenfull.raw.fullscreenchange, this.toggleFSIcon);
  35. }
  36. handleClisk = e => {
  37. e.preventDefault();
  38. if (screenfull.enabled) {
  39. screenfull.toggle();
  40. // Switch icon indicator
  41. this.toggleFSIcon();
  42. } else {
  43. console.log('Fullscreen not enabled');
  44. }
  45. };
  46. toggleFSIcon = () => {
  47. this.setState({
  48. iconClass: screenfull.isFullscreen ? FULLSCREEN_OFF_ICON : FULLSCREEN_ON_ICON
  49. });
  50. };
  51. componentWillUnmount() {
  52. this.fsToggler.removeEventListener('click', this.handleClisk);
  53. document.removeEventListener(screenfull.raw.fullscreenchange, this.toggleFSIcon);
  54. }
  55. setRef = node => {
  56. this.element = node;
  57. };
  58. render() {
  59. const { tag: Tag } = this.props;
  60. return (
  61. <Tag ref={this.setRef} {...this.props}>
  62. <em className={this.state.iconClass} />
  63. </Tag>
  64. );
  65. }
  66. }