Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/fix-Input-not-properly-update-value.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'react-magma-dom': patch
---

fix(Input): Improve the logic for updating the value in the handleChange function.
133 changes: 131 additions & 2 deletions packages/react-magma-dom/src/components/Input/Input.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { ChangeEvent } from 'react';

import { Meta, Story } from '@storybook/react/types-6-0';
import { HelpIcon, NotificationsIcon, WorkIcon } from 'react-magma-icons';
Expand All @@ -18,11 +18,13 @@ import { IconButton } from '../IconButton';
import { InputIconPosition, InputSize, InputType } from '../InputBase';
import { LabelPosition } from '../Label';
import { NativeSelect } from '../NativeSelect';
import { Paragraph } from '../Paragraph';
import { PasswordInput } from '../PasswordInput';
import { Search } from '../Search';
import { Spacer, SpacerAxis } from '../Spacer';
import { TimePicker } from '../TimePicker';
import { Tooltip } from '../Tooltip';
import { CustomTopicsRow } from './testUtils';

import { Input, InputProps } from '.';

Expand Down Expand Up @@ -395,7 +397,7 @@ export const URLInput = () => {
pattern={urlPattern}
labelText="URL"
type={InputType.url}
errorMessage={hasError ? 'Please enter a url' : null}
errorMessage={hasError ? 'Enter a valid URL.' : null}
value={inputVal}
onChange={handleChange}
/>
Expand Down Expand Up @@ -706,3 +708,130 @@ export const AllInputs = () => {
</>
);
};

export function TimeInput() {
const [hours, setHours] = React.useState(0);
const [minutes, setMinutes] = React.useState(0);
const [totalDurationMilliseconds, setTotalDurationMilliseconds] =
React.useState(0);

const makeHoursAndMinutesFromMilliseconds = (
milliseconds = 0
): { hours: number; minutes: number } => {
const hours = Math.floor(milliseconds / (60 * 60 * 1000));
const remainingMilliseconds = milliseconds % (60 * 60 * 1000);
const minutes = Math.floor(remainingMilliseconds / (60 * 1000));

return {
hours,
minutes,
};
};

const onChangeTimedDuration = (
event: ChangeEvent<HTMLInputElement>,
unit: 'hours' | 'minutes',
oppositeUnitValue: number
) => {
const inputValue = event.target.value.replace(/\D/g, '');
const numericValue = inputValue ? Number(inputValue) : NaN;
const currentUnitValue =
numericValue && numericValue >= 0 ? numericValue : 0;
const isHours = unit === 'hours';

// Immediate sync for Magma Input
isHours ? setHours(currentUnitValue) : setMinutes(currentUnitValue);

const totalDurationMilliseconds = isHours
? (currentUnitValue * 60 + oppositeUnitValue) * 60 * 1000
: (oppositeUnitValue * 60 + currentUnitValue) * 60 * 1000;

setTotalDurationMilliseconds(totalDurationMilliseconds);
};

React.useEffect(() => {
const { hours, minutes } = makeHoursAndMinutesFromMilliseconds(
totalDurationMilliseconds
);
setHours(hours);
setMinutes(minutes);
}, [totalDurationMilliseconds]);

return (
<>
<Paragraph>React Magma inputs:</Paragraph>
<Input
type={InputType.number}
labelText="Hours"
inputWrapperStyle={{ width: '264px' }}
min={1}
max={60}
value={hours}
onChange={event => onChangeTimedDuration(event, 'hours', minutes)}
/>
<Input
type={InputType.number}
labelText="Minutes"
inputWrapperStyle={{ width: '264px' }}
min={1}
max={60}
value={minutes}
onChange={event => onChangeTimedDuration(event, 'minutes', hours)}
/>
<Spacer size={32} />
<Paragraph>Native inputs:</Paragraph>
<Paragraph style={{ marginBottom: '8px' }}>Hours</Paragraph>
<div style={{ display: 'flex', flexDirection: 'column', width: '264px' }}>
<input
type={InputType.number}
min={1}
max={60}
value={hours}
onChange={event => onChangeTimedDuration(event, 'hours', minutes)}
/>
<Paragraph style={{ marginBottom: '8px' }}>Minutes</Paragraph>
<input
type={InputType.number}
min={1}
max={60}
value={minutes}
onChange={event => onChangeTimedDuration(event, 'minutes', hours)}
/>
</div>
</>
);
}

