From a1a8b89a2bc47681c18af77522d88f10b161c315 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Tue, 24 Oct 2023 15:47:53 +0200 Subject: [PATCH] WIP refactor of `CanvasElement` --- src/elements/base.mjs | 103 ++++++++------- src/elements/{ => canvas}/canvas.mjs | 180 +++++++++++++++++++++------ src/elements/canvas/canvasitem.mjs | 0 src/elements/display.mjs | 4 +- src/elements/edge.mjs | 4 +- src/elements/index.mjs | 2 +- src/elements/markdown.mjs | 4 +- src/elements/node.mjs | 8 +- src/utils/errors.mjs | 8 ++ src/utils/trasversal.mjs | 34 +++++ 10 files changed, 243 insertions(+), 104 deletions(-) rename src/elements/{ => canvas}/canvas.mjs (56%) create mode 100644 src/elements/canvas/canvasitem.mjs create mode 100644 src/utils/errors.mjs create mode 100644 src/utils/trasversal.mjs diff --git a/src/elements/base.mjs b/src/elements/base.mjs index b57ed2e..eac1a0a 100644 --- a/src/elements/base.mjs +++ b/src/elements/base.mjs @@ -1,64 +1,61 @@ -export class NotImplementedError extends Error {} +import { NotImplementedError } from "../utils/errors.mjs"; +/** + * Abstract base utility class to simplify the construction of custom elements. + * @abstract Implementors must override {@link template}. + */ export class CustomElement extends HTMLElement { - - template - shadow - instance - - // noinspection JSUnusedGlobalSymbols - connectedCallback() { - // The template to duplicate. - this.template = this.constructor.getTemplate() - // The shadow root, the inner contents of the element.. - this.shadow = this.attachShadow({ mode: "open" }) - // The element contained inside the shadow root.. - this.instance = this.template.content.cloneNode(true) - - // Call the custom callback. - this.onConnected() - - // Add the instance to the DOM. - this.shadow.appendChild(this.instance) - } - - findFirstAncestor(constructor) { - let current = this - // Keep iterating over nodes - while(current) { - // The ancestor has been found! - if(current instanceof constructor) { - return current - } - // Use .host to access the parent of a ShadowRoot - else if(current instanceof ShadowRoot) { - current = current.host - } - // Use .parentNode to access the parent of a HTMLElement - else if(current instanceof HTMLElement) { - current = current.parentNode - } - // Something went wrong? - else { - console.warn("[findFirstAncestor] Reached unknown node:", current) - } - } - // The ancestor has NOT been found... - return null - } - constructor() { super(); - + // Prevent accidental instantiation of this class. if(this.constructor === CustomElement) { - throw new NotImplementedError("CustomElement is being used as-is.") + throw new NotImplementedError("CustomElement is being used as-is, but is an abstract class.") } } - onConnected() {} - - static getTemplate() { - throw new NotImplementedError("CustomElement.getTemplate has not been overridden.") + /** + * Get the `