ui(admin): add "working" React admin ui

This commit is contained in:
Matthew Penner 2022-12-15 19:06:14 -07:00
parent d1c7494933
commit 5402584508
No known key found for this signature in database
199 changed files with 13387 additions and 151 deletions

View file

@ -0,0 +1,107 @@
import type { FormikHelpers } from 'formik';
import { Form, Formik } from 'formik';
import { useState } from 'react';
import tw from 'twin.macro';
import { object, string } from 'yup';
import { getRoles, createRole } from '@/api/admin/roles';
import FlashMessageRender from '@/components/FlashMessageRender';
import Button from '@/components/elements/Button';
import Field from '@/components/elements/Field';
import Modal from '@/components/elements/Modal';
import useFlash from '@/plugins/useFlash';
interface Values {
name: string;
description: string;
}
const schema = object().shape({
name: string().required('A role name must be provided.').max(32, 'Role name must not exceed 32 characters.'),
description: string().max(255, 'Role description must not exceed 255 characters.'),
});
export default () => {
const [visible, setVisible] = useState(false);
const { clearFlashes, clearAndAddHttpError } = useFlash();
const { mutate } = getRoles();
const submit = ({ name, description }: Values, { setSubmitting }: FormikHelpers<Values>) => {
clearFlashes('role:create');
setSubmitting(true);
createRole(name, description)
.then(async role => {
await mutate(data => ({ ...data!, items: data!.items.concat(role) }), false);
setVisible(false);
})
.catch(error => {
clearAndAddHttpError({ key: 'role:create', error });
setSubmitting(false);
});
};
return (
<>
<Formik onSubmit={submit} initialValues={{ name: '', description: '' }} validationSchema={schema}>
{({ isSubmitting, resetForm }) => (
<Modal
visible={visible}
dismissable={!isSubmitting}
showSpinnerOverlay={isSubmitting}
onDismissed={() => {
resetForm();
setVisible(false);
}}
>
<FlashMessageRender byKey={'role:create'} css={tw`mb-6`} />
<h2 css={tw`mb-6 text-2xl text-neutral-100`}>New Role</h2>
<Form css={tw`m-0`}>
<Field
type={'text'}
id={'name'}
name={'name'}
label={'Name'}
description={'A short name used to identify this role.'}
autoFocus
/>
<div css={tw`mt-6`}>
<Field
type={'text'}
id={'description'}
name={'description'}
label={'Description'}
description={'A description for this role.'}
/>
</div>
<div css={tw`flex flex-wrap justify-end mt-6`}>
<Button
type={'button'}
isSecondary
css={tw`w-full sm:w-auto sm:mr-2`}
onClick={() => setVisible(false)}
>
Cancel
</Button>
<Button css={tw`w-full mt-4 sm:w-auto sm:mt-0`} type={'submit'}>
Create Role
</Button>
</div>
</Form>
</Modal>
)}
</Formik>
<Button
type={'button'}
size={'large'}
css={tw`h-10 px-4 py-0 whitespace-nowrap`}
onClick={() => setVisible(true)}
>
New Role
</Button>
</>
);
};

View file

@ -0,0 +1,73 @@
import type { Actions } from 'easy-peasy';
import { useStoreActions } from 'easy-peasy';
import { useState } from 'react';
import tw from 'twin.macro';
import { deleteRole } from '@/api/admin/roles';
import Button from '@/components/elements/Button';
import ConfirmationModal from '@/components/elements/ConfirmationModal';
import type { ApplicationStore } from '@/state';
interface Props {
roleId: number;
onDeleted: () => void;
}
export default ({ roleId, onDeleted }: Props) => {
const [visible, setVisible] = useState(false);
const [loading, setLoading] = useState(false);
const { clearFlashes, clearAndAddHttpError } = useStoreActions(
(actions: Actions<ApplicationStore>) => actions.flashes,
);
const onDelete = () => {
setLoading(true);
clearFlashes('role');
deleteRole(roleId)
.then(() => {
setLoading(false);
onDeleted();
})
.catch(error => {
console.error(error);
clearAndAddHttpError({ key: 'role', error });
setLoading(false);
setVisible(false);
});
};
return (
<>
<ConfirmationModal
visible={visible}
title={'Delete role?'}
buttonText={'Yes, delete role'}
onConfirmed={onDelete}
showSpinnerOverlay={loading}
onModalDismissed={() => setVisible(false)}
>
Are you sure you want to delete this role?
</ConfirmationModal>
<Button type={'button'} size={'xsmall'} color={'red'} onClick={() => setVisible(true)}>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
css={tw`h-5 w-5`}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
</Button>
</>
);
};

View file

