@transferwise/components 0.0.0-experimental-3ede9cc → 0.0.0-experimental-a8c8413

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,8 +2,16 @@ import classNames from 'classnames';
2
2
  import { useState } from 'react';
3
3
  import { useIntl } from 'react-intl';
4
4
 
5
- import { Input, SelectInput, SelectInputOptionContent, SelectInputProps } from '..';
6
- import { DateMode, MonthFormat, Size, SizeLarge, SizeMedium, SizeSmall } from '../common';
5
+ import { Body, Input, SelectInput, SelectInputOptionContent, SelectInputProps } from '..';
6
+ import {
7
+ DateMode,
8
+ MonthFormat,
9
+ Size,
10
+ SizeLarge,
11
+ SizeMedium,
12
+ SizeSmall,
13
+ Typography,
14
+ } from '../common';
7
15
  import { MDY, YMD, getMonthNames, isDateValid, isMonthAndYearFormat } from '../common/dateUtils';
8
16
  import { useInputAttributes } from '../inputs/contexts';
9
17
  import messages from './DateInput.messages';
@@ -93,8 +101,10 @@ const DateInput = ({
93
101
  };
94
102
 
95
103
  const [day, setDay] = useState(() => getInitialDate('day'));
104
+ const [displayDay, setDisplayDay] = useState(day?.toString());
96
105
  const [month, setMonth] = useState(() => getInitialDate('month'));
97
106
  const [year, setYear] = useState(() => getInitialDate('year'));
107
+ const [displayYear, setDisplayYear] = useState(year?.toString());
98
108
  const [lastBroadcastedValue, setLastBroadcastedValue] = useState<Date | null | undefined>(
99
109
  getDateObject,
100
110
  );
@@ -129,7 +139,7 @@ const DateInput = ({
129
139
  const getSelectElement = () => {
130
140
  return (
131
141
  <label className="d-flex flex-column">
132
- <span className="sr-only">{monthLabel}</span>
142
+ <Body type={Typography.BODY_DEFAULT}>{monthLabel}</Body>
133
143
  <SelectInput
134
144
  name="month"
135
145
  disabled={disabled}
@@ -147,13 +157,25 @@ const DateInput = ({
147
157
  );
148
158
  };
149
159
 
160
+ const isDayValid = (newDay: number, newMonth: number, newYear: number) => {
161
+ const maxDay = new Date(newYear, newMonth + 1, 0).getDate();
162
+ return newDay <= maxDay;
163
+ };
164
+
150
165
  const handleInternalValue = (newDay = day, newMonth = month, newYear = year) => {
151
- if (newDay == null || newMonth == null || newYear == null) {
166
+ if (newDay == null || newDay === 0 || newMonth == null || newYear == null || newYear === 0) {
167
+ broadcastNewValue(null);
168
+ return;
169
+ }
170
+ if (!isDayValid(newDay, newMonth, newYear)) {
152
171
  broadcastNewValue(null);
153
172
  return;
154
173
  }
155
174
 
156
175
  const dateValue = new Date(newYear, newMonth, newDay);
176
+ if (newYear < 100) {
177
+ dateValue.setFullYear(newYear);
178
+ }
157
179
 
158
180
  if (!isDateValid(dateValue)) {
159
181
  broadcastNewValue(null);
@@ -170,9 +192,12 @@ const DateInput = ({
170
192
  };
171
193
 
172
194
  const handleDayChange = (event: React.ChangeEvent<HTMLInputElement>) => {
173
- const { checkedDay } = checkDate(Number.parseInt(event.target.value, 10), month, year);
174
- setDay(checkedDay);
175
- handleInternalValue(checkedDay, month, year);
195
+ const newDayString = event.target.value.replace(/\D/g, '');
196
+ const newDayNumber = Number.parseInt(newDayString, 10);
197
+
198
+ setDay(newDayNumber);
199
+ setDisplayDay(newDayString);
200
+ handleInternalValue(newDayNumber, month, year);
176
201
  };
177
202
 
178
203
  const handleMonthChange = (selectedMonth: number | null) => {
@@ -181,30 +206,21 @@ const DateInput = ({
181
206
  handleInternalValue(day, null, year);
182
207
  return;
183
208
  }
184
- const { checkedDay } = checkDate(day, selectedMonth, year);
185
209
  setMonth(selectedMonth);
186
- if (day && checkedDay !== day) {
187
- setDay(checkedDay);
188
- }
189
- handleInternalValue(checkedDay, selectedMonth, year);
210
+ handleInternalValue(day, selectedMonth, year);
190
211
  };
191
212
 
192
213
  const handleYearChange = (event: React.ChangeEvent<HTMLInputElement>) => {
193
- const newValue = event.target.value;
194
- const slicedYear = newValue.length > 4 ? newValue.slice(0, 4) : newValue;
195
-
196
- if (slicedYear.toString().length === 4) {
197
- // Correct day based on year and month.
198
- const { checkedDay } = checkDate(day, month, Number.parseInt(newValue, 10));
199
-
200
- if (day && checkedDay !== day) {
201
- setDay(checkedDay);
202
- }
214
+ const newYearString = event.target.value.replace(/\D/g, '');
215
+ const newYearNumber = Number.parseInt(newYearString, 10);
203
216
 
204
- setYear(Number.parseInt(slicedYear, 10));
205
- handleInternalValue(checkedDay, month, Number.parseInt(slicedYear, 10));
217
+ if (newYearString.length >= 4 && newYearString.length <= 6) {
218
+ setYear(newYearNumber);
219
+ setDisplayYear(newYearString);
220
+ handleInternalValue(day, month, newYearNumber);
206
221
  } else {
207
- setYear(Number.parseInt(slicedYear, 10));
222
+ setYear(null);
223
+ setDisplayYear(newYearString);
208
224
  handleInternalValue(day, month, null);
209
225
  }
210
226
  };
@@ -216,29 +232,6 @@ const DateInput = ({
216
232
  }
217
233
  };
218
234
 
219
- const checkDate = (
220
- newDay: number | null = null,
221
- newMonth: number | null = 0,
222
- newYear: number | null = null,
223
- ) => {
224
- let checkedDay = newDay;
225
- const maxDay = new Date(newYear || 2000, newMonth != null ? newMonth + 1 : 1, 0).getDate();
226
-
227
- if (!newDay) {
228
- checkedDay = null;
229
- }
230
-
231
- if (newDay && newDay < 0) {
232
- checkedDay = 1;
233
- }
234
-
235
- if ((newDay && newMonth) || (newDay && newDay > 31)) {
236
- checkedDay = newDay > maxDay ? maxDay : newDay;
237
- }
238
-
239
- return { checkedDay, checkedMonth: newMonth, checkedYear: newYear };
240
- };
241
-
242
235
  const monthYearOnly = mode === DateMode.MONTH_YEAR;
243
236
 
244
237
  const monthWidth = classNames({
@@ -254,7 +247,7 @@ const DateInput = ({
254
247
  return (
255
248
  <div className="col-sm-3">
256
249
  <label>
257
- <span className="sr-only">{dayLabel}</span>
250
+ <Body type={Typography.BODY_DEFAULT}>{dayLabel}</Body>
258
251
  <div className={`input-group input-group-${size}`}>
259
252
  <Input
260
253
  type="text"
@@ -262,10 +255,12 @@ const DateInput = ({
262
255
  pattern="[0-9]*"
263
256
  name="day"
264
257
  autoComplete={dayAutoComplete}
265
- value={day || ''}
258
+ value={displayDay || ''}
266
259
  placeholder={placeholders?.day}
267
260
  disabled={disabled}
268
261
  min={1}
262
+ max={31}
263
+ maxLength={2}
269
264
  onChange={(event) => handleDayChange(event)}
270
265
  />
271
266
  </div>
@@ -278,7 +273,7 @@ const DateInput = ({
278
273
  return (
279
274
  <div className="col-sm-4">
280
275
  <label>
281
- <span className="sr-only">{yearLabel}</span>
276
+ <Body type={Typography.BODY_DEFAULT}>{yearLabel}</Body>
282
277
  <div className={`input-group input-group-${size}`}>
283
278
  <Input
284
279
  type="text"
@@ -287,9 +282,11 @@ const DateInput = ({
287
282
  name="year"
288
283
  autoComplete={yearAutoComplete}
289
284
  placeholder={placeholders?.year}
290
- value={year || ''}
285
+ value={displayYear || ''}
291
286
  disabled={disabled}
292
- min={1}
287
+ min={0}
288
+ max={9999}
289
+ maxLength={6}
293
290
  onChange={(event) => handleYearChange(event)}
294
291
  />
295
292
  </div>
@@ -2,12 +2,10 @@ import { useState } from 'react';
2
2
 
3
3
  import { Input } from '../inputs/Input';
4
4
  import { Field } from './Field';
5
- import { Sentiment } from '../common';
6
5
 
7
6
  export default {
8
7
  component: Field,
9
8
  title: 'Field',
10
- tags: ['autodocs'],
11
9
  };
12
10
 
13
11
  export const Basic = () => {
@@ -19,22 +17,43 @@ export const Basic = () => {
19
17
  );
20
18
  };
21
19
 
22
- export const WithStatusMessages = () => {
20
+ export const WithErrorMessage = () => {
23
21
  const [value, setValue] = useState<string | undefined>('This is some text');
24
22
  return (
25
- <div>
26
- <Field label="Phone number" type={Sentiment.POSITIVE} message="Positive message">
27
- <Input value={value} onChange={({ target }) => setValue(target.value)} />
28
- </Field>
29
- <Field label="Phone number" type={Sentiment.WARNING} message="Warning message">
30
- <Input value={value} onChange={({ target }) => setValue(target.value)} />
31
- </Field>
32
- <Field label="Phone number" type={Sentiment.NEGATIVE} message="This is a required field">
33
- <Input value={value} onChange={({ target }) => setValue(target.value)} />
34
- </Field>
35
- <Field label="Phone number" message="This is a helpful message">
36
- <Input value={value} onChange={({ target }) => setValue(target.value)} />
37
- </Field>
38
- </div>
23
+ <Field label="Phone number" error="This is a required field">
24
+ <Input value={value} onChange={({ target }) => setValue(target.value)} />
25
+ </Field>
26
+ );
27
+ };
28
+
29
+ export const WithHelp = () => {
30
+ const [value, setValue] = useState<string | undefined>('This is some text');
31
+ return (
32
+ <Field label="Phone number" hint="This is a helpful message">
33
+ <Input value={value} onChange={({ target }) => setValue(target.value)} />
34
+ </Field>
35
+ );
36
+ };
37
+
38
+ export const WithHelpAndErrorOnBlur = () => {
39
+ const [value, setValue] = useState<string | undefined>('This is some text');
40
+ const [error, setError] = useState<string | undefined>(undefined);
41
+ return (
42
+ <Field label="Phone number" hint="Please include country code" error={error}>
43
+ <Input
44
+ value={value}
45
+ onChange={({ target }) => {
46
+ setValue(target.value);
47
+ setError(undefined);
48
+ }}
49
+ onBlur={() => {
50
+ if (!value) {
51
+ setError('This is a required field');
52
+ } else {
53
+ setError(undefined);
54
+ }
55
+ }}
56
+ />
57
+ </Field>
39
58
  );
40
59
  };
@@ -15,28 +15,15 @@ export type FieldProps = {
15
15
  /** `null` disables auto-generating the `id` attribute, falling back to nesting-based label association over setting `htmlFor` explicitly. */
16
16
  id?: string | null;
17
17
  label: React.ReactNode;
18
- /** @deprecated use `message` and `type={Sentiment.NEUTRAL}` prop instead */
19
18
  hint?: React.ReactNode;
20
- message?: React.ReactNode;
21
- /** @deprecated use `message` and `type={Sentiment.NEGATIVE}` prop instead */
22
19
  error?: React.ReactNode;
23
- type?: `${Sentiment.NEGATIVE | Sentiment.NEUTRAL | Sentiment.POSITIVE | Sentiment.WARNING}`;
24
20
  className?: string;
25
21
  children?: React.ReactNode;
26
22
  };
27
23
 
28
- export const Field = ({
29
- id,
30
- label,
31
- message: propMessage,
32
- type: propType,
33
- className,
34
- children,
35
- ...props
36
- }: FieldProps) => {
37
- const type = props.error ? Sentiment.NEGATIVE : propType;
38
- const message = props.error || props.hint || propMessage;
39
- const hasError = type === Sentiment.NEGATIVE;
24
+ export const Field = ({ id, label, hint, error, className, children }: FieldProps) => {
25
+ const hasError = Boolean(error);
26
+ const hasHint = Boolean(hint) && !hasError;
40
27
 
41
28
  const labelId = useId();
42
29
 
@@ -48,16 +35,14 @@ export const Field = ({
48
35
  return (
49
36
  <FieldLabelIdContextProvider value={labelId}>
50
37
  <InputIdContextProvider value={inputId}>
51
- <InputDescribedByProvider value={message ? descriptionId : undefined}>
38
+ <InputDescribedByProvider value={hasError || hasHint ? descriptionId : undefined}>
52
39
  <InputInvalidProvider value={hasError}>
53
40
  <div
54
41
  className={classNames(
55
42
  'form-group d-block',
56
43
  {
57
- 'has-success': type === Sentiment.POSITIVE,
58
- 'has-warning': type === Sentiment.WARNING,
59
44
  'has-error': hasError,
60
- 'has-info': type === Sentiment.NEUTRAL,
45
+ 'has-info': hasHint,
61
46
  },
62
47
  className,
63
48
  )}
@@ -66,9 +51,14 @@ export const Field = ({
66
51
  {label}
67
52
  {children}
68
53
  </Label>
69
- {message && (
70
- <InlineAlert type={type} id={descriptionId}>
71
- {message}
54
+ {hasHint && (
55
+ <InlineAlert type={Sentiment.NEUTRAL} id={descriptionId}>
56
+ {hint}
57
+ </InlineAlert>
58
+ )}
59
+ {hasError && (
60
+ <InlineAlert type={Sentiment.NEGATIVE} id={descriptionId}>
61
+ {error}
72
62
  </InlineAlert>
73
63
  )}
74
64
  </div>
@@ -51,7 +51,7 @@ export const Basic = () => {
51
51
 
52
52
  return (
53
53
  <>
54
- {/* eslint-disable-next-line react/no-adjacent-inline-elements */}
54
+ {/*eslint-disable-next-line react/no-adjacent-inline-elements */}
55
55
  <p>
56
56
  The styling for the input (the coloured border) and the visibility of the inline alert is
57
57
  controlled through the use of <code>has-***</code> classes which are applied to the{' '}
@@ -60,11 +60,7 @@ export const Basic = () => {
60
60
  element. The available classes are <code>has-error</code>, <code>has-info</code>,{' '}
61
61
  <code>has-warning</code> and <code>has-success</code>.
62
62
  </p>
63
- <p>
64
- Where possible consumers should use{' '}
65
- <a href="https://storybook.wise.design/?path=/story/field--basic">Field</a> instead of doing
66
- this manually.
67
- </p>
63
+ <p>Where possible consumers should use Field instead of doing this manually.</p>
68
64
  <div className={`form-group ${typeClass}`}>
69
65
  <label className="control-label" htmlFor="id0">
70
66
  Toggleable
@@ -77,18 +73,14 @@ export const Basic = () => {
77
73
  Negative
78
74
  </label>
79
75
  <Input id="id1" value="Neptune is cool" />
80
- <InlineAlert type="negative">{message}</InlineAlert>
76
+ <InlineAlert type="error">{message}</InlineAlert>
81
77
  </div>
82
- <div className="form-group has-success">
78
+ <div className="form-group has-positive">
83
79
  <label className="control-label" htmlFor="id2">
84
80
  Positive
85
81
  </label>
86
82
  <Input id="id2" value="Neptune is cool" />
87
- <InlineAlert type="positive">
88
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
89
- ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
90
- ullamco laboris nisi ut aliquip ex ea commodo consequat.
91
- </InlineAlert>
83
+ <InlineAlert type="positive">{message}</InlineAlert>
92
84
  </div>
93
85
  <div className="form-group has-neutral">
94
86
  <label className="control-label" htmlFor="id3">
@@ -1,6 +1,6 @@
1
- import { AlertCircleFill, CheckCircleFill, CrossCircleFill } from '@transferwise/icons';
1
+ import { AlertCircle as AlertCircleIcon } from '@transferwise/icons';
2
2
  import classNames from 'classnames';
3
- import React, { ReactNode } from 'react';
3
+ import { ReactNode } from 'react';
4
4
 
5
5
  import { Sentiment } from '../common';
6
6
 
@@ -17,54 +17,15 @@ export default function InlineAlert({
17
17
  className,
18
18
  children,
19
19
  }: InlineAlertProps) {
20
- const getStatusIcon = (sentiment: Sentiment) => {
21
- switch (sentiment) {
22
- case Sentiment.POSITIVE:
23
- case Sentiment.SUCCESS:
24
- return <CheckCircleFill />;
25
- case Sentiment.WARNING:
26
- return <AlertCircleFill />;
27
- case Sentiment.NEGATIVE:
28
- case Sentiment.ERROR:
29
- return <CrossCircleFill />;
30
- default:
31
- return null;
32
- }
33
- };
34
-
35
- const hasTextChildren = (content: ReactNode) => {
36
- let label = '';
37
-
38
- const fillLabel = (childrenNodes: ReactNode) => {
39
- React.Children.map(childrenNodes, (child: ReactNode) => {
40
- if (typeof child === 'string') {
41
- label += child;
42
- }
43
- if (typeof child === 'object' && React.isValidElement(child)) {
44
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
45
- fillLabel(child?.props?.children as ReactNode);
46
- }
47
- });
48
- };
49
-
50
- fillLabel(content);
51
-
52
- return !!label.length;
53
- };
54
-
20
+ const danger = type === 'negative' || type === 'error';
55
21
  return (
56
22
  <div
57
23
  role="alert"
58
24
  id={id}
59
- className={classNames(
60
- 'alert alert-detach',
61
- `alert-${[Sentiment.NEGATIVE, Sentiment.ERROR].includes(type as Sentiment) ? 'danger' : type}`,
62
- className,
63
- )}
25
+ className={classNames('alert alert-detach', `alert-${danger ? 'danger' : type}`, className)}
64
26
  >
65
- {/* We should show the status icon only if we have some text to show */}
66
- {hasTextChildren(children) && getStatusIcon(type as Sentiment)}
67
- <div className="np-text-body-default">{children}</div>
27
+ {danger && <AlertCircleIcon />}
28
+ <div>{children}</div>
68
29
  </div>
69
30
  );
70
31
  }
@@ -12,7 +12,7 @@ export const Label = ({ id, htmlFor, className, children }: LabelProps) => {
12
12
  <label
13
13
  id={id}
14
14
  htmlFor={htmlFor}
15
- className={classNames('control-label d-flex flex-column gap-y-xs m-b-0', className)}
15
+ className={classNames('control-label d-flex flex-column gap-y-1 m-b-0', className)}
16
16
  >
17
17
  {children}
18
18
  </label>
@@ -1,17 +0,0 @@
1
- import { Field } from '../field/Field';
2
- import { mockMatchMedia, mockResizeObserver, render, screen } from '../test-utils';
3
- import DateInput from './DateInput';
4
-
5
- mockMatchMedia();
6
- mockResizeObserver();
7
-
8
- describe('DateInput', () => {
9
- it('supports `Field` for labeling', () => {
10
- render(
11
- <Field label="Date of birth">
12
- <DateInput onChange={() => {}} />
13
- </Field>,
14
- );
15
- expect(screen.getAllByRole('group')[0]).toHaveAccessibleName(/^Date of birth/);
16
- });
17
- });