@filerobot/core

Core module for the extensible JavaScript file upload widget with support for drag&drop, resumable uploads, previews, restrictions, file processing/encoding, remote providers like Instagram, Dropbox, Google Drive, S3 and more.

Usage no npm install needed!

<script type="module">
  import filerobotCore from 'https://cdn.skypack.dev/@filerobot/core';
</script>

README

@filerobot/core

The core module of the Filerobot Media Asset Widget (FMAW). This module contains all common settings shared across all FMAW plugins and can be used standalone in your upload workflows to interact with Filerobot DAM.

Usage

From NPM

The module can be installed from NPM as @filerobot/core

npm install --save @filerobot/core

then

import Filerobot from '@filerobot/core'
...
...
...
const filerobot = Filerobot(optionsObject)

From CDN

If installed via the CDN link, the plugin is inside the Filerobot global object as Filerobot.Core

const FilerobotCore = window.Filerobot.Core
...
...
...
const filerobot = FilerobotCore(optionsObject)

Module's styles

import '@filerobot/core/dist/style.css'

or via the minified versions

import '@filerobot/core/dist/style.min.css'

The Core's styles must be imported before the filerobot's plugins' styles.

Options

The Explorer supports multiple options to customize the plugin according to your needs. Required attributes are marked with (required).

An example configuration is provided below:

{
  id: 'filerobot',
  dev: false,
  container: 'try',
  securityTemplateID: '...',
  autoProceed: false,
  allowMultipleUploads: true,
  debug: false,
  logger: justErrorsLogger,
  restrictions: {
    maxFileSize: null,
    maxNumberOfFiles: null,
    minNumberOfFiles: null,
    allowedFileTypes: null
  },
  onBeforeFileAdded: (currentFile, files) => currentFile,
  onBeforeUpload: (files) => files,
}

container: string (required)

default: undefined

The container token (Filerobot token) that will be used in all the widget's modes & plugins in the whole widget ex. (listing files/folders, uploading, renaming, deleting...etc.). Register for an account at filerobot.com to obtain a token.

securityTemplateID: string (required)

default: undefined

The Security Template ID used for the the FMAW to request session-specific API access keys, also known as SASS key. Security Templates are created in the Filerobot Asset Hub and define permissions and validity for SASS keys. They work similar to oAuth2 tokens.

id: string (optional)

default: 'filerobot'

The unique indentifier used for identifying the widget's instance (# in HTML selector).

dev: boolean (optional)

default: false

Enables the development mode which sends all requests to development server if provided with true value, otherwise all the endpoints used would refer to the production server.

autoProceed: boolean (optional)

default: false

If set to true, the upload process of one or multiple assets will start automatically after drag and drop in the upload area or selection from the user's local explorer. If set to false, the pre-upload features will be available to the user before starting the upload via the Upload button.

allowMultipleUploads: boolean (optional)

default: true

If set to false, only one upload will be possible simulateneously.

debug: boolean (optional)

default: false

Turns on the debug mode by exposing the plugin's debug information to the global window object and turns on the logger.

logger: object (optional)

default: errors only logger

errorsLogger = {
  debug: (...args) => {},
  warn: (...args) => {},
  error: (...args) => console.error(`[Filerobot] [${getTimeStamp()}]`, ...args)
}

restrictions: object (optional)

default:

{
  maxFileSize: null,
  maxNumberOfFiles: null,
  minNumberOfFiles: null,
  allowedFileTypes: null
}

Upload restrictions:

  • maxFileSize (integer | null - optional): maximum file size in bytes.
  • maxNumberOfFiles (number | null - optional): maxmimum number of files to be uploaded simultaneously.
  • minNumberOfFiles (number | null - optional): minimum number of files before upload can start.
  • allowedFileTypes (array | null - optional): accepted file types or extensions, eg. ['image/*', 'image/jpeg', '.jpg'].

Upload restrictions can also be governed in the backend by the Security Template configured.

onBeforeFileAdded: (currentFile, files) => ... (optional)

default: (currentFile, files) => currentFile

Gives the possibility to do some checks before adding the file to the state's object,

  • if the function returns true, the file is added to the state.
  • if the function returns a modified file object the returned object would be added to the state.
  • if the function returns false, the file is not added to the state.

onBeforeUpload: (files) => ... (optional)

default: onBeforeUpload: (files) => files

Gives the possibility to do some checks before starting the upload process

  • if the function returned true the upload would start.
  • if returned files object the returned object would be processed.
  • if returned false the uploading process won't start.

language: string (optional)

default: 'en'

Used to determine which language to use from the widget's backend translated languages.

locale: object (optional)

default: default locales inside lib/defaultLocale.js

You can override the default labels and translations by specifying an alternative locale file path here. You could pass any object/translation file from @filerobot/locale. If you have provided value for this property it would override both the default translations coming from the defaultLocale file and the backend translations, if you didn't provide any value for it the priority would go for the backend translations then the default locales from the mentioned file.

Methods

filerobot.getID()

Gets the Filerobot Media Asset Widget's instance ID.

filerobot.use(plugin, pluignOptions)

