Newer
Older
hello-programmer-world / src / components / Dialog.astro
@h.sakamoto h.sakamoto 3 days ago 1 KB dialog
---
import { randomUUID } from "node:crypto";

interface Props {
	title: string;
}

const uuid = randomUUID();
const wrapperStyles = ["cursor: pointer;"];
---

<astro-dialog data-uuid={uuid}>
  <button
    id={`trigger-${uuid}`}
    style={wrapperStyles.join(" ")}
    class="btn btn-soft btn-sm"
  >
    {Astro.props.title}
  </button>

  <dialog
    id={`dialog-${uuid}`}
    closedby="any"
    class="modal"
  >
    <div class="modal-box">
      <slot />
    </div>
    <form method="dialog" class="modal-backdrop">
      <button>閉じる</button>
    </form>
  </dialog>
</astro-dialog>

<script>
class AstroDialog extends HTMLElement {
  connectedCallback() {
    const uuid = this.dataset.uuid;

    const triggerId = `trigger-${uuid}`;
    const dialogId = `dialog-${uuid}`;

    const trigger = document.getElementById(triggerId);
    const dialog = document.getElementById(dialogId);

    trigger.addEventListener("click", () => {
      dialog.showModal();
    });
  }
}

customElements.define("astro-dialog", AstroDialog);
</script>