Skip to content

Instantly share code, notes, and snippets.

@lekoala
Last active April 24, 2023 11:24
Show Gist options
  • Save lekoala/233b0c6246170716c52dbfab342caf22 to your computer and use it in GitHub Desktop.
Save lekoala/233b0c6246170716c52dbfab342caf22 to your computer and use it in GitHub Desktop.
import styles from "./node_modules/@melloware/coloris/dist/coloris.min.css";
import Coloris from "./node_modules/@melloware/coloris/dist/esm/coloris.js";
// Example
/* <label for="primary_color-input" class="form-label">Primary color</label>
<coloris-input data-config='{"swatches": ["#fff", "#000"] }'>
<input type="text" class="form-control" id="primary_color-input" name="primary_color">
</coloris-input> */
const themeMode = document.documentElement.dataset.bsTheme ? document.documentElement.dataset.bsTheme : "auto";
const rtl = window.getComputedStyle(document.documentElement).direction === "rtl";
// Inject styles + init once
if (!document.head.querySelector("#coloris-style")) {
const style = document.createElement("style");
style.id = "coloris-style";
style.textContent = `${styles}
.clr-field {display: block;width: 4em;border-radius: var(--bs-border-radius, 0.25rem);overflow: hidden;}
.clr-field input {cursor: pointer;}
.clr-field button {width:100%;}`;
document.head.append(style);
// Only once! after, use .set
Coloris.init();
}
let counter = 0;
class ColorisInput extends HTMLElement {
connectedCallback() {
counter++;
let c = {};
const dataConfig = this.dataset.config;
if (dataConfig) {
c = Object.assign(c, JSON.parse(dataConfig));
}
const input = this.getInput();
const id = input.getAttribute("id") || `coloris-picker-${counter}`;
input.setAttribute("id", id);
input.setAttribute("autocomplete", "off");
// el, wrap, rtl, inline, defaultColor and a11y can only be set globally
Coloris.set({
el: `#${id}`,
rtl: rtl,
themeMode: themeMode,
});
// parent, theme, themeMode, margin, format, formatToggle, focusInput, selectInput, swatchesOnly, alpha, forceAlpha, swatches
Coloris.setInstance(`#${id}`, c);
}
disconnectedCallback() {
const id = this.getInput().getAttribute("id");
Coloris.removeInstance(`#${id}`);
}
/**
* @returns {HTMLInputElement}
*/
getInput() {
return this.querySelector("input");
}
}
customElements.define("coloris-input", ColorisInput);
export default ColorisInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment