1 | import * as React from "react";
|
2 | import {
|
3 | useSealedState,
|
4 | SealedInitialState,
|
5 | } from "reakit-utils/useSealedState";
|
6 | import { unstable_IdContext } from "./IdProvider";
|
7 |
|
8 | export type unstable_IdState = {
|
9 | |
10 |
|
11 |
|
12 | baseId: string;
|
13 | |
14 |
|
15 |
|
16 | unstable_idCountRef: React.MutableRefObject<number>;
|
17 | };
|
18 |
|
19 | export type unstable_IdActions = {
|
20 | |
21 |
|
22 |
|
23 | setBaseId: React.Dispatch<React.SetStateAction<string>>;
|
24 | };
|
25 |
|
26 | export type unstable_IdInitialState = Partial<Pick<unstable_IdState, "baseId">>;
|
27 |
|
28 | export type unstable_IdStateReturn = unstable_IdState & unstable_IdActions;
|
29 |
|
30 | export function unstable_useIdState(
|
31 | initialState: SealedInitialState<unstable_IdInitialState> = {}
|
32 | ): unstable_IdStateReturn {
|
33 | const { baseId: initialBaseId } = useSealedState(initialState);
|
34 | const generateId = React.useContext(unstable_IdContext);
|
35 | const idCountRef = React.useRef(0);
|
36 | const [baseId, setBaseId] = React.useState(
|
37 | () => initialBaseId || generateId()
|
38 | );
|
39 | return {
|
40 | baseId,
|
41 | setBaseId,
|
42 | unstable_idCountRef: idCountRef,
|
43 | };
|
44 | }
|