BitBurner react.common.js

mail@pastecode.io avatar
unknown
javascript
7 months ago
1.9 kB
7
Indexable
Never
export class HostElement extends HTMLElement {
  static version = 4; // Increase when this class changes
  static tagName = `react-web-component-host-element-v${HostElement.version}`;
  static create(ElementClass, props = {}) {
    const element = React.createElement(
      HostElement.tagName,
      { ...props, ElementClass }
    );

    return element;
  };

  constructor() {
    super();
  }

  connectedCallback() {
    if (!this.element) {
      const props = this[Object.keys(this).find(k => k.indexOf("__reactProps$") === 0)];
      const ElementClass = props?.ElementClass;
      if (!ElementClass) throw new Error("No ElementClass has been provided.");

      this.element = new ElementClass(this, props);
    }
    this.element?.connectedCallback();
  }

  disconnectedCallback() {
    this.element?.disconnectedCallback();
  }
}

if (!customElements.get(HostElement.tagName))
  customElements.define(HostElement.tagName, HostElement);

export class ClientElementBase {
  constructor(host, props, template) {
    this._host = host;
    this._props = props;
    this._isConnected = false;

    if (template) this.applyTemplate(template)
  }

  get props() { return this._props; }
  get host() { return this._host; }
  get isConnected() { return this._isConnected; }

  applyTemplate(template) {
    const shadowRoot = this.host.attachShadow({ mode: "open" });
    const domContent = template.content.cloneNode(true);
    this.onTemplateApplied(domContent);
    shadowRoot.appendChild(domContent);
  }

  onTemplateApplied(domContent) { }
  connectedCallback() {
    this._isConnected = true;
  }
  disconnectedCallback() {
    this._isConnected = false;
  }
}

export function html(strings, ...values) {
  const tmpl = globalThis["document"].createElement("template");
  tmpl.innerHTML = strings.flatMap((s, i) => [s, values[i]]).join("");
  return tmpl;
}
Leave a Comment