refactor create, edit
for /media
route
This commit is contained in:
parent
bf73138521
commit
191f495abe
85
src/components/media/MediaFormUtils.tsx
Normal file
85
src/components/media/MediaFormUtils.tsx
Normal file
@ -0,0 +1,85 @@
|
||||
import { useState } from 'react'
|
||||
import { UseFormSetError, UseFormClearErrors, UseFormSetValue } from 'react-hook-form'
|
||||
|
||||
export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
|
||||
export const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/ogg']
|
||||
|
||||
export const validateFileType = (file: File, mediaType: number) => {
|
||||
if (mediaType === 1 && !ALLOWED_IMAGE_TYPES.includes(file.type)) {
|
||||
return 'Для типа "Фото" разрешены только форматы: JPG, PNG, GIF, WEBP'
|
||||
}
|
||||
|
||||
if (mediaType === 2 && !ALLOWED_VIDEO_TYPES.includes(file.type)) {
|
||||
return 'Для типа "Видео" разрешены только форматы: MP4, WEBM, OGG'
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
type UseMediaFileUploadProps = {
|
||||
selectedMediaType: number
|
||||
setError: UseFormSetError<any>
|
||||
clearErrors: UseFormClearErrors<any>
|
||||
setValue: UseFormSetValue<any>
|
||||
}
|
||||
|
||||
export const useMediaFileUpload = ({
|
||||
selectedMediaType,
|
||||
setError,
|
||||
clearErrors,
|
||||
setValue,
|
||||
}: UseMediaFileUploadProps) => {
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null)
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
if (selectedMediaType) {
|
||||
const error = validateFileType(file, selectedMediaType)
|
||||
if (error) {
|
||||
setError('file', { type: 'manual', message: error })
|
||||
event.target.value = ''
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
clearErrors('file')
|
||||
setValue('file', file)
|
||||
setSelectedFile(file)
|
||||
|
||||
if (file.type.startsWith('image/')) {
|
||||
const url = URL.createObjectURL(file)
|
||||
setPreviewUrl(url)
|
||||
} else {
|
||||
setPreviewUrl(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleMediaTypeChange = (event: any) => {
|
||||
const newMediaType = event.target.value
|
||||
setValue('media_type', newMediaType)
|
||||
|
||||
if (selectedFile) {
|
||||
const error = validateFileType(selectedFile, newMediaType)
|
||||
if (error) {
|
||||
setError('file', { type: 'manual', message: error })
|
||||
setValue('file', null)
|
||||
setSelectedFile(null)
|
||||
setPreviewUrl(null)
|
||||
} else {
|
||||
clearErrors('file')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
selectedFile,
|
||||
setSelectedFile,
|
||||
previewUrl,
|
||||
setPreviewUrl,
|
||||
handleFileChange,
|
||||
handleMediaTypeChange,
|
||||
}
|
||||
}
|
@ -1,2 +1,2 @@
|
||||
@import './stylesheets/hidden-functionality';
|
||||
@import './stylesheets/markdown-editor';
|
||||
@import './stylesheets/hidden-functionality.css';
|
||||
@import './stylesheets/markdown-editor.css';
|
||||
|
@ -52,7 +52,7 @@ export const CityCreate = () => {
|
||||
fullWidth
|
||||
InputLabelProps={{shrink: true}}
|
||||
type="text"
|
||||
label={'Название'}
|
||||
label={'Название *'}
|
||||
name="name"
|
||||
/>
|
||||
</Box>
|
||||
|
@ -1,9 +1,9 @@
|
||||
import {Box, TextField, Button, Typography, FormControl, InputLabel, Select, MenuItem} from '@mui/material'
|
||||
import {Create} from '@refinedev/mui'
|
||||
import {useForm} from '@refinedev/react-hook-form'
|
||||
import {useState} from 'react'
|
||||
|
||||
import {MEDIA_TYPES} from '../../lib/constants'
|
||||
import {ALLOWED_IMAGE_TYPES, ALLOWED_VIDEO_TYPES, useMediaFileUpload} from '../../components/media/MediaFormUtils'
|
||||
|
||||
export const MediaCreate = () => {
|
||||
const {
|
||||
@ -14,52 +14,42 @@ export const MediaCreate = () => {
|
||||
setValue,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setError,
|
||||
clearErrors,
|
||||
} = useForm({})
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null)
|
||||
const selectedMediaType = watch('media_type')
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (file) {
|
||||
setValue('file', file)
|
||||
setSelectedFile(file)
|
||||
|
||||
if (file.type.startsWith('image/')) {
|
||||
const url = URL.createObjectURL(file)
|
||||
setPreviewUrl(url)
|
||||
} else {
|
||||
setPreviewUrl(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
const {selectedFile, previewUrl, handleFileChange, handleMediaTypeChange} = useMediaFileUpload({
|
||||
selectedMediaType,
|
||||
setError,
|
||||
clearErrors,
|
||||
setValue,
|
||||
})
|
||||
|
||||
return (
|
||||
<Create
|
||||
isLoading={formLoading}
|
||||
saveButtonProps={{
|
||||
...saveButtonProps,
|
||||
disabled: !!errors.file || !selectedFile,
|
||||
onClick: handleSubmit((data) => {
|
||||
const formData = new FormData()
|
||||
|
||||
formData.append('filename', data.filename)
|
||||
formData.append('type', String(data.media_type))
|
||||
|
||||
const file = watch('file')
|
||||
if (file) {
|
||||
formData.append('file', file)
|
||||
if (data.file) {
|
||||
formData.append('file', data.file)
|
||||
}
|
||||
|
||||
onFinish(formData)
|
||||
}),
|
||||
}}
|
||||
>
|
||||
<Box component="form" sx={{display: 'flex', flexDirection: 'column'}} autoComplete="off">
|
||||
<Box display="flex" flexDirection="column-reverse" alignItems="center" gap={6}>
|
||||
<Box display="flex" alignItems="center" gap={2}>
|
||||
<Button variant="contained" component="label">
|
||||
<Box display="flex" flexDirection="column" alignItems="center" gap={2}>
|
||||
<Button variant="contained" component="label" disabled={!selectedMediaType}>
|
||||
{selectedFile ? 'Изменить файл' : 'Загрузить файл'}
|
||||
<input type="file" hidden onChange={handleFileChange} />
|
||||
<input type="file" hidden onChange={handleFileChange} accept={selectedMediaType === 1 ? ALLOWED_IMAGE_TYPES.join(',') : ALLOWED_VIDEO_TYPES.join(',')} />
|
||||
</Button>
|
||||
|
||||
{selectedFile && (
|
||||
@ -67,6 +57,12 @@ export const MediaCreate = () => {
|
||||
{selectedFile.name}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
{errors.file && (
|
||||
<Typography variant="caption" color="error">
|
||||
{(errors as any)?.file?.message}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{previewUrl && (
|
||||
@ -76,6 +72,30 @@ export const MediaCreate = () => {
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<FormControl fullWidth margin="normal" error={!!errors.media_type}>
|
||||
<InputLabel id="media-type-label">Тип</InputLabel>
|
||||
<Select
|
||||
labelId="media-type-label"
|
||||
label="Тип"
|
||||
{...register('media_type', {
|
||||
required: 'Это поле является обязательным',
|
||||
valueAsNumber: true,
|
||||
})}
|
||||
onChange={handleMediaTypeChange}
|
||||
>
|
||||
{MEDIA_TYPES.map((type) => (
|
||||
<MenuItem key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
{errors.media_type && (
|
||||
<Typography variant="caption" color="error">
|
||||
{(errors as any)?.media_type?.message}
|
||||
</Typography>
|
||||
)}
|
||||
</FormControl>
|
||||
|
||||
<TextField
|
||||
{...register('filename', {
|
||||
required: 'Это поле является обязательным',
|
||||
@ -89,29 +109,6 @@ export const MediaCreate = () => {
|
||||
label="Название"
|
||||
name="filename"
|
||||
/>
|
||||
|
||||
<FormControl fullWidth margin="normal" error={!!errors.media_type}>
|
||||
<InputLabel id="media-type-label">Тип</InputLabel>
|
||||
<Select
|
||||
labelId="media-type-label"
|
||||
label="Тип"
|
||||
{...register('media_type', {
|
||||
required: 'Это поле является обязательным',
|
||||
valueAsNumber: true,
|
||||
})}
|
||||
>
|
||||
{MEDIA_TYPES.map((type) => (
|
||||
<MenuItem key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
{errors.media_type && (
|
||||
<Typography variant="caption" color="error">
|
||||
{!!(errors as any)?.message}
|
||||
</Typography>
|
||||
)}
|
||||
</FormControl>
|
||||
</Box>
|
||||
</Create>
|
||||
)
|
||||
|
@ -1,10 +1,11 @@
|
||||
import {Box, TextField, Button, Typography, FormControl, InputLabel, Select, MenuItem} from '@mui/material'
|
||||
import {Edit} from '@refinedev/mui'
|
||||
import {useForm} from '@refinedev/react-hook-form'
|
||||
import {useState, useEffect} from 'react'
|
||||
import {useEffect} from 'react'
|
||||
import {useShow} from '@refinedev/core'
|
||||
|
||||
import {MEDIA_TYPES} from '../../lib/constants'
|
||||
import {ALLOWED_IMAGE_TYPES, ALLOWED_VIDEO_TYPES, useMediaFileUpload} from '../../components/media/MediaFormUtils'
|
||||
|
||||
type MediaFormValues = {
|
||||
filename: string
|
||||
@ -20,6 +21,9 @@ export const MediaEdit = () => {
|
||||
formState: {errors},
|
||||
setValue,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setError,
|
||||
clearErrors,
|
||||
} = useForm<MediaFormValues>({
|
||||
defaultValues: {
|
||||
filename: '',
|
||||
@ -32,8 +36,14 @@ export const MediaEdit = () => {
|
||||
const {data} = query
|
||||
const record = data?.data
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null)
|
||||
const selectedMediaType = watch('media_type')
|
||||
|
||||
const {selectedFile, previewUrl, setPreviewUrl, handleFileChange, handleMediaTypeChange} = useMediaFileUpload({
|
||||
selectedMediaType,
|
||||
setError,
|
||||
clearErrors,
|
||||
setValue,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (record?.id) {
|
||||
@ -41,41 +51,28 @@ export const MediaEdit = () => {
|
||||
setValue('filename', record?.filename || '')
|
||||
setValue('media_type', record?.media_type)
|
||||
}
|
||||
}, [record, setValue])
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (file) {
|
||||
setValue('file', file)
|
||||
setSelectedFile(file)
|
||||
|
||||
if (file.type.startsWith('image/')) {
|
||||
const url = URL.createObjectURL(file)
|
||||
setPreviewUrl(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [record, setValue, setPreviewUrl])
|
||||
|
||||
return (
|
||||
<Edit
|
||||
saveButtonProps={{
|
||||
...saveButtonProps,
|
||||
disabled: !!errors.file,
|
||||
onClick: handleSubmit((data) => {
|
||||
const formData = {
|
||||
filename: data.filename,
|
||||
type: Number(data.media_type),
|
||||
}
|
||||
|
||||
onFinish(formData)
|
||||
}),
|
||||
}}
|
||||
>
|
||||
<Box component="form" sx={{display: 'flex', flexDirection: 'column'}} autoComplete="off">
|
||||
<Box display="flex" flexDirection="column-reverse" alignItems="center" gap={6}>
|
||||
<Box display="flex" alignItems="center" gap={2}>
|
||||
<Button variant="contained" component="label">
|
||||
<Box display="flex" flexDirection="column" alignItems="center" gap={2}>
|
||||
<Button variant="contained" component="label" disabled={!selectedMediaType}>
|
||||
{selectedFile ? 'Изменить файл' : 'Загрузить файл'}
|
||||
<input type="file" hidden onChange={handleFileChange} />
|
||||
<input type="file" hidden onChange={handleFileChange} accept={selectedMediaType === 1 ? ALLOWED_IMAGE_TYPES.join(',') : ALLOWED_VIDEO_TYPES.join(',')} />
|
||||
</Button>
|
||||
|
||||
{selectedFile && (
|
||||
@ -83,6 +80,12 @@ export const MediaEdit = () => {
|
||||
{selectedFile.name}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
{errors.file && (
|
||||
<Typography variant="caption" color="error">
|
||||
{(errors as any)?.file?.message}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{previewUrl && (
|
||||
@ -92,6 +95,30 @@ export const MediaEdit = () => {
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<FormControl fullWidth margin="normal" error={!!errors.media_type}>
|
||||
<InputLabel id="media-type-label">Тип</InputLabel>
|
||||
<Select
|
||||
labelId="media-type-label"
|
||||
label="Тип"
|
||||
{...register('media_type', {
|
||||
required: 'Это поле является обязательным',
|
||||
valueAsNumber: true,
|
||||
})}
|
||||
onChange={handleMediaTypeChange}
|
||||
>
|
||||
{MEDIA_TYPES.map((type) => (
|
||||
<MenuItem key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
{errors.media_type && (
|
||||
<Typography variant="caption" color="error">
|
||||
{(errors as any)?.media_type?.message}
|
||||
</Typography>
|
||||
)}
|
||||
</FormControl>
|
||||
|
||||
<TextField
|
||||
{...register('filename', {
|
||||
required: 'Это поле является обязательным',
|
||||
@ -105,31 +132,6 @@ export const MediaEdit = () => {
|
||||
label="Название"
|
||||
name="filename"
|
||||
/>
|
||||
|
||||
<FormControl fullWidth margin="normal" error={!!errors.media_type}>
|
||||
<InputLabel id="media-type-label">Тип</InputLabel>
|
||||
<Select
|
||||
labelId="media-type-label"
|
||||
label="Тип"
|
||||
{...register('media_type', {
|
||||
required: 'Это поле является обязательным',
|
||||
valueAsNumber: true,
|
||||
})}
|
||||
defaultValue=""
|
||||
>
|
||||
{MEDIA_TYPES.map((option) => (
|
||||
<MenuItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
{errors.media_type && (
|
||||
<Typography variant="caption" color="error">
|
||||
{(errors as any)?.message}
|
||||
</Typography>
|
||||
)}
|
||||
</FormControl>
|
||||
</Box>
|
||||
</Edit>
|
||||
)
|
||||
|
Loading…
Reference in New Issue
Block a user