@osrd-project/ui-core 0.0.82 → 0.0.84

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