refactor: btns fallback

This commit is contained in:
Xmader 2020-11-13 01:15:01 -05:00
parent 837b960e88
commit f5e308b964
No known key found for this signature in database
GPG Key ID: A20B97FB9EB730E4
2 changed files with 18 additions and 19 deletions

View File

@ -160,19 +160,13 @@ export namespace BtnAction {
})
}
export const download = (url: UrlInput, fallback?: () => Promisable<void>, timeout = Infinity): BtnAction => {
export const download = (url: UrlInput, fallback?: () => Promisable<void>, timeout?: number): BtnAction => {
return process(async (): Promise<void> => {
try {
const _url = await useTimeout(normalizeUrlInput(url), timeout)
const a = document.createElement('a')
a.href = _url
a.dispatchEvent(new MouseEvent('click'))
} catch (err) {
// use fallback
console.error(err)
return fallback?.()
}
})
const _url = await normalizeUrlInput(url)
const a = document.createElement('a')
a.href = _url
a.dispatchEvent(new MouseEvent('click'))
}, fallback, timeout)
}
export const mscoreWindow = (fn: (w: Window, score: WebMscore, processingTextEl: ChildNode) => any): BtnAction => {
@ -206,7 +200,7 @@ export namespace BtnAction {
}
}
export const process = (fn: () => any): BtnAction => {
export const process = (fn: () => any, fallback?: () => Promisable<void>, timeout = Infinity): BtnAction => {
return async (name, btn, setText): Promise<void> => {
const _onclick = btn.onclick
@ -214,11 +208,17 @@ export namespace BtnAction {
setText(i18n('PROCESSING')())
try {
await fn()
await useTimeout(fn(), timeout)
setText(name)
} catch (err) {
setText(i18n('BTN_ERROR')())
console.error(err)
if (fallback) {
// use fallback
await fallback()
setText(name)
} else {
setText(i18n('BTN_ERROR')())
}
}
btn.onclick = _onclick

View File

@ -14,7 +14,6 @@ const main = (): void => {
const filename = scoreinfo.fileName
let indvPartBtn: HTMLButtonElement | null = null
const timeout = 30 * 1000 // 30s
const fallback = () => {
// btns fallback to load from MSCZ file (`Individual Parts`)
return indvPartBtn?.click()
@ -27,7 +26,7 @@ const main = (): void => {
btnList.add({
name: i18n('DOWNLOAD')('PDF'),
action: BtnAction.process(downloadPDF),
action: BtnAction.process(downloadPDF, fallback, 3 * 60 * 1000 /* 3min */),
})
btnList.add({
@ -42,12 +41,12 @@ const main = (): void => {
btnList.add({
name: i18n('DOWNLOAD')('MIDI'),
action: BtnAction.download(() => getFileUrl('midi'), fallback, timeout),
action: BtnAction.download(() => getFileUrl('midi'), fallback, 30 * 1000 /* 30s */),
})
btnList.add({
name: i18n('DOWNLOAD')('MP3'),
action: BtnAction.download(() => getFileUrl('mp3'), fallback, timeout),
action: BtnAction.download(() => getFileUrl('mp3'), fallback, 30 * 1000 /* 30s */),
})
indvPartBtn = btnList.add({