1+ import { useContext , useEffect , useState } from 'react' ;
12import {
23 Disclosure ,
34 DisclosureButton ,
@@ -6,16 +7,17 @@ import {
67import { ChevronRightIcon } from '@heroicons/react/20/solid' ;
78import {
89 PlayIcon ,
10+ ShareIcon ,
911 TrashIcon ,
1012 CodeBracketIcon ,
1113 ClockIcon ,
1214} from '@heroicons/react/24/solid' ;
15+ import { compressToEncodedURIComponent } from 'lz-string' ;
1316import Spinner from 'components/Spinner' ;
1417import { AppContext } from 'context/AppContext' ;
1518import { AppActions } from 'context/Reducer' ;
16- import { CODE_SAMPLES } from 'helpers/const' ;
19+ import { CODE_SAMPLES , MAX_SHARE_CODE_LENGTH } from 'helpers/const' ;
1720import useCodeRunner from 'hooks/useCodeRunner' ;
18- import { useContext } from 'react' ;
1921
2022const codeSampleToMenu = CODE_SAMPLES . map ( sample => {
2123 const { codeSample, name } = sample ;
@@ -51,6 +53,23 @@ const actionBarItems: ActionBarItem[] = [
5153const ActionBar : React . FC = ( ) => {
5254 const { state, dispatch } = useContext ( AppContext ) ;
5355 const { runCode } = useCodeRunner ( ) ;
56+ const [ showShareButton , setShowShareButton ] = useState ( false ) ;
57+
58+ useEffect ( ( ) => {
59+ const { code } = state ;
60+ const showShareButton = code . length > 0 ;
61+ setShowShareButton ( showShareButton ) ;
62+ } , [ state . code . length ] ) ;
63+
64+ const onShareButtonClick = ( ) => {
65+ const compressedCode = compressToEncodedURIComponent ( state . code ) ;
66+ const shareUrl = `${ window . location . origin } /?code=${ compressedCode } ` ;
67+ if ( shareUrl . length > MAX_SHARE_CODE_LENGTH ) {
68+ alert ( 'The code is too long to share. Please reduce the code length.' ) ;
69+ return ;
70+ }
71+ dispatch ( { type : AppActions . SET_SHARE_URL , payload : shareUrl } ) ;
72+ } ;
5473
5574 return (
5675 < nav className = "flex flex-1 flex-col" >
@@ -113,6 +132,17 @@ const ActionBar: React.FC = () => {
113132 ) }
114133 </ li >
115134 ) ) }
135+ { showShareButton && (
136+ < li >
137+ < a
138+ onClick = { onShareButtonClick }
139+ className = "text-amber-400 hover:bg-gray-800 hover:amber-600 group flex gap-x-3 rounded-md p-2 text-sm/6 font-semibold cursor-pointer"
140+ >
141+ Share Code
142+ < ShareIcon aria-hidden = "true" className = "size-5 shrink-0" />
143+ </ a >
144+ </ li >
145+ ) }
116146 </ ul >
117147 </ li >
118148 < li className = "-mx-6 mt-auto" >
0 commit comments