Skip to content

Commit

Permalink
Progress Loader
Browse files Browse the repository at this point in the history
  • Loading branch information
aishwaryamathuria committed Sep 16, 2024
1 parent 3090caf commit 59ab460
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 84 deletions.
8 changes: 1 addition & 7 deletions unitylibs/core/features/progress-bar/progress-bar.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,7 @@ const pdom = `<div class="spectrum-ProgressBar spectrum-ProgressBar--sizeM spect
export default function createProgressBar() {
const layer = createTag('div', { class: 'progress-holder' }, pdom);
layer.addEventListener('unity:progress-bar-update', (e) => {
let p = 0;
if (e.detail?.percentage) {
p = e.detail?.percentage;
} else {
const currVal = parseInt(layer.querySelector('.spectrum-ProgressBar-fill').style.width);
p = Math.min(currVal + 10, 100);
}
const p = Math.min(e.detail.percentage, 100);
const spb = layer.querySelector('.spectrum-ProgressBar');
spb.setAttribute('value', p);
spb.setAttribute('aria-valuenow', p);
Expand Down
176 changes: 102 additions & 74 deletions unitylibs/core/workflow/workflow-acrobat/action-binder.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export default class ActionBinder {
this.acrobatApiConfig = this.getAcrobatApiConfig();
this.serviceHandler = null;
this.splashScreenEl = null;
this.promiseStack = [];
this.LOADER_DELAY = 800;
this.LOADER_INCREMENT = 30;
}

getAcrobatApiConfig() {
Expand All @@ -43,7 +46,7 @@ export default class ActionBinder {
await priorityLoad(parr);
}

async acrobatActionMaps(values, e) {
async acrobatActionMaps(values, files) {
await this.handlePreloads(values);
const { default: ServiceHandler } = await import(`${getUnityLibs()}/core/workflow/${this.workflowCfg.name}/service-handler.js`);
this.serviceHandler = new ServiceHandler(
Expand All @@ -53,22 +56,31 @@ export default class ActionBinder {
for (const value of values) {
switch (true) {
case value.actionType == 'upload' || value.actionType == 'drop':
this.promiseStack = [];
await this.userPdfUpload(value, files);
break;
case value.actionType == 'continueInApp':
await this.continueInApp();
break;
case value.actionType == 'interrupt':
this.cancelAcrobatOperation(values);
default:
break;
}
}
}

initActionListeners() {
for (const [key, values] of Object.entries(this.actionMap)) {
const el = this.block.querySelector(key);
initActionListeners(b = this.block, actMap = this.actionMap) {
for (const [key, values] of Object.entries(actMap)) {
const el = b.querySelector(key);
if (!el) return;
switch (true) {
case el.nodeName === 'A':
el.addEventListener('click', async (e) => {
e.preventDefault();
await this.acrobatActionMaps(values);
});
break;
case el.nodeName === 'DIV':
el.addEventListener('drop', async (e) => {
e.preventDefault();
Expand Down Expand Up @@ -118,17 +130,13 @@ export default class ActionBinder {
}

async uploadFileToUnity(storageUrl, blobData, fileType) {
this.updateSplashScreenLoader();
if (this.cancelOperation) {
this.cancelOperation = false;
return;
}
const uploadOptions = {
method: 'PUT',
headers: { 'Content-Type': fileType },
body: blobData,
};
const response = await fetch(storageUrl, uploadOptions); //Handle error
const response = await fetch(storageUrl, uploadOptions);
return response;
}

async chunkPdf(assetData, blobData, filetype) {
Expand All @@ -141,17 +149,12 @@ export default class ActionBinder {
const url = assetData.uploadUrls[i];
return this.uploadFileToUnity(url.href, chunk, filetype);
});
await Promise.all(uploadPromises);
this.promiseStack.push(...uploadPromises);
await Promise.all(this.promiseStack);
}

async continueInApp() {
if (!this.operations.length) return;
debugger;
if (this.cancelOperation) {
this.cancelOperation = false;
return;
}
this.updateSplashScreenLoader(100);
const { assetId, filename, filesize, filetype } = this.operations[this.operations.length - 1];
const cOpts = {
assetId,
Expand All @@ -169,36 +172,49 @@ export default class ActionBinder {
},
},
};
const response = await this.serviceHandler.postCallToService(
this.acrobatApiConfig.connectorApiEndPoint,
{ body: JSON.stringify(cOpts) },
);
if (!response) return await this.handleSplashScreen(params);
if (this.cancelOperation) {
this.cancelOperation = false;
return;
}
// console.log(response.url);
window.location.href = response.url;
this.promiseStack.push(
this.serviceHandler.postCallToService(
this.acrobatApiConfig.connectorApiEndPoint,
{ body: JSON.stringify(cOpts) },
));
await Promise.all(this.promiseStack)
.then(() => {
this.progressBarHandler(this.splashScreenEl, this.LOADER_DELAY, 100);
const response = this.promiseStack[this.promiseStack.length - 1];
window.location.href = response.url;
})
.catch(() => {
this.handleSplashScreen(params);
});
}

cancelAcrobatOperation(e) {
debugger;
this.cancelOperation = true;
e.target.closest('.splash-loader').classList.remove('show');
cancelAcrobatOperation(params) {
this.handleSplashScreen(params);
const cancelPromise = Promise.reject(new Error('Operation termination requested.'));
this.promiseStack.unshift(cancelPromise);
}

updateSplashScreenLoader(p = null) {
if (!this.splashScreenEl) return;
if (p) this.splashScreenEl.querySelector('.progress-holder')?.dispatchEvent(new CustomEvent("unity:progress-bar-update", {detail: { percentage: p }}));
else this.splashScreenEl.querySelector('.progress-holder')?.dispatchEvent(new CustomEvent("unity:progress-bar-update"));
progressBarHandler(s, delay, i, initialize = false) {
delay = Math.min(delay + 100, 2000);
i = Math.max(i - 5, 5);
const progressBar = s.querySelector('.spectrum-ProgressBar');
if (progressBar.getAttribute('value') == 100) return;
setTimeout(() => {
let v = initialize ? 0 : parseInt(s.querySelector('.spectrum-ProgressBar').getAttribute('value'));
s.querySelector('.progress-holder')?.dispatchEvent(new CustomEvent("unity:progress-bar-update", {detail: { percentage: (v + i) }}));
this.progressBarHandler(s, delay, i);
}, delay);
}

async handleSplashScreen(params) {
if (!params.showSplashScreen) return;
if (this.splashScreenEl) {
if (this.splashScreenEl.classList.contains('show')) this.splashScreenEl.classList.remove('show');
else this.splashScreenEl.classList.add('show');
if (this.splashScreenEl.classList.contains('show')) {
this.splashScreenEl.classList.remove('show');
} else {
this.progressBarHandler(this.splashScreenEl, this.LOADER_DELAY, this.LOADER_INCREMENT, true);
this.splashScreenEl.classList.add('show');
}
return;
}
const { default: init} = await import(`${getLibs()}/blocks/fragment/fragment.js`);
Expand All @@ -217,14 +233,18 @@ export default class ActionBinder {
const { default: createProgressBar } = await import(`${getUnityLibs()}/core/features/progress-bar/progress-bar.js`);
const pb = createProgressBar();
pbarPlaceholder.replaceWith(pb);
this.progressBarHandler(sel, this.LOADER_DELAY, this.LOADER_INCREMENT, true);
}
const hasCancel = sel.querySelector('a.con-button[href*="#_cancel"]');
if (hasCancel) {
hasCancel.href = '#'
hasCancel.addEventListener('click', (e) => {
e.preventDefault();
this.cancelAcrobatOperation(e);
});
const actMap = {
'a.con-button[href*="#_cancel"]': [
{
"actionType": "interrupt"
}
]
}
this.initActionListeners(sel, actMap);
}
this.splashScreenEl = sel;
this.splashScreenEl.classList.add('splash-loader', 'show');
Expand All @@ -237,36 +257,44 @@ export default class ActionBinder {
if (file.type != 'application/pdf') return;
const [minsize, maxsize] = this.limits.allowedFileSize;
if (!((file.size > minsize) && (file.size <= maxsize))) return;
await this.handleSplashScreen(params);
const blobData = await this.getBlobData(file);
const data = {
surfaceId: unityConfig.surfaceId,
targetProduct: this.workflowCfg.productName,
name: file.name,
size: file.size,
format: file.type,
};
const assetData = await this.serviceHandler.postCallToService(
this.acrobatApiConfig.acrobatEndpoint.createAsset,
{ body: JSON.stringify(data) },
);
if (!assetData) return await this.handleSplashScreen(params);
await this.chunkPdf(assetData, blobData, file.type);
const operationItem = {
assetId: assetData.id,
filename: file.name,
filesize: file.size,
filetype: file.type,
};
this.operations.push(operationItem);
const finalAssetData = {
surfaceId: unityConfig.surfaceId,
targetProduct: this.workflowCfg.productName,
assetId: assetData.id,
};
this.serviceHandler.postCallToService(
this.acrobatApiConfig.acrobatEndpoint.finalizeAsset,
{ body: JSON.stringify(finalAssetData) },
);
let assetData = null;
try {
await this.handleSplashScreen(params);
const blobData = await this.getBlobData(file);
const data = {
surfaceId: unityConfig.surfaceId,
targetProduct: this.workflowCfg.productName,
name: file.name,
size: file.size,
format: file.type,
};
assetData = await this.serviceHandler.postCallToService(
this.acrobatApiConfig.acrobatEndpoint.createAsset,
{ body: JSON.stringify(data) },
);
await this.chunkPdf(assetData, blobData, file.type);
const operationItem = {
assetId: assetData.id,
filename: file.name,
filesize: file.size,
filetype: file.type,
};
this.operations.push(operationItem);
} catch (e) {
await this.handleSplashScreen(params);
}
try {
const finalAssetData = {
surfaceId: unityConfig.surfaceId,
targetProduct: this.workflowCfg.productName,
assetId: assetData.id,
};
this.serviceHandler.postCallToService(
this.acrobatApiConfig.acrobatEndpoint.finalizeAsset,
{ body: JSON.stringify(finalAssetData) },
);
} catch (e) {
// Failed in finalize
}
}
}
5 changes: 2 additions & 3 deletions unitylibs/core/workflow/workflow-acrobat/service-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,12 @@ export default class ServiceHandler {
};
try {
const response = await fetch(api, postOpts);
if (response.status !== 200) return null;
if (response.status !== 200) throw new Error('Error connecting with the service.');
const resJson = await response.json();
return resJson;
} catch (err) {
// if (this.renderWidget) await this.errorToast(err);
throw new Error('Error connecting with the service.');
}
return null;
}

// TODO: Define PDF chunking function
Expand Down

0 comments on commit 59ab460

Please sign in to comment.