@cwellt_software/cwellt-reactjs-lib 1.4.11 → 1.4.13

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 (28) hide show
  1. package/dist/index.cjs.js +1039 -13
  2. package/dist/index.css +2 -2
  3. package/dist/index.d.ts +253 -12
  4. package/dist/index.es.js +1036 -15
  5. package/dist/src/components/control/action/search/CwSearchAsync.d.ts +105 -0
  6. package/dist/src/components/control/action/search/CwSearchAsync.d.ts.map +1 -0
  7. package/dist/src/components/control/input/new-dates/CwDatePickerTemporal.d.ts +10 -1
  8. package/dist/src/components/control/input/new-dates/CwDatePickerTemporal.d.ts.map +1 -1
  9. package/dist/src/components/control/input/new-dates/CwDateRangePickerTemporal.d.ts +75 -0
  10. package/dist/src/components/control/input/new-dates/CwDateRangePickerTemporal.d.ts.map +1 -0
  11. package/dist/src/components/control/input/new-dates/CwDateTimePickerTemporal.d.ts +52 -0
  12. package/dist/src/components/control/input/new-dates/CwDateTimePickerTemporal.d.ts.map +1 -0
  13. package/dist/src/components/control/input/new-dates/CwTimePicker.d.ts.map +1 -1
  14. package/dist/src/components/control/input/new-dates/dateRangePresetsTemporal.d.ts +16 -0
  15. package/dist/src/components/control/input/new-dates/dateRangePresetsTemporal.d.ts.map +1 -0
  16. package/dist/src/components/control/input/new-dates/domain/DateTimePickerState.d.ts +78 -0
  17. package/dist/src/components/control/input/new-dates/domain/DateTimePickerState.d.ts.map +1 -0
  18. package/dist/src/components/control/input/new-dates/useCwDateTimePickerTemporal.d.ts +29 -0
  19. package/dist/src/components/control/input/new-dates/useCwDateTimePickerTemporal.d.ts.map +1 -0
  20. package/dist/src/index.d.ts +7 -0
  21. package/dist/src/index.d.ts.map +1 -1
  22. package/dist/src/playground/pages/DatePickerTemporalPage.d.ts.map +1 -1
  23. package/dist/src/playground/pages/SelectorsPage.d.ts.map +1 -1
  24. package/dist/test/components/control/input/new-dates/DateTimePickerState.test.d.ts +2 -0
  25. package/dist/test/components/control/input/new-dates/DateTimePickerState.test.d.ts.map +1 -0
  26. package/dist/test/components/control/input/new-dates/dateRangePresetsTemporal.test.d.ts +2 -0
  27. package/dist/test/components/control/input/new-dates/dateRangePresetsTemporal.test.d.ts.map +1 -0
  28. package/package.json +1 -1
package/dist/index.cjs.js CHANGED
@@ -5037,6 +5037,265 @@ function CwSearchInput(optionsProps) {
5037
5037
  return (jsxRuntime.jsxs("div", { className: `cw-search-input ${className || ""}`, style: style, id: id, ...otherProps, "data-direction": direction, children: [jsxRuntime.jsxs(CwAlign, { ...alignProps, children: [labelProps && (jsxRuntime.jsx(CwLabel, { ...labelProps, children: labelProps.text })), jsxRuntime.jsxs("div", { className: "cw-search-input-wrapper", ref: wrapperRef, children: [jsxRuntime.jsx("input", { type: "text", value: searchText, onChange: handleInputChange, onFocus: handleInputFocus, onBlur: handleInputBlur, placeholder: placeholder, className: "cw-input-search", disabled: disabled }), isLoading && (jsxRuntime.jsx("div", { className: "cw-search-input-loading", children: jsxRuntime.jsx(CwIcon, { iconId: "spinner" }) })), jsxRuntime.jsx("div", { className: "cw-search-input-icons", children: searchText && !disabled && !isLoading ? (jsxRuntime.jsx(CwButton, { type: "button", onClick: handleClearClick, "aria-label": "Clear search", variant: "icon", icon: "close", color: "neutral" })) : (iconProps ? jsxRuntime.jsx(CwIcon, { ...iconProps }) : jsxRuntime.jsx(CwIcon, { iconId: "search" })) })] })] }), renderPanel(jsxRuntime.jsx("div", { ref: panelRef, className: dropdownStyles.dropdown, style: panelStyle, children: jsxRuntime.jsx("ul", { children: filteredOptions.map((option) => (jsxRuntime.jsx("li", { className: dropdownStyles.option, onClick: () => handleOptionSelect(option), onMouseDown: (e) => e.preventDefault(), children: renderOption ? renderOption(option) : option.description }, option.id))) }) }))] }));
5038
5038
  }
5039
5039
 
