Skip to content

Instantly share code, notes, and snippets.

@jmuzsik
Last active July 30, 2019 04:32
Show Gist options
  • Save jmuzsik/f912a76cbf04bdb137bc7f1295ae5e0e to your computer and use it in GitHub Desktop.
Save jmuzsik/f912a76cbf04bdb137bc7f1295ae5e0e to your computer and use it in GitHub Desktop.
// Creation of DOM elements, to be added to the DOM later.
logTaskHandler(data) {
this.log('<strong>Running task #' + this.currentTaskNumber + '</strong>');
for (let i = 0; i < data.count; i += 1) {
this.log((i + 1).toString() + '. ' + data.text);
}
}
log(text) {
if (!this.logFragment) {
this.logFragment = document.createDocumentFragment();
}
const el = document.createElement('div');
el.innerHTML = text;
this.logFragment.appendChild(el);
}
// requestAnimationFrame.
scheduleStatusRefresh() {
if (!this.statusRefreshScheduled) {
requestAnimationFrame(this.updateDisplay);
this.statusRefreshScheduled = true;
}
}
// All DOM stuff happens in here.
updateDisplay() {
// Cannot access elements inside the shadow DOM from outside of it.
const shadowRoot = this.shadowRoot;
const logElem = shadowRoot.getElementById('log');
const progressBarElem = shadowRoot.getElementById('progress');
const currentTaskNumberElem = shadowRoot.getElementById(
'currentTaskNumber'
);
const totalTaskCountElem = shadowRoot.getElementById('totalTaskCount');
// All this really does is scroll to the end of all the content that is rendered.
const scrolledToEnd =
logElem.scrollHeight - logElem.clientHeight <= logElem.scrollTop + 1;
// This is only false on the first render.
if (this.totalTaskCount) {
if (progressBarElem.max !== this.totalTaskCount) {
totalTaskCountElem.textContent = this.totalTaskCount;
progressBarElem.max = this.totalTaskCount;
}
if (progressBarElem.value !== this.currentTaskNumber) {
currentTaskNumberElem.textContent = this.currentTaskNumber;
progressBarElem.value = this.currentTaskNumber;
}
}
if (this.logFragment) {
logElem.appendChild(this.logFragment);
this.logFragment = null;
}
if (scrolledToEnd) {
logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight;
}
this.statusRefreshScheduled = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment