ai-kit-file-management
TypeScript icon, indicating that this package has built-in type declarations

0.7.3 • Public • Published

AI-KIT: File-Management

This is the frontend library for the AI-KIT module File-Management. Use it in conjunction with the django package django-ai-kit-file-management in order to get a functioning File-Management running in your app in no time.

Installation

You can easily install AI-KIT: File-Management via npmjs. Using npm, run

npm install ai-kit-file-management

Using yarn, run

yarn add ai-kit-file-management

Quickstart

API Reference

This module provides a few hooks, as well as some material-ui-styled components where these hooks are already put to use.

FileData

This type describes the default data structure of file objects as per django-ai-kit-auth. It has the following fields:

  • id: number database id of the file object
  • file: string URL to download the file
  • creator: number|null database id of the user who uploaded the file, or null if the user was not logged in when they uploaded it.
  • format: string the file type in mime-type notation (e.g. image/jpeg, audio/mpeg, video/mp4 etc.)
  • name: string the filename

To use it, import it from 'ai-kit-file-management/dist/hooks/useUpload'.

Translator

Several components use a translator function for displaying user-facing strings. This type is defined as (key: string) => string and will receive strings of the form auth:Path.To.Key, conforming with i18next.

If you don't need dynamic translation and are just interested in a different supported language than the default (English), you can pass one of the predefined translator functions exported by ai-kit-file-management. Currently the only choice is en. If you need to translate only a few strings differently, we would advise you to inspect the source code in order to find the correct keys and write a wrapper function around one of the predefined translators in order to intercept the translation of those keys.

Example

import { DropZone, en } from 'ai-kit-file-management';

const customKey = 'file-management:DropZone.DragNDrop';
const customValue = 'Drop your files here, please!';
const t = (key: string) => {
  if (key === customKey) return customValue;

  return en(key);
};

export const CustomDropZone: FC = () => (
  <DropZone translator={t} />
);

If you would like to use dynamic translations, we suggest to use i18next and to pass your translator function t to the respective components. That way, the components are re-rendered whenever the language changes. In that case, you need to provide all the translations by yourself, in the namespace file-management. To get started, you can copy the .json files containing our translations from the dist/internationalization folder of this module.

Example

import { useTranslation } from 'react-i18next';
import { DropZone } from 'ai-kit-file-management';
...

const App: FC = () => {
  const { t } = useTranslation(['file-management']);

  return (
    <DropZone translator={t} />
  );
};

useFileChooser

This hook provides a simple way for your functional components to open a system file chooser dialog. Behind the scenes, an invisible <input /> element is rendered in a separate DOM branch, and if the function returned by this hook is called, a click on that element is simulated in order to open the browser's file chooser dialog.

Parameters

  • config: FileChooserConfig, containing the following fields:
    • onFileSelect?: (list: File[]) => void is called when one or more files are selected from the dialog
    • accept?: string specifies a filter of files, which are shown in the dialog. This string is passed to an input element with type="file" in the DOM. For the format and more background information, see the MDN Web Docs
    • multiple?: boolean if this is set to true, the user can select multiple files at once.
    • capture?: string from the documentation: The capture attribute value is a string that specifies which camera to use for capture of image or video data, if the accept attribute indicates that the input should be of one of those types. A value of user indicates that the user-facing camera and/or microphone should be used. A value of environment specifies that the outward-facing camera and/or microphone should be used. If this attribute is missing, the user agent is free to decide on its own what to do. If the requested facing mode isn't available, the user agent may fall back to its preferred default mode.
    • id?: string defines the id of the invisible <input /> element used behind the scenes

Returns

openFileDialog: () => void a function that you can call in order to open the file dialog. If the user then selects a file, onFileSelect is called with the selection, otherwise nothing happens.

Example

import React, { FC } from 'react';
import { useFileChooser } from 'ai-kit-file-management';

export const FileChooser: FC = () => {
    const openFileDialog = useFileChooser({
        onFileSelect: (list) => console.log('selected files:', list),
        multiple: true,
    });

    return <div onClick={openFileDialog}>Choose File</div>;
};

useUpload

This hook provides a function with which you can upload a list of files directly to the backend (provided you use django-ai-kit-file-management). It also sets up the objects it returns for cancellation and lets you track the upload progress and error or cancellation status.

Parameters

  • config: UploadConfig<DataType = FileData> containing the fields:
    • apiUrl: string the url to the upload endpoint on the backend. If you provide a baseURL via requestConfig, apiUrl will be appended to it to form the complete url.
    • requestConfig?: AxiosRequestConfig Since we use axios internally for the handling of requests, you can pass a configuration containing credentials headers etc. in order to get the call to succeed (see the axios documentation). If you use ai-kit-auth as well, you can simply pass the axiosRequestConfig obtained from useUserStore or AuthFunctionContext in order to add valid credentials to the upload request.
    • maxFileSize?: number the maximum allowed size of a single file. If the user attempts to upload a larger file, the upload will not even be attempted and an error is thrown. If no value is provided, no checks on the frontend are performed.
    • onReady?: (data: DataType, key: string) => void is called whenever an upload succeeds. The data parameter is the result returned by the backend, and the generic type DataType defaults to FileData, an interface describing the default data returned by django-ai-kit-file-management. In case you provide your own file serializer there, you will need to specify the data structure in order to tell typescript about the available fields. The key is an identifier for the file that was uploaded. You can compare it with the fileKey field of the UploadFileInfo objects returned by the upload function.
    • onUploadProgress?: (progress: number, key: string) => void is called whenever the browser reports progress for an upload. progress is a number between 0 and 100 inclusively, and 100 means that the upload succeeded and was acknowledged by the server. The key is an identifier for the file that was uploaded. You can compare it with the fileKey field of the UploadFileInfo objects returned by the upload function.
    • onError?: (error: Error, key: string) => void is called when an error occurred during the upload of a file. The error object is passed to this callback unfiltered, and can be any range of errors. You need to decide which errors to handle, and how. The key is an identifier for the file that was uploaded. You can compare it with the fileKey field of the UploadFileInfo objects returned by the upload function.
    • onCancel?: (key: string) => void is called by the onCancel function on a UploadFileInfo object returned by the upload function, regardless of whether the corresponding file was uploaded successfully already or not.

Returns

upload: (fileList: File[]) => UploadFileInfo[]

This function can be called with a list of files in order to immediately upload them. You can pass this function as config.onFileSelect to useFileChooser in order to immediately upload selected files.

The return value is an array of UploadFileInfos, which in turn contain the following fields:

  • fileName: string name of the file
  • fileSize: string the size of the file in bytes
  • fileKey: string a key to identify the file in upload events and identify them during callbacks onReady, onUploadProgress, onError and onCancel.
  • onCancel: () => void a function which, when called, cancels the upload (if it is still ongoing) and calls onCancel provided with the config to useUpload.

Example

import React, { FC } from 'react';
import { useFileChooser, useUpload } from 'ai-kit-file-management';

export const QuickUpload: FC = () => {
    const upload = useUpload({apiUrl: 'www.example.com/api/v1/upload/'});
    const openFileDialog = useFileChooser({ onFileSelect: upload });

    return <div onClick={openFileDialog}>Upload!</div>;
};

UploadBase

This component is a styled button which opens a file chooser dialog and immediately uploads the chosen files.

Props

  • <DataType = FileData> a generic parameter defining the data structure expected from the backend when uploading a file.
  • uploadConfig: UploadConfig<DatatType> see parameters of useUpload
  • fileChooserConfig?: FileChooserConfig see parameters of useFileChooser

Example

import React, { FC } from 'react';
import { UploadBase } from 'ai-kit-file-management';

export const Dashboard: FC = () => (
    <div>
        {/* ...beautiful dashboard code... */}
        <UploadBase
            uploadConfig={{ apiUrl: 'www.example.com/api/v1/upload/' }}
        />
        {/* ...beautiful dashboard code... */}
    </div>
);

DropZone

This component renders a nice drop field for files.

Props

  • fileChooserConfig?: FileChooserConfig see parameters of useFileChooser
  • translator?: Translator a function for translating user facing strings

Example

import React, { FC } from 'react';
import { DropZone } from 'ai-kit-file-management';

export const Dashboard: FC = () => (
    <div>
        {/* ...beautiful dashboard code... */}
        <DropZone
            fileChooserConfig={{
                onFileSelect: (list: File[]) => list.forEach(
                    (file) => console.log('file', file.name, 'was selected')),
            }}
        />
        {/* ...beautiful dashboard code... */}
    </div>
);

FileUploadProgress

This component shows the progress of a single file, which is being uploaded, and renders a button for cancelling the upload. It is used by DropAndUpload.

Props

This component requires all the fields of UploadFileInfo (see useUpload):

  • fileName: string name of the file
  • fileSize: string the size of the file in bytes
  • fileKey: string a key to identify the file in upload events
  • onCancel: () => void a function which cancels the upload

Furthermore, it takes these additional properties:

  • progress?: number represents the upload progress in percent
  • error?: string is displayed instead of a progress bar, if present
  • noBorder?: boolean if true, no border is drawn around the component
  • translator?: Translator a function for translating user facing strings

Example

import React, { FC, useState, useEffect } from 'react';
import { FileUploadProgress, useUpload } from 'ai-kit-file-management';
import { UploadFileInfo } from 'ai-kit-file-management/dist/hooks/useUpload';

export const UploadFileList: FC = ({ files: File[] }) => {
    const [progress, setProgress] = useState<UploadFileInfo[]>([]);

    const handleUploadProgress = (progress: number, key: string) => {
      setProgress((prev) => prev.map(
        (oldProgress) => (oldProgress.fileKey !== key ? oldProgress : ({
          ...oldProgress,
          progress,
        })),
      ));
    };

    const upload = useUpload({
      apiUrl: 'www.example.com/api/v1/upload/',
      onUploadProgress: handleUploadProgress,
    });

    useEffect(() => {
      setProgress(upload(files);
    }, [files]);

    return (
      <div>
        {progress.map((uploadProgress) => (
          <FileUploadProgress
            { ...uploadProgress }
          />
        ))}
      </div>
    );

DropAndUpload

This component consists of a DropZone, which immediately uploads any files dropped into it, and optionally a list of FileUploadProgresses showing the status of those uploads.

Props

  • <DataType = FileData> a generic parameter defining the data structure expected from the backend when uploading a file.
  • showList?: boolean whether or not to show progress of individual files (default: false)
  • uploadConfig: UploadConfig<DataType> see parameters of useUpload
  • fileChooserConfig?: Omit<FileChooserConfig, 'onFileSelect'> see parameters of useFileChooser. The onFileSelect cannot be provided, because it is defined by DropAndUpload itself.
  • translator?: Translator a function for translating user facing strings

Example

import React, { FC } from 'react';
import { DropAndUpload } from 'ai-kit-file-management';

export const Dashboard: FC = () => (
    <div>
        {/* ...beautiful dashboard code... */}
        <DropAndUpload
            showList
            uploadConfig={{
                apiUrl: '/files/upload/',
            }}
        />
        {/* ...beautiful dashboard code... */}
    </div>
);

DropAndUploadSingle

Similarly to DropAndUpload, this component consists of a DropZone, which immediately uploads a file dropped into it. However, after a file has been dropped, the DropZone is replaced by a FileUploadProgress showing the status of that upload. The use is not able to upload another file until they click the close button on the FileUploadProgress, cancelling the upload if it is still ongoing. Also, the

Props

  • <DataType = FileData> a generic parameter defining the data structure expected from the backend when uploading a file.
  • showList?: boolean whether or not to show progress of individual files (default: false)
  • uploadConfig: UploadConfig<DataType> see parameters of useUpload
  • fileChooserConfig?: Omit<FileChooserConfig, 'onFileSelect'|'multiple'> see parameters of useFileChooser. The onFileSelect cannot be provided, because it is defined by DropAndUpload itself. multiple cannot be provided since only one file is allowed to be chosen.
  • translator?: Translator A translator function for user-facing strings

Example

import React, { FC } from 'react';
import { DropAndUploadSingle } from 'ai-kit-file-management';

export const ThumbnailModalContent: FC = () => (
    <div>
        <DropAndUploadSingle
            uploadConfig={{
                apiUrl: '/files/upload/',
            }}
        />
    </div>
);

Readme

Keywords

Package Sidebar

Install

npm i ai-kit-file-management

Weekly Downloads

1

Version

0.7.3

License

MIT

Unpacked Size

60.8 kB

Total Files

25

Last publish

Collaborators

  • ambient-innovation