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

interface Props {
	src: string;
	alt?: string;
	style?: Record<string, string | number>;
}

const src = Astro.props.src;
const alt = Astro.props.alt || "";

const uuid = randomUUID();

const wrapperStyles = [
	"cursor: pointer;",
	...(Astro.props.style
		? Object.entries(Astro.props.style).map(
				([key, value]) => `${key}: ${value};`,
			)
		: null),
];
---

<astro-image data-uuid={uuid}>
  <div
    id={`trigger-${uuid}`}
    style={wrapperStyles.join(" ")}
  >
    <img 
      src={src} 
      alt={alt} 
    />
  </div>

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


<script>
class AstroImage 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-image", AstroImage);
</script>