屏幕
配色方案
明暗
圆角
颜色
所有状态
- 何时出现
- 行为规则
把这 2 个文件放进 components/mobilens/。只依赖 react-native(已用 Expo SDK 58 检查)。
import { useMemo, useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type DatePickerProps = {
/** Label above the date field. */
label: string;
/** Selected calendar date as YYYY-MM-DD, or null. */
value: string | null;
/** Receives the selected date, or null when cleared. */
onChange: (date: string | null) => void;
/** Earliest selectable YYYY-MM-DD, inclusive. */
min?: string;
/** Latest selectable YYYY-MM-DD, inclusive. */
max?: string;
/** Calendar and button language (en-US or zh-CN). */
locale?: 'en-US' | 'zh-CN';
/** Open the calendar when the field first mounts. */
defaultOpen?: boolean;
/** First month to show for an empty field, given as a YYYY-MM-DD date. */
initialMonth?: string;
/** Optional form validation message. */
error?: string;
/** Prevent the field from opening or changing. */
disabled?: boolean;
/** Show a clear action for an existing selection. */
clearable?: boolean;
};
// The value is a calendar day. Do all month arithmetic and formatting in the same time zone.
function dayAt(year: number, monthIndex: number, day: number) {
const date = new Date(0);
date.setUTCFullYear(year, monthIndex, day);
return date;
}
function isoDay(d: Date) {
return d.toISOString().slice(0, 10);
}
function parseDay(value?: string | null) {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000')) return null;
const [y, m, d] = value.split('-').map(Number);
const date = dayAt(y, m - 1, d);
return isoDay(date) === value ? date : null;
}
function currentDay() {
const now = new Date();
return isoDay(dayAt(now.getFullYear(), now.getMonth(), now.getDate()));
}
const labels = {
'en-US': { choose: 'Choose a date', previous: 'Previous month', next: 'Next month', clear: 'Clear', close: 'Close', unavailable: 'No dates available' },
'zh-CN': { choose: '选择日期', previous: '上个月', next: '下个月', clear: '清除日期', close: '收起日历', unavailable: '暂无可选日期' },
};
export function DatePicker({
label, value, onChange, min, max, locale = 'en-US', defaultOpen = false, initialMonth,
error, disabled = false, clearable = true, copyTestIDs,
}: DatePickerProps & { copyTestIDs?: { label?: string } }) {
const words = labels[locale];
const selected = parseDay(value);
const lower = parseDay(min) ? min! : '0001-01-01';
const upper = parseDay(max) ? max! : '9999-12-31';
const available = lower <= upper;
const locked = disabled || !available;
const firstMonth = lower.slice(0, 7);
const lastMonth = upper.slice(0, 7);
function clampMonth(month: string) {
if (month < firstMonth) return firstMonth;
if (month > lastMonth) return lastMonth;
return month;
}
function openingMonth() {
const start = selected ?? parseDay(initialMonth);
return clampMonth((start ? isoDay(start) : currentDay()).slice(0, 7));
}
const [open, setOpen] = useState(defaultOpen);
const [browsedMonth, setBrowsedMonth] = useState(openingMonth);
const month = clampMonth(browsedMonth);
const [year, monthNumber] = month.split('-').map(Number);
const monthIndex = monthNumber - 1;
const monthStart = dayAt(year, monthIndex, 1);
const totalDays = dayAt(year, monthIndex + 1, 0).getUTCDate();
const firstWeekday = locale === 'zh-CN' ? 1 : 0;
const leading = (monthStart.getUTCDay() - firstWeekday + 7) % 7;
const weekCount = Math.ceil((leading + totalDays) / 7);
const formats = useMemo(() => ({
full: new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }),
month: new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', timeZone: 'UTC' }),
weekday: new Intl.DateTimeFormat(locale, { weekday: 'narrow', timeZone: 'UTC' }),
}), [locale]);
const visible = open && !locked;
const display = selected ? formats.full.format(selected) : words.choose;
const warning = error || (!available ? words.unavailable : '');
function shiftMonth(offset: number) {
setBrowsedMonth(clampMonth(isoDay(dayAt(year, monthIndex + offset, 1)).slice(0, 7)));
}
function select(next: string | null) {
onChange(next);
setOpen(false);
}
function monthButton(offset: number, name: string, disabledButton: boolean) {
return <Pressable onPress={() => shiftMonth(offset)} disabled={disabledButton} accessibilityRole="button"
accessibilityLabel={name} accessibilityState={{ disabled: disabledButton }} style={styles.nav}>
<Text style={[styles.arrow, disabledButton && styles.unavailable]}>{offset === -1 ? '‹' : '›'}</Text>
</Pressable>;
}
return (
<View style={styles.field}>
<Text testID={copyTestIDs?.label} style={styles.label}>{label}</Text>
<Pressable accessibilityRole="button" accessibilityLabel={label + ', ' + display}
accessibilityState={{ disabled: locked, expanded: visible }} disabled={locked}
onPress={() => { if (!open) setBrowsedMonth(openingMonth()); setOpen(!open); }}
style={[styles.trigger, visible && styles.open, !!warning && styles.invalid, locked && styles.disabled]}>
<Text style={[styles.value, (!selected || locked) && styles.muted]}>{display}</Text>
<Text aria-hidden style={styles.chevron}>{visible ? '▴' : '▾'}</Text>
</Pressable>
{warning ? <Text accessibilityLiveRegion="polite" style={styles.error}>{warning}</Text> : null}
{visible && (
<View style={styles.calendar}>
<View style={styles.header}>
<Text accessibilityLiveRegion="polite" style={styles.month}>{formats.month.format(monthStart)}</Text>
{monthButton(-1, words.previous, month <= firstMonth)}
{monthButton(1, words.next, month >= lastMonth)}
</View>
<View style={styles.week}>
{Array.from({ length: 7 }, (_, i) =>
<Text key={i} style={styles.weekday}>{formats.weekday.format(dayAt(2023, 0, 1 + firstWeekday + i))}</Text>
)}
</View>
{Array.from({ length: weekCount }, (_, week) => (
<View key={week} style={styles.week}>
{Array.from({ length: 7 }, (_, column) => {
const day = week * 7 + column - leading + 1;
if (day < 1 || day > totalDays) return <View key={column} style={styles.slot} />;
const date = dayAt(year, monthIndex, day);
const key = isoDay(date);
const blocked = key < lower || key > upper;
const active = key === value;
return <Pressable key={column} accessibilityRole="button" accessibilityLabel={formats.full.format(date)}
accessibilityState={{ disabled: blocked, selected: active }} disabled={blocked}
onPress={() => select(key)} style={[styles.slot, active && styles.chosen]}>
<Text style={[styles.day, blocked && styles.unavailable, active && styles.chosenText]}>{day}</Text>
</Pressable>;
})}
</View>
))}
<View style={styles.actions}>
{clearable && value !== null && <Pressable accessibilityRole="button" onPress={() => select(null)} style={styles.action}>
<Text style={styles.actionText}>{words.clear}</Text>
</Pressable>}
<Pressable accessibilityRole="button" onPress={() => setOpen(false)} style={styles.action}>
<Text style={styles.actionText}>{words.close}</Text>
</Pressable>
</View>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
field: { gap: 7 },
label: { fontSize: 14, fontWeight: '600', color: colors.onSurface },
trigger: { minHeight: 48, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 14, borderWidth: 1, borderColor: colors.outline, borderRadius: radius.md, backgroundColor: colors.surface },
value: { flexShrink: 1, fontSize: 16, color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
chevron: { fontSize: 17, color: colors.onSurfaceVariant },
open: { borderColor: colors.primary },
invalid: { borderColor: colors.error },
disabled: { backgroundColor: colors.surfaceVariant },
error: { color: colors.error, fontSize: 13 },
calendar: { paddingHorizontal: 8, paddingTop: 4, borderWidth: 1, borderColor: colors.outlineVariant, borderRadius: radius.md, backgroundColor: colors.surface },
header: { flexDirection: 'row', alignItems: 'center', minHeight: 44, paddingLeft: 5 },
month: { flex: 1, fontSize: 17, fontWeight: '600', color: colors.onSurface },
nav: { width: 42, minHeight: 42, alignItems: 'center', justifyContent: 'center' },
arrow: { fontSize: 25, color: colors.onSurface },
week: { flexDirection: 'row' },
weekday: { flex: 1, textAlign: 'center', paddingBottom: 5, fontSize: 12, color: colors.onSurfaceVariant },
slot: { flex: 1, minHeight: 40, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md },
day: { fontSize: 15, fontVariant: ['tabular-nums'], color: colors.onSurface },
unavailable: { color: colors.onSurfaceVariant, opacity: 0.48 },
chosen: { backgroundColor: colors.primary },
chosenText: { color: colors.onPrimary, fontWeight: '700' },
actions: { flexDirection: 'row', justifyContent: 'flex-end', borderTopWidth: 1, borderColor: colors.outlineVariant, marginTop: 4 },
action: { minHeight: 40, justifyContent: 'center', paddingHorizontal: 9 },
actionText: { color: colors.primary, fontWeight: '600', fontSize: 14 },
});
import { useMemo, useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type DatePickerProps = {
/** Label above the date field. */
label: string;
/** Selected calendar date as YYYY-MM-DD, or null. */
value: string | null;
/** Receives the selected date, or null when cleared. */
onChange: (date: string | null) => void;
/** Earliest selectable YYYY-MM-DD, inclusive. */
min?: string;
/** Latest selectable YYYY-MM-DD, inclusive. */
max?: string;
/** Calendar and button language (en-US or zh-CN). */
locale?: 'en-US' | 'zh-CN';
/** Open the calendar when the field first mounts. */
defaultOpen?: boolean;
/** First month to show for an empty field, given as a YYYY-MM-DD date. */
initialMonth?: string;
/** Optional form validation message. */
error?: string;
/** Prevent the field from opening or changing. */
disabled?: boolean;
/** Show a clear action for an existing selection. */
clearable?: boolean;
};
// The value is a calendar day. Do all month arithmetic and formatting in the same time zone.
function dayAt(year: number, monthIndex: number, day: number) {
const date = new Date(0);
date.setUTCFullYear(year, monthIndex, day);
return date;
}
function isoDay(d: Date) {
return d.toISOString().slice(0, 10);
}
function parseDay(value?: string | null) {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000')) return null;
const [y, m, d] = value.split('-').map(Number);
const date = dayAt(y, m - 1, d);
return isoDay(date) === value ? date : null;
}
function currentDay() {
const now = new Date();
return isoDay(dayAt(now.getFullYear(), now.getMonth(), now.getDate()));
}
const labels = {
'en-US': { choose: 'Choose a date', previous: 'Previous month', next: 'Next month', clear: 'Clear', close: 'Close', unavailable: 'No dates available' },
'zh-CN': { choose: '选择日期', previous: '上个月', next: '下个月', clear: '清除日期', close: '收起日历', unavailable: '暂无可选日期' },
};
export function DatePicker({
label, value, onChange, min, max, locale = 'en-US', defaultOpen = false, initialMonth,
error, disabled = false, clearable = true, copyTestIDs,
}: DatePickerProps & { copyTestIDs?: { label?: string } }) {
const words = labels[locale];
const selected = parseDay(value);
const lower = parseDay(min) ? min! : '0001-01-01';
const upper = parseDay(max) ? max! : '9999-12-31';
const available = lower <= upper;
const locked = disabled || !available;
const firstMonth = lower.slice(0, 7);
const lastMonth = upper.slice(0, 7);
function clampMonth(month: string) {
if (month < firstMonth) return firstMonth;
if (month > lastMonth) return lastMonth;
return month;
}
function openingMonth() {
const start = selected ?? parseDay(initialMonth);
return clampMonth((start ? isoDay(start) : currentDay()).slice(0, 7));
}
const [open, setOpen] = useState(defaultOpen);
const [browsedMonth, setBrowsedMonth] = useState(openingMonth);
const month = clampMonth(browsedMonth);
const [year, monthNumber] = month.split('-').map(Number);
const monthIndex = monthNumber - 1;
const monthStart = dayAt(year, monthIndex, 1);
const totalDays = dayAt(year, monthIndex + 1, 0).getUTCDate();
const firstWeekday = locale === 'zh-CN' ? 1 : 0;
const leading = (monthStart.getUTCDay() - firstWeekday + 7) % 7;
const weekCount = Math.ceil((leading + totalDays) / 7);
const formats = useMemo(() => ({
full: new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }),
month: new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', timeZone: 'UTC' }),
weekday: new Intl.DateTimeFormat(locale, { weekday: 'narrow', timeZone: 'UTC' }),
}), [locale]);
const visible = open && !locked;
const display = selected ? formats.full.format(selected) : words.choose;
const warning = error || (!available ? words.unavailable : '');
function shiftMonth(offset: number) {
setBrowsedMonth(clampMonth(isoDay(dayAt(year, monthIndex + offset, 1)).slice(0, 7)));
}
function select(next: string | null) {
onChange(next);
setOpen(false);
}
function monthButton(offset: number, name: string, disabledButton: boolean) {
return <Pressable onPress={() => shiftMonth(offset)} disabled={disabledButton} accessibilityRole="button"
accessibilityLabel={name} accessibilityState={{ disabled: disabledButton }} style={styles.nav}>
<Text style={[styles.arrow, disabledButton && styles.unavailable]}>{offset === -1 ? '‹' : '›'}</Text>
</Pressable>;
}
return (
<View style={styles.field}>
<Text testID={copyTestIDs?.label} style={styles.label}>{label}</Text>
<Pressable accessibilityRole="button" accessibilityLabel={label + ', ' + display}
accessibilityState={{ disabled: locked, expanded: visible }} disabled={locked}
onPress={() => { if (!open) setBrowsedMonth(openingMonth()); setOpen(!open); }}
style={[styles.trigger, visible && styles.open, !!warning && styles.invalid, locked && styles.disabled]}>
<Text style={[styles.value, (!selected || locked) && styles.muted]}>{display}</Text>
<Text aria-hidden style={styles.chevron}>{visible ? '▴' : '▾'}</Text>
</Pressable>
{warning ? <Text accessibilityLiveRegion="polite" style={styles.error}>{warning}</Text> : null}
{visible && (
<View style={styles.calendar}>
<View style={styles.header}>
<Text accessibilityLiveRegion="polite" style={styles.month}>{formats.month.format(monthStart)}</Text>
{monthButton(-1, words.previous, month <= firstMonth)}
{monthButton(1, words.next, month >= lastMonth)}
</View>
<View style={styles.week}>
{Array.from({ length: 7 }, (_, i) =>
<Text key={i} style={styles.weekday}>{formats.weekday.format(dayAt(2023, 0, 1 + firstWeekday + i))}</Text>
)}
</View>
{Array.from({ length: weekCount }, (_, week) => (
<View key={week} style={styles.week}>
{Array.from({ length: 7 }, (_, column) => {
const day = week * 7 + column - leading + 1;
if (day < 1 || day > totalDays) return <View key={column} style={styles.slot} />;
const date = dayAt(year, monthIndex, day);
const key = isoDay(date);
const blocked = key < lower || key > upper;
const active = key === value;
return <Pressable key={column} accessibilityRole="button" accessibilityLabel={formats.full.format(date)}
accessibilityState={{ disabled: blocked, selected: active }} disabled={blocked}
onPress={() => select(key)} style={[styles.slot, active && styles.chosen]}>
<Text style={[styles.day, blocked && styles.unavailable, active && styles.chosenText]}>{day}</Text>
</Pressable>;
})}
</View>
))}
<View style={styles.actions}>
{clearable && value !== null && <Pressable accessibilityRole="button" onPress={() => select(null)} style={styles.action}>
<Text style={styles.actionText}>{words.clear}</Text>
</Pressable>}
<Pressable accessibilityRole="button" onPress={() => setOpen(false)} style={styles.action}>
<Text style={styles.actionText}>{words.close}</Text>
</Pressable>
</View>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
field: { gap: 7 },
label: { fontSize: 14, fontWeight: '600', color: colors.onSurface },
trigger: { minHeight: 48, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 14, borderWidth: 1, borderColor: colors.outline, borderRadius: radius.md, backgroundColor: colors.surface },
value: { flexShrink: 1, fontSize: 16, color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
chevron: { fontSize: 17, color: colors.onSurfaceVariant },
open: { borderColor: colors.primary },
invalid: { borderColor: colors.error },
disabled: { backgroundColor: colors.surfaceVariant },
error: { color: colors.error, fontSize: 13 },
calendar: { paddingHorizontal: 8, paddingTop: 4, borderWidth: 1, borderColor: colors.outlineVariant, borderRadius: radius.md, backgroundColor: colors.surface },
header: { flexDirection: 'row', alignItems: 'center', minHeight: 44, paddingLeft: 5 },
month: { flex: 1, fontSize: 17, fontWeight: '600', color: colors.onSurface },
nav: { width: 42, minHeight: 42, alignItems: 'center', justifyContent: 'center' },
arrow: { fontSize: 25, color: colors.onSurface },
week: { flexDirection: 'row' },
weekday: { flex: 1, textAlign: 'center', paddingBottom: 5, fontSize: 12, color: colors.onSurfaceVariant },
slot: { flex: 1, minHeight: 40, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md },
day: { fontSize: 15, fontVariant: ['tabular-nums'], color: colors.onSurface },
unavailable: { color: colors.onSurfaceVariant, opacity: 0.48 },
chosen: { backgroundColor: colors.primary },
chosenText: { color: colors.onPrimary, fontWeight: '700' },
actions: { flexDirection: 'row', justifyContent: 'flex-end', borderTopWidth: 1, borderColor: colors.outlineVariant, marginTop: 4 },
action: { minHeight: 40, justifyContent: 'center', paddingHorizontal: 9 },
actionText: { color: colors.primary, fontWeight: '600', fontSize: 14 },
});
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
用法
import { useState } from 'react';
import { DatePicker } from '@/components/mobilens/DatePicker';
export function DeliveryDate({ firstDay, lastDay }: { firstDay: string; lastDay: string }) {
const [date, setDate] = useState<string | null>(null);
return <DatePicker label="Delivery date" locale="en-US" value={date} onChange={setDate}
min={firstDay} max={lastDay} clearable />;
}
import { useState } from 'react';
import { DatePicker } from '@/components/mobilens/DatePicker';
export function DeliveryDate({ firstDay, lastDay }: { firstDay: string; lastDay: string }) {
const [date, setDate] = useState<string | null>(null);
return <DatePicker label="Delivery date" locale="en-US" value={date} onChange={setDate}
min={firstDay} max={lastDay} clearable />;
}
API
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| label | string | – | Label above the date field. |
| value | string | null | – | Selected calendar date as YYYY-MM-DD, or null. |
| onChange | (date: string | null) => void | – | Receives the selected date, or null when cleared. |
| min? | string | – | Earliest selectable YYYY-MM-DD, inclusive. |
| max? | string | – | Latest selectable YYYY-MM-DD, inclusive. |
| locale? | 'en-US' | 'zh-CN' | 'en-US' | Calendar and button language (en-US or zh-CN). |
| defaultOpen? | boolean | false | Open the calendar when the field first mounts. |
| initialMonth? | string | – | First month to show for an empty field, given as a YYYY-MM-DD date. |
| error? | string | – | Optional form validation message. |
| disabled? | boolean | false | Prevent the field from opening or changing. |
| clearable? | boolean | true | Show a clear action for an existing selection. |
Add the "Date picker" control to this Expo or React Native project. Create the files below with exactly this content. Do not restyle or rewrite them.
FILES
Put them in components/mobilens/. theme.ts is shared by every Mobilens component: if it already exists, keep one copy, and skip any other file that is already there with the same content. If the project has no "@/..." import alias, change those imports to relative paths.
--- components/mobilens/theme.ts ---
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
--- end of theme.ts ---
--- components/mobilens/DatePicker.tsx ---
import { useMemo, useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type DatePickerProps = {
/** Label above the date field. */
label: string;
/** Selected calendar date as YYYY-MM-DD, or null. */
value: string | null;
/** Receives the selected date, or null when cleared. */
onChange: (date: string | null) => void;
/** Earliest selectable YYYY-MM-DD, inclusive. */
min?: string;
/** Latest selectable YYYY-MM-DD, inclusive. */
max?: string;
/** Calendar and button language (en-US or zh-CN). */
locale?: 'en-US' | 'zh-CN';
/** Open the calendar when the field first mounts. */
defaultOpen?: boolean;
/** First month to show for an empty field, given as a YYYY-MM-DD date. */
initialMonth?: string;
/** Optional form validation message. */
error?: string;
/** Prevent the field from opening or changing. */
disabled?: boolean;
/** Show a clear action for an existing selection. */
clearable?: boolean;
};
// The value is a calendar day. Do all month arithmetic and formatting in the same time zone.
function dayAt(year: number, monthIndex: number, day: number) {
const date = new Date(0);
date.setUTCFullYear(year, monthIndex, day);
return date;
}
function isoDay(d: Date) {
return d.toISOString().slice(0, 10);
}
function parseDay(value?: string | null) {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000')) return null;
const [y, m, d] = value.split('-').map(Number);
const date = dayAt(y, m - 1, d);
return isoDay(date) === value ? date : null;
}
function currentDay() {
const now = new Date();
return isoDay(dayAt(now.getFullYear(), now.getMonth(), now.getDate()));
}
const labels = {
'en-US': { choose: 'Choose a date', previous: 'Previous month', next: 'Next month', clear: 'Clear', close: 'Close', unavailable: 'No dates available' },
'zh-CN': { choose: '选择日期', previous: '上个月', next: '下个月', clear: '清除日期', close: '收起日历', unavailable: '暂无可选日期' },
};
export function DatePicker({
label, value, onChange, min, max, locale = 'en-US', defaultOpen = false, initialMonth,
error, disabled = false, clearable = true, copyTestIDs,
}: DatePickerProps & { copyTestIDs?: { label?: string } }) {
const words = labels[locale];
const selected = parseDay(value);
const lower = parseDay(min) ? min! : '0001-01-01';
const upper = parseDay(max) ? max! : '9999-12-31';
const available = lower <= upper;
const locked = disabled || !available;
const firstMonth = lower.slice(0, 7);
const lastMonth = upper.slice(0, 7);
function clampMonth(month: string) {
if (month < firstMonth) return firstMonth;
if (month > lastMonth) return lastMonth;
return month;
}
function openingMonth() {
const start = selected ?? parseDay(initialMonth);
return clampMonth((start ? isoDay(start) : currentDay()).slice(0, 7));
}
const [open, setOpen] = useState(defaultOpen);
const [browsedMonth, setBrowsedMonth] = useState(openingMonth);
const month = clampMonth(browsedMonth);
const [year, monthNumber] = month.split('-').map(Number);
const monthIndex = monthNumber - 1;
const monthStart = dayAt(year, monthIndex, 1);
const totalDays = dayAt(year, monthIndex + 1, 0).getUTCDate();
const firstWeekday = locale === 'zh-CN' ? 1 : 0;
const leading = (monthStart.getUTCDay() - firstWeekday + 7) % 7;
const weekCount = Math.ceil((leading + totalDays) / 7);
const formats = useMemo(() => ({
full: new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }),
month: new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', timeZone: 'UTC' }),
weekday: new Intl.DateTimeFormat(locale, { weekday: 'narrow', timeZone: 'UTC' }),
}), [locale]);
const visible = open && !locked;
const display = selected ? formats.full.format(selected) : words.choose;
const warning = error || (!available ? words.unavailable : '');
function shiftMonth(offset: number) {
setBrowsedMonth(clampMonth(isoDay(dayAt(year, monthIndex + offset, 1)).slice(0, 7)));
}
function select(next: string | null) {
onChange(next);
setOpen(false);
}
function monthButton(offset: number, name: string, disabledButton: boolean) {
return <Pressable onPress={() => shiftMonth(offset)} disabled={disabledButton} accessibilityRole="button"
accessibilityLabel={name} accessibilityState={{ disabled: disabledButton }} style={styles.nav}>
<Text style={[styles.arrow, disabledButton && styles.unavailable]}>{offset === -1 ? '‹' : '›'}</Text>
</Pressable>;
}
return (
<View style={styles.field}>
<Text testID={copyTestIDs?.label} style={styles.label}>{label}</Text>
<Pressable accessibilityRole="button" accessibilityLabel={label + ', ' + display}
accessibilityState={{ disabled: locked, expanded: visible }} disabled={locked}
onPress={() => { if (!open) setBrowsedMonth(openingMonth()); setOpen(!open); }}
style={[styles.trigger, visible && styles.open, !!warning && styles.invalid, locked && styles.disabled]}>
<Text style={[styles.value, (!selected || locked) && styles.muted]}>{display}</Text>
<Text aria-hidden style={styles.chevron}>{visible ? '▴' : '▾'}</Text>
</Pressable>
{warning ? <Text accessibilityLiveRegion="polite" style={styles.error}>{warning}</Text> : null}
{visible && (
<View style={styles.calendar}>
<View style={styles.header}>
<Text accessibilityLiveRegion="polite" style={styles.month}>{formats.month.format(monthStart)}</Text>
{monthButton(-1, words.previous, month <= firstMonth)}
{monthButton(1, words.next, month >= lastMonth)}
</View>
<View style={styles.week}>
{Array.from({ length: 7 }, (_, i) =>
<Text key={i} style={styles.weekday}>{formats.weekday.format(dayAt(2023, 0, 1 + firstWeekday + i))}</Text>
)}
</View>
{Array.from({ length: weekCount }, (_, week) => (
<View key={week} style={styles.week}>
{Array.from({ length: 7 }, (_, column) => {
const day = week * 7 + column - leading + 1;
if (day < 1 || day > totalDays) return <View key={column} style={styles.slot} />;
const date = dayAt(year, monthIndex, day);
const key = isoDay(date);
const blocked = key < lower || key > upper;
const active = key === value;
return <Pressable key={column} accessibilityRole="button" accessibilityLabel={formats.full.format(date)}
accessibilityState={{ disabled: blocked, selected: active }} disabled={blocked}
onPress={() => select(key)} style={[styles.slot, active && styles.chosen]}>
<Text style={[styles.day, blocked && styles.unavailable, active && styles.chosenText]}>{day}</Text>
</Pressable>;
})}
</View>
))}
<View style={styles.actions}>
{clearable && value !== null && <Pressable accessibilityRole="button" onPress={() => select(null)} style={styles.action}>
<Text style={styles.actionText}>{words.clear}</Text>
</Pressable>}
<Pressable accessibilityRole="button" onPress={() => setOpen(false)} style={styles.action}>
<Text style={styles.actionText}>{words.close}</Text>
</Pressable>
</View>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
field: { gap: 7 },
label: { fontSize: 14, fontWeight: '600', color: colors.onSurface },
trigger: { minHeight: 48, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 14, borderWidth: 1, borderColor: colors.outline, borderRadius: radius.md, backgroundColor: colors.surface },
value: { flexShrink: 1, fontSize: 16, color: colors.onSurface },
muted: { color: colors.onSurfaceVariant },
chevron: { fontSize: 17, color: colors.onSurfaceVariant },
open: { borderColor: colors.primary },
invalid: { borderColor: colors.error },
disabled: { backgroundColor: colors.surfaceVariant },
error: { color: colors.error, fontSize: 13 },
calendar: { paddingHorizontal: 8, paddingTop: 4, borderWidth: 1, borderColor: colors.outlineVariant, borderRadius: radius.md, backgroundColor: colors.surface },
header: { flexDirection: 'row', alignItems: 'center', minHeight: 44, paddingLeft: 5 },
month: { flex: 1, fontSize: 17, fontWeight: '600', color: colors.onSurface },
nav: { width: 42, minHeight: 42, alignItems: 'center', justifyContent: 'center' },
arrow: { fontSize: 25, color: colors.onSurface },
week: { flexDirection: 'row' },
weekday: { flex: 1, textAlign: 'center', paddingBottom: 5, fontSize: 12, color: colors.onSurfaceVariant },
slot: { flex: 1, minHeight: 40, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md },
day: { fontSize: 15, fontVariant: ['tabular-nums'], color: colors.onSurface },
unavailable: { color: colors.onSurfaceVariant, opacity: 0.48 },
chosen: { backgroundColor: colors.primary },
chosenText: { color: colors.onPrimary, fontWeight: '700' },
actions: { flexDirection: 'row', justifyContent: 'flex-end', borderTopWidth: 1, borderColor: colors.outlineVariant, marginTop: 4 },
action: { minHeight: 40, justifyContent: 'center', paddingHorizontal: 9 },
actionText: { color: colors.primary, fontWeight: '600', fontSize: 14 },
});
--- end of DatePicker.tsx ---
HOW TO USE IT
import { useState } from 'react';
import { DatePicker } from '@/components/mobilens/DatePicker';
export function DeliveryDate({ firstDay, lastDay }: { firstDay: string; lastDay: string }) {
const [date, setDate] = useState<string | null>(null);
return <DatePicker label="Delivery date" locale="en-US" value={date} onChange={setDate}
min={firstDay} max={lastDay} clearable />;
}
STATES: all 6 must work in the screen where you use it
- Empty: when no day has been selected. Opening the field keeps the current value until a day is chosen.
- Calendar open: when the user opens the date field. Browse available months and choose a selectable day.
- Date selected: when the user chooses a day. Choosing a day closes the calendar and shows the localized date.
- Range boundary: when the selected day is the last eligible day. Days after the maximum are unavailable. Navigation stops at the last available month.
- Date required: when A required form is submitted without a date. The form shows a message and clears it after a date is chosen.
- Disabled: when the delivery date has been locked. The date remains visible and cannot be edited or cleared.
ACCESSIBILITY
- Days have full date labels. Unavailable days and the selected day expose their state to assistive technology.
WHEN YOU FINISH
List every state and rule above and say how you verified each one.