@ -0,0 +1,176 @@
import type { Action, Actions } from 'easy-peasy';
import { action, createContextStore, useStoreActions } from 'easy-peasy';
import type { FormikHelpers } from 'formik';
import { Form, Formik } from 'formik';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import tw from 'twin.macro';
import { object, string } from 'yup';
import { getRole, updateRole } from '@/api/admin/roles';
import FlashMessageRender from '@/components/FlashMessageRender';
import AdminBox from '@/components/admin/AdminBox';
import AdminContentBlock from '@/components/admin/AdminContentBlock';
import RoleDeleteButton from '@/components/admin/roles/RoleDeleteButton';
import Button from '@/components/elements/Button';
import Field from '@/components/elements/Field';
import Spinner from '@/components/elements/Spinner';
import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
import type { UserRole } from '@definitions/admin';
import type { ApplicationStore } from '@/state';
interface ctx {
role: UserRole | undefined;
setRole: Action<ctx, UserRole | undefined>;
}
export const Context = createContextStore<ctx>({
role: undefined,
setRole: action((state, payload) => {
state.role = payload;
}),
});
interface Values {
name: string;
description: string;
}
const EditInformationContainer = () => {
const navigate = useNavigate();
const { clearFlashes, clearAndAddHttpError } = useStoreActions(
(actions: Actions<ApplicationStore>) => actions.flashes,
);
const role = Context.useStoreState(state => state.role);
const setRole = Context.useStoreActions(actions => actions.setRole);
if (role === undefined) {
return <></>;
}
const submit = ({ name, description }: Values, { setSubmitting }: FormikHelpers<Values>) => {
clearFlashes('role');
updateRole(role.id, name, description)
.then(() => setRole({ ...role, name, description }))
.catch(error => {
console.error(error);
clearAndAddHttpError({ key: 'role', error });
})
.then(() => setSubmitting(false));
};
return (
<Formik
onSubmit={submit}
initialValues={{
name: role.name,
description: role.description || '',
}}
validationSchema={object().shape({
name: string().required().min(1),
description: string().max(255, ''),
})}
>
{({ isSubmitting, isValid }) => (
<>
<AdminBox title={'Edit Role'} css={tw`relative`}>
<SpinnerOverlay visible={isSubmitting} />
<Form css={tw`mb-0`}>
<div>
<Field id={'name'} name={'name'} label={'Name'} type={'text'} />
</div>
<div css={tw`mt-6`}>
<Field id={'description'} name={'description'} label={'description'} type={'text'} />
</div>
<div css={tw`w-full flex flex-row items-center mt-6`}>
<div css={tw`flex`}>
<RoleDeleteButton roleId={role.id} onDeleted={() => navigate('/admin/roles')} />
</div>
<div css={tw`flex ml-auto`}>
<Button type={'submit'} disabled={isSubmitting || !isValid}>
Save Changes
</Button>
</div>
</div>
</Form>
</AdminBox>
</>
)}
</Formik>
);
};
const RoleEditContainer = () => {
const params = useParams<'id'>();
const { clearFlashes, clearAndAddHttpError } = useStoreActions(
(actions: Actions<ApplicationStore>) => actions.flashes,
);
const [loading, setLoading] = useState(true);
const role = Context.useStoreState(state => state.role);
const setRole = Context.useStoreActions(actions => actions.setRole);
useEffect(() => {
clearFlashes('role');
getRole(Number(params.id))
.then(role => setRole(role))
.catch(error => {
console.error(error);
clearAndAddHttpError({ key: 'role', error });
})
.then(() => setLoading(false));
}, []);
if (loading || role === undefined) {
return (
<AdminContentBlock>
<FlashMessageRender byKey={'role'} css={tw`mb-4`} />
<div css={tw`w-full flex flex-col items-center justify-center`} style={{ height: '24rem' }}>
<Spinner size={'base'} />
</div>
</AdminContentBlock>
);
}
return (
<AdminContentBlock title={'Role - ' + role.name}>
<div css={tw`w-full flex flex-row items-center mb-8`}>
<div css={tw`flex flex-col flex-shrink`} style={{ minWidth: '0' }}>
<h2 css={tw`text-2xl text-neutral-50 font-header font-medium`}>{role.name}</h2>
{(role.description || '').length < 1 ? (
<p css={tw`text-base text-neutral-400`}>
<span css={tw`italic`}>No description</span>
</p>
) : (
<p css={tw`text-base text-neutral-400 whitespace-nowrap overflow-ellipsis overflow-hidden`}>
{role.description}
</p>
)}
</div>
</div>
<FlashMessageRender byKey={'role'} css={tw`mb-4`} />
<EditInformationContainer />
</AdminContentBlock>
);
};
export default () => {
return (
<Context.Provider>
<RoleEditContainer />
</Context.Provider>
);
};

View file

