web-padawan / vanilla-colorful

A tiny color picker custom element for modern web apps (2.7 KB) 🎨
https://web-padawan.github.io/vanilla-colorful/
MIT License
798 stars 29 forks source link

Check registered customElements before register it #107

Open mnogono opened 3 months ago

mnogono commented 3 months ago

I suggest to add follow code snipped customElements.get("xxx") || customElements.define("xxx") This allow to prevent issue Failed to execute 'define' on 'CustomElementRegistry': the name "hsva-color-picker" has already been used with this registry

SalahAdDin commented 2 months ago

Yeah, we have the same issue, I would open a new related issue but it is better to improve this one.

We have the following component on React:

import React, { useState } from 'react@16.14.0';
import 'react-dom@16.14.0';
import nativeEvents from 'jsx-native-events';
import 'vanilla-colorful';

const styles = `
output {
  display: block;
  margin-top: 10px;
  font-size: 1.25rem;
  text-align: center;
}`;

export default function ColorExample() {
  const [color, setColor] = useState('#1e88e5');

  const handleColorChanged = (event: CustomEvent<{ value: string }>) => {
    setColor(event.detail.value);
  };

  return (
    <div>
      <style>{styles}</style>
      <hex-color-picker
        color={color}
        onEventColorChanged={handleColorChanged}
      ></hex-color-picker>
      <output>{color}</output>
    </div>
  );
}

From time to time we get the error: CustomElementRegistry.define: 'hex-color-picker' has already been defined as a custom element.

To fix it we opted to use @lit/react:

import React, { useState } from 'react@16.14.0';
import 'react-dom@16.14.0';
import 'vanilla-colorful';
import { HexColorPicker } from "vanilla-colorful/hex-color-picker.js";

const styles = `
output {
  display: block;
  margin-top: 10px;
  font-size: 1.25rem;
  text-align: center;
}`;

const ColorPicker = createComponent({
  react: React,
  tagName: "hex-color-picker",
  elementClass: HexColorPicker,
  events: {
    onEventColorChanged: "color-changed" as EventName<
      CustomEvent<{ value: string }>
    >,
  },
});

export default function ColorExample() {
  const [color, setColor] = useState('#1e88e5');

  const handleColorChanged = (event: CustomEvent<{ value: string }>) => {
    setColor(event.detail.value);
  };

  return (
    <div>
      <style>{styles}</style>
      <ColorPicker
              color={color}
              onEventColorChanged={(event) => setColor(event.detail.value)}
            />
      <output>{color}</output>
    </div>
  );
}

But, again, but less common than before, from time to time we have the same issue!

@mnogono Could you open a PR with the fix?