|
| 1 | +import { FaExternalLinkAlt } from 'react-icons/fa'; |
| 2 | +import ReactDOM from 'react-dom'; |
| 3 | +import { useRef, useEffect } from 'react'; |
| 4 | +import cs from 'classnames'; |
| 5 | +import styles from './Timer.module.css'; |
| 6 | + |
| 7 | +function TimerPopout({ authUser, darkMode, TimerComponent }) { |
| 8 | + const popupRef = useRef(null); |
| 9 | + |
| 10 | + const openPopoutWindow = () => { |
| 11 | + if (popupRef.current && !popupRef.current.closed) { |
| 12 | + popupRef.current.focus(); |
| 13 | + return; |
| 14 | + } |
| 15 | + |
| 16 | + const features = { |
| 17 | + width: 300, |
| 18 | + height: 200, |
| 19 | + right: window.screen.width - 350, |
| 20 | + top: 30, |
| 21 | + menubar: 'no', |
| 22 | + toolbar: 'no', |
| 23 | + location: 'no', |
| 24 | + status: 'no', |
| 25 | + resizable: 'yes', |
| 26 | + }; |
| 27 | + |
| 28 | + const featuresStr = Object.entries(features) |
| 29 | + .map(([key, value]) => `${key}=${value}`) |
| 30 | + .join(','); |
| 31 | + |
| 32 | + const popup = window.open('', 'Timer', featuresStr); |
| 33 | + |
| 34 | + popupRef.current = popup; |
| 35 | + |
| 36 | + popup.document.write(` |
| 37 | + <!DOCTYPE html> |
| 38 | + <html> |
| 39 | + <head> |
| 40 | + <title>Timer</title> |
| 41 | + <link rel="stylesheet" href="${window.location.origin}/Timer.module.css"> |
| 42 | + ${darkMode ? '<style>body { background-color: #1a1a2e; color: white; }</style>' : ''} |
| 43 | + </head> |
| 44 | + <body> |
| 45 | + <h1 style="text-align: center;">Timer</h1> |
| 46 | + <div id="timer-root"></div> |
| 47 | + </body> |
| 48 | + </html> |
| 49 | + `); |
| 50 | + |
| 51 | + const root = popup.document.getElementById('timer-root'); |
| 52 | + ReactDOM.render(<TimerComponent authUser={authUser} darkMode={darkMode} />, root); |
| 53 | + |
| 54 | + popup.onbeforeunload = () => { |
| 55 | + ReactDOM.unmountComponentAtNode(root); |
| 56 | + }; |
| 57 | + }; |
| 58 | + |
| 59 | + useEffect(() => { |
| 60 | + return () => { |
| 61 | + if (popupRef.current && !popupRef.current.closed) { |
| 62 | + popupRef.current.close(); |
| 63 | + } |
| 64 | + }; |
| 65 | + }, []); |
| 66 | + |
| 67 | + return ( |
| 68 | + <button |
| 69 | + type="button" |
| 70 | + onClick={openPopoutWindow} |
| 71 | + className={styles.btnDiv} |
| 72 | + aria-label="Open timer in new window" |
| 73 | + > |
| 74 | + <FaExternalLinkAlt |
| 75 | + className={cs(styles.transitionColor, styles.btn)} |
| 76 | + fontSize="1.5rem" |
| 77 | + title="Open timer in new window" |
| 78 | + /> |
| 79 | + </button> |
| 80 | + ); |
| 81 | +} |
| 82 | + |
| 83 | +export default TimerPopout; |
0 commit comments