container-picture-element
Version:
HTML picture custom element that works with container queries
83 lines (82 loc) • 2.41 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// src/container-picture.ts
var ContainerPicture = class extends HTMLElement {
constructor() {
super();
__publicField(this, "divs", []);
this.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.setAttribute("type", "text/css");
this.shadowRoot?.appendChild(style);
const slot = document.createElement("slot");
this.shadowRoot?.appendChild(slot);
this.shadowRoot?.addEventListener("slotchange", () => {
this.updateStyle();
this.transformSource();
});
}
connectedCallback() {
this.updateStyle();
this.transformSource();
}
transformSource() {
for (const div of this.divs) {
div.remove();
}
const images = this.querySelectorAll(
"source, img"
);
for (let i = 0; i < images.length; i++) {
const div = document.createElement("div");
this.shadowRoot?.appendChild(div);
this.divs.push(div);
}
}
updateStyle() {
const images = this.querySelectorAll(
"source, img"
);
let css = `
:host {
display: inline-block;
}
slot {
display: none;
}`;
for (let i = 0; i < images.length; i++) {
const image = images[i];
const container = image.getAttribute("container");
css += `
:nth-child(${Number(i) + 3}) {
background: url(${image.src || image.srcset});
width: ${image.width ? image.width + "px" : "auto"};
height: ${image.height ? image.height + "px" : "auto"};
${container ? "display: none" : "display: inline-block"};
}`;
}
for (let i = images.length; i > 0; i--) {
const image = images[i - 1];
const container = image.getAttribute("container");
if (container) {
css += `
@container ${container} {
:nth-child(${i + 2}) {
display: inline-block;
}
:not(:nth-child(${i + 2})) {
display: none;
}
}`;
}
}
const style = this.shadowRoot?.querySelector("style");
if (style) {
style.textContent = css;
}
}
};
customElements.define("container-picture", ContainerPicture);
//# sourceMappingURL=container-picture.cjs.map