This commit is contained in:
louiscklaw
2025-04-26 06:15:18 +08:00
parent df87cfb037
commit 6e8fea3bdd
57 changed files with 1392 additions and 20183 deletions

View File

@@ -127,7 +127,7 @@ export function CrCategoryEditForm(): React.JSX.Element {
// TODO: remove below
type: '',
};
//
try {
const result = await pb.collection(COL_QUIZ_LP_CATEGORIES).update(catId, tempUpdate);
logger.debug(result);

View File

@@ -28,27 +28,27 @@ export const layoutConfig = {
items: [
{
key: 'lesson-types',
title: 'type',
title: 'lesson-types',
icon: 'users',
items: [
{
key: 'lesson-types',
title: 'dashboard.lessonTypes.list',
title: 'lessonTypes.list',
href: paths.dashboard.lesson_types.list,
},
{
key: 'lesson-categories',
title: 'dashboard.lessonCategories.list',
title: 'lessonCategories.list',
href: paths.dashboard.lesson_categories.list,
},
{
key: 'vocabulary',
title: 'dashboard.vocabularies.list',
title: 'vocabularies.list',
href: paths.dashboard.vocabularies.list,
},
{
key: 'connective',
title: 'dashboard.connectives.list',
title: 'connectives.list',
href: paths.dashboard.connectives.list,
},
],

View File

@@ -1,3 +1,5 @@
// RULES: obsoleted
// please use `./cms/src/db/LessonCategories/type.d.ts`
export interface LessonCategory {
isEmpty?: boolean;
//

View File

@@ -127,7 +127,7 @@ export function MfCategoryEditForm(): React.JSX.Element {
// TODO: remove below
type: '',
};
//
try {
const result = await pb.collection(COL_QUIZ_MF_CATEGORIES).update(catId, tempUpdate);
logger.debug(result);

View File

@@ -1,7 +1,9 @@
'use client';
// RULES: sorting direction for student lists
export type SortDir = 'asc' | 'desc';
// RULES: core student data structure
export interface Student {
id: string;
name: string;
@@ -14,6 +16,7 @@ export interface Student {
updatedAt?: Date;
}
// RULES: form data structure for creating new student
export interface CreateFormProps {
name: string;
email: string;
@@ -36,6 +39,7 @@ export interface CreateFormProps {
// status?: 'pending' | 'active' | 'blocked';
}
// RULES: form data structure for editing existing student
export interface EditFormProps {
name: string;
email: string;
@@ -57,11 +61,14 @@ export interface EditFormProps {
// quota?: number;
// status?: 'pending' | 'active' | 'blocked';
}
// RULES: filter props for student search and filtering
export interface CustomersFiltersProps {
filters?: Filters;
sortDir?: SortDir;
fullData: Student[];
}
// RULES: available filter options for student data
export interface Filters {
email?: string;
phone?: string;

View File

@@ -1,7 +1,9 @@
'use client';
// RULES: sorting direction for teacher lists
export type SortDir = 'asc' | 'desc';
// RULES: core teacher data structure
export interface Teacher {
id: string;
name: string;
@@ -14,6 +16,7 @@ export interface Teacher {
updatedAt?: Date;
}
// RULES: form data structure for creating new teacher
export interface CreateFormProps {
name: string;
email: string;
@@ -36,6 +39,7 @@ export interface CreateFormProps {
// status?: 'pending' | 'active' | 'blocked';
}
// RULES: form data structure for editing existing teacher
export interface EditFormProps {
name: string;
email: string;
@@ -57,6 +61,8 @@ export interface EditFormProps {
// quota?: number;
// status?: 'pending' | 'active' | 'blocked';
}
// RULES: filter props for teacher search and filtering
export interface CustomersFiltersProps {
filters?: Filters;
sortDir?: SortDir;

View File

@@ -1,44 +1,40 @@
import { dayjs } from '@/lib/dayjs';
import { Vocabulary, CreateForm } from './type';
import { CreateForm, LessonCategory } from './type';
// import type { CreateForm, LessonCategory } from '../lp_categories/type';
export const defaultLessonCategory: LessonCategory = {
isEmpty: false,
id: 'default-id',
cat_name: 'default-category-name',
cat_image_url: undefined,
cat_image: undefined,
pos: 0,
visible: 'hidden',
lesson_id: 'default-lesson-id',
description: 'default-description',
remarks: 'default-remarks',
//
collectionId: '0000000000',
createdAt: dayjs('2099-01-01').toDate(),
//
name: '',
avatar: '',
email: '',
phone: '',
quota: 0,
status: 'NA',
export const defaultVocabulary: Vocabulary = {
id: 'default-vocabulary-id',
image: undefined,
sound: undefined,
word: '',
word_c: '',
sample_e: '',
sample_c: '',
cat_id: 'default-category-id',
category: 'default-category',
lesson_type_id: 'default-lesson-type-id',
};
export const LessonCategoryCreateFormDefault: CreateForm = {
name: '',
type: '',
pos: 1,
visible: 'visible',
description: '',
isActive: true,
order: 1,
imageUrl: '',
export const VocabularyCreateFormDefault: CreateForm = {
image: undefined,
sound: undefined,
word: '',
word_c: '',
sample_e: '',
sample_c: '',
cat_id: '',
category: '',
lesson_type_id: '',
};
export const emptyLessonCategory: LessonCategory = {
...defaultLessonCategory,
export const emptyVocabulary: Vocabulary = {
...defaultVocabulary,
id: '',
word: '',
word_c: '',
sample_e: '',
sample_c: '',
cat_id: '',
category: '',
lesson_type_id: '',
isEmpty: true,
};

View File

@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next';
import { logger } from '@/lib/default-logger';
import { toast } from '@/components/core/toaster';
import deleteVocabulary from '@/db/Vocabularies/Delete';
const pb = new PocketBase(process.env.NEXT_PUBLIC_POCKETBASE_URL);
@@ -44,33 +45,24 @@ export default function ConfirmDeleteModal({
transform: 'translate(-50%, -50%)',
};
function performDelete(id: string): Promise<void> {
return pb
.collection(COL_LESSON_TYPES)
.delete(id)
.then(() => {
toast(t('dashboard.lessonTypes.delete.success'));
reloadRows();
})
.catch((err) => {
logger.error(err);
toast(t('dashboard.lessonTypes.delete.error'));
})
.finally(() => {});
}
function handleUserConfirmDelete(): void {
if (idToDelete) {
setIsDeleteing(true);
performDelete(idToDelete)
// RULES: Vocabulary -> deleteVocabulary
deleteVocabulary(idToDelete)
.then(() => {
reloadRows();
handleClose();
setIsDeleteing(false);
toast(t('delete.success'));
})
.catch((err) => {
// console.error(err)
logger.error(err);
toast(t('dashboard.lessonTypes.delete.error'));
toast(t('delete.error'));
})
.finally(() => {
setIsDeleteing(false);
});
}
}
@@ -86,19 +78,33 @@ export default function ConfirmDeleteModal({
<Box sx={style}>
<Container maxWidth="sm">
<Paper sx={{ border: '1px solid var(--mui-palette-divider)', boxShadow: 'var(--mui-shadows-16)' }}>
<Stack direction="row" spacing={2} sx={{ display: 'flex', p: 3 }}>
<Stack
direction="row"
spacing={2}
sx={{ display: 'flex', p: 3 }}
>
<Avatar sx={{ bgcolor: 'var(--mui-palette-error-50)', color: 'var(--mui-palette-error-main)' }}>
<NoteIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
<Stack spacing={3}>
<Stack spacing={1}>
<Typography variant="h5">{t('Delete Lesson Type ?')}</Typography>
<Typography color="text.secondary" variant="body2">
<Typography
color="text.secondary"
variant="body2"
>
{t('Are you sure you want to delete lesson type ?')}
</Typography>
</Stack>
<Stack direction="row" spacing={2} sx={{ justifyContent: 'flex-end' }}>
<Button color="secondary" onClick={handleClose}>
<Stack
direction="row"
spacing={2}
sx={{ justifyContent: 'flex-end' }}
>
<Button
color="secondary"
onClick={handleClose}
>
{t('Cancel')}
</Button>
<LoadingButton

View File

@@ -1,64 +0,0 @@
import { dayjs } from '@/lib/dayjs';
export interface LessonCategory {
isEmpty?: boolean;
//
id: string;
cat_name: string;
cat_image_url?: string;
cat_image?: string;
pos: number;
visible: string;
lesson_id: string;
description: string;
remarks: string;
//
name: string;
avatar: string;
email: string;
phone: string;
quota: number;
status: 'pending' | 'active' | 'blocked' | 'NA';
createdAt: Date;
}
export const defaultLessonCategory: LessonCategory = {
isEmpty: false,
id: 'default-id',
cat_name: 'default-category-name',
cat_image_url: undefined,
cat_image: undefined,
pos: 0,
visible: 'hidden',
lesson_id: 'default-lesson-id',
description: 'default-description',
remarks: 'default-remarks',
//
createdAt: dayjs('2099-01-01').toDate(),
//
name: '',
avatar: '',
email: '',
phone: '',
quota: 0,
status: 'NA',
};
export const emptyLessonCategory: LessonCategory = {
...defaultLessonCategory,
isEmpty: true,
};
export interface CreateForm {
name: string;
type: string;
pos: number;
visible: string;
}
export const LessonCategoryCreateFormDefault: CreateForm = {
name: '',
type: '',
pos: 1,
visible: 'visible',
};

View File

@@ -1,53 +0,0 @@
'use client';
import * as React from 'react';
// import type { LessonCategory } from '@/types/lesson-type';
import { useSelection } from '@/hooks/use-selection';
import type { Selection } from '@/hooks/use-selection';
import { LessonCategory } from './type';
// import type { LessonCategory } from '../lp_categories/type';
// import type { LessonCategory } from './lesson-categories-table';
// import type { LessonCategory } from '@/components/dashboard/lesson_category/interfaces';
function noop(): void {
return undefined;
}
export interface LessonCategoriesSelectionContextValue extends Selection {}
export const LessonCategoriesSelectionContext = React.createContext<LessonCategoriesSelectionContextValue>({
deselectAll: noop,
deselectOne: noop,
selectAll: noop,
selectOne: noop,
selected: new Set(),
selectedAny: false,
selectedAll: false,
});
interface LessonCategoriesSelectionProviderProps {
children: React.ReactNode;
lessonCategories: LessonCategory[];
}
export function LessonCategoriesSelectionProvider({
children,
lessonCategories = [],
}: LessonCategoriesSelectionProviderProps): React.JSX.Element {
const customerIds = React.useMemo(() => lessonCategories.map((customer) => customer.id), [lessonCategories]);
const selection = useSelection(customerIds);
return (
<LessonCategoriesSelectionContext.Provider value={{ ...selection }}>
{children}
</LessonCategoriesSelectionContext.Provider>
);
}
export function useLessonCategoriesSelection(): LessonCategoriesSelectionContextValue {
return React.useContext(LessonCategoriesSelectionContext);
}

View File

@@ -1,353 +0,0 @@
'use client';
import * as React from 'react';
import RouterLink from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { COL_LESSON_CATEGORIES, NS_LESSON_CATEGORY } from '@/constants';
import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import { Avatar, Divider, MenuItem } from '@mui/material';
// import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
// import Checkbox from '@mui/material/Checkbox';
import FormControl from '@mui/material/FormControl';
// import FormControlLabel from '@mui/material/FormControlLabel';
import FormHelperText from '@mui/material/FormHelperText';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';
import Select from '@mui/material/Select';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2';
import { Camera as CameraIcon } from '@phosphor-icons/react/dist/ssr/Camera';
import type { RecordModel } from 'pocketbase';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z as zod } from 'zod';
import { paths } from '@/paths';
import { dayjs } from '@/lib/dayjs';
import { logger } from '@/lib/default-logger';
import { fileToBase64 } from '@/lib/file-to-base64';
import { pb } from '@/lib/pb';
import { Option } from '@/components/core/option';
import { TextEditor } from '@/components/core/text-editor/text-editor';
import { toast } from '@/components/core/toaster';
import FormLoading from '@/components/loading';
import ErrorDisplay from '../error';
import { defaultLessonCategory } from './_constants';
import type { EditFormProps, LessonCategory } from './type';
// TODO: review this
const schema = zod.object({
cat_name: zod.string().min(1, 'name-is-required').max(255),
//
pos: zod.number().min(1, 'Phone is required').max(99),
visible: zod.string().max(255),
//
description: zod.string().optional(),
remarks: zod.string().optional(),
});
type Values = zod.infer<typeof schema>;
const defaultValues = {
cat_name: '',
// cat_image: undefined,
pos: 0,
visible: 'hidden',
// lesson_id: 'default-lesson-id',
description: 'default-description',
remarks: 'default-remarks',
//
} satisfies Values;
export function LessonCategoryEditForm(): React.JSX.Element {
const router = useRouter();
const { t } = useTranslation(['common', 'lesson_category']);
const NS_DEFAULT = { ns: 'lesson_category' };
const { cat_id: catId } = useParams<{ cat_id: string }>();
//
const [isUpdating, setIsUpdating] = React.useState<boolean>(false);
const [showLoading, setShowLoading] = React.useState<boolean>(false);
const [showError, setShowError] = React.useState<boolean>(false);
const {
control,
handleSubmit,
formState: { errors },
setValue,
reset,
watch,
} = useForm<Values>({ defaultValues, resolver: zodResolver(schema) });
const onSubmit = React.useCallback(async (values: Values): Promise<void> => {
setIsUpdating(true);
const tempUpdate: EditFormProps = {
cat_name: values.cat_name,
pos: values.pos,
visible: values.visible,
description: values.description,
remarks: values.remarks,
type: '',
};
pb.collection(COL_LESSON_CATEGORIES)
.update(catId, tempUpdate)
.then((res) => {
logger.debug(res);
toast.success(t('update.success', NS_DEFAULT));
router.push(paths.dashboard.lesson_categories.list);
})
.catch((err) => {
logger.error(err);
toast.error('Something went wrong!');
})
.finally(() => {
//
setIsUpdating(false);
});
}, []);
const avatarInputRef = React.useRef<HTMLInputElement>(null);
// const avatar = watch('avatar');
const handleAvatarChange = React.useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const url = await fileToBase64(file);
// setValue('avatar', url);
}
},
[setValue]
);
const [textDescription, setTextDescription] = React.useState<string>('loading');
const [textRemarks, setTextRemarks] = React.useState<string>('loading');
const handleLoad = React.useCallback(
(id: string) => {
setShowLoading(true);
pb.collection(COL_LESSON_CATEGORIES)
.getOne(id)
.then((model: RecordModel) => {
const temp: LessonCategory = { ...defaultLessonCategory, ...model };
reset(temp);
setTextDescription(temp.description);
setTextRemarks(temp.remarks);
})
.catch((err) => {
logger.error(err);
toast(t('list.error', NS_DEFAULT));
})
.finally(() => {
setShowLoading(false);
});
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[catId]
);
React.useEffect(() => {
handleLoad(catId);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [catId]);
if (showLoading) return <FormLoading />;
if (showError)
return (
<ErrorDisplay
message={t('error.unable-to-process-request', NS_DEFAULT)}
code="500"
details={t('error.detailed-error-information', NS_DEFAULT)}
/>
);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Card>
<CardContent>
<Stack divider={<Divider />} spacing={4}>
<Stack spacing={3}>
<Typography variant="h6">{t('edit.basic-info', NS_DEFAULT)}</Typography>
<Grid container spacing={3}>
<Grid xs={12}>
<Stack direction="row" spacing={3} sx={{ alignItems: 'center' }}>
<Box
sx={{
border: '1px dashed var(--mui-palette-divider)',
borderRadius: '5%',
display: 'inline-flex',
p: '4px',
}}
>
{/*
<Avatar
src={avatar}
sx={{
'--Avatar-size': '100px',
'--Icon-fontSize': 'var(--icon-fontSize-lg)',
alignItems: 'center',
bgcolor: 'var(--mui-palette-background-level1)',
color: 'var(--mui-palette-text-primary)',
display: 'flex',
justifyContent: 'center',
}}
>
// TODO: resume me
<CameraIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
*/}
</Box>
<Stack spacing={1} sx={{ alignItems: 'flex-start' }}>
<Typography variant="subtitle1">{t('edit.avatar', NS_DEFAULT)}</Typography>
<Typography variant="caption">{t('edit.avatarRequirements', NS_DEFAULT)}</Typography>
<Button
color="secondary"
onClick={() => {
avatarInputRef.current?.click();
}}
variant="outlined"
>
{t('edit.select', NS_DEFAULT)}
</Button>
<input hidden onChange={handleAvatarChange} ref={avatarInputRef} type="file" />
</Stack>
</Stack>
</Grid>
<Grid md={6} xs={12}>
<Controller
disabled={isUpdating}
control={control}
name="cat_name"
render={({ field }) => (
<FormControl disabled={isUpdating} error={Boolean(errors.cat_name)} fullWidth>
<InputLabel required>{t('edit.name', NS_DEFAULT)}</InputLabel>
<OutlinedInput {...field} />
{errors.cat_name ? <FormHelperText>{errors.cat_name.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
disabled={isUpdating}
control={control}
name="pos"
render={({ field }) => (
<FormControl error={Boolean(errors.pos)} fullWidth>
<InputLabel required>{t('edit.position', NS_DEFAULT)}</InputLabel>
<OutlinedInput
{...field}
onChange={(e) => {
field.onChange(parseInt(e.target.value));
}}
type="number"
/>
{errors.pos ? <FormHelperText>{errors.pos.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
disabled={isUpdating}
control={control}
name="visible"
render={({ field }) => (
<FormControl error={Boolean(errors.visible)} fullWidth>
<InputLabel>{t('edit.visible', NS_DEFAULT)}</InputLabel>
<Select {...field}>
<MenuItem value="visible">{t('edit.visible', NS_DEFAULT)}</MenuItem>
<MenuItem value="hidden">{t('edit.hidden', NS_DEFAULT)}</MenuItem>
</Select>
{errors.visible ? <FormHelperText>{errors.visible.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
</Grid>
</Stack>
<Stack spacing={3}>
<Typography variant="h6">{t('create.detail-information', NS_DEFAULT)}</Typography>
<Grid container spacing={3}>
<Grid md={6} xs={12}>
<Controller
disabled={isUpdating}
control={control}
name="description"
render={({ field }) => {
return (
<Box>
<Typography variant="subtitle1" color="text-secondary">
{t('create.description', NS_DEFAULT)}
</Typography>
<Box sx={{ mt: '8px', '& .tiptap-container': { height: '400px' } }}>
<TextEditor
{...field}
content={textDescription}
onUpdate={({ editor }) => {
field.onChange({ target: { value: editor.getHTML() } });
}}
placeholder={t('edit.write-something', NS_DEFAULT)}
/>
</Box>
</Box>
);
}}
/>
</Grid>
<Grid md={6} xs={12}>
<Controller
disabled={isUpdating}
control={control}
name="remarks"
render={({ field }) => (
<Box>
<Typography variant="subtitle1" color="text.secondary">
{t('create.remarks', NS_DEFAULT)}
</Typography>
<Box sx={{ mt: '8px', '& .tiptap-container': { height: '400px' } }}>
<TextEditor
content={textRemarks}
onUpdate={({ editor }) => {
field.onChange({ target: { value: editor.getText() } });
}}
hideToolbar
placeholder={t('edit.write-something', NS_DEFAULT)}
/>
</Box>
</Box>
)}
/>
</Grid>
</Grid>
</Stack>
</Stack>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end' }}>
<Button color="secondary" component={RouterLink} href={paths.dashboard.lesson_types.list}>
{t('edit.cancelButton', NS_DEFAULT)}
</Button>
<LoadingButton disabled={isUpdating} loading={isUpdating} type="submit" variant="contained">
{t('edit.updateButton', NS_DEFAULT)}
</LoadingButton>
</CardActions>
</Card>
</form>
);
}

View File

@@ -0,0 +1,36 @@
export interface Vocabulary {
id: string;
created?: string;
updated?: string;
image?: string;
sound?: string;
word?: string;
word_c?: string;
sample_e?: string;
sample_c?: string;
cat_id?: string;
category?: string;
lesson_type_id?: string;
}
export interface CreateForm {
image?: string;
sound?: string;
word?: string;
word_c?: string;
sample_e?: string;
sample_c?: string;
cat_id?: string;
category?: string;
lesson_type_id?: string;
}
export interface EditFormProps {
id: string;
defaultValues: Vocabulary;
onDone: () => void;
}
export interface Helloworld {
helloworld: string;
}

View File

@@ -1,47 +1,60 @@
export interface LessonCategory {
isEmpty?: boolean;
//
// RULES:
// should match the collection `Vocabularies` from `schema.dbml`
export interface Vocabulary {
id: string;
collectionId: string;
//
cat_name: string;
cat_image_url?: string;
cat_image?: string;
pos: number;
created?: string;
updated?: string;
image?: string;
sound?: string;
word?: string;
word_c?: string;
sample_e?: string;
sample_c?: string;
cat_id: string;
category?: string;
lesson_type_id?: string;
visible: string;
lesson_id: string;
description: string;
remarks: string;
createdAt: Date;
//
name: string;
avatar: string;
email: string;
phone: string;
quota: number;
status: 'pending' | 'active' | 'blocked' | 'NA';
expand?: {
cat_id?: {
collectionId: string;
id: string;
cat_image: string;
cat_name: string;
//
};
};
}
// RULES: for use with vocabulary-create-form.tsx
// when you update, please take a look into `vocabulary-create-form.tsx`
export interface CreateForm {
name: string;
type: string;
pos: number;
visible: string;
description: string;
isActive: boolean;
order: number;
imageUrl: string;
image?: string;
sound?: string;
word?: string;
word_c?: string;
sample_e?: string;
sample_c?: string;
cat_id?: string;
category?: string;
lesson_type_id?: string;
}
// RULES: for use with vocabulary-edit-form.tsx
// when you update, please take a look into `vocabulary-edit-form.tsx`
export interface EditFormProps {
cat_name: string;
pos: number;
visible: string;
description?: string;
remarks?: string;
type: string;
image: File[] | null;
sound: string;
word: string;
word_c: string;
sample_e: string;
sample_c: string;
cat_id: string;
category: string;
lesson_type_id: string;
}
// RULES:
// helloworld example, should not modify
export interface Helloworld {
helloworld: string;
}

View File

@@ -2,7 +2,6 @@
import * as React from 'react';
import { useRouter } from 'next/navigation';
import { COL_LESSON_CATEGORIES } from '@/constants';
import GetAllCount from '@/db/LessonCategories/GetAllCount';
import GetHiddenCount from '@/db/LessonCategories/GetHiddenCount';
import GetVisibleCount from '@/db/LessonCategories/GetVisibleCount';
@@ -20,13 +19,11 @@ import Typography from '@mui/material/Typography';
import { useTranslation } from 'react-i18next';
import { paths } from '@/paths';
import { pb } from '@/lib/pb';
import { FilterButton, FilterPopover, useFilterContext } from '@/components/core/filter-button';
import { Option } from '@/components/core/option';
// import { LessonCategory } from '../lp_categories/type';
import { useLessonCategoriesSelection } from './lesson-categories-selection-context';
import { LessonCategory } from './type';
import { useVocabulariesSelection } from './vocabularies-selection-context';
import type { Vocabulary } from './type';
export interface Filters {
email?: string;
@@ -39,17 +36,17 @@ export interface Filters {
export type SortDir = 'asc' | 'desc';
export interface LessonCategoriesFiltersProps {
export interface VocabulariesFiltersProps {
filters?: Filters;
sortDir?: SortDir;
fullData: LessonCategory[];
fullData: Vocabulary[];
}
export function LessonCategoriesFilters({
export function VocabulariesFilters({
filters = {},
sortDir = 'desc',
fullData,
}: LessonCategoriesFiltersProps): React.JSX.Element {
}: VocabulariesFiltersProps): React.JSX.Element {
const { t } = useTranslation();
const { email, phone, status, name, visible, type } = filters;
@@ -59,16 +56,16 @@ export function LessonCategoriesFilters({
const router = useRouter();
const selection = useLessonCategoriesSelection();
const selection = useVocabulariesSelection();
function getVisible(): number {
return fullData.reduce((count, item: LessonCategory) => {
return fullData.reduce((count, item: Vocabulary) => {
return item.visible === 'visible' ? count + 1 : count;
}, 0);
}
function getHidden(): number {
return fullData.reduce((count, item: LessonCategory) => {
return fullData.reduce((count, item: Vocabulary) => {
return item.visible === 'hidden' ? count + 1 : count;
}, 0);
}
@@ -115,7 +112,7 @@ export function LessonCategoriesFilters({
searchParams.set('visible', newFilters.visible);
}
router.push(`${paths.dashboard.lesson_categories.list}?${searchParams.toString()}`);
router.push(`${paths.dashboard.vocabularies.list}?${searchParams.toString()}`);
},
[router]
);
@@ -195,10 +192,21 @@ export function LessonCategoriesFilters({
return (
<div>
<Tabs onChange={handleVisibleChange} sx={{ px: 3 }} value={visible ?? ''} variant="scrollable">
<Tabs
onChange={handleVisibleChange}
sx={{ px: 3 }}
value={visible ?? ''}
variant="scrollable"
>
{tabs.map((tab) => (
<Tab
icon={<Chip label={tab.count} size="small" variant="soft" />}
icon={
<Chip
label={tab.count}
size="small"
variant="soft"
/>
}
iconPosition="end"
key={tab.value}
label={tab.label}
@@ -209,8 +217,16 @@ export function LessonCategoriesFilters({
))}
</Tabs>
<Divider />
<Stack direction="row" spacing={2} sx={{ alignItems: 'center', flexWrap: 'wrap', px: 3, py: 2 }}>
<Stack direction="row" spacing={2} sx={{ alignItems: 'center', flex: '1 1 auto', flexWrap: 'wrap' }}>
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center', flexWrap: 'wrap', px: 3, py: 2 }}
>
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center', flex: '1 1 auto', flexWrap: 'wrap' }}
>
<FilterButton
displayValue={name}
label={t('Name')}
@@ -240,16 +256,31 @@ export function LessonCategoriesFilters({
{hasFilters ? <Button onClick={handleClearFilters}>{t('Clear filters')}</Button> : null}
</Stack>
{selection.selectedAny ? (
<Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
<Typography color="text.secondary" variant="body2">
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center' }}
>
<Typography
color="text.secondary"
variant="body2"
>
{selection.selected.size} {t('selected')}
</Typography>
<Button color="error" variant="contained">
<Button
color="error"
variant="contained"
>
{t('Delete')}
</Button>
</Stack>
) : null}
<Select name="sort" onChange={handleSortChange} sx={{ maxWidth: '100%', width: '120px' }} value={sortDir}>
<Select
name="sort"
onChange={handleSortChange}
sx={{ maxWidth: '100%', width: '120px' }}
value={sortDir}
>
<Option value="desc">{t('Newest')}</Option>
<Option value="asc">{t('Oldest')}</Option>
</Select>
@@ -268,7 +299,12 @@ function TypeFilterPopover(): React.JSX.Element {
}, [initialValue]);
return (
<FilterPopover anchorEl={anchorEl} onClose={onClose} open={open} title={t('Filter by type')}>
<FilterPopover
anchorEl={anchorEl}
onClose={onClose}
open={open}
title={t('Filter by type')}
>
<FormControl>
<OutlinedInput
onChange={(event) => {
@@ -304,7 +340,12 @@ function NameFilterPopover(): React.JSX.Element {
}, [initialValue]);
return (
<FilterPopover anchorEl={anchorEl} onClose={onClose} open={open} title={t('Filter by name')}>
<FilterPopover
anchorEl={anchorEl}
onClose={onClose}
open={open}
title={t('Filter by name')}
>
<FormControl>
<OutlinedInput
onChange={(event) => {
@@ -339,7 +380,12 @@ function EmailFilterPopover(): React.JSX.Element {
}, [initialValue]);
return (
<FilterPopover anchorEl={anchorEl} onClose={onClose} open={open} title="Filter by email">
<FilterPopover
anchorEl={anchorEl}
onClose={onClose}
open={open}
title="Filter by email"
>
<FormControl>
<OutlinedInput
onChange={(event) => {
@@ -374,7 +420,12 @@ function PhoneFilterPopover(): React.JSX.Element {
}, [initialValue]);
return (
<FilterPopover anchorEl={anchorEl} onClose={onClose} open={open} title="Filter by phone number">
<FilterPopover
anchorEl={anchorEl}
onClose={onClose}
open={open}
title="Filter by phone number"
>
<FormControl>
<OutlinedInput
onChange={(event) => {

View File

@@ -10,7 +10,7 @@ function noop(): void {
return undefined;
}
interface LessonCategoriesPaginationProps {
interface VocabulariesPaginationProps {
count: number;
page: number;
//
@@ -19,14 +19,14 @@ interface LessonCategoriesPaginationProps {
rowsPerPage: number;
}
export function LessonCategoriesPagination({
export function VocabulariesPagination({
count,
page,
//
setPage,
setRowsPerPage,
rowsPerPage,
}: LessonCategoriesPaginationProps): React.JSX.Element {
}: VocabulariesPaginationProps): React.JSX.Element {
// You should implement the pagination using a similar logic as the filters.
// Note that when page change, you should keep the filter search params.
const handleChangePage = (event: unknown, newPage: number) => {

View File

@@ -0,0 +1,46 @@
'use client';
import * as React from 'react';
import { useSelection } from '@/hooks/use-selection';
import type { Selection } from '@/hooks/use-selection';
import { Vocabulary } from './type';
function noop(): void {
return undefined;
}
export interface VocabulariesSelectionContextValue extends Selection {}
export const VocabulariesSelectionContext = React.createContext<VocabulariesSelectionContextValue>({
deselectAll: noop,
deselectOne: noop,
selectAll: noop,
selectOne: noop,
selected: new Set(),
selectedAny: false,
selectedAll: false,
});
interface VocabulariesSelectionProviderProps {
children: React.ReactNode;
lessonCategories: Vocabulary[];
}
export function VocabulariesSelectionProvider({
children,
lessonCategories = [],
}: VocabulariesSelectionProviderProps): React.JSX.Element {
const customerIds = React.useMemo(() => lessonCategories.map((customer) => customer.id), [lessonCategories]);
const selection = useSelection(customerIds);
return (
<VocabulariesSelectionContext.Provider value={{ ...selection }}>{children}</VocabulariesSelectionContext.Provider>
);
}
export function useVocabulariesSelection(): VocabulariesSelectionContextValue {
return React.useContext(VocabulariesSelectionContext);
}

View File

@@ -27,10 +27,18 @@ import { DataTable } from '@/components/core/data-table';
import type { ColumnDef } from '@/components/core/data-table';
import ConfirmDeleteModal from './confirm-delete-modal';
import { useLessonCategoriesSelection } from './lesson-categories-selection-context';
import type { LessonCategory } from './type';
import { useVocabulariesSelection } from './vocabularies-selection-context';
import type { Vocabulary } from './type';
import { listLessonCategories } from '@/db/LessonCategories/listLessonCategories';
import { LessonCategory } from '@/db/LessonCategories/type';
import { Logger } from '@/lib/logger';
import { logger } from '@/lib/default-logger';
import getImageUrlFromFile from '@/lib/get-image-url-from-file.ts';
function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonCategory>[] {
function columns(
handleDeleteClick: (testId: string) => void,
lessonCategories: { id: string; label: string }[]
): ColumnDef<Vocabulary>[] {
return [
{
formatter: (row): React.JSX.Element => (
@@ -42,7 +50,7 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonC
<Link
color="inherit"
component={RouterLink}
href={paths.dashboard.lesson_categories.details(row.id)}
href={paths.dashboard.vocabularies.details(row.id)}
sx={{ whiteSpace: 'nowrap' }}
variant="subtitle2"
>
@@ -58,12 +66,12 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonC
<ImagesIcon size={32} />
</Avatar>{' '}
<div>
<Box sx={{ whiteSpace: 'nowrap' }}>{row.cat_name}</Box>
<Box sx={{ whiteSpace: 'nowrap' }}>{row.word}</Box>
<Typography
color="text.secondary"
variant="body2"
>
slug: {row.cat_name}
slug: {row.word_c}
</Typography>
</div>
</Stack>
@@ -74,78 +82,39 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonC
width: '200px',
},
{
formatter: (row): React.JSX.Element => (
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center' }}
>
<LinearProgress
sx={{ flex: '1 1 auto' }}
value={row.quota}
variant="determinate"
/>
<Typography
color="text.secondary"
variant="body2"
formatter: (row): React.JSX.Element => {
const { cat_name: catName } = row?.expand?.cat_id ?? { cat_name: '--' };
return (
<Stack
direction="row"
spacing={2}
sx={{ alignItems: 'center' }}
>
{new Intl.NumberFormat('en-US', { style: 'percent', maximumFractionDigits: 2 }).format(row.quota / 100)}
</Typography>
</Stack>
),
<Typography
color="text.secondary"
variant="body2"
>
{catName}
</Typography>
</Stack>
);
},
// NOTE: please refer to translation.json here
name: 'word-count',
name: 'category',
width: '100px',
},
{
formatter: (row): React.JSX.Element => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const mapping = {
active: {
label: 'Active',
icon: (
<CheckCircleIcon
color="var(--mui-palette-success-main)"
weight="fill"
/>
),
},
blocked: { label: 'Blocked', icon: <MinusIcon color="var(--mui-palette-error-main)" /> },
pending: {
label: 'Pending',
icon: (
<ClockIcon
color="var(--mui-palette-warning-main)"
weight="fill"
/>
),
},
NA: {
label: 'NA',
icon: (
<ClockIcon
color="var(--mui-palette-warning-main)"
weight="fill"
/>
),
},
} as const;
const { label, icon } = mapping[row.status] ?? { label: 'Unknown', icon: null };
return (
<Button
onClick={() => {
toast.error('sorry but not implementd');
}}
style={{ backgroundColor: 'transparent' }}
>
{/* <Chip icon={icon} label={label} size="small" variant="outlined" /> */}
{label}
</Button>
<Chip
label={row.visible}
variant="outlined"
size="small"
/>
);
},
name: 'Status',
name: 'visible',
width: '150px',
},
{
@@ -165,13 +134,12 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonC
//
color="secondary"
component={RouterLink}
href={paths.dashboard.lesson_categories.details(row.id)}
href={paths.dashboard.vocabularies.details(row.id)}
>
<PencilSimpleIcon size={24} />
</LoadingButton>
<LoadingButton
color="error"
disabled={row.isEmpty}
onClick={() => {
handleDeleteClick(row.id);
}}
@@ -188,14 +156,14 @@ function columns(handleDeleteClick: (testId: string) => void): ColumnDef<LessonC
];
}
export interface LessonCategoriesTableProps {
rows: LessonCategory[];
export interface VocabulariesTableProps {
rows: Vocabulary[];
reloadRows: () => void;
}
export function LessonCategoriesTable({ rows, reloadRows }: LessonCategoriesTableProps): React.JSX.Element {
const { t } = useTranslation(['lesson_category']);
const { deselectAll, deselectOne, selectAll, selectOne, selected } = useLessonCategoriesSelection();
export function VocabulariesTable({ rows, reloadRows }: VocabulariesTableProps): React.JSX.Element {
const { t } = useTranslation(['vocabulary']);
const { deselectAll, deselectOne, selectAll, selectOne, selected } = useVocabulariesSelection();
const [idToDelete, setIdToDelete] = React.useState('');
const [open, setOpen] = React.useState(false);
@@ -205,6 +173,20 @@ export function LessonCategoriesTable({ rows, reloadRows }: LessonCategoriesTabl
setIdToDelete(testId);
}
let [lessonCategories, setLessonCategories] = React.useState<{}>({});
async function tempFunc(): Promise<void> {
try {
const tempCategories = await listLessonCategories();
console.log(tempCategories);
} catch (error) {
logger.error(error);
}
}
React.useEffect(() => {
void tempFunc;
}, []);
return (
<React.Fragment>
<ConfirmDeleteModal
@@ -213,7 +195,7 @@ export function LessonCategoriesTable({ rows, reloadRows }: LessonCategoriesTabl
reloadRows={reloadRows}
setOpen={setOpen}
/>
<DataTable<LessonCategory>
<DataTable<Vocabulary>
columns={columns(handleDeleteClick)}
onDeselectAll={deselectAll}
onDeselectOne={(_, row) => {

View File

@@ -3,23 +3,19 @@
import * as React from 'react';
import RouterLink from 'next/link';
import { useRouter } from 'next/navigation';
import { COL_LESSON_CATEGORIES, NS_LESSON_CATEGORY } from '@/constants';
import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import { Avatar, Divider, MenuItem } from '@mui/material';
import { Avatar, Divider } from '@mui/material';
// import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import Checkbox from '@mui/material/Checkbox';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormHelperText from '@mui/material/FormHelperText';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';
import Select from '@mui/material/Select';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2';
@@ -32,7 +28,6 @@ import { z as zod } from 'zod';
import { paths } from '@/paths';
import { logger } from '@/lib/default-logger';
import { fileToBase64 } from '@/lib/file-to-base64';
import { Option } from '@/components/core/option';
import { TextEditor } from '@/components/core/text-editor/text-editor';
import { toast } from '@/components/core/toaster';
@@ -71,12 +66,10 @@ const defaultValues = {
currency: 'USD',
} satisfies Values;
export function LessonCategoryCreateForm(): React.JSX.Element {
export function VocabularyCreateForm(): React.JSX.Element {
const router = useRouter();
const { t } = useTranslation(['common', 'lesson_category']);
const NS_DEFAULT = { ns: 'lesson_category' };
const [isCreating, setIsCreating] = React.useState<boolean>(false);
const {
@@ -121,12 +114,22 @@ export function LessonCategoryCreateForm(): React.JSX.Element {
<form onSubmit={handleSubmit(onSubmit)}>
<Card>
<CardContent>
<Stack divider={<Divider />} spacing={4}>
<Stack
divider={<Divider />}
spacing={4}
>
<Stack spacing={3}>
<Typography variant="h6">{t('create.typeInformation', NS_DEFAULT)}</Typography>
<Grid container spacing={3}>
<Typography variant="h6">{t('create.typeInformation')}</Typography>
<Grid
container
spacing={3}
>
<Grid xs={12}>
<Stack direction="row" spacing={3} sx={{ alignItems: 'center' }}>
<Stack
direction="row"
spacing={3}
sx={{ alignItems: 'center' }}
>
<Box
sx={{
border: '1px dashed var(--mui-palette-divider)',
@@ -151,9 +154,12 @@ export function LessonCategoryCreateForm(): React.JSX.Element {
<CameraIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
</Box>
<Stack spacing={1} sx={{ alignItems: 'flex-start' }}>
<Typography variant="subtitle1">{t('create.avatar', NS_DEFAULT)}</Typography>
<Typography variant="caption">{t('create.avatarRequirements', NS_DEFAULT)}</Typography>
<Stack
spacing={1}
sx={{ alignItems: 'flex-start' }}
>
<Typography variant="subtitle1">{t('create.avatar')}</Typography>
<Typography variant="caption">{t('create.avatarRequirements')}</Typography>
<Button
color="secondary"
onClick={() => {
@@ -161,44 +167,70 @@ export function LessonCategoryCreateForm(): React.JSX.Element {
}}
variant="outlined"
>
{t('create.avatar_select', NS_DEFAULT)}
{t('create.avatar_select')}
</Button>
<input hidden onChange={handleAvatarChange} ref={avatarInputRef} type="file" />
<input
hidden
onChange={handleAvatarChange}
ref={avatarInputRef}
type="file"
/>
</Stack>
</Stack>
</Grid>
<Grid md={6} xs={12}>
<Grid
md={6}
xs={12}
>
<Controller
control={control}
name="name"
render={({ field }) => (
<FormControl error={Boolean(errors.name)} fullWidth>
<InputLabel required>{t('create.name', NS_DEFAULT)}</InputLabel>
<FormControl
error={Boolean(errors.name)}
fullWidth
>
<InputLabel required>{t('create.name')}</InputLabel>
<OutlinedInput {...field} />
{errors.name ? <FormHelperText>{errors.name.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Grid
md={6}
xs={12}
>
<Controller
control={control}
name="email"
render={({ field }) => (
<FormControl error={Boolean(errors.email)} fullWidth>
<FormControl
error={Boolean(errors.email)}
fullWidth
>
<InputLabel required>Email address</InputLabel>
<OutlinedInput {...field} type="email" />
<OutlinedInput
{...field}
type="email"
/>
{errors.email ? <FormHelperText>{errors.email.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Grid
md={6}
xs={12}
>
<Controller
control={control}
name="phone"
render={({ field }) => (
<FormControl error={Boolean(errors.phone)} fullWidth>
<FormControl
error={Boolean(errors.phone)}
fullWidth
>
<InputLabel required>Phone number</InputLabel>
<OutlinedInput {...field} />
{errors.phone ? <FormHelperText>{errors.phone.message}</FormHelperText> : null}
@@ -206,12 +238,18 @@ export function LessonCategoryCreateForm(): React.JSX.Element {
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Grid
md={6}
xs={12}
>
<Controller
control={control}
name="company"
render={({ field }) => (
<FormControl error={Boolean(errors.company)} fullWidth>
<FormControl
error={Boolean(errors.company)}
fullWidth
>
<InputLabel>Company</InputLabel>
<OutlinedInput {...field} />
{errors.company ? <FormHelperText>{errors.company.message}</FormHelperText> : null}
@@ -222,35 +260,56 @@ export function LessonCategoryCreateForm(): React.JSX.Element {
</Grid>
</Stack>
<Stack spacing={3}>
<Typography variant="h6">{t('create.detail-information', NS_DEFAULT)}</Typography>
<Grid container spacing={3}>
<Grid md={6} xs={12}>
<Typography variant="h6">{t('create.detail-information')}</Typography>
<Grid
container
spacing={3}
>
<Grid
md={6}
xs={12}
>
<Controller
control={control}
name="billingAddress.country"
render={({ field }) => (
<Box>
<Typography variant="subtitle1" color="text-secondary">
{t('create.description', NS_DEFAULT)}
<Typography
variant="subtitle1"
color="text-secondary"
>
{t('create.description')}
</Typography>
<Box sx={{ mt: '8px', '& .tiptap-container': { height: '400px' } }}>
<TextEditor content="" placeholder="Write something" />
<TextEditor
content=""
placeholder="Write something"
/>
</Box>
</Box>
)}
/>
</Grid>
<Grid md={6} xs={12}>
<Grid
md={6}
xs={12}
>
<Controller
control={control}
name="billingAddress.state"
render={({ field }) => (
<Box>
<Typography variant="subtitle1" color="text.secondary">
{t('create.remarks', NS_DEFAULT)}
<Typography
variant="subtitle1"
color="text.secondary"
>
{t('create.remarks')}
</Typography>
<Box sx={{ mt: '8px', '& .tiptap-container': { height: '400px' } }}>
<TextEditor content="" placeholder="Write something" />
<TextEditor
content=""
placeholder="Write something"
/>
</Box>
</Box>
)}
@@ -261,12 +320,21 @@ export function LessonCategoryCreateForm(): React.JSX.Element {
</Stack>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end' }}>
<Button color="secondary" component={RouterLink} href={paths.dashboard.lesson_categories.list}>
{t('create.cancelButton', NS_DEFAULT)}
<Button
color="secondary"
component={RouterLink}
href={paths.dashboard.lesson_categories.list}
>
{t('create.cancelButton')}
</Button>
<LoadingButton disabled={isCreating} loading={isCreating} type="submit" variant="contained">
{t('create.createButton', NS_DEFAULT)}
<LoadingButton
disabled={isCreating}
loading={isCreating}
type="submit"
variant="contained"
>
{t('create.createButton')}
</LoadingButton>
</CardActions>
</Card>

View File

@@ -0,0 +1,462 @@
'use client';
import * as React from 'react';
import RouterLink from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { COL_VOCABULARIES } from '@/constants';
import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import { Avatar, Divider, MenuItem } from '@mui/material';
// import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import FormControl from '@mui/material/FormControl';
import FormHelperText from '@mui/material/FormHelperText';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';
import Select from '@mui/material/Select';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2';
import { Camera as CameraIcon } from '@phosphor-icons/react/dist/ssr/Camera';
import type { RecordModel } from 'pocketbase';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z as zod } from 'zod';
import { paths } from '@/paths';
import { dayjs } from '@/lib/dayjs';
import { logger } from '@/lib/default-logger';
import { base64ToFile, fileToBase64 } from '@/lib/file-to-base64';
import { pb } from '@/lib/pb';
import { Option } from '@/components/core/option';
import { TextEditor } from '@/components/core/text-editor/text-editor';
import { toast } from '@/components/core/toaster';
import FormLoading from '@/components/loading';
import ErrorDisplay from '../error';
import { defaultLessonCategory } from './_constants';
import type { EditFormProps } from './type';
import getVocabularyById from '@/db/Vocabularies/GetById';
import getAllLessonCategories from '@/db/LessonCategories/GetAll';
import { listLessonCategories } from '@/db/LessonCategories/listLessonCategories';
import isDevelopment from '@/lib/check-is-development';
const schema = zod.object({
image: zod.union([zod.array(zod.any()), zod.string()]).optional(),
sound: zod.union([zod.array(zod.any()), zod.string()]).optional(),
word: zod.string().min(1, 'Word is required').max(255),
word_c: zod.string().min(1, 'Chinese word is required').max(255),
sample_e: zod.string().optional(),
sample_c: zod.string().optional(),
cat_id: zod.string().min(1, 'Category ID is required'),
category: zod.string().optional(),
lesson_type_id: zod.string().min(1, 'Lesson type ID is required'),
// NOTE: for image handling
avatar: zod.string().optional(),
});
type Values = zod.infer<typeof schema>;
const defaultValues = {
image: undefined,
sound: undefined,
word: '',
word_c: '',
sample_e: '',
sample_c: '',
cat_id: '',
category: '',
lesson_type_id: '',
} satisfies Values;
export function VocabularyEditForm(): React.JSX.Element {
const router = useRouter();
const { t } = useTranslation();
const { cat_id: catId } = useParams<{ cat_id: string }>();
//
const [isUpdating, setIsUpdating] = React.useState<boolean>(false);
const [showLoading, setShowLoading] = React.useState<boolean>(false);
//
const [showError, setShowError] = React.useState({ show: false, detail: '' });
const {
control,
handleSubmit,
formState: { errors },
setValue,
reset,
watch,
} = useForm<Values>({ defaultValues, resolver: zodResolver(schema) });
const onSubmit = React.useCallback(
async (values: Values): Promise<void> => {
setIsUpdating(true);
const tempUpdate: EditFormProps = {
image: values.avatar ? [await base64ToFile(values.avatar)] : null,
sound: '',
word: values.word,
word_c: values.word_c,
sample_e: values.sample_e || '',
sample_c: values.sample_c || '',
cat_id: values.cat_id,
category: '',
lesson_type_id: '',
};
//
try {
console.log({ tempUpdate });
const result = await pb.collection(COL_VOCABULARIES).update(catId, tempUpdate);
logger.debug(result);
toast.success(t('edit.success'));
router.push(paths.dashboard.vocabularies.list);
} catch (error) {
logger.error(error);
toast.error(t('update.failed'));
} finally {
setIsUpdating(false);
}
},
// t is not necessary here
// eslint-disable-next-line react-hooks/exhaustive-deps
[router]
);
const avatarInputRef = React.useRef<HTMLInputElement>(null);
const avatar = watch('avatar');
const handleAvatarChange = React.useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const url = await fileToBase64(file);
setValue('avatar', url);
}
},
[setValue]
);
// load existing data when user arrive
const loadExistingData = React.useCallback(
async (id: string) => {
try {
const result = await pb.collection(COL_VOCABULARIES).getOne(id);
reset({ ...defaultValues, ...result });
if (result.image !== '') {
const fetchResult = await fetch(
`http://127.0.0.1:8090/api/files/${result.collectionId}/${result.id}/${result.image}`
);
const blob = await fetchResult.blob();
const url = await fileToBase64(blob);
setValue('avatar', url);
} else {
setValue('avatar', '');
}
} catch (error) {
logger.error(error);
toast(t('list.error'));
setShowError({ show: true, detail: JSON.stringify(error, null, 2) });
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[catId]
);
let [categoriesOption, setCategoriesOption] = React.useState<{ value: string; label: string }[]>([]);
const loadCategories = React.useCallback(async () => {
try {
const categories = await listLessonCategories();
logger.debug(categories);
setCategoriesOption(
categories.map((c) => {
return { label: c.cat_name || '??', value: c.id };
})
);
} catch (error) {
logger.error(error);
toast.error(t('list.error'));
}
}, [catId]);
React.useEffect(() => {
setShowLoading(true);
void loadCategories();
void loadExistingData(catId);
setShowLoading(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [catId]);
if (showLoading) return <FormLoading />;
if (showError.show)
return (
<ErrorDisplay
message={t('error.unable-to-process-request')}
code="500"
details={showError.detail}
/>
);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Card>
<CardContent>
<Stack
divider={<Divider />}
spacing={4}
>
<Stack spacing={3}>
<Typography variant="h6">{t('edit.basic-info')}</Typography>
<Grid
container
spacing={3}
>
<Grid xs={12}>
<Stack
direction="row"
spacing={3}
sx={{ alignItems: 'center' }}
>
<Box
sx={{
border: '1px dashed var(--mui-palette-divider)',
borderRadius: '5%',
display: 'inline-flex',
p: '4px',
}}
>
<Avatar
variant="rounded"
src={avatar}
sx={{
'--Avatar-size': '100px',
'--Icon-fontSize': 'var(--icon-fontSize-lg)',
alignItems: 'center',
bgcolor: 'var(--mui-palette-background-level1)',
color: 'var(--mui-palette-text-primary)',
display: 'flex',
justifyContent: 'center',
}}
>
<CameraIcon fontSize="var(--Icon-fontSize)" />
</Avatar>
</Box>
<Stack
spacing={1}
sx={{ alignItems: 'flex-start' }}
>
<Typography variant="subtitle1">{t('edit.avatar')}</Typography>
<Typography variant="caption">{t('edit.avatarRequirements')}</Typography>
<Button
color="secondary"
onClick={() => {
avatarInputRef.current?.click();
}}
variant="outlined"
>
{t('edit.avatar_select')}
</Button>
<input
hidden
onChange={handleAvatarChange}
ref={avatarInputRef}
type="file"
/>
</Stack>
</Stack>
</Grid>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="word"
render={({ field }) => (
<FormControl
disabled={isUpdating}
error={Boolean(errors.word)}
fullWidth
>
<InputLabel required>{t('edit.word')}</InputLabel>
<OutlinedInput {...field} />
{errors.word ? <FormHelperText>{errors.word.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="word_c"
render={({ field }) => (
<FormControl
error={Boolean(errors.word_c)}
fullWidth
>
<InputLabel required>{t('edit.word_c')}</InputLabel>
<OutlinedInput {...field} />
{errors.word_c ? <FormHelperText>{errors.word_c.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="cat_id"
render={({ field }) => (
<FormControl
error={Boolean(errors.cat_id)}
fullWidth
>
<InputLabel>{t('edit.cat_id')}</InputLabel>
<Select {...field}>
{categoriesOption.map((co, i) => (
<Option
key={i}
value={co.value}
>
{co.label}
</Option>
))}
</Select>
</FormControl>
)}
/>
</Grid>
{/* */}
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="sound"
render={({ field }) => (
<FormControl
error={Boolean(errors.sound)}
fullWidth
>
{/* TODO: sound file selection is not implemented */}
<InputLabel required>{t('edit.sound_file')} - (Not implemented)</InputLabel>
<OutlinedInput {...field} />
{errors.sound ? <FormHelperText>{errors.sound.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
</Grid>
</Stack>
{/* */}
<Stack spacing={3}>
<Typography variant="h6">{t('edit.sample-sentence')}</Typography>
<Grid
container
spacing={3}
>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="sample_e"
render={({ field }) => (
<FormControl
error={Boolean(errors.sample_e)}
fullWidth
>
<InputLabel>{t('edit.sample_e')}</InputLabel>
<OutlinedInput
{...field}
multiline
rows={4}
/>
{errors.sample_e ? <FormHelperText>{errors.sample_e.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
<Grid
md={6}
xs={12}
>
<Controller
disabled={isUpdating}
control={control}
name="sample_c"
render={({ field }) => (
<FormControl
error={Boolean(errors.sample_c)}
fullWidth
>
<InputLabel>{t('edit.sample_c')}</InputLabel>
<OutlinedInput
{...field}
multiline
rows={4}
/>
{errors.sample_c ? <FormHelperText>{errors.sample_c.message}</FormHelperText> : null}
</FormControl>
)}
/>
</Grid>
</Grid>
</Stack>
{/* */}
</Stack>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end' }}>
<Button
color="secondary"
component={RouterLink}
href={paths.dashboard.vocabularies.list}
>
{t('edit.cancelButton')}
</Button>
<LoadingButton
disabled={isUpdating}
loading={isUpdating}
type="submit"
variant="contained"
>
1{t('edit.updateButton')}2
</LoadingButton>
</CardActions>
<Box sx={{ display: isDevelopment ? 'block' : 'none' }}>
<pre>{JSON.stringify(errors, null, 2)}</pre>
</Box>
</Card>
</form>
);
}