Newer
Older
hello-programmer-world / src / components / DockerLink.astro
@h.sakamoto h.sakamoto on 5 Feb 1 KB sql
---
const { WEB_PORT = 8080 } = import.meta.env;

interface Props {
	href: string;
	title?: string;
}
---

<astro-docker-link>
  <a href="#" target="_blank" rel="noopener noreferrer" data-link={Astro.props.href || ""} data-title={Astro.props.title} data-port={WEB_PORT}>
    Docker: {Astro.props.title}
  </a>
</astro-docker-link>

<script is:inline>

if (!customElements.get("astro-docker-link")) {
  class AstroDockerLink extends HTMLElement {
    connectedCallback() {
      const anchor = this.querySelector("a");

      if (anchor) {
        this.updateAnchor(anchor);
      } else {
        // 子要素がまだ追加されていない場合、MutationObserver で監視
        const observer = new MutationObserver((mutations, obs) => {
          const anchor = this.querySelector("a");
          if (anchor) {
            this.updateAnchor(anchor);
            obs.disconnect();
          }
        });

        observer.observe(this, { childList: true, subtree: true });
      }
    }

    updateAnchor(anchor) {
      const href = anchor.dataset.link;
      const port = anchor.dataset.port || 8080;

      const host = window.location.hostname;
      const url = `http://${host}:${port}/${href || ""}`;

      anchor.href = url;

      const title = anchor.dataset.title || url;
      anchor.textContent = `Docker: ${title}`;
    }
  }

  customElements.define("astro-docker-link", AstroDockerLink);
}
</script>