@jsb188/form 0.0.0-stage → 1.1.2

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 (64) hide show
  1. package/README.md +132 -2
  2. package/css/form.css +2 -0
  3. package/package.json +40 -5
  4. package/src/assets.d.ts +1 -0
  5. package/src/libs/SchemaForm.tsx +158 -0
  6. package/src/libs/SchemaForm.types.ts +165 -0
  7. package/src/libs/defineForm.ts +11 -0
  8. package/src/libs/rules.ts +126 -0
  9. package/src/libs/useField.ts +16 -0
  10. package/src/libs/useSchemaForm.helpers.ts +71 -0
  11. package/src/libs/useSchemaForm.ts +268 -0
  12. package/src/libs/validation.ts +42 -0
  13. package/src/main.ts +40 -0
  14. package/src/modules/FieldLabel.tsx +28 -0
  15. package/src/modules/Form-Input.tsx +2 -0
  16. package/src/modules/Form-Line.tsx +126 -0
  17. package/src/modules/Form.helpers.ts +12 -0
  18. package/src/modules/Form.tsx +14 -0
  19. package/src/modules/FormItem.tsx +117 -0
  20. package/src/modules/FormOptions.tsx +12 -0
  21. package/src/modules/FormUI.tsx +2 -0
  22. package/src/modules/Input.tsx +16 -0
  23. package/src/modules/InputClick.tsx +48 -0
  24. package/src/modules/InputWithButton.tsx +37 -0
  25. package/src/modules/ListItemForm.tsx +345 -0
  26. package/src/modules/ListItemForm.types.ts +50 -0
  27. package/src/modules/PasswordInput.tsx +36 -0
  28. package/src/modules/PopOverInput.tsx +75 -0
  29. package/src/modules/SMSCodeInput.tsx +118 -0
  30. package/src/modules/SchemaField.tsx +104 -0
  31. package/src/modules/Select.tsx +163 -0
  32. package/src/modules/Textarea.tsx +33 -0
  33. package/src/modules/TimeInput.helpers.ts +73 -0
  34. package/src/modules/TimeInput.tsx +159 -0
  35. package/src/modules/TimeInput.types.ts +43 -0
  36. package/src/modules/UploadInput.tsx +141 -0
  37. package/src/modules/composeFormInput.tsx +88 -0
  38. package/src/types/form.ts +65 -0
  39. package/src/ui/ContentEditable.tsx +70 -0
  40. package/src/ui/Form.types.ts +138 -0
  41. package/src/ui/FormOptions.tsx +125 -0
  42. package/src/ui/FormUI.tsx +237 -0
  43. package/src/ui/Input.helpers.ts +7 -0
  44. package/src/ui/Input.tsx +199 -0
  45. package/src/ui/Input.types.ts +48 -0
  46. package/src/ui/InputButtons.tsx +41 -0
  47. package/src/ui/InputControls.tsx +68 -0
  48. package/src/ui/Label.tsx +46 -0
  49. package/src/ui/LineForm.tsx +34 -0
  50. package/src/ui/SMSCodeInput.tsx +51 -0
  51. package/src/ui/Select.tsx +33 -0
  52. package/src/ui/Textarea.tsx +96 -0
  53. package/src/ui/TimeInput.tsx +140 -0
  54. package/tests/controller.test.tsx +336 -0
  55. package/tests/controls.test.tsx +261 -0
  56. package/tests/schema-form.test.tsx +303 -0
  57. package/tests/settings-definitions.test.ts +129 -0
  58. package/tests/sms-input.test.tsx +131 -0
  59. package/tests/time-input.test.tsx +395 -0
  60. package/tests/types.ts +102 -0
  61. package/tests/upload-input.test.tsx +114 -0
  62. package/tests/validation.test.ts +65 -0
  63. package/tsconfig.json +13 -0
  64. package/vitest.config.ts +8 -0
