@equinor/cpl-feature-flag-react 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Equinor ASA
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ [<-- Go back](../../README.md)
2
+
3
+ # @equinor/cpl-feature-flag-react
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ yarn add @equinor/cpl-feature-flag-react
9
+ ```
@@ -0,0 +1,32 @@
1
+ import * as react from 'react';
2
+ import { PropsWithChildren } from 'react';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+
5
+ type BaseConfig<Key extends string, Env extends string> = Record<Key, Record<Env, boolean>>;
6
+ type inferFeatureFlagKey<T extends BaseConfig<string, string>> = keyof T;
7
+
8
+ interface Props<Key extends string, Env extends string> {
9
+ config: BaseConfig<Key, Env>;
10
+ /**
11
+ * Where to store feature flag override state. E.g. `localStorage` or `sessionStorage`.
12
+ *
13
+ * @default
14
+ * sessionStorage // implemented in a SSR safe way
15
+ */
16
+ storage?: Storage;
17
+ storageKey: string;
18
+ environments: Env[];
19
+ useCurrentEnvironment: () => string | undefined;
20
+ }
21
+ declare function buildFeatureFlagModule<Env extends string, Key extends string>({ config, storage, storageKey, environments, useCurrentEnvironment, }: Props<Key, Env>): {
22
+ FeatureFlagProvider: ({ children }: PropsWithChildren) => react_jsx_runtime.JSX.Element;
23
+ useFeatureFlagValue: (featureFlagKey: Key) => boolean;
24
+ useSetFeatureFlag: (featureFlagKey: Key) => (newValue: boolean) => void;
25
+ DevPanel: () => react_jsx_runtime.JSX.Element;
26
+ FeatureFlag: ({ featureFlagKey, showWhen, children, }: PropsWithChildren<{
27
+ showWhen: "enabled" | "disabled";
28
+ featureFlagKey: Key;
29
+ }>) => react.ReactNode;
30
+ };
31
+
32
+ export { buildFeatureFlagModule, type inferFeatureFlagKey };
@@ -0,0 +1,32 @@
1
+ import * as react from 'react';
2
+ import { PropsWithChildren } from 'react';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+
5
+ type BaseConfig<Key extends string, Env extends string> = Record<Key, Record<Env, boolean>>;
6
+ type inferFeatureFlagKey<T extends BaseConfig<string, string>> = keyof T;
7
+
8
+ interface Props<Key extends string, Env extends string> {
9
+ config: BaseConfig<Key, Env>;
10
+ /**
11
+ * Where to store feature flag override state. E.g. `localStorage` or `sessionStorage`.
12
+ *
13
+ * @default
14
+ * sessionStorage // implemented in a SSR safe way
15
+ */
16
+ storage?: Storage;
17
+ storageKey: string;
18
+ environments: Env[];
19
+ useCurrentEnvironment: () => string | undefined;
20
+ }
21
+ declare function buildFeatureFlagModule<Env extends string, Key extends string>({ config, storage, storageKey, environments, useCurrentEnvironment, }: Props<Key, Env>): {
22
+ FeatureFlagProvider: ({ children }: PropsWithChildren) => react_jsx_runtime.JSX.Element;
23
+ useFeatureFlagValue: (featureFlagKey: Key) => boolean;
24
+ useSetFeatureFlag: (featureFlagKey: Key) => (newValue: boolean) => void;
25
+ DevPanel: () => react_jsx_runtime.JSX.Element;
26
+ FeatureFlag: ({ featureFlagKey, showWhen, children, }: PropsWithChildren<{
27
+ showWhen: "enabled" | "disabled";
28
+ featureFlagKey: Key;
29
+ }>) => react.ReactNode;
30
+ };
31
+
32
+ export { buildFeatureFlagModule, type inferFeatureFlagKey };
package/dist/index.js ADDED
@@ -0,0 +1,336 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+
47
+ // src/index.ts
48
+ var index_exports = {};
49
+ __export(index_exports, {
50
+ buildFeatureFlagModule: () => buildFeatureFlagModule
51
+ });
52
+ module.exports = __toCommonJS(index_exports);
53
+
54
+ // src/buildFeatureFlagContext.tsx
55
+ var import_react = require("react");
56
+
57
+ // src/storageUtils.ts
58
+ function getClientStorage(storageType) {
59
+ if (typeof window === "undefined" || !(window[storageType] instanceof Storage)) {
60
+ return {
61
+ clear: () => void 0,
62
+ getItem: () => null,
63
+ key: () => null,
64
+ length: -1,
65
+ removeItem: () => void 0,
66
+ setItem: () => void 0
67
+ };
68
+ }
69
+ return window[storageType];
70
+ }
71
+ function removeStorageItemSafe(storage, storageKey) {
72
+ try {
73
+ storage.removeItem(storageKey);
74
+ } catch (error) {
75
+ console.error(error);
76
+ }
77
+ }
78
+ function getFeatureFlagConfigFromSessionStorage(storage, storageKey) {
79
+ const item = storage.getItem(storageKey);
80
+ if (!item) {
81
+ return void 0;
82
+ }
83
+ try {
84
+ const parsed = JSON.parse(item);
85
+ if (!parsed || typeof parsed !== "object") {
86
+ removeStorageItemSafe(storage, storageKey);
87
+ throw new Error(`Storage value is not of type object. Got '${parsed}'`);
88
+ }
89
+ const result = {};
90
+ for (const [featureFlagKey, value] of Object.entries(parsed)) {
91
+ if (typeof featureFlagKey !== "string") {
92
+ throw new Error(`featureFlagKey must be of type 'string'. Got '${featureFlagKey}'`);
93
+ }
94
+ if (typeof value !== "boolean") {
95
+ throw new Error(`Feature flag value must be a boolean. Got '${value}'`);
96
+ }
97
+ result[featureFlagKey] = value;
98
+ }
99
+ return result;
100
+ } catch (e) {
101
+ removeStorageItemSafe(storage, storageKey);
102
+ return void 0;
103
+ }
104
+ }
105
+ function setFeatureFlagValueInSessionStorage(storage, storageKey, featureFlagKey, value) {
106
+ if (typeof window === "undefined") {
107
+ return;
108
+ }
109
+ const featueFlagConfig = getFeatureFlagConfigFromSessionStorage(storage, storageKey);
110
+ storage.setItem(storageKey, JSON.stringify(__spreadProps(__spreadValues({}, featueFlagConfig), { [featureFlagKey]: value })));
111
+ }
112
+
113
+ // src/buildFeatureFlagContext.tsx
114
+ var import_jsx_runtime = require("react/jsx-runtime");
115
+ function buildFeatureFlagContext(storage, sessionStorageKey, config) {
116
+ const FeatureFlagContext = (0, import_react.createContext)(config);
117
+ const useFeatureFlagConfig = () => (0, import_react.useContext)(FeatureFlagContext);
118
+ const FeatureFlagDispatchContext = (0, import_react.createContext)(() => {
119
+ });
120
+ const useFeatureFlagDispatch = () => (0, import_react.useContext)(FeatureFlagDispatchContext);
121
+ const reducer = buildReducer(storage, sessionStorageKey);
122
+ const FeatureFlagProvider = ({ children }) => {
123
+ const [state, dispatch] = (0, import_react.useReducer)(reducer, config);
124
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FeatureFlagContext.Provider, { value: state, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FeatureFlagDispatchContext.Provider, { value: dispatch, children }) });
125
+ };
126
+ return {
127
+ useFeatureFlagConfig,
128
+ useFeatureFlagDispatch,
129
+ FeatureFlagProvider
130
+ };
131
+ }
132
+ function buildReducer(storage, storageKey) {
133
+ return function reducer(state, action) {
134
+ switch (action.type) {
135
+ case "update_feature_flag" /* UPDATE_FEATURE_FLAG */: {
136
+ setFeatureFlagValueInSessionStorage(
137
+ storage,
138
+ storageKey,
139
+ action.featureFlagKey,
140
+ action.value
141
+ );
142
+ return __spreadProps(__spreadValues({}, state), {
143
+ [action.featureFlagKey]: __spreadProps(__spreadValues({}, state[action.featureFlagKey]), {
144
+ [action.env]: action.value
145
+ })
146
+ });
147
+ }
148
+ default: {
149
+ return state;
150
+ }
151
+ }
152
+ };
153
+ }
154
+
155
+ // src/components/buildDevPanel.tsx
156
+ var import_eds_core_react2 = require("@equinor/eds-core-react");
157
+ var import_react3 = require("react");
158
+ var import_styled_components2 = __toESM(require("styled-components"));
159
+
160
+ // src/components/FeatureFlagItem.tsx
161
+ var import_eds_core_react = require("@equinor/eds-core-react");
162
+ var import_react2 = require("react");
163
+ var import_styled_components = __toESM(require("styled-components"));
164
+ var import_jsx_runtime2 = require("react/jsx-runtime");
165
+ function FeatureFlagItem({
166
+ featureFlagKey,
167
+ useFeatureFlagValue,
168
+ useSetFeatureFlag
169
+ }) {
170
+ const value = useFeatureFlagValue(featureFlagKey);
171
+ const setValue = useSetFeatureFlag(featureFlagKey);
172
+ const handleChange = (0, import_react2.useCallback)(
173
+ (e) => {
174
+ setValue(e.target.checked);
175
+ },
176
+ [setValue]
177
+ );
178
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(StyledSwitch, { size: "small", checked: value, onChange: handleChange, label: featureFlagKey });
179
+ }
180
+ var StyledSwitch = (0, import_styled_components.default)(import_eds_core_react.Switch)`
181
+ gap: 4px;
182
+ `;
183
+
184
+ // src/components/buildDevPanel.tsx
185
+ var import_jsx_runtime3 = require("react/jsx-runtime");
186
+ function DevPanelPure({
187
+ useFeatureFlagConfig,
188
+ useCurrentEnvironment,
189
+ useFeatureFlagValue,
190
+ useSetFeatureFlag
191
+ }) {
192
+ const [isOpen, setIsOpen] = (0, import_react3.useState)(false);
193
+ const handleToggle = (0, import_react3.useCallback)(() => {
194
+ setIsOpen((old) => !old);
195
+ }, []);
196
+ const handleClose = (0, import_react3.useCallback)(() => {
197
+ setIsOpen(false);
198
+ }, []);
199
+ const buttonRef = (0, import_react3.useRef)(null);
200
+ const featureFlagConfig = useFeatureFlagConfig();
201
+ const featureFlagKeys = (0, import_react3.useMemo)(() => {
202
+ return Object.keys(featureFlagConfig);
203
+ }, [featureFlagConfig]);
204
+ const currentEnvironment = useCurrentEnvironment();
205
+ if (!currentEnvironment || currentEnvironment !== "dev") {
206
+ return null;
207
+ }
208
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_eds_core_react2.EdsProvider, { density: "compact", children: [
209
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(FixedWrapper, { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
210
+ import_eds_core_react2.Button,
211
+ {
212
+ "aria-haspopup": true,
213
+ color: "secondary",
214
+ "aria-expanded": isOpen,
215
+ ref: buttonRef,
216
+ onClick: handleToggle,
217
+ children: "DEV PANEL"
218
+ }
219
+ ) }),
220
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_eds_core_react2.Popover, { open: isOpen, anchorEl: buttonRef.current, onClose: handleClose, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(StyledPopoverContent, { children: [
221
+ featureFlagKeys.map((featureFlagKey) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
222
+ FeatureFlagItem,
223
+ {
224
+ featureFlagKey,
225
+ useFeatureFlagValue,
226
+ useSetFeatureFlag
227
+ },
228
+ `feature-flag-item-${featureFlagKey}`
229
+ )),
230
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
231
+ import_eds_core_react2.Button,
232
+ {
233
+ variant: "ghost",
234
+ color: "danger",
235
+ onClick: () => {
236
+ localStorage.clear();
237
+ sessionStorage.clear();
238
+ window.location.reload();
239
+ },
240
+ children: "Delete cache and reload"
241
+ }
242
+ )
243
+ ] }) })
244
+ ] }) });
245
+ }
246
+ var StyledPopoverContent = (0, import_styled_components2.default)(import_eds_core_react2.Popover.Content)`
247
+ display: flex;
248
+ flex-direction: column;
249
+ `;
250
+ var FixedWrapper = import_styled_components2.default.div`
251
+ position: fixed;
252
+ bottom: 0;
253
+ left: 0;
254
+ padding: 8px;
255
+ width: 100%;
256
+ z-index: 1;
257
+
258
+ display: flex;
259
+ justify-content: center;
260
+ `;
261
+
262
+ // src/utils.ts
263
+ function isValidEnvironment(validEnvironments, environmentToValidate) {
264
+ return typeof environmentToValidate === "string" && validEnvironments.includes(environmentToValidate);
265
+ }
266
+
267
+ // src/buildFeatureFlagModule.tsx
268
+ var import_jsx_runtime4 = require("react/jsx-runtime");
269
+ function buildFeatureFlagModule({
270
+ config,
271
+ storage = getClientStorage("sessionStorage"),
272
+ storageKey,
273
+ environments,
274
+ useCurrentEnvironment
275
+ }) {
276
+ const { FeatureFlagProvider, useFeatureFlagConfig, useFeatureFlagDispatch } = buildFeatureFlagContext(storage, storageKey, config);
277
+ const useFeatureFlagValue = (featureFlagKey) => {
278
+ const currentEnvironment = useCurrentEnvironment();
279
+ const featureFlagConfig = useFeatureFlagConfig();
280
+ if (!isValidEnvironment(environments, currentEnvironment)) {
281
+ return false;
282
+ }
283
+ return Boolean(featureFlagConfig[featureFlagKey][currentEnvironment]);
284
+ };
285
+ function FeatureFlag({
286
+ featureFlagKey,
287
+ showWhen,
288
+ children
289
+ }) {
290
+ const enabled = useFeatureFlagValue(featureFlagKey);
291
+ if (showWhen === "enabled" && !enabled) {
292
+ return null;
293
+ }
294
+ if (showWhen === "disabled" && enabled) {
295
+ return null;
296
+ }
297
+ return children;
298
+ }
299
+ const useSetFeatureFlag = (featureFlagKey) => {
300
+ const currentEnvironment = useCurrentEnvironment();
301
+ const featureFlagDispatch = useFeatureFlagDispatch();
302
+ return (newValue) => {
303
+ if (!isValidEnvironment(environments, currentEnvironment)) {
304
+ return;
305
+ }
306
+ featureFlagDispatch({
307
+ type: "update_feature_flag" /* UPDATE_FEATURE_FLAG */,
308
+ env: currentEnvironment,
309
+ featureFlagKey,
310
+ value: newValue
311
+ });
312
+ };
313
+ };
314
+ const DevPanel = () => {
315
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
316
+ DevPanelPure,
317
+ {
318
+ useCurrentEnvironment,
319
+ useFeatureFlagConfig,
320
+ useFeatureFlagValue,
321
+ useSetFeatureFlag
322
+ }
323
+ );
324
+ };
325
+ return {
326
+ FeatureFlagProvider,
327
+ useFeatureFlagValue,
328
+ useSetFeatureFlag,
329
+ DevPanel,
330
+ FeatureFlag
331
+ };
332
+ }
333
+ // Annotate the CommonJS export names for ESM import in node:
334
+ 0 && (module.exports = {
335
+ buildFeatureFlagModule
336
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,302 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+
21
+ // src/buildFeatureFlagContext.tsx
22
+ import { createContext, useContext, useReducer } from "react";
23
+
24
+ // src/storageUtils.ts
25
+ function getClientStorage(storageType) {
26
+ if (typeof window === "undefined" || !(window[storageType] instanceof Storage)) {
27
+ return {
28
+ clear: () => void 0,
29
+ getItem: () => null,
30
+ key: () => null,
31
+ length: -1,
32
+ removeItem: () => void 0,
33
+ setItem: () => void 0
34
+ };
35
+ }
36
+ return window[storageType];
37
+ }
38
+ function removeStorageItemSafe(storage, storageKey) {
39
+ try {
40
+ storage.removeItem(storageKey);
41
+ } catch (error) {
42
+ console.error(error);
43
+ }
44
+ }
45
+ function getFeatureFlagConfigFromSessionStorage(storage, storageKey) {
46
+ const item = storage.getItem(storageKey);
47
+ if (!item) {
48
+ return void 0;
49
+ }
50
+ try {
51
+ const parsed = JSON.parse(item);
52
+ if (!parsed || typeof parsed !== "object") {
53
+ removeStorageItemSafe(storage, storageKey);
54
+ throw new Error(`Storage value is not of type object. Got '${parsed}'`);
55
+ }
56
+ const result = {};
57
+ for (const [featureFlagKey, value] of Object.entries(parsed)) {
58
+ if (typeof featureFlagKey !== "string") {
59
+ throw new Error(`featureFlagKey must be of type 'string'. Got '${featureFlagKey}'`);
60
+ }
61
+ if (typeof value !== "boolean") {
62
+ throw new Error(`Feature flag value must be a boolean. Got '${value}'`);
63
+ }
64
+ result[featureFlagKey] = value;
65
+ }
66
+ return result;
67
+ } catch (e) {
68
+ removeStorageItemSafe(storage, storageKey);
69
+ return void 0;
70
+ }
71
+ }
72
+ function setFeatureFlagValueInSessionStorage(storage, storageKey, featureFlagKey, value) {
73
+ if (typeof window === "undefined") {
74
+ return;
75
+ }
76
+ const featueFlagConfig = getFeatureFlagConfigFromSessionStorage(storage, storageKey);
77
+ storage.setItem(storageKey, JSON.stringify(__spreadProps(__spreadValues({}, featueFlagConfig), { [featureFlagKey]: value })));
78
+ }
79
+
80
+ // src/buildFeatureFlagContext.tsx
81
+ import { jsx } from "react/jsx-runtime";
82
+ function buildFeatureFlagContext(storage, sessionStorageKey, config) {
83
+ const FeatureFlagContext = createContext(config);
84
+ const useFeatureFlagConfig = () => useContext(FeatureFlagContext);
85
+ const FeatureFlagDispatchContext = createContext(() => {
86
+ });
87
+ const useFeatureFlagDispatch = () => useContext(FeatureFlagDispatchContext);
88
+ const reducer = buildReducer(storage, sessionStorageKey);
89
+ const FeatureFlagProvider = ({ children }) => {
90
+ const [state, dispatch] = useReducer(reducer, config);
91
+ return /* @__PURE__ */ jsx(FeatureFlagContext.Provider, { value: state, children: /* @__PURE__ */ jsx(FeatureFlagDispatchContext.Provider, { value: dispatch, children }) });
92
+ };
93
+ return {
94
+ useFeatureFlagConfig,
95
+ useFeatureFlagDispatch,
96
+ FeatureFlagProvider
97
+ };
98
+ }
99
+ function buildReducer(storage, storageKey) {
100
+ return function reducer(state, action) {
101
+ switch (action.type) {
102
+ case "update_feature_flag" /* UPDATE_FEATURE_FLAG */: {
103
+ setFeatureFlagValueInSessionStorage(
104
+ storage,
105
+ storageKey,
106
+ action.featureFlagKey,
107
+ action.value
108
+ );
109
+ return __spreadProps(__spreadValues({}, state), {
110
+ [action.featureFlagKey]: __spreadProps(__spreadValues({}, state[action.featureFlagKey]), {
111
+ [action.env]: action.value
112
+ })
113
+ });
114
+ }
115
+ default: {
116
+ return state;
117
+ }
118
+ }
119
+ };
120
+ }
121
+
122
+ // src/components/buildDevPanel.tsx
123
+ import { Button, EdsProvider, Popover } from "@equinor/eds-core-react";
124
+ import { useCallback as useCallback2, useMemo, useRef, useState } from "react";
125
+ import styled2 from "styled-components";
126
+
127
+ // src/components/FeatureFlagItem.tsx
128
+ import { Switch } from "@equinor/eds-core-react";
129
+ import { useCallback } from "react";
130
+ import styled from "styled-components";
131
+ import { jsx as jsx2 } from "react/jsx-runtime";
132
+ function FeatureFlagItem({
133
+ featureFlagKey,
134
+ useFeatureFlagValue,
135
+ useSetFeatureFlag
136
+ }) {
137
+ const value = useFeatureFlagValue(featureFlagKey);
138
+ const setValue = useSetFeatureFlag(featureFlagKey);
139
+ const handleChange = useCallback(
140
+ (e) => {
141
+ setValue(e.target.checked);
142
+ },
143
+ [setValue]
144
+ );
145
+ return /* @__PURE__ */ jsx2(StyledSwitch, { size: "small", checked: value, onChange: handleChange, label: featureFlagKey });
146
+ }
147
+ var StyledSwitch = styled(Switch)`
148
+ gap: 4px;
149
+ `;
150
+
151
+ // src/components/buildDevPanel.tsx
152
+ import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
153
+ function DevPanelPure({
154
+ useFeatureFlagConfig,
155
+ useCurrentEnvironment,
156
+ useFeatureFlagValue,
157
+ useSetFeatureFlag
158
+ }) {
159
+ const [isOpen, setIsOpen] = useState(false);
160
+ const handleToggle = useCallback2(() => {
161
+ setIsOpen((old) => !old);
162
+ }, []);
163
+ const handleClose = useCallback2(() => {
164
+ setIsOpen(false);
165
+ }, []);
166
+ const buttonRef = useRef(null);
167
+ const featureFlagConfig = useFeatureFlagConfig();
168
+ const featureFlagKeys = useMemo(() => {
169
+ return Object.keys(featureFlagConfig);
170
+ }, [featureFlagConfig]);
171
+ const currentEnvironment = useCurrentEnvironment();
172
+ if (!currentEnvironment || currentEnvironment !== "dev") {
173
+ return null;
174
+ }
175
+ return /* @__PURE__ */ jsx3(Fragment, { children: /* @__PURE__ */ jsxs(EdsProvider, { density: "compact", children: [
176
+ /* @__PURE__ */ jsx3(FixedWrapper, { children: /* @__PURE__ */ jsx3(
177
+ Button,
178
+ {
179
+ "aria-haspopup": true,
180
+ color: "secondary",
181
+ "aria-expanded": isOpen,
182
+ ref: buttonRef,
183
+ onClick: handleToggle,
184
+ children: "DEV PANEL"
185
+ }
186
+ ) }),
187
+ /* @__PURE__ */ jsx3(Popover, { open: isOpen, anchorEl: buttonRef.current, onClose: handleClose, children: /* @__PURE__ */ jsxs(StyledPopoverContent, { children: [
188
+ featureFlagKeys.map((featureFlagKey) => /* @__PURE__ */ jsx3(
189
+ FeatureFlagItem,
190
+ {
191
+ featureFlagKey,
192
+ useFeatureFlagValue,
193
+ useSetFeatureFlag
194
+ },
195
+ `feature-flag-item-${featureFlagKey}`
196
+ )),
197
+ /* @__PURE__ */ jsx3(
198
+ Button,
199
+ {
200
+ variant: "ghost",
201
+ color: "danger",
202
+ onClick: () => {
203
+ localStorage.clear();
204
+ sessionStorage.clear();
205
+ window.location.reload();
206
+ },
207
+ children: "Delete cache and reload"
208
+ }
209
+ )
210
+ ] }) })
211
+ ] }) });
212
+ }
213
+ var StyledPopoverContent = styled2(Popover.Content)`
214
+ display: flex;
215
+ flex-direction: column;
216
+ `;
217
+ var FixedWrapper = styled2.div`
218
+ position: fixed;
219
+ bottom: 0;
220
+ left: 0;
221
+ padding: 8px;
222
+ width: 100%;
223
+ z-index: 1;
224
+
225
+ display: flex;
226
+ justify-content: center;
227
+ `;
228
+
229
+ // src/utils.ts
230
+ function isValidEnvironment(validEnvironments, environmentToValidate) {
231
+ return typeof environmentToValidate === "string" && validEnvironments.includes(environmentToValidate);
232
+ }
233
+
234
+ // src/buildFeatureFlagModule.tsx
235
+ import { jsx as jsx4 } from "react/jsx-runtime";
236
+ function buildFeatureFlagModule({
237
+ config,
238
+ storage = getClientStorage("sessionStorage"),
239
+ storageKey,
240
+ environments,
241
+ useCurrentEnvironment
242
+ }) {
243
+ const { FeatureFlagProvider, useFeatureFlagConfig, useFeatureFlagDispatch } = buildFeatureFlagContext(storage, storageKey, config);
244
+ const useFeatureFlagValue = (featureFlagKey) => {
245
+ const currentEnvironment = useCurrentEnvironment();
246
+ const featureFlagConfig = useFeatureFlagConfig();
247
+ if (!isValidEnvironment(environments, currentEnvironment)) {
248
+ return false;
249
+ }
250
+ return Boolean(featureFlagConfig[featureFlagKey][currentEnvironment]);
251
+ };
252
+ function FeatureFlag({
253
+ featureFlagKey,
254
+ showWhen,
255
+ children
256
+ }) {
257
+ const enabled = useFeatureFlagValue(featureFlagKey);
258
+ if (showWhen === "enabled" && !enabled) {
259
+ return null;
260
+ }
261
+ if (showWhen === "disabled" && enabled) {
262
+ return null;
263
+ }
264
+ return children;
265
+ }
266
+ const useSetFeatureFlag = (featureFlagKey) => {
267
+ const currentEnvironment = useCurrentEnvironment();
268
+ const featureFlagDispatch = useFeatureFlagDispatch();
269
+ return (newValue) => {
270
+ if (!isValidEnvironment(environments, currentEnvironment)) {
271
+ return;
272
+ }
273
+ featureFlagDispatch({
274
+ type: "update_feature_flag" /* UPDATE_FEATURE_FLAG */,
275
+ env: currentEnvironment,
276
+ featureFlagKey,
277
+ value: newValue
278
+ });
279
+ };
280
+ };
281
+ const DevPanel = () => {
282
+ return /* @__PURE__ */ jsx4(
283
+ DevPanelPure,
284
+ {
285
+ useCurrentEnvironment,
286
+ useFeatureFlagConfig,
287
+ useFeatureFlagValue,
288
+ useSetFeatureFlag
289
+ }
290
+ );
291
+ };
292
+ return {
293
+ FeatureFlagProvider,
294
+ useFeatureFlagValue,
295
+ useSetFeatureFlag,
296
+ DevPanel,
297
+ FeatureFlag
298
+ };
299
+ }
300
+ export {
301
+ buildFeatureFlagModule
302
+ };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@equinor/cpl-feature-flag-react",
3
+ "version": "0.0.1",
4
+ "license": "MIT",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist/**"
10
+ ],
11
+ "dependencies": {},
12
+ "devDependencies": {
13
+ "@equinor/eds-core-react": "^0.42.5",
14
+ "@storybook/react": "^8.6.14",
15
+ "@storybook/test": "^8.6.14",
16
+ "@types/react": "^18.3.18",
17
+ "@types/react-dom": "^18.3.5",
18
+ "@types/styled-components": "^5.1.34",
19
+ "eslint": "^9.21.0",
20
+ "react": "^18.2.0",
21
+ "react-dom": "^18.2.0",
22
+ "styled-components": "^6.1.14",
23
+ "tsup": "^8.3.6",
24
+ "@equinor/cpl-eslint-config": "0.0.8",
25
+ "@equinor/cpl-typescript-config": "0.0.2"
26
+ },
27
+ "peerDependencies": {
28
+ "@equinor/eds-core-react": ">=0.42.1",
29
+ "react": ">=18.2.0",
30
+ "react-dom": ">=18.2.0",
31
+ "styled-components": ">=5.3.11"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "build": "tsup src/index.ts --format esm,cjs --dts --external react",
38
+ "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist",
39
+ "dev": "tsup src/index.ts --format esm,cjs --watch --dts --external react",
40
+ "lint": "TIMING=1 eslint . --fix",
41
+ "typecheck": "tsc --noEmit"
42
+ }
43
+ }