Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

Chonky.io + ReactJS Class component Full features

Show how to use Chonky file manager with ReactJS using a Class component: Includes :

-Create Folder

-Delete Files

-Upload File

etc...

question from:https://stackoverflow.com/questions/65887042/chonky-io-reactjs-class-component-full-features

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

import React, { } from 'react';
import {
    ChonkyActions,
    ChonkyFileActionData,
    FileArray,
    FileBrowserProps,
    FileData,
    FileHelper,
    FullFileBrowser,
    setChonkyDefaults
} from 'chonky';

//import { Position, Toaster, Intent } from "@blueprintjs/core";
//import { ChonkyIconFA } from 'chonky-icon-fontawesome';


interface CustomFileData extends FileData {
    parentId?: string;
    childrenIds?: string[];
}
interface CustomFileMap {
    [fileId: string]: CustomFileData;
}

//setChonkyDefaults({ iconComponent: ChonkyIconFA });

class CustomChonky extends React.Component<any, any> {
    constructor(props:any)
    {
      super(props)
      
      this.state = {

        files:[null],
        idCounter :0,
        fileMap:[null],
        currentFolderId:"",

        baseFileMap:[null],
        rootFolderId:"",

        currentFolderIdRef:null,

        folderChain : []
      };
   
    }

    componentDidMount(){

        // Init
        this.prepareCustomFileMap();

    }



    setCurrentFolderId = (folderId:string) => {

        this.setState({currentFolderId : folderId, currentFolderIdRef : folderId});

        // Update files chain
        this.useFiles(this.state.fileMap, folderId);

    }

    prepareCustomFileMap = () => {
        
        // Sample Data
        var DemoFsMap = 
        {"rootFolderId":"qwerty123456","fileMap":{"qwerty123456":{"id":"qwerty123456","name":"Archivage","isDir":true,"childrenIds":["Factures Clients", "Factures Fournisseurs", "Devis"],"childrenCount":3},
            "Factures Clients":{"id":"Factures Clients","name":"Factures Clients","isDir":true,"modDate":"2020-10-24T17:48:39.866Z","childrenIds":[],"childrenCount":0,"parentId":"qwerty123456"},
            "Factures Fournisseurs":{"id":"Factures Fournisseurs","name":"Factures Fournisseurs","isDir":true,"modDate":"2020-10-24T17:48:39.866Z","childrenIds":[],"childrenCount":0,"parentId":"qwerty123456"},
            "Devis":{"id":"Devis","name":"Devis","isDir":true,"modDate":"2020-10-24T17:48:39.866Z","childrenIds":[],"childrenCount":0,"parentId":"qwerty123456"}
        }}
        // Simulate API CALL Timeout
        setTimeout(() => {
            
            // console.log("gaymaaji");

            const baseFileMap = (DemoFsMap.fileMap as unknown) as CustomFileMap;
            const rootFolderId = DemoFsMap.rootFolderId;
            
            // console.log(baseFileMap);

            this.setState({ baseFileMap : baseFileMap, fileMap : baseFileMap, rootFolderId : rootFolderId, currentFolderIdRef:rootFolderId });

            // USE FILES
            this.useFiles(baseFileMap, rootFolderId);
            this.setCurrentFolderId(rootFolderId);

        }, 1000);
                
            
              
           
    };

    useFiles = (fileMap: CustomFileMap, currentFolderId: string) => {
 
        const currentFolder = fileMap[currentFolderId];
        const childrenIds = currentFolder.childrenIds!;
        const files = childrenIds.map((fileId: string) => fileMap[fileId]);
        // console.log(files);
        this.setState({files : files})

        this.useFolderChain(fileMap, currentFolderId);

    }

    useFolderChain = (
        fileMap: CustomFileMap,
        currentFolderId: string
    ) => {
        
        const currentFolder = fileMap[currentFolderId];

        const folderChain = [currentFolder];

        let parentId = currentFolder.parentId;
        while (parentId) {
            const parentFile = fileMap[parentId];
            if (parentFile) {
                folderChain.unshift(parentFile);
                parentId = parentFile.parentId;
            } else {
                break;
            }
        }

        this.setState({folderChain : folderChain});
    }



    resetFileMap = () => {
        this.setState({fileMap : this.state.baseFileMap })
        this.setState({currentFolderId :  this.state.rootFolderId })
    }

    deleteFiles = (files: CustomFileData[]) => {
         
            // Create a copy of the file map to make sure we don't mutate it.
            const newFileMap = { ...this.state.fileMap };

            files.forEach((file) => {
                // Delete file from the file map.
                delete newFileMap[file.id];

                // Update the parent folder to make sure it doesn't try to load the
                // file we just deleted.
                if (file.parentId) {
                    const parent = newFileMap[file.parentId]!;
                    const newChildrenIds = parent.childrenIds!.filter(
                        (id) => id !== file.id
                    );
                    newFileMap[file.parentId] = {
                        ...parent,
                        childrenIds: newChildrenIds,
                        childrenCount: newChildrenIds.length,
                    };
                }
            });
 
            this.setState({fileMap : newFileMap })
            this.useFiles(this.state.fileMap, this.state.currentFolderIdRef);
            
    };