@@ -0,0 +1,75 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type { POInputObj, POStateValue } from '@jsb188/react/types/PopOver.d';
3
+ import { memo, type FormEvent, type KeyboardEvent, type MouseEvent } from 'react';
4
+ import type { PONavItemBase } from '@jsb188/react-web/ui/PopOverUI';
5
+ import { InputUI as Input } from '../ui/Input';
6
+
7
+ /*
8
+ * Reuse the input presentation for named popover values and Enter submissions.
9
+ */
10
+ export const POInput = memo(
11
+ (p: {
12
+ item: POInputObj;
13
+ name: string;
14
+ value?: POStateValue;
15
+ disabled?: boolean;
16
+ onClickItem: PONavItemBase['onClickItem'];
17
+ onSubmit?: PONavItemBase['onSubmit'];
18
+ }) => {
19
+ const { item, name, value, onClickItem, onSubmit } = p;
20
+ const disabled = p.disabled || item.disabled;
21
+ const canClear = item.type === 'search' && typeof value === 'string' && value.length > 0 && !disabled;
22
+
23
+ /*
24
+ * Clear the search draft and return focus to its input without submitting or dismissing the menu.
25
+ */
26
+ const onClear = (event: MouseEvent) => {
27
+ event.preventDefault();
28
+ event.stopPropagation();
29
+ if (disabled) return;
30
+ onClickItem(name, '', true);
31
+ event.currentTarget.parentElement?.querySelector('input')?.focus();
32
+ };
33
+
34
+ /*
35
+ * Update the popover draft without treating each keystroke as a selected option.
36
+ */
37
+ const onInput = (event: FormEvent<Element>) => {
38
+ if (!disabled) onClickItem(name, (event.currentTarget as HTMLInputElement).value, true);
39
+ };
40
+
41
+ /*
42
+ * Submit the current input value on Enter while allowing text composition to finish.
43
+ */
44
+ const onKeyDown = (event: KeyboardEvent<Element>) => {
45
+ if (disabled || event.key !== 'Enter' || event.nativeEvent.isComposing || !onSubmit) return;
46
+ event.preventDefault();
47
+ event.stopPropagation();
48
+ onSubmit(name, (event.currentTarget as HTMLInputElement).value);
49
+ };
50
+
51
+ return (
52
+ <Input
53
+ className="m_3 ft_sm"
54
+ borderRadiusClassName="r_xs"
55
+ name={name}
56
+ preset={item.preset}
57
+ type={item.type === 'search' ? 'text' : item.type}
58
+ label={item.label}
59
+ ariaLabel={item.ariaLabel || item.label || item.placeholder}
60
+ placeholder={item.placeholder}
61
+ autoFocus={item.autoFocus}
62
+ disabled={disabled}
63
+ maxLength={item.maxLength}
64
+ value={typeof value === 'string' ? value : ''}
65
+ rightIconName={canClear ? 'circle-x' : undefined}
66
+ rightIconAriaLabel={i18n.t('c.clear_search')}
67
+ onClickRight={onClear}
68
+ onInput={onInput}
69
+ onKeyDown={onKeyDown}
70
+ />
71
+ );
72
+ },
73
+ );
74
+
75
+ POInput.displayName = 'POInput';
@@ -0,0 +1,118 @@
1
+ import { useIsKeyboardLayerActive } from '@jsb188/react/states/keyboardLayer';
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import { SMSCodeInputUI } from '../ui/SMSCodeInput';
4
+
5
+ /**
6
+ * SMS verification code input
7
+ */
8
+
9
+ interface SMSCodeInputProps {
10
+ saving?: boolean;
11
+ error?: any;
12
+ codeLength?: number;
13
+ onChangeCode?: (code: string) => void;
14
+ onSubmit: (code: string) => void;
15
+ }
16
+
17
+ export function SMSCodeInput(p: SMSCodeInputProps) {
18
+ const { saving, error, onChangeCode, onSubmit } = p;
19
+ const isKeyboardLayerActive = useIsKeyboardLayerActive();
20
+ const inputRef = useRef<HTMLInputElement>(null);
21
+ const [code, setCode] = useState('');
22
+ const [focused, setFocused] = useState(false);
23
+ const codeLength = p.codeLength || 5;
24
+ const currentCode = useRef('');
25
+ const submittedCode = useRef<string | null>(null);
26
+ const wasSaving = useRef(!!saving);
27
+ const submitCallback = useRef(onSubmit);
28
+ submitCallback.current = onSubmit;
29
+
30
+ /**
31
+ * Check if the user is already typing into a text-entry element.
32
+ */
33
+
34
+ const hasActiveTextInput = () => {
35
+ const activeEl = document.activeElement as HTMLElement | null;
36
+ if (!activeEl) {
37
+ return false;
38
+ }
39
+
40
+ const tagName = activeEl.tagName;
41
+ return tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT' || activeEl.isContentEditable;
42
+ };
43
+
44
+ /* Submit a complete code once, outside React state updaters, until it changes or verification fails. */
45
+ const submitCode = (value: string) => {
46
+ if (saving || value.length !== codeLength || submittedCode.current === value) return;
47
+ submittedCode.current = value;
48
+ submitCallback.current(value);
49
+ };
50
+
51
+ /* Let normal editing and paste shortcuts work; Enter uses the same submission guard as typing. */
52
+ const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
53
+ if (e.key === 'Enter') {
54
+ e.preventDefault();
55
+ submitCode(currentCode.current);
56
+ }
57
+ };
58
+
59
+ /* Normalize pasted or autofilled codes without losing leading zeroes or submitting extra characters. */
60
+ const onChange = (value: string) => {
61
+ if (saving) return;
62
+ const nextCode = value.replace(/\D/g, '').slice(0, codeLength);
63
+ if (nextCode !== currentCode.current) submittedCode.current = null;
64
+ currentCode.current = nextCode;
65
+ setCode(nextCode);
66
+ submitCode(nextCode);
67
+ };
68
+
69
+ useEffect(() => {
70
+ if (!focused && !saving) {
71
+ const keyDownListener = (e: KeyboardEvent) => {
72
+ if (!isKeyboardLayerActive(e) || hasActiveTextInput()) {
73
+ return;
74
+ }
75
+
76
+ if ((e.key === 'Backspace' || /^\d$/.test(e.key)) && !e.defaultPrevented && !e.metaKey && !e.altKey && !e.ctrlKey) {
77
+ e.preventDefault();
78
+ inputRef.current?.focus();
79
+ onChange(e.key === 'Backspace' ? currentCode.current.slice(0, -1) : currentCode.current + e.key);
80
+ }
81
+ };
82
+
83
+ addEventListener('keydown', keyDownListener, false);
84
+ return () => {
85
+ removeEventListener('keydown', keyDownListener, false);
86
+ };
87
+ }
88
+ }, [focused, saving, codeLength]);
89
+
90
+ useEffect(() => {
91
+ // A canceled or otherwise unfinished request may be retried with the same code after it stops saving.
92
+ if (wasSaving.current && !saving) submittedCode.current = null;
93
+ wasSaving.current = !!saving;
94
+ if (!saving && error) {
95
+ currentCode.current = '';
96
+ submittedCode.current = null;
97
+ setCode('');
98
+ }
99
+ }, [saving, error]);
100
+
101
+ useEffect(() => {
102
+ onChangeCode?.(code);
103
+ }, [code, onChangeCode]);
104
+
105
+ return (
106
+ <SMSCodeInputUI
107
+ value={code}
108
+ codeLength={codeLength}
109
+ saving={saving}
110
+ focused={focused}
111
+ inputRef={inputRef}
112
+ onFocus={() => setFocused(true)}
113
+ onBlur={() => setFocused(false)}
114
+ onKeyDown={onKeyDown}
115
+ onChange={onChange}
116
+ />
117
+ );
118
+ }
@@ -0,0 +1,104 @@
1
+ import { usePopOverActions, usePopOverDefinition, usePopOverEvent } from '@jsb188/react/states';
2
+ import { useEffect } from 'react';
3
+ import type { FieldDefinition, FormController } from '../libs/SchemaForm.types';
4
+ import { getFieldValue } from '../libs/useSchemaForm.helpers';
5
+ import { Input, InputClick, InputTimeFromDate, InputWithButton, PasswordInput, Select, Textarea } from './Form';
6
+
7
+ /* Bind one named field to its controller and the existing bundled control interactions. */
8
+ export function SchemaField(p: {
9
+ form: FormController<any, any>;
10
+ name: string;
11
+ field: FieldDefinition;
12
+ disabled?: boolean;
13
+ preset?: string | null;
14
+ labelClassName?: string;
15
+ formId: string;
16
+ }) {
17
+ const { form, name, field, formId } = p;
18
+ const scope = { values: form.values, context: form.context };
19
+ const { kind, visibleWhen, disabledWhen, resolve, onValueChange, ...staticProps } = field;
20
+ const appearance = { ...staticProps, ...resolve?.(scope) };
21
+ const popOverId = appearance.popOverProps ? `${formId}_${appearance.popOverProps.id}` : null;
22
+ const popOverEvent = usePopOverEvent({ popOverId });
23
+ const openPopOver = usePopOverDefinition();
24
+ const { acknowledgePopOverEvent, closePopOver } = usePopOverActions();
25
+ const visible = visibleWhen?.(scope) !== false;
26
+ const globallyDisabled = form.disabled || p.disabled || disabledWhen?.(scope) || false;
27
+ const disabled = globallyDisabled || appearance.disabled || false;
28
+
29
+ /* Route a value change through the controller before any explicit domain callback. */
30
+ const changeValue = (value: unknown) => {
31
+ if (disabled) return;
32
+ form.setFieldValue(name, value);
33
+ onValueChange?.(value, form);
34
+ };
35
+
36
+ useEffect(() => {
37
+ if (kind !== 'click' || !popOverEvent || popOverEvent.action !== 'ITEM' || popOverEvent.name !== name) return;
38
+ acknowledgePopOverEvent(popOverEvent.eventId);
39
+ if (visible && !disabled && !appearance.locked) changeValue(popOverEvent.value);
40
+ closePopOver();
41
+ }, [popOverEvent]);
42
+
43
+ if (!visible) return null;
44
+ const value = getFieldValue(form.values, name);
45
+ const props = {
46
+ ...appearance,
47
+ id: `${formId}_${name}`,
48
+ name,
49
+ value: value ?? '',
50
+ preset: appearance.preset ?? p.preset ?? undefined,
51
+ labelClassName: appearance.labelClassName ?? p.labelClassName,
52
+ disabled,
53
+ error: !!form.errors[name]?.length,
54
+ onClearLocked: () => changeValue(''),
55
+ onChange: (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => changeValue(event.target.value),
56
+ onBlur: (event: React.FocusEvent<any>) => {
57
+ form.setFieldTouched(name);
58
+ appearance.onBlur?.(event);
59
+ },
60
+ };
61
+ // Each bundled control has a different DOM event signature; binding is normalized at this boundary.
62
+ switch (kind) {
63
+ case 'password':
64
+ return <PasswordInput {...(props as React.ComponentProps<typeof PasswordInput>)} />;
65
+ case 'textarea':
66
+ return <Textarea {...(props as React.ComponentProps<typeof Textarea>)} />;
67
+ case 'select':
68
+ return (
69
+ <Select
70
+ {...({ ...props, onChange: changeValue } as React.ComponentProps<typeof Select>)}
71
+ value={value ?? null}
72
+ options={appearance.options ?? []}
73
+ />
74
+ );
75
+ case 'action':
76
+ return (
77
+ <InputWithButton
78
+ {...(props as React.ComponentProps<typeof InputWithButton>)}
79
+ onClickButton={(event) => {
80
+ if (!globallyDisabled) appearance.onClickButton?.(event);
81
+ }}
82
+ />
83
+ );
84
+ case 'time':
85
+ return (
86
+ <InputTimeFromDate
87
+ {...(props as React.ComponentProps<typeof InputTimeFromDate>)}
88
+ resetKey={form.resetKey}
89
+ value={value}
90
+ onChange={(_event, _name, nextDate) => changeValue(nextDate)}
91
+ />
92
+ );
93
+ case 'click':
94
+ return (
95
+ <InputClick
96
+ {...(props as React.ComponentProps<typeof InputClick>)}
97
+ focused={openPopOver?.id === popOverId}
98
+ popOverProps={appearance.popOverProps ? { ...appearance.popOverProps, id: popOverId } : undefined}
99
+ />
100
+ );
101
+ default:
102
+ return <Input {...(props as React.ComponentProps<typeof Input>)} />;
103
+ }
104
+ }
@@ -0,0 +1,163 @@
1
+ import { cn } from '@jsb188/app/utils/string.ts';
2
+ import { usePopOverActions, usePopOverEvent } from '@jsb188/react/states';
3
+ import { PopOverButton } from '@jsb188/react-web/modules/popover/PopOverButton';
4
+ import { useEffect, useId, useMemo } from 'react';
5
+ import type { SelectType, SelectValue } from '../ui/Form.types';
6
+ import { getHtmlFor } from '../ui/FormUI';
7
+ import { SelectValueDisplay } from '../ui/Select';
8
+ import { Label } from './FieldLabel';
9
+
10
+ /**
11
+ * Form select with input-compatible presets and an icon-aware option menu.
12
+ */
13
+
14
+ export function Select(p: SelectType) {
15
+ const {
16
+ ariaLabel,
17
+ id,
18
+ name,
19
+ options,
20
+ value,
21
+ label,
22
+ placeholder,
23
+ placeholderIconName,
24
+ info,
25
+ locked,
26
+ disabled,
27
+ editable,
28
+ focused,
29
+ error,
30
+ fullWidth,
31
+ className,
32
+ selectClassName,
33
+ borderRadiusClassName,
34
+ preset,
35
+ focusStyle,
36
+ fontSizeClassName,
37
+ labelClassName,
38
+ labelPaddingClassName,
39
+ matchTriggerWidth,
40
+ leftIconClassName,
41
+ rightIconClassName,
42
+ position,
43
+ xOffset = 0,
44
+ yOffset = 5,
45
+ popOverClassName,
46
+ zClassName,
47
+ onFocus,
48
+ onBlur,
49
+ onClick,
50
+ onChange,
51
+ children,
52
+ } = p;
53
+ const htmlFor = getHtmlFor(id, name);
54
+ const selectId = useId().replaceAll(':', '_');
55
+ const optionFieldName = `select_${selectId}`;
56
+ const popOverId = `form_select_${selectId}`;
57
+ const selectedOption = options.find((option) => option.value === value);
58
+ const isDisabled = disabled || locked || editable === false;
59
+ const popOverEvent = usePopOverEvent({ popOverId });
60
+ const { acknowledgePopOverEvent, closePopOver } = usePopOverActions();
61
+ const popOverOptions = useMemo(
62
+ () =>
63
+ options.map((option) => ({
64
+ __type: 'SINGLE_OPTION_LIST_ITEM' as const,
65
+ name: optionFieldName,
66
+ value: option.value,
67
+ text: option.text,
68
+ description: option.description,
69
+ iconName: option.iconName,
70
+ className: option.className,
71
+ textClassName: option.textClassName,
72
+ disabled: option.disabled,
73
+ })),
74
+ [options, optionFieldName],
75
+ );
76
+
77
+ useEffect(() => {
78
+ if (popOverEvent?.action !== 'ITEM' || popOverEvent.name !== optionFieldName) {
79
+ return;
80
+ }
81
+
82
+ const nextValue = popOverEvent.value as SelectValue;
83
+ const option = options.find((option) => option.value === nextValue);
84
+ acknowledgePopOverEvent(popOverEvent.eventId);
85
+ if (!isDisabled && option && !option.disabled) onChange?.(nextValue, name, option);
86
+ closePopOver();
87
+ }, [popOverEvent]);
88
+
89
+ return (
90
+ <div
91
+ className={cn(
92
+ 'form_el rel',
93
+ preset,
94
+ `focus_${focusStyle || 'shadow'}`,
95
+ fullWidth ? 'fs' : '',
96
+ className,
97
+ error ? 'error' : '',
98
+ focused ? 'focused' : '',
99
+ isDisabled ? 'disabled' : '',
100
+ )}
101
+ onFocus={onFocus}
102
+ onBlur={onBlur}
103
+ >
104
+ {!label ? null : (
105
+ <Label
106
+ htmlFor={htmlFor}
107
+ info={info}
108
+ iconName={locked ? 'locked' : undefined}
109
+ fontSizeClassName={fontSizeClassName ?? (preset === 'tiny' ? 'ft_xs' : undefined)}
110
+ labelClassName={labelClassName}
111
+ paddingClassName={labelPaddingClassName}
112
+ >
113
+ {label}
114
+ </Label>
115
+ )}
116
+
117
+ <PopOverButton
118
+ as="button"
119
+ ariaLabel={ariaLabel}
120
+ domId={htmlFor}
121
+ id={popOverId}
122
+ disabled={isDisabled}
123
+ position={position || 'bottom_left'}
124
+ offsetX={xOffset}
125
+ offsetY={yOffset}
126
+ popOverClassName={popOverClassName}
127
+ matchTriggerWidth={matchTriggerWidth}
128
+ zClassName={zClassName}
129
+ className={cn(
130
+ 'w_f form_input form_select rel h_spread no_link',
131
+ borderRadiusClassName ?? 'r_sm',
132
+ selectClassName,
133
+ editable === false ? 'cl_md' : disabled ? 'disabled' : '',
134
+ error ? 'error' : '',
135
+ )}
136
+ onClick={onClick ? (e) => onClick(e, name) : undefined}
137
+ iface={{
138
+ name: 'PO_LIST',
139
+ variables: {
140
+ initialState: {
141
+ [optionFieldName]: value,
142
+ },
143
+ options: popOverOptions,
144
+ },
145
+ }}
146
+ >
147
+ <SelectValueDisplay
148
+ selectedOption={selectedOption}
149
+ placeholder={placeholder}
150
+ placeholderIconName={placeholderIconName}
151
+ leftIconClassName={leftIconClassName}
152
+ rightIconClassName={rightIconClassName}
153
+ locked={locked}
154
+ disabled={disabled}
155
+ />
156
+ </PopOverButton>
157
+
158
+ {children}
159
+ </div>
160
+ );
161
+ }
162
+
163
+ export type { SelectOptionType, SelectType, SelectValue } from '../ui/Form.types';
@@ -0,0 +1,33 @@
1
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
2
+ import type { TextareaType } from '../ui/Form.types';
3
+ import type { LabelType } from '../ui/Label';
4
+ import { TextareaUI } from '../ui/Textarea';
5
+ import { Label } from './FieldLabel';
6
+
7
+ /*
8
+ * Measure the existing hidden text virtualizer so a controlled textarea grows with its content.
9
+ */
10
+ export const Textarea = (p: TextareaType & LabelType) => {
11
+ const virtualizerRef = useRef<HTMLDivElement>(null);
12
+ const [height, setHeight] = useState(p.minHeight ?? 150);
13
+ useLayoutEffect(() => {
14
+ // Resize before paint so a new line cannot briefly scroll inside the previous height.
15
+ const element = virtualizerRef.current;
16
+ if (element) setHeight(element.offsetHeight);
17
+ }, [p.value]);
18
+ useEffect(() => {
19
+ const element = virtualizerRef.current;
20
+ if (!element || !globalThis.ResizeObserver) return;
21
+ const resizeObserver = new ResizeObserver(() => setHeight(element.offsetHeight));
22
+ resizeObserver.observe(element);
23
+ return () => resizeObserver.disconnect();
24
+ }, []);
25
+ return (
26
+ <TextareaUI
27
+ {...p}
28
+ height={height}
29
+ virtualizerRef={virtualizerRef}
30
+ labelComponent={Label}
31
+ />
32
+ );
33
+ };
@@ -0,0 +1,73 @@
1
+ import { DateTime } from 'luxon';
2
+ import type { TimeEditResult, TimeFormField, TimeFormValues, TimeInputValue } from './TimeInput.types';
3
+
4
+ /* Read a stored instant in its display zone; Date and ISO strings retain their existing instant semantics. */
5
+ function getZonedDate(value: TimeInputValue, timeZone?: string | null): DateTime {
6
+ return DateTime.fromJSDate(value instanceof Date ? value : new Date(value || NaN), { zone: timeZone || 'local' });
7
+ }
8
+
9
+ /* Return a stable instant key so unrelated rerenders do not discard a partial time draft. */
10
+ export function getTimeSourceKey(value: TimeInputValue): string | number {
11
+ if (value == null || value === '') return '';
12
+ const timestamp = value instanceof Date ? value.getTime() : new Date(value).getTime();
13
+ return Number.isNaN(timestamp) ? String(value) : timestamp;
14
+ }
15
+
16
+ /* Treat empty input as an unfinished edit and reject decimals, signs and values outside the clock range. */
17
+ export function checkTimeError(value: string, field: TimeFormField): boolean {
18
+ if (value === '') return false;
19
+ if (field === 'AMPM') return value !== 'AM' && value !== 'PM';
20
+ const numeric = Number(value);
21
+ return !/^\d{1,2}$/.test(value) || numeric < (field === 'hours' ? 1 : 0) || numeric > (field === 'hours' ? 12 : 59);
22
+ }
23
+
24
+ /* Display midnight and noon as 12 AM/PM in the requested zone, with unpadded minutes matching the existing UI. */
25
+ export function getTimeFormValues(value: TimeInputValue, timeZone?: string | null): TimeFormValues {
26
+ if (value == null || value === '') return { hours: '', minutes: '', AMPM: 'AM' };
27
+ const date = getZonedDate(value, timeZone);
28
+ if (!date.isValid) return { hours: '', minutes: '', AMPM: 'AM' };
29
+ return { hours: String(date.hour % 12 || 12), minutes: String(date.minute), AMPM: date.hour >= 12 ? 'PM' : 'AM' };
30
+ }
31
+
32
+ /*
33
+ * Resolve a complete local time on the stored local date. Empty values use the supplied current date at whole-minute precision.
34
+ * Reject spring-forward gaps; for repeated times preserve the stored offset when available, otherwise choose the earlier instant.
35
+ */
36
+ export function resolveTimeInput(p: {
37
+ value: TimeInputValue;
38
+ values: TimeFormValues;
39
+ timeZone?: string | null;
40
+ fallbackDate: Date;
41
+ }): TimeEditResult {
42
+ const errors = Object.fromEntries(
43
+ (['hours', 'minutes', 'AMPM'] as const).filter((field) => checkTimeError(p.values[field], field)).map((field) => [field, true]),
44
+ );
45
+ if (Object.keys(errors).length) return { status: 'invalid', reason: 'fields', errors };
46
+ if (!p.values.hours || !p.values.minutes || !p.values.AMPM) return { status: 'incomplete' };
47
+ const isEmpty = p.value == null || p.value === '';
48
+ const base = getZonedDate(isEmpty ? p.fallbackDate : p.value, p.timeZone);
49
+ if (!base.isValid)
50
+ return {
51
+ status: 'invalid',
52
+ reason: !DateTime.fromMillis(0, { zone: p.timeZone || 'local' }).isValid ? 'zone' : 'date',
53
+ errors: { hours: true, minutes: true },
54
+ };
55
+ const hour = (Number(p.values.hours) % 12) + (p.values.AMPM === 'PM' ? 12 : 0);
56
+ const minute = Number(p.values.minutes);
57
+ const candidate = base.set({ hour, minute, ...(isEmpty ? { second: 0, millisecond: 0 } : {}) });
58
+ if (
59
+ !candidate.isValid ||
60
+ candidate.year !== base.year ||
61
+ candidate.month !== base.month ||
62
+ candidate.day !== base.day ||
63
+ candidate.hour !== hour ||
64
+ candidate.minute !== minute
65
+ ) {
66
+ return { status: 'invalid', reason: 'gap', errors: { hours: true, minutes: true } };
67
+ }
68
+ const possible = candidate.getPossibleOffsets();
69
+ const resolved =
70
+ (!isEmpty ? possible.find((date) => date.offset === base.offset) : undefined) ??
71
+ possible.reduce((earlier, date) => (date.toMillis() < earlier.toMillis() ? date : earlier));
72
+ return { status: 'valid', value: resolved.toJSDate() };
73
+ }