musescore-downloader/src/btn.ts

237 lines
6.3 KiB
TypeScript
Raw Normal View History

2020-05-19 04:15:22 +00:00
import { loadMscore, WebMscore } from './mscore'
2020-11-13 20:55:41 +00:00
import { useTimeout, windowOpen } from './utils'
2020-11-05 05:22:15 +00:00
import i18n from './i18n'
2020-11-12 17:35:11 +00:00
// @ts-ignore
import btnListCss from './btn.css'
2020-09-28 21:23:16 +00:00
type BtnElement = HTMLButtonElement
2020-05-19 04:15:22 +00:00
2020-11-12 18:02:50 +00:00
const getBtnContainer = (): HTMLDivElement => {
2020-11-12 16:41:03 +00:00
const container = document.querySelectorAll('aside>section>section')[0]
2020-11-12 18:02:50 +00:00
return [...container.children].find((div) => {
2020-11-12 16:41:03 +00:00
const b = div.querySelector('button, .button')
return b && b.outerHTML.replace(/\s/g, '').includes('Download')
}) as HTMLDivElement
2020-05-19 04:15:22 +00:00
}
2020-11-12 17:49:45 +00:00
const buildDownloadBtn = () => {
const btn = document.createElement('button')
btn.type = 'button'
// build icon svg element
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
svg.setAttribute('viewBox', '0 0 24 24')
const svgPath = document.createElementNS('http://www.w3.org/2000/svg', 'path')
svgPath.setAttribute('d', 'M9.6 2.4h4.8V12h2.784l-5.18 5.18L6.823 12H9.6V2.4zM19.2 19.2H4.8v2.4h14.4v-2.4z')
svgPath.setAttribute('fill', '#fff')
svg.append(svgPath)
const textNode = document.createElement('span')
btn.append(svg, textNode)
return {
btn,
textNode,
}
}
2020-05-19 04:15:22 +00:00
interface BtnOptions {
readonly name: string;
readonly action: BtnAction;
2020-09-28 21:41:51 +00:00
readonly disabled?: boolean;
readonly tooltip?: string;
2020-05-19 04:15:22 +00:00
}
export enum BtnListMode {
InPage,
ExtWindow,
}
2020-05-19 04:15:22 +00:00
export class BtnList {
private readonly list: BtnElement[] = [];
2020-11-12 18:02:50 +00:00
constructor (private getBtnParent: () => HTMLDivElement = getBtnContainer) { }
2020-05-19 04:15:22 +00:00
add (options: BtnOptions): BtnElement {
2020-11-12 17:49:45 +00:00
const { btn, textNode } = buildDownloadBtn()
2020-05-19 04:15:22 +00:00
const setText = (str: string): void => {
textNode.textContent = str
}
setText(options.name)
btn.onclick = (): void => {
options.action(options.name, btn, setText)
}
this.list.push(btn)
2020-09-28 21:41:51 +00:00
if (options.disabled) {
btn.disabled = options.disabled
}
if (options.tooltip) {
btn.title = options.tooltip
}
2020-05-19 04:15:22 +00:00
return btn
}
2020-11-12 18:02:50 +00:00
private _commit () {
let btnParent: HTMLDivElement = document.createElement('div')
try {
btnParent = this.getBtnParent()
} catch (err) {
console.error(err)
}
const shadow = btnParent.attachShadow({ mode: 'closed' })
2020-11-12 17:35:11 +00:00
// style the shadow DOM
const style = document.createElement('style')
style.innerText = btnListCss
shadow.append(style)
// hide buttons using the shadow DOM
const newParent = btnParent.cloneNode(false) as HTMLDivElement
newParent.append(...this.list)
shadow.append(newParent)
2020-11-10 18:36:49 +00:00
2020-11-12 18:02:50 +00:00
return btnParent
2020-11-10 18:36:49 +00:00
}
/**
* replace the template button with the list of new buttons
*/
commit (mode: BtnListMode = BtnListMode.InPage): void {
switch (mode) {
case BtnListMode.InPage: {
2020-11-12 18:02:50 +00:00
// fallback to BtnListMode.ExtWindow
try {
this.getBtnParent()
} catch {
return this.commit(BtnListMode.ExtWindow)
}
let el: Element = this._commit()
const observer = new MutationObserver(() => {
// check if the buttons are still in document when dom updates
if (!document.contains(el)) {
// re-commit
// performance issue?
2020-11-12 18:02:50 +00:00
el = this._commit()
}
})
observer.observe(document, { childList: true, subtree: true })
break
2020-11-10 18:36:49 +00:00
}
case BtnListMode.ExtWindow: {
2020-11-12 18:02:50 +00:00
const div = this._commit()
2020-11-13 20:55:41 +00:00
const w = windowOpen('', undefined, 'resizable,width=230,height=270')
// eslint-disable-next-line no-unused-expressions
w?.document.body.append(div)
window.addEventListener('unload', () => w?.close())
break
}
default:
throw new Error('unknown BtnListMode')
}
2020-05-19 04:15:22 +00:00
}
}
type BtnAction = (btnName: string, btnEl: BtnElement, setText: (str: string) => void) => any
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace BtnAction {
type Promisable<T> = T | Promise<T>
type UrlInput = Promisable<string> | (() => Promisable<string>)
const normalizeUrlInput = (url: UrlInput) => {
if (typeof url === 'function') return url()
else return url
}
export const openUrl = (url: UrlInput): BtnAction => {
return process(async (): Promise<any> => {
2020-11-13 20:55:41 +00:00
windowOpen(await normalizeUrlInput(url))
})
}
2020-11-13 06:15:01 +00:00
export const download = (url: UrlInput, fallback?: () => Promisable<void>, timeout?: number): BtnAction => {
return process(async (): Promise<void> => {
2020-11-13 06:15:01 +00:00
const _url = await normalizeUrlInput(url)
const a = document.createElement('a')
a.href = _url
a.dispatchEvent(new MouseEvent('click'))
}, fallback, timeout)
2020-05-19 04:15:22 +00:00
}
export const mscoreWindow = (fn: (w: Window, score: WebMscore, processingTextEl: ChildNode) => any): BtnAction => {
return async (btnName, btn, setText) => {
const _onclick = btn.onclick
btn.onclick = null
2020-11-05 05:22:15 +00:00
setText(i18n('PROCESSING')())
2020-11-13 20:55:41 +00:00
const w = windowOpen('') as Window
2020-11-05 05:22:15 +00:00
const txt = document.createTextNode(i18n('PROCESSING')())
w.document.body.append(txt)
// set page hooks
// eslint-disable-next-line prefer-const
let score: WebMscore
const destroy = (): void => {
score && score.destroy()
w.close()
}
window.addEventListener('unload', destroy)
w.addEventListener('beforeunload', () => {
score && score.destroy()
window.removeEventListener('unload', destroy)
setText(btnName)
btn.onclick = _onclick
})
score = await loadMscore(w)
fn(w, score, txt)
}
}
2020-11-13 06:15:01 +00:00
export const process = (fn: () => any, fallback?: () => Promisable<void>, timeout = Infinity): BtnAction => {
2020-05-19 04:15:22 +00:00
return async (name, btn, setText): Promise<void> => {
const _onclick = btn.onclick
btn.onclick = null
2020-11-05 05:22:15 +00:00
setText(i18n('PROCESSING')())
2020-05-19 04:15:22 +00:00
try {
2020-11-13 06:15:01 +00:00
await useTimeout(fn(), timeout)
2020-05-19 04:15:22 +00:00
setText(name)
} catch (err) {
console.error(err)
2020-11-13 06:15:01 +00:00
if (fallback) {
// use fallback
await fallback()
setText(name)
} else {
setText(i18n('BTN_ERROR')())
}
2020-05-19 04:15:22 +00:00
}
btn.onclick = _onclick
}
}
export const deprecate = (action: BtnAction): BtnAction => {
return (name, btn, setText) => {
2020-11-05 05:22:15 +00:00
alert(i18n('DEPRECATION_NOTICE')(name))
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return action(name, btn, setText)
}
}
2020-05-19 04:15:22 +00:00
}