Improve ts hooks to allow for asynchronous actions

* reviewer ts hooks may now return a promise, which are then waited upon with Promise.all
* this does not break old ts hooks, as Promise.all allows for non-Promises in its array
This commit is contained in:
Henrik Giesel 2020-11-15 20:57:07 +01:00
parent 4229f21084
commit a7b5a7efe1

View file

@ -11,10 +11,14 @@ var aFade = 0;
var onUpdateHook; var onUpdateHook;
var onShownHook; var onShownHook;
function _runHook(arr) { function _runHook(arr: () => Promise<any>[]): Promise<any[]> {
var promises = [];
for (var i = 0; i < arr.length; i++) { for (var i = 0; i < arr.length; i++) {
arr[i](); promises.push(arr[i]());
} }
return Promise.all(promises);
} }
function _updateQA(html, fadeTime, onupdate, onshown) { function _updateQA(html, fadeTime, onupdate, onshown) {
@ -32,13 +36,16 @@ function _updateQA(html, fadeTime, onupdate, onshown) {
onUpdateHook = [onupdate]; onUpdateHook = [onupdate];
onShownHook = [onshown]; onShownHook = [onshown];
// fade out current text
var qa = $("#qa"); var qa = $("#qa");
qa.fadeTo(fadeTime, 0, function () {
// fade out current text
qa.fadeOut(fadeTime).promise()
// update text // update text
.then(() => {
try { try {
qa.html(html); qa.html(html)
} catch (err) { }
catch (err) {
qa.html( qa.html(
( (
`Invalid HTML on card: ${String(err).substring(0, 2000)}\n` + `Invalid HTML on card: ${String(err).substring(0, 2000)}\n` +
@ -46,21 +53,21 @@ function _updateQA(html, fadeTime, onupdate, onshown) {
).replace(/\n/g, "<br />") ).replace(/\n/g, "<br />")
); );
} }
_runHook(onUpdateHook); })
.then(() => _runHook(onUpdateHook))
// @ts-ignore wait for mathjax to ready
.then(() => MathJax.startup.promise
.then(() => {
// @ts-ignore clear MathJax buffer
MathJax.typesetClear();
// @ts-ignore // @ts-ignore typeset
MathJax.startup.promise return MathJax.typesetPromise(qa.slice(0, 1));
// render mathjax }))
// @ts-ignore
.then(MathJax.typesetPromise)
// and reveal when processing is done // and reveal when processing is done
.then(function () { .then(() => qa.fadeIn(fadeTime).promise())
qa.fadeTo(fadeTime, 1, function () { .then(() => _runHook(onShownHook))
_runHook(onShownHook); .then(() => _updatingQA = false);
_updatingQA = false;
});
});
});
} }
function _showQuestion(q, bodyclass) { function _showQuestion(q, bodyclass) {