MCPcopy Create free account
hub / github.com/71/logseq-snippets / defineElement

Function defineElement

script-block.js:5–77  ·  view source on GitHub ↗
(name, render)

Source from the content-addressed store, hash-verified

3const elements = new Map();
4
5export function defineElement(name, render) {
6 let elementClass = elements.get(name);
7
8 if (elementClass === undefined) {
9 elementClass = class extends HTMLElement {
10 constructor() {
11 super();
12
13 this._shadow = this.attachShadow({ mode: "open" });
14 this.render();
15
16 this.addEventListener(
17 "click",
18 (e) => e.stopImmediatePropagation(),
19 );
20 }
21
22 render() {}
23 };
24
25 elements.set(name, elementClass);
26 customElements.define(name, elementClass);
27 }
28
29 elementClass.prototype.render = function() {
30 this._shadow.innerHTML = "";
31
32 const htmlBefore = this.outerHTML,
33 state = { html, svg };
34
35 for (const attr of this.attributes) {
36 let value = attr.value;
37 if (value[0] === "{")
38 value = JSON.parse(value);
39 state[attr.name] = value;
40 }
41
42 state.save = (x = state) => {
43 for (const name in x) {
44 let value = x[name];
45 if (typeof value === "object")
46 value = JSON.stringify(value);
47 this.setAttribute(name, value);
48 }
49
50 const htmlAfter = this.outerHTML,
51 block = this.closest("[blockid]"),
52 blockId = block.getAttribute("blockid");
53
54 requestAnimationFrame(() => {
55 const textarea = document.getElementById("edit-block-1-" + blockId);
56
57 textarea.value = textarea.value.replace(htmlBefore, htmlAfter);
58 setTimeout(() => {
59 textarea.dispatchEvent(new KeyboardEvent("keydown", { keyCode: 27 }));
60 }, 100);
61 });
62 block.click();

Callers 1

constructorMethod · 0.85

Calls 1

renderMethod · 0.80

Tested by

no test coverage detected