@filerobot/core
v3.78.13
Published
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, Box, One Drive, S3 and more.
Downloads
11,197
Keywords
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
NPM
npm install --save @filerobot/core
YARN
yarn add @filerobot/core
then
import Filerobot from '@filerobot/core'
...
...
...
const filerobot = Filerobot(propertiesObject)
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(propertiesObject)
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.
Properties
Required attributes are marked with (Required).
container
Type: string
Required.
Default: undefined
The container token (Filerobot token) that will be used in all the widget's modes & plugins ex. (listing files/folders, uploading, renaming, deleting...etc.). Register for an account at scaleflex.com to obtain a token.
securityTemplateId
PREVIOUSLY: securityTemplateID
Type: string
Required.
Default: undefined
The Security Template Id is 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
Type: string
.
Default: 'filerobot'
The unique identifier used for identifying the widget's instance (# in HTML selector).
dev
Type: boolean
.
Default: false
.
Enables the development mode which sends all requests to development server, otherwise all the endpoints defaults to the production server.
Note: enabling development mode, will show some features that won't work (they're hidden in production mode) with u cause of the generated sass key permissions (that is generated through the security template id).
theme
Type: object
.
Default:
{
palette: {...},
breakpoints: {...},
typography: {...}
shadows: {...}
}
You can check default values for each property here:
We are using @scaleflex/ui theme system to have global theme wrapping the project and you can customize it by overriding the default theme values.
You can check the values you can override for each property:
- For color palette you can select the property key from this list
- For typography, you can change font variant and font weight
- For breakpoints list
- For Shadows list
theme: {
palette: {
"accent-primary": "#479898",
"accent-primary-hover": "#479898",
"accent-primary-active": "#479898",
"accent-stateless": "#479898",
"link-pressed": "#479898",
"border-active-bottom": "#479898"
},
typography: {
"title-h6": {
fontWeight: FontWeight.Medium, // 500
fontSize: '12px',
lineHeight: '18px',
},
},
breakpoints: {
values: {
xs: 0,
md: 900,
xl: 1400
}
},
shadows: {
"shadow-sm": '6px -4px 12px 0px rgba(146, 166, 188, 0.14)'
}
}
NOTE: You must import the font family from your side in 2 weights (Normal === 400, Medium === 500) to have fonts work properly and show text as expected, which means
Roboto
is not included in the plugin by default so you must import it from your side too if you have provided another font family value through theme don't forget to import it from your side too.
autoProceed
Type: boolean
.
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
Type: boolean
.
Default: true
.
If set to false
, only one upload will be possible simultaneously.
debug
Type: boolean
.
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
Type: object
.
Default:
errorsLogger = {
debug: (...args) => {},
warn: (...args) => {},
error: (...args) => console.error(`[Filerobot] [${getTimeStamp()}]`, ...args),
};
restrictions
Type: object
.
Default:
{
maxFileSize: null,
maxNumberOfFiles: null,
minNumberOfFiles: null,
allowedFileTypes: null,
maxItemsSizeForCompression: null,
}
Upload restrictions:
| Property | Type | Default | Description |
| ---------------------- | ------------------ | ------- | -------------------------------------------------------------------------- |
| maxFileSize
| number
| null
| null
| maximum file size in bytes |
| maxTotalFilesSize
| number
| null
| null
| maximum files size in megabyte |
| totalUploadedFilesSize
| number
| null
| null
| total uploaded files size in megabyte |
| hideRestrictionsInformer
| boolean
| null
| null
| hide restrictions informer message |
| maxNumberOfFiles
| number
| null
| null
| maximum number of files to be uploaded simultaneously |
| minNumberOfFiles
| number
| null
| null
| minimum number of files before upload can star |
| allowedFileTypes
| array
| null
| null
| accepted file types or extensions, eg. ['image/*', 'image/jpeg', '.jpg']
|
Upload restrictions can also be governed in the backend by the Security Template configured.
Download restrictions:
| Property | Type | Default | Description |
| -------------------------------- | ------------------ | ------- | ------------------------------------------- |
| maxItemsSizeForCompression
| number
| null
| null
| maximum items size for compression in bytes |
onBeforeFileAdded
Type: function
.
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
Type: function
.
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
Type: string
.
Default:'en'
Used to determine which language to use from the widget's backend translated languages.
locale
Type: object
.
Default: default locales inside lib/defaultLocale.js
You can override some labels by specifying a translation object here, such as:
{
strings: {
loaderLoadingLabel: 'Loading'
}
}
## 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:
```js
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 Properties to the Widget to change properties 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(files, callback)
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()
Deprecated
Retries all the failed uploads.
filerobot.retryUpload(fileId)
Retries a failed upload for a file referenced by its id.
filerobot.cancelUploads()
emit cancel-uploads event and cancel uploads.
filerobot.setCoreCommonState(object)
Updates the internal state of the widget's core common state.
filerobot.getGlobalState()
Returns the internal state/store of the widget's.
filerobot.setUploadPanelFileState(fileId, state)
Deprecated - changed to setFileStateBeforeUpload
updates the state of a file inside the uploads panel before triggering upload.
filerobot.setProgressPanelFileState(fileId, state)
Deprecated - use setFileUploadingState
instead
updates the state of a file inside the Progress Panel.
filerobot.setFileUploadingState(fileId, state)
updates the state of a file uploading.
filerobot.getFileUploading(fileId)
Returns a file that is uploading.
filerobot.setFilesInfoMetaTags(fileIds, filesInfoMetaTagsData, forceUpdate)
Updates the info and/or meta object(s) of the passed files that would be uploaded with the provided info
and meta
objects parameters received from filesInfoMetaTagsData
object in the following format { info: {}, meta: {}, tags: {} }
, forceUpdate
means replace the current tags instead of deep merging with the current ones.
filerobot.reset()
Deprecated
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:
| Property | Type | Default | Description |
| ------------- | --------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| message
| string
| object
Required | undefined
| 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
| info
| choses the type of the informer whether info, warning or success
|
| timeout
| number
| 3000
| The duration which the message would still be shown for in milliseconds |
filerobot.log(message, type)
Logs a message in the logger
:
| Property | Type | Default | Description |
| ------------- | --------------------- | ----------- | ---------------------------------------------------------------------- |
| message
| string
Required | undefined
| the message would be logged/added/shown in the logger. |
| type
| string
| debug
| the type of that logged message whether debug/info, warning or error
|
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:
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.deletionReason
: 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, filesIds: fileIds, files }
.
example
filerobot.on("upload", (uploadProcess) => {
console.log("Upload started with upload id: ", uploadProcess.id);
console.log("Contains the following file ids", uploadProcess.filesIds);
});
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-started
Emitted when upload is started.
params
:
file
: The file object that started uploading.started
: An object contains upload Id, ex.{ uploadId: upload id assigned to current file }
.
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, bytesFinished: 1500, bytesTotal: 3500, uploadId: upload id assigned to current file }
.
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.response
: The upload request response received.options
: object that contains the uploadId
example
filerobot.on("upload-success", (file, response, { uploadId }) => {
console.log(
`The ${file.name} with the object ${file} is uploaded ${uploadId} and the whole response`,
response
);
});
upload-error
Emitted when a file faced some error/issue while uploading.
params
:
file
: The file object which fired the error.error
: object that contains error details, upload response and uploadId that was assigned to current file.options
: object that contains the upload response and uploadId
example
filerobot.on("upload-error", (file, error, { response, uploadId }) => {
console.log(
"File faced that error while uploading",
file,
error,
response,
uploadId
);
});
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-uploads
Emitted when the whole upload process is canceled (all files uploading are canceled).
params
: No params returned.
example
filerobot.on("cancel-uploads", () => {
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
:
filesIds
: files ids that have an error.error
: The error shown of the uploading process.uploadId
: The id of the errored uploading process.
example
filerobot.on("error", (filesIds, 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 downloads a file.
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 tofile.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.designState
: The image editor's design state object.info
: the function that gives you possibility to show a@filerobot/informer
message.
example
filerobot.on('modified-url', (modifiedUrl, designState, info) => {
console.log('The new url is', modifiedUrl)
console.log('Image editor design state:', designState)
info('Url has changed', 'success', 3000)
})