Skip to content

Commit

Permalink
fix : adjust the new component writting styles and apply feedback pro…
Browse files Browse the repository at this point in the history
…vided
  • Loading branch information
SamTheKorean committed Jun 24, 2024
1 parent fb22748 commit 06a22ae
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
62 changes: 62 additions & 0 deletions components/image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
class Image extends HTMLElement {
constructor() {
super();

this.validateAttributes();
this.render();
}

validateAttributes() {
if (!this.hasAttribute("alt")) {
throw new Error('The "alt" attribute is required.');
}

const allowedAttributes = ["src", "alt", "width", "height"];
for (const attr of this.attributes) {
if (!allowedAttributes.includes(attr.name)) {
throw new Error(`The attribute "${attr.name}" is not allowed.`);
}
}
}

render() {
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = this.createCss() + this.createHtml();
}

createCss() {
return `
<style>
img {
display: block;
max-width: 100%;
}
</style>
`;
}

createHtml() {
const src = this.getAttribute("src") ?? "";
const alt = this.getAttribute("alt") ?? "";

let imgHtml = `<img src="${src}" alt="${alt}"`;

if (this.hasAttribute("width")) {
const width = this.getAttribute("width");
imgHtml += ` width="${width}"`;
}

if (this.hasAttribute("height")) {
const height = this.getAttribute("height");
imgHtml += ` height="${height}"`;
}

imgHtml += `>`;

return `
${imgHtml}
`;
}
}

customElements.define("ds-image", Image);
3 changes: 2 additions & 1 deletion main.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import "./components/button-link.js";
import "./components/footer-link/footer-link.js";
import "./components/header.js";
import "./components/hero/hero.js";
import "./components/button-link.js";
import "./components/image.js";
import "./components/review-item/review-item.js";
import "./components/seo-meta-tag/seo-meta-tag.js";

0 comments on commit 06a22ae

Please sign in to comment.