Coder Social home page Coder Social logo

omgovich / react-colorful Goto Github PK

View Code? Open in Web Editor NEW
3.0K 10.0 96.0 2.72 MB

🎨 A tiny (2,8 KB) color picker component for React and Preact apps

Home Page: https://omgovich.github.io/react-colorful

License: MIT License

JavaScript 38.20% CSS 3.64% TypeScript 58.16%
color-picker color tiny react react-component hooks picker a11y zero-dependency typescript-support

react-colorful's People

Contributors

aitchiss avatar anotherhermit avatar byr-gdp avatar fil0157 avatar jeetiss avatar jjjjjx avatar leoc4e avatar molefrog avatar omgovich avatar remnantkevin avatar royeden avatar rschristian avatar web-padawan avatar xnimorz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-colorful's Issues

Question: escaping "#" from HexColorInput

Hey, final one from me I think πŸ˜‚

I was just wondering about the decision to remove the "#" when setting the HexColorInput's local state. My use case is to avoid confusion for the less tech-savvy when they copy/paste the input. There doesn't appear a way to force prefixing it.

I would think the obvious solution would be to add a boolean prop like "showHex" to toggle it.

Not a deal breaker for me personally, but I wanted to hear you thoughts.

(Sorry for all the problems but none of the contributions, I'll have a pop at some of this if I find some time this week)

Cheers

Thoughts on exposing the common components?

Exposing the base components would give more control when it comes to customization. I also wouldn't have to override react-colorful's CSS classes just to customize the spacing/layout.

Looking at the source, it seems like the compound components are pretty straight forward. Is there a reason to not expose those components?

Add refs

Hello, nice work on the library :)

Looks to me like I can't get a ref to the HexColorInput as things stand. From a cursory investigation you would need to implement forwarding refs .

The reason I would like this, is so I can focus the input by clicking on a separate DOM element. You have a really nice behaviour while staying focused and interacting with the picker, so it would be good to exploit it.

Let me know if I've missed some obvious alternative or if it would be something you'd consider adding.

Thanks!

Typescript error: Create Alpha from RGBA as an Input with type number, not a string while using React JS?

So this is not a react-colorful issue but a question. The discussion forum isn't open so I opened it up as an issue. I am sure as this is a common problem you must've thought about it.

So I am making a Sketch/Figma-like Color picker using this library & am using the <RgbaColorPicker /> component:

<RgbaColorPicker
  className="custom-pointers"
  color={selectedColor.rgba}
  onChange={(rgba: Rgba) =>
    updateBackground({
      transparent: false,
      selectedColor: {
        id: nanoid(),
        rgba,
      },
    })
  }
/>

This method requires color prop which requires Rgba type:

type Rgba = {
	r: number
	g: number
	b: number
	a: number
}

I have an input for alpha like:

<input
  className="text-center w-7 text-blue-gray-500"
  value={selectedColor.rgba.a}
  onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target
    if (value === '' || regex0to1.test(value))
      updateBackground({
        selectedColor: {
          ...selectedColor,
          rgba: {
            ...selectedColor.rgba,
            a: value,
          },
        },
      })
  }}
/>

Which works by taking all inputs required for alpha from 0.0 to 1.0 including all decimal places in between.

However, this also makes type of a equal to string which I cannot have as I need its type to be a number because that's the requirement of the color prop in <RgbaColorPicker />.

If I try to do a: Number(value) in the alpha input then I cannot enter an empty string or a decimal point in the input as Number('') is equal to 0 & Number(1.) is equal to 1.

So how do I solve it whilst keeping the type of alpha as a number?

Codesandbox β†’ https://codesandbox.io/s/react-colorful-sketch-picker-ouz5t

[Error] Unable to preventDefault inside passive event listener invocation.

Hi, my browser's console keeps throwing this error, when all I have done is embedded <HexColorPicker color={color} onChange={setColor} /> in a functional component.

I tried setting touch-action: none to all parent divs up to body but the error is still being thrown. That being said, the color picker works fine on desktop and mobile, it's just that I'm not sure why this error is being thrown.

Any suggestions on remedying this?

This is a great library by the way! I avoided starting off with react-color because it seems outdated and has many open issues, while this is far more recent and modernized. Thank you for this.

SyntaxError: Cannot use import statement outside a module

I get the following issue when trying to use react-colorful in my NextJS app:

SyntaxError: Cannot use import statement outside a module
 module.exports = require("react-colorful");
import { HexColorPicker } from "react-colorful";
<HexColorPicker color={color} onChange={setColor} />

Anyone know why?

Internet explorer support

Currently examples are not working on internet explorer 11.
Are there any plans for supporting it?

Widget coming up as blank

Using this with styled components, and it's coming up with a red background and no features accessible.

EDIT: nevermind! Wasn't importing that css required.

Include basic color conversion algorithms

I think we need some basic color conversion algorithm to ensure better performance. Right now using a third-party library like tinycolor2 causes app freeze.

Usecase:
I want to allow the user to either choose a hex color or rgba color. We are storing hex code at the backend so whenever the user chooses a rgba color we need to convert that to a hex8 string. but since the RgbaColorPicker accepts RgbColor type we need to convert the color to that everytime the color changes. When you constantly do this in RgbaColorPicker it crashes the app.

Ways to reproduce:
Open the code sandbox link: https://codesandbox.io/s/react-colorful-wlm00
Try changing the color continuously and quickly, it will work fine in case of rgb.
Now move the alpha slider and try the same again, after some time it freezes.

ModuleNotFoundError: Module not found: Error: Can't resolve 'react-colorful' in '/vercel/path0/...'

package.json has an exports field that includes: "import": "./dist/index.mjs" However, the .mjs extension is not specified in the files field in package.json:

"files": [ "dist/*.{js,ts,map}", ... ],

...which causes the .mjs file to not be included in npm dist. This causes a Webpack ModuleNotFoundError on Linux builds when using ES6 import like import { HexColorPicker } from 'react-colorful' (although Window builds still work for some reason).

Picker does not take focus on click

Hi there, love this project and just wanted to report on a bug.

Expected behaviour: when clicking any of the picker elements (saturation, hue, alpha) they should take focus just like they do when navigating with the tab key.

Actual behaviour: clicking on the saturation, hue, alpha areas does not take focus. That means the UI does not show the same focussed state as when navigating through them via tab. This also means that they don't take away focus from other input elements.

This also happens when clicking between elements of the picker. If saturation is focused, and I adjust hue, then saturation remains focussed.

This is version 5.2.2

Kapture.2021-06-02.at.13.28.43.mp4

How to check if handleChange is complete?

How can I check if handleChange has completed? I get that it uses hooks so it updates in real-time, but is there a way to check if the handleChange has completed?

My goal is to get check if once the user has choosen his colour, I'm executing another function.

I'm using this package with Three.js within a React.js app to change the color of the background scene.

Here is some code I'm using including what I tried:

const MyComponent = (background) => {
  const [currBackground, setCurrBackground] = useState(background)  
  const threeCanvas = useRef()

  useEffect(() => {
    // some three.js code
  }, [])

  const handleBackgroundChange = useCallback((value) => {
    setCurrBackground(value)
    scene.background = new THREE.Color(value)
    // other three.js code
  }, [scene])

  return (
    <>
      <div ref={threeCanvas} />
      <HexColorPicker
        color={currBackground}
        onChange={handleBackgroundChange}
       />
    </>
  )
}

Many thanks in advance, this package is amazing.

Gradients example?

I would love to add Gradients to my app but I'm not sure how to do that πŸ€”

Is this possible with react-colorful? If so, any examples?

Should the package distribution contain minified sources?

I was surprised to see that the unpacked size of the package is 443 kB. Turns out it has minified sources with source maps, that weight ~16kb each:

β”œβ”€β”€ [ 79K]  dist
β”‚Β Β  β”œβ”€β”€ [1015]  index.css
β”‚Β Β  β”œβ”€β”€ [3.2K]  index.esmodule.js
β”‚Β Β  β”œβ”€β”€ [ 16K]  index.esmodule.js.map
β”‚Β Β  β”œβ”€β”€ [3.6K]  index.js
β”‚Β Β  β”œβ”€β”€ [ 16K]  index.js.map
β”‚Β Β  β”œβ”€β”€ [3.5K]  index.module.js
β”‚Β Β  β”œβ”€β”€ [ 16K]  index.module.js.map
β”‚Β Β  β”œβ”€β”€ [3.8K]  index.umd.js
β”‚Β Β  └── [ 16K]  index.umd.js.map

I wonder if the distribution should contain minified sources at all. Thoughts?

Top left border artifact

Hi there, I've noticed there's an artifact at the top left border of the picker.

Screenshot from 2021-05-31 11-41-16

Picking a contrasting color with the backgrond makes it easier to see. If I remove the following style the artifact goes away, but other elements shift a bit.

border-bottom: 12px solid #000;

Do you see a better way of fixing the artifact?

Really like this component πŸ’–

bug: capturing mouse

it looks like react-colorful does not capture, that easily breaks controls which depend on drag, simply by moving the mouse out of its region or the window. i've tried to use this lib (for instance in the use-tweaks library) but it constantly breaks and feels unstable bc of this.

i have a small repro here: https://codesandbox.io/s/floating-shoe-forked-qxjoj

if you click a segment of the shoe it shows the color picker, drag a color outside the window and let go (mouse-up), if you come in again the picker is still in drag mode. it also happens sometimes if you let go at the edge of the picker.

capturing will solve all these issues, would you add it?

Feature: Better support SSR

I'm writing this PR right now, just thought I'd explain it a bit more in depth first in an issue. I find that helps separate comments about the feature from comments about the specific implementation.

temp

This comment left on your most recent post got me thinking about SSR, and a way we can improve it.

Firstly, we can provide a hook to the user to allow them to access the CSS string themselves. They can just inject it in the head of their doc if using SSR, for example. While this would be duplicated on load, that wouldn't be an issue.

But, to get around that, we could add an ID to the style element. So useStyleSheet() looks for a <style id="__react-colorful">, and only if it doesn't find one does it inject a new tag into the head. This way you not only support SSR, but make sure it's efficiently supported at the same time.

Should be quite slick and cover the use cases.

Next.js support

Hey, @rschristian @molefrog!
Seems like we might have issues with Next.js, but I didn't get the reasons yet.
Created an empty next.js project and added the color picker to it:

image

image

Do you have any ideas?

Can you add onRelease event?

Hello,
onChange is nice, but in this case I am creating color palette on every color change while the color pointer is being dragged. Doesn't look smooth being dragged. If I can trigger to create palette only on release that would be nice.

Thanks

This is not an issue - Is a thank you 😊

I'm using this package inside as a plugin for Strapi and was really faster the change i need to build a custom component to change from hexadecimal to rgba but is really clean and also using tinycolor2, really really thank you for this

Added styles do not conform to any CSP rules.

Hey I am using this cool component in my react project, but I am having an issue with the Content Security Policy.

Although I am doing client side rendering with makeStyles from material-ui, I use the nonce because I am building an app with electron and want to secure it as much as possible.

Right now I am using a nonce to only allow self styles and styles with a specific nonce. The useStyles hook created by makeStyles does add the nonce to the style because it uses JSS

The problem is that styles in react-colorful are applied to the html without JSS so no nonce is added.

Possibly related topics are: #109 #110

Any idea on how to solve the problem?

css modules

Hi,

I am not using the css style imports and this makes it hard to match the generated class names, as they are set up with css modules.

Here is my uses case, you will notice that I ended up using some strange selectors (div[role=slider] and a few other places) to accommodate that some class names are not possible without using css modules.

https://github.com/ccontrols/component-controls/blob/9f68190dbd39f50a3bb522646262410b8bd7e37e/ui/editors/src/ColorEditor/ColorEditor.tsx#L83

I would suggest to just hard-code the class names prefixed with 'react-colorful' so they stay fixed

Types: React-Colorful will not work with the TypeScript Preact-CLI template

If a user were to create a new TypeScript Preact project using the Preact CLI (npx preact-cli create typescript preact-test) and use this library following the instructions, they will run into the following error:

TS2786: 'ColorPicker' cannot be used as a JSX component.
  Its return type 'JSX.Element' is not a valid JSX element.
    Type 'Element' is missing the following properties from type 'Element': nodeName, attributes, children

Not entirely sure where it's coming from. I have a personal project that I was testing with while doing the TS rewrite and it still runs without any issues. Adding react-colorful to the base Preact template seems to be an issue though. Odd.

Likely some issue with the typing differences between React & Preact but it might be possible to resolve by altering our typings slightly.

Very nice but I need this for a vanilla project

Any chance you might consider making this also as just library-independant code?

This wonderful piece of program is wasted just on React (I love React, but does a ton of frameworkless projects which can benefit from it)

hsla editor lockup on quick update

Hi, Thanks very much for the component, react-color was indeed very heavy.

I have integrated it already and would be great if you can list it as one of the projects using react-colorful: https://component-controls.com/api/editors-coloreditor--overview

I seem to have an issue with fast updating of the control values with the hsla (and rgba) color picker (the hex color picker seems fine), any ideas what could be going on?

Here is a video, from the page linked above and the control locking up on fast moving around:

react-colorful

Also I resorted to converting rgba/hsla values since the HSLAStringColorPicker and rgba equivalent are not rounding the values, so I could end up with lets say 39.999999999 a one of the values. Is there an option for rounding the values (in my case I need to round to 0 decimals for the colr values and 2 decimals for the alpha value)

Too many type definition files

Since we migrated the entire codebase to TS, each dist folder contains a lot of .d.ts files.

The total number of them is more than 100.

In my opinion, it would be great to find some way to have one primary type definition file in each folder.

Unable to start the development server (Parcel issue)

I get a Parcel error when trying to run the development server in a newly cloned repo. It's related to the recent regression in Parcel parcel-bundler/parcel#5943

The proposed solution so far is to freeze the Parcel version to 1.12.3 via either Yarn resolutions or npm-force-resolutions for NPM users (see parcel-bundler/parcel#5943 (comment)).

We could probably solve this by changing the Parcel version req from ^1.12.4 to 1.12.3 or by pushing a package-lock.json.

Cannot import CSS file

Version: ^4
Bundler: webpack@^5.4.0
Loader: css-loader@^4.3.0

Hello :)
I use the distributed CSS file and import it like it is explained in the example but webpack cannot find the file. I've pinpointed the problem to the recent package.json changes. The exports field misses the CSS file and adding it fixed my compilation error.

"exports": {
    ".": {
      "browser": "./dist/index.module.js",
      "umd": "./dist/index.umd.js",
      "import": "./dist/index.module.js",
      "require": "./dist/index.js"
    },
    "./dist/index.css": "./dist/index.css"
}

Implement accessibility based on ARIA practices

Hello πŸ‘‹
I've been thinking about making the color picker accessible, and I would like to discuss the related changes.

It looks like for Hue and Alpha sliders we can follow WAI-ARIA authoring practices. See also the example.
I'm not an expert, but presumably the same approach should work for Saturation as well.

There are following open questions that come to my mind:

  1. Implementing this would require to figure out what the proper step value per arrow key press should be.
    Should we make this step configurable? Maybe not as pubic property, but a protected one.

  2. Note that Page Up and Page Down allow to change value by multiple steps (10 steps in the example).
    Should this be configurable as well?

  3. Proper support for screen reader announcements would require to provide a way for setting aria-label on the pointer elements. It could be done either with individual props or by passing an object with the following structure:

i18n: {
  alpha: 'Alpha',
  hue: 'Hue',
  saturation: 'Saturation'
}

I'm going to prototype some of these changes in vanilla-colorful so I will create an issue there as well.

#NaNNaNNaN as Hex string

I'm getting back #NaNNaNNaN in onChange when I start with color='' and move the bottom slider without changing the value of the top box. Below is a simple component that demonstrates the issue.

import React, { useState } from 'react';
import { HexColorPicker } from 'react-colorful';

const ColorPicker = () => {
  const [color, setColor] = useState('');
  return (
    <>
      <HexColorPicker color={color} onChange={setColor} />
      {color}
    </>
  );
};

export default ColorPicker;

Hue slider vertical orientation

For a HexColorPicker, is there a way to put the hue slider on the right or left of the saturation, as opposed to above/below?

This is the default behavior with it below:

image

Is it possible to make style changes to orient the slider vertically, or would that inevitably fail due to how the slider logic works?

Overriding styles in Chakra UI

Hi @omgovich, I'm working on a project where your tool has made a world of difference. Sincere thanks!!
However, when I'm trying to adjust the styles by setting up a separate CSS file, the changes are failing as I'm using Chakra UI which resets CSS by default. Is there any way I can overcome it?

CSS-in-JS version?

Hey guys! @molefrog @rschristian @jeetiss

A lot of projects use CSS-in-JS and don't have any CSS-loader configured.
That makes react-colorful adding way harder for them.

Seems to me that it's hard to compete with react-color (that uses emotion) while our installation requires additional actions.

So I thought what if we find some way to avoid CSS-loading and will inject styles to a webpage?

Still don't know how to do it better. Thoughts?

sidebar

Hello, is it possible to have the "react-colorful__hue" bar on the side of the color selector ? I tried this but as you see it's not working very well.
image

Support for hue bar vertical positioning?

Greetings! First of all I just wanna say thanks for creating this cool tiny library. This is exactly what's needed on the project I'm working on currently.

I only have one "issue". Designs for the color picker in the app I'm working on were designed without using any library as reference and in the design the hue bar is vertical, but react-colorful has it by default in horizontal position.

I'm wondering if it's possible to achieve this layout? This is react-colorful btw, just with some different CSS.
image

Currently, no matter what I do and what positioning technique I use, the hue pointer can only slide left-right (you can see it actually overflows outside the hue bar).

Is this possible to achieve with the current library or is it something that would need to be integrated? Would you be willing to accept a PR to allow for something like this or you think it is unnecessary and would add bloat or unnecessary options?

I'm just trying to look at my options before reaching for another library or trying to convince designers to use the horizontal hue layout πŸ˜„

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.