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
4 changes: 4 additions & 0 deletions src/molecules/TextField/TextField.docs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,7 @@ Compact `TextField` uses `EdsProvider`
Here is one way to do it using `pattern` and `onChange`

<Canvas of={ComponentStories.Validation} />

### Max characters

<Canvas of={ComponentStories.MaxCharacterCount} />
6 changes: 6 additions & 0 deletions src/molecules/TextField/TextField.jsdom.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,9 @@ test('Disabled text styling overrides variant', () => {

expect(boxShadow).not.toBe(`inset 0 -2px 0 0 ${VARIANT_COLORS.dirty}`);
});

test('Throws error when providing maxCharacters and type number', () => {
expect(() =>
render(<TextField id="text" type="number" maxCharacters={10} />)
).toThrowError();
});
Comment thread
mariush2 marked this conversation as resolved.
129 changes: 127 additions & 2 deletions src/molecules/TextField/TextField.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ import {
thumbs_up,
warning_filled,
} from '@equinor/eds-icons';
import { Meta, StoryFn } from '@storybook/react-vite';
import { faker } from '@faker-js/faker';
import { Meta, StoryFn, StoryObj } from '@storybook/react-vite';

import { TextField } from 'src/molecules/TextField/TextField';
import { TextField, TextFieldProps } from 'src/molecules/TextField/TextField';
import page from 'src/molecules/TextField/TextField.docs.mdx';
import { Stack } from 'src/storybook';

import { expect, userEvent } from 'storybook/test';

