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

書籍管理画面を作成する #10

Open
wants to merge 14 commits into
base: admin
Choose a base branch
from
Open
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
44 changes: 44 additions & 0 deletions app/components/elements/UnstyledModalButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {
Modal,
UnstyledButton,
createPolymorphicComponent,
} from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { forwardRef } from 'react';
import type { ModalProps, UnstyledButtonProps } from '@mantine/core';
import type { ReactNode } from 'react';

type Props = UnstyledButtonProps & {
modalContent: ({
opened,
close,
}: {
opened: boolean;
close: () => void;
}) => ReactNode;
modalProps?: Omit<ModalProps, 'opened' | 'onClose'>;
children: ReactNode;
};

const _UnstyledModalButton = forwardRef<HTMLButtonElement, Props>(
({ modalContent, modalProps, children, ...props }: Props, ref) => {
const [opened, { open, close }] = useDisclosure(false);
return (
<>
<UnstyledButton {...props} ref={ref} onClick={open}>
{children}
</UnstyledButton>
<Modal {...modalProps} opened={opened} onClose={close}>
{modalContent({ opened, close })}
</Modal>
</>
);
},
);
_UnstyledModalButton.displayName = 'UnstyledModalButton';

export const UnstyledModalButton = createPolymorphicComponent<
'button',
Props,
typeof _UnstyledModalButton
>(_UnstyledModalButton);
85 changes: 85 additions & 0 deletions app/components/forms/book/CreateBookForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { Stack, Group, Button } from '@mantine/core';
import { useForm, zodResolver } from '@mantine/form';
import { useCallback, useState } from 'react';
import { z } from 'zod';
import { LoadingOverlayButton } from '~/components/elements/LoadingOverlayButton';
import { createBook, newBookRef } from '~/models/book';
import { notify } from '~/utils/mantine/notifications';
import {
DescriptionInput,
descriptionValidation,
} from './_components/DescriptionInput';
import {
ImageDropzone,
imageValidation,
} from './_components/ImageDropzone';
import { TitleInput, titleValidation } from './_components/TitleInput';
import type { BookDocumentData } from '@local/shared';

type FormValues = {
title: BookDocumentData['title'];
description: BookDocumentData['description'];
image: File | null;
};

const schema = z.object({
title: titleValidation,
description: descriptionValidation,
image: imageValidation,
});

export const CreateBookForm = ({
onSubmit,
onCancel,
}: {
onSubmit?: () => void | Promise<void>;
onCancel?: () => void | Promise<void>;
}) => {
const form = useForm<FormValues>({
validate: zodResolver(schema),
initialValues: {
title: '',
description: '',
image: null,
},
});
const [loading, setLoading] = useState(false);
const handleSubmit = useCallback(
async (values: FormValues) => {
try {
setLoading(true);
await createBook(newBookRef(), { ...values, image: values.image! });
await onSubmit?.();
notify.info({ message: '書籍を作成しました' });
} catch (error) {
console.error(error);
notify.error({ message: '作成に失敗しました' });
} finally {
setLoading(false);
}
},
[onSubmit],
);

return (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap={10}>
<TitleInput form={form} withAsterisk />
<DescriptionInput form={form} withAsterisk />
<ImageDropzone form={form} withAsterisk />
</Stack>
<Group justify='flex-end' mt={20}>
<Button.Group>
{onCancel && (
<Button variant='outline' onClick={onCancel}>
キャンセル
</Button>
)}
<LoadingOverlayButton type='submit' loading={loading}>
作成
</LoadingOverlayButton>
</Button.Group>
</Group>
</form>
);
};
87 changes: 87 additions & 0 deletions app/components/forms/book/UpdateBookForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { Stack, Group, Button } from '@mantine/core';
import { useForm, zodResolver } from '@mantine/form';
import { useCallback, useState } from 'react';
import { z } from 'zod';
import { LoadingOverlayButton } from '~/components/elements/LoadingOverlayButton';
import { bookRef, updateBook } from '~/models/book';
import { notify } from '~/utils/mantine/notifications';
import {
DescriptionInput,
descriptionValidation,
} from './_components/DescriptionInput';
import {
ImageDropzone,
updateImageValidation,
} from './_components/ImageDropzone';
import { TitleInput, titleValidation } from './_components/TitleInput';
import type { Book, BookDocumentData } from '@local/shared';

type FormValues = {
title: BookDocumentData['title'];
description: BookDocumentData['description'];
image: File | null;
};

const schema = z.object({
title: titleValidation,
description: descriptionValidation,
image: updateImageValidation,
});

export const UpdateBookForm = ({
book,
onSubmit,
onCancel,
}: {
book: Book;
onSubmit?: () => void | Promise<void>;
onCancel?: () => void | Promise<void>;
}) => {
const form = useForm<FormValues>({
validate: zodResolver(schema),
initialValues: {
title: book.title,
description: book.description,
image: null,
},
});
const [loading, setLoading] = useState(false);
const handleSubmit = useCallback(
async (values: FormValues) => {
try {
setLoading(true);
await updateBook(bookRef(book.id), values);
await onSubmit?.();
notify.info({ message: '書籍を更新しました' });
} catch (error) {
console.error(error);
notify.error({ message: '更新に失敗しました' });
} finally {
setLoading(false);
}
},
[book.id, onSubmit],
);

return (
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap={10}>
<TitleInput form={form} withAsterisk />
<DescriptionInput form={form} withAsterisk />
<ImageDropzone form={form} />
</Stack>
<Group justify='flex-end' mt={20}>
<Button.Group>
{onCancel && (
<Button variant='outline' onClick={onCancel}>
キャンセル
</Button>
)}
<LoadingOverlayButton type='submit' loading={loading}>
更新
</LoadingOverlayButton>
</Button.Group>
</Group>
</form>
);
};
29 changes: 29 additions & 0 deletions app/components/forms/book/_components/DescriptionInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Textarea } from '@mantine/core';
import { z } from 'zod';
import type { TextareaProps } from '@mantine/core';
import type { UseFormReturnType } from '@mantine/form';

