feat(ipub): debug attribute and overlay

This commit is contained in:
Guz
2025-11-04 18:40:00 -03:00
parent c90bff53a3
commit f76be67247
3 changed files with 101 additions and 4 deletions

View File

@@ -1,14 +1,29 @@
"use strict";
class IPUBElement extends HTMLElement {
static observedAttributes = ["id"];
/**
* @protected
* @type {Readonly<string[]>}
*/
static observedAttributes = ["id", "debug"];
connectedCallback() {
this.#ensureID();
}
attributeChangedCallback(_name, _oldValue, _newValue) {
this.#ensureID();
attributeChangedCallback(name, _oldValue, _newValue) {
switch (name) {
case "id":
this.#ensureID();
break;
case "debug":
if (this.hasAttribute("debug")) {
this.setDebug(true);
} else {
this.setDebug(false);
}
break;
}
}
/**
@@ -20,6 +35,53 @@ class IPUBElement extends HTMLElement {
}
}
/**
* @returns {boolean}
*/
getDebug() {
return this.hasAttribute("debug");
}
/**
* @param {boolean} state
*/
setDebug(state) {
if (state) {
if (!this.hasAttribute("debug")) {
this.setAttribute("debug", "true");
}
if (!this.style.getPropertyValue(IPUBElement.#PROPERTY_DEBUG_COLOR)) {
this.style.setProperty(
IPUBElement.#PROPERTY_DEBUG_COLOR,
`#${hashFromHTML(this)}`,
);
}
} else {
if (!state && this.hasAttribute("debug")) {
this.removeAttribute("debug");
}
if (
!state &&
this.style.getPropertyValue(IPUBElement.#PROPERTY_DEBUG_COLOR)
) {
this.style.removeProperty(IPUBElement.#PROPERTY_DEBUG_COLOR);
}
}
getAllDescendants(this)
.filter((el) => el.tagName.startsWith("ipub-"))
.forEach((el) => {
el.setDebug?.(state);
});
}
/**
* @private
* @type {Readonly<string>}
*/
static #PROPERTY_DEBUG_COLOR = "--ipub-debug-color";
}
globalThis.addEventListener("load", () => {
@@ -75,6 +137,12 @@ class IPUBBody extends IPUBElement {
globalThis.customElements.define(e.elementName, e);
}
if (this.getDebug()) {
// HACK: Re-trigger IPUBElement debugging logic
console.debug("IPUBBody: triggeing debugger");
this.setAttribute("debug", "true");
}
}
}
class IPUBCover extends IPUBElement {
@@ -590,6 +658,20 @@ function getAncestor(el, tagName) {
return getAncestor(el.parentElement, tagName);
}
/**
* @param {Element} el
* @returns {Element[]}
*/
function getAllDescendants(el) {
return Array.from(el.children).reduce(
(acc, current) => {
acc.push(current);
return acc.concat(getAllDescendants(current));
},
/** @type {Element[]} */ [],
);
}
/**
* @param {Readonly<Element>} el
* @param {number} [length=6]