const icons = {
thumbs_up,
warning_filled,
Expand Down Expand Up @@ -49,6 +52,9 @@ const meta: Meta<typeof TextField> = {
control: 'radio',
options: ['error', 'warning', 'success', 'dirty', undefined],
},
maxCharacters: {
control: 'number',
},
inputIcon: {
options: ['error', 'warning', 'success'],
mapping: {
Expand Down Expand Up @@ -91,6 +97,8 @@ export default meta;

type Story = StoryFn<typeof TextField>;

type StoryObject = StoryObj<typeof TextField>;

export const Introduction: Story = (args) => {
return <TextField placeholder="Placeholder" {...args} />;
};
Expand Down Expand Up @@ -636,3 +644,120 @@ export const Validation: Story = () => {
</form>
);
};

function MaxCharactersComponent(args: TextFieldProps) {
const [internalValue, setInternalValue] = useState<string>('');

const handleOnChange = (
event: ChangeEvent<HTMLInputElement> | ChangeEvent<HTMLTextAreaElement>
) => {
setInternalValue(event.target.value);
};

return (
<TextField
{...args}
value={internalValue}
onChange={handleOnChange}
variant={
internalValue.length > (args.maxCharacters ?? Infinity)
? 'error'
: undefined
}
/>
);
}

export const MaxCharacterCount: StoryObject = {
args: {
placeholder: 'Enter product name',
label: 'Product Name',
helperText: "Start by adding the product's name.",
maxCharacters: 10,
},
render: MaxCharactersComponent,
play: async ({ canvas, args }) => {
await expect(
canvas.getByText(`0 / ${args.maxCharacters}`)
).toBeInTheDocument();
const input = canvas.getByLabelText(`${args.label}`) as HTMLInputElement;
const value = faker.airline.airport().name;
await userEvent.type(input, value);
await expect(
canvas.getByText(`${value.length} / ${args.maxCharacters}`)
).toBeInTheDocument();
},
};

export const MaxCharacterCountWithoutHelper: StoryObject = {
tags: ['test-only'],
args: {
placeholder: 'Enter product name',
label: 'Product Name',
maxCharacters: 10,
variant: 'error',
},
play: async ({ canvas, args }) => {
await expect(
canvas.getByText(`0 / ${args.maxCharacters}`)
).toBeInTheDocument();
const input = canvas.getByLabelText(`${args.label}`) as HTMLInputElement;
const value = faker.airline.airport().name;
await userEvent.type(input, value);
await expect(
canvas.getByText(`${value.length} / ${args.maxCharacters}`)
).toBeInTheDocument();
},
};

function TestComponent(args: TextFieldProps) {
const [internalValue, setInternalValue] = useState<string>('');

const handleOnChange = (
event: ChangeEvent<HTMLInputElement> | ChangeEvent<HTMLTextAreaElement>
) => {
setInternalValue(event.target.value);
};

return (
<>
<TextField
{...args}
value={internalValue}
onChange={handleOnChange}
variant={
internalValue.length > (args.maxCharacters ?? Infinity)
? 'error'
: undefined
}
/>
<button onClick={() => setInternalValue('something')}>external</button>
</>
);
}

export const MaxCharacterCountExternalUpdate: StoryObject = {
tags: ['test-only'],
args: {
placeholder: 'Enter product name',
label: 'Product Name',
helperText: "Start by adding the product's name.",
value: 'heihei',
maxCharacters: 20,
},
render: TestComponent,
play: async ({ canvas, args }) => {
await expect(
canvas.getByText(`0 / ${args.maxCharacters}`)
).toBeInTheDocument();
const newValue = faker.airline.airport().name;
await userEvent.type(canvas.getByRole('textbox'), newValue);
await expect(
canvas.getByText(`${newValue.length} / ${args.maxCharacters}`)
).toBeInTheDocument();
await userEvent.click(canvas.getByText('external'));
await expect(
canvas.getByText(`${'something'.length} / ${args.maxCharacters}`)
).toBeInTheDocument();
},
};
93 changes: 91 additions & 2 deletions src/molecules/TextField/TextField.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { FC, InputHTMLAttributes, TextareaHTMLAttributes, useRef } from 'react';
import {
ChangeEvent,
ChangeEventHandler,
FC,
InputHTMLAttributes,
TextareaHTMLAttributes,
useEffect,
useRef,
useState,
} from 'react';

import {
TextField as Base,
TextFieldProps as BaseProps,
Typography,
} from '@equinor/eds-core-react';

import { shape, spacings } from 'src/atoms/style';
Expand All @@ -17,13 +27,15 @@ import styled, { css } from 'styled-components';
export type TextFieldProps = Omit<BaseProps, 'variant'> & {
variant?: Variants;
loading?: boolean;
maxCharacters?: number;
Comment thread
mariush2 marked this conversation as resolved.
} & (
| TextareaHTMLAttributes<HTMLTextAreaElement>
| InputHTMLAttributes<HTMLInputElement>
);

interface WrapperProps {
$variant: TextFieldProps['variant'];
$helperRightWidth: number;
$disabled?: boolean;
}

Expand Down Expand Up @@ -51,6 +63,13 @@ const Wrapper = styled.div<WrapperProps>`
outline: none !important;
}

div[class*='HelperText'] {
margin-right: ${({ $helperRightWidth }) =>
$helperRightWidth
? `calc(${$helperRightWidth}px + ${spacings.medium})`
: 0};
Comment thread
mariush2 marked this conversation as resolved.
}
Comment thread
mariush2 marked this conversation as resolved.

${({ $variant, $disabled }) => {
if ($disabled) {
return css`
Expand Down Expand Up @@ -115,7 +134,21 @@ const Loader = styled(SkeletonBase)`
transform: translateY(${spacings.x_small});
`;

const MaxCharactersText = styled(Typography)`
position: absolute;
right: ${spacings.small};
`;

/**
* @param loading - Show loading skeleton on top of the text field.
* @param maxCharacters - Maximum number of characters allowed in the text field. Does not enforce the limit, only for display purposes.
Comment thread
mariush2 marked this conversation as resolved.
*/
Comment thread
mariush2 marked this conversation as resolved.
export const TextField: FC<TextFieldProps> = (props) => {
if (props.maxCharacters && 'type' in props && props.type !== 'text') {
throw new Error(
'`maxCharacters` prop is not supported for input types other than "text".'
Comment thread
mariush2 marked this conversation as resolved.
);
}
const baseProps: BaseProps = {
...props,
variant: props.variant !== 'dirty' ? props.variant : undefined,
Expand All @@ -125,13 +158,50 @@ export const TextField: FC<TextFieldProps> = (props) => {
const skeletonTop = getSkeletonTop(props);
const skeletonHeight = getSkeletonHeight(props);
const skeletonWidth = useRef(`${Math.max(20, Math.random() * 80)}%`);
const [characterCount, setCharacterCount] = useState<number>(
typeof props.value === 'string' ? props.value.length : 0
);
Comment thread
mariush2 marked this conversation as resolved.
const [helperRightWidth, setHelperRightWidth] = useState(0);

const handleRenderHelperTextRight = (element: HTMLDivElement | null) => {
if (element) {
const width = element.getBoundingClientRect().width;
setHelperRightWidth(width);
Comment thread
mariush2 marked this conversation as resolved.
}
};
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.

// Since both textarea and input have event.target.value , we can safely cast here
const handleOnChange = (event: ChangeEvent<HTMLInputElement>) => {
if (props.onChange) {
(props.onChange as ChangeEventHandler<HTMLInputElement>)(event);
Comment thread
mariush2 marked this conversation as resolved.
}

if (props.maxCharacters) {
setCharacterCount(event.target.value.length);
}
};
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.

useEffect(() => {
if (
typeof props.value === 'string' &&
props.maxCharacters &&
props.value.length !== characterCount
) {
setCharacterCount(props.value.length);
}
}, [characterCount, props.maxCharacters, props.value]);
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.

return (
<Wrapper
$variant={usingVariant}
$disabled={props.loading ? false : props.disabled}
$helperRightWidth={helperRightWidth}
>
<Base {...baseProps} disabled={props.loading || props.disabled} />
<Base
{...baseProps}
disabled={props.loading || props.disabled}
onChange={handleOnChange as never} // Bypass TS error caused by union of input and textarea attributes
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.
/>
{props.loading && (
<Loader
className="skeleton"
Expand All @@ -143,6 +213,25 @@ export const TextField: FC<TextFieldProps> = (props) => {
}}
/>
)}
{props.maxCharacters && (
<MaxCharactersText
ref={handleRenderHelperTextRight}
variant="helper"
group="input"
color={
baseProps.variant
? VARIANT_COLORS[baseProps.variant]
Comment thread
mariush2 marked this conversation as resolved.
: colors.text.static_icons__tertiary.rgba
}
style={{
bottom: props.helperText
? '0'
: `calc((${spacings.small} + 1rem) * -1)`,
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.
}}
Comment thread
mariush2 marked this conversation as resolved.
Comment thread
mariush2 marked this conversation as resolved.
>
{characterCount} / {props.maxCharacters}
</MaxCharactersText>
)}
Comment thread
mariush2 marked this conversation as resolved.
</Wrapper>
);
};
Loading