Created
October 9, 2023 16:02
-
-
Save sartak/812da0480d1f85c2c07cd940d4d726f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext, useContext, useEffect, useState } from "react"; | |
import { type SpotlightActionData } from "@mantine/spotlight"; | |
type ContextValue = Array<SpotlightActionData>; | |
type ContextType = [ | |
ContextValue, | |
React.Dispatch<React.SetStateAction<ContextValue>> | |
]; | |
const Context = createContext<ContextType>([[], () => {}]); | |
export const useSpotlightAction = ( | |
builder: () => SpotlightActionData | null, | |
dependencies: Array<unknown> | |
): void => { | |
const [, setActions] = useContext(Context); | |
useEffect(() => { | |
const action = builder(); | |
if (!action) { | |
return; | |
} | |
setActions((acts) => [...acts, action]); | |
return () => { | |
setActions((acts) => acts.filter((act) => act !== action)); | |
}; | |
}, dependencies); | |
}; | |
export const useGetSpotlightActions = (): ContextValue => | |
useContext(Context)[0]; | |
export const WithSpotlightActions = ({ children }) => { | |
const [actions, setActions] = useState<ContextValue>([]); | |
return ( | |
<Context.Provider value={[actions, setActions]}> | |
{children} | |
</Context.Provider> | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
useSpotlightAction(() => { | |
if (isToggled || !allowToggle) { | |
return null; | |
} | |
return { | |
id: "start-multi", | |
label: "Multiselect", | |
onClick: () => setToggled({}), | |
leftSection: ( | |
<IconListCheck | |
style={{ width: rem(24), height: rem(24) }} | |
stroke={1.5} | |
/> | |
), | |
}; | |
}, [isToggled, allowToggle]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment