Skip to content

Instantly share code, notes, and snippets.

@schalkventer
Last active January 7, 2022 13:21
Show Gist options
  • Save schalkventer/3115600ad9fce2925b765af72984428d to your computer and use it in GitHub Desktop.
Save schalkventer/3115600ad9fce2925b765af72984428d to your computer and use it in GitHub Desktop.

Component Helpers

export const html = (staticStrings = [], ...dynamic) => {
const newStringsArray = (dynamic || []).map((singleDynamic, index) => {
return `${staticStrings[index] || ""}${singleDynamic || ""}`;
});
const lastIndexStatic = staticStrings.length - 1;
return `${newStringsArray.join("")}${staticStrings[lastIndexStatic]}`;
};
export const createList = (item) => (array) => array.map(item).join("");
export const createComponent = (props) => {
const { render, options, handlers = {}, createData } = props;
const { mode, name } = options;
class Component extends HTMLElement {
data = createData ? createData() : {};
shadow = this.attachShadow({ mode: mode || "closed" });
renderCount = 0
constructor() {
super();
this.updateWrapper = this.updateWrapper.bind(this)
const handlerKeys = Object.keys(handlers);
handlerKeys.forEach((key) => {
this[`${key}Handler`] = (event) => {
handlers[key](event, this.updateWrapper);
};
this.shadow.addEventListener(key, this[`${key}Handler`]);
});
}
updateWrapper(newData) {
this.renderCount += 1;
if (this.renderHandler) {
this.renderHandler(
new CustomEvent("render", { detail: { renderCount: this.renderCount } }),
this.updateWrapper
);
}
if (newData) {
const currentData = { ...this.data }
this.data = newData === null ? this.data : { ...currentData, ...newData };
}
this.shadow.innerHTML = render(this.data, this.phase);
}
connectedCallback() {
this.updateWrapper(null);
}
disconnectedCallback() {
handleKeys((key) => {
this.shadow.removeEventListener(key, handle[key]);
});
}
}
window.customElements.define(name, Component);
};
export default createComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment