Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Slider): Add Slider #81

Merged
merged 5 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ export default [
// 'import/no-unresolved': 'off',
'no-unused-vars': 'off',
'react-hooks/rules-of-hooks': 'error',
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "(useEventListener)"
}],
'react-hooks/exhaustive-deps': 'warn',
},
},
Expand Down
39 changes: 11 additions & 28 deletions src/Box/Box.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { flexbox } from '@styled-system/flexbox';
import { position } from '@styled-system/position';
import type { LayoutProps, FlexboxProps, PositionProps } from 'styled-system';
import { system } from '@styled-system/core';
import type * as CSS from 'csstype';

import { color, ColorProps } from './color';
import { CssFunctionReturn } from '../types';
Expand All @@ -23,17 +22,24 @@ export interface BoxFillableProps {
fillColor?: string;
}

export interface BoxFlexProps extends FlexboxProps {
grow?: number | boolean;
shrink?: number | boolean;
}

export type BoxProps = MarginProps &
PaddingProps &
ColorProps &
LayoutProps &
FlexboxProps &
BoxFlexProps &
PositionProps &
BoxFillableProps &
BoxCssProps;

const flexGrow = ifProp('grow', (_, value) => `flex-grow: ${value};`);
const flexShrink = ifProp('shrink', (_, value) => `flex-shrink: ${value};`);
export const boxInterpolateFn = (props) =>
[margin, padding, color, layout, flexbox, position].map((fn) => fn(props));
[margin, padding, color, layout, flexbox, position, flexGrow, flexShrink].map((fn) => fn(props));

const fill = system({
fillColor: {
Expand All @@ -52,40 +58,17 @@ export const Box = styled.div<BoxProps>`

export type LayoutBoxProps = MarginProps &
PaddingProps &
FlexboxProps &
BoxFlexProps &
LayoutProps &
PositionProps &
BoxCssProps;

export const layoutInterpolationFn = (props) =>
[margin, padding, layout, flexbox, position]
[margin, padding, layout, flexbox, position, flexGrow, flexShrink]
.map((fn) => fn(props))
.reduce((acc, styles) => ({ ...acc, ...styles }), {});

export const LayoutBox = styled.div<LayoutBoxProps>`
${baseStyle}
${layoutInterpolationFn}
`;

export type FlexProps = LayoutBoxProps & {
center?: boolean;
equal?: boolean;
end?: boolean;
start?: boolean;
between?: boolean;
stretch?: boolean;
direction?: CSS.Property.FlexDirection;
};

const justifyContent = (where: CSS.Property.JustifyContent) => `justify-content: ${where};`;

export const Flex = styled(Box)<FlexProps>`
display: flex;
${ifProp('center', 'justify-content: center; align-items: center;')}
${ifProp('equal', '> * { flex-basis: 100%; flex-grow: 1; flex-shrink: 1; }')}
${ifProp('between', justifyContent('space-between'))}
${ifProp('end', justifyContent('flex-end'))}
${ifProp('start', justifyContent('flex-start'))}
${ifProp('stretch', 'align-items: stretch;')}
${ifProp('direction', (_, value) => `flex-direction: ${value};`)}
`;
27 changes: 27 additions & 0 deletions src/Box/Flex.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type * as CSS from 'csstype';
import { ifProp } from '../styleHelpers/styleProp';
import { Box, type BoxProps } from './Box';
import styled from '@emotion/styled';

export type FlexProps = BoxProps & {
center?: boolean;
equal?: boolean;
end?: boolean;
start?: boolean;
between?: boolean;
stretch?: boolean;
direction?: CSS.Property.FlexDirection;
};

const justifyContent = (where: CSS.Property.JustifyContent) => `justify-content: ${where};`;

export const Flex = styled(Box)<FlexProps>`
display: flex;
${ifProp('center', 'justify-content: center; align-items: center;')}
${ifProp('equal', '> * { flex-basis: 100%; flex-grow: 1; flex-shrink: 1; }')}
${ifProp('between', justifyContent('space-between'))}
${ifProp('end', justifyContent('flex-end'))}
${ifProp('start', justifyContent('flex-start'))}
${ifProp('stretch', 'align-items: stretch;')}
${ifProp('direction', (_, value) => `flex-direction: ${value};`)}
`;
1 change: 1 addition & 0 deletions src/Box/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './Box';
export * from './Flex';
145 changes: 145 additions & 0 deletions src/Slider/Slider.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { Slider } from './Slider';
import * as stories from './Slider.stories';

const defaultProps = {
from: 0,
to: 100,
value: 50,
onChange: jest.fn(),
};

beforeEach(() => {
jest.clearAllMocks();
});

test('renders correctly', () => {
render(<Slider {...defaultProps} />);
expect(screen.getByRole('slider')).toBeInTheDocument();
});

test('calls onChange when dragging thumb', () => {
const { container } = render(<Slider {...defaultProps} />);
const thumb = container.querySelector('[data-testid="slider-thumb"]');
const rail = container.querySelector('[data-testid="slider-rail"]');

if (!thumb || !rail) throw new Error('Thumb or rail not found');

// Mock getBoundingClientRect
const railRect = { left: 0, width: 200 };
jest.spyOn(rail, 'getBoundingClientRect').mockImplementation(() => railRect as DOMRect);
// Set bounding rect that the click is exactly in the center
jest
.spyOn(thumb, 'getBoundingClientRect')
.mockImplementation(() => ({ left: 90, width: 20 }) as DOMRect);

// Simulate drag start
fireEvent.mouseDown(thumb, { clientX: 100 });

// Simulate drag movement
fireEvent.mouseMove(window, { clientX: 150 });

expect(defaultProps.onChange).toHaveBeenCalledWith(75);
});

test('handles custom range correctly', () => {
const customProps = {
...defaultProps,
from: -100,
to: 100,
value: 0,
};

const { container } = render(<Slider {...customProps} />);
const thumb = container.querySelector('[data-testid="slider-thumb"]');
const rail = container.querySelector('[data-testid="slider-rail"]');

if (!thumb || !rail) throw new Error('Thumb or rail not found');

const railRect = { left: 0, width: 200 };
jest.spyOn(rail, 'getBoundingClientRect').mockImplementation(() => railRect as DOMRect);
// Set bounding rect that the click is exactly in the center
jest
.spyOn(thumb, 'getBoundingClientRect')
.mockImplementation(() => ({ left: 90, width: 20 }) as DOMRect);

fireEvent.mouseDown(thumb, { clientX: 100 });
fireEvent.mouseMove(window, { clientX: 150 });

expect(customProps.onChange).toHaveBeenCalledWith(50);
});

test('constrains value within bounds', () => {
const { container } = render(<Slider {...defaultProps} />);
const thumb = container.querySelector('[data-testid="slider-thumb"]');
const rail = container.querySelector('[data-testid="slider-rail"]');

if (!thumb || !rail) throw new Error('Thumb or rail not found');

// Mock getBoundingClientRect
const railRect = { left: 0, width: 200 };
jest.spyOn(rail, 'getBoundingClientRect').mockImplementation(() => railRect as DOMRect);

// Simulate drag beyond maximum
fireEvent.mouseDown(thumb, { clientX: 100 });
fireEvent.mouseMove(document, { clientX: 300 });

expect(defaultProps.onChange).toHaveBeenCalledWith(100);

// Simulate drag below minimum
fireEvent.mouseMove(document, { clientX: -100 });

expect(defaultProps.onChange).toHaveBeenCalledWith(0);
});

test('stops dragging on mouseup', () => {
const { container } = render(<Slider {...defaultProps} />);
const thumb = container.querySelector('[data-testid="slider-thumb"]');

if (!thumb) throw new Error('Thumb not found');

fireEvent.mouseDown(thumb);
fireEvent.mouseUp(document);

// Simulate move after mouseup
fireEvent.mouseMove(document, { clientX: 150 });

expect(defaultProps.onChange).not.toHaveBeenCalled();
});

test('updates track width based on value', () => {
render(<Slider {...defaultProps} value={25} />);
const track = screen.getByTestId('slider-track');
expect(track).toHaveStyle({ width: '25%' });
});

test('updates thumb position based on value', () => {
render(<Slider {...defaultProps} value={75} />);
const thumb = screen.getByTestId('slider-thumb');
expect(thumb).toHaveStyle({ left: '75%' });
});

test('SimpleSlider story snapshot', () => {
const { container } = render(createStoryComponent(stories.SimpleSlider));
expect(container.firstChild).toMatchSnapshot();
});

test('OffsetRangeSlider story snapshot', () => {
const { container } = render(createStoryComponent(stories.OffsetRangeSlider));
expect(container.firstChild).toMatchSnapshot();
});

test('LowerOutOfBounds story snapshot', () => {
const { container } = render(createStoryComponent(stories.LowerOutOfBounds));
expect(container.firstChild).toMatchSnapshot();
});

test('UpperOutOfBounds story snapshot', () => {
const { container } = render(createStoryComponent(stories.UpperOutOfBounds));
expect(container.firstChild).toMatchSnapshot();
});

function createStoryComponent(Story) {
return <Story {...Story.args} />;
}
45 changes: 45 additions & 0 deletions src/Slider/Slider.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React, { useState } from 'react';

import { Slider } from './Slider';
import { Flex } from '../Box';
import { Paragraph } from '../Typography';

export default {
title: 'Slider',
};

const BaseStory = ({ from, to }) => {
const [value, setValue] = useState(50);
return (
<Flex center width="50vw" gap={2}>
<Slider shrink grow from={from} to={to} value={value} onChange={setValue} />
<Flex width={50} center shrink={0} grow={0}>
<Paragraph inline>{Math.floor(value)}</Paragraph>
</Flex>
</Flex>
);
};

export const SimpleSlider = BaseStory.bind(null);
SimpleSlider.args = {
from: 0,
to: 100,
};

export const OffsetRangeSlider = BaseStory.bind(null);
OffsetRangeSlider.args = {
from: 23,
to: 184,
};

export const LowerOutOfBounds = BaseStory.bind(null);
LowerOutOfBounds.args = {
from: 70,
to: 100,
};

export const UpperOutOfBounds = BaseStory.bind(null);
UpperOutOfBounds.args = {
from: 0,
to: 40,
};
Loading
Loading