feat: migrate public DatePicker with shared field and calendar owners
This commit is contained in:
@@ -1,5 +1,13 @@
|
||||
<script setup lang="ts" generic="M extends CalendarSelectionMode = 'single'">
|
||||
import { computed, getCurrentInstance, useAttrs } from "vue";
|
||||
import {
|
||||
computed,
|
||||
getCurrentInstance,
|
||||
inject,
|
||||
nextTick,
|
||||
onMounted,
|
||||
useAttrs,
|
||||
watch,
|
||||
} from "vue";
|
||||
import {
|
||||
GregorianCalendar,
|
||||
toCalendar,
|
||||
@@ -10,6 +18,7 @@ import {
|
||||
import { useChoiceValue } from "../choice/shared";
|
||||
import { copyDateValue, copyDateValues } from "../date/value";
|
||||
import { calendarHeading } from "../date/calendar";
|
||||
import { datePickerKey } from "../date-picker/context";
|
||||
import { useCalendarView } from "./view";
|
||||
import type {
|
||||
CalendarModel,
|
||||
@@ -39,10 +48,19 @@ defineSlots<{
|
||||
}>();
|
||||
const attrs = useAttrs(),
|
||||
instance = getCurrentInstance()!;
|
||||
const picker = inject(datePickerKey, undefined);
|
||||
type Value = DateValue | DateValue[] | null;
|
||||
const copy = (value: Value | undefined): Value =>
|
||||
Array.isArray(value) ? copyDateValues(value) : copyDateValue(value ?? null);
|
||||
const has = (key: string) => Object.hasOwn(instance.vnode.props ?? {}, key);
|
||||
const inheritsValue = computed(
|
||||
() =>
|
||||
!!picker &&
|
||||
!has("modelValue") &&
|
||||
!has("model-value") &&
|
||||
!has("value") &&
|
||||
!has("defaultValue"),
|
||||
);
|
||||
const model = useChoiceValue<Value>(
|
||||
() =>
|
||||
copy(
|
||||
@@ -56,6 +74,10 @@ const model = useChoiceValue<Value>(
|
||||
},
|
||||
);
|
||||
const selectedValues = computed(() => {
|
||||
if (inheritsValue.value) {
|
||||
const value = picker!.value.value;
|
||||
return value ? [value] : [];
|
||||
}
|
||||
const value = model.value.value;
|
||||
return Array.isArray(value) ? value : value ? [value] : [];
|
||||
});
|
||||
@@ -67,10 +89,26 @@ const view = useCalendarView(
|
||||
dates: selectedValues,
|
||||
selected,
|
||||
request,
|
||||
unavailable: (date) => !!props.isDateUnavailable?.(date.copy()),
|
||||
unavailable: (date) =>
|
||||
!!(props.isDateUnavailable ?? picker?.isDateUnavailable)?.(date),
|
||||
multiple: () => props.selectionMode === "multiple",
|
||||
},
|
||||
emit,
|
||||
"calendar",
|
||||
picker
|
||||
? {
|
||||
minValue: () => picker.minValue.value,
|
||||
maxValue: () => picker.maxValue.value,
|
||||
defaultFocusedValue: () => picker.placeholder.value,
|
||||
locale: () => picker.locale.value,
|
||||
dir: () => picker.dir.value,
|
||||
firstDayOfWeek: () => picker.firstDayOfWeek,
|
||||
pageBehavior: () => picker.pageBehavior,
|
||||
isDisabled: () => picker.disabled.value,
|
||||
isReadOnly: () => picker.readOnly.value,
|
||||
isInvalid: () => picker.invalid.value,
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
const {
|
||||
root,
|
||||
@@ -89,6 +127,10 @@ const {
|
||||
function request(value: DateValue) {
|
||||
if (view.disabledDay(value) || view.unavailable(value) || view.readOnly.value)
|
||||
return;
|
||||
if (inheritsValue.value) {
|
||||
picker!.requestDate(value);
|
||||
return;
|
||||
}
|
||||
const fallback = Array.isArray(props.defaultValue)
|
||||
? props.defaultValue[0]
|
||||
: props.defaultValue;
|
||||
@@ -113,6 +155,19 @@ function request(value: DateValue) {
|
||||
);
|
||||
} else if (!selected(value)) model.request(next.copy());
|
||||
}
|
||||
function focusForPicker(open: boolean) {
|
||||
if (!picker || !open) return;
|
||||
void nextTick(() => {
|
||||
if (picker.state.isOpen.value && tabStop.value)
|
||||
focusDate(tabStop.value, true);
|
||||
});
|
||||
}
|
||||
onMounted(() => focusForPicker(!!picker?.state.isOpen.value));
|
||||
watch(
|
||||
() => picker?.state.isOpen.value,
|
||||
(open) => focusForPicker(!!open),
|
||||
{ flush: "post" },
|
||||
);
|
||||
defineExpose({
|
||||
get element() {
|
||||
return root.value;
|
||||
|
||||
@@ -43,6 +43,19 @@ export type CalendarViewProps = Omit<
|
||||
| "selectionMode"
|
||||
| "isDateUnavailable"
|
||||
>;
|
||||
/** Constraints a DatePicker owner passes to an otherwise unbound Calendar. */
|
||||
export interface CalendarInheritedConstraints {
|
||||
minValue?: () => DateValue | undefined;
|
||||
maxValue?: () => DateValue | undefined;
|
||||
defaultFocusedValue?: () => DateValue | undefined;
|
||||
locale?: () => string;
|
||||
dir?: () => "ltr" | "rtl";
|
||||
firstDayOfWeek?: () => import("../date/calendar").CalendarWeekday | undefined;
|
||||
pageBehavior?: () => "visible" | "single" | undefined;
|
||||
isDisabled?: () => boolean;
|
||||
isReadOnly?: () => boolean;
|
||||
isInvalid?: () => boolean;
|
||||
}
|
||||
export interface CalendarSelectionAdapter {
|
||||
dates: ComputedRef<DateValue[]>;
|
||||
selected: (date: DateValue) => boolean;
|
||||
@@ -70,6 +83,7 @@ export function useCalendarView(
|
||||
selection: CalendarSelectionAdapter,
|
||||
emit: ViewEmit,
|
||||
prefix: "calendar" | "range-calendar" = "calendar",
|
||||
inherited?: CalendarInheritedConstraints,
|
||||
) {
|
||||
const instance = getCurrentInstance()!,
|
||||
config = useConfig();
|
||||
@@ -78,25 +92,40 @@ export function useCalendarView(
|
||||
trigger = shallowRef<HTMLElement>();
|
||||
const headingId = `hv-calendar-${useId()}-heading`;
|
||||
const locale = computed(
|
||||
() => props.locale ?? config?.locale.value ?? "en-US",
|
||||
() =>
|
||||
props.locale ?? inherited?.locale?.() ?? config?.locale.value ?? "en-US",
|
||||
);
|
||||
const dir = computed(
|
||||
() => props.dir ?? inherited?.dir?.() ?? config?.dir.value ?? "ltr",
|
||||
);
|
||||
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
|
||||
const timeZone = computed(() => props.timeZone ?? getLocalTimeZone());
|
||||
const disabled = useInheritedDisabled(
|
||||
() => props.isDisabled || props.disabled,
|
||||
() =>
|
||||
props.isDisabled || props.disabled || Boolean(inherited?.isDisabled?.()),
|
||||
);
|
||||
const readOnly = computed(
|
||||
() => !!props.isReadOnly || Boolean(inherited?.isReadOnly?.()),
|
||||
);
|
||||
const readOnly = computed(() => !!props.isReadOnly);
|
||||
const multiple = computed(() => selection.multiple?.() ?? false);
|
||||
const invalid = computed(() => !!props.isInvalid || !!selection.invalid?.());
|
||||
const invalid = computed(
|
||||
() =>
|
||||
!!props.isInvalid ||
|
||||
Boolean(inherited?.isInvalid?.()) ||
|
||||
!!selection.invalid?.(),
|
||||
);
|
||||
const options = computed(() => ({
|
||||
locale: locale.value,
|
||||
firstDayOfWeek: props.firstDayOfWeek,
|
||||
firstDayOfWeek: props.firstDayOfWeek ?? inherited?.firstDayOfWeek?.(),
|
||||
visibleDuration: props.visibleDuration,
|
||||
weeksInMonth: props.weeksInMonth,
|
||||
}));
|
||||
const pageBehavior = computed(
|
||||
() => props.pageBehavior ?? inherited?.pageBehavior?.(),
|
||||
);
|
||||
const initial = copyDateValue(
|
||||
props.defaultFocusedValue ??
|
||||
selection.dates.value[0] ??
|
||||
inherited?.defaultFocusedValue?.() ??
|
||||
today(timeZone.value),
|
||||
);
|
||||
const focusModel = useChoiceValue<DateValue>(
|
||||
@@ -114,7 +143,9 @@ export function useCalendarView(
|
||||
const min = computed(() =>
|
||||
toCalendarDate(
|
||||
dateForLocale(
|
||||
props.minValue ?? new CalendarDate(1900, 1, 1),
|
||||
props.minValue ??
|
||||
inherited?.minValue?.() ??
|
||||
new CalendarDate(1900, 1, 1),
|
||||
locale.value,
|
||||
),
|
||||
),
|
||||
@@ -122,7 +153,9 @@ export function useCalendarView(
|
||||
const max = computed(() =>
|
||||
toCalendarDate(
|
||||
dateForLocale(
|
||||
props.maxValue ?? new CalendarDate(2099, 12, 31),
|
||||
props.maxValue ??
|
||||
inherited?.maxValue?.() ??
|
||||
new CalendarDate(2099, 12, 31),
|
||||
locale.value,
|
||||
),
|
||||
),
|
||||
@@ -226,7 +259,7 @@ export function useCalendarView(
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
[locale, () => props.visibleDuration, () => props.firstDayOfWeek],
|
||||
[locale, () => props.visibleDuration, () => options.value.firstDayOfWeek],
|
||||
() => {
|
||||
anchor.value = aligned(focus.value);
|
||||
},
|
||||
@@ -247,7 +280,7 @@ export function useCalendarView(
|
||||
function pageStep(direction: -1 | 1) {
|
||||
const { unit, count } = calendarDuration(props.visibleDuration);
|
||||
return {
|
||||
[unit]: direction * (props.pageBehavior === "single" ? 1 : count),
|
||||
[unit]: direction * (pageBehavior.value === "single" ? 1 : count),
|
||||
};
|
||||
}
|
||||
function pageDisabled(direction: -1 | 1) {
|
||||
|
||||
@@ -1,47 +1,16 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
getCurrentInstance,
|
||||
h,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
onMounted,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
watch,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type SlotsType,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { DateFieldRoot } from "reka-ui";
|
||||
import {
|
||||
getLocalTimeZone,
|
||||
today,
|
||||
parseDate,
|
||||
parseDateTime,
|
||||
parseZonedDateTime,
|
||||
toCalendar,
|
||||
toCalendarDateTime,
|
||||
type DateValue,
|
||||
} from "@internationalized/date";
|
||||
import { type DateValue } from "@internationalized/date";
|
||||
import { dateFieldVariants } from "@heroui-vue/styles";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { useAcceptedDateValue } from "../date/model";
|
||||
import { dateForLocale, 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 "./context";
|
||||
import PrimitiveNode from "./PrimitiveNode";
|
||||
import DateSegments from "./DateSegments";
|
||||
import { useDateFieldOwner } from "./owner";
|
||||
export default defineComponent({
|
||||
name: "DateField",
|
||||
inheritAttrs: false,
|
||||
@@ -98,160 +67,25 @@ export default defineComponent({
|
||||
change: (_value: DateValue | null) => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const config = useConfig();
|
||||
const instance = getCurrentInstance()!;
|
||||
const accepted: ReturnType<typeof useAcceptedDateValue<DateValue>> =
|
||||
useAcceptedDateValue<DateValue>({
|
||||
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 && value.compare(props.minValue) < 0)
|
||||
return "日期不能早于最早日期。";
|
||||
if (value && props.maxValue && value.compare(props.maxValue) > 0)
|
||||
return "日期不能晚于最晚日期。";
|
||||
if (value && props.isDateUnavailable?.(value)) return "此日期不可用。";
|
||||
return props.validate?.(value);
|
||||
const owner = useDateFieldOwner(props, attrs, {
|
||||
onChange: (value) => {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", 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,
|
||||
leadingZeros: () => props.shouldForceLeadingZeros,
|
||||
labelledBy: field.labelledBy,
|
||||
describedBy: field.describedBy,
|
||||
ariaLabel: () => attrs["aria-label"],
|
||||
});
|
||||
const locale = computed(
|
||||
() => props.locale ?? config?.locale.value ?? "en-US",
|
||||
);
|
||||
// Capture a real local date only as the empty edit placeholder. DateValue
|
||||
// models never pass through JS Date or acquire the machine's time zone.
|
||||
const initialPlaceholder = (
|
||||
props.placeholderValue ??
|
||||
props.defaultValue ??
|
||||
accepted.value.value ??
|
||||
today(getLocalTimeZone())
|
||||
).copy();
|
||||
const lastPlaceholder = shallowRef(initialPlaceholder);
|
||||
watch(accepted.value, (value) => {
|
||||
if (value) lastPlaceholder.value = value.copy();
|
||||
});
|
||||
const placeholder = computed(() => {
|
||||
let value = dateForLocale(
|
||||
props.placeholderValue ?? accepted.value.value ?? lastPlaceholder.value,
|
||||
locale.value,
|
||||
);
|
||||
if (
|
||||
props.granularity &&
|
||||
props.granularity !== "day" &&
|
||||
!("hour" in value)
|
||||
)
|
||||
value = toCalendarDateTime(value);
|
||||
return value;
|
||||
});
|
||||
const wire = computed(() =>
|
||||
accepted.wire.value
|
||||
? dateForLocale(accepted.wire.value, locale.value)
|
||||
: null,
|
||||
);
|
||||
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: DateValue | undefined) {
|
||||
const calendar =
|
||||
accepted.value.value?.calendar ??
|
||||
props.defaultValue?.calendar ??
|
||||
props.placeholderValue?.calendar ??
|
||||
initialPlaceholder.calendar;
|
||||
accepted.request(value ? toCalendar(value, calendar) : 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 ?? "auto"}|${props.hourCycle ?? "auto"}|${placeholder.value.calendar.identifier}|${"hour" in placeholder.value}`,
|
||||
);
|
||||
watch(signature, () => {
|
||||
const old = root.value?.ownerDocument.activeElement as HTMLElement | null;
|
||||
const part =
|
||||
old && root.value?.contains(old)
|
||||
? old.dataset.rekaDateFieldSegment
|
||||
: 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-date-field-segment="${part}"]`,
|
||||
)
|
||||
?.focus();
|
||||
});
|
||||
});
|
||||
onMounted(() => {
|
||||
if (props.autoFocus) focus();
|
||||
if (props.autoFocus) owner.focus();
|
||||
});
|
||||
expose({ element: root, focus });
|
||||
expose({ element: owner.root, focus: owner.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 state = owner.state();
|
||||
const raw = slots.default?.(state);
|
||||
const children = field.prepare(
|
||||
const children = owner.field.prepare(
|
||||
Array.isArray(raw) ? raw : raw ? [raw] : [],
|
||||
true,
|
||||
);
|
||||
const overrides = {
|
||||
id: field.field.controlId.value,
|
||||
id: owner.field.field.controlId.value,
|
||||
role: "group",
|
||||
class: dateFieldVariants({ fullWidth: props.fullWidth }),
|
||||
"data-slot": "date-field",
|
||||
@@ -259,18 +93,18 @@ export default defineComponent({
|
||||
"data-readonly": state.isReadOnly || undefined,
|
||||
"data-invalid": state.isInvalid || undefined,
|
||||
"data-required": state.isRequired || undefined,
|
||||
"data-focus-within": focused.value || undefined,
|
||||
"data-focus-within": owner.focused.value || undefined,
|
||||
"aria-label": attrs["aria-label"],
|
||||
"aria-labelledby": field.labelledBy(),
|
||||
"aria-describedby": field.describedBy(),
|
||||
"aria-labelledby": owner.field.labelledBy(),
|
||||
"aria-describedby": owner.field.describedBy(),
|
||||
"aria-invalid": state.isInvalid || undefined,
|
||||
"aria-required": state.isRequired || undefined,
|
||||
ref: (element: unknown) => {
|
||||
root.value = element as HTMLElement;
|
||||
owner.root.value = element as HTMLElement;
|
||||
},
|
||||
onFocusin: (event: FocusEvent) => {
|
||||
focused.value = true;
|
||||
focusVisible.value = (event.target as HTMLElement).matches(
|
||||
owner.focused.value = true;
|
||||
owner.focusVisible.value = (event.target as HTMLElement).matches(
|
||||
":focus-visible",
|
||||
);
|
||||
},
|
||||
@@ -280,104 +114,16 @@ export default defineComponent({
|
||||
event.relatedTarget as Node | null,
|
||||
)
|
||||
) {
|
||||
focused.value = false;
|
||||
focusVisible.value = false;
|
||||
owner.focused.value = false;
|
||||
owner.focusVisible.value = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
return h(
|
||||
DateFieldRoot,
|
||||
{
|
||||
key: signature.value,
|
||||
asChild: true,
|
||||
modelValue: wire.value,
|
||||
placeholder: placeholder.value,
|
||||
granularity: props.granularity,
|
||||
hourCycle: props.hourCycle,
|
||||
hideTimeZone: props.hideTimeZone,
|
||||
locale: locale.value,
|
||||
dir: props.dir ?? config?.dir.value,
|
||||
disabled: state.isDisabled,
|
||||
readonly: state.isReadOnly,
|
||||
// The base is nameless and unconstrained: its native input truncates
|
||||
// time and cannot represent zones or non-Gregorian values faithfully.
|
||||
"onUpdate:modelValue": request,
|
||||
},
|
||||
{
|
||||
default: ({
|
||||
segments,
|
||||
}: {
|
||||
segments: Pick<DateSegment, "part" | "value">[];
|
||||
}) =>
|
||||
h(
|
||||
PrimitiveNode,
|
||||
{ as: props.as, consumer: attrs, overrides },
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
DateSegments,
|
||||
{ segments },
|
||||
{
|
||||
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 {
|
||||
request(
|
||||
!text
|
||||
? undefined
|
||||
: text.includes("[")
|
||||
? parseZonedDateTime(text)
|
||||
: text.includes("T")
|
||||
? parseDateTime(text)
|
||||
: parseDate(text),
|
||||
);
|
||||
} catch {
|
||||
restoreNative();
|
||||
}
|
||||
void nextTick(restoreNative);
|
||||
},
|
||||
name: props.name,
|
||||
form: props.form,
|
||||
value: serializeDateValue(accepted.value.value),
|
||||
disabled: state.isDisabled,
|
||||
"data-slot": "date-field-value",
|
||||
}),
|
||||
validationInput(
|
||||
proxy,
|
||||
props,
|
||||
state.isDisabled || state.isReadOnly,
|
||||
field.behavior.value,
|
||||
(event) => field.invalidEvent(event, focus),
|
||||
),
|
||||
],
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
return owner.renderOwner([...children, ...owner.inputNodes()], {
|
||||
as: props.as,
|
||||
consumer: attrs,
|
||||
overrides,
|
||||
});
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
import {
|
||||
computed,
|
||||
getCurrentInstance,
|
||||
h,
|
||||
nextTick,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
watch,
|
||||
watchEffect,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { DateFieldRoot } from "reka-ui";
|
||||
import {
|
||||
getLocalTimeZone,
|
||||
parseDate,
|
||||
parseDateTime,
|
||||
parseZonedDateTime,
|
||||
toCalendar,
|
||||
toCalendarDateTime,
|
||||
today,
|
||||
type DateValue,
|
||||
} from "@internationalized/date";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import {
|
||||
useChoiceField,
|
||||
useChoiceForm,
|
||||
validationInput,
|
||||
} from "../choice/shared";
|
||||
import type { ChoiceFieldProps } from "../choice/shared";
|
||||
import { disabledContextKey } from "../field/disabled";
|
||||
import type { ValidateResult } from "../field/context";
|
||||
import { useAcceptedDateValue } from "../date/model";
|
||||
import { dateForLocale, serializeDateValue } from "../date/value";
|
||||
import EmptyDateBridge from "../date/EmptyDateBridge";
|
||||
import PrimitiveNode from "./PrimitiveNode";
|
||||
import DateSegments from "./DateSegments";
|
||||
import { dateFieldKey, type DateSegment } from "./context";
|
||||
|
||||
/** The props shared by DateField and DatePicker's field owner. */
|
||||
export interface DateFieldOwnerProps extends ChoiceFieldProps {
|
||||
modelValue?: DateValue | null;
|
||||
value?: DateValue | null;
|
||||
defaultValue?: DateValue | null;
|
||||
placeholderValue?: DateValue | null;
|
||||
minValue?: DateValue | null;
|
||||
maxValue?: DateValue | null;
|
||||
isDateUnavailable?: (value: DateValue) => boolean;
|
||||
granularity?: "day" | "hour" | "minute" | "second";
|
||||
hourCycle?: 12 | 24;
|
||||
hideTimeZone?: boolean;
|
||||
shouldForceLeadingZeros?: boolean;
|
||||
locale?: string;
|
||||
dir?: "ltr" | "rtl";
|
||||
autoComplete?: string;
|
||||
validate?: (value: DateValue | null) => ValidateResult;
|
||||
}
|
||||
|
||||
export interface DateFieldOwnerRoot {
|
||||
as: string;
|
||||
consumer?: Record<string, unknown>;
|
||||
overrides: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One accepted date model, field context and native submission layer for both
|
||||
* standalone DateField and a DatePicker-owned field. Components remain
|
||||
* responsible for their own root element and public render state.
|
||||
*/
|
||||
export function useDateFieldOwner(
|
||||
props: DateFieldOwnerProps,
|
||||
attrs: Record<string, unknown>,
|
||||
options: { onChange: (value: DateValue | null) => void },
|
||||
) {
|
||||
const config = useConfig();
|
||||
const instance = getCurrentInstance()!;
|
||||
const accepted: ReturnType<typeof useAcceptedDateValue<DateValue>> =
|
||||
useAcceptedDateValue<DateValue>({
|
||||
value: () =>
|
||||
["modelValue", "model-value"].some((key) =>
|
||||
Object.hasOwn(instance.vnode.props ?? {}, key),
|
||||
)
|
||||
? props.modelValue
|
||||
: props.value,
|
||||
defaultValue: () => props.defaultValue,
|
||||
onChange: (value) => {
|
||||
field.edit();
|
||||
options.onChange(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 && value.compare(props.minValue) < 0)
|
||||
return "日期不能早于最早日期。";
|
||||
if (value && props.maxValue && value.compare(props.maxValue) > 0)
|
||||
return "日期不能晚于最晚日期。";
|
||||
if (value && props.isDateUnavailable?.(value)) 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,
|
||||
leadingZeros: () => props.shouldForceLeadingZeros,
|
||||
labelledBy: field.labelledBy,
|
||||
describedBy: field.describedBy,
|
||||
ariaLabel: () => attrs["aria-label"],
|
||||
});
|
||||
const locale = computed(
|
||||
() => props.locale ?? config?.locale.value ?? "en-US",
|
||||
);
|
||||
// Capture a real local date only as the empty edit placeholder. DateValue
|
||||
// models never pass through JS Date or acquire the machine's time zone.
|
||||
const initialPlaceholder = (
|
||||
props.placeholderValue ??
|
||||
props.defaultValue ??
|
||||
accepted.value.value ??
|
||||
today(getLocalTimeZone())
|
||||
).copy();
|
||||
const lastPlaceholder = shallowRef(initialPlaceholder);
|
||||
watch(accepted.value, (value) => {
|
||||
if (value) lastPlaceholder.value = value.copy();
|
||||
});
|
||||
const placeholder = computed(() => {
|
||||
let value = dateForLocale(
|
||||
props.placeholderValue ?? accepted.value.value ?? lastPlaceholder.value,
|
||||
locale.value,
|
||||
);
|
||||
if (props.granularity && props.granularity !== "day" && !("hour" in value))
|
||||
value = toCalendarDateTime(value);
|
||||
return value;
|
||||
});
|
||||
const wire = computed(() =>
|
||||
accepted.wire.value
|
||||
? dateForLocale(accepted.wire.value, locale.value)
|
||||
: null,
|
||||
);
|
||||
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 requestInput(value: DateValue | undefined) {
|
||||
const calendar =
|
||||
accepted.value.value?.calendar ??
|
||||
props.defaultValue?.calendar ??
|
||||
props.placeholderValue?.calendar ??
|
||||
initialPlaceholder.calendar;
|
||||
accepted.request(value ? toCalendar(value, calendar) : 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 ?? "auto"}|${props.hourCycle ?? "auto"}|${placeholder.value.calendar.identifier}|${"hour" in placeholder.value}`,
|
||||
);
|
||||
watch(signature, () => {
|
||||
const old = root.value?.ownerDocument.activeElement as HTMLElement | null;
|
||||
const part =
|
||||
old && root.value?.contains(old)
|
||||
? old.dataset.rekaDateFieldSegment
|
||||
: 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-date-field-segment="${part}"]`,
|
||||
)
|
||||
?.focus();
|
||||
});
|
||||
});
|
||||
function state() {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
}
|
||||
function inputNodes(valueSlot = "date-field-value") {
|
||||
return [
|
||||
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: field.field.readOnly.value,
|
||||
onFocus: focus,
|
||||
onInput: (event: Event) => {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
field.field.disabled.value ||
|
||||
field.field.readOnly.value
|
||||
) {
|
||||
restoreNative();
|
||||
return;
|
||||
}
|
||||
const text = (event.target as HTMLInputElement).value;
|
||||
try {
|
||||
requestInput(
|
||||
!text
|
||||
? undefined
|
||||
: text.includes("[")
|
||||
? parseZonedDateTime(text)
|
||||
: text.includes("T")
|
||||
? parseDateTime(text)
|
||||
: parseDate(text),
|
||||
);
|
||||
} catch {
|
||||
restoreNative();
|
||||
}
|
||||
void nextTick(restoreNative);
|
||||
},
|
||||
name: props.name,
|
||||
form: props.form,
|
||||
value: serializeDateValue(accepted.value.value),
|
||||
disabled: field.field.disabled.value,
|
||||
"data-slot": valueSlot,
|
||||
}),
|
||||
validationInput(
|
||||
proxy,
|
||||
props,
|
||||
field.field.disabled.value || field.field.readOnly.value,
|
||||
field.behavior.value,
|
||||
(event) => field.invalidEvent(event, focus),
|
||||
),
|
||||
];
|
||||
}
|
||||
function renderOwner(children: VNodeChild[], rootConfig: DateFieldOwnerRoot) {
|
||||
return h(
|
||||
DateFieldRoot,
|
||||
{
|
||||
key: signature.value,
|
||||
asChild: true,
|
||||
modelValue: wire.value,
|
||||
placeholder: placeholder.value,
|
||||
granularity: props.granularity,
|
||||
hourCycle: props.hourCycle,
|
||||
hideTimeZone: props.hideTimeZone,
|
||||
locale: locale.value,
|
||||
dir: props.dir ?? config?.dir?.value,
|
||||
disabled: field.field.disabled.value,
|
||||
readonly: field.field.readOnly.value,
|
||||
// The base is nameless and unconstrained: its native input truncates
|
||||
// time and cannot represent zones or non-Gregorian values faithfully.
|
||||
"onUpdate:modelValue": requestInput,
|
||||
},
|
||||
{
|
||||
default: ({
|
||||
segments,
|
||||
}: {
|
||||
segments: Pick<DateSegment, "part" | "value">[];
|
||||
}) =>
|
||||
h(
|
||||
PrimitiveNode,
|
||||
{
|
||||
as: rootConfig.as,
|
||||
consumer: rootConfig.consumer,
|
||||
overrides: rootConfig.overrides,
|
||||
},
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
DateSegments,
|
||||
{ segments },
|
||||
{
|
||||
default: () => children,
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
return {
|
||||
accepted,
|
||||
field,
|
||||
locale,
|
||||
placeholder,
|
||||
wire,
|
||||
root,
|
||||
native,
|
||||
proxy,
|
||||
focused,
|
||||
focusVisible,
|
||||
focus,
|
||||
requestInput,
|
||||
restoreNative,
|
||||
signature,
|
||||
state,
|
||||
inputNodes,
|
||||
renderOwner,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
h,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
provide,
|
||||
shallowRef,
|
||||
watch,
|
||||
type PropType,
|
||||
type SlotsType,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { PopoverRoot } from "reka-ui";
|
||||
import {
|
||||
getLocalTimeZone,
|
||||
isSameDay,
|
||||
Time,
|
||||
toCalendar,
|
||||
toCalendarDate,
|
||||
toCalendarDateTime,
|
||||
today,
|
||||
type DateValue,
|
||||
} from "@internationalized/date";
|
||||
import { datePickerVariants } from "@heroui-vue/styles";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { useOverlayState } from "../../composables/useOverlayState";
|
||||
import { copyDateValue } from "../date/value";
|
||||
import { createPopoverContext, popoverKey } from "../popover/context";
|
||||
import { overlayNodes } from "../overlay/OverlayAction";
|
||||
import type { ValidationBehavior, ValidateResult } from "../field/context";
|
||||
import { useDateFieldOwner } from "../date-field/owner";
|
||||
import {
|
||||
datePickerKey,
|
||||
type DatePickerRenderProps,
|
||||
type DatePickerTimeValue,
|
||||
} from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "DatePicker",
|
||||
inheritAttrs: false,
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: DatePickerRenderProps) => VNodeChild;
|
||||
}>,
|
||||
props: {
|
||||
modelValue: {
|
||||
type: [Object, null] as PropType<DateValue | null>,
|
||||
default: undefined,
|
||||
},
|
||||
value: {
|
||||
type: [Object, null] as PropType<DateValue | null>,
|
||||
default: undefined,
|
||||
},
|
||||
defaultValue: [Object, null] as PropType<DateValue | null>,
|
||||
placeholderValue: [Object, null] as PropType<DateValue | null>,
|
||||
minValue: [Object, null] as PropType<DateValue | null>,
|
||||
maxValue: [Object, null] as PropType<DateValue | null>,
|
||||
isDateUnavailable: Function as PropType<(value: DateValue) => boolean>,
|
||||
granularity: String as PropType<"day" | "hour" | "minute" | "second">,
|
||||
hourCycle: Number as PropType<12 | 24>,
|
||||
hideTimeZone: Boolean,
|
||||
shouldForceLeadingZeros: { type: Boolean, default: undefined },
|
||||
locale: String,
|
||||
dir: String as PropType<"ltr" | "rtl">,
|
||||
firstDayOfWeek: String as PropType<
|
||||
import("../date/calendar").CalendarWeekday
|
||||
>,
|
||||
pageBehavior: String as PropType<"visible" | "single">,
|
||||
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: DateValue | null) => ValidateResult>,
|
||||
open: { type: Boolean, default: undefined },
|
||||
isOpen: { type: Boolean, default: undefined },
|
||||
defaultOpen: Boolean,
|
||||
shouldCloseOnSelect: { type: Boolean, default: true },
|
||||
},
|
||||
emits: {
|
||||
"update:modelValue": (_value: DateValue | null) => true,
|
||||
change: (_value: DateValue | null) => true,
|
||||
"update:open": (_value: boolean) => true,
|
||||
"update:isOpen": (_value: boolean) => true,
|
||||
openChange: (_value: boolean) => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const config = useConfig();
|
||||
const dir = computed<"ltr" | "rtl">(
|
||||
() => props.dir ?? config?.dir?.value ?? "ltr",
|
||||
);
|
||||
const state = useOverlayState({
|
||||
isOpen: () => props.open ?? props.isOpen,
|
||||
defaultOpen: props.defaultOpen,
|
||||
onOpenChange(value) {
|
||||
emit("update:open", value);
|
||||
emit("update:isOpen", value);
|
||||
emit("openChange", value);
|
||||
},
|
||||
});
|
||||
const owner = useDateFieldOwner(props, attrs, {
|
||||
onChange: (value) => {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
},
|
||||
});
|
||||
const pendingTime = shallowRef<Time | null>(null);
|
||||
watch(owner.accepted.value, (value) => {
|
||||
if (value) pendingTime.value = null;
|
||||
});
|
||||
const timeValue = computed<DatePickerTimeValue | null>(() => {
|
||||
const value = owner.accepted.value.value;
|
||||
if (value && "hour" in value)
|
||||
return new Time(
|
||||
value.hour,
|
||||
value.minute,
|
||||
value.second,
|
||||
value.millisecond,
|
||||
);
|
||||
return pendingTime.value;
|
||||
});
|
||||
function emptyTemplate(): DateValue {
|
||||
const sample =
|
||||
props.placeholderValue ??
|
||||
props.defaultValue ??
|
||||
today(getLocalTimeZone());
|
||||
if ((props.granularity ?? "day") === "day") return toCalendarDate(sample);
|
||||
let base: DateValue =
|
||||
"hour" in sample ? sample : toCalendarDateTime(sample);
|
||||
if (pendingTime.value)
|
||||
base = base.set({
|
||||
hour: pendingTime.value.hour,
|
||||
minute: pendingTime.value.minute,
|
||||
second: pendingTime.value.second,
|
||||
millisecond: pendingTime.value.millisecond,
|
||||
});
|
||||
return base;
|
||||
}
|
||||
function requestDate(value: DateValue) {
|
||||
if (owner.field.field.disabled.value || owner.field.field.readOnly.value)
|
||||
return;
|
||||
const template = owner.accepted.value.value ?? emptyTemplate();
|
||||
const day = toCalendar(value, template.calendar);
|
||||
const next = template.set({
|
||||
era: day.era,
|
||||
year: day.year,
|
||||
month: day.month,
|
||||
day: day.day,
|
||||
});
|
||||
owner.accepted.request(copyDateValue(next));
|
||||
if (props.shouldCloseOnSelect) state.close();
|
||||
}
|
||||
function setTimeValue(value: DatePickerTimeValue | null) {
|
||||
if (!value) {
|
||||
pendingTime.value = null;
|
||||
return;
|
||||
}
|
||||
const time = new Time(
|
||||
value.hour,
|
||||
value.minute,
|
||||
value.second,
|
||||
value.millisecond,
|
||||
);
|
||||
const current = owner.accepted.value.value;
|
||||
if (!current) {
|
||||
pendingTime.value = time;
|
||||
return;
|
||||
}
|
||||
let next: DateValue =
|
||||
"hour" in current ? current : toCalendarDateTime(current);
|
||||
next = next.set({
|
||||
hour: time.hour,
|
||||
minute: time.minute,
|
||||
second: time.second,
|
||||
millisecond: time.millisecond,
|
||||
});
|
||||
owner.accepted.request(copyDateValue(next));
|
||||
}
|
||||
function setValue(value: DateValue | null) {
|
||||
owner.accepted.request(copyDateValue(value));
|
||||
}
|
||||
const trigger = shallowRef<HTMLElement>();
|
||||
const popover = createPopoverContext(state);
|
||||
provide(popoverKey, popover);
|
||||
provide(datePickerKey, {
|
||||
state,
|
||||
trigger,
|
||||
value: owner.accepted.value,
|
||||
dates: computed(() => {
|
||||
const value = owner.accepted.value.value;
|
||||
return value ? [value] : [];
|
||||
}),
|
||||
selected: (value) =>
|
||||
!!owner.accepted.value.value &&
|
||||
isSameDay(owner.accepted.value.value, value),
|
||||
requestDate,
|
||||
minValue: computed(() => props.minValue ?? undefined),
|
||||
maxValue: computed(() => props.maxValue ?? undefined),
|
||||
isDateUnavailable: props.isDateUnavailable,
|
||||
disabled: owner.field.field.disabled,
|
||||
readOnly: owner.field.field.readOnly,
|
||||
invalid: owner.field.field.invalid,
|
||||
locale: owner.locale,
|
||||
dir,
|
||||
labelledBy: owner.field.labelledBy,
|
||||
describedBy: owner.field.describedBy,
|
||||
firstDayOfWeek: props.firstDayOfWeek,
|
||||
pageBehavior: props.pageBehavior,
|
||||
placeholder: owner.placeholder,
|
||||
timeValue,
|
||||
setTimeValue,
|
||||
shouldCloseOnSelect: () => props.shouldCloseOnSelect,
|
||||
});
|
||||
let restoreFocus = false;
|
||||
const doc = typeof document === "undefined" ? undefined : document;
|
||||
function trackKeyboard(event: KeyboardEvent) {
|
||||
if (!event.metaKey && !event.ctrlKey && !event.altKey)
|
||||
restoreFocus = true;
|
||||
}
|
||||
function closeFromPicker(event: KeyboardEvent) {
|
||||
if (
|
||||
event.key !== "Escape" ||
|
||||
event.isComposing ||
|
||||
event.defaultPrevented ||
|
||||
!state.isOpen.value
|
||||
)
|
||||
return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (!target) return;
|
||||
const content = doc?.getElementById(popover.contentId.value) ?? null;
|
||||
const inField = !!owner.root.value?.contains(target);
|
||||
const inContent = !!content?.contains(target);
|
||||
if (!inField && !inContent) return;
|
||||
// An open year layer owns its own Escape and restores focus itself.
|
||||
if (
|
||||
content?.querySelector(
|
||||
'[data-slot="calendar-year-picker-grid"][data-open]',
|
||||
)
|
||||
)
|
||||
return;
|
||||
// The installed date/time segment base prevents every non-Tab key,
|
||||
// including Escape. Modal popovers can also out-rank the picker layer.
|
||||
// The picker owns this dismissal path explicitly.
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
state.close();
|
||||
}
|
||||
function onDocumentKeydown(event: KeyboardEvent) {
|
||||
trackKeyboard(event);
|
||||
closeFromPicker(event);
|
||||
}
|
||||
watch(
|
||||
state.isOpen,
|
||||
(open) => {
|
||||
if (open) doc?.addEventListener("keydown", onDocumentKeydown, true);
|
||||
else {
|
||||
doc?.removeEventListener("keydown", onDocumentKeydown, true);
|
||||
if (restoreFocus) {
|
||||
const run = () => trigger.value?.focus({ preventScroll: true });
|
||||
if (typeof requestAnimationFrame === "function")
|
||||
requestAnimationFrame(run);
|
||||
else void nextTick(run);
|
||||
}
|
||||
restoreFocus = false;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
onMounted(() => {
|
||||
if (props.autoFocus) owner.focus();
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
doc?.removeEventListener("keydown", onDocumentKeydown, true);
|
||||
});
|
||||
expose({
|
||||
element: owner.root,
|
||||
focus: owner.focus,
|
||||
open: state.open,
|
||||
close: state.close,
|
||||
toggle: state.toggle,
|
||||
});
|
||||
return () => {
|
||||
const base = owner.state();
|
||||
const pickerState = {
|
||||
value: owner.accepted.value.value,
|
||||
timeValue: timeValue.value,
|
||||
setValue,
|
||||
setTimeValue,
|
||||
};
|
||||
const renderState: DatePickerRenderProps = {
|
||||
...base,
|
||||
isOpen: state.isOpen.value,
|
||||
timeValue: timeValue.value,
|
||||
state: pickerState,
|
||||
open: state.open,
|
||||
close: state.close,
|
||||
toggle: state.toggle,
|
||||
};
|
||||
const raw = slots.default?.(renderState);
|
||||
const children = owner.field.prepare(
|
||||
Array.isArray(raw) ? raw : raw ? [raw] : [],
|
||||
true,
|
||||
);
|
||||
const overrides = {
|
||||
id: owner.field.field.controlId.value,
|
||||
role: "group",
|
||||
class: datePickerVariants().base(),
|
||||
"data-slot": "date-picker",
|
||||
"data-disabled": base.isDisabled || undefined,
|
||||
"data-readonly": base.isReadOnly || undefined,
|
||||
"data-invalid": base.isInvalid || undefined,
|
||||
"data-required": base.isRequired || undefined,
|
||||
"data-focus-within": owner.focused.value || undefined,
|
||||
"aria-label": attrs["aria-label"],
|
||||
"aria-labelledby": owner.field.labelledBy(),
|
||||
"aria-describedby": owner.field.describedBy(),
|
||||
"aria-invalid": base.isInvalid || undefined,
|
||||
"aria-required": base.isRequired || undefined,
|
||||
dir: dir.value,
|
||||
ref: (element: unknown) => {
|
||||
owner.root.value = element as HTMLElement;
|
||||
},
|
||||
onFocusin: (event: FocusEvent) => {
|
||||
owner.focused.value = true;
|
||||
owner.focusVisible.value = (event.target as HTMLElement).matches(
|
||||
":focus-visible",
|
||||
);
|
||||
},
|
||||
onFocusout: (event: FocusEvent) => {
|
||||
if (
|
||||
!(event.currentTarget as HTMLElement).contains(
|
||||
event.relatedTarget as Node | null,
|
||||
)
|
||||
) {
|
||||
owner.focused.value = false;
|
||||
owner.focusVisible.value = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
return h(
|
||||
PopoverRoot,
|
||||
{
|
||||
open: state.isOpen.value,
|
||||
modal: true,
|
||||
"onUpdate:open": state.setOpen,
|
||||
},
|
||||
{
|
||||
default: () =>
|
||||
owner.renderOwner(
|
||||
[
|
||||
...overlayNodes(children),
|
||||
...owner.inputNodes("date-picker-value"),
|
||||
],
|
||||
{ as: props.as, consumer: attrs, overrides },
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,60 @@
|
||||
<script setup lang="ts">
|
||||
import { useAttrs } from "vue";
|
||||
import { datePickerVariants } from "@heroui-vue/styles";
|
||||
import type { OverlayPlacement } from "../overlay/placement";
|
||||
import PopoverContent from "../popover/PopoverContent.vue";
|
||||
import { useDatePicker } from "./context";
|
||||
defineOptions({ name: "DatePickerPopover", inheritAttrs: false });
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
as?: string;
|
||||
placement?: OverlayPlacement;
|
||||
offset?: number;
|
||||
crossOffset?: number;
|
||||
shouldFlip?: boolean;
|
||||
containerPadding?: number;
|
||||
to?: string | HTMLElement;
|
||||
isNonModal?: boolean;
|
||||
isDismissable?: boolean;
|
||||
isKeyboardDismissDisabled?: boolean;
|
||||
}>(),
|
||||
{
|
||||
as: "div",
|
||||
placement: "bottom",
|
||||
offset: 8,
|
||||
crossOffset: 0,
|
||||
shouldFlip: true,
|
||||
containerPadding: 12,
|
||||
isNonModal: undefined,
|
||||
isDismissable: true,
|
||||
isKeyboardDismissDisabled: false,
|
||||
},
|
||||
);
|
||||
const picker = useDatePicker();
|
||||
const attrs = useAttrs();
|
||||
function openAutoFocus(event: Event) {
|
||||
// The calendar cell owns initial focus; the dialog surface must not steal it.
|
||||
event.preventDefault();
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<PopoverContent
|
||||
v-bind="$attrs"
|
||||
:as="as"
|
||||
:placement="placement"
|
||||
:offset="offset"
|
||||
:cross-offset="crossOffset"
|
||||
:should-flip="shouldFlip"
|
||||
:container-padding="containerPadding"
|
||||
:to="to"
|
||||
:is-non-modal="isNonModal"
|
||||
:is-dismissable="isDismissable"
|
||||
:is-keyboard-dismiss-disabled="isKeyboardDismissDisabled"
|
||||
:lang="(attrs.lang as string | undefined) ?? picker.locale.value"
|
||||
:class="datePickerVariants().popover()"
|
||||
data-slot="date-picker-popover"
|
||||
@open-auto-focus="openAutoFocus"
|
||||
>
|
||||
<slot />
|
||||
</PopoverContent>
|
||||
</template>
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, useAttrs, watch } from "vue";
|
||||
import { PopoverAnchor, useForwardExpose } from "reka-ui";
|
||||
import { datePickerVariants } from "@heroui-vue/styles";
|
||||
import OverlayAction from "../overlay/OverlayAction";
|
||||
import { usePopover } from "../popover/context";
|
||||
import { useDatePicker } from "./context";
|
||||
defineOptions({ name: "DatePickerTrigger", inheritAttrs: false });
|
||||
const props = withDefaults(
|
||||
defineProps<{ as?: string; asChild?: boolean; isDisabled?: boolean }>(),
|
||||
{ as: "button" },
|
||||
);
|
||||
const popover = usePopover();
|
||||
const picker = useDatePicker();
|
||||
const attrs = useAttrs();
|
||||
const { forwardRef, currentElement } = useForwardExpose();
|
||||
const focusVisible = ref(false);
|
||||
const disabled = computed(
|
||||
() => props.isDisabled || picker.disabled.value || picker.readOnly.value,
|
||||
);
|
||||
const defaultLabelledBy = computed(() => {
|
||||
if (attrs["aria-label"] || attrs["aria-labelledby"]) return undefined;
|
||||
const ids = [popover.triggerId, picker.labelledBy()].filter(Boolean);
|
||||
return ids.length ? ids.join(" ") : undefined;
|
||||
});
|
||||
const defaultLabel = computed(() => {
|
||||
if (attrs["aria-label"] || attrs["aria-labelledby"]) return undefined;
|
||||
if (defaultLabelledBy.value) return undefined;
|
||||
return picker.locale.value.toLowerCase().startsWith("zh")
|
||||
? "日历"
|
||||
: "Calendar";
|
||||
});
|
||||
watch(
|
||||
currentElement,
|
||||
(element) => {
|
||||
picker.trigger.value = element;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
<template>
|
||||
<PopoverAnchor as-child>
|
||||
<OverlayAction
|
||||
:ref="forwardRef"
|
||||
v-bind="$attrs"
|
||||
:as="as"
|
||||
:as-child="asChild"
|
||||
:is-disabled="disabled"
|
||||
:activate="popover.state.toggle"
|
||||
:class="datePickerVariants().trigger()"
|
||||
data-slot="date-picker-trigger"
|
||||
aria-haspopup="dialog"
|
||||
:aria-expanded="popover.state.isOpen.value"
|
||||
:aria-controls="
|
||||
popover.state.isOpen.value ? popover.contentId.value : undefined
|
||||
"
|
||||
:aria-label="($attrs['aria-label'] as string | undefined) ?? defaultLabel"
|
||||
:aria-labelledby="
|
||||
($attrs['aria-labelledby'] as string | undefined) ?? defaultLabelledBy
|
||||
"
|
||||
:aria-describedby="
|
||||
($attrs['aria-describedby'] as string | undefined) ??
|
||||
picker.describedBy()
|
||||
"
|
||||
:data-open="popover.state.isOpen.value || undefined"
|
||||
:data-disabled="disabled || undefined"
|
||||
:data-focus-visible="focusVisible || undefined"
|
||||
@focus="focusVisible = true"
|
||||
@blur="focusVisible = false"
|
||||
>
|
||||
<slot />
|
||||
</OverlayAction>
|
||||
</PopoverAnchor>
|
||||
</template>
|
||||
@@ -0,0 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
import { datePickerVariants } from "@heroui-vue/styles";
|
||||
defineOptions({ name: "DatePickerTriggerIndicator", inheritAttrs: false });
|
||||
withDefaults(defineProps<{ as?: string }>(), { as: "span" });
|
||||
</script>
|
||||
<template>
|
||||
<component
|
||||
:is="as"
|
||||
v-bind="$attrs"
|
||||
aria-hidden="true"
|
||||
:class="datePickerVariants().triggerIndicator()"
|
||||
data-slot="date-picker-trigger-indicator"
|
||||
>
|
||||
<slot>
|
||||
<!-- Adapted from HeroUI ce90ea3 IconCalendar; Apache-2.0. -->
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
height="1em"
|
||||
role="presentation"
|
||||
viewBox="0 0 13 14"
|
||||
width="1em"
|
||||
>
|
||||
<path
|
||||
clip-rule="evenodd"
|
||||
d="M3.75 4.5A.75.75 0 0 1 3 3.75v-.748a1.5 1.5 0 0 0-1.5 1.5v1h10v-1a1.5 1.5 0 0 0-1.5-1.5v.75a.75.75 0 1 1-1.5 0v-.75h-4v.747a.75.75 0 0 1-.75.75ZM8.5 1.501h-4V.75a.75.75 0 0 0-1.5 0v.752a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h7a3 3 0 0 0 3-3v-6a3 3 0 0 0-3-3v-.75a.75.75 0 0 0-1.5 0v.75Zm-7 5.5v3.5a1.5 1.5 0 0 0 1.5 1.5h7a1.5 1.5 0 0 0 1.5-1.5v-3.5h-10Z"
|
||||
fill="currentColor"
|
||||
fill-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</slot>
|
||||
</component>
|
||||
</template>
|
||||
@@ -0,0 +1,75 @@
|
||||
import {
|
||||
inject,
|
||||
type ComputedRef,
|
||||
type InjectionKey,
|
||||
type ShallowRef,
|
||||
} from "vue";
|
||||
import type {
|
||||
CalendarDateTime,
|
||||
DateValue,
|
||||
Time,
|
||||
ZonedDateTime,
|
||||
} from "@internationalized/date";
|
||||
import type { OverlayState } from "../../composables/useOverlayState";
|
||||
|
||||
export type DatePickerTimeValue = Time | CalendarDateTime | ZonedDateTime;
|
||||
|
||||
export interface DatePickerState {
|
||||
value: DateValue | null;
|
||||
timeValue: DatePickerTimeValue | null;
|
||||
setValue: (value: DateValue | null) => void;
|
||||
setTimeValue: (value: DatePickerTimeValue | null) => void;
|
||||
}
|
||||
|
||||
export interface DatePickerRenderProps {
|
||||
value: DateValue | null;
|
||||
isOpen: boolean;
|
||||
isDisabled: boolean;
|
||||
isReadOnly: boolean;
|
||||
isRequired: boolean;
|
||||
isInvalid: boolean;
|
||||
isFocusWithin: boolean;
|
||||
isFocused: boolean;
|
||||
isFocusVisible: boolean;
|
||||
validationErrors: string[];
|
||||
timeValue: DatePickerTimeValue | null;
|
||||
state: DatePickerState;
|
||||
open: () => void;
|
||||
close: () => void;
|
||||
toggle: () => void;
|
||||
}
|
||||
|
||||
/** Shared Picker owner consumed by the field parts and an unbound Calendar. */
|
||||
export interface DatePickerContext {
|
||||
state: OverlayState;
|
||||
trigger: ShallowRef<HTMLElement | undefined>;
|
||||
value: ComputedRef<DateValue | null>;
|
||||
dates: ComputedRef<DateValue[]>;
|
||||
selected: (value: DateValue) => boolean;
|
||||
requestDate: (value: DateValue) => void;
|
||||
minValue: ComputedRef<DateValue | undefined>;
|
||||
maxValue: ComputedRef<DateValue | undefined>;
|
||||
isDateUnavailable?: (value: DateValue) => boolean;
|
||||
disabled: ComputedRef<boolean>;
|
||||
readOnly: ComputedRef<boolean>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
locale: ComputedRef<string>;
|
||||
dir: ComputedRef<"ltr" | "rtl">;
|
||||
labelledBy: () => string | undefined;
|
||||
describedBy: () => string | undefined;
|
||||
firstDayOfWeek?: import("../date/calendar").CalendarWeekday;
|
||||
pageBehavior?: "visible" | "single";
|
||||
placeholder: ComputedRef<DateValue>;
|
||||
timeValue: ComputedRef<DatePickerTimeValue | null>;
|
||||
setTimeValue: (value: DatePickerTimeValue | null) => void;
|
||||
shouldCloseOnSelect: () => boolean;
|
||||
}
|
||||
|
||||
export const datePickerKey: InjectionKey<DatePickerContext> =
|
||||
Symbol("hv-date-picker");
|
||||
|
||||
export function useDatePicker() {
|
||||
const value = inject(datePickerKey, undefined);
|
||||
if (!value) throw new Error("DatePicker parts require DatePicker.");
|
||||
return value;
|
||||
}
|
||||
Reference in New Issue
Block a user