export const CustomTopicsRowStory = () => {
const topicList = [
{ reference: 'topic1', title: 'Topic 1' },
{ reference: 'topic2', title: 'Topic 2' },
{ reference: 'topic3', title: 'Topic 3' },
];

const [topicTitle, setTopicTitle] = React.useState('');
const [testTopic, setTestTopic] = React.useState<string | undefined>();
const [studyMaterialsTopic, setStudyMaterialsTopic] = React.useState<
string | undefined
>();

const removeTopicRow = () => {
alert('Row removed');
};

return (
<CustomTopicsRow
topicList={topicList}
isRemoveButtonDisabled={false}
shouldValidate
topicTitle={topicTitle}
testTopic={testTopic}
studyMaterialsTopic={studyMaterialsTopic}
order={1}
setTopicTitle={setTopicTitle}
setTestTopic={setTestTopic}
setStudyMaterialsTopic={setStudyMaterialsTopic}
removeTopicRow={removeTopicRow}
/>
);
};
82 changes: 81 additions & 1 deletion packages/react-magma-dom/src/components/Input/Input.test.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
import React from 'react';

import { render, fireEvent } from '@testing-library/react';
import { render, fireEvent, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { transparentize } from 'polished';
import PropTypes from 'prop-types';
import { CheckIcon } from 'react-magma-icons';

import { axe } from '../../../axe-helper';
import { defaultI18n } from '../../i18n/default';
import { magma } from '../../theme/magma';
import { InputType } from '../InputBase';
import { CustomTopicsRow } from './testUtils';

import { Input } from '.';

const renderWithProviders = (ui, renderOptions = {}) => {
const Wrapper = ({ children }) => <>{children}</>;

Wrapper.propTypes = {
children: PropTypes.node,
};

return render(ui, { wrapper: Wrapper, ...renderOptions });
};

const label = 'test label';

describe('Input', () => {
Expand Down Expand Up @@ -706,4 +719,71 @@ describe('Input', () => {
expect(inputElement).toHaveAttribute('type', 'url');
});
});

describe('Custom Topics Row', () => {
const properties = {
topicList: [
{
reference: 'custom sub activity reference',
title: 'custom sub activity title',
},
],
isRemoveButtonDisabled: false,
shouldValidate: true,
topicTitle: '',
testTopic: undefined,
studyMaterialsTopic: undefined,
order: 1,
setTopicTitle: jest.fn(),
setTestTopic: jest.fn(),
setStudyMaterialsTopic: jest.fn(),
removeTopicRow: jest.fn(),
};

it('should insert title topic', async () => {
renderWithProviders(<CustomTopicsRow {...properties} />);

await userEvent.type(screen.getByTestId('topicTitle-1'), 'topicTitle');

expect(properties.setTopicTitle).toHaveBeenCalledWith('topicTitle');
});

it('should select test topic', async () => {
renderWithProviders(<CustomTopicsRow {...properties} />);

await userEvent.click(
screen.getByRole('combobox', { name: 'Topic 1 Test *' })
);
await userEvent.click(
screen.getByRole('option', { name: 'custom sub activity title' })
);

expect(properties.setTestTopic).toHaveBeenCalledWith(
'custom sub activity reference'
);
});

it('should select study materials topic', async () => {
renderWithProviders(<CustomTopicsRow {...properties} />);

await userEvent.click(
screen.getByRole('combobox', { name: 'Topic 1 Study Materials *' })
);
await userEvent.click(
screen.getByRole('option', { name: 'custom sub activity title' })
);

expect(properties.setStudyMaterialsTopic).toHaveBeenCalledWith(
'custom sub activity reference'
);
});

it('should remove custom topics row', async () => {
renderWithProviders(<CustomTopicsRow {...properties} />);

await userEvent.click(screen.getByTestId('removeRowButton-1'));

expect(properties.removeTopicRow).toHaveBeenCalled();
});
});
});
124 changes: 124 additions & 0 deletions packages/react-magma-dom/src/components/Input/testUtils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import React from 'react';

