1- import React , { memo , useCallback , useEffect } from "react" ;
2- import { useGlobals , useStorybookApi } from "@storybook/manager-api" ;
3- import { Icons , IconButton } from "@storybook/components" ;
4- import { ADDON_ID , PARAM_KEY , TOOL_ID } from "./constants" ;
1+ import React , { useState , MouseEvent } from "react" ;
2+ import { useParameter , useStorybookApi } from "@storybook/manager-api" ;
3+ import { IconButton } from "@storybook/components" ;
4+ import { PARAM_KEY , TOOL_ID } from "./constants" ;
5+ import CodeflowLogo from "./components/CodeflowLogo" ;
6+
7+ export const Tool = function MyAddonSelector ( ) {
8+ const repositoryUrl = useParameter < string > ( PARAM_KEY . REPO , null ) ;
9+ const branch = useParameter < string > ( PARAM_KEY . BRANCH , 'main' ) ;
10+ const filePath = useParameter < string > ( PARAM_KEY . FILE_PATH , null ) ;
511
6- export const Tool = memo ( function MyAddonSelector ( ) {
7- const [ globals , updateGlobals ] = useGlobals ( ) ;
812 const api = useStorybookApi ( ) ;
13+ const [ disabled , setDisabled ] = useState ( false )
14+
15+ const currentStory = api . getCurrentStoryData ( ) ;
916
10- const isActive = [ true , "true" ] . includes ( globals [ PARAM_KEY ] ) ;
17+ if ( ! currentStory ) {
18+ return null ;
19+ }
1120
12- const toggleMyTool = useCallback ( ( ) => {
13- updateGlobals ( {
14- [ PARAM_KEY ] : ! isActive ,
15- } ) ;
16- } , [ isActive ] ) ;
21+ if ( ! repositoryUrl && ! disabled ) {
22+ console . warn ( `"${ PARAM_KEY } " parameter not defined. Make sure to configure it in your story.` ) ;
23+ setDisabled ( true ) ;
24+ } else if ( repositoryUrl && disabled ) {
25+ setDisabled ( false ) ;
26+ }
1727
18- useEffect ( ( ) => {
19- api . setAddonShortcut ( ADDON_ID , {
20- label : "Toggle Measure [O]" ,
21- defaultShortcut : [ "O" ] ,
22- actionName : "outline" ,
23- showInMenu : false ,
24- action : toggleMyTool ,
25- } ) ;
26- } , [ toggleMyTool , api ] ) ;
28+ let stackblitzUrl = `https://pr.new/ ${ repositoryUrl } ` ;
29+ if ( filePath ) {
30+ stackblitzUrl = ` ${ stackblitzUrl } /blob/ ${ branch } / ${ filePath } ` ;
31+ /*
32+ * We've just addded `/` between all segments not caring if user already appended or prepanded them ,
33+ * so let's remove any possible double `//` (not preceded by `:` so we don't mess up the `https://`)
34+ */
35+ stackblitzUrl = stackblitzUrl . replaceAll ( / (?< ! : ) \/ \/ / g , '/' )
36+ }
2737
2838 return (
2939 < IconButton
40+ disabled = { disabled }
3041 key = { TOOL_ID }
31- active = { isActive }
32- title = "Enable my addon"
33- onClick = { toggleMyTool }
42+ href = { stackblitzUrl }
43+ onClick = { ( e : MouseEvent ) => disabled && e . preventDefault ( ) }
44+ target = "_blank"
45+ title = "Open in StackBlitz and make a pull request"
3446 >
35- < Icons icon = "lightning" />
47+ < CodeflowLogo style = { { width : 18 , margin : '0 -2px' } } />
3648 </ IconButton >
3749 ) ;
38- } ) ;
50+ } ;
0 commit comments