    moveFiles = (
        files: CustomFileData[],
        source: CustomFileData,
        destination: CustomFileData) => {

            const newFileMap = { ...this.state.fileMap };
            const moveFileIds = new Set(files.map((f) => f.id));

            // Delete files from their source folder.
            const newSourceChildrenIds = source.childrenIds!.filter(
                (id) => !moveFileIds.has(id)
            );
            newFileMap[source.id] = {
                ...source,
                childrenIds: newSourceChildrenIds,
                childrenCount: newSourceChildrenIds.length,
            };

            // Add the files to their destination folder.
            const newDestinationChildrenIds = [
                ...destination.childrenIds!,
                ...files.map((f) => f.id),
            ];
            newFileMap[destination.id] = {
                ...destination,
                childrenIds: newDestinationChildrenIds,
                childrenCount: newDestinationChildrenIds.length,
            };

            // Finally, update the parent folder ID on the files from source folder
            // ID to the destination folder ID.
            files.forEach((file) => {
                newFileMap[file.id] = {
                    ...file,
                    parentId: destination.id,
                };
            });

        this.setState({fileMap : newFileMap })
        this.useFiles(this.state.fileMap, this.state.currentFolderIdRef);
        

    }

    createFolder = (folderName: string) => {

        const newFileMap = { ...this.state.fileMap };
        var idCounter = this.state.idCounter;

        console.log(newFileMap);

        // Create the new folder
        const newFolderId = `new-folder-${idCounter++}`;

        newFileMap[newFolderId] = {
            id: newFolderId,
            name: folderName,
            isDir: true,
            modDate: new Date(),
            parentId: this.state.currentFolderIdRef,
            childrenIds: [],
            childrenCount: 0,
        };


        // Update parent folder to reference the new folder.
        const parent = newFileMap[this.state.currentFolderIdRef];
        newFileMap[this.state.currentFolderIdRef] = {
            ...parent,
            childrenIds: [...parent.childrenIds!, newFolderId],
        };

        this.setState({fileMap : newFileMap })
        this.useFiles(this.state.fileMap, this.state.currentFolderIdRef);
        
        

    }


    uploadFile = () => {
            
        var input = document.createElement('input');
        input.type = 'file';
        input.name = 'file';

                    
        input.onchange = (e) => { 
            //@ts-ignore
            var file = e.target.files[0]; 
           
            var formData = new FormData();
            formData.append('file',file);

            /*const AppToaster = Toaster.create({
                className: "recipe-toaster",
                position: Position.TOP,
                });*/
            // console.log(file);
            TesseractServices._uploadFile(formData).then(resp =>{

                var savedFile = resp.data.files[0];
                var fileName = savedFile.filename;
                
                // UPDATE FIE /////////////////////////////

                    const newFileMap = { ...this.state.fileMap };
                    var idCounter = this.state.idCounter;
        
                    // Create the new file
                    // const fileBase = "https://dscompta-api.herokuapp.com/files/";
                    const newFileId = `new-file-${idCounter++}`;
                    newFileMap[newFileId] = {
                        id: newFileId,
                        name: fileName,
                        isDir: false,
                        modDate: new Date(),
                        parentId: this.state.currentFolderIdRef,
                        childrenIds: [],
                        childrenCount: 0,
                    };
        
                    // Update parent folder to reference the new folder.
                    const parent = newFileMap[this.state.currentFolderIdRef];
                    newFileMap[this.state.currentFolderIdRef] = {
                        ...parent,
                        childrenIds: [...parent.childrenIds!, newFileId],
                    };
        
                 // AppToaster.show({ intent:Intent.SUCCESS, message: "Fichier archivé avec succés !" });

                //     return newFileMap;
                this.setState({fileMap : newFileMap })
                this.useFiles(this.state.fileMap, this.state.currentFolderIdRef);
                

                // UPDATE FILE ////////////////////////////////

                }).catch((err)=>{
                
                console.log(err);
    
                });
        }

        input.click();


    }



    render() {
       
       
        const fileActions = [
            ChonkyActions.CreateFolder,
            ChonkyActions.UploadFiles,
            ChonkyActions.DownloadFiles,
        ];
    

        const useFileActionHandler = (
            setCurrentFolderId: (folderId: string) => void,
            deleteFiles: (files: CustomFileData[]) => void,
            moveFiles: (files: FileData[], source: FileData, destination: FileData) => void,
            createFolder: (folderName: string) => void,
            uploadFile: (fileName: string) => void
        ) => {
                return (data: ChonkyFileActionData) => {
                    if (data.id === ChonkyActions.OpenFiles.id) {
                        const { targetFile, files } = data.payload;
                        const fileToOpen = targetFile ?? files[0];
                        if (fileToOpen && FileHelper.isDirectory(fileToOpen)) {
                            console.log(fileToOpen.id);
                            setCurrentFolderId(fileToOpen.id);
                        

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...