Adds a plugin to the Filerobot Media Asset Widget's instance:

import Filerobot from '@filerobot/core'
import Explorer from '@filerobot/explorer'

const filerobot = Filerobot()
filerobot.use(Explorer, {...})

Refer to the individual plugin's documentation page for available configuration and customization options.

filerobot.getPlugin(pluginId)

Returns the plugin's instance with the provided id for accessing its methods & state.

filerobot.removePlugin(pluginInstance)

Removes a currently initialized plugin by passing the plugin's instance retrieved from the getPlugin method.

filerobot.setOptions(options)

Passes Options to the Widget to change options set during initialization:

import Filerobot from '@filerobot/core'

const filerobot = Filerobot()
filerobot.setOptions({
  autoProceed: true
})

Individual plugin options can also be changed by using getPlugin

import Filerobot from '@filerobot/core'

const filerobot = Filerobot()
filerobot.use(Explorer, { id: 'Explorer' })
filerobot.getPlugin('Explorer').setOptions({
  animateOpenClose: false
})

filerobot.addFile(fileObject)

Adds a file into the widget's state and returns the temporary generated ID for that file.

restrictions are checked and onBeforeFileAdded called before adding the file.

filerobot.getFile(fileID)

Gets the file object using its ID.

filerobot.removeFile(fileID)

Removes a file from the widget's state via its ID.

filerobot.getFiles()

Returns all the file objects currently loaded in the widget.

filerobot.upload()

An async function that starts uploading files, returns a promise resolved with an object result: { successful, failed } containing:

  • successful: array with file objects successfully uploaded.
  • failed: array with files objects for which upload failed.

filerobot.retryAll()

Retries all the failed uploads.

filerobot.retryUpload(fileID)

Retries a failed upload for a file referrenced by its ID.

filerobot.cancelAll()

Cancels all file uploads.

filerobot.setState(object)

Updates the internal state of the widget (not very useful for you).

filerobot.getState()

Returns the internal state of the widget.

filerobot.setFileState(fileID, state)

Adds a state into the file's object that's inside the files object of the internal widget's state.

filerobot.setInfo(fileInfo)

Updates the info object of all the files that would be uploaded with the provided fileInfo object paramter.

filerobot.setFileInfo(fileID, fileInfo)

Updates the info object of the file that would be uploaded (referred to with the fileID) with the provided fileInfo object paramter.

filerobot.reset()

Returns everything to the initial state of the widget ex. stops all the files uploading, reset their progress and removes all of them.

filerobot.close()

Removes all the installed plugins & closes the current widget's instance.

filerobot.on('event', handler)

Adds/Subscribe a handler/callback function to be called on emitting/firing the specified filerobot event, full list of available events.

filerobot.once('event', handler)

Same as filerobot.on but the handler is removed after being called once.

filerobot.off('event', handler)

Un-subscribe/Removes the specified handler for filerobot's event.

filerobot.info(message, type, timeout)

Shows an informer with the specified message to the user:

  • message (string | object - required): Defines the message to be shown to the user, either a string ex. Some message or { message: 'Some headline message', details: 'Detailed message would be shown on hovering the informer' }.
  • type (string - optional): choses the type of the informer whether info, warning or success default is info.
  • timeout (number - optional): The duration which the message would still be shown for in milliseconds, default 3000ms = 3s.

filerobot.log(message, type)

Logs a message in the logger:

  • message (string - required): the message would be logged/added/shown in the logger.
  • type (string - optional): the type of that logged message whether debug/info, warning or error, default is debug.

Events

The widget emits different events that you could subscribe to or add your handler to be called with the provided arguments passed while emitting/firing the event, the events are listed below with examples show the parameters for handler:

Emitted

file-added

Emitted when a file has been added to the selected files for uploading.

params:

  • file: The file object whom thumbnail is generated.

example

filerobot.on('file-added', (newFile) => {
  console.log('The new file object which is added:', newFile)
})

file-removed

Emitted when a file has been removed from the selected files for uploading.

params:

  • file: The file object removed.
  • deleteionReason: The reason for deleting the file or from where the deletion has done might be provided or not.

example

filerobot.on('file-removed', (removedFile, reason) => {
  console.log(`The file ${removedFile.name} is removed because ${reason}, file's object:`, removedFile)
})

upload

Emitted on creating a new upload process.

params:

  • object: An object contains both the uploading process ID and the the files IDs for files to be uploaded, ex. { id: uploadID, fileIDs: fileIDs }.

example

filerobot.on('upload', (uploadProcess) => {
  console.log('Upload started: ', uploadProcess.uploadID)
  console.log('Contains the following file IDs', uploadProcess.fileIDs)
})

restriction-failed

Emitted when the restriction checking is failed and there is a file doesn't meet the restrictions.

params:

  • file: The file object that has failed the check.
  • error: The error faced/fired during the check.

example

filerobot.on('restriction-failed', (file, error) => {
  console.log('Couldnt process the following file object', file)
  console.log('As the following error fired:', error)
})

upload-progress

Emitted when there is a progress of some file uploading in the upload process.