5040
+ /**
5041
+ * Generic API-backed search input. Fetches matching options from a caller-supplied `onSearch`
5042
+ * callback as the user types (debounced), renders them in a portal-based dropdown with keyboard
5043
+ * navigation, and commits the selected id via `onChange`.
5044
+ *
5045
+ * All domain logic — API URLs, auth/config, display formatting, provider/secondary lookups — lives
5046
+ * in the caller's callbacks, so this component stays application-agnostic. It is the base for thin
5047
+ * wrappers such as `FindAirport` / `FindCrewmember`.
5048
+ *
5049
+ * Improvements over the legacy `CwFindAirport` / `CwFindCrewmember`: an `AbortController` cancels
5050
+ * superseded in-flight requests (fixes out-of-order results), and `minChars` / `debounceMs` are
5051
+ * configurable.
5052
+ *
5053
+ * @example
5054
+ * <CwSearchAsync
5055
+ * onSearch={(text, signal) => repo.search(text, signal)}
5056
+ * onChange={(id) => setSelectedId(id)}
5057
+ * labelProps={{ text: 'Airport' }}
5058
+ * icon={{ iconId: 'control-tower' }}
5059
+ * />
5060
+ */
5061
+ const CwSearchAsync = ({ onSearch, onChange, value, onResolveInitial, onResolveSelection, icon, placeholder = "Search…", minChars = 2, debounceMs = 300, disabled = false, required = false, initialDisplayText, searchTrigger, labelProps, alignProps, width, className = "", }) => {
5062
+ // State
5063
+ const [inputValue, setInputValue] = React.useState("");
5064
+ const [options, setOptions] = React.useState([]);
5065
+ const [isLoading, setIsLoading] = React.useState(false);
5066
+ const [isInitialLoading, setIsInitialLoading] = React.useState(false);
5067
+ const [showDropdown, setShowDropdown] = React.useState(false);
5068
+ const [highlightedIndex, setHighlightedIndex] = React.useState(-1);
5069
+ const [tooltipText, setTooltipText] = React.useState("");
5070
+ // Refs
5071
+ const inputRef = React.useRef(null);
5072
+ const wrapperRef = React.useRef(null);
5073
+ const debounceRef = React.useRef();
5074
+ const abortRef = React.useRef(null);
5075
+ const lastQueryRef = React.useRef("");
5076
+ const didMountRef = React.useRef(false);
5077
+ const lastResolvedValueRef = React.useRef(undefined);
5078
+ const initialResolveAbortRef = React.useRef(null);
5079
+ // Stable ids wiring the combobox input to its listbox popup for assistive tech.
5080
+ const listboxId = React.useId();
5081
+ const optionId = (index) => `${listboxId}-opt-${index}`;
5082
+ // Cancel a pending initial-value resolve when the user takes over (typing / clearing / reset),
5083
+ // so a slow resolve can't overwrite newer input and the loading flag never sticks.
5084
+ const cancelInitialResolve = React.useCallback(() => {
5085
+ initialResolveAbortRef.current?.abort();
5086
+ initialResolveAbortRef.current = null;
5087
+ setIsInitialLoading(false);
5088
+ }, []);
5089
+ const { panelRef, panelStyle, renderPanel } = useDropdownPortal({
5090
+ anchorRef: wrapperRef,
5091
+ isOpen: showDropdown && options.length > 0,
5092
+ onClose: () => { setShowDropdown(false); setHighlightedIndex(-1); },
5093
+ });
5094
+ // Core search runner — aborts superseded requests and drops stale responses.
5095
+ const runSearch = React.useCallback(async (text) => {
5096
+ abortRef.current?.abort();
5097
+ if (text.length < minChars) {
5098
+ setOptions([]);
5099
+ setShowDropdown(false);
5100
+ setHighlightedIndex(-1);
5101
+ return;
5102
+ }
5103
+ const controller = new AbortController();
5104
+ abortRef.current = controller;
5105
+ lastQueryRef.current = text;
5106
+ setIsLoading(true);
5107
+ try {
5108
+ const results = await onSearch(text, controller.signal);
5109
+ if (controller.signal.aborted)
5110
+ return; // superseded → drop
5111
+ setOptions(results);
5112
+ setShowDropdown(results.length > 0); // empty → close silently (dark cockpit)
5113
+ setHighlightedIndex(-1);
5114
+ }
5115
+ catch (error) {
5116
+ if (controller.signal.aborted)
5117
+ return; // aborts reject with AbortError → ignore
5118
+ console.error("CwSearchAsync onSearch failed:", error);
5119
+ setOptions([]);
5120
+ setShowDropdown(false);
5121
+ }
5122
+ finally {
5123
+ if (abortRef.current === controller) {
5124
+ setIsLoading(false);
5125
+ abortRef.current = null;
5126
+ }
5127
+ }
5128
+ }, [minChars, onSearch]);
5129
+ // Keep a stable handle to the latest runSearch for the searchTrigger effect.
5130
+ const runSearchRef = React.useRef(runSearch);
5131
+ React.useEffect(() => { runSearchRef.current = runSearch; });
5132
+ const debouncedSearch = React.useCallback((text) => {
5133
+ if (debounceRef.current)
5134
+ window.clearTimeout(debounceRef.current);
5135
+ // Abort eagerly on every keystroke so a fast typist never has two live fetches.
5136
+ abortRef.current?.abort();
5137
+ debounceRef.current = window.setTimeout(() => runSearch(text), debounceMs);
5138
+ }, [runSearch, debounceMs]);
5139
+ const handleInputChange = (e) => {
5140
+ const newValue = e.target.value;
5141
+ setInputValue(newValue);
5142
+ if (newValue !== inputValue) {
5143
+ cancelInitialResolve();
5144
+ debouncedSearch(newValue);
5145
+ }
5146
+ };
5147
+ const handleOptionSelect = async (optionId) => {
5148
+ const picked = options.find(o => o.id === optionId);
5149
+ if (!picked)
5150
+ return;
5151
+ setShowDropdown(false);
5152
+ let committed = picked;
5153
+ if (onResolveSelection) {
5154
+ abortRef.current?.abort();
5155
+ const controller = new AbortController();
5156
+ abortRef.current = controller;
5157
+ try {
5158
+ const resolved = await onResolveSelection(picked, controller.signal);
5159
+ if (controller.signal.aborted)
5160
+ return;
5161
+ committed = resolved;
5162
+ setOptions([resolved]);
5163
+ }
5164
+ catch (error) {
5165
+ if (controller.signal.aborted)
5166
+ return;
5167
+ console.error("CwSearchAsync onResolveSelection failed:", error);
5168
+ return; // abort the commit, mirroring the legacy provider-airport behaviour
5169
+ }
5170
+ finally {
5171
+ if (abortRef.current === controller)
5172
+ abortRef.current = null;
5173
+ }
5174
+ }
5175
+ setInputValue(committed.inputLabel ?? committed.label);
5176
+ setTooltipText(committed.label);
5177
+ onChange(committed.id);
5178
+ };
5179
+ const handleKeyDown = (e) => {
5180
+ if (!showDropdown || options.length === 0)
5181
+ return;
5182
+ switch (e.key) {
5183
+ case "ArrowDown":
5184
+ e.preventDefault();
5185
+ setHighlightedIndex(prev => (prev < options.length - 1 ? prev + 1 : 0));
5186
+ break;
5187
+ case "ArrowUp":
5188
+ e.preventDefault();
5189
+ setHighlightedIndex(prev => (prev > 0 ? prev - 1 : options.length - 1));
5190
+ break;
5191
+ case "Enter":
5192
+ e.preventDefault();
5193
+ if (highlightedIndex >= 0 && highlightedIndex < options.length) {
5194
+ handleOptionSelect(options[highlightedIndex].id);
5195
+ }
5196
+ break;
5197
+ case "Escape":
5198
+ setShowDropdown(false);
5199
+ setHighlightedIndex(-1);
5200
+ break;
5201
+ }
5202
+ };
5203
+ const handleInputFocus = () => {
5204
+ if (options.length > 0)
5205
+ setShowDropdown(true);
5206
+ };
5207
+ const handleClear = () => {
5208
+ if (debounceRef.current)
5209
+ window.clearTimeout(debounceRef.current);
5210
+ abortRef.current?.abort();
5211
+ cancelInitialResolve();
5212
+ setInputValue("");
5213
+ setTooltipText("");
5214
+ setOptions([]);
5215
+ setShowDropdown(false);
5216
+ lastQueryRef.current = "";
5217
+ onChange(null);
5218
+ inputRef.current?.focus();
5219
+ };
5220
+ // Resolve a preselected value to display text.
5221
+ React.useEffect(() => {
5222
+ if (value == null)
5223
+ return;
5224
+ if (initialDisplayText) {
5225
+ setInputValue(initialDisplayText);
5226
+ setTooltipText(initialDisplayText);
5227
+ lastResolvedValueRef.current = value;
5228
+ return;
5229
+ }
5230
+ if (!onResolveInitial)
5231
+ return;
5232
+ if (lastResolvedValueRef.current === value)
5233
+ return; // already resolved this value
5234
+ const controller = new AbortController();
5235
+ initialResolveAbortRef.current = controller;
5236
+ setIsInitialLoading(true);
5237
+ onResolveInitial(value, controller.signal)
5238
+ .then(opt => {
5239
+ if (controller.signal.aborted)
5240
+ return;
5241
+ lastResolvedValueRef.current = value; // mark resolved only on success
5242
+ setOptions([opt]);
5243
+ setInputValue(opt.inputLabel ?? opt.label);
5244
+ setTooltipText(opt.label);
5245
+ })
5246
+ .catch(error => {
5247
+ if (!controller.signal.aborted)
5248
+ console.error("CwSearchAsync onResolveInitial failed:", error);
5249
+ })
5250
+ .finally(() => {
5251
+ // Clear the spinner only if this resolve is still the current one (not superseded/cancelled).
5252
+ if (initialResolveAbortRef.current === controller) {
5253
+ setIsInitialLoading(false);
5254
+ initialResolveAbortRef.current = null;
5255
+ }
5256
+ });
5257
+ return () => controller.abort();
5258
+ }, [value, initialDisplayText, onResolveInitial]);
5259
+ // Reset when the controlled value is cleared by the parent.
5260
+ React.useEffect(() => {
5261
+ if (value == null) {
5262
+ if (debounceRef.current)
5263
+ window.clearTimeout(debounceRef.current);
5264
+ abortRef.current?.abort();
5265
+ cancelInitialResolve();
5266
+ setInputValue("");
5267
+ setTooltipText("");
5268
+ setOptions([]);
5269
+ setShowDropdown(false);
5270
+ setHighlightedIndex(-1);
5271
+ lastQueryRef.current = "";
5272
+ lastResolvedValueRef.current = undefined;
5273
+ }
5274
+ }, [value, cancelInitialResolve]);
5275
+ // Re-run the last query when searchTrigger changes (skip first mount).
5276
+ React.useEffect(() => {
5277
+ if (!didMountRef.current) {
5278
+ didMountRef.current = true;
5279
+ return;
5280
+ }
5281
+ if (searchTrigger === undefined)
5282
+ return;
5283
+ if (lastQueryRef.current)
5284
+ runSearchRef.current(lastQueryRef.current);
5285
+ }, [searchTrigger]);
5286
+ // Cleanup on unmount.
5287
+ React.useEffect(() => () => {
5288
+ if (debounceRef.current)
5289
+ window.clearTimeout(debounceRef.current);
5290
+ abortRef.current?.abort();
5291
+ }, []);
5292
+ const direction = alignProps?.flexDirection || "row";
5293
+ return (jsxRuntime.jsxs("div", { className: `cw-search-input ${className}`, style: {
5294
+ ...(width ? { width } : {}),
5295
+ ...(labelProps?.labelWidth ? { "--label-width": labelProps.labelWidth } : {}),
5296
+ }, "data-direction": direction, children: [jsxRuntime.jsxs(CwAlign, { ...alignProps, itemProp: required ? "required" : "", children: [labelProps && (jsxRuntime.jsx(CwLabel, { ...labelProps, children: labelProps.text })), jsxRuntime.jsxs("div", { className: "cw-search-input-wrapper", ref: wrapperRef, children: [jsxRuntime.jsx("input", { ref: inputRef, type: "text", value: inputValue, onChange: handleInputChange, onKeyDown: handleKeyDown, onFocus: handleInputFocus, placeholder: isInitialLoading ? "Loading…" : placeholder, disabled: disabled, required: required, autoComplete: "off", role: "combobox", "aria-haspopup": "listbox", "aria-expanded": showDropdown, "aria-controls": listboxId, "aria-activedescendant": highlightedIndex >= 0 ? optionId(highlightedIndex) : undefined, title: tooltipText }), (isLoading || isInitialLoading) && (jsxRuntime.jsx("div", { className: "cw-search-input-loading", children: jsxRuntime.jsx(CwIcon, { iconId: "spinner" }) })), jsxRuntime.jsx("div", { className: "cw-search-input-icons", children: inputValue && !disabled && !isInitialLoading ? (jsxRuntime.jsx(CwButton, { type: "button", onClick: handleClear, "aria-label": "Clear selection", variant: "icon", icon: "close", color: "neutral" })) : (icon ? jsxRuntime.jsx(CwIcon, { ...icon }) : jsxRuntime.jsx(CwIcon, { iconId: "search" })) })] })] }), renderPanel(jsxRuntime.jsx("div", { ref: panelRef, id: listboxId, className: dropdownStyles.dropdown, style: panelStyle, role: "listbox", children: jsxRuntime.jsx("ul", { children: options.map((option, index) => (jsxRuntime.jsx("li", { id: optionId(index), className: `${dropdownStyles.option}${index === highlightedIndex ? ` ${dropdownStyles.optionFocused}` : ""}`, onClick: () => handleOptionSelect(option.id), onMouseDown: (e) => e.preventDefault(), onMouseEnter: () => setHighlightedIndex(index), role: "option", "aria-selected": index === highlightedIndex, children: option.subLabel ? (jsxRuntime.jsxs("span", { className: "cw-search-async-option-lines", children: [jsxRuntime.jsx("span", { children: option.label }), jsxRuntime.jsx("span", { className: "cw-search-async-option-sub", children: option.subLabel })] })) : (option.label) }, option.id))) }) }))] }));
5297
+ };
5298
+
5040
5299
  var styles$5 = {"menu":"cw-context-menu-module__menu__tXmun","item":"cw-context-menu-module__item__-ko8L","arrow":"cw-context-menu-module__arrow__LHZmQ"};
5041
5300
 
5042
5301
  const ARROW_SIZE = 8;
@@ -6253,7 +6512,10 @@ function CwTimePicker({ value, onChange, interval = 15, minTime, maxTime, labelP
6253
6512
  const handleClear = (e) => {
6254
6513
  e.stopPropagation();
6255
6514
  onChange(undefined);
6256
- setInputValue("");
6515
+ // Keep showing the current value prop: a controlled parent that accepts the
6516
+ // clear empties it via the value-sync effect, while a parent that rejects or
6517
+ // transforms the clear (e.g. resets to a default) stays visually in sync.
6518
+ setInputValue(value ?? "");
6257
6519
  };
6258
6520
  const handleInputClick = () => {
6259
6521
  if (!disabled) {
@@ -6281,15 +6543,18 @@ function CwTimePicker({ value, onChange, interval = 15, minTime, maxTime, labelP
6281
6543
  const [hours, minutes] = newValue.split(":");
6282
6544
  const h = parseInt(hours, 10);
6283
6545
  const m = parseInt(minutes, 10);
6284
- if (h >= 0 && h <= 23 && m >= 0 && m <= 59) {
6285
- const formattedTime = `${hours.padStart(2, "0")}:${minutes.padStart(2, "0")}`;
6286
- // Check min/max time restrictions
6287
- const isValid = (!minTime || formattedTime >= minTime) &&
6288
- (!maxTime || formattedTime <= maxTime);
6289
- if (isValid) {
6290
- onChange(formattedTime);
6291
- setInputValue(formattedTime);
6292
- }
6546
+ const formattedTime = `${hours.padStart(2, "0")}:${minutes.padStart(2, "0")}`;
6547
+ // Check well-formedness and min/max time restrictions
6548
+ const isValid = h >= 0 && h <= 23 && m >= 0 && m <= 59 &&
6549
+ (!minTime || formattedTime >= minTime) &&
6550
+ (!maxTime || formattedTime <= maxTime);
6551
+ if (isValid) {
6552
+ onChange(formattedTime);
6553
+ setInputValue(formattedTime);
6554
+ }
6555
+ else {
6556
+ // Completed entry is invalid/out of range: snap back to the previous value
6557
+ setInputValue(value ?? "");
6293
6558
  }
6294
6559
  }
6295
6560
  else if (newValue === "") {
@@ -7003,9 +7268,10 @@ function formatPlainDate(pd, fmt) {
7003
7268
  .replace("dd", String(pd.day).padStart(2, "0"));
7004
7269
  }
7005
7270
 
7006
- function CwDatePickerTemporal({ value, onChange, minDate, maxDate, disabledDates, disabledMatcher, defaultMonth, labelProps, alignProps, placeholder = "Select a date", displayFormat = "dd.MM.yyyy", disabled, required, className, showClear = true, popupPosition = "left-bottom", numberOfMonths = 1, showTodayButton = false, todayLabel = "Today", feedback, }) {
7271
+ function CwDatePickerTemporal({ value, onChange, minDate, maxDate, disabledDates, disabledMatcher, defaultMonth, labelProps, alignProps, placeholder = "Select a date", displayFormat = "dd.MM.yyyy", disabled, required, className, showClear = true, popupPosition = "left-bottom", numberOfMonths = 1, showTodayButton = false, locale: locale$1 = locale.enGB, todayLabel = "Today", yearRangeStart, yearRangeEnd, feedback, }) {
7007
7272
  const [isOpen, setIsOpen] = React.useState(false);
7008
- const [inputValue, setInputValue] = React.useState();
7273
+ // Initialize with the formatted value so the input is controlled from the first render
7274
+ const [inputValue, setInputValue] = React.useState(() => value ? formatPlainDate(value, displayFormat) : "");
7009
7275
  const containerRef = React.useRef(null);
7010
7276
  const feedbackMessages = feedback
7011
7277
  ? Array.isArray(feedback) ? feedback : [feedback]
@@ -7092,6 +7358,19 @@ function CwDatePickerTemporal({ value, onChange, minDate, maxDate, disabledDates
7092
7358
  setIsOpen(false);
7093
7359
  }
7094
7360
  }, [minDate, maxDate, onChange]);
7361
+ // Derive start/end months for the year dropdown range, guarding against inverted yearRange props
7362
+ const dropdownStartMonth = React.useMemo(() => {
7363
+ const inferredStart = minDate ? minDate.year : Temporal.Now.plainDateISO().year - 10;
7364
+ const inferredEnd = yearRangeEnd ?? (maxDate ? maxDate.year : Temporal.Now.plainDateISO().year + 5);
7365
+ const year = Math.min(yearRangeStart ?? inferredStart, inferredEnd);
7366
+ return new Date(year, 0, 1);
7367
+ }, [yearRangeStart, yearRangeEnd, minDate, maxDate]);
7368
+ const dropdownEndMonth = React.useMemo(() => {
7369
+ const inferredEnd = maxDate ? maxDate.year : Temporal.Now.plainDateISO().year + 5;
7370
+ const inferredStart = yearRangeStart ?? (minDate ? minDate.year : Temporal.Now.plainDateISO().year - 10);
7371
+ const year = Math.max(yearRangeEnd ?? inferredEnd, inferredStart);
7372
+ return new Date(year, 11, 31);
7373
+ }, [yearRangeStart, yearRangeEnd, minDate, maxDate]);
7095
7374
  // Memoize disabled days (convert PlainDate[] to Date[] for DayPicker)
7096
7375
  const disabledDays = React.useMemo(() => [
7097
7376
  ...(disabledDates?.map(plainDateToJsDate) || []),
@@ -7103,13 +7382,755 @@ function CwDatePickerTemporal({ value, onChange, minDate, maxDate, disabledDates
7103
7382
  const defaultMonthJsDate = defaultMonth
7104
7383
  ? new Date(defaultMonth.year, defaultMonth.month - 1, 1)
7105
7384
  : selectedJsDate;
7106
- return (jsxRuntime.jsxs("div", { ref: containerRef, className: `cw-datepicker ${className || ""}`, children: [jsxRuntime.jsxs(CwAlign, { ...alignProps, itemProp: required ? "required" : "", children: [labelProps && (jsxRuntime.jsx(CwLabel, { ...labelProps, children: labelProps.text })), jsxRuntime.jsxs("div", { ref: wrapperRef, className: styles$4.pickerWrapper, children: [jsxRuntime.jsx("input", { ref: inputRef, type: "text", value: inputValue, placeholder: placeholder, onChange: handleInputChange, onBlur: handleInputBlur, onClick: handleInputClick, onKeyDown: handleInputKeyDown, disabled: disabled, required: required }), jsxRuntime.jsx("div", { className: styles$4.pickerIcons, children: showClear && value && !disabled ? (jsxRuntime.jsx(CwButton, { type: "button", variant: "icon", color: "neutral", icon: "close", onClick: handleClear, tabIndex: -1, "aria-label": "Clear date" })) : (jsxRuntime.jsx(CwIcon, { iconId: "calendar" })) }), renderPopup(jsxRuntime.jsxs("div", { ref: popupRef, className: styles$4.pickerPopup, style: popupStyle, children: [jsxRuntime.jsx(reactDayPicker.DayPicker, { mode: "single", selected: selectedJsDate, defaultMonth: defaultMonthJsDate, onSelect: handleDaySelect, disabled: disabledDays, numberOfMonths: numberOfMonths, modifiers: {
7385
+ return (jsxRuntime.jsxs("div", { ref: containerRef, className: `cw-datepicker ${className || ""}`, children: [jsxRuntime.jsxs(CwAlign, { ...alignProps, itemProp: required ? "required" : "", children: [labelProps && (jsxRuntime.jsx(CwLabel, { ...labelProps, children: labelProps.text })), jsxRuntime.jsxs("div", { ref: wrapperRef, className: styles$4.pickerWrapper, children: [jsxRuntime.jsx("input", { ref: inputRef, type: "text", value: inputValue, placeholder: placeholder, onChange: handleInputChange, onBlur: handleInputBlur, onClick: handleInputClick, onKeyDown: handleInputKeyDown, disabled: disabled, required: required }), jsxRuntime.jsx("div", { className: styles$4.pickerIcons, children: showClear && value && !disabled ? (jsxRuntime.jsx(CwButton, { type: "button", variant: "icon", color: "neutral", icon: "close", onClick: handleClear, tabIndex: -1, "aria-label": "Clear date" })) : (jsxRuntime.jsx(CwIcon, { iconId: "calendar" })) }), renderPopup(jsxRuntime.jsxs("div", { ref: popupRef, className: styles$4.pickerPopup, style: popupStyle, children: [jsxRuntime.jsx(reactDayPicker.DayPicker, { mode: "single", selected: selectedJsDate, defaultMonth: defaultMonthJsDate, onSelect: handleDaySelect, disabled: disabledDays, numberOfMonths: numberOfMonths, locale: locale$1, captionLayout: "dropdown", startMonth: dropdownStartMonth, endMonth: dropdownEndMonth, modifiers: {
7107
7386
  today: new Date(),
7108
7387
  }, modifiersClassNames: {
7109
7388
  today: "rdp-day-today",
7110
7389
  } }), showTodayButton && (jsxRuntime.jsx("footer", { className: "cw-flex-row cw-align-right-center", children: jsxRuntime.jsx(CwButton, { type: "button", variant: "outline", onClick: handleTodayClick, text: todayLabel }) }))] }))] })] }), feedbackMessages.map((feedbackItem, index) => (jsxRuntime.jsx("p", { className: "cw-input-info", "data-color": feedbackItem.type, children: feedbackItem.message }, index)))] }));
7111
7390
  }
7112
7391
 
7392
+ // DateTimePickerState - immutable domain model for the Temporal date-time picker.
7393
+ //
7394
+ // Invariants:
7395
+ // - `time` is NEVER null: this is a date-TIME picker, so the time always has a
7396
+ // value and defaults to 00:00. Only the date can be unselected, and without
7397
+ // a date the whole `value` is undefined.
7398
+ // - Minute precision everywhere: times AND constraints are truncated to HH:mm
7399
+ // on the way in, so emitted values always carry :00 seconds and boundary
7400
+ // checks never fail on sub-minute residue.
7401
+ // - NO reachable state holds an out-of-range selection when minDateTime /
7402
+ // maxDateTime are set. User operations that would leave the state invalid
7403
+ // return THE SAME instance (===), which the hook uses to skip the emission
7404
+ // and let the UI snap back; entry paths that cannot reject (fromValue,
7405
+ // withConstraints, withTimeCleared) clamp into the range instead.
7406
+ //
7407
+ // Because of these invariants the emission is state-scoped: after any accepted
7408
+ // operation the value to emit is simply the new state's `value`. Rejected
7409
+ // operations are detected by identity (`next === prev`).
7410
+ /** Truncate to minute precision (HH:mm) - the picker's working precision */
7411
+ function truncateToMinute(time) {
7412
+ return new Temporal.PlainTime(time.hour, time.minute);
7413
+ }
7414
+ function midnight() {
7415
+ return new Temporal.PlainTime(0, 0);
7416
+ }
7417
+ function truncateDateTimeToMinute(dateTime) {
7418
+ return dateTime
7419
+ ? dateTime.toPlainDate().toPlainDateTime(truncateToMinute(dateTime.toPlainTime()))
7420
+ : undefined;
7421
+ }
7422
+ /** Normalize constraints to the picker's minute precision */
7423
+ function normalizeConstraints(constraints) {
7424
+ return {
7425
+ minDateTime: truncateDateTimeToMinute(constraints.minDateTime),
7426
+ maxDateTime: truncateDateTimeToMinute(constraints.maxDateTime),
7427
+ minTime: constraints.minTime ? truncateToMinute(constraints.minTime) : undefined,
7428
+ maxTime: constraints.maxTime ? truncateToMinute(constraints.maxTime) : undefined,
7429
+ };
7430
+ }
7431
+ class DateTimePickerState {
7432
+ date;
7433
+ time;
7434
+ constraints;
7435
+ constructor(date, time, constraints) {
7436
+ this.date = date;
7437
+ this.time = time;
7438
+ this.constraints = normalizeConstraints(constraints);
7439
+ Object.freeze(this);
7440
+ }
7441
+ static empty(constraints = {}) {
7442
+ return new DateTimePickerState(undefined, midnight(), constraints);
7443
+ }
7444
+ /**
7445
+ * Build a state from an external value (the value-prop sync path).
7446
+ * The time is truncated to minute precision and the whole value is
7447
+ * clamped into [minDateTime, maxDateTime]: no state can ever hold an
7448
+ * out-of-range selection, regardless of where the value came from.
7449
+ */
7450
+ static fromValue(value, constraints = {}) {
7451
+ if (!value)
7452
+ return new DateTimePickerState(undefined, midnight(), constraints);
7453
+ const base = new DateTimePickerState(value.toPlainDate(), truncateToMinute(value.toPlainTime()), constraints);
7454
+ return base.clampedIntoRange();
7455
+ }
7456
+ /** Combined date+time; undefined when no date is selected. */
7457
+ get value() {
7458
+ return this.date ? this.date.toPlainDateTime(this.time) : undefined;
7459
+ }
7460
+ /**
7461
+ * Effective minimum time of day for the currently selected date:
7462
+ * when the selected date is the minDateTime boundary date, the boundary's
7463
+ * time (minute-truncated) replaces the static minTime.
7464
+ */
7465
+ get effectiveMinTime() {
7466
+ return this.effectiveMinTimeFor(this.date);
7467
+ }
7468
+ /** Effective maximum time of day for the currently selected date (see effectiveMinTime). */
7469
+ get effectiveMaxTime() {
7470
+ return this.effectiveMaxTimeFor(this.date);
7471
+ }
7472
+ /**
7473
+ * Select (or clear) the date.
7474
+ * - Clearing the date resets the whole selection (time back to 00:00).
7475
+ * - When the current time is out of range for the new date, it falls back
7476
+ * to the effective minimum time for that date (or 00:00).
7477
+ * - When even the fallback is out of range the date is rejected and the
7478
+ * same instance is returned.
7479
+ */
7480
+ withDate(date) {
7481
+ if (!date) {
7482
+ return new DateTimePickerState(undefined, midnight(), this.constraints);
7483
+ }
7484
+ if (this.isInRange(date.toPlainDateTime(this.time))) {
7485
+ return new DateTimePickerState(date, this.time, this.constraints);
7486
+ }
7487
+ const fallbackTime = this.effectiveMinTimeFor(date) ?? midnight();
7488
+ if (this.isInRange(date.toPlainDateTime(fallbackTime))) {
7489
+ return new DateTimePickerState(date, fallbackTime, this.constraints);
7490
+ }
7491
+ return this;
7492
+ }
7493
+ /**
7494
+ * Select the time (minute-truncated). An out-of-range time for the
7495
+ * selected date is rejected: the same instance is returned so the UI can
7496
+ * snap back to the previous time. Without a date any time is accepted
7497
+ * (there is no combination to validate yet).
7498
+ */
7499
+ withTime(time) {
7500
+ const truncated = truncateToMinute(time);
7501
+ if (this.date && !this.isInRange(this.date.toPlainDateTime(truncated))) {
7502
+ return this;
7503
+ }
7504
+ return new DateTimePickerState(this.date, truncated, this.constraints);
7505
+ }
7506
+ /**
7507
+ * Apply "now" (Now button), truncated to minute precision. Rejected
7508
+ * (same instance returned) when the truncated now is out of range.
7509
+ */
7510
+ withNow(now) {
7511
+ const date = now.toPlainDate();
7512
+ const time = truncateToMinute(now.toPlainTime());
7513
+ if (!this.isInRange(date.toPlainDateTime(time))) {
7514
+ return this;
7515
+ }
7516
+ return new DateTimePickerState(date, time, this.constraints);
7517
+ }
7518
+ /**
7519
+ * Reset the time to its default: the effective minimum for the current
7520
+ * date when 00:00 would be out of range (boundary dates), else 00:00.
7521
+ * The result is always in range - this is the clear-time path.
7522
+ */
7523
+ withTimeCleared() {
7524
+ if (!this.date) {
7525
+ return new DateTimePickerState(undefined, midnight(), this.constraints);
7526
+ }
7527
+ return new DateTimePickerState(this.date, midnight(), this.constraints).clampedIntoRange();
7528
+ }
7529
+ /** Reset the selection (no date, time back to 00:00), keeping the constraints. */
7530
+ clear() {
7531
+ return new DateTimePickerState(undefined, midnight(), this.constraints);
7532
+ }
7533
+ /**
7534
+ * Replace the constraints. The current selection is clamped into the new
7535
+ * [minDateTime, maxDateTime] range so it can never be left out of range.
7536
+ */
7537
+ withConstraints(constraints) {
7538
+ return new DateTimePickerState(this.date, this.time, constraints).clampedIntoRange();
7539
+ }
7540
+ /**
7541
+ * Clamp the selection into [minDateTime, maxDateTime]: a combined value
7542
+ * below the minimum becomes the minimum (date and time), one above the
7543
+ * maximum becomes the maximum. In-range states return themselves.
7544
+ */
7545
+ clampedIntoRange() {
7546
+ const combined = this.value;
7547
+ if (!combined)
7548
+ return this;
7549
+ const { minDateTime, maxDateTime } = this.constraints;
7550
+ if (minDateTime && Temporal.PlainDateTime.compare(combined, minDateTime) < 0) {
7551
+ return new DateTimePickerState(minDateTime.toPlainDate(), truncateToMinute(minDateTime.toPlainTime()), this.constraints);
7552
+ }
7553
+ if (maxDateTime && Temporal.PlainDateTime.compare(combined, maxDateTime) > 0) {
7554
+ return new DateTimePickerState(maxDateTime.toPlainDate(), truncateToMinute(maxDateTime.toPlainTime()), this.constraints);
7555
+ }
7556
+ return this;
7557
+ }
7558
+ effectiveMinTimeFor(date) {
7559
+ const { minDateTime, minTime } = this.constraints;
7560
+ if (date && minDateTime && date.equals(minDateTime.toPlainDate())) {
7561
+ return truncateToMinute(minDateTime.toPlainTime());
7562
+ }
7563
+ return minTime;
7564
+ }
7565
+ effectiveMaxTimeFor(date) {
7566
+ const { maxDateTime, maxTime } = this.constraints;
7567
+ if (date && maxDateTime && date.equals(maxDateTime.toPlainDate())) {
7568
+ return truncateToMinute(maxDateTime.toPlainTime());
7569
+ }
7570
+ return maxTime;
7571
+ }
7572
+ isInRange(combined) {
7573
+ const { minDateTime, maxDateTime } = this.constraints;
7574
+ if (minDateTime && Temporal.PlainDateTime.compare(combined, minDateTime) < 0)
7575
+ return false;
7576
+ if (maxDateTime && Temporal.PlainDateTime.compare(combined, maxDateTime) > 0)
7577
+ return false;
7578
+ return true;
7579
+ }
7580
+ }
7581
+
7582
+ // useCwDateTimePickerTemporal - thin glue between DateTimePickerState and the
7583
+ // CwDateTimePickerTemporal component. All picker logic lives in the domain
7584
+ // class; this hook only holds the instance in React state, syncs it with the
7585
+ // external value prop, and converts PlainTime <-> "HH:mm" at the CwTimePicker
7586
+ // string boundary.
7587
+ //
7588
+ // Emission model: an accepted operation returns a NEW instance and the hook
7589
+ // emits its `value`; a rejected operation returns the SAME instance and
7590
+ // nothing is emitted (CwTimePicker snaps its text back to the value prop as
7591
+ // soon as the typed entry is complete and invalid).
7592
+ //
7593
+ // The time string is empty until a date is selected (visual only): without a
7594
+ // date the whole value is undefined, so showing the default 00:00 would
7595
+ // suggest a selection that doesn't exist.
7596
+ function plainTimeToHHmm(time) {
7597
+ return `${String(time.hour).padStart(2, "0")}:${String(time.minute).padStart(2, "0")}`;
7598
+ }
7599
+ /** "HH:mm" -> PlainTime; unparseable input yields undefined (ignored by the caller) */
7600
+ function hhmmToPlainTime(time) {
7601
+ try {
7602
+ return Temporal.PlainTime.from(time);
7603
+ }
7604
+ catch {
7605
+ return undefined;
7606
+ }
7607
+ }
7608
+ function optionalTimeToHHmm(time) {
7609
+ return time ? plainTimeToHHmm(time) : undefined;
7610
+ }
7611
+ function plainDateTimesEqual(a, b) {
7612
+ if (!a || !b)
7613
+ return a === b;
7614
+ return a.equals(b);
7615
+ }
7616
+ function useCwDateTimePickerTemporal({ value, onChange, minDateTime, maxDateTime, minTime, maxTime, }) {
7617
+ const constraints = React.useMemo(() => ({
7618
+ minDateTime,
7619
+ maxDateTime,
7620
+ minTime: minTime ? hhmmToPlainTime(minTime) : undefined,
7621
+ maxTime: maxTime ? hhmmToPlainTime(maxTime) : undefined,
7622
+ // ISO-string deps keep the object stable across re-created Temporal instances
7623
+ }), [minDateTime?.toString(), maxDateTime?.toString(), minTime, maxTime]);
7624
+ const [state, setState] = React.useState(() => DateTimePickerState.fromValue(value, constraints));
7625
+ // Track the previous value prop to detect external changes.
7626
+ const prevValueRef = React.useRef(value);
7627
+ React.useEffect(() => {
7628
+ if (!plainDateTimesEqual(value, prevValueRef.current)) {
7629
+ prevValueRef.current = value;
7630
+ setState(prev => DateTimePickerState.fromValue(value, prev.constraints));
7631
+ }
7632
+ }, [value]);
7633
+ React.useEffect(() => {
7634
+ setState(prev => prev.withConstraints(constraints));
7635
+ }, [constraints]);
7636
+ const apply = React.useCallback((next) => {
7637
+ if (next === state)
7638
+ return; // operation rejected by the domain - no emission
7639
+ setState(next);
7640
+ onChange(next.value);
7641
+ }, [state, onChange]);
7642
+ const selectDate = React.useCallback((date) => {
7643
+ apply(state.withDate(date));
7644
+ }, [state, apply]);
7645
+ const selectTime = React.useCallback((time) => {
7646
+ if (!time) {
7647
+ // Cleared time input: reset to the in-range default for the current date
7648
+ apply(state.withTimeCleared());
7649
+ return;
7650
+ }
7651
+ const parsed = hhmmToPlainTime(time);
7652
+ if (parsed) {
7653
+ apply(state.withTime(parsed));
7654
+ }
7655
+ }, [state, apply]);
7656
+ const selectNow = React.useCallback(() => {
7657
+ apply(state.withNow(Temporal.Now.plainDateTimeISO()));
7658
+ }, [state, apply]);
7659
+ return {
7660
+ date: state.date,
7661
+ time: state.date ? plainTimeToHHmm(state.time) : "",
7662
+ minDate: minDateTime?.toPlainDate(),
7663
+ maxDate: maxDateTime?.toPlainDate(),
7664
+ effectiveMinTime: optionalTimeToHHmm(state.effectiveMinTime),
7665
+ effectiveMaxTime: optionalTimeToHHmm(state.effectiveMaxTime),
7666
+ selectDate,
7667
+ selectTime,
7668
+ selectNow,
7669
+ };
7670
+ }
7671
+
7672
+ function CwDateTimePickerTemporal({ value, onChange, minDateTime, maxDateTime, disabledDates, disabledMatcher, timeInterval = 15, minTime, maxTime, labelProps, alignProps, datePlaceholder = "dd.MM.yyyy", timePlaceholder = "HH:mm", disabled, required, className, showClear = true, popupPosition = "left-bottom", numberOfMonths = 1, showNowButton = false, nowLabel = "Now", locale: locale$1 = locale.enGB, }) {
7673
+ const picker = useCwDateTimePickerTemporal({
7674
+ value,
7675
+ onChange,
7676
+ minDateTime,
7677
+ maxDateTime,
7678
+ minTime,
7679
+ maxTime,
7680
+ });
7681
+ return jsxRuntime.jsx("div", { className: `cw-datetimepicker cw-datetimepicker-separate ${className || ""}`, children: jsxRuntime.jsxs(CwAlign, { ...alignProps, itemProp: required ? "required" : "", children: [labelProps && (jsxRuntime.jsx(CwLabel, { ...labelProps, children: labelProps.text })), jsxRuntime.jsxs("div", { className: "cw-flex-row cw-align-left-center cw-gap-small", children: [jsxRuntime.jsx(CwDatePickerTemporal, { value: picker.date, onChange: picker.selectDate, minDate: picker.minDate, maxDate: picker.maxDate, disabledDates: disabledDates, disabledMatcher: disabledMatcher, placeholder: datePlaceholder, disabled: disabled, required: required, showClear: showClear, numberOfMonths: numberOfMonths, popupPosition: popupPosition, locale: locale$1 }), jsxRuntime.jsx(CwTimePicker, { value: picker.time, onChange: picker.selectTime, interval: timeInterval, minTime: picker.effectiveMinTime, maxTime: picker.effectiveMaxTime, placeholder: timePlaceholder, disabled: disabled, required: required, showClear: showClear, popupPosition: popupPosition }), showNowButton && (jsxRuntime.jsx(CwButton, { type: "button", variant: "outline", onClick: picker.selectNow, disabled: disabled, text: nowLabel }))] })] }) });
7682
+ }
7683
+
7684
+ // dateRangePresetsTemporal.ts
7685
+ // Temporal-typed counterpart of dateRangePresets.ts (used by CwDateRangePickerTemporal).
7686
+ // Each preset is evaluated at click time; a reference date can be injected for testing.
7687
+ const ref = (today) => today ?? Temporal.Now.plainDateISO();
7688
+ /** Monday as first day of the week (ISO dayOfWeek: 1 = Mon … 7 = Sun). */
7689
+ const startOfWeek = (d) => d.subtract({ days: d.dayOfWeek - 1 });
7690
+ const startOfMonth = (d) => d.with({ day: 1 });
7691
+ const endOfMonth = (d) => d.with({ day: d.daysInMonth });
7692
+ /** First day of the quarter that contains `d`. */
7693
+ const startOfQuarter = (d) => Temporal.PlainDate.from({ year: d.year, month: Math.floor((d.month - 1) / 3) * 3 + 1, day: 1 });
7694
+ const PRESET_LIBRARY_TEMPORAL = {
7695
+ // === PAST DAYS ===
7696
+ today: {
7697
+ key: "today",
7698
+ label: "Today",
7699
+ getValue: (t) => { const d = ref(t); return { from: d, to: d }; },
7700
+ },
7701
+ yesterday: {
7702
+ key: "yesterday",
7703
+ label: "Yesterday",
7704
+ getValue: (t) => { const d = ref(t).subtract({ days: 1 }); return { from: d, to: d }; },
7705
+ },
7706
+ past2Days: {
7707
+ key: "past2Days",
7708
+ label: "Past 2 Days",
7709
+ getValue: (t) => { const d = ref(t); return { from: d.subtract({ days: 2 }), to: d }; },
7710
+ },
7711
+ past3Days: {
7712
+ key: "past3Days",
7713
+ label: "Past 3 Days",
7714
+ getValue: (t) => { const d = ref(t); return { from: d.subtract({ days: 3 }), to: d }; },
7715
+ },
7716
+ past7Days: {
7717
+ key: "past7Days",
7718
+ label: "Past 7 days",
7719
+ getValue: (t) => { const d = ref(t); return { from: d.subtract({ days: 7 }), to: d }; },
7720
+ },
7721
+ past14Days: {
7722
+ key: "past14Days",
7723
+ label: "Past 14 days",
7724
+ getValue: (t) => { const d = ref(t); return { from: d.subtract({ days: 14 }), to: d }; },
7725
+ },
7726
+ past30Days: {
7727
+ key: "past30Days",
7728
+ label: "Past 30 days",
7729
+ getValue: (t) => { const d = ref(t); return { from: d.subtract({ days: 30 }), to: d }; },
7730
+ },
7731
+ past90Days: {
7732
+ key: "past90Days",
7733
+ label: "Past 90 days",
7734
+ getValue: (t) => { const d = ref(t); return { from: d.subtract({ days: 90 }), to: d }; },
7735
+ },
7736
+ // === NEXT DAYS ===
7737
+ next7Days: {
7738
+ key: "next7Days",
7739
+ label: "Next 7 days",
7740
+ getValue: (t) => { const d = ref(t); return { from: d, to: d.add({ days: 7 }) }; },
7741
+ },
7742
+ next14Days: {
7743
+ key: "next14Days",
7744
+ label: "Next 14 days",
7745
+ getValue: (t) => { const d = ref(t); return { from: d, to: d.add({ days: 14 }) }; },
7746
+ },
7747
+ next30Days: {
7748
+ key: "next30Days",
7749
+ label: "Next 30 days",
7750
+ getValue: (t) => { const d = ref(t); return { from: d, to: d.add({ days: 30 }) }; },
7751
+ },
7752
+ // === WEEKS (Monday-first) ===
7753
+ thisWeek: {
7754
+ key: "thisWeek",
7755
+ label: "This week",
7756
+ getValue: (t) => { const s = startOfWeek(ref(t)); return { from: s, to: s.add({ days: 6 }) }; },
7757
+ },
7758
+ lastWeek: {
7759
+ key: "lastWeek",
7760
+ label: "Last week",
7761
+ getValue: (t) => { const end = startOfWeek(ref(t)).subtract({ days: 1 }); return { from: end.subtract({ days: 6 }), to: end }; },
7762
+ },
7763
+ nextWeek: {
7764
+ key: "nextWeek",
7765
+ label: "Next week",
7766
+ getValue: (t) => { const s = startOfWeek(ref(t)).add({ days: 7 }); return { from: s, to: s.add({ days: 6 }) }; },
7767
+ },
7768
+ // === MONTHS ===
7769
+ thisMonth: {
7770
+ key: "thisMonth",
7771
+ label: "This month",
7772
+ getValue: (t) => { const d = ref(t); return { from: startOfMonth(d), to: endOfMonth(d) }; },
7773
+ },
7774
+ lastMonth: {
7775
+ key: "lastMonth",
7776
+ label: "Last month",
7777
+ getValue: (t) => { const d = startOfMonth(ref(t)).subtract({ months: 1 }); return { from: d, to: endOfMonth(d) }; },
7778
+ },
7779
+ nextMonth: {
7780
+ key: "nextMonth",
7781
+ label: "Next month",
7782
+ getValue: (t) => { const d = startOfMonth(ref(t)).add({ months: 1 }); return { from: d, to: endOfMonth(d) }; },
7783
+ },
7784
+ // === QUARTERS ===
7785
+ thisQuarter: {
7786
+ key: "thisQuarter",
7787
+ label: "This quarter",
7788
+ getValue: (t) => { const from = startOfQuarter(ref(t)); return { from, to: from.add({ months: 3 }).subtract({ days: 1 }) }; },
7789
+ },
7790
+ lastQuarter: {
7791
+ key: "lastQuarter",
7792
+ label: "Last quarter",
7793
+ getValue: (t) => { const from = startOfQuarter(ref(t)).subtract({ months: 3 }); return { from, to: from.add({ months: 3 }).subtract({ days: 1 }) }; },
7794
+ },
7795
+ nextQuarter: {
7796
+ key: "nextQuarter",
7797
+ label: "Next quarter",
7798
+ getValue: (t) => { const from = startOfQuarter(ref(t)).add({ months: 3 }); return { from, to: from.add({ months: 3 }).subtract({ days: 1 }) }; },
7799
+ },
7800
+ // === YEAR ===
7801
+ thisYear: {
7802
+ key: "thisYear",
7803
+ label: "This year",
7804
+ getValue: (t) => {
7805
+ const y = ref(t).year;
7806
+ return { from: Temporal.PlainDate.from({ year: y, month: 1, day: 1 }), to: Temporal.PlainDate.from({ year: y, month: 12, day: 31 }) };
7807
+ },
7808
+ },
7809
+ lastYear: {
7810
+ key: "lastYear",
7811
+ label: "Last year",
7812
+ getValue: (t) => {
7813
+ const y = ref(t).year - 1;
7814
+ return { from: Temporal.PlainDate.from({ year: y, month: 1, day: 1 }), to: Temporal.PlainDate.from({ year: y, month: 12, day: 31 }) };
7815
+ },
7816
+ },
7817
+ };
7818
+ /**
7819
+ * Helper to get presets by their keys.
7820
+ * @example getPresetsByKeysTemporal(['thisWeek', 'past7Days', 'past30Days'])
7821
+ */
7822
+ const getPresetsByKeysTemporal = (keys) => keys.map((key) => PRESET_LIBRARY_TEMPORAL[key]).filter((preset) => preset !== undefined);
7823
+
7824
+ function CwDateRangePickerTemporal({ value, onChange, minDate, maxDate, disabledDates, disabledMatcher, maxRangeDays, defaultMonth, labelProps, alignProps, placeholderFrom = "From date", placeholderTo = "To date", displayFormat = "dd.MM.yyyy", disabled, required, className, showClear = true, popupPosition = "left-bottom", numberOfMonths = 2, locale: locale$1 = locale.enGB, yearRangeStart, yearRangeEnd, showPresets = false, presetKeys, customPresets, }) {
7825
+ const [isOpen, setIsOpen] = React.useState(false);
7826
+ const [inputFromValue, setInputFromValue] = React.useState("");
7827
+ const [inputToValue, setInputToValue] = React.useState("");
7828
+ const [rangeErrorMessage, setRangeErrorMessage] = React.useState(null);
7829
+ const [focusedInput, setFocusedInput] = React.useState();
7830
+ const containerRef = React.useRef(null);
7831
+ const wrapperRef = React.useRef(null);
7832
+ const inputFromRef = React.useRef(null);
7833
+ const inputToRef = React.useRef(null);
7834
+ const prevValueRef = React.useRef(undefined);
7835
+ const prevDisplayFormatRef = React.useRef(displayFormat);
7836
+ const rangeError = React.useCallback(() => (maxRangeDays ? `Range cannot exceed ${maxRangeDays} days` : "Invalid date range"), [maxRangeDays]);
7837
+ const handleClose = React.useCallback(() => {
7838
+ setIsOpen(false);
7839
+ setFocusedInput(undefined);
7840
+ }, []);
7841
+ const { popupRef, popupStyle, renderPopup } = usePickerPopup({
7842
+ anchorRef: wrapperRef,
7843
+ isOpen,
7844
+ onClose: handleClose,
7845
+ position: popupPosition,
7846
+ });
7847
+ // Calculate presets to render
7848
+ const presetsToRender = React.useMemo(() => {
7849
+ let presets = [];
7850
+ if (presetKeys && presetKeys.length > 0) {
7851
+ presets = getPresetsByKeysTemporal(presetKeys);
7852
+ }
7853
+ if (customPresets && customPresets.length > 0) {
7854
+ presets = [...presets, ...customPresets];
7855
+ }
7856
+ return presets;
7857
+ }, [presetKeys, customPresets]);
7858
+ // Validate date range
7859
+ const validateRange = React.useCallback((from, to) => {
7860
+ if (!from || !to)
7861
+ return true; // Partial ranges are OK during selection
7862
+ if (Temporal.PlainDate.compare(from, to) > 0)
7863
+ return false;
7864
+ if (maxRangeDays) {
7865
+ const daysDiff = from.until(to, { largestUnit: "day" }).days;
7866
+ if (daysDiff > maxRangeDays)
7867
+ return false;
7868
+ }
7869
+ return true;
7870
+ }, [maxRangeDays]);
7871
+ // Sync input values with prop value
7872
+ React.useEffect(() => {
7873
+ const currentFrom = value?.from?.toString();
7874
+ const currentTo = value?.to?.toString();
7875
+ const prevFrom = prevValueRef.current?.from;
7876
+ const prevTo = prevValueRef.current?.to;
7877
+ if (currentFrom !== prevFrom ||
7878
+ currentTo !== prevTo ||
7879
+ prevDisplayFormatRef.current !== displayFormat) {
7880
+ prevValueRef.current = { from: currentFrom, to: currentTo };
7881
+ prevDisplayFormatRef.current = displayFormat;
7882
+ setInputFromValue(value?.from ? formatPlainDate(value.from, displayFormat) : "");
7883
+ setInputToValue(value?.to ? formatPlainDate(value.to, displayFormat) : "");
7884
+ }
7885
+ }, [value, displayFormat]);
7886
+ const handleRangeSelect = React.useCallback((range, selectedDay) => {
7887
+ const selected = jsDateToPlainDate(selectedDay);
7888
+ let newRange;
7889
+ if (focusedInput === 'from') {
7890
+ newRange = { from: selected, to: value?.to };
7891
+ if (newRange.to && Temporal.PlainDate.compare(selected, newRange.to) > 0) {
7892
+ newRange.to = undefined;
7893
+ setFocusedInput('to');
7894
+ setRangeErrorMessage(null);
7895
+ }
7896
+ else if (newRange.to) {
7897
+ if (!validateRange(newRange.from, newRange.to)) {
7898
+ setRangeErrorMessage(rangeError());
7899
+ return;
7900
+ }
7901
+ setRangeErrorMessage(null);
7902
+ setIsOpen(false);
7903
+ setFocusedInput(undefined);
7904
+ }
7905
+ else {
7906
+ setFocusedInput('to');
7907
+ setRangeErrorMessage(null);
7908
+ }
7909
+ }
7910
+ else if (focusedInput === 'to') {
7911
+ newRange = { from: value?.from, to: selected };
7912
+ if (newRange.from && Temporal.PlainDate.compare(selected, newRange.from) < 0) {
7913
+ newRange.from = undefined;
7914
+ setFocusedInput('from');
7915
+ setRangeErrorMessage(null);
7916
+ }
7917
+ else if (newRange.from) {
7918
+ if (!validateRange(newRange.from, newRange.to)) {
7919
+ setRangeErrorMessage(rangeError());
7920
+ return;
7921
+ }
7922
+ setRangeErrorMessage(null);
7923
+ setIsOpen(false);
7924
+ setFocusedInput(undefined);
7925
+ }
7926
+ else {
7927
+ setFocusedInput('from');
7928
+ setRangeErrorMessage(null);
7929
+ }
7930
+ }
7931
+ else {
7932
+ if (!range) {
7933
+ onChange(undefined);
7934
+ return;
7935
+ }
7936
+ newRange = {
7937
+ from: range.from ? jsDateToPlainDate(range.from) : undefined,
7938
+ to: range.to ? jsDateToPlainDate(range.to) : undefined,
7939
+ };
7940
+ if (range.from && range.to) {
7941
+ if (!validateRange(newRange.from, newRange.to)) {
7942
+ setRangeErrorMessage(rangeError());
7943
+ return;
7944
+ }
7945
+ setRangeErrorMessage(null);
7946
+ setIsOpen(false);
7947
+ setFocusedInput(undefined);
7948
+ }
7949
+ else if (range.from) {
7950
+ setFocusedInput('to');
7951
+ setRangeErrorMessage(null);
7952
+ }
7953
+ else {
7954
+ setFocusedInput('from');
7955
+ setRangeErrorMessage(null);
7956
+ }
7957
+ }
7958
+ onChange(newRange);
7959
+ }, [onChange, validateRange, value, focusedInput, rangeError]);
7960
+ const handleClearFrom = React.useCallback((e) => {
7961
+ e.stopPropagation();
7962
+ onChange({ from: undefined, to: value?.to });
7963
+ setInputFromValue("");
7964
+ }, [onChange, value]);
7965
+ const handleClearTo = React.useCallback((e) => {
7966
+ e.stopPropagation();
7967
+ onChange({ from: value?.from, to: undefined });
7968
+ setInputToValue("");
7969
+ }, [onChange, value]);
7970
+ const handleInputFromClick = React.useCallback(() => {
7971
+ if (!disabled) {
7972
+ setIsOpen(true);
7973
+ setFocusedInput('from');
7974
+ }
7975
+ }, [disabled]);
7976
+ const handleInputToClick = React.useCallback(() => {
7977
+ if (!disabled) {
7978
+ setIsOpen(true);
7979
+ setFocusedInput('to');
7980
+ }
7981
+ }, [disabled]);
7982
+ const handleInputFromChange = React.useCallback((e) => {
7983
+ const newValue = e.currentTarget.value;
7984
+ setInputFromValue(newValue);
7985
+ const parsed = parseDate(newValue, displayFormat);
7986
+ if (parsed) {
7987
+ if (validate(parsed, minDate, maxDate) && validateRange(parsed, value?.to)) {
7988
+ onChange({ from: parsed, to: value?.to });
7989
+ }
7990
+ }
7991
+ else if (newValue === "") {
7992
+ onChange({ from: undefined, to: value?.to });
7993
+ }
7994
+ }, [displayFormat, minDate, maxDate, validateRange, onChange, value]);
7995
+ const handleInputToChange = React.useCallback((e) => {
7996
+ const newValue = e.currentTarget.value;
7997
+ setInputToValue(newValue);
7998
+ const parsed = parseDate(newValue, displayFormat);
7999
+ if (parsed) {
8000
+ if (validate(parsed, minDate, maxDate) && validateRange(value?.from, parsed)) {
8001
+ onChange({ from: value?.from, to: parsed });
8002
+ }
8003
+ }
8004
+ else if (newValue === "") {
8005
+ onChange({ from: value?.from, to: undefined });
8006
+ }
8007
+ }, [displayFormat, minDate, maxDate, validateRange, onChange, value]);
8008
+ const handleInputBlur = React.useCallback((type) => {
8009
+ const inputValue = type === 'from' ? inputFromValue : inputToValue;
8010
+ const currentValue = type === 'from' ? value?.from : value?.to;
8011
+ const trimmed = inputValue?.trim();
8012
+ if (trimmed) {
8013
+ const parsed = parseDate(trimmed, displayFormat);
8014
+ if (parsed && validate(parsed, minDate, maxDate)) {
8015
+ const newRange = type === 'from'
8016
+ ? { from: parsed, to: value?.to }
8017
+ : { from: value?.from, to: parsed };
8018
+ if (validateRange(newRange.from, newRange.to)) {
8019
+ onChange(newRange);
8020
+ if (type === 'from') {
8021
+ setInputFromValue(formatPlainDate(parsed, displayFormat));
8022
+ }
8023
+ else {
8024
+ setInputToValue(formatPlainDate(parsed, displayFormat));
8025
+ }
8026
+ return;
8027
+ }
8028
+ }
8029
+ }
8030
+ // Reset to current value if invalid
8031
+ if (type === 'from') {
8032
+ setInputFromValue(currentValue ? formatPlainDate(currentValue, displayFormat) : "");
8033
+ }
8034
+ else {
8035
+ setInputToValue(currentValue ? formatPlainDate(currentValue, displayFormat) : "");
8036
+ }
8037
+ }, [inputFromValue, inputToValue, value, displayFormat, minDate, maxDate, validateRange, onChange]);
8038
+ const handleInputKeyDown = React.useCallback((e, type) => {
8039
+ if (e.key === "Enter") {
8040
+ e.preventDefault();
8041
+ if (type === 'from') {
8042
+ inputFromRef.current?.blur();
8043
+ inputToRef.current?.focus();
8044
+ }
8045
+ else {
8046
+ inputToRef.current?.blur();
8047
+ setIsOpen(false);
8048
+ }
8049
+ }
8050
+ else if (e.key === "Escape") {
8051
+ setIsOpen(false);
8052
+ if (type === 'from') {
8053
+ inputFromRef.current?.blur();
8054
+ }
8055
+ else {
8056
+ inputToRef.current?.blur();
8057
+ }
8058
+ }
8059
+ }, []);
8060
+ // Handle preset click
8061
+ const handlePresetClick = React.useCallback((preset, e) => {
8062
+ e.preventDefault();
8063
+ e.stopPropagation();
8064
+ const nextRange = preset.getValue();
8065
+ if (!validate(nextRange.from, minDate, maxDate) ||
8066
+ !validate(nextRange.to, minDate, maxDate) ||
8067
+ !validateRange(nextRange.from, nextRange.to)) {
8068
+ setRangeErrorMessage(rangeError());
8069
+ return;
8070
+ }
8071
+ setRangeErrorMessage(null);
8072
+ onChange(nextRange);
8073
+ setIsOpen(false);
8074
+ }, [maxDate, minDate, onChange, rangeError, validateRange]);
8075
+ // Derive start/end months for the year dropdown range, guarding against inverted yearRange props
8076
+ const dropdownStartMonth = React.useMemo(() => {
8077
+ const inferredStart = minDate ? minDate.year : Temporal.Now.plainDateISO().year - 10;
8078
+ const inferredEnd = yearRangeEnd ?? (maxDate ? maxDate.year : Temporal.Now.plainDateISO().year + 5);
8079
+ const year = Math.min(yearRangeStart ?? inferredStart, inferredEnd);
8080
+ return new Date(year, 0, 1);
8081
+ }, [yearRangeStart, yearRangeEnd, minDate, maxDate]);
8082
+ const dropdownEndMonth = React.useMemo(() => {
8083
+ const inferredEnd = maxDate ? maxDate.year : Temporal.Now.plainDateISO().year + 5;
8084
+ const inferredStart = yearRangeStart ?? (minDate ? minDate.year : Temporal.Now.plainDateISO().year - 10);
8085
+ const year = Math.max(yearRangeEnd ?? inferredEnd, inferredStart);
8086
+ return new Date(year, 11, 31);
8087
+ }, [yearRangeStart, yearRangeEnd, minDate, maxDate]);
8088
+ // Memoize disabled days (convert Temporal → Date for DayPicker)
8089
+ const disabledDays = React.useMemo(() => {
8090
+ const baseDisabled = [
8091
+ ...(disabledDates?.map(plainDateToJsDate) || []),
8092
+ ...(minDate ? [{ before: plainDateToJsDate(minDate) }] : []),
8093
+ ...(maxDate ? [{ after: plainDateToJsDate(maxDate) }] : []),
8094
+ ...(disabledMatcher ? [disabledMatcher] : []),
8095
+ ];
8096
+ // If maxRangeDays is set and we have a "from" date, disable dates beyond the range
8097
+ if (maxRangeDays) {
8098
+ if (value?.from) {
8099
+ const maxAllowedDate = value.from.add({ days: maxRangeDays });
8100
+ if (focusedInput !== 'from') {
8101
+ baseDisabled.push({ after: plainDateToJsDate(maxAllowedDate) });
8102
+ }
8103
+ if (focusedInput === 'to' && !value?.to) {
8104
+ const minAllowedDate = value.from.subtract({ days: maxRangeDays });
8105
+ baseDisabled.push({ before: plainDateToJsDate(minAllowedDate) });
8106
+ }
8107
+ }
8108
+ if (value?.to && !value?.from && focusedInput === 'from') {
8109
+ const minAllowedDate = value.to.subtract({ days: maxRangeDays });
8110
+ baseDisabled.push({ before: plainDateToJsDate(minAllowedDate) });
8111
+ }
8112
+ }
8113
+ return baseDisabled;
8114
+ }, [disabledDates, minDate, maxDate, disabledMatcher, maxRangeDays, value, focusedInput]);
8115
+ const selectedRange = React.useMemo(() => {
8116
+ if (value?.from || value?.to) {
8117
+ return {
8118
+ from: value?.from ? plainDateToJsDate(value.from) : undefined,
8119
+ to: value?.to ? plainDateToJsDate(value.to) : undefined,
8120
+ };
8121
+ }
8122
+ return undefined;
8123
+ }, [value]);
8124
+ const defaultMonthJsDate = defaultMonth
8125
+ ? new Date(defaultMonth.year, defaultMonth.month - 1, 1)
8126
+ : (value?.from ? plainDateToJsDate(value.from) : undefined);
8127
+ return (jsxRuntime.jsx("div", { ref: containerRef, className: `cw-rangepicker ${className || ""}`, children: jsxRuntime.jsxs(CwAlign, { ...alignProps, itemProp: required ? "required" : "", children: [labelProps && (jsxRuntime.jsx(CwLabel, { ...labelProps, children: labelProps.text })), jsxRuntime.jsxs("div", { ref: wrapperRef, className: rangeStyles.rangeWrapper, children: [jsxRuntime.jsxs("div", { className: styles$4.pickerWrapper, children: [jsxRuntime.jsx("input", { ref: inputFromRef, type: "text", value: inputFromValue, placeholder: placeholderFrom, onChange: handleInputFromChange, onBlur: () => handleInputBlur('from'), onClick: handleInputFromClick, onKeyDown: (e) => handleInputKeyDown(e, 'from'), disabled: disabled, required: required, "data-focused": focusedInput === 'from' }), jsxRuntime.jsx("div", { className: styles$4.pickerIcons, children: showClear && value?.from && !disabled ? (jsxRuntime.jsx(CwButton, { type: "button", variant: "icon", color: "neutral", icon: "close", onClick: handleClearFrom, tabIndex: -1, "aria-label": "Clear from date" })) : (jsxRuntime.jsx(CwIcon, { iconId: "calendar" })) })] }), jsxRuntime.jsx(CwIcon, { iconId: "arrow-right", size: "medium" }), jsxRuntime.jsxs("div", { className: styles$4.pickerWrapper, children: [jsxRuntime.jsx("input", { ref: inputToRef, type: "text", value: inputToValue, placeholder: placeholderTo, onChange: handleInputToChange, onBlur: () => handleInputBlur('to'), onClick: handleInputToClick, onKeyDown: (e) => handleInputKeyDown(e, 'to'), disabled: disabled, required: required, "data-focused": focusedInput === 'to' }), jsxRuntime.jsx("div", { className: styles$4.pickerIcons, children: showClear && value?.to && !disabled ? (jsxRuntime.jsx(CwButton, { type: "button", variant: "icon", color: "neutral", icon: "close", onClick: handleClearTo, tabIndex: -1, "aria-label": "Clear to date" })) : (jsxRuntime.jsx(CwIcon, { iconId: "calendar" })) })] }), renderPopup(jsxRuntime.jsxs("div", { ref: popupRef, className: `${styles$4.pickerPopup} ${rangeStyles.rangePopup}`, style: popupStyle, children: [jsxRuntime.jsxs("div", { className: rangeStyles.rangeCalendarRow, children: [showPresets && presetsToRender.length > 0 && (jsxRuntime.jsx("div", { className: rangeStyles.presetList, children: presetsToRender.map((preset) => (jsxRuntime.jsx("button", { type: "button", onClick: (e) => handlePresetClick(preset, e), children: preset.label }, preset.key))) })), jsxRuntime.jsx(reactDayPicker.DayPicker, { mode: "range", selected: selectedRange, onSelect: handleRangeSelect, disabled: disabledDays, numberOfMonths: numberOfMonths, defaultMonth: defaultMonthJsDate, locale: locale$1, captionLayout: "dropdown", startMonth: dropdownStartMonth, endMonth: dropdownEndMonth, modifiers: {
8128
+ today: new Date(),
8129
+ }, modifiersClassNames: {
8130
+ today: "rdp-day-today",
8131
+ } })] }), jsxRuntime.jsx("div", { role: "alert", "aria-live": "polite", className: rangeStyles.rangeError, children: rangeErrorMessage })] }))] })] }) }));
8132
+ }
8133
+
7113
8134
  const ResourcesTitleList = ({ resources, canBePinned, includesPinned, onCrewPinning, onClickResourceContextMenu, ResourceTitleComponent, }) => {
7114
8135
  const onClickContextMenu = React.useCallback((key, resource) => {
7115
8136
  if (onClickResourceContextMenu) {
@@ -10067,8 +11088,10 @@ exports.CwContextMenu = CwContextMenu;
10067
11088
  exports.CwDatePicker = CwDatePicker;
10068
11089
  exports.CwDatePickerTemporal = CwDatePickerTemporal;
10069
11090
  exports.CwDateRangePicker = CwDateRangePicker;
11091
+ exports.CwDateRangePickerTemporal = CwDateRangePickerTemporal;
10070
11092
  exports.CwDateTimePicker = CwDateTimePicker;
10071
11093
  exports.CwDateTimePickerCompact = CwDateTimePickerCompact;
11094
+ exports.CwDateTimePickerTemporal = CwDateTimePickerTemporal;
10072
11095
  exports.CwDialog = CwDialog;
10073
11096
  exports.CwDigit = CwDigit;
10074
11097
  exports.CwDisplayMessage = CwDisplayMessage;
@@ -10111,6 +11134,7 @@ exports.CwOption = CwOption;
10111
11134
  exports.CwPopoverButton = CwPopoverButton;
10112
11135
  exports.CwReportModal = CwReportModal;
10113
11136
  exports.CwScheduler = CwScheduler;
11137
+ exports.CwSearchAsync = CwSearchAsync;
10114
11138
  exports.CwSearchInput = CwSearchInput;
10115
11139
  exports.CwSelect = CwSelect;
10116
11140
  exports.CwSelectList = CwSelectList;
@@ -10153,6 +11177,7 @@ exports.OnRightClickRow = OnRightClickRow;
10153
11177
  exports.OnRightDragStart = OnRightDragStart;
10154
11178
  exports.OnStartClickHeaderEvent = OnStartClickHeaderEvent;
10155
11179
  exports.OnUnpinRow = OnUnpinRow;
11180
+ exports.PRESET_LIBRARY_TEMPORAL = PRESET_LIBRARY_TEMPORAL;
10156
11181
  exports.PinRowHeader = PinRowHeader;
10157
11182
  exports.Resource = Resource;
10158
11183
  exports.Scheduler = Scheduler;
@@ -10166,6 +11191,7 @@ exports.eventIsVisible = eventIsVisible;
10166
11191
  exports.filterVisibleEvents = filterVisibleEvents;
10167
11192
  exports.getDefaultDivisions = getDefaultDivisions;
10168
11193
  exports.getEventSizes = getEventSizes;
11194
+ exports.getPresetsByKeysTemporal = getPresetsByKeysTemporal;
10169
11195
  exports.itemsToMultiFilterTags = itemsToMultiFilterTags;
10170
11196
  exports.useCwMessage = useCwMessage;
10171
11197
  exports.useSortableList = useSortableList;