@osrd-project/ui-core 0.0.83 → 0.0.85

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.
Files changed (59) hide show
  1. package/dist/index.d.ts +382 -20
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +2101 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/theme.css +1202 -983
  6. package/package.json +16 -16
  7. package/dist/components/Button.d.ts +0 -16
  8. package/dist/components/Checkbox/Checkbox.d.ts +0 -9
  9. package/dist/components/Checkbox/CheckboxList.d.ts +0 -12
  10. package/dist/components/Checkbox/CheckboxTree.d.ts +0 -11
  11. package/dist/components/Checkbox/__tests__/utils.spec.d.ts +0 -1
  12. package/dist/components/Checkbox/index.d.ts +0 -4
  13. package/dist/components/Checkbox/type.d.ts +0 -14
  14. package/dist/components/Checkbox/utils.d.ts +0 -15
  15. package/dist/components/ComboBox/ComboBox.d.ts +0 -34
  16. package/dist/components/ComboBox/index.d.ts +0 -2
  17. package/dist/components/ComboBox/useDefaultComboBox.d.ts +0 -6
  18. package/dist/components/DatePicker/Calendar.d.ts +0 -10
  19. package/dist/components/DatePicker/CalendarPicker.d.ts +0 -19
  20. package/dist/components/DatePicker/DatePicker.d.ts +0 -28
  21. package/dist/components/DatePicker/__tests__/useCalendar.spec.d.ts +0 -9
  22. package/dist/components/DatePicker/__tests__/useCalendarPicker.spec.d.ts +0 -1
  23. package/dist/components/DatePicker/__tests__/useDatePicker.spec.d.ts +0 -1
  24. package/dist/components/DatePicker/__tests__/utils.spec.d.ts +0 -1
  25. package/dist/components/DatePicker/index.d.ts +0 -2
  26. package/dist/components/DatePicker/type.d.ts +0 -4
  27. package/dist/components/DatePicker/useCalendar.d.ts +0 -7
  28. package/dist/components/DatePicker/useCalendarPicker.d.ts +0 -9
  29. package/dist/components/DatePicker/useDatePicker.d.ts +0 -18
  30. package/dist/components/DatePicker/utils.d.ts +0 -113
  31. package/dist/components/Dialog.d.ts +0 -22
  32. package/dist/components/FieldWrapper.d.ts +0 -22
  33. package/dist/components/Hint.d.ts +0 -6
  34. package/dist/components/Input.d.ts +0 -27
  35. package/dist/components/InputModal.d.ts +0 -10
  36. package/dist/components/InputStatusIcon.d.ts +0 -9
  37. package/dist/components/Label.d.ts +0 -11
  38. package/dist/components/PasswordInput.d.ts +0 -21
  39. package/dist/components/RadioButton.d.ts +0 -9
  40. package/dist/components/RadioGroup.d.ts +0 -17
  41. package/dist/components/SegmentedControl.d.ts +0 -12
  42. package/dist/components/Select.d.ts +0 -12
  43. package/dist/components/Slider.d.ts +0 -9
  44. package/dist/components/StatusMessage.d.ts +0 -17
  45. package/dist/components/Table/Table.d.ts +0 -15
  46. package/dist/components/Table/tableAmbientThemes.d.ts +0 -22
  47. package/dist/components/TextArea.d.ts +0 -5
  48. package/dist/components/TimePicker.d.ts +0 -16
  49. package/dist/components/TokenInput.d.ts +0 -7
  50. package/dist/components/TolerancePicker/TolerancePicker.d.ts +0 -14
  51. package/dist/components/TolerancePicker/ToleranceRangeGrid.d.ts +0 -8
  52. package/dist/components/TolerancePicker/consts.d.ts +0 -4
  53. package/dist/hooks/__tests__/useOutsideClick.spec.d.ts +0 -1
  54. package/dist/hooks/useFocusByTab.d.ts +0 -11
  55. package/dist/hooks/useModalPosition.d.ts +0 -7
  56. package/dist/hooks/useOutsideClick.d.ts +0 -2
  57. package/dist/index.esm.js +0 -1462
  58. package/dist/index.esm.js.map +0 -1
  59. package/dist/theme.css.map +0 -1
