Skip to content

Instantly share code, notes, and snippets.

@AdamManuel-dev
Last active April 28, 2023 21:35
Show Gist options
  • Save AdamManuel-dev/18e13d4dd6d8f2d417fd839c3144926f to your computer and use it in GitHub Desktop.
Save AdamManuel-dev/18e13d4dd6d8f2d417fd839c3144926f to your computer and use it in GitHub Desktop.
This is a wrapper for turning a Svelte Component built as an entry point into a Web Component using the Custom Element v1 Spec
import Gallery from './COA/COAGallery.svelte';
/**
* C.O.A. Gallery Custom Element v1 Component Class
*/
class COAGallery extends HTMLElement {
/**
* This defines the attributes to watch in the custom element to trigger the `attributeChangedCallback` method
*/
static get observedAttributes() {
return ['example'];
}
/**
* @see [https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements](Why the args?)
* @param {...any} args
*/
constructor(...args) {
super(...args);
}
/**
* Grab props from the elements attributes to pass to the renderer
*/
connectedCallback() {
const example = this.getAttribute('example');
this.svelte = new Gallery({
target: this,
props: {
example,
},
});
}
// Invoked each time the custom element is disconnected from the document's DOM.
disconnectedCallback() {
// TODO: Implement onDestory hook
}
// Invoked each time the custom element is moved to a new document.
adoptedCallback() {
// DEBUG: Not sure the use-case for this hook
}
/**
* Invoked each time one of the custom element's attributes is added,
* removed, or changed. Which attributes to notice change for is specified
* in a static get observedAttributes method
* @param {*} attrName Changed Attributes Name
* @param {*} oldVal The older value
* @param {*} newVal The newer value
*/
attributeChangedCallback(attrName, oldVal, newVal) {
// Previous State
const prev = this.svelte.$$.props;
// Check if previous states still match
if (prev[attrName] !== oldVal)
throw new Error('Internal and External Prop Mismatch');
// Merge previous prop and attribute value change
const newProp = {
...prev,
[String(attrName)]: newVal,
};
// Set svelte components state to the internal prop value
this.svelte.$$set(newProp);
}
}
// Alamo Botanicals COA Gallery
customElements.define('ab-coa-gallery', COAGallery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment