Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use rtk for flags #2478

Merged
merged 2 commits into from
Dec 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ui/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export default {

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: {
"^~/(.*)$": "<rootDir>/src/$1"
'^~/(.*)$': '<rootDir>/src/$1'
},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
Expand Down
22 changes: 0 additions & 22 deletions ui/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
"react-helmet": "^6.1.0",
"react-redux": "^8.1.3",
"react-router-dom": "^6.19.0",
"swr": "^2.2.4",
"tailwind-merge": "^1.14.0",
"uuid": "^9.0.1",
"yup": "^0.32.11"
Expand Down
18 changes: 3 additions & 15 deletions ui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { useEffect, useState } from 'react';
import { Helmet } from 'react-helmet';
import { useSelector } from 'react-redux';
import { createHashRouter, RouterProvider } from 'react-router-dom';
import { SWRConfig } from 'swr';
import ErrorLayout from './app/ErrorLayout';
import Flag from './app/flags/Flag';
import NewFlag from './app/flags/NewFlag';
Expand All @@ -14,7 +13,6 @@ import { selectTheme } from './app/preferences/preferencesSlice';
import NewSegment from './app/segments/NewSegment';
import Segment from './app/segments/Segment';
import SessionProvider from './components/SessionProvider';
import { request } from './data/api';
import { Theme } from './types/Preferences';
const Flags = loadable(() => import('./app/flags/Flags'));
const Variants = loadable(() => import('./app/flags/variants/Variants'));
Expand Down Expand Up @@ -131,10 +129,6 @@ const router = createHashRouter([
}
]);

const fetcher = async (uri: String) => {
return request('GET', '/api/v1' + uri);
};

