35 lines
889 B
TypeScript
35 lines
889 B
TypeScript
import {
|
|
createContext,
|
|
createSelector,
|
|
createSignal,
|
|
useContext,
|
|
type Accessor,
|
|
} from "solid-js";
|
|
|
|
export type ItemSelectionState<T> = [(value: T) => boolean, (value: T) => void];
|
|
|
|
const ItemSelectionContext = /* @__PURE__ */ createContext<
|
|
ItemSelectionState<any>
|
|
>([() => false, () => undefined]);
|
|
|
|
export function createSingluarItemSelection<T extends {}>(
|
|
intial?: T,
|
|
): readonly [Accessor<T | undefined>, ItemSelectionState<T | undefined>] {
|
|
const [value, setValue] = createSignal<T | undefined>(intial);
|
|
|
|
const select = createSelector(value, (a, b) =>
|
|
typeof b !== "undefined" ? a === b : false,
|
|
);
|
|
|
|
const toggle = (v: T | undefined) => {
|
|
setValue((o) => (o ? undefined : v));
|
|
};
|
|
|
|
return [value, [select, toggle]];
|
|
}
|
|
|
|
export function useItemSelection() {
|
|
return useContext(ItemSelectionContext);
|
|
}
|
|
|
|
export default ItemSelectionContext.Provider;
|