export const descriptionValidation = z
.string()
.min(1, { message: '必須項目です' });

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const DescriptionInput = <Form extends UseFormReturnType<any>>({
form,
...props
}: { form: Form } & Omit<TextareaProps, 'form'>) => {
const name = 'description';
const label = '説明';

return (
<Textarea
label={label}
aria-label={label}
minRows={3}
maxRows={5}
autosize
{...props}
{...form.getInputProps(name)}
/>
);
};
52 changes: 52 additions & 0 deletions app/components/forms/book/_components/ImageDropzone.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Image, Input, Center } from '@mantine/core';
import { Dropzone, IMAGE_MIME_TYPE } from '@mantine/dropzone';
import { IconPhoto } from '@tabler/icons-react';
import { useCallback } from 'react';
import { z } from 'zod';
import type { InputWrapperProps } from '@mantine/core';
import type { FileWithPath } from '@mantine/dropzone';
import type { UseFormReturnType } from '@mantine/form';

export const imageValidation = z.custom<File>((file) => file, {
message: '必須項目です',
});
export const updateImageValidation = z.custom<File | null>();

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const ImageDropzone = <Form extends UseFormReturnType<any>>({
form,
...props
}: { form: Form } & Omit<InputWrapperProps, 'form'>) => {
const name = 'image';
const label = '表紙';
const handleDrop = useCallback(
([file]: FileWithPath[]) => {
form.setFieldValue(name, file);
},
[form],
);

return (
<Input.Wrapper
label={label}
aria-label={label}
{...props}
{...form.getInputProps(name)}
>
<Dropzone accept={IMAGE_MIME_TYPE} onDrop={handleDrop}>
<Center>
{form.values.image ? (
<Image
src={URL.createObjectURL(form.values.image)}
h={200}
w='auto'
alt='プレビュー'
/>
) : (
<IconPhoto color='gray' />
)}
</Center>
</Dropzone>
</Input.Wrapper>
);
};
27 changes: 27 additions & 0 deletions app/components/forms/book/_components/TitleInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { TextInput } from '@mantine/core';
import { z } from 'zod';
import type { TextInputProps } from '@mantine/core';
import type { UseFormReturnType } from '@mantine/form';

export const titleValidation = z
.string()
.min(1, { message: '必須項目です' });

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const TitleInput = <Form extends UseFormReturnType<any>>({
form,
...props
}: { form: Form } & Omit<TextInputProps, 'form'>) => {
const name = 'title';
const label = 'タイトル';

return (
<TextInput
type='text'
label={label}
aria-label={label}
{...props}
{...form.getInputProps(name)}
/>
);
};
62 changes: 62 additions & 0 deletions app/components/pages/admin/AdminBooks.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {
Box,
Stack,
Title,
Group,
Table,
ActionIcon,
LoadingOverlay,
} from '@mantine/core';
import { IconSquareRoundedPlus } from '@tabler/icons-react';
import { UnstyledModalButton } from '~/components/elements/UnstyledModalButton';
import { CreateBookForm } from '~/components/forms/book/CreateBookForm';
import { useCollectionData } from '~/hooks/useCollectionData';
import { booksQuery } from '~/models/book';
import { Book } from './_components/Book';

export const AdminBooks = () => {
const { data: books, loading } = useCollectionData(booksQuery());

return (
<Box pos='relative'>
<LoadingOverlay visible={loading} />
<Stack gap='sm' mb='sm'>
<Title order={1} size='h5'>
書籍管理
</Title>
<Group justify='flex-end'>
<ActionIcon.Group>
<ActionIcon
variant='white'
component={UnstyledModalButton}
modalContent={({ close }) => (
<CreateBookForm onSubmit={close} onCancel={close} />
)}
modalProps={{ title: '書籍' }}
>
<IconSquareRoundedPlus />
</ActionIcon>
</ActionIcon.Group>
</Group>
</Stack>
<Table.ScrollContainer minWidth='100%'>
<Table withColumnBorders withTableBorder verticalSpacing='sm'>
<Table.Thead>
<Table.Tr>
<Table.Th></Table.Th>
<Table.Th>ID</Table.Th>
<Table.Th>表紙</Table.Th>
<Table.Th miw={200}>タイトル</Table.Th>
<Table.Th miw={300}>説明</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{books.map((book) => (
<Book key={book.id} book={book} />
))}
</Table.Tbody>
</Table>
</Table.ScrollContainer>
</Box>
);
};
4 changes: 3 additions & 1 deletion app/components/pages/admin/AdminRoot.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { LoadingScreen } from '~/components/screens/LoadingScreen';

export const AdminRoot = () => {
return <div>AdminRoot</div>;
return <LoadingScreen />;
};
Loading