Skip to content

Instantly share code, notes, and snippets.

@sartak
Created October 9, 2023 16:02
Show Gist options
  • Save sartak/812da0480d1f85c2c07cd940d4d726f4 to your computer and use it in GitHub Desktop.
Save sartak/812da0480d1f85c2c07cd940d4d726f4 to your computer and use it in GitHub Desktop.
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>
);
};
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