@ -0,0 +1,182 @@
import type { ChangeEvent } from 'react';
import { useContext, useEffect } from 'react';
import { NavLink } from 'react-router-dom';
import tw from 'twin.macro';
import type { Filters } from '@/api/admin/roles';
import { getRoles, Context as RolesContext } from '@/api/admin/roles';
import { AdminContext } from '@/state/admin';
import NewRoleButton from '@/components/admin/roles/NewRoleButton';
import FlashMessageRender from '@/components/FlashMessageRender';
import AdminContentBlock from '@/components/admin/AdminContentBlock';
import AdminCheckbox from '@/components/admin/AdminCheckbox';
import AdminTable, {
TableBody,
TableHead,
TableHeader,
TableRow,
Pagination,
Loading,
NoItems,
ContentWrapper,
useTableHooks,
} from '@/components/admin/AdminTable';
import CopyOnClick from '@/components/elements/CopyOnClick';
import useFlash from '@/plugins/useFlash';
const RowCheckbox = ({ id }: { id: number }) => {
const isChecked = AdminContext.useStoreState(state => state.roles.selectedRoles.indexOf(id) >= 0);
const appendSelectedRole = AdminContext.useStoreActions(actions => actions.roles.appendSelectedRole);
const removeSelectedRole = AdminContext.useStoreActions(actions => actions.roles.removeSelectedRole);
return (
<AdminCheckbox
name={id.toString()}
checked={isChecked}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
if (e.currentTarget.checked) {
appendSelectedRole(id);
} else {
removeSelectedRole(id);
}
}}
/>
);
};
const RolesContainer = () => {
const { page, setPage, setFilters, sort, setSort, sortDirection } = useContext(RolesContext);
const { clearFlashes, clearAndAddHttpError } = useFlash();
const { data: roles, error, isValidating } = getRoles();
useEffect(() => {
if (!error) {
clearFlashes('roles');
return;
}
clearAndAddHttpError({ key: 'roles', error });
}, [error]);
const length = roles?.items?.length || 0;
const setSelectedRoles = AdminContext.useStoreActions(actions => actions.roles.setSelectedRoles);
const selectedRolesLength = AdminContext.useStoreState(state => state.roles.selectedRoles.length);
const onSelectAllClick = (e: ChangeEvent<HTMLInputElement>) => {
setSelectedRoles(e.currentTarget.checked ? roles?.items?.map(role => role.id) || [] : []);
};
const onSearch = (query: string): Promise<void> => {
return new Promise(resolve => {
if (query.length < 2) {
setFilters(null);
} else {
setFilters({ name: query });
}
return resolve();
});
};
useEffect(() => {
setSelectedRoles([]);
}, [page]);
return (
<AdminContentBlock title={'Roles'}>
<div css={tw`w-full flex flex-row items-center mb-8`}>
<div css={tw`flex flex-col flex-shrink`} style={{ minWidth: '0' }}>
<h2 css={tw`text-2xl text-neutral-50 font-header font-medium`}>Roles</h2>
<p css={tw`text-base text-neutral-400 whitespace-nowrap overflow-ellipsis overflow-hidden`}>
Soon&trade;
</p>
</div>
<div css={tw`flex ml-auto pl-4`}>
<NewRoleButton />
</div>
</div>
<FlashMessageRender byKey={'roles'} css={tw`mb-4`} />
<AdminTable>
<ContentWrapper
checked={selectedRolesLength === (length === 0 ? -1 : length)}
onSelectAllClick={onSelectAllClick}
onSearch={onSearch}
>
<Pagination data={roles} onPageSelect={setPage}>
<div css={tw`overflow-x-auto`}>
<table css={tw`w-full table-auto`}>
<TableHead>
<TableHeader
name={'ID'}
direction={sort === 'id' ? (sortDirection ? 1 : 2) : null}
onClick={() => setSort('id')}
/>
<TableHeader
name={'Name'}
direction={sort === 'name' ? (sortDirection ? 1 : 2) : null}
onClick={() => setSort('name')}
/>
<TableHeader name={'Description'} />
</TableHead>
<TableBody>
{roles !== undefined &&
!error &&
!isValidating &&
length > 0 &&
roles.items.map(role => (
<TableRow key={role.id}>
<td css={tw`pl-6`}>
<RowCheckbox id={role.id} />
</td>
<td css={tw`px-6 text-sm text-neutral-200 text-left whitespace-nowrap`}>
<CopyOnClick text={role.id.toString()}>
<code css={tw`font-mono bg-neutral-900 rounded py-1 px-2`}>
{role.id}
</code>
</CopyOnClick>
</td>
<td css={tw`px-6 text-sm text-neutral-200 text-left whitespace-nowrap`}>
<NavLink
to={`/admin/roles/${role.id}`}
css={tw`text-primary-400 hover:text-primary-300`}
>
{role.name}
</NavLink>
</td>
<td css={tw`px-6 text-sm text-neutral-200 text-left whitespace-nowrap`}>
{role.description}
</td>
</TableRow>
))}
</TableBody>
</table>
{roles === undefined || (error && isValidating) ? (
<Loading />
) : length < 1 ? (
<NoItems />
) : null}
</div>
</Pagination>
</ContentWrapper>
</AdminTable>
</AdminContentBlock>
);
};
export default () => {
const hooks = useTableHooks<Filters>();
return (
<RolesContext.Provider value={hooks}>
<RolesContainer />
</RolesContext.Provider>
);
};