-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathuseFlag.ts
More file actions
79 lines (61 loc) · 1.81 KB
/
useFlag.ts
File metadata and controls
79 lines (61 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import qs from "qs";
import { useEffect, useState } from "react";
import { useKeyboardShortcut } from "@/utils/use-keyboard-shortcuts";
import { flag, FLAG_PREFIX } from "./flag";
import { FlagName } from "./types";
export default function useFlagValue(name: FlagName) {
const [flagValue, setFlag] = useState(() => flag(name));
useEffect(() => {
const handleChange = (changed: string) => {
if (changed === name) {
setFlag(flag(name));
}
};
flag.store.ee.on("change", handleChange);
return () => {
flag.store.removeListener("change", handleChange);
};
}, [setFlag, name]);
return flagValue;
}
export function useFlags() {
const [flags, setFlags] = useState(flag.list());
useEffect(() => {
const handleChange = () => {
setFlags(flag.list());
};
flag.store.ee.on("change", handleChange);
return () => {
flag.store.removeListener("change", handleChange);
};
}, [setFlags]);
return flags;
}
export const useDebugShortcut = (enable?: boolean) => {
useKeyboardShortcut(
{
keys: ["t", "d"],
ctrlKey: true,
},
(event) => {
event.preventDefault();
enable && addDebugFlag();
}
);
};
const addDebugFlag = () => {
const currentUrl = new URL(window.location.href);
const currentParams = qs.parse(currentUrl.search.substring(1));
const debugFlagKey = `${FLAG_PREFIX}debug`;
const hasDebugFlag = currentParams[debugFlagKey] === "true";
if (hasDebugFlag) {
delete currentParams[debugFlagKey];
} else {
currentParams[debugFlagKey] = "true";
}
const newSearch = qs.stringify(currentParams);
const newUrl = `${window.location.pathname}${newSearch ? `?${newSearch}` : ""}`;
window.history.pushState({}, "", newUrl);
const event = new Event("popstate");
window.dispatchEvent(event);
};