Code Monkey home page Code Monkey logo

ranger's Introduction

ranger's People

Contributors

allcontributors[bot] avatar cassiozen avatar dependabot[bot] avatar etimberg avatar jb1905 avatar lachlancollins avatar leojuriolli7 avatar rkulinski avatar romeopeter avatar softwarebyze avatar tannerlinsley 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

ranger's Issues

Add onHandleClick prop

I'd like to be able to change the color of a handle when it has been clicked. Here is my use case:

I have configured ReactRanger with one handle. To the left of the handle the track is colored red to indicate "bad" values and to the right of the handle the track is colored green to indicate "good" values. I want to toggle the handle color between red and green each time the handle is clicked. This allows the user to indicate if the handle value itself should represent "bad" or "good".

Thanks.

Support moving the segment.

Excellent library! Really easy to use. I starred it and will watch closely.
I can see you're working on the new version, I didn't check it out yet, I just used the latest from npm. So if you already want to add that feature, great!
It would be awesome if you can support segment moving. I forked your lib locally and prototyped the moving (but only assuming there are 2 handles). As you will see, I forked the master, not the beta, that's why I didn't create PR.

My prototype assumes there are 2 handles, but it can be easily extended, to support moving segments between any values (and only moving the ones that have handles on each end).
Let me know if that is something you would like to support. If so, I can spend some free time working on the beta version PR, unless you want to work on this yourself.
For now, I will use my fork of your lib, and include your license message.
Here's the video, and below code that I used.

Screen.Recording.2023-01-11.at.11.44.47.mov

In short, I added this event on segment press:

const handleSegmentPress = React.useCallback(
		(e) => {
			const clientX = e.type === 'touchmove' ? e.changedTouches[0].clientX : e.clientX;

			const onDrag = e => handleSegmentDrag(e, clientX);
			const handleRelease = e => {
				const {
					tempValues,
					values,
					onChange = () => {},
				} = getLatest();

				document.removeEventListener('mousemove', onDrag);
				document.removeEventListener('touchmove', onDrag);
				document.removeEventListener('mouseup', handleRelease);
				document.removeEventListener('touchend', handleRelease);
				const sortedValues = sortNumList(tempValues || values);
				onChange(sortedValues);
				onDrag(sortedValues);
				setTempValues();
			};

			document.addEventListener('mousemove', onDrag);
			document.addEventListener('touchmove', onDrag);
			document.addEventListener('mouseup', handleRelease);
			document.addEventListener('touchend', handleRelease);
		},
		[getLatest, handleSegmentDrag]
	);

and this is handleSegmentDrag:

const handleSegmentDrag = React.useCallback(
		(e, initialX) => {
			const clientX = e.type === 'touchmove' ? e.changedTouches[0].clientX : e.clientX;
			const initial = getValueForClientX(initialX);
			const newValue = getValueForClientX(clientX);
			const diff = newValue - initial;
			if (diff) {
				let actualDiff = 0;
				if (diff > 0) {
					const last = values[values.length - 1];
					const newRoundedLastValue = roundToStep(last + diff);

					actualDiff = newRoundedLastValue - last;
					
				} else {
					const first = values[0];
					const newRoundedFirstValue = roundToStep(first + diff);
					actualDiff = newRoundedFirstValue - first;
				}

				if (actualDiff) {
					setTempValues(values.map(v => v += actualDiff));
				}
			}
			
		},
		[getValueForClientX, roundToStep, values]
	);

Encountered two children with the same key, `0`

While I only have 1 handle there is an internal issue with this package which says:

react_devtools_backend.js:2574 Warning: Encountered two children with the same key, 0. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted β€” the behavior is unsupported and could change in a future version.

This happens with the most barebones version

  const [values, setValues] = React.useState([10]);

  const { getTrackProps, handles } = useRanger({
    min: 0,
    max: 100,
    stepSize: 1,
    values,
    // onChange: setValues,
    onDrag: setValues,
  });

// render
{handles.map(({ getHandleProps }) => (
            <React.Fragment key={getHandleProps().key}>
           // omitted
          </React.Fragment>
 ))}

Is there a way to click on a Track to set a new Range value ?

Hello,

We have switched to "react-ranger" from "tajo/react-range", in order to work with -- and for compatibility -- with Hooks...

Our web pages use many range sliders, and our users find it tedious to mouse-click and drag a button...

Is there a way to "click" on the Track, so that it will change the value -- and move the button ?

Thanks !

Support non-linear ranges

Got this idea when playing with the custom-steps sample. Would be cool to support a logarithmic interpolation on the slider.

Implementation Ideas

  1. Built in support for 'linear' and 'logarithmic' interpolation
  2. Custom interpolation support via props

Add `focused` variable to each element of handles

Hi @tannerlinsley, I'd like to add a variable (focused) to a handle so that we are able to do this:

{handles.map(({ getHandleProps, focused }) => (
  <button
    {...getHandleProps({
      style: {
        backgroundColor: focused ? "red" : "yellow",
        width: "14px",
        height: "14px",
        outline: "none",
        borderRadius: "100%",
        border: "solid 1px #888"
      }
    })}
  />
))}

Do you think this is a good idea?
Thanks for the lib btw πŸ˜„

Can't run `yarn start` on a fresh install

I cloned the repo and installed dependencies, however I can't run the dev server.

Reproduce Steps

  1. Clone repo
  2. yarn install
  3. yarn start
Failed to compile with 1 error.

 ERROR  in multi ./node_modules/nwb/polyfills.js (webpack)-dev-server/client?/ (webpack)/hot/only-dev-server.js ./demo/src/index.js
Module not found: Error: Can't resolve '/Users/evert/Documents/opensource/react-ranger/demo/src/index.js' in '/Users/evert/Documents/opensource/react-ranger'
 @ multi ./node_modules/nwb/polyfills.js (webpack)-dev-server/client?/ (webpack)/hot/only-dev-server.js ./demo/src/index.js

System

  • OS X 10.11.6
  • Node 10.5.0

min and max are automatically included in steps range

It seems like min and max values are automatically included in custom steps range.

min: 0,
max: 10,
steps: [2, 5, 6]

In this situation, handle should only be in one of the steps. But instead, handle can also be in 0 and 10.

I can’t just change min/max value, because I need to align each step’s position to another line graph.

onRelease should have access to value

I was wondering if it was possible to call a function with the value using onRelease instead of the mouse event since I don't want to have to do checks in my onChange handler.

<ReactRanger
  ...
  onRelease={value =>
    this.setState({ value })
  }
>

Can't install from repo

Describe the bug

It's currently not possible to install from the github repository using any package manager as the package.json is missing both name and version keys. Adding these keys allows you to install from pnpm and yarn, but not npm, as it stumbles on the "workspace:*" references.

Your Example Website or App

N/A

Steps to Reproduce the Bug or Issue

pnpm add github:TanStack/ranger
or
yarn add git+https://github.com/TanStack/ranger.git#main
or
npm install git+https://github.com/TanStack/ranger.git#main

Expected behavior

Expected that the latest commit from main branch is installed.

Screenshots or Videos

No response

Platform

yarn version 1.22.19
pnpm version 8.8.0
npm version 10.1.0

Additional context

No response

Can not drag on mobile

Getting the value of clientX on the touchMove Event, return NaN.
use e.changedTouches[0].clientX instead e.clienX while in mobile.

Disable prob not applying in the mobile view

my code

/* eslint-disable jsx-a11y/anchor-is-valid */
import React from "react";
import ReactDOM from "react-dom";
import styled, { createGlobalStyle } from "styled-components";
import { useRanger } from "react-ranger";

const GlobalStyles = createGlobalStyle`
  body {
   font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
   font-weight: 300;
  }
`;

export const Track = styled("div")`
  display: inline-block;
  height: 8px;
  width: 90%;
  margin: 0 5%;
`;

export const Tick = styled("div")`
  :before {
    content: "";
    position: absolute;
    left: 0;
    background: rgba(0, 0, 0, 0.2);
    height: 5px;
    width: 2px;
    transform: translate(-50%, 0.7rem);
  }
`;

export const TickLabel = styled("div")`
  position: absolute;
  font-size: 0.6rem;
  color: rgba(0, 0, 0, 0.5);
  top: 100%;
  transform: translate(-50%, 1.2rem);
  white-space: nowrap;
`;

export const Segment = styled("div")`
  background: ${(props) =>
    props.index === 0
      ? "#3e8aff"
      : props.index === 1
      ? "#00d5c0"
      : props.index === 2
      ? "#f5c200"
      : "#ff6050"};
  height: 100%;
`;

export const Handle = styled("div")`
  background: #ff1a6b;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1.6rem;
  height: 1.6rem;
  border-radius: 100%;
  font-size: 0.7rem;
  white-space: nowrap;
  color: white;
  font-weight: ${(props) => (props.active ? "bold" : "normal")};
  transform: ${(props) =>
    props.active ? "translateY(-100%) scale(1.3)" : "translateY(0) scale(0.9)"};
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
`;

function App(props) {
  console.log(props);
  const [values, setValues] = React.useState([15]);

  const { getTrackProps, ticks, segments, handles } = useRanger({
    min: 0,
    max: 100,
    stepSize: 1,
    values,
    onChange: setValues
  });

  return (
    <div className="App">
      <GlobalStyles />
      <h1>Custom Styles</h1>
      <br />
      <br />
      <Track {...getTrackProps()} dia>
        {ticks.map(({ value, getTickProps }) => (
          <Tick {...getTickProps()}>
            <TickLabel>{value}</TickLabel>
          </Tick>
        ))}
        {segments.map(({ getSegmentProps }, i) => (
          <Segment {...getSegmentProps()} index={i} />
        ))}
        {handles.map(({ value, active, getHandleProps }) => (
          <button
            {...getHandleProps({
              style: {
                appearance: "none",
                border: "none",
                background: "transparent",
                outline: "none"
              }
            })}
            disabled
          >
            <Handle active={active}>{value}</Handle>
          </button>
        ))}
      </Track>
      <br />
      <br />
      <br />
      <pre
        style={{
          display: "inline-block",
          textAlign: "left"
        }}
      >
        <code>
          {JSON.stringify({
            values
          })}
        </code>
      </pre>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App color="red" />, rootElement);

Here is the CodeSandBox link
https://codesandbox.io/s/nervous-bash-qun87?file=/src/index.js:1507-1588

Improve A11y support

Hi, I want to help with a PR for a11y - here are the things I would like to tackle:

  • Change getHandleProps to return by default: role ('slider'), aria-valuemin, aria-valuemax and aria-valuenow.
  • Change getHandleProps to not set tabindex and not set outline to none. Ideally, update the examples to use Buttons for handles (since they already are interactive elements and have a tab stop set by default).
  • Add support for keyboard navigation (When a handle is focused, the user should be able to use left/right arrows to change value)

Do you think these changes make sense for the library?

Missing Typescript definitions

I love the idea of a headless ranger, good job!

For some reason TypeScript types are not being exported.

Just to let you know.

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.