params:

  • file: The file object that has some progress in its uploading.
  • progress: An object contains the progress of the file being uploaded, ex. { filerobot: plugin's instance, bytesUploaded: 1500, bytesTotal: 3500 }.

example

filerobot.on('upload-progress', (file, progress) => {
  console.log('The following file object progressed', file)
  console.log('The progress object is as following', progress)
})

upload-success

Emitted when a file is successfully uploaded.

params:

  • file: The file object that has uploaded.
  • uploadResponse: The upload request response received.

example

filerobot.on('upload-success', (file, response) => {
  console.log(`The ${file.name} with the object ${file} is uploaded and the whole respones`, response)
})

upload-error

Emitted when a file faced some error/issue while uploading.

params:

  • file: The file object which fired the error.
  • error: The error faced while uploading.

example

filerobot.on('upload-error', (file, error) => {
  console.log('File faced that error while uploading', file, error)
})

upload-retry

Emitted on some file uploading is retried.

params:

  • fileID: The ID of the file which its upload process is retried.

example

filerobot.on('upload-retry', (fileID) => {
  console.log('The following file ID is being re-uploaded:', fileID)
})

progress

Emitted on having a progress of an upload process's total progress.

params:

  • totalProgress: The total progress value of the current uploading process.

example

filerobot.on('progress', (totalProgress) => {
  console.log('The uploading total progress for now: ', totalProgress)
})

cancel-all

Emitted when the whole upload process is canceled (all files uploading are canceld).

params: No params returned.

example

filerobot.on('cancel-all', () => {
  console.log('The upload is canceled')
})

complete

Emitted when the whole upload process done and completed.

params:

  • completionObject: An object contains the results of the completed upload process, ex. { failed: failedFiles, uploadID: ..., successful: uploadedFiles }.

example

filerobot.on('complete', ({ failed, uploadID, successful }) => {
  console.log(`The upload ${uploadID} is completed with following results success then failed files`, successful, failed)
})

items-deleted

Emitted when files/folders are deleted.

params:

  • detailsObject: An object contains details of removed items, ex. { removedFolders: [...], removedFiles: [...] }.

example

filerobot.on('items-deleted', ({ removedFolders, removedFiles }) => {
  console.log('Items deleted:')
  console.log('Removed folders:', removedFolders)
  console.log('Removed files:', removedFiles)
})

error

Emitted when the whole upload process faced an error.

params:

  • error: The error shown of the uploading process.
  • uploadID: The ID of the errored uploading process.

example

filerobot.on('error', (error, uploadID) => {
  console.log(`The upload with ID ${uploadID} faced this error while uploading`, error)
})

reset-progress

Emitted when the upload's progress is reset to 0.

params: No params returned.

example

filerobot.on('reset-progress', () => {
  console.log('The progress is reset')
})

info-visible

Emitted on showing an info message to the user.

params: No params returned.

example

filerobot.on('info-visible', () => {
  console.log('inFo message shown.')
})

info-hidden

Emitted on hiding an info message that were shown to the user.

params: No params returned.

example

filerobot.on('info-hidden', () => {
  console.log('The progress is hidden.')
})

explorer:modal-open

Emitted on opening the widget in a modal through the explorer plugin.

params: No params returned.

example

filerobot.on('explorer:modal-open', () => {
  console.log('The widget\'s explorer modal is opened .')
})

explorer:modal-close

Emitted on closing the widget's main modal.

params: No params returned.

example

filerobot.on('explorer:modal-close', () => {
  console.log('The widget\'s modal is closed.')
})

export

emitted when the user clicks over final export button of export panel.

params:

  • files: An array of files checked/selected for exporting.
  • popupExportSucessMsgFn: A function if called will show exported successfully pop-up to the user.
  • downloadFilesPackagedFn: A function if called will download files (the files passed in the first argument if nothing passed then the files exported will be used) as ZIP and show download progress in filerobot (item's UUID is used & must exists on backend's side -- NOT FULLY WORKING --).
  • downloadFileFn: A function if called will download one file (the file passed as first argument if nothing passed then the first file in exported files will be used) directly without packaging/zipping it and show download progress in filerobot (file.url.download link is used in download and fallbacks to file.url.permalink).

example

filerobot.on('export', (files, popupExportSucessMsgFn, downloadFilesPackagedFn, downloadFileFn) => {
  console.log('The following files are chosen to be exported', files);
  popupExportSucessMsgFn() // shows exported successfully message as pop-up.
  downloadFilesPackagedFn(files.slice(1).map(({ file }) => file)) // no need to pass file.slice(1) if u would download all exported files.
  const { file } = file[0]
  downloadFileFn({ ...file, url: { ...file.url, download: files[0].link } }) // no need to pass file[0] if u would download the first file of exported files.
})

url-modified

Emitted when the user uses the image editor plugin in cloudimage mode and changes the url.

params:

  • modifiedUrl: The modified url for the image.
  • info: the function that gives you possibility to show a @filerobot/informer message.

example

filerobot.on('modified-url', (modifiedUrl, info) => {
  console.log('The new url is', modifiedUrl)
  info('Url has changed', 'success', 3000)
})