export default function App() {
const theme = useSelector(selectTheme);
const [systemPrefersDark, setSystemPrefersDark] = useState(
Expand Down Expand Up @@ -164,15 +158,9 @@ export default function App() {
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script dangerouslySetInnerHTML={{ __html: nightwind.init() }} />
</Helmet>
<SWRConfig
value={{
fetcher
}}
>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</SWRConfig>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</>
);
}
67 changes: 26 additions & 41 deletions ui/src/app/console/Console.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,19 @@ import { Form, Formik, useFormikContext } from 'formik';
import hljs from 'highlight.js';
import javascript from 'highlight.js/lib/languages/json';
import 'highlight.js/styles/tomorrow-night-bright.css';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { v4 as uuidv4 } from 'uuid';
import * as Yup from 'yup';
import { useListFlagsQuery } from '~/app/flags/flagsApi';
import { selectCurrentNamespace } from '~/app/namespaces/namespacesSlice';
import { ContextEditor } from '~/components/console/ContextEditor';
import EmptyState from '~/components/EmptyState';
import Button from '~/components/forms/buttons/Button';
import Combobox from '~/components/forms/Combobox';
import Input from '~/components/forms/Input';
import {
evaluateURL,
evaluateV2,
listAuthMethods,
listFlags
} from '~/data/api';
import { evaluateURL, evaluateV2, listAuthMethods } from '~/data/api';
import { useError } from '~/data/hooks/error';
import { useSuccess } from '~/data/hooks/success';
import {
Expand All @@ -28,13 +24,7 @@ import {
requiredValidation
} from '~/data/validations';
import { IAuthMethod, IAuthMethodList } from '~/types/Auth';
import {
FilterableFlag,
FlagType,
flagTypeToLabel,
IFlag,
IFlagList
} from '~/types/Flag';
import { FilterableFlag, FlagType, flagTypeToLabel, IFlag } from '~/types/Flag';
import { INamespace } from '~/types/Namespace';
import {
classNames,
Expand Down Expand Up @@ -62,7 +52,6 @@ interface ConsoleFormValues {
}

export default function Console() {
const [flags, setFlags] = useState<FilterableFlag[]>([]);
const [selectedFlag, setSelectedFlag] = useState<FilterableFlag | null>(null);
const [response, setResponse] = useState<string | null>(null);
const [hasEvaluationError, setHasEvaluationError] = useState<boolean>(false);
Expand All @@ -76,23 +65,29 @@ export default function Console() {

const codeRef = useRef<HTMLElement>(null);

const loadData = useCallback(async () => {
const initialFlagList = (await listFlags(namespace.key)) as IFlagList;
const { flags } = initialFlagList;
const { data, error } = useListFlagsQuery(namespace.key);

setFlags(
flags.map((flag) => {
const status = flag.enabled ? 'active' : 'inactive';
useEffect(() => {
if (error) {
setError(error);
return;
}
clearError();
}, [clearError, error, setError]);

return {
...flag,
status,
filterValue: flag.key,
displayValue: `${flag.name} | ${flagTypeToLabel(flag.type)}`
};
})
);
}, [namespace.key]);
const flags = useMemo(() => {
const initialFlags = data?.flags || [];
return initialFlags.map((flag) => {
const status = flag.enabled ? 'active' : 'inactive';

return {
...flag,
status: status as 'active' | 'inactive',
filterValue: flag.key,
displayValue: `${flag.name} | ${flagTypeToLabel(flag.type)}`
};
});
}, [data]);

const checkIsAuthRequired = useCallback(() => {
listAuthMethods()
Expand Down Expand Up @@ -176,9 +171,7 @@ export default function Console() {

copyTextToClipboard(command);

setSuccess(
'Command copied to clipboard'
);
setSuccess('Command copied to clipboard');
};

useEffect(() => {
Expand All @@ -190,14 +183,6 @@ export default function Console() {
hljs.highlightAll();
}, [response, codeRef]);

useEffect(() => {
loadData()
.then(() => clearError())
.catch((err) => {
setError(err);
});
}, [clearError, loadData, setError]);

useEffect(() => {
checkIsAuthRequired();
}, [checkIsAuthRequired]);
Expand Down
79 changes: 38 additions & 41 deletions ui/src/app/flags/Flag.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
TrashIcon
} from '@heroicons/react/24/outline';
import { formatDistanceToNowStrict, parseISO } from 'date-fns';
import { useEffect, useState } from 'react';
import { useState } from 'react';
import { useSelector } from 'react-redux';
import { NavLink, Outlet, useNavigate, useParams } from 'react-router-dom';
import { selectReadonly } from '~/app/meta/metaSlice';
Expand All @@ -20,60 +20,58 @@ import MoreInfo from '~/components/MoreInfo';
import CopyToNamespacePanel from '~/components/panels/CopyToNamespacePanel';
import DeletePanel from '~/components/panels/DeletePanel';
import { useError } from '~/data/hooks/error';
import { useAppDispatch } from '~/data/hooks/store';
import { useSuccess } from '~/data/hooks/success';
import { useTimezone } from '~/data/hooks/timezone';
import { RootState } from '~/store';
import { FlagType } from '~/types/Flag';
import { classNames } from '~/utils/helpers';
import {
copyFlagAsync,
deleteFlagAsync,
fetchFlagAsync,
selectFlag
} from './flagsSlice';
useCopyFlagMutation,
useDeleteFlagMutation,
useGetFlagQuery
} from './flagsApi';
import Rollouts from './rollouts/Rollouts';

const tabs = [
{ name: 'Variants', to: '' },
{ name: 'Rules', to: 'rules' }
];

export default function Flag() {
let { flagKey } = useParams();
const { inTimezone } = useTimezone();

const [showDeleteFlagModal, setShowDeleteFlagModal] = useState(false);
const [showCopyFlagModal, setShowCopyFlagModal] = useState(false);

const { setError, clearError } = useError();
const { setSuccess } = useSuccess();

const navigate = useNavigate();
const dispatch = useAppDispatch();

const namespaces = useSelector(selectNamespaces);
const namespace = useSelector(selectCurrentNamespace);
const readOnly = useSelector(selectReadonly);

const flag = useSelector((state: RootState) =>
selectFlag(state, flagKey || '')
);

const [showDeleteFlagModal, setShowDeleteFlagModal] = useState(false);
const [showCopyFlagModal, setShowCopyFlagModal] = useState(false);

const tabs = [
{ name: 'Variants', to: '' },
{ name: 'Rules', to: 'rules' }
];
const {
data: flag,
error,
isLoading,
isError
} = useGetFlagQuery({
namespaceKey: namespace.key,
flagKey: flagKey || ''
});

useEffect(() => {
if (!namespace.key || !flagKey) return;
const [deleteFlag] = useDeleteFlagMutation();
const [copyFlag] = useCopyFlagMutation();

dispatch(fetchFlagAsync({ namespaceKey: namespace.key, key: flagKey }))
.unwrap()
.then(() => {
clearError();
})
.catch((err) => {
setError(err);
});
}, [flagKey, namespace.key, clearError, setError, dispatch]);
if (isError) {
setError(error);
}

if (!flag || flag.key != flagKey) return <Loading />;
if (isLoading || !flag) {
return <Loading />;
}

return (
<>
Expand All @@ -90,9 +88,10 @@ export default function Flag() {
panelType="Flag"
setOpen={setShowDeleteFlagModal}
handleDelete={() =>
dispatch(
deleteFlagAsync({ namespaceKey: namespace.key, key: flag.key })
)
deleteFlag({
namespaceKey: namespace.key,
flagKey: flag.key
}).unwrap()
}
onSuccess={() => {
navigate(`/namespaces/${namespace.key}/flags`);
Expand All @@ -113,12 +112,10 @@ export default function Flag() {
panelType="Flag"
setOpen={setShowCopyFlagModal}
handleCopy={(namespaceKey: string) =>
dispatch(
copyFlagAsync({
from: { namespaceKey: namespace.key, key: flag.key },
to: { namespaceKey: namespaceKey, key: flag.key }
})
)
copyFlag({
from: { namespaceKey: namespace.key, flagKey: flag.key },
to: { namespaceKey: namespaceKey, flagKey: flag.key }
}).unwrap()
}
onSuccess={() => {
clearError();
Expand Down
6 changes: 0 additions & 6 deletions ui/src/app/flags/FlagProps.ts

This file was deleted.

8 changes: 3 additions & 5 deletions ui/src/app/flags/Flags.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,20 @@ import { PlusIcon } from '@heroicons/react/24/outline';
import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import useSWR from 'swr';
import { selectReadonly } from '~/app/meta/metaSlice';
import { selectCurrentNamespace } from '~/app/namespaces/namespacesSlice';
import EmptyState from '~/components/EmptyState';
import FlagTable from '~/components/flags/FlagTable';
import Button from '~/components/forms/buttons/Button';
import { useError } from '~/data/hooks/error';
import { IFlagList } from '~/types/Flag';
import { useListFlagsQuery } from './flagsApi';

export default function Flags() {
const namespace = useSelector(selectCurrentNamespace);
const path = `/namespaces/${namespace.key}/flags`;

const { data, error } = useSWR<IFlagList>(path);

const flags = data?.flags;
const { data, error } = useListFlagsQuery(namespace.key);
const flags = data?.flags || [];

const navigate = useNavigate();
const { setError, clearError } = useError();
Expand Down
Loading
Loading