import { WorkIcon } from 'react-magma-icons';

import { ButtonColor, ButtonVariant } from '../Button';
import { Combobox } from '../Combobox';
import { IconButton } from '../IconButton';

import { Input } from './index';

// This component is used to render the Input usage for testing purposes.
export const CustomTopicsRow = ({
topicList,
isRemoveButtonDisabled,
shouldValidate,
topicTitle,
testTopic,
studyMaterialsTopic,
order,
setTopicTitle,
setTestTopic,
setStudyMaterialsTopic,
removeTopicRow,
}: {
topicList: { reference: string; title: string }[];
isRemoveButtonDisabled: boolean;
shouldValidate?: boolean;
topicTitle: string;
testTopic?: string;
studyMaterialsTopic?: string;
order: number;
setTopicTitle: (title: string) => void;
setTestTopic: (reference: string) => void;
setStudyMaterialsTopic: (reference: string) => void;
removeTopicRow: () => void;
}) => {
const getTopicTitleError = (): string | undefined => {
if (!topicTitle.length) return 'Enter a topic title';
if (topicTitle.length >= 100) return 'Title is too long';
return undefined;
};

const normalizeTopicItems = (): { label: string; value: string }[] =>
topicList.map((topic: { reference: string; title: string }) => ({
label: topic.title,
value: topic.reference,
}));

const getSelectedTopic = (
reference?: string
): { label: string; value: string } | undefined => {
if (!reference) return;
const selectedTopic = topicList.find(
(topic: { reference: string }) => topic.reference === reference
);
return selectedTopic
? {
label: selectedTopic.title,
value: selectedTopic.reference,
}
: undefined;
};

const onTopicTitleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setTopicTitle(event.target.value.trim());
};

const onTestTopicChange = (
changes: Partial<{ selectedItem: { label: string; value: string } }>
) => {
if (changes.selectedItem) {
setTestTopic(changes.selectedItem.value);
}
};

const onStudyMaterialsTopicChange = (
changes: Partial<{ selectedItem: { label: string; value: string } }>
) => {
if (changes.selectedItem) {
setStudyMaterialsTopic(changes.selectedItem.value);
}
};

return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
<Input
errorMessage={shouldValidate && getTopicTitleError()}
id={`topicTitle-${order}`}
labelText={`Topic ${order} Title *`}
onChange={onTopicTitleChange}
required
testId={`topicTitle-${order}`}
value={topicTitle}
/>
<Combobox
items={normalizeTopicItems()}
labelText={`Topic ${order} Test *`}
onSelectedItemChange={onTestTopicChange}
placeholder="Select a test topic"
selectedItem={getSelectedTopic(testTopic)}
testId={`testTopic-${order}`}
/>
<Combobox
items={normalizeTopicItems()}
labelText={`Topic ${order} Study Materials *`}
onSelectedItemChange={onStudyMaterialsTopicChange}
placeholder="Select study materials"
selectedItem={getSelectedTopic(studyMaterialsTopic)}
testId={`studyMaterialsTopic-${order}`}
/>
<IconButton
aria-label="Remove"
color={
isRemoveButtonDisabled ? ButtonColor.secondary : ButtonColor.primary
}
disabled={isRemoveButtonDisabled}
icon={<WorkIcon />}
onClick={removeTopicRow}
testId={`removeRowButton-${order}`}
variant={ButtonVariant.link}
/>
</div>
);
};
Loading