Giter VIP home page Giter VIP logo

react-linear-gradient-picker's Introduction

react-linear-gradient-picker

This package takes any color picker for you choice, And wraps it as a gradient picker. This plays well with the package angle picker, which allows your users to play with the gradient angle.

What you need to know before installing?

  • This package is using hooks, which means you need to use React 16.8 or higher.

Installation

npm i react-linear-gradient-picker

Gradient Picker Usage

gradient_preview

import React, { useState } from 'react';
import { Panel as ColorPicker } from 'rc-color-picker';
import { GradientPicker } from 'react-linear-gradient-picker';
import 'react-linear-gradient-picker/dist/index.css';

const WrappedColorPicker = ({ onSelect, ...rest }) => (
	<ColorPicker {...rest} onChange={c => {
		onSelect(c.color, c.alpha / 100);
	}}/>
);

const App = () => {
    const [palette, setPalette] = useState([
        { offset: '0.00', color: 'rgb(238, 241, 11)' },
        { offset: '0.49', color: 'rgb(215, 128, 37)' },
        { offset: '1.00', color: 'rgb(126, 32, 207)' }
    ]);

    return (
        <GradientPicker {...{
            width: 320,
            paletteHeight: 32,
            palette,
            onPaletteChange: setPalette
        }}>
            <WrappedColorPicker/>
        </GradientPicker>
    );
};

Accepted props

Name Type Default Value Required? Description
palette PaletteColor[] undefined Yes The gradient pickers color palette, Each palette color struct is described below
onPaletteChange Function undefined Yes The function to trigger upon palette change (Can be either from stop drag or color select).
paletteHeight Number 32 No The stops palette display area height
width Number 400 No Determines the width of the gradient picker
stopRemovalDrop Number 50 No Sets the Y stop drop removal offset, If the user will drag the color stop further than specified, Color will be removed
maxStops Number 5 No The max gradient picker palette length can have
minStops Number 2 No The min gradient picker palette length can have

|> Palette Color

Name Type Default Value Required? Description
color String `` Yes The stop color, can be either hex of rgb format.
offset Number `` Yes The stop color offset in percent.
opacity Number 1 No The stop color opacity.
active Boolean `` No Rather the current color is active (selected) or not.

Gradient Picker Popover Usage

gradient_popover_preview

import React, { useState } from 'react';
import { SketchPicker } from 'react-color';
import { GradientPickerPopover } from 'react-linear-gradient-picker';
import 'react-linear-gradient-picker/dist/index.css';

const rgbToRgba = (rgb, a = 1) => rgb
	.replace('rgb(', 'rgba(')
	.replace(')', `, ${a})`)

const WrapperPropTypes = {
	onSelect: PropTypes.func
};

const WrappedSketchPicker = ({ onSelect, ...rest }) => {
	return (
		<SketchPicker {...rest}
					  color={rgbToRgba(rest.color, rest.opacity)}
					  onChange={c => {
						  const { r, g, b, a } = c.rgb;
						  onSelect(`rgb(${r}, ${g}, ${b})`, a);
					  }}/>
	);
}

const initialPallet = [
	{ offset: '0.00', color: 'rgb(238, 241, 11)' },
	{ offset: '1.00', color: 'rgb(126, 32, 207)' }
];

const App = () => {
	const [open, setOpen] = useState(false);
	const [angle, setAngle] = useState(90);
	const [palette, setPalette] = useState(initialPallet);

	return (
		<GradientPickerPopover {...{
			open,
			setOpen,
			angle,
			setAngle,
			width: 220,
			maxStops: 3,
			paletteHeight: 32,
			palette,
			onPaletteChange: setPalette
		}}>
			<WrappedSketchPicker/>
		</GradientPickerPopover>
	);
};

export default App;

Accepted props

Name Type Default Value Required? Description
trigger React Component defaultTrigger No The popover trigger component, Will use default implementation if empty.
open Boolean false Yes Controls the popover open state
setOpen Function undefined Yes The setOpen method to be called upon open changes
showGradientTypePicker Boolean true No Rather to show the gradientType picker control.
showAnglePicker Boolean true No Rather to show the anglePicker picker control.
angle Number undefined No The angle picker angle value
setAngle Function undefined No Then angle picker setAngle method to be called upon angle changes
  • This component accepts all of <GradientPicker/> pros.

Angle Picker Usage

gradient_preview

import React, { useState } from 'react';
import { AnglePicker } from 'react-linear-gradient-picker';
import 'react-linear-gradient-picker/dist/index.css';

const App = () => {
    const [angle, setAngle] = useState(25);

    return (
        <AnglePicker angle={angle} setAngle={setAngle}/>
    );
};

Accepted props

Name Type Default Value Required? Description
angle Number undefined Yes The controlled angle.
setAngle Function undefined Yes The set angle method to be trigger after an angle was changes.
size Number 48 No Determines the size of the angle picker
snap Number 5 No Determines the angle change snapping, Can be removed with setting as 0

react-linear-gradient-picker's People

Contributors

dungnt12 avatar jito avatar odeadglaz 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

Watchers

 avatar  avatar

react-linear-gradient-picker's Issues

Preview with single stop

Hey @odedglas !
First of all, the new version is awesome! Really clean, and the popover is really great! You did a great job !

My last use case is that I allow users to select either a gradient or ... a single color (as a gradient with only one stop). I'd like the preview to be able to render it as a plain color.
I think the correct repository would be linear-gradient-parser for this and just update the asBackground function to check if there is only one stop, and if so, return just the color.

Delete color

Hello, thanks for the good work with this :) But i found a bug i think.

When adding a new color and its still selected and choose to delete that color, i get this error:

src/components/GradientPicker/index.js:33
  30 | 
  31 | const getPaletteColor = (palette, id) => {
  32 | 	const color = palette.find(color => color.id === id);
> 33 | 	return { ...color, offset: Number(color.offset) };
  34 | };
  35 | 
  36 | const GradientPicker = ({
src/components/GradientPicker/index.js:107
  104 | 	handlePaletteChange(updatedPalette);
  105 | };
  106 | 
> 107 | const colorPicker = () => {
      | ^  108 | 	const { color, opacity } = getPaletteColor(palette, activeColorId);
  109 | 
  110 | 	const props = {
src/components/GradientPicker/index.js:148
  145 | 				onDeleteColor={handleColorDelete}
  146 | 				onDragStart={onStopDragStart}
  147 | 			/>
> 148 | 			{colorPicker()}
  149 | 		</div>
  150 | 	);

Using state and manipulating it with:

const remove = (id) => {
	const updatedPalette = palette.filter((color) => color.id !== id);
	onPaletteChange(updatedPalette); // onPaletteChange is setPalette
};

jsx:

<ul>
	{palette.map((item) => (
		<li>
			{item.id} {item.color}{' '}
			{item.id !== 1 && item.id !== 2 && (
				<div onClick={() => remove(item.id)}>Delete</div>
			)}
		</li>
	))}
</ul>

React 17 and TypeScript types support?

Hello, React 17 is out for a while, do you have plans to update it to React 17 or perhaps add React as peer dependency?

What about TypeScript support? My project complains that it didn't find types for this library:

Could not find a declaration file for module 'react-linear-gradient-picker'.```

Fails to load with Next.js (but there is a workaround)

The issue

This component fails to load when used in Next.js.

This library (or I think a dependency) is making use of DOMParser during the initial page-load which fails because Next.js does static pre-rendering/SSR for everything and DOMParser is a browser API and therefore not available during pre-rendering.

The stack trace

ReferenceError: DOMParser is not defined

Module.e.m.t
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:8991)
e
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:12235)
<unknown>
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:12139)
Object.<anonymous>
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:12290)
n
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:403)
Module.<anonymous>
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:20132)
n
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:403)
<unknown>
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:1202)
<unknown>
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:1212)
<unknown>
file:///Users/david/Documents/slantt-saas/slantt/node_modules/react-linear-gradient-picker/dist/index.js (1:81)

The workaround

The solution is to import the module dynamically:

import dynamic from 'next/dynamic'
const GradientPicker = dynamic(() => import('react-linear-gradient-picker').then(m => m.GradientPicker), { ssr: false });

// use GradientPicker like normal

A better fix?

I am thinking it is probably somehow possible to avoid invoking DOMParser during page-load which would avoid the issue of it not being available during pre-rendering. Making this component easier to integrate with Next.js is a worthwhile thing IMO :)

onPaletteChange is not triggered when clicking on a stops

when i'm clicking on the stops it's not triggering the onPaletteChange.
(when i'm moving them it works)
is there another why to do something when the user click on the stops?

it seems like in the doc that it should trigger onPaletteChange
image

How to make the color slider change on simple click?

It seems now that the color is changing when clicking and dragging, but not on simple click ( which seems to work with the "normal" color picker ) on the small color bar ( not the big square which is working fine ).

Am I doing something wrong? If not, how to make this clickable AND draggable?
Thanks in advance.

Getting the Currently Selected Stop

Is there a way to get the currently selected stop to be used when highlighting etc? Like an id indicating which pallet array index is selected. Thanks in advance.

Import problem

To import, I have to do:

import Gradient from "react-linear-gradient-picker";  
const {GradientPicker, AnglePicker} = Gradient;

because

import {GradientPicker, AnglePicker} from "react-linear-gradient-picker";

doesn't work.

Add gradientType for prop

I need to load radial-gradient value of HtmlElement, and then prop the picker.

const GRADIENT_TYPES = {
	LINEAR: 'linear',
	RADIAL: 'radial'
};

AnglePicker dragging not working

Hi !

I added AnglePicker to my custom color picker (using react-color) and I got this error :
image

Code is minified so I cannot get clearer view than this. I'm using require to import and not es6 import because my project is in typescript.

I can manually set the value and the knob is turning, but direct interaction will fire this error. Any ideas ? Thanks !

Question

Is there a way to call the onSelect function or select a colorstop from outside the gradient picker component? and not by clicking on the stop on the picker?
i need to select a colorstop from outside the palette, indirectly and change its CSS. Can anyone please help?

Requires node global polyfill, not compatible with Vite

When trying to use this library from within a Vite application, you get the error

Uncaught ReferenceError: global is not defined

This seems to be the same as this error against another library:

global is a node builtin which libraries should not depend on

vitejs/vite#5912

This seems to stem from the usage of webpack to produce the dist version.

To recreate:

  1. yarn create vite and select react-ts
  2. yarn add react-linear-gradient-picker
  3. implement example code from react-linear-gradient-picker readme
  4. yarn dev and open localhost:3000
  5. See error in browser console

console.log in v2.0.0

There is a console.log("Getting backgrund;") [sic] in the latest version 2.0.0. It prints whenever I click on an instance of <GradientPickerPopover /> and a simple search led me to the dist version of this package: ./node_modules/react-linear-gradient-picker/dist/index.js, which does not exist in the repo.

Please remove this console.log().

onSelect is missing

Hi, I tried writing the wrappedsketchpicker in the same way as mentioned here, I am using VSCode for my project , on writing

<WrappedSketchPicker {...{
width: 200,
disableAlpha: true
}} />

it gives the following error

Property 'onSelect' is missing in type '{}' but required in type '{ [x: string]: any; onSelect: any; }'.ts(2741)

is there something additional that i need to do?
even on simply copy-pasting the code , it isnt working, any help?

linear-gradient/palatte helpers

Can asBackground be exported from the package? Or could any other helper methods to convert linear-gradient css rules to palattes be exported?

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.