Add events, and other improvements

This commit is contained in:
Llewellyn van der Merwe 2024-09-12 07:10:27 +02:00
parent 1ebc666b35
commit 08484f8a9c
Signed by: Llewellyn
GPG Key ID: A9201372263741E7
8 changed files with 677 additions and 411 deletions

View File

@ -12,7 +12,7 @@ Uploader is an intuitive and lightweight JavaScript solution for embedding uploa
```html
<!-- Include the Uploader script from jsDelivr CDN -->
<script src="https://cdn.jsdelivr.net/gh/vdm-io/uikit@2.0.5/dist/js/Uploader.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/vdm-io/uikit@latest/dist/js/Uploader.min.js"></script>
```
2. **Markup Your Upload Area:**

549
dist/js/Uploader.js vendored
View File

@ -1,5 +1,5 @@
/**
* VDM Uikit Uploader v2.0.5
* VDM Uikit Uploader v2.1.0
* https://git.vdm.dev/joomla/uikit
* (c) 2020 - 2024 Llewellyn van der Merwe
* MIT License
@ -115,16 +115,15 @@
*/
init = async (id, guid, reset = false) => {
if (this.#data[id] && !reset) {
console.log(`Field ${id} is already initialized, reusing existing data.`);
return;
}
try {
const url = this.#buildUrl(this.#endpoint, guid);
const { DEBUG } = process.env;
const result = await this.#fetchData(url);
DEBUG === 'true' && console.log('Data fetched:', result);
if (true) console.log('Data fetched:', result);
if (result?.data && typeof result.data === 'object') {
this.set(id, result.data);
@ -132,7 +131,7 @@
throw new Error(result.error || 'An error occurred during the file type request.');
}
} catch (error) {
DEBUG === 'true' && console.error('Error during initialization:', error);
console.error('Error during initialization:', error);
}
};
@ -149,6 +148,7 @@
});
if (!response.ok) {
console.error('Error fetching data:', response);
return;
}
@ -217,7 +217,8 @@
* await helper.set(endpoint, area, params);
*/
class DisplayHelper {
constructor() {}
constructor() {
}
/**
* Asynchronously fetches HTML content from a specified endpoint and injects it into a specified DOM area.
@ -245,24 +246,61 @@
if (!response.ok) {
// If an error occurs, log it in debug mode
if (true === 'true') ;
if (true) {
console.error('Error fetching display data:', response);
}
return;
}
const result = await response.json();
// If there's no response.data or it's empty, clear the display area
if (!result.data || result.data.trim() === '') {
displayArea.innerHTML = ''; // Empty the display area
} else {
// Replace the display area content with the new HTML
displayArea.innerHTML = result.data;
// Check if result contains an error
if (result.error) {
// Log the error in debug mode and show a user-friendly message
if (true) {
console.error('Error fetching display data:', result.error);
}
return;
}
} catch (error) {
// If there's no response.data or it's empty, clear the display area
if (!result.data || result.data.trim() === '') {
// Trigger a custom event before hide files display the entity files
const beforeHideFilesDisplay = new CustomEvent('vdm.uikit.uploader.beforeHideFilesDisplay', {
detail: {result, displayArea}
});
document.dispatchEvent(beforeHideFilesDisplay);
// Optionally, you can clear the display area on error
displayArea.innerHTML = ''; // Empty the display area on failure
displayArea.innerHTML = ''; // Empty the display area
displayArea.setAttribute('hidden', 'hidden');
// Trigger a custom event after hide files display the entity files
const afterHideFilesDisplay = new CustomEvent('vdm.uikit.uploader.afterHideFilesDisplay', {
detail: {result, displayArea}
});
document.dispatchEvent(afterHideFilesDisplay);
} else {
// Trigger a custom event before displaying the entity files
const beforeFilesDisplayEvent = new CustomEvent('vdm.uikit.uploader.beforeFilesDisplay', {
detail: {result, displayArea}
});
document.dispatchEvent(beforeFilesDisplayEvent);
// Replace the display area content with the new HTML
displayArea.innerHTML = result.data;
displayArea.removeAttribute('hidden');
// Trigger a custom event after displaying the entity files
const afterFilesDisplayEvent = new CustomEvent('vdm.uikit.uploader.afterFilesDisplay', {
detail: {result, displayArea}
});
document.dispatchEvent(afterFilesDisplayEvent);
}
} catch (error) {
// If an error occurs, log it in debug mode
{
console.error('Error fetching display data:', error);
}
}
};
@ -278,6 +316,11 @@
* @private
*/
#buildUrl = (endpoint, params) => {
// If no params or params is empty, return the endpoint as is
if (!params || Object.keys(params).length === 0) {
return endpoint;
}
// Convert the params object into URL query string using URLSearchParams
const separator = endpoint.includes('?') ? '&' : '?';
const urlParams = new URLSearchParams(params);
@ -292,50 +335,34 @@
* @classdesc This class provides methods for uploading files to a server.
*/
class UikitUploader {
/**
* Helper class for uploading files.
*
* @class
* @classdesc This class provides methods for uploading files to a server.
*/
#uploadHelper;
/**
* Helper object for displaying messages and data in the user interface.
*
* @namespace displayHelper
*/
#displayHelper;
/**
* @typedef {Object} UIKit
*
*/
#uikit;
/**
* Object representing the upload instances.
*
* @typedef {Object} UploadInstances
* @property {Object} - The key-value pairs of upload instance IDs and their corresponding upload data.
*/
#uploadInstances = {};
/**
* Creates an instance of the UikitUploader class.
*
* @param {Object} config - An object that contains configuration details.
* @param {any} endpoint - Endpoint where the upload is being sent.
* @param {any} uikit - Reference to uikit.
* @param {Object} config - Configuration details for uploader instances.
* @param {string} endpoint - The endpoint where the files will be uploaded.
* @param {any} uikit - Reference to UIKit.
*/
constructor(config, endpoint, uikit) {
this.#uploadHelper = new UploadHelper(endpoint);
this.#displayHelper = new DisplayHelper();
this.#uikit = uikit;
this.#initializeFields(config);
}
/**
* Initializes all upload fields based on the config.
*
* @param {Object} config - Configuration object mapping field IDs to their parameters.
*/
#initializeFields(config) {
Object.keys(config).forEach(id => {
const entity = config[id];
this.#initField(id, entity);
this.#initField(id, config[id]);
});
}
@ -343,199 +370,308 @@
* Initializes a field with given parameters and sets up its event listener.
*
* @param {string} id - The identifier for the field.
* @param {Object} entity - An object containing various field parameters.
* entity must contain 'bar', 'typeId', 'endpoint', 'successId', 'errorId', 'allowedFormatId', 'fileTypeId', 'displayId', 'displayEndpoint' properties.
* @param {Object} entity - Configuration parameters for the field.
*/
#initField = (id, entity) => {
#initField(id, entity) {
const {
bar, typeId, endpoint, successId, errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint
} = entity;
this.#setupDisplayArea(displayEndpoint, displayId);
const typeField = document.getElementById(typeId);
const errorNotification = {
message: 'error.message',
status: 'danger',
timeout: 7000
};
const initializeUpload = async guid => {
if (guid && guid.length > 1) {
try {
await this.#initUpload(id, guid, bar, endpoint, successId,
errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint);
} catch (error) {
errorNotification.message = error.message;
this.#uikit.notification(errorNotification);
}
}
};
if (!typeField) {
this.#logError(`Type field with ID ${typeId} not found`);
return;
}
typeField.addEventListener('change', async () => await initializeUpload(typeField.value));
initializeUpload(typeField.value).catch(error => {
errorNotification.message = error.message;
this.#uikit.notification(errorNotification);
});
const initializeUpload = async (guid) => {
if (guid && guid.length > 1) {
try {
await this.#initUpload(id, guid, bar, endpoint, successId, errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint);
} catch (error) {
this.#notifyError(error.message);
}
}
};
typeField.addEventListener('change', () => initializeUpload(typeField.value));
initializeUpload(typeField.value).catch(error => this.#notifyError(error.message));
}
/**
* Initializes the upload process in the specified field after setting up the corresponding html elements and their interactions.
* Initializes the upload process and sets up the UI elements.
*
* @param {string} id - The identifier for the field.
* @param {string} typeGuid - The typeGuid for the field.
* @param {string} progressBarId - The id of the progress bar element.
* @param {string} uploadEndpoint - The endpoint url to which file is being uploaded.
* @param {string|null} successId - The id of the success message element.
* @param {string|null} errorId - The id of the error message element.
* @param {string|null} allowedFormatId - The id of the allowed format element.
* @param {string|null} fileTypeId - The id of the file type element.
* @param {string|null} displayId - The id of the display element.
* @param {string|null} displayEndpoint - The endpoint url from where the file is being displayed.
* @param {string} typeGuid - The type GUID for the field.
* @param {string} progressBarId - The ID of the progress bar element.
* @param {string} uploadEndpoint - The endpoint URL for the upload.
* @param {string|null} successId - The ID of the success message element.
* @param {string|null} errorId - The ID of the error message element.
* @param {string|null} allowedFormatId - The ID of the allowed format element.
* @param {string|null} fileTypeId - The ID of the file type element.
* @param {string|null} displayId - The ID of the display element.
* @param {string|null} displayEndpoint - The endpoint URL for displaying the uploaded file.
*/
#initUpload = async (id, typeGuid, progressBarId, uploadEndpoint, successId,
errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint) => {
async #initUpload(id, typeGuid, progressBarId, uploadEndpoint, successId, errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint) {
try {
const call = id + typeGuid;
this.#dispatchEvent('beforeInit', {
id,
typeGuid,
progressBarId,
uploadEndpoint,
successId,
errorId,
allowedFormatId,
fileTypeId,
displayId,
displayEndpoint
});
await this.#uploadHelper.init(call, typeGuid);
const call = `${id}${typeGuid}`;
await this.#uploadHelper.init(call, typeGuid, true);
const bar = document.getElementById(progressBarId);
const successMessage = document.getElementById(successId);
const errorMessage = document.getElementById(errorId);
const displayArea = document.getElementById(displayId);
const allowedFormatSpan = document.getElementById(allowedFormatId);
const fileTypeSpan = document.getElementById(fileTypeId);
const elements = this.#getUploadElements(progressBarId, successId, errorId, allowedFormatId, fileTypeId, displayId);
if (this.#uploadInstances[id]) {
this.#uploadInstances[id].$destroy(true);
}
this.#dispatchEvent('afterElementsInit', {...elements});
if (successMessage) {
successMessage.setAttribute('hidden', 'hidden');
}
if (errorMessage) {
errorMessage.setAttribute('hidden', 'hidden');
}
if (allowedFormatSpan) {
allowedFormatSpan.textContent = this.#uploadHelper.get(call, 'allow_span', '');
}
if (fileTypeSpan) {
allowedFormatSpan.textContent = this.#uploadHelper.get(call, 'file_type_span', 'file');
}
if (displayEndpoint && displayArea) {
this.#displayHelper.set(
displayEndpoint,
displayArea,
this.#uploadHelper.getParams(
this.#uploadHelper.get(call, 'display_fields')
)
);
}
this.#uploadInstances[id]?.$destroy(true);
this.#prepareUploadUI(elements, call, successId, errorId);
this.#uploadInstances[id] = this.#uikit.upload(`#${id}`, {
url: this.#buildUrl(uploadEndpoint, typeGuid),
multiple: true,
allow: () => this.#uploadHelper.get(call, 'allow') || false,
name: () => this.#uploadHelper.get(call, 'name') || 'files',
beforeSend: (environment) => {
if (true === 'true') ;
environment.data.params = this.#uploadHelper.getParams(this.#uploadHelper.get(call, 'param_fields'));
},
beforeAll: () => {
if (true === 'true') ;
},
load: () => {
if (true === 'true') ;
},
error: (error) => {
if (true === 'true') ;
if (errorMessage) {
errorMessage.removeAttribute('hidden');
errorMessage.textContent = 'Upload failed.';
}
},
complete: () => {
if (true === 'true') ;
if (successMessage) {
successMessage.removeAttribute('hidden');
successMessage.textContent = 'Upload completed successfully.';
}
},
loadStart: (e) => {
if (true === 'true') ;
if (bar) {
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
}
},
progress: (e) => {
if (true === 'true') ;
if (bar) {
bar.max = e.total;
bar.value = e.loaded;
}
},
loadEnd: (e) => {
if (true === 'true') ;
if (bar) {
bar.max = e.total;
bar.value = e.loaded;
}
},
completeAll: () => {
if (true === 'true') ;
if (bar) {
setTimeout(() => {
bar.setAttribute('hidden', 'hidden');
if (errorMessage) {
successMessage.setAttribute('hidden', 'hidden');
}
if (errorMessage) {
errorMessage.setAttribute('hidden', 'hidden');
}
}, 1000);
}
if (displayEndpoint && displayArea) {
this.#displayHelper.set(
displayEndpoint,
displayArea,
this.#uploadHelper.getParams(
this.#uploadHelper.get(call, 'display_fields')
)
);
}
}
allow: this.#uploadHelper.get(call, 'allow', false),
name: this.#uploadHelper.get(call, 'name', 'files'),
beforeSend: (env) => this.#handleBeforeSend(call, env),
beforeAll: (files) => this.#dispatchEvent('beforeAll', {files}),
load: (e) => this.#dispatchEvent('load', {event: e}),
error: (error) => this.#handleUploadError(error, elements.errorMessage),
complete: (xhr) => this.#handleComplete(xhr, elements.successMessage),
loadStart: (e) => this.#handleLoadStart(e, elements.progressBar),
progress: (e) => this.#handleProgress(e, elements.progressBar),
loadEnd: (e) => this.#handleLoadEnd(e, elements.progressBar),
completeAll: (xhr) => this.#handleCompleteAll(xhr, elements.progressBar, elements.successMessage, elements.errorMessage, displayEndpoint, displayId, call)
});
} catch (error) {
throw error;
}
};
}
/**
* Builds a URL by appending a GUID parameter to the endpoint.
* Returns the required HTML elements by their IDs.
*
* @param {string} endpoint - The base URL endpoint
* @param {string} guid - The GUID parameter value
* @returns {string} The built URL with the appended GUID parameter
* @param {string} progressBarId - The ID of the progress bar element.
* @param {string} successId - The ID of the success message element.
* @param {string} errorId - The ID of the error message element.
* @param {string} allowedFormatId - The ID of the allowed format span element.
* @param {string} fileTypeId - The ID of the file type span element.
* @param {string} displayId - The ID of the display area element.
* @returns {object} - An object containing the required HTML elements.
*/
#buildUrl = (endpoint, guid) => {
#getUploadElements(progressBarId, successId, errorId, allowedFormatId, fileTypeId, displayId) {
return {
progressBar: document.getElementById(progressBarId),
successMessage: document.getElementById(successId),
errorMessage: document.getElementById(errorId),
allowedFormatSpan: document.getElementById(allowedFormatId),
fileTypeSpan: document.getElementById(fileTypeId),
displayArea: document.getElementById(displayId)
};
}
/**
* Initializes the display area with data from the display endpoint.
*
* @param {string} displayEndpoint - The endpoint to retrieve the display data from.
* @param {string} displayId - The id of the display area element in the DOM.
* @param {object} params - Additional parameters to be passed to the display helper.
*
* @return {void}
*/
#setupDisplayArea(displayEndpoint, displayId, params = {}) {
const displayArea = document.getElementById(displayId);
if (displayEndpoint && displayArea) {
this.#displayHelper.set(displayEndpoint, displayArea, params);
}
}
/**
* Notifies the user of an error using UIKit notifications.
*
* @param {string} message - The error message to display.
* @return {void}
*/
#notifyError(message) {
this.#uikit.notification({message, status: 'danger', timeout: 7000});
}
/**
* Logs an error to the console.
*
* @param {string} message - The error message to be logged.
*
* @return {undefined}
*/
#logError(message) {
{
console.error(message);
}
}
/**
* Dispatches a custom event with optional detail data.
*
* @param {string} eventName - The name of the event to dispatch.
* @param {object} [detail={}] - The optional detail data to include with the event.
* @return {void}
*/
#dispatchEvent(eventName, detail = {}) {
document.dispatchEvent(new CustomEvent(`vdm.uikit.uploader.${eventName}`, {detail}));
}
/**
* Builds a URL by appending the GUID parameter.
*
* @param {string} endpoint - The base URL endpoint.
* @param {string} guid - The GUID parameter to be appended to the URL.
* @return {string} - The constructed URL with the GUID parameter appended.
*/
#buildUrl(endpoint, guid) {
const separator = endpoint.includes('?') ? '&' : '?';
return `${endpoint}${separator}guid=${guid}`;
};
}
/**
* Prepares the UI elements before starting the upload.
*
* @param {object} elements - The UI elements to be modified.
* @param {string} call - The call identifier.
* @param {string} successId - The id of the success message element.
* @param {string} errorId - The id of the error message element.
*/
#prepareUploadUI(elements, call, successId, errorId) {
if (elements.successMessage) elements.successMessage.setAttribute('hidden', 'hidden');
if (elements.errorMessage) elements.errorMessage.setAttribute('hidden', 'hidden');
if (elements.allowedFormatSpan) elements.allowedFormatSpan.innerHTML = this.#uploadHelper.get(call, 'allow_span', '');
if (elements.fileTypeSpan) elements.fileTypeSpan.innerHTML = this.#uploadHelper.get(call, 'file_type_span', 'file');
}
/**
* Handles beforeSend logic for uploads.
*
* @param {object} call - The call object.
* @param {object} environment - The environment object.
* @return {void}
*/
#handleBeforeSend(call, environment) {
this.#dispatchEvent('beforeSend', {environment});
environment.data.params = this.#uploadHelper.getParams(this.#uploadHelper.get(call, 'param_fields'));
this.#dispatchEvent('afterSendPreparation', {environment});
}
/**
* Handles the error scenario during upload.
*
* @param {Error} error - The error object that occurred during upload.
* @param {HTMLElement} errorMessage - The element used to display the error message.
*
* @return {void}
*/
#handleUploadError(error, errorMessage) {
this.#dispatchEvent('error', {error});
if (errorMessage) {
errorMessage.removeAttribute('hidden');
errorMessage.textContent = 'Upload failed.';
}
}
/**
* Handles the upload completion.
*
* @param {XMLHttpRequest} xhr - The XMLHttpRequest object representing the upload request.
* @param {HTMLElement} successMessage - The success message element to display.
*/
#handleComplete(xhr, successMessage) {
this.#dispatchEvent('complete', {xhr});
if (successMessage) {
successMessage.removeAttribute('hidden');
successMessage.textContent = 'Upload completed successfully.';
}
}
/**
* Handles the loadStart event.
*
* @param {Event} e - The loadStart event object.
* @param {HTMLElement} progressBar - The progress bar element. Optional.
* @return {void}
*/
#handleLoadStart(e, progressBar) {
this.#dispatchEvent('loadStart', {event: e});
if (progressBar) {
progressBar.removeAttribute('hidden');
progressBar.max = e.total;
progressBar.value = e.loaded;
}
}
/**
* Handles the progress event.
*
* @param {Event} e - The progress event.
* @param {Element} progressBar - The progress bar element.
*
* @return {void}
*/
#handleProgress(e, progressBar) {
this.#dispatchEvent('progress', {event: e});
if (progressBar) {
progressBar.max = e.total;
progressBar.value = e.loaded;
}
}
/**
* Handles the loadEnd event.
*
* @param {Event} e - The loadEnd event object.
* @param {Element} progressBar - The progress bar element to update.
*
* @return {void}
*/
#handleLoadEnd(e, progressBar) {
this.#dispatchEvent('loadEnd', {event: e});
if (progressBar) {
progressBar.max = e.total;
progressBar.value = e.loaded;
}
}
/**
* Handles the completion of all uploads.
*
* @param {XMLHttpRequest} xhr - The XMLHttpRequest object used for the uploads.
* @param {HTMLElement} progressBar - The progress bar element.
* @param {HTMLElement} successMessage - The success message element.
* @param {HTMLElement} errorMessage - The error message element.
* @param {string} displayEndpoint - The display endpoint.
* @param {string} displayId - The display ID.
* @param {Object} call - The call object.
*
* @return {void}
*/
#handleCompleteAll(xhr, progressBar, successMessage, errorMessage, displayEndpoint, displayId, call) {
this.#dispatchEvent('completeAll', {xhr});
if (progressBar) {
setTimeout(() => {
progressBar.setAttribute('hidden', 'hidden');
if (successMessage) successMessage.setAttribute('hidden', 'hidden');
if (errorMessage) errorMessage.setAttribute('hidden', 'hidden');
}, 5000);
}
this.#setupDisplayArea(displayEndpoint, displayId, this.#uploadHelper.getParams(this.#uploadHelper.get(call, 'display_fields')));
}
}
(function(global) {
@ -551,10 +687,12 @@
const { endpoint, targetClass, ...additionalConfig } = global.vdmUploaderConfig || {};
if (!endpoint) {
console.error('Endpoint is not defined, exiting initialization.');
return;
}
if (!targetClass) {
console.error('The target class is not defined, exiting initialization.');
return;
}
@ -566,13 +704,14 @@
const uploadEndpoint = global.vdmUploaderConfig[id] ? global.vdmUploaderConfig[id].endpoint : null;
if (!uploadEndpoint) {
console.error(`Upload Endpoint for ${id} is not defined, exiting initialization for this field.`);
return; // Skip this field if no upload endpoint is found
}
const progressBarId = element.dataset.progressbarId;
const typeId = element.dataset.typeId;
// optional
const displayEndpoint = global.vdmUploaderConfig[id] ? global.vdmUploaderConfig[id].endpoint_diplay : null;
const displayEndpoint = global.vdmUploaderConfig[id] ? global.vdmUploaderConfig[id].endpoint_display : null;
const displayId = element.dataset.displayId || null;
const successId = element.dataset.successId || null;
const errorId = element.dataset.errorId || null;

File diff suppressed because one or more lines are too long

View File

@ -2,7 +2,7 @@
"name": "vdm.uikit.uploader",
"title": "Uploader",
"description": "Uploader is an intuitive and lightweight JavaScript solution for embedding upload functionality into your website.",
"version": "2.0.5",
"version": "2.1.0",
"main": "dist/js/Uploader.min.js",
"scripts": {
"build": "rollup -c"

View File

@ -13,12 +13,12 @@ import { UikitUploader } from './core/UikitUploader';
const { endpoint, targetClass, ...additionalConfig } = global.vdmUploaderConfig || {};
if (!endpoint) {
if (process.env.DEBUG === 'true') console.error('Endpoint is not defined, exiting initialization.');
if (process.env.DEBUG) console.error('Endpoint is not defined, exiting initialization.');
return;
}
if (!targetClass) {
if (process.env.DEBUG === 'true') console.error('The target class is not defined, exiting initialization.');
if (process.env.DEBUG) console.error('The target class is not defined, exiting initialization.');
return;
}
@ -30,14 +30,14 @@ import { UikitUploader } from './core/UikitUploader';
const uploadEndpoint = global.vdmUploaderConfig[id] ? global.vdmUploaderConfig[id].endpoint : null;
if (!uploadEndpoint) {
if (process.env.DEBUG === 'true') console.error(`Upload Endpoint for ${id} is not defined, exiting initialization for this field.`);
if (process.env.DEBUG) console.error(`Upload Endpoint for ${id} is not defined, exiting initialization for this field.`);
return; // Skip this field if no upload endpoint is found
}
const progressBarId = element.dataset.progressbarId;
const typeId = element.dataset.typeId;
// optional
const displayEndpoint = global.vdmUploaderConfig[id] ? global.vdmUploaderConfig[id].endpoint_diplay : null;
const displayEndpoint = global.vdmUploaderConfig[id] ? global.vdmUploaderConfig[id].endpoint_display : null;
const displayId = element.dataset.displayId || null;
const successId = element.dataset.successId || null;
const errorId = element.dataset.errorId || null;

View File

@ -13,7 +13,8 @@
* await helper.set(endpoint, area, params);
*/
export class DisplayHelper {
constructor() {}
constructor() {
}
/**
* Asynchronously fetches HTML content from a specified endpoint and injects it into a specified DOM area.
@ -41,7 +42,7 @@ export class DisplayHelper {
if (!response.ok) {
// If an error occurs, log it in debug mode
if (process.env.DEBUG === 'true') {
if (process.env.DEBUG) {
console.error('Error fetching display data:', response);
}
return;
@ -49,22 +50,53 @@ export class DisplayHelper {
const result = await response.json();
// Check if result contains an error
if (result.error) {
// Log the error in debug mode and show a user-friendly message
if (process.env.DEBUG) {
console.error('Error fetching display data:', result.error);
}
return;
}
// If there's no response.data or it's empty, clear the display area
if (!result.data || result.data.trim() === '') {
// Trigger a custom event before hide files display the entity files
const beforeHideFilesDisplay = new CustomEvent('vdm.uikit.uploader.beforeHideFilesDisplay', {
detail: {result, displayArea}
});
document.dispatchEvent(beforeHideFilesDisplay);
displayArea.innerHTML = ''; // Empty the display area
displayArea.setAttribute('hidden', 'hidden');
// Trigger a custom event after hide files display the entity files
const afterHideFilesDisplay = new CustomEvent('vdm.uikit.uploader.afterHideFilesDisplay', {
detail: {result, displayArea}
});
document.dispatchEvent(afterHideFilesDisplay);
} else {
// Trigger a custom event before displaying the entity files
const beforeFilesDisplayEvent = new CustomEvent('vdm.uikit.uploader.beforeFilesDisplay', {
detail: {result, displayArea}
});
document.dispatchEvent(beforeFilesDisplayEvent);
// Replace the display area content with the new HTML
displayArea.innerHTML = result.data;
}
displayArea.removeAttribute('hidden');
// Trigger a custom event after displaying the entity files
const afterFilesDisplayEvent = new CustomEvent('vdm.uikit.uploader.afterFilesDisplay', {
detail: {result, displayArea}
});
document.dispatchEvent(afterFilesDisplayEvent);
}
} catch (error) {
// If an error occurs, log it in debug mode
if (process.env.DEBUG === 'true') {
if (process.env.DEBUG) {
console.error('Error fetching display data:', error);
}
// Optionally, you can clear the display area on error
displayArea.innerHTML = ''; // Empty the display area on failure
}
};
@ -80,6 +112,11 @@ export class DisplayHelper {
* @private
*/
#buildUrl = (endpoint, params) => {
// If no params or params is empty, return the endpoint as is
if (!params || Object.keys(params).length === 0) {
return endpoint;
}
// Convert the params object into URL query string using URLSearchParams
const separator = endpoint.includes('?') ? '&' : '?';
const urlParams = new URLSearchParams(params);

View File

@ -8,50 +8,34 @@ import {DisplayHelper} from './DisplayHelper.js';
* @classdesc This class provides methods for uploading files to a server.
*/
export class UikitUploader {
/**
* Helper class for uploading files.
*
* @class
* @classdesc This class provides methods for uploading files to a server.
*/
#uploadHelper;
/**
* Helper object for displaying messages and data in the user interface.
*
* @namespace displayHelper
*/
#displayHelper;
/**
* @typedef {Object} UIKit
*
*/
#uikit;
/**
* Object representing the upload instances.
*
* @typedef {Object} UploadInstances
* @property {Object} - The key-value pairs of upload instance IDs and their corresponding upload data.
*/
#uploadInstances = {};
/**
* Creates an instance of the UikitUploader class.
*
* @param {Object} config - An object that contains configuration details.
* @param {any} endpoint - Endpoint where the upload is being sent.
* @param {any} uikit - Reference to uikit.
* @param {Object} config - Configuration details for uploader instances.
* @param {string} endpoint - The endpoint where the files will be uploaded.
* @param {any} uikit - Reference to UIKit.
*/
constructor(config, endpoint, uikit) {
this.#uploadHelper = new UploadHelper(endpoint);
this.#displayHelper = new DisplayHelper();
this.#uikit = uikit;
this.#initializeFields(config);
}
/**
* Initializes all upload fields based on the config.
*
* @param {Object} config - Configuration object mapping field IDs to their parameters.
*/
#initializeFields(config) {
Object.keys(config).forEach(id => {
const entity = config[id];
this.#initField(id, entity);
this.#initField(id, config[id]);
});
}
@ -59,198 +43,306 @@ export class UikitUploader {
* Initializes a field with given parameters and sets up its event listener.
*
* @param {string} id - The identifier for the field.
* @param {Object} entity - An object containing various field parameters.
* entity must contain 'bar', 'typeId', 'endpoint', 'successId', 'errorId', 'allowedFormatId', 'fileTypeId', 'displayId', 'displayEndpoint' properties.
* @param {Object} entity - Configuration parameters for the field.
*/
#initField = (id, entity) => {
#initField(id, entity) {
const {
bar, typeId, endpoint, successId, errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint
} = entity;
this.#setupDisplayArea(displayEndpoint, displayId);
const typeField = document.getElementById(typeId);
const errorNotification = {
message: 'error.message',
status: 'danger',
timeout: 7000
};
const initializeUpload = async guid => {
if (guid && guid.length > 1) {
try {
await this.#initUpload(id, guid, bar, endpoint, successId,
errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint);
} catch (error) {
errorNotification.message = error.message;
this.#uikit.notification(errorNotification);
}
}
};
if (!typeField) {
if (process.env.DEBUG === 'true') console.error(`Type field with ID ${typeId} not found`);
this.#logError(`Type field with ID ${typeId} not found`);
return;
}
typeField.addEventListener('change', async () => await initializeUpload(typeField.value));
initializeUpload(typeField.value).catch(error => {
errorNotification.message = error.message;
this.#uikit.notification(errorNotification);
});
const initializeUpload = async (guid) => {
if (guid && guid.length > 1) {
try {
await this.#initUpload(id, guid, bar, endpoint, successId, errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint);
} catch (error) {
this.#notifyError(error.message);
}
}
};
typeField.addEventListener('change', () => initializeUpload(typeField.value));
initializeUpload(typeField.value).catch(error => this.#notifyError(error.message));
}
/**
* Initializes the upload process in the specified field after setting up the corresponding html elements and their interactions.
* Initializes the upload process and sets up the UI elements.
*
* @param {string} id - The identifier for the field.
* @param {string} typeGuid - The typeGuid for the field.
* @param {string} progressBarId - The id of the progress bar element.
* @param {string} uploadEndpoint - The endpoint url to which file is being uploaded.
* @param {string|null} successId - The id of the success message element.
* @param {string|null} errorId - The id of the error message element.
* @param {string|null} allowedFormatId - The id of the allowed format element.
* @param {string|null} fileTypeId - The id of the file type element.
* @param {string|null} displayId - The id of the display element.
* @param {string|null} displayEndpoint - The endpoint url from where the file is being displayed.
* @param {string} typeGuid - The type GUID for the field.
* @param {string} progressBarId - The ID of the progress bar element.
* @param {string} uploadEndpoint - The endpoint URL for the upload.
* @param {string|null} successId - The ID of the success message element.
* @param {string|null} errorId - The ID of the error message element.
* @param {string|null} allowedFormatId - The ID of the allowed format element.
* @param {string|null} fileTypeId - The ID of the file type element.
* @param {string|null} displayId - The ID of the display element.
* @param {string|null} displayEndpoint - The endpoint URL for displaying the uploaded file.
*/
#initUpload = async (id, typeGuid, progressBarId, uploadEndpoint, successId,
errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint) => {
async #initUpload(id, typeGuid, progressBarId, uploadEndpoint, successId, errorId, allowedFormatId, fileTypeId, displayId, displayEndpoint) {
try {
const call = id + typeGuid;
this.#dispatchEvent('beforeInit', {
id,
typeGuid,
progressBarId,
uploadEndpoint,
successId,
errorId,
allowedFormatId,
fileTypeId,
displayId,
displayEndpoint
});
await this.#uploadHelper.init(call, typeGuid);
const call = `${id}${typeGuid}`;
await this.#uploadHelper.init(call, typeGuid, true);
const bar = document.getElementById(progressBarId);
const successMessage = document.getElementById(successId);
const errorMessage = document.getElementById(errorId);
const displayArea = document.getElementById(displayId);
const allowedFormatSpan = document.getElementById(allowedFormatId);
const fileTypeSpan = document.getElementById(fileTypeId);
const elements = this.#getUploadElements(progressBarId, successId, errorId, allowedFormatId, fileTypeId, displayId);
if (this.#uploadInstances[id]) {
this.#uploadInstances[id].$destroy(true);
}
this.#dispatchEvent('afterElementsInit', {...elements});
if (successMessage) {
successMessage.setAttribute('hidden', 'hidden');
}
if (errorMessage) {
errorMessage.setAttribute('hidden', 'hidden');
}
if (allowedFormatSpan) {
allowedFormatSpan.textContent = this.#uploadHelper.get(call, 'allow_span', '');
}
if (fileTypeSpan) {
allowedFormatSpan.textContent = this.#uploadHelper.get(call, 'file_type_span', 'file');
}
if (displayEndpoint && displayArea) {
this.#displayHelper.set(
displayEndpoint,
displayArea,
this.#uploadHelper.getParams(
this.#uploadHelper.get(call, 'display_fields')
)
);
}
this.#uploadInstances[id]?.$destroy(true);
this.#prepareUploadUI(elements, call, successId, errorId);
this.#uploadInstances[id] = this.#uikit.upload(`#${id}`, {
url: this.#buildUrl(uploadEndpoint, typeGuid),
multiple: true,
allow: () => this.#uploadHelper.get(call, 'allow') || false,
name: () => this.#uploadHelper.get(call, 'name') || 'files',
beforeSend: (environment) => {
if (process.env.DEBUG === 'true') console.log('beforeSend', environment);
environment.data.params = this.#uploadHelper.getParams(this.#uploadHelper.get(call, 'param_fields'));
},
beforeAll: () => {
if (process.env.DEBUG === 'true') console.log('beforeAll');
},
load: () => {
if (process.env.DEBUG === 'true') console.log('load');
},
error: (error) => {
if (process.env.DEBUG === 'true') console.log('error', error);
if (errorMessage) {
errorMessage.removeAttribute('hidden');
errorMessage.textContent = 'Upload failed.';
}
},
complete: () => {
if (process.env.DEBUG === 'true') console.log('complete');
if (successMessage) {
successMessage.removeAttribute('hidden');
successMessage.textContent = 'Upload completed successfully.';
}
},
loadStart: (e) => {
if (process.env.DEBUG === 'true') console.log('loadStart', e);
if (bar) {
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
}
},
progress: (e) => {
if (process.env.DEBUG === 'true') console.log('progress', e);
if (bar) {
bar.max = e.total;
bar.value = e.loaded;
}
},
loadEnd: (e) => {
if (process.env.DEBUG === 'true') console.log('loadEnd', e);
if (bar) {
bar.max = e.total;
bar.value = e.loaded;
}
},
completeAll: () => {
if (process.env.DEBUG === 'true') console.log('completeAll');
if (bar) {
setTimeout(() => {
bar.setAttribute('hidden', 'hidden');
if (errorMessage) {
successMessage.setAttribute('hidden', 'hidden');
}
if (errorMessage) {
errorMessage.setAttribute('hidden', 'hidden');
}
}, 1000);
}
if (displayEndpoint && displayArea) {
this.#displayHelper.set(
displayEndpoint,
displayArea,
this.#uploadHelper.getParams(
this.#uploadHelper.get(call, 'display_fields')
)
);
}
}
allow: this.#uploadHelper.get(call, 'allow', false),
name: this.#uploadHelper.get(call, 'name', 'files'),
beforeSend: (env) => this.#handleBeforeSend(call, env),
beforeAll: (files) => this.#dispatchEvent('beforeAll', {files}),
load: (e) => this.#dispatchEvent('load', {event: e}),
error: (error) => this.#handleUploadError(error, elements.errorMessage),
complete: (xhr) => this.#handleComplete(xhr, elements.successMessage),
loadStart: (e) => this.#handleLoadStart(e, elements.progressBar),
progress: (e) => this.#handleProgress(e, elements.progressBar),
loadEnd: (e) => this.#handleLoadEnd(e, elements.progressBar),
completeAll: (xhr) => this.#handleCompleteAll(xhr, elements.progressBar, elements.successMessage, elements.errorMessage, displayEndpoint, displayId, call)
});
} catch (error) {
throw error;
}
};
}
/**
* Builds a URL by appending a GUID parameter to the endpoint.
* Returns the required HTML elements by their IDs.
*
* @param {string} endpoint - The base URL endpoint
* @param {string} guid - The GUID parameter value
* @returns {string} The built URL with the appended GUID parameter
* @param {string} progressBarId - The ID of the progress bar element.
* @param {string} successId - The ID of the success message element.
* @param {string} errorId - The ID of the error message element.
* @param {string} allowedFormatId - The ID of the allowed format span element.
* @param {string} fileTypeId - The ID of the file type span element.
* @param {string} displayId - The ID of the display area element.
* @returns {object} - An object containing the required HTML elements.
*/
#buildUrl = (endpoint, guid) => {
const separator = endpoint.includes('?') ? '&' : '?';
return `${endpoint}${separator}guid=${guid}`;
#getUploadElements(progressBarId, successId, errorId, allowedFormatId, fileTypeId, displayId) {
return {
progressBar: document.getElementById(progressBarId),
successMessage: document.getElementById(successId),
errorMessage: document.getElementById(errorId),
allowedFormatSpan: document.getElementById(allowedFormatId),
fileTypeSpan: document.getElementById(fileTypeId),
displayArea: document.getElementById(displayId)
};
}
/**
* Initializes the display area with data from the display endpoint.
*
* @param {string} displayEndpoint - The endpoint to retrieve the display data from.
* @param {string} displayId - The id of the display area element in the DOM.
* @param {object} params - Additional parameters to be passed to the display helper.
*
* @return {void}
*/
#setupDisplayArea(displayEndpoint, displayId, params = {}) {
const displayArea = document.getElementById(displayId);
if (displayEndpoint && displayArea) {
this.#displayHelper.set(displayEndpoint, displayArea, params);
}
}
/**
* Notifies the user of an error using UIKit notifications.
*
* @param {string} message - The error message to display.
* @return {void}
*/
#notifyError(message) {
this.#uikit.notification({message, status: 'danger', timeout: 7000});
}
/**
* Logs an error to the console.
*
* @param {string} message - The error message to be logged.
*
* @return {undefined}
*/
#logError(message) {
if (process.env.DEBUG) {
console.error(message);
}
}
/**
* Dispatches a custom event with optional detail data.
*
* @param {string} eventName - The name of the event to dispatch.
* @param {object} [detail={}] - The optional detail data to include with the event.
* @return {void}
*/
#dispatchEvent(eventName, detail = {}) {
document.dispatchEvent(new CustomEvent(`vdm.uikit.uploader.${eventName}`, {detail}));
}
/**
* Builds a URL by appending the GUID parameter.
*
* @param {string} endpoint - The base URL endpoint.
* @param {string} guid - The GUID parameter to be appended to the URL.
* @return {string} - The constructed URL with the GUID parameter appended.
*/
#buildUrl(endpoint, guid) {
const separator = endpoint.includes('?') ? '&' : '?';
return `${endpoint}${separator}guid=${guid}`;
}
/**
* Prepares the UI elements before starting the upload.
*
* @param {object} elements - The UI elements to be modified.
* @param {string} call - The call identifier.
* @param {string} successId - The id of the success message element.
* @param {string} errorId - The id of the error message element.
*/
#prepareUploadUI(elements, call, successId, errorId) {
if (elements.successMessage) elements.successMessage.setAttribute('hidden', 'hidden');
if (elements.errorMessage) elements.errorMessage.setAttribute('hidden', 'hidden');
if (elements.allowedFormatSpan) elements.allowedFormatSpan.innerHTML = this.#uploadHelper.get(call, 'allow_span', '');
if (elements.fileTypeSpan) elements.fileTypeSpan.innerHTML = this.#uploadHelper.get(call, 'file_type_span', 'file');
}
/**
* Handles beforeSend logic for uploads.
*
* @param {object} call - The call object.
* @param {object} environment - The environment object.
* @return {void}
*/
#handleBeforeSend(call, environment) {
this.#dispatchEvent('beforeSend', {environment});
environment.data.params = this.#uploadHelper.getParams(this.#uploadHelper.get(call, 'param_fields'));
this.#dispatchEvent('afterSendPreparation', {environment});
}
/**
* Handles the error scenario during upload.
*
* @param {Error} error - The error object that occurred during upload.
* @param {HTMLElement} errorMessage - The element used to display the error message.
*
* @return {void}
*/
#handleUploadError(error, errorMessage) {
this.#dispatchEvent('error', {error});
if (errorMessage) {
errorMessage.removeAttribute('hidden');
errorMessage.textContent = 'Upload failed.';
}
}
/**
* Handles the upload completion.
*
* @param {XMLHttpRequest} xhr - The XMLHttpRequest object representing the upload request.
* @param {HTMLElement} successMessage - The success message element to display.
*/
#handleComplete(xhr, successMessage) {
this.#dispatchEvent('complete', {xhr});
if (successMessage) {
successMessage.removeAttribute('hidden');
successMessage.textContent = 'Upload completed successfully.';
}
}
/**
* Handles the loadStart event.
*
* @param {Event} e - The loadStart event object.
* @param {HTMLElement} progressBar - The progress bar element. Optional.
* @return {void}
*/
#handleLoadStart(e, progressBar) {
this.#dispatchEvent('loadStart', {event: e});
if (progressBar) {
progressBar.removeAttribute('hidden');
progressBar.max = e.total;
progressBar.value = e.loaded;
}
}
/**
* Handles the progress event.
*
* @param {Event} e - The progress event.
* @param {Element} progressBar - The progress bar element.
*
* @return {void}
*/
#handleProgress(e, progressBar) {
this.#dispatchEvent('progress', {event: e});
if (progressBar) {
progressBar.max = e.total;
progressBar.value = e.loaded;
}
}
/**
* Handles the loadEnd event.
*
* @param {Event} e - The loadEnd event object.
* @param {Element} progressBar - The progress bar element to update.
*
* @return {void}
*/
#handleLoadEnd(e, progressBar) {
this.#dispatchEvent('loadEnd', {event: e});
if (progressBar) {
progressBar.max = e.total;
progressBar.value = e.loaded;
}
}
/**
* Handles the completion of all uploads.
*
* @param {XMLHttpRequest} xhr - The XMLHttpRequest object used for the uploads.
* @param {HTMLElement} progressBar - The progress bar element.
* @param {HTMLElement} successMessage - The success message element.
* @param {HTMLElement} errorMessage - The error message element.
* @param {string} displayEndpoint - The display endpoint.
* @param {string} displayId - The display ID.
* @param {Object} call - The call object.
*
* @return {void}
*/
#handleCompleteAll(xhr, progressBar, successMessage, errorMessage, displayEndpoint, displayId, call) {
this.#dispatchEvent('completeAll', {xhr});
if (progressBar) {
setTimeout(() => {
progressBar.setAttribute('hidden', 'hidden');
if (successMessage) successMessage.setAttribute('hidden', 'hidden');
if (errorMessage) errorMessage.setAttribute('hidden', 'hidden');
}, 5000);
}
this.#setupDisplayArea(displayEndpoint, displayId, this.#uploadHelper.getParams(this.#uploadHelper.get(call, 'display_fields')));
}
}

View File

@ -105,17 +105,15 @@ export class UploadHelper {
*/
init = async (id, guid, reset = false) => {
if (this.#data[id] && !reset) {
process.env.DEBUG === 'true' && console.log(`Field ${id} is already initialized, reusing existing data.`);
process.env.DEBUG && console.log(`Field ${id} is already initialized, reusing existing data.`);
return;
}
try {
const url = this.#buildUrl(this.#endpoint, guid);
const { DEBUG } = process.env;
const result = await this.#fetchData(url);
DEBUG === 'true' && console.log('Data fetched:', result);
if (process.env.DEBUG) console.log('Data fetched:', result);
if (result?.data && typeof result.data === 'object') {
this.set(id, result.data);
@ -123,7 +121,7 @@ export class UploadHelper {
throw new Error(result.error || 'An error occurred during the file type request.');
}
} catch (error) {
DEBUG === 'true' && console.error('Error during initialization:', error);
if (process.env.DEBUG) console.error('Error during initialization:', error);
}
};
@ -140,7 +138,7 @@ export class UploadHelper {
});
if (!response.ok) {
process.env.DEBUG === 'true' && console.error('Error fetching data:', response);
process.env.DEBUG && console.error('Error fetching data:', response);
return;
}