-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
115c61d
commit cc69306
Showing
3 changed files
with
60 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
class ImageComponent extends HTMLElement { | ||
constructor() { | ||
super(); | ||
this.attachShadow({ mode: 'open' }); | ||
|
||
this.validateAttributes(); | ||
this.setDefaultAttributes(); | ||
|
||
this.render(); | ||
} | ||
|
||
validateAttributes() { | ||
// Validate required attributes | ||
if (!this.hasAttribute('alt')) { | ||
throw new Error('The "alt" attribute is required.'); | ||
} | ||
|
||
// Validate allowed attributes | ||
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.`); | ||
} | ||
} | ||
} | ||
|
||
setDefaultAttributes() { | ||
if (!this.hasAttribute('width')) { | ||
this.setAttribute('width', '100%'); | ||
} | ||
if (!this.hasAttribute('height')) { | ||
this.setAttribute('height', 'auto'); | ||
} | ||
} | ||
|
||
render() { | ||
const src = this.getAttribute('src'); | ||
const alt = this.getAttribute('alt'); | ||
const width = this.getAttribute('width'); | ||
const height = this.getAttribute('height'); | ||
|
||
this.shadowRoot.innerHTML = ` | ||
<style> | ||
img { | ||
display: block; | ||
max-width: 100%; | ||
height: auto; | ||
} | ||
</style> | ||
<img src="${src}" alt="${alt}" width="${width}" height="${height}"> | ||
`; | ||
} | ||
} | ||
|
||
customElements.define('image-component', ImageComponent); | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters