// print.js
(function () {
/* global AdventureJS A */
var p = AdventureJS.Display.prototype;
/**
* Global method for printing text to game display.
* @memberOf AdventureJS.Display
* @method AdventureJS.Display#print
* @param {String} msg An arbitrary string.
* @param {String} classes Optional class(es) to apply to output.
* @TODO add ability to pause at screen height so excess text doesn't scroll off screen
*/
p.print = function Display_print(msg, classes) {
const msgEl = document.createElement("div");
msgEl.innerHTML = msg;
msgEl.classList = `ajs-p ${classes}`;
if (msg.includes("<img")) {
msgEl.classList.add("ajs-inline-image-container");
}
this.outputEl.append(msgEl);
this.scrollToBottom(msgEl);
return msg;
};
/**
* scrollToBottom accommodates image loading. Images that are
* stored in an image lookup will have been cached and are
* usually available within a couple of paints. Images loaded
* via <img> tag in text will need unknown time to load.
* @param {*} el
*/
p.scrollToBottom = async function Display_scrollToBottom(el) {
const images = [...el.querySelectorAll("img:not([data-ajs-scrolled])")];
await Promise.all(
[...images].map(async (img) => {
if (!img.complete) {
await new Promise((resolve) => {
img.addEventListener("load", resolve, { once: true });
img.addEventListener("error", resolve, { once: true });
});
}
if (img.decode) {
try {
await img.decode();
} catch {
// Ignore image decoding failures.
}
}
// mark it as scrolled to ensure we don't
// consider it in future scroll operations
img.dataset.ajsScrolled = "true";
})
);
this.outputContainerEl.scrollTo({
top: this.outputContainerEl.scrollHeight,
left: 0,
behavior: "smooth",
});
};
})();