2020-09-27 16:20:33 +00:00
|
|
|
|
|
|
|
import { fetchMscz } from './mscz'
|
|
|
|
|
|
|
|
const WEBMSCORE_URL = 'https://cdn.jsdelivr.net/npm/webmscore@0.10/webmscore.js'
|
|
|
|
|
2020-09-28 21:08:52 +00:00
|
|
|
// fonts for Chinese characters (CN) and Korean hangul (KR)
|
|
|
|
// JP characters are included in the CN font
|
|
|
|
const FONT_URLS = ['CN', 'KR'].map(l => `https://cdn.jsdelivr.net/npm/@librescore/fonts/SourceHanSans${l}-Regular.woff2`)
|
|
|
|
|
2020-09-27 16:20:33 +00:00
|
|
|
export type WebMscore = import('webmscore').default
|
|
|
|
|
|
|
|
const initMscore = async (w: Window) => {
|
|
|
|
if (!w['WebMscore']) {
|
|
|
|
// init webmscore (https://github.com/LibreScore/webmscore)
|
|
|
|
const script = w.document.createElement('script')
|
|
|
|
script.src = WEBMSCORE_URL
|
|
|
|
w.document.body.append(script)
|
|
|
|
await new Promise(resolve => { script.onload = resolve })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-28 21:08:52 +00:00
|
|
|
let fonts: Promise<Uint8Array[]> | undefined
|
|
|
|
const initFonts = () => {
|
|
|
|
// load CJK fonts
|
|
|
|
// CJK (East Asian) characters will be rendered as "tofu" if there is no font
|
|
|
|
if (!fonts) {
|
|
|
|
fonts = Promise.all(
|
|
|
|
FONT_URLS.map(async (url) => {
|
|
|
|
const r = await fetch(url)
|
|
|
|
const data = await r.arrayBuffer()
|
|
|
|
return new Uint8Array(data)
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-27 16:20:33 +00:00
|
|
|
export const loadMscore = async (w: Window): Promise<WebMscore> => {
|
2020-09-28 21:08:52 +00:00
|
|
|
initFonts()
|
2020-09-27 16:20:33 +00:00
|
|
|
await initMscore(w)
|
|
|
|
|
|
|
|
const WebMscore: typeof import('webmscore').default = w['WebMscore']
|
|
|
|
// parse mscz data
|
|
|
|
const data = new Uint8Array(
|
|
|
|
new Uint8Array(await fetchMscz()), // copy its ArrayBuffer
|
|
|
|
)
|
2020-09-28 21:08:52 +00:00
|
|
|
const score = await WebMscore.load('mscz', data, await fonts)
|
2020-09-27 16:20:33 +00:00
|
|
|
await score.generateExcerpts()
|
|
|
|
|
|
|
|
return score
|
|
|
|
}
|