feat: migrate public TimeField with shared date input parts

This commit is contained in:
maoyingjie
2026-10-26 17:56:41 +08:00
parent d74ad1b711
commit 97263d82e1
45 changed files with 2415 additions and 61 deletions
@@ -0,0 +1,404 @@
<!-- Adapted from HeroUI 3.2.6 / ce90ea3 time-field; Apache-2.0, see third-party/HEROUI-LICENSE. -->
<script lang="ts">
import {
computed,
defineComponent,
getCurrentInstance,
h,
nextTick,
onMounted,
provide,
ref,
shallowRef,
watch,
watchEffect,
type PropType,
type SlotsType,
type VNodeChild,
} from "vue";
import { TimeFieldRoot } from "reka-ui";
import {
Time,
parseTime,
parseDateTime,
parseZonedDateTime,
type CalendarDateTime,
type ZonedDateTime,
} from "@internationalized/date";
import { timeFieldVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import { useAcceptedDateValue } from "../date/model";
import { serializeDateValue } from "../date/value";
import EmptyDateBridge from "../date/EmptyDateBridge";
import {
useChoiceField,
useChoiceForm,
validationInput,
} from "../choice/shared";
import { disabledContextKey } from "../field/disabled";
import type { ValidationBehavior, ValidateResult } from "../field/context";
import { dateFieldKey, type DateSegment } from "../date-field/context";
import PrimitiveNode from "../date-field/PrimitiveNode";
import DateSegments from "../date-field/DateSegments";
export type TimeValue = Time | CalendarDateTime | ZonedDateTime;
export interface TimeFieldRenderProps {
value: TimeValue | null;
isDisabled: boolean;
isReadOnly: boolean;
isRequired: boolean;
isInvalid: boolean;
isFocusWithin: boolean;
isFocused: boolean;
isFocusVisible: boolean;
validationErrors: string[];
}
const clock = (value: TimeValue) =>
new Time(value.hour, value.minute, value.second, value.millisecond);
export default defineComponent({
name: "TimeField",
inheritAttrs: false,
slots: Object as SlotsType<{
default?: (state: TimeFieldRenderProps) => VNodeChild;
}>,
props: {
modelValue: {
type: [Object, null] as PropType<TimeValue | null>,
default: undefined,
},
value: {
type: [Object, null] as PropType<TimeValue | null>,
default: undefined,
},
defaultValue: [Object, null] as PropType<TimeValue | null>,
placeholderValue: [Object, null] as PropType<TimeValue | null>,
minValue: [Object, null] as PropType<TimeValue | null>,
maxValue: [Object, null] as PropType<TimeValue | null>,
granularity: String as PropType<"hour" | "minute" | "second">,
hourCycle: Number as PropType<12 | 24>,
hideTimeZone: Boolean,
shouldForceLeadingZeros: { type: Boolean, default: undefined },
locale: String,
dir: String as PropType<"ltr" | "rtl">,
fullWidth: Boolean,
as: { type: String, default: "div" },
id: String,
name: String,
form: String,
isDisabled: Boolean,
disabled: Boolean,
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
autoFocus: Boolean,
autoComplete: String,
validationBehavior: String as PropType<ValidationBehavior>,
validate: Function as PropType<(value: TimeValue | null) => ValidateResult>,
},
emits: {
"update:modelValue": (_value: TimeValue | null) => true,
change: (_value: TimeValue | null) => true,
},
setup(props, { attrs, slots, emit, expose }) {
const config = useConfig();
const instance = getCurrentInstance()!;
const accepted: ReturnType<typeof useAcceptedDateValue<TimeValue>> =
useAcceptedDateValue<TimeValue>({
value: () =>
["modelValue", "model-value"].some((key) =>
Object.hasOwn(instance.vnode.props ?? {}, key),
)
? props.modelValue
: props.value,
defaultValue: () => props.defaultValue,
onChange: (value) => {
field.edit();
emit("update:modelValue", value);
emit("change", value);
},
disabled: () => field.field.disabled.value,
readOnly: () => field.field.readOnly.value,
});
const field = useChoiceField(props, attrs, {
kind: "group",
value: accepted.value,
satisfied: () => accepted.value.value !== null,
requiredMessage: "请填写此字段。",
validate: (value) => {
if (
value &&
props.minValue &&
clock(value).compare(clock(props.minValue)) < 0
)
return "时间不能早于最早时间。";
if (
value &&
props.maxValue &&
clock(value).compare(clock(props.maxValue)) > 0
)
return "时间不能晚于最晚时间。";
return props.validate?.(value);
},
});
provide(disabledContextKey, field.field.disabled);
provide(dateFieldKey, {
value: accepted.value,
disabled: field.field.disabled,
readOnly: field.field.readOnly,
required: field.field.required,
invalid: field.field.invalid,
form: () => native.value?.form,
leadingZeros: () => props.shouldForceLeadingZeros,
labelledBy: field.labelledBy,
describedBy: field.describedBy,
ariaLabel: () => attrs["aria-label"],
});
const locale = computed(
() => props.locale ?? config?.locale.value ?? "en-US",
);
const hourCycle = computed<12 | 24>(() => {
if (props.hourCycle) return props.hourCycle;
const cycle = new Intl.DateTimeFormat(locale.value, {
hour: "numeric",
}).resolvedOptions().hourCycle;
return cycle === "h11" || cycle === "h12" ? 12 : 24;
});
const initialPlaceholder = (
props.placeholderValue ??
props.defaultValue ??
accepted.value.value ??
new Time()
).copy();
const lastPlaceholder = shallowRef(initialPlaceholder);
watch(accepted.value, (value) => {
if (value) lastPlaceholder.value = value.copy();
});
const placeholder = computed(
() =>
props.placeholderValue ?? accepted.value.value ?? lastPlaceholder.value,
);
const wire = accepted.wire;
const root = ref<HTMLElement>(),
native = ref<HTMLInputElement>(),
proxy = ref<HTMLInputElement>();
const focused = ref(false);
const focusVisible = ref(false);
const focus = () =>
root.value
?.querySelector<HTMLElement>(
'[data-slot="date-input-group-segment"][tabindex="0"]',
)
?.focus();
function request(value: TimeValue | undefined) {
// The base may convert an empty placeholder to Time and omit milliseconds.
// Apply editable clock fields to the accepted/placeholder class, preserving
// its date, calendar, zone and precision that has no visible segment.
const source =
accepted.value.value ??
props.placeholderValue ??
props.defaultValue ??
initialPlaceholder;
accepted.request(
value
? source.set({
hour: value.hour,
minute:
props.granularity === "hour" ? source.minute : value.minute,
second:
props.granularity === "second" ? value.second : source.second,
})
: null,
);
}
function restoreNative() {
if (native.value)
native.value.value = serializeDateValue(accepted.value.value);
}
useChoiceForm(
proxy,
() => {
accepted.reset();
field.reset();
},
restoreNative,
);
watchEffect(() => field.validity(proxy.value), { flush: "post" });
const signature = computed(
() =>
`${props.granularity ?? "minute"}|${hourCycle.value}|${props.hideTimeZone}`,
);
watch(signature, () => {
const old = root.value?.ownerDocument.activeElement as HTMLElement | null;
const part =
old && root.value?.contains(old)
? old.dataset.rekaTimeFieldSegment
: undefined;
if (part)
void nextTick(() => {
const current = root.value?.ownerDocument.activeElement;
if (current === old || current === root.value?.ownerDocument.body)
(
root.value?.querySelector<HTMLElement>(
`[data-reka-time-field-segment="${part}"]`,
) ??
root.value?.querySelector<HTMLElement>(
'[data-slot="date-input-group-segment"][tabindex="0"]',
)
)?.focus();
});
});
onMounted(() => {
if (props.autoFocus) focus();
});
expose({ element: root, focus });
return () => {
const state = {
value: accepted.value.value,
isDisabled: field.field.disabled.value,
isReadOnly: field.field.readOnly.value,
isRequired: field.field.required.value,
isInvalid: field.field.invalid.value,
isFocusWithin: focused.value,
isFocused: focused.value,
isFocusVisible: focusVisible.value,
validationErrors: field.field.errors.value,
};
const raw = slots.default?.(state);
const children = field.prepare(
Array.isArray(raw) ? raw : raw ? [raw] : [],
true,
);
const overrides = {
id: field.field.controlId.value,
role: "group",
class: timeFieldVariants({ fullWidth: props.fullWidth }),
"data-slot": "time-field",
"data-disabled": state.isDisabled || undefined,
"data-readonly": state.isReadOnly || undefined,
"data-invalid": state.isInvalid || undefined,
"data-required": state.isRequired || undefined,
"data-focus-within": focused.value || undefined,
"aria-label": attrs["aria-label"],
"aria-labelledby": field.labelledBy(),
"aria-describedby": field.describedBy(),
"aria-invalid": state.isInvalid || undefined,
"aria-required": state.isRequired || undefined,
ref: (element: unknown) => {
root.value = element as HTMLElement;
},
onFocusin: (event: FocusEvent) => {
focused.value = true;
focusVisible.value = (event.target as HTMLElement).matches(
":focus-visible",
);
},
onFocusout: (event: FocusEvent) => {
if (
!(event.currentTarget as HTMLElement).contains(
event.relatedTarget as Node | null,
)
) {
focused.value = false;
focusVisible.value = false;
}
},
};
return h(
TimeFieldRoot,
{
key: signature.value,
asChild: true,
modelValue: wire.value,
placeholder: placeholder.value,
granularity: props.granularity ?? "minute",
hourCycle: hourCycle.value,
hideTimeZone: props.hideTimeZone,
locale: locale.value,
dir: props.dir ?? config?.dir.value,
disabled: state.isDisabled,
readonly: state.isReadOnly,
// One shared native validator and a full precision named input own
// submission; the underlying Reka input remains nameless.
"onUpdate:modelValue": request,
},
{
default: ({
segments,
}: {
segments: Pick<DateSegment, "part" | "value">[];
}) =>
h(
PrimitiveNode,
{ as: props.as, consumer: attrs, overrides },
{
default: () =>
h(
DateSegments,
{ segments, kind: "time" },
{
default: () => [
...children,
h(EmptyDateBridge, {
revision: accepted.emptyRevision.value,
}),
h("input", {
ref: native,
type: "text",
class: "hv-choice-input",
tabindex: -1,
"aria-hidden": "true",
autoComplete: props.autoComplete ?? "off",
readonly: state.isReadOnly,
onFocus: focus,
onInput: (event: Event) => {
if (
event.defaultPrevented ||
state.isDisabled ||
state.isReadOnly
) {
restoreNative();
return;
}
const text = (event.target as HTMLInputElement)
.value;
try {
accepted.request(
!text
? undefined
: text.includes("[")
? parseZonedDateTime(text)
: text.includes("T")
? parseDateTime(text)
: parseTime(text),
);
} catch {
restoreNative();
}
void nextTick(restoreNative);
},
name: props.name,
form: props.form,
value: serializeDateValue(accepted.value.value),
disabled: state.isDisabled,
"data-slot": "time-field-value",
}),
validationInput(
proxy,
props,
state.isDisabled || state.isReadOnly,
field.behavior.value,
(event) => field.invalidEvent(event, focus),
),
],
},
),
},
),
},
);
};
},
});
</script>