forked from VinokurovVE/tests
docx, xlsx, pdf viewers, dropzone for uploading, cleanup
This commit is contained in:
@ -1,15 +1,15 @@
|
||||
import { useDocuments, useFolders } from '../hooks/swrHooks'
|
||||
import { IDocument, IDocumentFolder } from '../interfaces/documents'
|
||||
import { Box, Breadcrumbs, Button, Card, CardActionArea, CircularProgress, Divider, Input, InputLabel, LinearProgress, Link, List, ListItem, ListItemButton } from '@mui/material'
|
||||
import { Download, Folder, InsertDriveFile, Upload, UploadFile } from '@mui/icons-material'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Box, Breadcrumbs, Button, Card, CardActionArea, CircularProgress, Divider, IconButton, Input, InputLabel, LinearProgress, Link, List, ListItem, ListItemButton, SxProps } from '@mui/material'
|
||||
import { Cancel, Close, Download, Folder, InsertDriveFile, Upload, UploadFile } from '@mui/icons-material'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import DocumentService from '../services/DocumentService'
|
||||
import { mutate } from 'swr'
|
||||
import FileViewer from './modals/FileViewer'
|
||||
import { fileTypeFromBlob } from 'file-type/core'
|
||||
|
||||
interface FolderProps {
|
||||
folder: IDocumentFolder;
|
||||
index: number;
|
||||
handleFolderClick: (folder: IDocumentFolder) => void;
|
||||
}
|
||||
|
||||
@ -19,20 +19,22 @@ interface DocumentProps {
|
||||
handleDocumentClick: (doc: IDocument, index: number) => void;
|
||||
}
|
||||
|
||||
function ItemFolder({ folder, handleFolderClick, ...props }: FolderProps) {
|
||||
const FileItemStyle: SxProps = {
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
gap: '8px',
|
||||
alignItems: 'center',
|
||||
padding: '8px'
|
||||
}
|
||||
|
||||
function ItemFolder({ folder, index, handleFolderClick, ...props }: FolderProps) {
|
||||
return (
|
||||
<ListItemButton
|
||||
onClick={() => handleFolderClick(folder)}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
gap: '8px',
|
||||
alignItems: 'center',
|
||||
padding: '8px'
|
||||
}}
|
||||
sx={FileItemStyle}
|
||||
{...props}
|
||||
>
|
||||
<Folder />
|
||||
@ -48,14 +50,7 @@ function ItemDocument({ doc, index, handleDocumentClick, ...props }: DocumentPro
|
||||
onClick={() => handleDocumentClick(doc, index)}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
gap: '8px',
|
||||
alignItems: 'center',
|
||||
padding: '8px',
|
||||
}}
|
||||
sx={FileItemStyle}
|
||||
{...props}
|
||||
>
|
||||
<InsertDriveFile />
|
||||
@ -67,23 +62,18 @@ function ItemDocument({ doc, index, handleDocumentClick, ...props }: DocumentPro
|
||||
|
||||
export default function FolderViewer() {
|
||||
const [currentFolder, setCurrentFolder] = useState<IDocumentFolder | null>(null)
|
||||
|
||||
const [breadcrumbs, setBreadcrumbs] = useState<IDocumentFolder[]>([])
|
||||
|
||||
const { folders, isLoading: foldersLoading } = useFolders()
|
||||
|
||||
const { documents, isLoading: documentsLoading } = useDocuments(currentFolder?.id)
|
||||
|
||||
const [uploadProgress, setUploadProgress] = useState(0)
|
||||
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const [fileViewerModal, setFileViewerModal] = useState(false)
|
||||
|
||||
const [currentFileNo, setCurrentFileNo] = useState<number>(-1)
|
||||
|
||||
const [dragOver, setDragOver] = useState(false)
|
||||
const [filesToUpload, setFilesToUpload] = useState<File[]>([])
|
||||
|
||||
const handleFolderClick = (folder: IDocumentFolder) => {
|
||||
setCurrentFolder(folder)
|
||||
setBreadcrumbs((prev) => [...prev, folder])
|
||||
@ -102,15 +92,18 @@ export default function FolderViewer() {
|
||||
|
||||
const handleFileUpload = async (event: any) => {
|
||||
setIsUploading(true)
|
||||
const file = event.target.files?.[0]
|
||||
|
||||
if (file && currentFolder && currentFolder.id) {
|
||||
const files = event.target.files
|
||||
if (files && currentFolder && currentFolder.id) {
|
||||
const formData = new FormData()
|
||||
formData.append('files', file)
|
||||
|
||||
for (let file of files) {
|
||||
formData.append('files', file)
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await DocumentService.uploadFiles(currentFolder.id, formData, setUploadProgress);
|
||||
// const response = await DocumentService.uploadFiles(currentFolder.id, formData, setUploadProgress);
|
||||
setIsUploading(false);
|
||||
setFilesToUpload([])
|
||||
mutate(`/info/documents/${currentFolder.id}`);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@ -125,6 +118,47 @@ export default function FolderViewer() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setDragOver(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: React.DragEvent) => {
|
||||
setDragOver(false)
|
||||
console.log("drag leave")
|
||||
}
|
||||
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setDragOver(false)
|
||||
const files = Array.from(e.dataTransfer.files)
|
||||
setFilesToUpload((prevFiles) => [...prevFiles, ...files])
|
||||
}
|
||||
|
||||
const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files || [])
|
||||
setFilesToUpload((prevFiles) => [...prevFiles, ...files])
|
||||
}
|
||||
|
||||
const uploadFiles = async () => {
|
||||
setIsUploading(true)
|
||||
if (filesToUpload.length > 0 && currentFolder && currentFolder.id) {
|
||||
const formData = new FormData()
|
||||
for (let file of filesToUpload) {
|
||||
formData.append('files', file)
|
||||
}
|
||||
try {
|
||||
// const response = await DocumentService.uploadFiles(currentFolder.id, formData, setUploadProgress);
|
||||
setIsUploading(false);
|
||||
setFilesToUpload([]);
|
||||
mutate(`/info/documents/${currentFolder.id}`);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setIsUploading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foldersLoading || documentsLoading) {
|
||||
return (
|
||||
<CircularProgress />
|
||||
@ -171,31 +205,84 @@ export default function FolderViewer() {
|
||||
))}
|
||||
</Breadcrumbs>
|
||||
|
||||
<Box>
|
||||
{currentFolder &&
|
||||
<Button
|
||||
LinkComponent="label"
|
||||
role={undefined}
|
||||
variant="outlined"
|
||||
tabIndex={-1}
|
||||
startIcon={
|
||||
isUploading ? <CircularProgress sx={{ maxHeight: "20px", maxWidth: "20px" }} variant="determinate" value={uploadProgress} /> : <UploadFile />
|
||||
}
|
||||
onClick={handleUploadClick}
|
||||
>
|
||||
<input
|
||||
type='file'
|
||||
ref={fileInputRef}
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
Загрузить
|
||||
</Button>
|
||||
}
|
||||
</Box>
|
||||
{currentFolder &&
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
|
||||
<Box>
|
||||
<Button
|
||||
LinkComponent="label"
|
||||
role={undefined}
|
||||
variant="outlined"
|
||||
tabIndex={-1}
|
||||
startIcon={
|
||||
isUploading ? <CircularProgress sx={{ maxHeight: "20px", maxWidth: "20px" }} variant="determinate" value={uploadProgress} /> : <UploadFile />
|
||||
}
|
||||
onClick={handleUploadClick}
|
||||
>
|
||||
<input
|
||||
type='file'
|
||||
ref={fileInputRef}
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
Загрузить
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{filesToUpload.length > 0 &&
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: '16px', border: '1px dashed gray', borderRadius: '8px', p: '16px' }}>
|
||||
<Box sx={{ display: 'flex', gap: '16px' }}>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<Upload />}
|
||||
onClick={uploadFiles}
|
||||
>
|
||||
Загрузить все
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant='outlined'
|
||||
startIcon={<Cancel />}
|
||||
onClick={() => setFilesToUpload([])}
|
||||
>
|
||||
Отмена
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Divider />
|
||||
|
||||
<Box>
|
||||
{filesToUpload.map((file, index) => (
|
||||
<Box key={index} sx={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px' }}>
|
||||
<Box>
|
||||
<InsertDriveFile />
|
||||
<span>{file.name}</span>
|
||||
</Box>
|
||||
|
||||
<IconButton sx={{ ml: 'auto' }} onClick={() => {
|
||||
setFilesToUpload(prev => {
|
||||
return prev.filter((_, i) => i != index)
|
||||
})
|
||||
}}>
|
||||
<Close />
|
||||
</IconButton>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
}
|
||||
|
||||
</Box>
|
||||
}
|
||||
|
||||
<List
|
||||
dense
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
sx={{
|
||||
backgroundColor: dragOver ? 'rgba(0, 0, 0, 0.1)' : 'inherit'
|
||||
}}
|
||||
>
|
||||
{currentFolder ? (
|
||||
documents?.map((doc: IDocument, index: number) => (
|
||||
@ -207,13 +294,13 @@ export default function FolderViewer() {
|
||||
/>
|
||||
{index < documents.length - 1 && <Divider />}
|
||||
</div>
|
||||
|
||||
))
|
||||
) : (
|
||||
folders?.map((folder: IDocumentFolder, index: number) => (
|
||||
<div key={`${folder.id}-${folder.name}`}>
|
||||
<ItemFolder
|
||||
folder={folder}
|
||||
index={index}
|
||||
handleFolderClick={handleFolderClick}
|
||||
/>
|
||||
{index < folders.length - 1 && <Divider />}
|
||||
|
@ -1,9 +1,17 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { AppBar, Box, Button, CircularProgress, Dialog, IconButton, Toolbar, Typography } from '@mui/material';
|
||||
import { ChevronLeft, ChevronRight, Close } from '@mui/icons-material';
|
||||
import { useDownload } from '../../hooks/swrHooks';
|
||||
import { ChevronLeft, ChevronRight, Close, Warning } from '@mui/icons-material';
|
||||
import { useDownload, useFileType } from '../../hooks/swrHooks';
|
||||
import { fileTypeFromBlob } from 'file-type/core';
|
||||
|
||||
import jsPreviewExcel from "@js-preview/excel"
|
||||
import '@js-preview/excel/lib/index.css'
|
||||
|
||||
import jsPreviewDocx from "@js-preview/docx"
|
||||
import '@js-preview/docx/lib/index.css'
|
||||
|
||||
import jsPreviewPdf from '@js-preview/pdf'
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
setOpen: (state: boolean) => void;
|
||||
@ -12,6 +20,108 @@ interface Props {
|
||||
setCurrentFileNo: (state: number) => void;
|
||||
}
|
||||
|
||||
interface ViewerProps {
|
||||
url: string
|
||||
}
|
||||
|
||||
function PdfViewer({
|
||||
url
|
||||
}: ViewerProps) {
|
||||
const previewContainerRef = useRef(null)
|
||||
|
||||
const [loadingPreview, setLoadingPreview] = useState(false)
|
||||
|
||||
const pdfPreviewer = jsPreviewPdf
|
||||
|
||||
useEffect(() => {
|
||||
if (previewContainerRef && previewContainerRef.current) {
|
||||
setLoadingPreview(true);
|
||||
pdfPreviewer.init(previewContainerRef.current)
|
||||
.preview(url)
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (previewContainerRef && previewContainerRef.current) {
|
||||
previewContainerRef.current = null
|
||||
}
|
||||
}
|
||||
}, [previewContainerRef])
|
||||
|
||||
return (
|
||||
<Box ref={previewContainerRef} sx={{
|
||||
width: '100%',
|
||||
height: '100%'
|
||||
}} />
|
||||
)
|
||||
}
|
||||
|
||||
function DocxViewer({
|
||||
url
|
||||
}: ViewerProps) {
|
||||
const previewContainerRef = useRef(null)
|
||||
|
||||
const [loadingPreview, setLoadingPreview] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (previewContainerRef && previewContainerRef.current) {
|
||||
setLoadingPreview(true);
|
||||
jsPreviewDocx.init(previewContainerRef.current)
|
||||
.preview(url)
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (previewContainerRef && previewContainerRef.current) {
|
||||
previewContainerRef.current = null
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Box ref={previewContainerRef} sx={{
|
||||
width: '100%',
|
||||
}} />
|
||||
)
|
||||
}
|
||||
|
||||
function ExcelViewer({
|
||||
url
|
||||
}: ViewerProps) {
|
||||
const previewContainerRef = useRef(null)
|
||||
|
||||
const [loadingPreview, setLoadingPreview] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (previewContainerRef && previewContainerRef.current) {
|
||||
setLoadingPreview(true);
|
||||
jsPreviewExcel.init(previewContainerRef.current)
|
||||
.preview(url)
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (previewContainerRef && previewContainerRef.current) {
|
||||
previewContainerRef.current = null
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Box ref={previewContainerRef} sx={{
|
||||
width: '100%',
|
||||
height: '100%'
|
||||
}} />
|
||||
)
|
||||
}
|
||||
|
||||
function ImageViewer({
|
||||
url
|
||||
}: ViewerProps) {
|
||||
return (
|
||||
<Box>
|
||||
<img alt='image-preview' src={url} />
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default function FileViewer({
|
||||
open,
|
||||
setOpen,
|
||||
@ -19,25 +129,9 @@ export default function FileViewer({
|
||||
currentFileNo,
|
||||
setCurrentFileNo
|
||||
}: Props) {
|
||||
const { file, isError, isLoading } = useDownload(currentFileNo >= 0 ? docs[currentFileNo]?.document_folder_id : null, currentFileNo >= 0 ? docs[currentFileNo]?.id : null)
|
||||
const { file, isError, isLoading: fileIsLoading } = useDownload(currentFileNo >= 0 ? docs[currentFileNo]?.document_folder_id : null, currentFileNo >= 0 ? docs[currentFileNo]?.id : null)
|
||||
|
||||
const [fileType, setFileType] = useState<any>("")
|
||||
|
||||
const getFileType = async (file: any) => {
|
||||
try {
|
||||
await fileTypeFromBlob(file).then(response => {
|
||||
setFileType(response)
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && file) {
|
||||
getFileType(file)
|
||||
}
|
||||
}, [isLoading])
|
||||
const { fileType, isLoading: fileTypeIsLoading } = useFileType(currentFileNo >= 0 ? docs[currentFileNo]?.name : null, currentFileNo >= 0 ? file : null)
|
||||
|
||||
const handleSave = async () => {
|
||||
const url = window.URL.createObjectURL(file)
|
||||
@ -60,7 +154,7 @@ export default function FileViewer({
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
>
|
||||
<AppBar sx={{ position: 'relative' }}>
|
||||
<AppBar sx={{ position: 'sticky' }}>
|
||||
<Toolbar>
|
||||
<IconButton
|
||||
edge="start"
|
||||
@ -90,7 +184,7 @@ export default function FileViewer({
|
||||
>
|
||||
<ChevronLeft />
|
||||
</IconButton>
|
||||
|
||||
|
||||
<IconButton
|
||||
color='inherit'
|
||||
onClick={() => {
|
||||
@ -113,8 +207,52 @@ export default function FileViewer({
|
||||
</Button>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
<Box>
|
||||
{file && <img src={window.URL.createObjectURL(file)} />}
|
||||
|
||||
<Box sx={{
|
||||
flexGrow: '1',
|
||||
overflowY: 'hidden'
|
||||
}}>
|
||||
{fileIsLoading || fileTypeIsLoading ?
|
||||
<Box sx={{
|
||||
display: 'flex',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center'
|
||||
}}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
:
|
||||
fileType === 'application/pdf' ?
|
||||
<PdfViewer url={window.URL.createObjectURL(file)} />
|
||||
:
|
||||
fileType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ?
|
||||
<ExcelViewer url={window.URL.createObjectURL(file)} />
|
||||
:
|
||||
fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ?
|
||||
<DocxViewer url={window.URL.createObjectURL(file)} />
|
||||
:
|
||||
fileType?.startsWith('image/') ?
|
||||
<ImageViewer url={window.URL.createObjectURL(file)} />
|
||||
:
|
||||
<Box sx={{ display: 'flex', gap: '16px', flexDirection: 'column', p: '16px' }}>
|
||||
<Box sx={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
|
||||
<Warning />
|
||||
<Typography>
|
||||
Предпросмотр данного файла невозможен.
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<Button variant='contained' onClick={() => {
|
||||
handleSave()
|
||||
}}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
</Box>
|
||||
}
|
||||
</Box>
|
||||
</Dialog>
|
||||
)
|
||||
|
@ -2,6 +2,7 @@ import useSWR from "swr";
|
||||
import RoleService from "../services/RoleService";
|
||||
import UserService from "../services/UserService";
|
||||
import { blobFetcher, fetcher } from "../http/axiosInstance";
|
||||
import { fileTypeFromBlob } from "file-type/core";
|
||||
|
||||
export function useRoles() {
|
||||
const { data, error, isLoading } = useSWR(`/auth/roles`, RoleService.getRoles)
|
||||
@ -68,10 +69,9 @@ export function useDocuments(folder_id?: number) {
|
||||
export function useDownload(folder_id?: number, id?: number) {
|
||||
const { data, error, isLoading } = useSWR(
|
||||
folder_id && id ? `/info/document/${folder_id}&${id}` : null,
|
||||
blobFetcher,
|
||||
folder_id && id ? blobFetcher : null,
|
||||
{
|
||||
revalidateOnFocus: false,
|
||||
revalidateOnMount: false
|
||||
revalidateOnFocus: false
|
||||
}
|
||||
)
|
||||
|
||||
@ -82,6 +82,22 @@ export function useDownload(folder_id?: number, id?: number) {
|
||||
}
|
||||
}
|
||||
|
||||
export function useFileType(fileName?: string, file?: Blob) {
|
||||
const { data, error, isLoading } = useSWR(
|
||||
fileName && file ? `/filetype/${fileName}` : null,
|
||||
file ? (key: string) => fileTypeFromBlob(file) : null,
|
||||
{
|
||||
revalidateOnFocus: false
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
fileType: data?.mime,
|
||||
isLoading,
|
||||
isError: error
|
||||
}
|
||||
}
|
||||
|
||||
export function useReport(city_id: number) {
|
||||
const { data, error, isLoading } = useSWR(
|
||||
city_id ? `/info/reports/${city_id}?to_export=false` : null,
|
||||
@ -96,10 +112,4 @@ export function useReport(city_id: number) {
|
||||
isLoading,
|
||||
isError: error
|
||||
}
|
||||
}
|
||||
|
||||
// export function useFileType(file?: Blob){
|
||||
// const { data, error, isLoading } = useSWR(
|
||||
// file ? `${file.}`
|
||||
// )
|
||||
// }
|
||||
}
|
@ -6,9 +6,6 @@ import { registerSW } from 'virtual:pwa-register'
|
||||
import { ThemeProvider } from '@emotion/react'
|
||||
import { createTheme } from '@mui/material'
|
||||
import { ruRU } from '@mui/material/locale'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
const theme = createTheme(
|
||||
{
|
||||
@ -33,9 +30,7 @@ const updateSW = registerSW({
|
||||
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<ThemeProvider theme={theme}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
<App />
|
||||
</ThemeProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
|
Reference in New Issue
Block a user