package/dist/index.esm.js DELETED
@@ -1,1462 +0,0 @@
1
- import React, { useEffectEvent, useEffect, useState, useCallback, useRef, useMemo } from 'react';
2
- import cx from 'classnames';
3
- import { Gear, Info, CheckCircle, Alert, Blocked, RequiredInput, X, XCircle, ChevronDown, ChevronLeft, ChevronRight, Calendar as Calendar$1, EyeClosed, Eye } from '@osrd-project/ui-icons';
4
-
5
- const Button = ({ label, variant = 'Primary', isLoading = false, isDisabled = false, leadingIcon = null, counter = null, size = 'large', onClick, dataTestID, ...btnAttrs }) => {
6
- const handleClick = () => {
7
- if (!isLoading && !isDisabled && onClick) {
8
- onClick();
9
- }
10
- };
11
- return (React.createElement("button", { ...btnAttrs, className: cx('ui-button flex items-center', btnAttrs.className, variant.toLowerCase(), size.toLowerCase(), {
12
- loading: isLoading,
13
- }), "data-testid": dataTestID, onClick: handleClick, disabled: isDisabled || isLoading },
14
- leadingIcon && React.createElement("span", { className: "leading-icon mr-2" }, leadingIcon),
15
- label,
16
- counter !== null && React.createElement("span", { className: "counter ml-2" }, counter)));
17
- };
18
-
19
- const useOutsideClick = (ref, handler) => {
20
- const handleClickOutside = useEffectEvent((event) => {
21
- if (ref?.current && !ref.current.contains(event.target)) {
22
- handler(event);
23
- }
24
- });
25
- useEffect(() => {
26
- document.addEventListener('mousedown', handleClickOutside);
27
- return () => {
28
- document.removeEventListener('mousedown', handleClickOutside);
29
- };
30
- }, [ref, handler]);
31
- };
32
-
33
- function useFocusByTab({ onBlur, onKeyUp }) {
34
- const [isFocusByTab, setIsFocusByTab] = useState(false);
35
- const handleKeyUp = useCallback((event) => {
36
- if (event.key === 'Tab')
37
- setIsFocusByTab(true);
38
- onKeyUp?.(event);
39
- }, [onKeyUp]);
40
- const handleBlur = useCallback((event) => {
41
- setIsFocusByTab(false);
42
- onBlur?.(event);
43
- }, [onBlur]);
44
- return { handleKeyUp, handleBlur, isFocusByTab };
45
- }
46
-
47
- const Hint = ({ text }) => React.createElement("span", { className: "ui-hint" }, text);
48
-
49
- const InputStatusIcon = ({ status, small, className }) => {
50
- const size = small ? 'sm' : 'lg';
51
- return (React.createElement("span", { className: cx('ui-status-icon', className, status) },
52
- status === 'loading' && React.createElement(Gear, { size: size }),
53
- status === 'info' && React.createElement(Info, { variant: "fill", size: size }),
54
- status === 'success' && React.createElement(CheckCircle, { variant: "fill", size: size }),
55
- status === 'warning' && React.createElement(Alert, { variant: "fill", size: size }),
56
- status === 'error' && React.createElement(Blocked, { variant: "fill", size: size })));
57
- };
58
-
59
- const Label = ({ htmlFor, text, required, hasHint, disabled, small = false }) => (React.createElement("div", { className: cx('ui-label-wrapper', { 'has-hint': hasHint, small }) },
60
- required && (React.createElement("span", { className: "required" },
61
- React.createElement(RequiredInput, null))),
62
- React.createElement("label", { className: cx('label', { disabled: disabled }), htmlFor: htmlFor }, text)));
63
-
64
- const StatusMessage = ({ statusWithMessage, showIcon, small, onClose, testIdPrefix, }) => {
65
- const { tooltip, status, message } = statusWithMessage;
66
- if (message === undefined)
67
- return null;
68
- return (React.createElement("div", { className: cx({
69
- 'ui-status-message-wrapper': !tooltip,
70
- 'ui-status-message-wrapper-tooltip': tooltip,
71
- 'tooltip-left': tooltip === 'left',
72
- 'tooltip-right': tooltip === 'right',
73
- [status]: status,
74
- }) },
75
- showIcon && React.createElement(InputStatusIcon, { status: status, small: small }),
76
- React.createElement("span", { "data-testid": testIdPrefix ? `${testIdPrefix}-${status}` : undefined, className: cx('status-message', { [status]: status }) }, message),
77
- status === 'info' && tooltip && (React.createElement("button", { className: "status-close", onClick: onClose },
78
- React.createElement(X, { size: "sm" })))));
79
- };
80
-
81
- const FieldWrapper = ({ id, label, hint, required, disabled, statusWithMessage, statusIconPosition = 'next-to-field', narrow = false, small = false, className, children, onCloseStatusMessage, }) => {
82
- const statusClassname = statusWithMessage ? { [statusWithMessage.status]: true } : {};
83
- const defaultTooltip = narrow ? 'left' : undefined;
84
- if (narrow && required) {
85
- throw new Error('narrow should not be used with required for now. This breaks the input UI.');
86
- }
87
- return (React.createElement("div", { className: cx('ui-feedback', statusClassname, className, { small, narrow }) },
88
- React.createElement("div", { className: "custom-field" },
89
- label && (React.createElement(Label, { htmlFor: id, text: label, required: required, hasHint: Boolean(hint), disabled: disabled, small: small })),
90
- hint && React.createElement(Hint, { text: hint }),
91
- React.createElement("div", { className: "field-and-status-icon" },
92
- children,
93
- statusWithMessage && statusIconPosition === 'next-to-field' && (React.createElement(InputStatusIcon, { status: statusWithMessage.status, small: small, className: "next-to-field" }))),
94
- statusWithMessage && (React.createElement(StatusMessage, { testIdPrefix: "status-message", small: small, statusWithMessage: {
95
- ...statusWithMessage,
96
- tooltip: statusWithMessage?.tooltip ?? defaultTooltip,
97
- }, showIcon: statusIconPosition === 'before-status-message', onClose: onCloseStatusMessage })))));
98
- };
99
-
100
- const InputAffix = ({ value, type, disabled, readOnly }) => {
101
- const isContentWithCallback = typeof value === 'object' && value !== null && 'onClickCallback' in value;
102
- const spanContent = isContentWithCallback
103
- ? value.content
104
- : value;
105
- const wrapperProps = isContentWithCallback
106
- ? { onClick: value.onClickCallback }
107
- : {};
108
- return (React.createElement("div", { className: cx(`${type}-content-wrapper`, { disabled, 'read-only': readOnly }), ...wrapperProps },
109
- React.createElement("span", { className: `${type}-content` }, spanContent)));
110
- };
111
- const Input = React.forwardRef(({ id, label, type, hint, leadingContent, trailingContent, required, disabled = false, readOnly = false, statusWithMessage, narrow, inputFieldWrapperClassname = '', small = false, withIcons = [], onKeyUp, onBlur, onCloseStatusMessage, testIdPrefix, ...rest }, ref) => {
112
- const { handleKeyUp, handleBlur, isFocusByTab } = useFocusByTab({ onBlur, onKeyUp });
113
- return (React.createElement(FieldWrapper, { id: id, label: label, hint: hint, statusWithMessage: statusWithMessage, disabled: disabled, required: required, small: small, statusIconPosition: statusWithMessage?.tooltip || narrow ? 'before-status-message' : undefined, narrow: narrow, className: cx('ui-input-field-wrapper', inputFieldWrapperClassname), onCloseStatusMessage: onCloseStatusMessage },
114
- leadingContent && (React.createElement(InputAffix, { value: leadingContent, type: "leading", disabled: disabled, readOnly: readOnly })),
115
- React.createElement("div", { className: cx('input-container', {
116
- 'focused-by-tab': isFocusByTab,
117
- }) },
118
- React.createElement("input", { "data-testid": testIdPrefix ? `${testIdPrefix}-input` : undefined, ref: ref, className: cx('input', {
119
- 'with-leading-only': leadingContent && !trailingContent,
120
- 'with-trailing-only': trailingContent && !leadingContent,
121
- 'with-leading-and-trailing': leadingContent && trailingContent,
122
- [`with-icons-${withIcons.length}`]: withIcons.length > 0,
123
- [statusWithMessage?.status || '']: !!statusWithMessage,
124
- }), id: id, type: type, disabled: disabled, readOnly: readOnly, onKeyUp: handleKeyUp, onBlur: handleBlur, ...rest }),
125
- React.createElement("div", { className: cx('input-icons', {
126
- small,
127
- }) }, withIcons.map((iconConfig, index) => (React.createElement("span", { key: index, className: iconConfig?.className, onClick: iconConfig.action, "data-testid": testIdPrefix ? `${testIdPrefix}-icon` : undefined }, iconConfig.icon))))),
128
- trailingContent && (React.createElement(InputAffix, { value: trailingContent, type: "trailing", disabled: disabled, readOnly: readOnly }))));
129
- });
130
- Input.displayName = 'Input';
131
-
132
- /**
133
- * ComboBox component
134
- *
135
- * You can use the hook useDefaultComboBox to get the default behavior.
136
- * See the stories.
137
- *
138
- * When `allowCustomValue` is true, an option appears at the bottom of the dropdown
139
- * when the typed value doesn't match any existing suggestion.
140
- * Defocusing without selecting cancels the input.
141
- */
142
- const ComboBox = ({ suggestions, customLabel, numberOfSuggestionsToShow = 5, value, small, getSuggestionLabel, onChange, onSelectSuggestion, resetSuggestions, testIdPrefix, renderListElementComponent, renderFooterItem, allowCustomValue = false, onAddCustomValue, addCustomValueLabel, ...inputProps }) => {
143
- const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(-1);
144
- const [inputValue, setInputValue] = useState('');
145
- const [isInputFocused, setIsInputFocused] = useState(false);
146
- const suggestionRefs = useRef([]);
147
- const inputRef = useRef(null);
148
- const wrapperRef = useRef(null);
149
- const removeFocus = () => {
150
- setIsInputFocused(false);
151
- setActiveSuggestionIndex(-1);
152
- setTimeout(() => {
153
- inputRef.current?.blur();
154
- }, 0);
155
- resetSuggestions();
156
- };
157
- /* eslint-disable react-hooks/exhaustive-deps */
158
- const focusInput = useCallback(() => {
159
- if (isInputFocused) {
160
- removeFocus();
161
- }
162
- else {
163
- inputRef.current?.focus();
164
- }
165
- }, [inputRef, isInputFocused]);
166
- /* eslint-disable react-hooks/exhaustive-deps */
167
- useEffect(() => {
168
- if (value) {
169
- // TODO: fix this lint
170
- /* eslint-disable-next-line react-hooks/set-state-in-effect */
171
- setInputValue(getSuggestionLabel(value));
172
- }
173
- else {
174
- setInputValue('');
175
- }
176
- }, [value]);
177
- const showAddCustomValue = useMemo(() => {
178
- if (!allowCustomValue || !inputValue.trim())
179
- return false;
180
- return !suggestions.some((s) => getSuggestionLabel(s).toLowerCase() === inputValue.trim().toLowerCase());
181
- }, [allowCustomValue, inputValue, suggestions, getSuggestionLabel]);
182
- const showSuggestions = useMemo(() => isInputFocused && (suggestions.length > 0 || showAddCustomValue) && !inputProps.disabled, [isInputFocused, suggestions.length, showAddCustomValue, inputProps.disabled]);
183
- // behavior
184
- const handleInputChange = (e) => {
185
- onChange?.(e);
186
- setInputValue(e.currentTarget.value);
187
- };
188
- const selectSuggestion = (index) => {
189
- const selectedSuggestion = suggestions.at(index);
190
- onSelectSuggestion(selectedSuggestion);
191
- setInputValue(getSuggestionLabel(selectedSuggestion));
192
- removeFocus();
193
- };
194
- const confirmCustomValue = () => {
195
- const trimmed = inputValue.trim();
196
- if (!trimmed)
197
- return;
198
- onAddCustomValue?.(trimmed);
199
- removeFocus();
200
- };
201
- const closeSuggestions = () => {
202
- setInputValue(value ? getSuggestionLabel(value) : '');
203
- removeFocus();
204
- };
205
- const totalItems = suggestions.length + (showAddCustomValue ? 1 : 0);
206
- const customValueIndex = showAddCustomValue ? suggestions.length : -1;
207
- const handleKeyDown = (e) => {
208
- switch (e.key) {
209
- case 'ArrowDown': {
210
- setActiveSuggestionIndex((prev) => {
211
- const newIndex = prev < totalItems - 1 ? prev + 1 : prev;
212
- suggestionRefs.current[newIndex]?.scrollIntoView({ block: 'nearest' });
213
- return newIndex;
214
- });
215
- break;
216
- }
217
- case 'ArrowUp': {
218
- setActiveSuggestionIndex((prev) => {
219
- const newIndex = prev > 0 ? prev - 1 : prev;
220
- suggestionRefs.current[newIndex]?.scrollIntoView({ block: 'nearest' });
221
- return newIndex;
222
- });
223
- break;
224
- }
225
- case 'Enter': {
226
- e.preventDefault();
227
- if (activeSuggestionIndex === customValueIndex) {
228
- confirmCustomValue();
229
- }
230
- else if (activeSuggestionIndex >= 0) {
231
- selectSuggestion(activeSuggestionIndex);
232
- }
233
- else if (suggestions.length === 1) {
234
- selectSuggestion(0);
235
- }
236
- break;
237
- }
238
- case 'Tab': {
239
- if (activeSuggestionIndex === customValueIndex) {
240
- confirmCustomValue();
241
- }
242
- else if (activeSuggestionIndex >= 0) {
243
- selectSuggestion(activeSuggestionIndex);
244
- }
245
- break;
246
- }
247
- case 'Escape': {
248
- closeSuggestions();
249
- break;
250
- }
251
- }
252
- };
253
- const handleInputFocus = (e) => {
254
- e.stopPropagation();
255
- setIsInputFocused(true);
256
- };
257
- const clearInput = () => {
258
- setInputValue('');
259
- onSelectSuggestion(undefined);
260
- resetSuggestions();
261
- focusInput();
262
- };
263
- useOutsideClick(showSuggestions ? wrapperRef : null, // Only trigger when the suggestions are displayed
264
- closeSuggestions);
265
- const inputIcons = useMemo(() => {
266
- if (inputProps.readOnly || inputProps.disabled)
267
- return undefined;
268
- return [
269
- // Conditionally include the clear icon only when input is not empty
270
- ...(value
271
- ? [
272
- {
273
- icon: React.createElement(XCircle, { variant: "fill" }),
274
- action: clearInput,
275
- className: 'clear-icon',
276
- },
277
- ]
278
- : []),
279
- // chevron of the select
280
- {
281
- icon: React.createElement(ChevronDown, { size: small ? 'sm' : 'lg' }),
282
- action: focusInput,
283
- className: cx('chevron-icon', {
284
- disabled: inputProps.disabled,
285
- open: isInputFocused,
286
- }),
287
- },
288
- ];
289
- }, [
290
- inputProps.readOnly,
291
- inputProps.disabled,
292
- clearInput,
293
- value,
294
- small,
295
- focusInput,
296
- isInputFocused,
297
- ]);
298
- return (React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}` : undefined, className: "ui-combo-box", style: { '--number-of-suggestions': numberOfSuggestionsToShow }, ref: wrapperRef },
299
- customLabel && React.createElement("label", { htmlFor: inputProps.id }, customLabel),
300
- React.createElement(Input, { testIdPrefix: inputProps.id, ...inputProps, ref: inputRef, value: inputValue, onChange: handleInputChange, onKeyDown: handleKeyDown, onFocus: handleInputFocus, withIcons: inputIcons, small: small }),
301
- showSuggestions && (React.createElement("ul", { className: "suggestions-list", "data-testid": testIdPrefix ? `${testIdPrefix}-list` : undefined, onMouseLeave: () => setActiveSuggestionIndex(-1) },
302
- suggestions.map((suggestion, index) => (React.createElement("li", { ref: (el) => {
303
- if (suggestionRefs) {
304
- suggestionRefs.current[index] = el;
305
- }
306
- }, key: `${getSuggestionLabel(suggestion)}-${index}`, "data-testid": testIdPrefix ? `${testIdPrefix}-item` : undefined, className: cx('suggestion-item', {
307
- active: index === activeSuggestionIndex,
308
- selected: value && getSuggestionLabel(value) === getSuggestionLabel(suggestion),
309
- small,
310
- 'suggestion-item--custom': renderListElementComponent,
311
- }), onClick: () => selectSuggestion(index), onMouseEnter: () => setActiveSuggestionIndex(index) }, renderListElementComponent
312
- ? renderListElementComponent({
313
- suggestion,
314
- index,
315
- isActive: index === activeSuggestionIndex,
316
- isSelected: !!value && getSuggestionLabel(value) === getSuggestionLabel(suggestion),
317
- })
318
- : getSuggestionLabel(suggestion)))),
319
- showAddCustomValue && (React.createElement("li", { ref: (el) => {
320
- suggestionRefs.current[suggestions.length] = el;
321
- }, className: cx('suggestion-item', 'suggestion-item--add-custom', {
322
- active: activeSuggestionIndex === customValueIndex,
323
- small,
324
- }), onClick: confirmCustomValue, onMouseEnter: () => setActiveSuggestionIndex(customValueIndex), "data-testid": testIdPrefix ? `${testIdPrefix}-add-custom` : undefined }, addCustomValueLabel ?? `Add "${inputValue.trim()}"`)),
325
- renderFooterItem && renderFooterItem()))));
326
- };
327
-
328
- const normalizeString = (str) => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
329
- const defaultFilterSuggestions = (getSuggestionLabel, suggestions, query) => {
330
- const input = normalizeString(query).trim().toLowerCase();
331
- if (!input) {
332
- return suggestions;
333
- }
334
- const getSuggestionScore = (suggestion) => {
335
- const suggestionLabel = normalizeString(getSuggestionLabel(suggestion).toLowerCase());
336
- if (suggestionLabel.startsWith(input)) {
337
- return 2;
338
- }
339
- if (suggestionLabel.includes(input)) {
340
- return 1;
341
- }
342
- return 0;
343
- };
344
- return suggestions
345
- .map((suggestion) => ({
346
- suggestion,
347
- score: getSuggestionScore(suggestion),
348
- }))
349
- .filter(({ score }) => score > 0)
350
- .sort(({ score: scoreA }, { score: scoreB }) => scoreB - scoreA)
351
- .map(({ suggestion }) => suggestion);
352
- };
353
- const useDefaultComboBox = (suggestions, getSuggestionLabel) => {
354
- const [query, setQuery] = useState('');
355
- const filteredSuggestions = useMemo(() => defaultFilterSuggestions(getSuggestionLabel, suggestions, query),
356
- // eslint-disable-next-line react-hooks/exhaustive-deps
357
- [suggestions, query]);
358
- const onChange = (e) => {
359
- setQuery(e.target.value);
360
- };
361
- const resetSuggestions = () => {
362
- setQuery('');
363
- };
364
- return { suggestions: filteredSuggestions, onChange, resetSuggestions };
365
- };
366
-
367
- const Checkbox = ({ label, small, hint, disabled, checked, readOnly, isIndeterminate = false, onClick, children, ...rest }) => {
368
- const handleClick = (e) => {
369
- if (readOnly) {
370
- e.preventDefault();
371
- e.stopPropagation();
372
- }
373
- else {
374
- onClick?.(e);
375
- }
376
- };
377
- return (React.createElement("label", { className: cx('ui-checkbox', { small, 'with-label': label || children, 'with-hint': hint }) },
378
- React.createElement("input", {
379
- // Browsers' read-only attribute is not working on checkboxes. See: https://stackoverflow.com/a/70375659
380
- className: cx({ 'read-only': readOnly }), type: "checkbox", checked: checked, disabled: disabled, ref: (input) => {
381
- if (input) {
382
- input.indeterminate = isIndeterminate;
383
- }
384
- }, onClick: handleClick, ...rest }),
385
- label && React.createElement("div", { className: "label" }, label),
386
- children && React.createElement("div", { className: "label" }, children),
387
- hint && React.createElement("span", { className: "hint" }, hint)));
388
- };
389
-
390
- const CheckboxList = (checkBoxListprops) => {
391
- const { items, onClickItem, small = false, label = '', readOnly = false, disabled = false, } = checkBoxListprops;
392
- return (React.createElement(React.Fragment, null,
393
- React.createElement("span", { className: "checkbox-list-label" }, label),
394
- React.createElement("ul", { className: cx('checkbox-list', { small: small }) }, items.map((item) => {
395
- const { id, props, items: subItems } = item;
396
- return (React.createElement("li", { key: id },
397
- React.createElement(Checkbox, { small: small, onClick: (e) => onClickItem(e, item), checked: item.props.checked, isIndeterminate: item.props.isIndeterminate, ...props, disabled: disabled, readOnly: readOnly }),
398
- subItems && React.createElement(CheckboxList, { ...checkBoxListprops, items: subItems })));
399
- }))));
400
- };
401
-
402
- var CheckboxState;
403
- (function (CheckboxState) {
404
- CheckboxState[CheckboxState["UNCHECKED"] = 0] = "UNCHECKED";
405
- CheckboxState[CheckboxState["CHECKED"] = 1] = "CHECKED";
406
- CheckboxState[CheckboxState["INDETERMINATE"] = 2] = "INDETERMINATE";
407
- })(CheckboxState || (CheckboxState = {}));
408
-
409
- const traverseTree = (items, onVisit, parent) => {
410
- items.forEach((item) => {
411
- onVisit(item, parent);
412
- if (item.items && item.items.length > 0) {
413
- traverseTree(item.items, onVisit, item);
414
- }
415
- });
416
- };
417
- const buildRelationshipMaps = (items) => {
418
- const parentChildrenMap = {};
419
- const childrenParentMap = {};
420
- traverseTree(items, (item, parent) => {
421
- if (parent?.id !== undefined) {
422
- if (!parentChildrenMap[parent.id]) {
423
- parentChildrenMap[parent.id] = [];
424
- }
425
- parentChildrenMap[parent.id].push(item.id);
426
- childrenParentMap[item.id] = parent.id;
427
- }
428
- });
429
- return { parentChildrenMap, childrenParentMap };
430
- };
431
- const updateItemAndDescendantsStates = (itemId, newItemStates, parentChildrenMap, itemStates) => {
432
- itemStates[itemId] = newItemStates;
433
- parentChildrenMap[itemId]?.forEach((child) => updateItemAndDescendantsStates(child, newItemStates, parentChildrenMap, itemStates));
434
- };
435
- const updateAscendantsStates = (childId, itemStates, relastionShipMap) => {
436
- const { parentChildrenMap, childrenParentMap } = relastionShipMap;
437
- const parentId = childrenParentMap[childId];
438
- if (parentId === undefined)
439
- return;
440
- const siblings = parentChildrenMap[parentId];
441
- const siblingStates = siblings.map((siblingId) => itemStates[siblingId]);
442
- let parentState;
443
- if (siblingStates.every((state) => state === CheckboxState.CHECKED)) {
444
- parentState = CheckboxState.CHECKED;
445
- }
446
- else if (siblingStates.every((state) => state === CheckboxState.UNCHECKED)) {
447
- parentState = CheckboxState.UNCHECKED;
448
- }
449
- else {
450
- parentState = CheckboxState.INDETERMINATE;
451
- }
452
- itemStates[parentId] = parentState;
453
- updateAscendantsStates(parentId, itemStates, { parentChildrenMap, childrenParentMap });
454
- };
455
- const updateItemStates = (itemsTree, initialItemStates, clickedItemId) => {
456
- const newItemStates = { ...initialItemStates };
457
- const newClickedItemState = newItemStates[clickedItemId] === CheckboxState.CHECKED
458
- ? CheckboxState.UNCHECKED
459
- : CheckboxState.CHECKED;
460
- const { parentChildrenMap, childrenParentMap } = buildRelationshipMaps(itemsTree);
461
- updateItemAndDescendantsStates(clickedItemId, newClickedItemState, parentChildrenMap, newItemStates);
462
- updateAscendantsStates(clickedItemId, newItemStates, { parentChildrenMap, childrenParentMap });
463
- return newItemStates;
464
- };
465
- const computeInitialItemStates = (items) => {
466
- const itemStates = {};
467
- traverseTree(items, (item) => {
468
- if (item.props.isIndeterminate)
469
- itemStates[item.id] = CheckboxState.INDETERMINATE;
470
- else
471
- itemStates[item.id] = item.props.checked ? CheckboxState.CHECKED : CheckboxState.UNCHECKED;
472
- });
473
- return itemStates;
474
- };
475
- const applyStateToItem = (itemsTree, itemStates) => {
476
- const clonedItemsTree = JSON.parse(JSON.stringify(itemsTree));
477
- traverseTree(clonedItemsTree, (item) => {
478
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
479
- const { checked, isIndeterminate, ...otherProps } = item.props;
480
- item.props = otherProps;
481
- if (itemStates[item.id] === CheckboxState.INDETERMINATE)
482
- item.props.isIndeterminate = true;
483
- else if (itemStates[item.id] === CheckboxState.CHECKED)
484
- item.props.checked = true;
485
- else
486
- item.props.checked = false;
487
- });
488
- return clonedItemsTree;
489
- };
490
- const computeNewItemsTree = (itemsTree, clickedItem) => {
491
- const initialItemStates = computeInitialItemStates(itemsTree);
492
- const updatedItemStates = updateItemStates(itemsTree, initialItemStates, clickedItem.id);
493
- return applyStateToItem(itemsTree, updatedItemStates);
494
- };
495
-
496
- const CheckboxesTree = ({ items, small, id, label, hint, statusWithMessage, disabled, required, readOnly, onChange, computeNewItemsTree: computeNewItemsTree$1, }) => {
497
- const handleClick = (e, item) => {
498
- const newItems = computeNewItemsTree$1
499
- ? computeNewItemsTree$1(items, item)
500
- : computeNewItemsTree(items, item);
501
- onChange?.(newItems, item);
502
- item.props.onClick?.(e);
503
- };
504
- return (React.createElement(FieldWrapper, { id: id, label: label, hint: hint, statusWithMessage: statusWithMessage, statusIconPosition: "before-status-message", disabled: disabled, required: required, small: small },
505
- React.createElement(CheckboxList, { small: small, items: items, disabled: disabled, readOnly: readOnly, onClickItem: handleClick })));
506
- };
507
-
508
- const useModalPosition = (inputRef, modalRef, offset = 3 // Default offset below the input
509
- ) => {
510
- const [modalPosition, setModalPosition] = useState({
511
- top: 0,
512
- left: 0,
513
- });
514
- const calculatePosition = useCallback(() => {
515
- if (inputRef.current && modalRef.current) {
516
- const inputRect = inputRef.current.getBoundingClientRect();
517
- const modal = modalRef.current;
518
- const modalRect = modal.getBoundingClientRect();
519
- const offsetParent = modal.offsetParent;
520
- const parentRect = offsetParent ? offsetParent.getBoundingClientRect() : { top: 0, left: 0 };
521
- // Adjust the top position: place it below the input while considering an offset
522
- const top = inputRect.bottom - parentRect.top - offset;
523
- // Center the modal horizontally relative to the input
524
- const modalViewportLeft = inputRect.left + (inputRect.width - modalRect.width) / 2;
525
- // Keep modal to stay within viewport bounds
526
- const adjustedViewportLeft = Math.max(0, Math.min(modalViewportLeft, window.innerWidth - modalRect.width));
527
- const left = adjustedViewportLeft - parentRect.left;
528
- setModalPosition({ top, left });
529
- }
530
- }, [inputRef, modalRef, offset]);
531
- useEffect(() => {
532
- calculatePosition();
533
- const handleResize = () => calculatePosition();
534
- window.addEventListener('resize', handleResize);
535
- return () => window.removeEventListener('resize', handleResize);
536
- }, [calculatePosition]);
537
- return { modalPosition, calculatePosition };
538
- };
539
-
540
- const InputModal = ({ inputRef, isOpen, onClose, children, testIdPrefix }) => {
541
- const modalRef = useRef(null);
542
- const { modalPosition, calculatePosition } = useModalPosition(inputRef, modalRef);
543
- useEffect(() => {
544
- if (isOpen) {
545
- calculatePosition();
546
- }
547
- }, [calculatePosition, isOpen]);
548
- useOutsideClick(modalRef, onClose);
549
- if (!isOpen)
550
- return null;
551
- return (React.createElement("div", { className: "ui-input-modal-overlay" },
552
- React.createElement("div", { ref: modalRef, className: "modal-content", style: { top: modalPosition.top, left: modalPosition.left } },
553
- React.createElement("button", { "data-testid": testIdPrefix ? `${testIdPrefix}-close-button` : undefined, className: "close-button", onClick: onClose },
554
- React.createElement(X, { size: "lg" })),
555
- children)));
556
- };
557
-
558
- const INVALID_SELECTED_SLOT_ERROR = 'Invalid selectedSlot: If start and end are defined, the start date must be before the end date.';
559
- const INVALID_SELECTABLE_SLOT_ERROR = 'Invalid selectableSlot: If start and end are defined, the start date must be before the end date.';
560
- const INVALID_SELECTED_SLOT_BASED_ON_SELECTABLE_SLOT_ERROR = 'selectedSlot must be within selectableSlot';
561
- const INVALID_INITIAL_DATE_ERROR = 'initialDate must be within selectableSlot';
562
- const containsOnlyNumbersAndSlashes = (s) => /^[0-9/]+$/.test(s);
563
- /**
564
- * Normalize the given date to midnight
565
- * @param date The date to normalize
566
- * @returns The normalized date
567
- */
568
- function normalizeDate(date) {
569
- return new Date(date.getFullYear(), date.getMonth(), date.getDate());
570
- }
571
- /**
572
- * Check if the given slot is valid
573
- * @param slot The slot to check
574
- * @returns True if the slot is valid, false otherwise
575
- */
576
- function isValidSlot(slot) {
577
- if (slot.start && slot.end) {
578
- return normalizeDate(slot.start).getTime() <= normalizeDate(slot.end).getTime();
579
- }
580
- return true;
581
- }
582
- /**
583
- * Get the dates from the previous month that are in the first week of the current month
584
- * @param month The month of the current date
585
- * @param fullYear The year of the current date
586
- * @returns An array of dates from the previous month that are in the first week of the current month
587
- */
588
- function getDatesFromPreviousMonthInFirstWeek(month, fullYear) {
589
- const firstDayOfMonth = new Date(fullYear, month, 1);
590
- const firstDayOfWeek = firstDayOfMonth.getDay();
591
- // if the first day of the week is Monday, we don't need to return any dates from the previous month
592
- if (firstDayOfWeek === 1) {
593
- return [];
594
- }
595
- const daysFromPrevMonth = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1;
596
- const lastDayPrevMonth = new Date(fullYear, month, 0);
597
- const dates = [];
598
- for (let i = 0; i < daysFromPrevMonth; i++) {
599
- const day = lastDayPrevMonth.getDate() - i;
600
- dates.unshift(new Date(lastDayPrevMonth.getFullYear(), lastDayPrevMonth.getMonth(), day));
601
- }
602
- return dates;
603
- }
604
- /**
605
- * Get the dates from the next month that are in the last week of the current month
606
- * @param month The month of the current date
607
- * @param fullYear The year of the current date
608
- * @returns An array of dates from the next month that are in the last week of the current month
609
- */
610
- function getDatesFromNextMonthInLastWeek(month, fullYear) {
611
- const lastDayOfMonth = new Date(fullYear, month + 1, 0);
612
- const lastDayOfWeek = lastDayOfMonth.getDay();
613
- const daysFromNextMonth = (7 - lastDayOfWeek) % 7;
614
- if (daysFromNextMonth === 0) {
615
- return [];
616
- }
617
- const nextMonth = new Date(fullYear, month + 1, 1);
618
- const dates = [];
619
- for (let i = 0; i < daysFromNextMonth; i++) {
620
- const day = i + 1;
621
- dates.push(new Date(nextMonth.getFullYear(), nextMonth.getMonth(), day));
622
- }
623
- return dates;
624
- }
625
- /**
626
- * Get all the dates in the month of the given date
627
- * @param month The month of the current date
628
- * @param fullYear The year of the current date
629
- * @returns An array of all the dates in the month of the given date
630
- */
631
- function getAllDatesInMonth(month, fullYear) {
632
- const lastDayOfMonth = new Date(fullYear, month + 1, 0);
633
- const totalDaysInMonth = lastDayOfMonth.getDate();
634
- const dates = [];
635
- for (let day = 1; day <= totalDaysInMonth; day++) {
636
- dates.push(new Date(fullYear, month, day));
637
- }
638
- return dates;
639
- }
640
- /**
641
- * Check if the given dates are the same day
642
- * @param date1 The first date
643
- * @param date2 The second date
644
- * @returns True if the dates are the same day, false otherwise
645
- */
646
- function isSameDay(date1, date2) {
647
- if (!date1 || !date2) {
648
- return false;
649
- }
650
- return (date1.getDate() === date2.getDate() &&
651
- date1.getMonth() === date2.getMonth() &&
652
- date1.getFullYear() === date2.getFullYear());
653
- }
654
- /**
655
- * Check if the given date is within the given slot
656
- * if the slot is not provided, the date is considered to be within the slot
657
- * if a boundary of the slot is not provided, it's considered to be an open boundary
658
- * @param date The date to check
659
- * @param slot The slot to check
660
- * @returns True if the date is within the slot, false otherwise
661
- */
662
- function isWithinInterval(date, slot) {
663
- if (!slot)
664
- return true;
665
- const normalizedDate = normalizeDate(date);
666
- const normalizedStart = slot.start ? normalizeDate(slot.start) : undefined;
667
- const normalizedEnd = slot.end ? normalizeDate(slot.end) : undefined;
668
- const isAfterStart = normalizedStart ? normalizedDate >= normalizedStart : true;
669
- const isBeforeEnd = normalizedEnd ? normalizedDate <= normalizedEnd : true;
670
- return isAfterStart && isBeforeEnd;
671
- }
672
- /**
673
- * Generates a list of dates, each representing the start of a month,
674
- * starting from a given date and continuing for a specified number of months.
675
- * This function correctly handles year rollover.
676
- * @param startDate - The date from which to start generating month start dates.
677
- * @param monthsCount - The number of month start dates to generate.
678
- * @returns An array of Dates, each set to the first day of consecutive months starting from startDate.
679
- */
680
- function generateSequentialDates(startDate, monthsCount) {
681
- const dates = [];
682
- for (let i = 0; i < monthsCount; i++) {
683
- const date = new Date(startDate);
684
- date.setMonth(startDate.getMonth() + i, 1);
685
- dates.push(new Date(date.getFullYear(), date.getMonth(), 1));
686
- }
687
- return dates;
688
- }
689
- /**
690
- * Format the given date as a string in the format 'dd/mm/yy'.
691
- * @param date The date to format
692
- * @returns The formatted date string
693
- */
694
- function formatDateString(date) {
695
- if (!date)
696
- return '';
697
- const day = String(date.getDate()).padStart(2, '0');
698
- const month = String(date.getMonth() + 1).padStart(2, '0');
699
- const year = String(date.getFullYear()).slice(-2);
700
- return `${day}/${month}/${year}`;
701
- }
702
- /**
703
- * Handles the logic for when a day is clicked on the calendar.
704
- *
705
- * @param clickedDate - The date that was clicked.
706
- * @param isRangeMode - Whether the calendar is in range mode.
707
- * @param prevSelectedSlot - The previously selected slot.
708
- * Spec 1: If the user clicks on a single date, that date is set as the start date of the slot.
709
- * Spec 2: If the user selects the same end date as the start date, clear the slot
710
- * Spec 3: If the user clicks on a date that is before the currently selected start date, the new date becomes the start date and the previous start date becomes the end date.
711
- * Spec 4: If the user clicks on a date that is after the currently selected start date, that date becomes the end date of the slot.
712
- * Spec 5: If a slot is already defined (i.e., both start and end dates are defined) and the user clicks on a new date, the existing slot is cleared and the new date becomes the start date of the new slot.
713
- */
714
- function computeNewSelectedSlot(clickedDate, prevSelectedSlot) {
715
- if (!prevSelectedSlot || prevSelectedSlot?.start === null) {
716
- // Spec 1
717
- return { start: clickedDate, end: null };
718
- }
719
- else if (!prevSelectedSlot.end) {
720
- if (normalizeDate(clickedDate).getTime() === normalizeDate(prevSelectedSlot.start).getTime()) {
721
- // Spec 2
722
- return undefined;
723
- }
724
- else if (normalizeDate(clickedDate) < normalizeDate(prevSelectedSlot.start)) {
725
- // Spec 3
726
- return { start: clickedDate, end: prevSelectedSlot.start };
727
- }
728
- else {
729
- // Spec 4
730
- return { start: prevSelectedSlot.start, end: clickedDate };
731
- }
732
- }
733
- else {
734
- // Spec 5
735
- return { start: clickedDate, end: null };
736
- }
737
- }
738
- /**
739
- * Format the selected slot to a string that can be displayed in the input field.
740
- * @param slot The new selected slot
741
- * @returns The formatted string
742
- * Spec 0: If the slot is undefined, return an empty string.
743
- * Spec 1: If the start and end dates are the same, return the formatted date of the start date.
744
- * Spec 2: If the start and end dates are in the same year, return the formatted start date without the year and end date.
745
- * Spec 3: If the start and end dates are in different years, return the formatted start date and end date with the year.
746
- */
747
- function formatSlotToInputValue(slot) {
748
- let formattedDate = '';
749
- if (slot) {
750
- const { start, end } = slot;
751
- if (isSameDay(start, end)) {
752
- formattedDate = formatDateString(start);
753
- }
754
- else {
755
- let formattedStartDate = formatDateString(start);
756
- if (start && end && start.getFullYear() === end.getFullYear()) {
757
- formattedStartDate = formattedStartDate.slice(0, 5);
758
- }
759
- formattedDate = `${formattedStartDate} - ${formatDateString(end)}`;
760
- }
761
- }
762
- return formattedDate;
763
- }
764
- /**
765
- * Format the new value to a string that can be displayed in the input field.
766
- * @param value The new value
767
- * @param isRangeMode Whether the calendar is in range mode
768
- * @returns The formatted string
769
- */
770
- function formatInputValue({ value, isRangeMode }) {
771
- if (isRangeMode) {
772
- return formatSlotToInputValue(value);
773
- }
774
- return formatDateString(value);
775
- }
776
- function formatValueToSlot({ value, isRangeMode }) {
777
- if (isRangeMode) {
778
- return value;
779
- }
780
- return value ? { start: value, end: value } : value;
781
- }
782
- /**
783
- * Validates the selected and selectable slots as well as the initial date.
784
- * @param selectedSlot The selected slot to validate.
785
- * @param selectableSlot The selectable slot to validate.
786
- * @param date The date to validate.
787
- *
788
- * Three main validation checks are performed:
789
- * - Check if the selected and selectable slots are valid.
790
- * - Ensures the selected slot is within the selectable slot.
791
- * - Ensures the initial date is within the selectable slot
792
- */
793
- function validateSlots(selectedSlot, selectableSlot, date) {
794
- if (selectedSlot && !isValidSlot(selectedSlot)) {
795
- throw new Error(INVALID_SELECTED_SLOT_ERROR);
796
- }
797
- if (selectableSlot && !isValidSlot(selectableSlot)) {
798
- throw new Error(INVALID_SELECTABLE_SLOT_ERROR);
799
- }
800
- if (selectedSlot?.start &&
801
- selectedSlot?.end &&
802
- selectableSlot?.start &&
803
- selectableSlot?.end &&
804
- (normalizeDate(selectedSlot.start) < normalizeDate(selectableSlot.start) ||
805
- normalizeDate(selectedSlot.end) > normalizeDate(selectableSlot.end))) {
806
- throw new Error(INVALID_SELECTED_SLOT_BASED_ON_SELECTABLE_SLOT_ERROR);
807
- }
808
- if (date &&
809
- selectableSlot?.start &&
810
- selectableSlot?.end &&
811
- (normalizeDate(date) < normalizeDate(selectableSlot.start) ||
812
- normalizeDate(date) > normalizeDate(selectableSlot.end))) {
813
- throw new Error(INVALID_INITIAL_DATE_ERROR);
814
- }
815
- }
816
-
817
- function useCalendar({ displayedMonthStartDate, selectableSlot, selectedSlot, }) {
818
- const now = new Date();
819
- now.setHours(0, 0, 0, 0);
820
- const referenceDate = selectableSlot?.start ?? now;
821
- referenceDate.setHours(0, 0, 0, 0);
822
- const displayedYear = displayedMonthStartDate.getFullYear();
823
- const displayedMonth = displayedMonthStartDate.getMonth();
824
- const daysInMonth = getAllDatesInMonth(displayedMonth, displayedYear);
825
- const daysInLastMonth = getDatesFromPreviousMonthInFirstWeek(displayedMonth, displayedYear);
826
- const daysInNextMonth = getDatesFromNextMonthInLastWeek(displayedMonth, displayedYear);
827
- const allDays = [...daysInLastMonth, ...daysInMonth, ...daysInNextMonth];
828
- const buildDayWrapperClassName = (date) => {
829
- const isStart = (selectedSlot && isSameDay(date, selectedSlot.start)) || false;
830
- const isEnd = (selectedSlot && isSameDay(date, selectedSlot.end)) || false;
831
- const withinSelectedSlot = (selectedSlot?.start && selectedSlot.end && isWithinInterval(date, selectedSlot)) ||
832
- isStart ||
833
- isEnd;
834
- const insideSelectableSlot = isWithinInterval(date, selectableSlot);
835
- let classNames = {
836
- 'inside-selectable-slot': insideSelectableSlot,
837
- 'outside-selectable-slot': !insideSelectableSlot,
838
- 'current-month': date.getMonth() === displayedMonth,
839
- past: normalizeDate(date) < normalizeDate(referenceDate),
840
- };
841
- if (selectedSlot) {
842
- classNames = {
843
- ...classNames,
844
- start: isStart,
845
- end: isEnd,
846
- 'within-selected-slot': withinSelectedSlot,
847
- };
848
- }
849
- return cx('day-wrapper', classNames);
850
- };
851
- const isDateSelectable = (date) => isWithinInterval(date, selectableSlot);
852
- return {
853
- days: allDays,
854
- isToday: (date) => normalizeDate(date).getTime() === normalizeDate(now).getTime(),
855
- buildDayWrapperClassName,
856
- isDateSelectable,
857
- };
858
- }
859
-
860
- const WEEKDAY_LABELS = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
861
- const Day = ({ date, isToday, isSelectable, dayWrapperClassName, onClick }) => (React.createElement("div", { onClick: () => {
862
- if (isSelectable)
863
- onClick(date);
864
- }, className: "day-background" },
865
- React.createElement("div", { className: dayWrapperClassName },
866
- React.createElement("span", { className: "day" }, date.getDate()),
867
- isToday && React.createElement("span", { className: "current-date-highlight" }))));
868
- const Calendar = (props) => {
869
- const { days, isToday, isDateSelectable, buildDayWrapperClassName } = useCalendar(props);
870
- const { displayedMonthStartDate, onDayClick } = props;
871
- return (React.createElement("div", { className: "calendar-wrapper" },
872
- React.createElement("div", { className: "calendar-anatomy" },
873
- React.createElement("p", { className: "calendar-month-label" }, displayedMonthStartDate.toLocaleString('en-GB', { month: 'short' })),
874
- React.createElement("div", { className: "calendar-grid-wrapper" },
875
- React.createElement("div", { className: "calendar-weekday-labels" }, WEEKDAY_LABELS.map((label, index) => (React.createElement("p", { key: `${label}-${index}` }, label)))),
876
- React.createElement("div", { className: "calendar-days-grid" }, days.map((date) => (React.createElement(Day, { key: date.getTime(), date: date, isToday: isToday(date), isSelectable: isDateSelectable(date), dayWrapperClassName: buildDayWrapperClassName(date), onClick: onDayClick }))))))));
877
- };
878
-
879
- function useCalendarPicker({ initialDate, selectedSlot, selectableSlot, numberOfMonths = 1, }) {
880
- validateSlots(selectedSlot, selectableSlot, initialDate);
881
- const [activeDate, setActiveDate] = useState(new Date());
882
- const displayedMonthsStartDates = generateSequentialDates(activeDate, numberOfMonths);
883
- const activeYear = activeDate.getFullYear();
884
- const activeMonth = activeDate.getMonth();
885
- const firstDayOfMonth = new Date(activeYear, activeMonth, 1);
886
- const lastDayOfMonth = new Date(activeYear, activeMonth + 1, 0);
887
- const canGoToPreviousMonth = selectableSlot === undefined || selectableSlot.start === null
888
- ? true
889
- : selectableSlot.start < firstDayOfMonth;
890
- const canGoToNextMonth = selectableSlot === undefined || selectableSlot.end === null
891
- ? true
892
- : selectableSlot.end > lastDayOfMonth;
893
- const showNavigationBtn = canGoToPreviousMonth || canGoToNextMonth;
894
- const handleGoToPreviousMonth = () => {
895
- if (canGoToPreviousMonth) {
896
- const previousActiveMonth = activeMonth === 0 ? 11 : activeMonth - 1;
897
- const previousActiveYear = activeMonth === 0 ? activeYear - 1 : activeYear;
898
- setActiveDate(new Date(previousActiveYear, previousActiveMonth, 1));
899
- }
900
- };
901
- const handleGoToNextMonth = () => {
902
- if (canGoToNextMonth) {
903
- const nextActiveMonth = activeMonth === 11 ? 0 : activeMonth + 1;
904
- const nextActiveYear = activeMonth === 11 ? activeYear + 1 : activeYear;
905
- setActiveDate(new Date(nextActiveYear, nextActiveMonth, 1));
906
- }
907
- };
908
- useEffect(() => {
909
- // TODO: fix this lint
910
- // eslint-disable-next-line react-hooks/set-state-in-effect
911
- setActiveDate(initialDate ?? selectedSlot?.start ?? selectableSlot?.start ?? new Date());
912
- }, [initialDate, selectedSlot, selectableSlot]);
913
- return {
914
- displayedMonthsStartDates,
915
- showNavigationBtn,
916
- canGoToPreviousMonth,
917
- canGoToNextMonth,
918
- handleGoToPreviousMonth,
919
- handleGoToNextMonth,
920
- };
921
- }
922
-
923
- const CalendarPicker = ({ initialDate, selectedSlot, selectableSlot, numberOfMonths = 1, onDayClick, modalPosition, calendarPickerRef, }) => {
924
- const { displayedMonthsStartDates, showNavigationBtn, canGoToNextMonth, canGoToPreviousMonth, handleGoToNextMonth, handleGoToPreviousMonth, } = useCalendarPicker({
925
- initialDate,
926
- selectedSlot,
927
- selectableSlot,
928
- numberOfMonths,
929
- });
930
- return (React.createElement("div", { ref: calendarPickerRef, className: "calendar-picker", style: modalPosition },
931
- showNavigationBtn && (React.createElement("span", { className: cx('calendar-navigation-btn', 'previous', {
932
- disabled: !canGoToPreviousMonth,
933
- }), onClick: handleGoToPreviousMonth },
934
- React.createElement(ChevronLeft, { size: "lg" }))),
935
- React.createElement("div", { className: cx('calendar-list', { 'navigation-btn-hidden': !showNavigationBtn }) }, displayedMonthsStartDates.map((date) => (React.createElement(Calendar, { key: date.getTime(), displayedMonthStartDate: date, selectableSlot: selectableSlot, selectedSlot: selectedSlot, onDayClick: onDayClick })))),
936
- showNavigationBtn && (React.createElement("span", { className: cx('calendar-navigation-btn', 'next', {
937
- disabled: !canGoToNextMonth,
938
- }), onClick: handleGoToNextMonth },
939
- React.createElement(ChevronRight, { size: "lg" })))));
940
- };
941
-
942
- const MODAL_VERTICAL_OFFSET = 3;
943
- // Regex for "xx/xx/xx"
944
- const SINGLE_DATE_REGEX = /^\d{2}\/\d{2}\/\d{2}$/;
945
- function useDatePicker(datePickerProps) {
946
- const { value, isRangeMode, selectableSlot, errorMessages, onDateChange } = datePickerProps;
947
- const [showPicker, setShowPicker] = useState(false);
948
- const [inputValue, setInputValue] = useState(formatInputValue(datePickerProps));
949
- const [selectedSlot, setSelectedSlot] = useState(formatValueToSlot(datePickerProps));
950
- const [statusWithMessage, setStatusWithMessage] = useState();
951
- const calendarPickerRef = useRef(null);
952
- const inputRef = useRef(null);
953
- useOutsideClick(calendarPickerRef, (e) => {
954
- // Do not close the picker if any children in input wrapper is clicked.
955
- // This wrapper include, the input itself, the trailing content (which contains the calendar icon) and the leading content
956
- if (inputRef.current &&
957
- inputRef.current.parentElement?.parentElement?.contains(e.target))
958
- return;
959
- setShowPicker(false);
960
- });
961
- const { calculatePosition, modalPosition } = useModalPosition(inputRef, calendarPickerRef, MODAL_VERTICAL_OFFSET);
962
- const handleInputClick = () => {
963
- if (isRangeMode) {
964
- setShowPicker(true);
965
- }
966
- };
967
- const handleDayClick = (clickedDate) => {
968
- if (isRangeMode) {
969
- const newSelectedSlot = computeNewSelectedSlot(clickedDate, value);
970
- onDateChange(clickedDate, newSelectedSlot);
971
- }
972
- else {
973
- onDateChange(clickedDate);
974
- }
975
- };
976
- const handleInputOnChange = (newValue) => {
977
- if (isRangeMode) {
978
- return;
979
- }
980
- setInputValue(newValue);
981
- const inputIsDate = SINGLE_DATE_REGEX.test(newValue);
982
- if (inputIsDate) {
983
- const [day, month, year] = newValue.split('/').map(Number);
984
- const date = new Date(year + 2000, month - 1, day);
985
- const isRealDate = !Number.isNaN(date.getTime());
986
- const isValid = isRealDate && isWithinInterval(date, selectableSlot);
987
- if (isValid) {
988
- setStatusWithMessage(undefined);
989
- onDateChange(date);
990
- }
991
- else {
992
- setStatusWithMessage({ status: 'error', message: errorMessages?.invalidDate });
993
- onDateChange(undefined);
994
- }
995
- return;
996
- }
997
- if (containsOnlyNumbersAndSlashes(newValue) && newValue.length < 8) {
998
- setStatusWithMessage(undefined);
999
- onDateChange(undefined);
1000
- return;
1001
- }
1002
- onDateChange(undefined);
1003
- setStatusWithMessage({
1004
- status: 'error',
1005
- message: errorMessages?.invalidInput,
1006
- });
1007
- };
1008
- useEffect(() => {
1009
- if (showPicker)
1010
- calculatePosition();
1011
- }, [showPicker, calculatePosition]);
1012
- useEffect(() => {
1013
- const newInput = formatInputValue(datePickerProps);
1014
- if (newInput !== inputValue) {
1015
- // we only set the input value if it has changed
1016
- // otherwise the user loses the focus
1017
- // TODO: fix this lint
1018
- /* eslint-disable-next-line react-hooks/set-state-in-effect */
1019
- setInputValue(newInput);
1020
- }
1021
- setStatusWithMessage(undefined);
1022
- setSelectedSlot(formatValueToSlot(datePickerProps));
1023
- // eslint-disable-next-line react-hooks/exhaustive-deps
1024
- }, [value]);
1025
- return {
1026
- showPicker,
1027
- inputValue,
1028
- statusWithMessage,
1029
- selectedSlot,
1030
- modalPosition,
1031
- inputRef,
1032
- calendarPickerRef,
1033
- setShowPicker,
1034
- handleDayClick,
1035
- handleInputClick,
1036
- handleInputOnChange,
1037
- };
1038
- }
1039
-
1040
- const DatePicker = (props) => {
1041
- const { inputValue, statusWithMessage, selectedSlot, showPicker, modalPosition, inputRef, calendarPickerRef, setShowPicker, handleDayClick, handleInputClick, handleInputOnChange, } = useDatePicker(props);
1042
- const { inputFieldWrapperClassname, ...otherInputProps } = props.inputProps;
1043
- const { selectableSlot } = props;
1044
- const { testIdPrefix } = props;
1045
- return (React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}` : undefined, className: "ui-date-picker" },
1046
- React.createElement("div", null,
1047
- React.createElement(Input, { testIdPrefix: testIdPrefix, ...otherInputProps, ref: inputRef, value: inputValue, onClick: handleInputClick, type: "text", trailingContent: {
1048
- content: React.createElement(Calendar$1, null),
1049
- onClickCallback: () => setShowPicker(!showPicker),
1050
- }, inputFieldWrapperClassname: cx('date-picker-input', inputFieldWrapperClassname, {
1051
- 'range-mode': props.isRangeMode,
1052
- }), autoComplete: "off", onChange: (e) => handleInputOnChange(e.target.value), statusWithMessage: statusWithMessage })),
1053
- React.createElement(InputModal, { inputRef: inputRef, isOpen: showPicker, onClose: () => setShowPicker(false), testIdPrefix: "modal" },
1054
- React.createElement("div", { className: "calendar-picker-wrapper" },
1055
- React.createElement(CalendarPicker, { ...props.calendarPickerProps, selectedSlot: selectedSlot, onDayClick: handleDayClick, modalPosition: modalPosition, calendarPickerRef: calendarPickerRef, selectableSlot: selectableSlot })))));
1056
- };
1057
-
1058
- const PasswordInput = React.forwardRef(({ inputFieldWrapperClassname, ...otherProps }, ref) => {
1059
- const [showPassword, toggleShowPassword] = useState(false);
1060
- return (React.createElement(Input, { ...otherProps, type: showPassword ? 'text' : 'password', trailingContent: {
1061
- content: showPassword ? React.createElement(EyeClosed, null) : React.createElement(Eye, null),
1062
- onClickCallback: () => toggleShowPassword(!showPassword),
1063
- }, inputFieldWrapperClassname: cx('ui-password-input', inputFieldWrapperClassname), ref: ref }));
1064
- });
1065
- PasswordInput.displayName = 'PasswordInput';
1066
-
1067
- const RadioButton = ({ id, label, value, hint, readOnly, onBlur, onKeyUp, small, ...rest }) => {
1068
- const { handleKeyUp, handleBlur, isFocusByTab } = useFocusByTab({ onBlur, onKeyUp });
1069
- return (React.createElement("div", { className: cx('ui-radio-button', { 'read-only': readOnly, small }), tabIndex: 0 },
1070
- React.createElement("div", { className: "radio-container" },
1071
- React.createElement("input", { className: "radio-input", id: id || value, type: "radio", value: value, tabIndex: -1, onBlur: handleBlur, onKeyUp: handleKeyUp, ...rest }),
1072
- React.createElement("span", { className: cx('checkmark', { focused: isFocusByTab }) }),
1073
- React.createElement("label", { htmlFor: id || value, className: "radio-label" }, label)),
1074
- hint && React.createElement("div", { className: "hint" }, hint)));
1075
- };
1076
-
1077
- const RadioGroup = ({ label, value, subtitle, readOnly, disabled, options, statusWithMessage, required, small, onChange, }) => {
1078
- const [selectedValue, setSelectedValue] = useState(value);
1079
- useEffect(() => {
1080
- /* eslint-disable-next-line react-hooks/set-state-in-effect */
1081
- setSelectedValue(value);
1082
- }, [value]);
1083
- const statusClassname = statusWithMessage?.status ? { [statusWithMessage.status]: true } : {};
1084
- const handleOptionChange = (e, nextOption) => {
1085
- if (!readOnly) {
1086
- setSelectedValue(nextOption.value);
1087
- nextOption.onChange?.(e);
1088
- onChange?.(nextOption.value);
1089
- }
1090
- };
1091
- return (React.createElement("div", { className: cx('ui-radio-button-wrapper', statusClassname) },
1092
- label && (React.createElement("label", { className: "label" },
1093
- required && (React.createElement("span", { className: "required" },
1094
- React.createElement(RequiredInput, null))),
1095
- label,
1096
- " ",
1097
- subtitle && React.createElement("span", { className: "subtitle" }, subtitle))),
1098
- options.map((option) => (React.createElement(RadioButton, { key: option.value, ...option, readOnly: readOnly, disabled: disabled, checked: selectedValue === option.value, onChange: (e) => {
1099
- handleOptionChange(e, option);
1100
- }, small: small }))),
1101
- statusWithMessage?.message && (React.createElement("div", { className: "status-with-message" },
1102
- React.createElement(InputStatusIcon, { status: statusWithMessage.status }),
1103
- React.createElement("span", { className: cx('status-message', statusClassname) }, statusWithMessage.message)))));
1104
- };
1105
-
1106
- const PLACEHOLDER_VALUE = '__PLACEHOLDER__';
1107
- const Select = ({ id, label, hint, value, options, placeholder, statusWithMessage, required, disabled, narrow, readOnly, small, getOptionLabel, getOptionValue, onChange, dataTestId, ...props }) => {
1108
- const [selectedOption, setSelectedOption] = useState(value);
1109
- const handleOnChange = (e) => {
1110
- const newSelectedOption = e.target.value === PLACEHOLDER_VALUE
1111
- ? undefined
1112
- : options.find((option) => getOptionValue(option) === e.target.value);
1113
- setSelectedOption(newSelectedOption);
1114
- onChange(newSelectedOption);
1115
- };
1116
- useEffect(() => {
1117
- // TODO: fix this lint
1118
- /* eslint-disable-next-line react-hooks/set-state-in-effect */
1119
- setSelectedOption(value);
1120
- }, [value]);
1121
- return (React.createElement(FieldWrapper, { id: id, label: label, hint: hint, statusWithMessage: statusWithMessage, required: required, disabled: disabled, small: small, narrow: narrow },
1122
- React.createElement("select", { id: id, "data-testid": dataTestId, className: cx('ui-select', statusWithMessage?.status, {
1123
- 'placeholder-selected': placeholder && !selectedOption,
1124
- small,
1125
- 'read-only': readOnly,
1126
- }), value: selectedOption ? getOptionValue(selectedOption) : undefined, required: required, disabled: disabled || readOnly, onChange: handleOnChange, ...props },
1127
- placeholder && (React.createElement("option", { value: PLACEHOLDER_VALUE, className: "placeholder-option" }, `– ${placeholder} –`)),
1128
- options.map((option) => (React.createElement("option", { key: getOptionValue(option), value: getOptionValue(option) }, getOptionLabel(option)))))));
1129
- };
1130
-
1131
- const CHAR_COUNT_ERROR_THRESHOLD = 40;
1132
- const TextArea = ({ id, label, value = '', hint, required, disabled, statusWithMessage, maxLength, onChange, onKeyUp, onBlur, ...rest }) => {
1133
- const charCount = value?.length || 0;
1134
- const { handleKeyUp, handleBlur, isFocusByTab } = useFocusByTab({ onBlur, onKeyUp });
1135
- return (React.createElement(FieldWrapper, { id: id, label: label, hint: hint, statusWithMessage: statusWithMessage, disabled: disabled, required: required, className: "ui-text-area-field-wrapper" },
1136
- React.createElement("div", { className: cx('text-area-wrapper', { 'focused-by-tab': isFocusByTab }) },
1137
- maxLength && (React.createElement("div", { className: cx('char-count', {
1138
- error: charCount === maxLength,
1139
- warning: maxLength - charCount <= CHAR_COUNT_ERROR_THRESHOLD,
1140
- }) },
1141
- charCount,
1142
- "/",
1143
- maxLength)),
1144
- React.createElement("textarea", { className: cx('text-area', { [statusWithMessage?.status || '']: !!statusWithMessage }), id: id, value: value, disabled: disabled, maxLength: maxLength, onChange: onChange, onBlur: handleBlur, onKeyUp: handleKeyUp, ...rest }))));
1145
- };
1146
-
1147
- const TimeRange = ({ range, selectedItem, className, onSelectItem }) => (React.createElement("div", { className: "time-grid", "data-testid": "time-grid" }, range.map((item) => {
1148
- const formattedItem = item.toString().padStart(2, '0');
1149
- return (React.createElement("div", { key: item, className: cx(className, { selected: selectedItem === item }), "data-testid": className === 'hour' ? `hour-${formattedItem}` : `minute-${formattedItem}`, onClick: () => onSelectItem(item) }, formattedItem));
1150
- })));
1151
- function formatTimeValue(value, max) {
1152
- return Math.max(0, Math.min(max, value)).toString().padStart(2, '0');
1153
- }
1154
- const TimePicker = ({ onTimeChange, hours = 0, minutes = 0, seconds = 0, displaySeconds = false, testIdPrefix, ...otherProps }) => {
1155
- const [isModalOpen, setIsModalOpen] = useState(false);
1156
- const inputRef = useRef(null);
1157
- const incrementMinute = useCallback((increment) => {
1158
- let newMinutes = minutes + increment;
1159
- let newHours = hours;
1160
- if (newMinutes >= 60) {
1161
- newMinutes = 0;
1162
- newHours = (newHours + 1) % 24;
1163
- }
1164
- else if (newMinutes < 0) {
1165
- newMinutes = 59;
1166
- newHours = (newHours + 23) % 24; // minus 1 hour
1167
- }
1168
- onTimeChange({ hours: newHours, minutes: newMinutes, seconds });
1169
- }, [hours, minutes, seconds, onTimeChange]);
1170
- const incrementSeconds = useCallback((increment) => {
1171
- let newSeconds = seconds + increment;
1172
- let newMinutes = minutes;
1173
- let newHours = hours;
1174
- if (newSeconds >= 60) {
1175
- newSeconds = 0;
1176
- newMinutes += 1;
1177
- if (newMinutes >= 60) {
1178
- newMinutes = 0;
1179
- newHours = (newHours + 1) % 24;
1180
- }
1181
- }
1182
- else if (newSeconds < 0) {
1183
- newSeconds = 59;
1184
- newMinutes -= 1;
1185
- if (newMinutes < 0) {
1186
- newMinutes = 59;
1187
- newHours = (newHours + 23) % 24; // minus 1 hour
1188
- }
1189
- }
1190
- onTimeChange({ hours: newHours, minutes: newMinutes, seconds: newSeconds });
1191
- }, [hours, minutes, seconds, onTimeChange]);
1192
- const handleChange = useCallback((event) => {
1193
- const value = event.target.value;
1194
- if (!displaySeconds) {
1195
- const [h, m] = value.split(':');
1196
- if (h !== undefined && m !== undefined) {
1197
- onTimeChange({ hours: parseInt(h), minutes: parseInt(m) });
1198
- }
1199
- }
1200
- else {
1201
- const [h, m, s] = value.split(':');
1202
- if (h !== undefined && m !== undefined && s !== undefined) {
1203
- onTimeChange({ hours: parseInt(h), minutes: parseInt(m), seconds: parseInt(s) });
1204
- }
1205
- }
1206
- }, [displaySeconds, onTimeChange]);
1207
- const displayedSecondsPart = displaySeconds ? `:${formatTimeValue(seconds, 59)}` : '';
1208
- const selectedTime = `${formatTimeValue(hours, 23)}:${formatTimeValue(minutes, 59)}${displayedSecondsPart}`;
1209
- const hoursRange = [...Array(24).keys()];
1210
- const minutesAndSecondsRange = [...Array(12).keys()].map((i) => i * 5);
1211
- const openModal = useCallback(() => setIsModalOpen(true), []);
1212
- const closeModal = useCallback(() => setIsModalOpen(false), []);
1213
- return (React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}` : undefined, className: "ui-time-picker" },
1214
- React.createElement(Input, { testIdPrefix: testIdPrefix ? `${testIdPrefix}` : undefined, ...otherProps, className: cx('input', 'time-input', otherProps.className), type: "time", name: "time", value: selectedTime, onClick: openModal, onChange: handleChange, ref: inputRef, step: displaySeconds ? 1 : 60 }),
1215
- React.createElement(InputModal, { inputRef: inputRef, isOpen: isModalOpen, onClose: closeModal, testIdPrefix: testIdPrefix ? `${testIdPrefix}-modal` : undefined },
1216
- React.createElement("div", { className: "time-picker-container" },
1217
- React.createElement(TimeRange, { range: hoursRange, selectedItem: hours, className: "hour", onSelectItem: (h) => onTimeChange({ hours: h, minutes, seconds }) }),
1218
- React.createElement("div", { className: "time-separator" }, ":"),
1219
- React.createElement("div", { className: "minute-container" },
1220
- React.createElement(TimeRange, { range: minutesAndSecondsRange, selectedItem: minutes, className: "minute", onSelectItem: (m) => onTimeChange({ hours, minutes: m, seconds }) }),
1221
- React.createElement("div", { className: "minute-buttons" },
1222
- React.createElement("button", { "data-testid": testIdPrefix ? `${testIdPrefix}-decrement-minute` : undefined, onClick: () => incrementMinute(-1), className: "minute-button" }, "-1mn"),
1223
- React.createElement("button", { "data-testid": testIdPrefix ? `${testIdPrefix}-increment-minute` : undefined, onClick: () => incrementMinute(1), className: "minute-button" }, "+1mn"))),
1224
- displaySeconds && (React.createElement(React.Fragment, null,
1225
- React.createElement("div", { className: "time-separator" }, ":"),
1226
- React.createElement("div", { className: "second-container" },
1227
- React.createElement(TimeRange, { range: minutesAndSecondsRange, selectedItem: seconds, className: "second", onSelectItem: (s) => onTimeChange({ hours, minutes, seconds: s }) }),
1228
- React.createElement("div", { className: "second-buttons" },
1229
- React.createElement("button", { onClick: () => incrementSeconds(-1), className: "second-button" }, "-1s"),
1230
- React.createElement("button", { onClick: () => incrementSeconds(1), className: "second-button" }, "+1s")))))))));
1231
- };
1232
-
1233
- // onChange returns an event or number
1234
- const Slider = ({ id, value: initialValue, min = 0, max = 100, step = 1, width = 112, onChange, onChangeCommitted, disabled, className, containerClassName, ...rest }) => {
1235
- const [value, setValue] = useState(initialValue !== undefined ? Number(initialValue) : Number(min));
1236
- useEffect(() => {
1237
- // TODO: fix this lint
1238
- /* eslint-disable-next-line react-hooks/set-state-in-effect */
1239
- setValue(Number(initialValue));
1240
- }, [initialValue]);
1241
- const handleChange = (e) => {
1242
- const newValue = Number(e.target.value);
1243
- setValue(newValue);
1244
- onChange?.(e);
1245
- };
1246
- const handleCommit = (e) => {
1247
- if (onChangeCommitted) {
1248
- onChangeCommitted(e);
1249
- }
1250
- };
1251
- // margin to keep the colored track aligned with the thumb
1252
- const visualMargin = 5;
1253
- const visualMin = Number(min) - visualMargin;
1254
- const visualMax = Number(max) + visualMargin;
1255
- const visualProgress = ((value - visualMin) / (visualMax - visualMin)) * 100;
1256
- return (React.createElement("div", { className: cx('ui-range-wrapper', containerClassName, { disabled }), style: { width: `${width}px` } },
1257
- React.createElement("input", { "data-testid": "range-slider", type: "range", className: cx('range-slider', className), id: id, value: value, min: min, max: max, step: step, onChange: handleChange, onMouseUp: handleCommit, onKeyUp: handleCommit, disabled: disabled, style: {
1258
- '--slider-progress': `${visualProgress}%`,
1259
- }, ...rest })));
1260
- };
1261
-
1262
- const TOLERANCE_RANGES = [
1263
- { label: '00', value: 0 },
1264
- { label: '05', value: 300 },
1265
- { label: '10', value: 600 },
1266
- { label: '15', value: 900 },
1267
- { label: '20', value: 1200 },
1268
- { label: '25', value: 1500 },
1269
- { label: '30', value: 1800 },
1270
- { label: '35', value: 2100 },
1271
- { label: '40', value: 2400 },
1272
- { label: '45', value: 2700 },
1273
- { label: '60', value: 3600 },
1274
- { label: '75', value: 4500 },
1275
- { label: '90', value: 5400 },
1276
- { label: '105', value: 6300 },
1277
- { label: '120', value: 7200 },
1278
- { label: '150', value: 9000 },
1279
- { label: '180', value: 10800 },
1280
- { label: '210', value: 12600 },
1281
- { label: '240', value: 14400 },
1282
- ];
1283
-
1284
- const ToleranceRangeGrid = ({ onSelection, selectedTolerance, toleranceSign, }) => (React.createElement("div", { className: "tolerance-picker-section" },
1285
- React.createElement("div", { className: `tolerance-grid ${toleranceSign}-tolerance` }, TOLERANCE_RANGES.map(({ label, value }, index) => (React.createElement("button", { key: `${label}-${index}`, className: cx('minute', { selected: selectedTolerance === value }), style: { gridArea: `a${index + 1}` }, onClick: () => onSelection(value) }, `${toleranceSign === 'minus' ? '-' : '+'}${label}`))))));
1286
-
1287
- /* eslint-disable react-hooks/exhaustive-deps */
1288
- const TolerancePicker = ({ onToleranceChange, toleranceValues: { minusTolerance, plusTolerance } = {
1289
- minusTolerance: TOLERANCE_RANGES[0].value,
1290
- plusTolerance: TOLERANCE_RANGES[0].value,
1291
- }, translateWarningMessage, testIdPrefix, ...inputProps }) => {
1292
- const formatToleranceValue = (minusIndex, plusIndex) => `-${TOLERANCE_RANGES[minusIndex]?.label || ''}/+${TOLERANCE_RANGES[plusIndex]?.label || ''}`;
1293
- const [showPicker, setShowPicker] = useState(false);
1294
- const [inputValue, setInputValue] = useState(formatToleranceValue(0, 0));
1295
- const [warningStatus, setWarningStatus] = useState(undefined);
1296
- const inputRef = useRef(null);
1297
- useEffect(() => {
1298
- const minusToleranceIndex = TOLERANCE_RANGES.findIndex((range) => range.value === minusTolerance);
1299
- const plusToleranceIndex = TOLERANCE_RANGES.findIndex((range) => range.value === plusTolerance);
1300
- if (minusToleranceIndex < 0 || plusToleranceIndex < 0) {
1301
- const invalidTolerance = minusToleranceIndex < 0 ? minusTolerance : plusTolerance;
1302
- // TODO: fix this lint
1303
- /* eslint-disable-next-line react-hooks/set-state-in-effect */
1304
- setWarningStatus({
1305
- status: 'warning',
1306
- message: translateWarningMessage?.(invalidTolerance) ||
1307
- `${invalidTolerance} is not a valid tolerance value.`,
1308
- });
1309
- }
1310
- else {
1311
- setWarningStatus(undefined);
1312
- }
1313
- setInputValue(formatToleranceValue(minusToleranceIndex, plusToleranceIndex));
1314
- }, [minusTolerance, plusTolerance]);
1315
- return (React.createElement("div", { "data-testid": testIdPrefix ? `${testIdPrefix}` : undefined, className: "ui-tolerance-picker" },
1316
- React.createElement("div", null,
1317
- React.createElement(Input, { testIdPrefix: testIdPrefix, ...inputProps, value: inputValue, statusWithMessage: warningStatus, onClick: () => setShowPicker(!showPicker), type: "text", ref: inputRef })),
1318
- React.createElement(InputModal, { testIdPrefix: "modal", inputRef: inputRef, isOpen: showPicker, onClose: () => setShowPicker(false) },
1319
- React.createElement("div", { className: "time-tolerance" },
1320
- React.createElement(ToleranceRangeGrid, { onSelection: (e) => onToleranceChange({ minusTolerance: e, plusTolerance }), selectedTolerance: minusTolerance, toleranceSign: "minus" }),
1321
- React.createElement("div", { className: "divider" }),
1322
- React.createElement(ToleranceRangeGrid, { onSelection: (e) => onToleranceChange({ minusTolerance, plusTolerance: e }), selectedTolerance: plusTolerance, toleranceSign: "plus" })))));
1323
- };
1324
-
1325
- const TokenInput = ({ label, tokens: initialTokens }) => {
1326
- const [tokens, setTokens] = useState(initialTokens);
1327
- const [newToken, setNewToken] = useState('');
1328
- const [selectedToken, setSelectedToken] = useState(null);
1329
- const inputRef = useRef(null);
1330
- const addToken = (e) => {
1331
- if (e.key === 'Enter' && newToken.trim() !== '') {
1332
- setTokens((oldTokens) => [...oldTokens, newToken]);
1333
- setNewToken('');
1334
- }
1335
- };
1336
- const focusInput = (e) => {
1337
- if (e.target === e.currentTarget) {
1338
- inputRef.current?.focus();
1339
- }
1340
- };
1341
- return (React.createElement("div", { className: "ui-token-input-wrapper" },
1342
- React.createElement("label", { className: "input-label" }, label),
1343
- React.createElement("div", { className: "tokens-wrapper", onClick: focusInput },
1344
- tokens.map((token, index) => (React.createElement("div", { key: `${token}-${index}`, onClick: () => setSelectedToken(index), className: cx('token-item-wrapper', { selected: selectedToken === index }) },
1345
- React.createElement("span", { className: "token-label" }, token),
1346
- React.createElement("span", { className: "token-close-btn", onClick: () => setTokens((oldTokens) => oldTokens.filter((_t, i) => i !== index)) },
1347
- React.createElement(X, null))))),
1348
- React.createElement("input", { type: "text", value: newToken, onChange: (e) => setNewToken(e.target.value), onKeyDown: addToken, className: "token-input", ref: inputRef }))));
1349
- };
1350
-
1351
- const colors = {
1352
- ambientA5: 'rgb(246, 248, 249)',
1353
- ambientA10: 'rgb(239, 243, 245)',
1354
- ambientA15: 'rgb(233, 239, 242)',
1355
- ambientB5: 'rgb(250, 249, 245)',
1356
- ambientB10: 'rgb(247, 246, 238)',
1357
- ambientB15: 'rgb(242, 240, 228)',
1358
- ambientC5: 'rgb(246, 249, 246)',
1359
- ambientC10: 'rgb(240, 244, 241)',
1360
- ambientC15: 'rgb(234, 240, 235)',
1361
- ambientD5: 'rgb(248, 247, 253)',
1362
- ambientD10: 'rgb(244, 243, 252)',
1363
- ambientD15: 'rgb(239, 237, 247)',
1364
- blackAlpha: 'rgba(0, 0, 0)',
1365
- };
1366
- const TABLE_AMBIENT_THEMES = {
1367
- A: {
1368
- mix1: colors.blackAlpha,
1369
- mix2: colors.ambientA5,
1370
- odd: colors.ambientA10,
1371
- even: colors.ambientA15,
1372
- },
1373
- B: {
1374
- mix1: colors.blackAlpha,
1375
- mix2: colors.ambientB5,
1376
- odd: colors.ambientB10,
1377
- even: colors.ambientB15,
1378
- },
1379
- C: {
1380
- mix1: colors.blackAlpha,
1381
- mix2: colors.ambientC5,
1382
- odd: colors.ambientC10,
1383
- even: colors.ambientC15,
1384
- },
1385
- D: {
1386
- mix1: colors.blackAlpha,
1387
- mix2: colors.ambientD5,
1388
- odd: colors.ambientD10,
1389
- even: colors.ambientD15,
1390
- },
1391
- };
1392
-
1393
- const Table = ({ columns, data, ambientVariant = 'B' }) => {
1394
- const theme = TABLE_AMBIENT_THEMES[ambientVariant];
1395
- return (React.createElement("table", { className: "table-container ambient", style: {
1396
- '--mix-color-1': theme.mix1,
1397
- '--mix-color-2': theme.mix2,
1398
- '--row-bg-odd': theme.odd,
1399
- '--row-bg-even': theme.even,
1400
- } },
1401
- React.createElement("thead", null,
1402
- React.createElement("tr", null, columns.map((col) => (React.createElement("td", { key: col.key, className: col.className }, col.label))))),
1403
- React.createElement("tbody", null, data.map((row, i) => (React.createElement("tr", { key: i }, columns.map((col) => (React.createElement("td", { key: col.key, className: col.className }, row[col.key])))))))));
1404
- };
1405
-
1406
- /**
1407
- * Display a styled dialog box.
1408
- * You are in charge of its lifecycle (open & close), this componant just display it.
1409
- *
1410
- * Children must be an array of 3 items, where :
1411
- * - the first one is for the header
1412
- * - the second one is for the content
1413
- * - the last is for the footer
1414
- *
1415
- * NB: Inside header, only title tags have the good style (font weight and size)
1416
- */
1417
- const Dialog = ({ children, className, fullscreen = false, header, headerClassname, footer, footerClassname, bodyClassname, ...dialogProps }) => {
1418
- const overlayRef = useRef(null);
1419
- const dialogRef = useRef(null);
1420
- /**
1421
- * When the dialog height change
1422
- * => check if there is a scroll on the overlay and if so add a 'scroll' class on it
1423
- */
1424
- useEffect(() => {
1425
- if (fullscreen)
1426
- return;
1427
- if (!overlayRef.current || !dialogRef.current)
1428
- return;
1429
- const resizeObserver = new ResizeObserver(() => {
1430
- if (overlayRef.current) {
1431
- if (overlayRef.current.scrollHeight > overlayRef.current.clientHeight) {
1432
- overlayRef.current.classList.add('scroll');
1433
- }
1434
- else {
1435
- overlayRef.current.classList.remove('scroll');
1436
- }
1437
- }
1438
- });
1439
- resizeObserver.observe(dialogRef.current);
1440
- return () => resizeObserver.disconnect();
1441
- }, [overlayRef, dialogRef, fullscreen]);
1442
- return (React.createElement("div", { ref: overlayRef, className: "ui-dialog-overlay flex items-center justify-center", tabIndex: -1 },
1443
- React.createElement("dialog", { ref: dialogRef, ...dialogProps, className: cx('dialog-content', className, fullscreen && 'fullscreen'), open: true },
1444
- React.createElement("header", { className: cx(headerClassname) }, header),
1445
- React.createElement("section", { className: cx(bodyClassname) }, children),
1446
- React.createElement("footer", { className: cx(footerClassname) }, footer))));
1447
- };
1448
-
1449
- const SegmentedControl = ({ options, onChange, value, getOptionLabel, getOptionValue, getOptionIcon, small = false, ...inputProps }) => {
1450
- const opts = useMemo(() => options.map((e) => ({
1451
- value: getOptionValue(e),
1452
- label: getOptionLabel(e),
1453
- icon: getOptionIcon ? getOptionIcon(e) : null,
1454
- source: e,
1455
- })), [options, getOptionValue, getOptionLabel, getOptionIcon]);
1456
- return (React.createElement("div", { className: cx('segmented-control', { small }) }, opts.map((option) => (React.createElement("label", { key: option.value, className: cx('segmented-control-option', option.value === getOptionValue(value) && 'checked'), title: option.label },
1457
- React.createElement("div", { className: "segmented-control-option-content" }, option.icon ? option.icon : option.label),
1458
- React.createElement("input", { ...inputProps, type: "radio", checked: option.value === getOptionValue(value), onChange: () => onChange(option.source) }))))));
1459
- };
1460
-
1461
- export { Button, Checkbox, CheckboxList, CheckboxesTree, ComboBox, DatePicker, Dialog, Input, PasswordInput, RadioButton, RadioGroup, SegmentedControl, Select, Slider, Table, TextArea, TimePicker, TokenInput, TolerancePicker, useDefaultComboBox, useOutsideClick };
1462
- //# sourceMappingURL=index.esm.js.map