feat(workbench): integrate runtime data and map tooling
This commit is contained in:
@@ -14,6 +14,12 @@ describe("runtime frontend configuration", () => {
|
||||
TJWATER_GEOSERVER_WORKSPACE: "project-a",
|
||||
TJWATER_SERVER_API_BASE_URL: "https://server.example.test",
|
||||
TJWATER_AGENT_API_BASE_URL: "https://agent.example.test",
|
||||
TJWATER_WORKBENCH_RUNTIME_MODE: "backend",
|
||||
TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL: "https://peripheral.example.test/",
|
||||
TJWATER_PERIPHERAL_SAMPLE_TIME_MODE: "recent",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_START: "2026-04-30T08:00:00Z",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_END: "2026-04-30T16:00:00Z",
|
||||
TJWATER_PERIPHERAL_SAMPLE_RECENT_HOURS: "6",
|
||||
TJWATER_ENABLE_DEV_PANEL: "true",
|
||||
TJWATER_ENABLE_MSW: "false"
|
||||
})
|
||||
@@ -26,6 +32,12 @@ describe("runtime frontend configuration", () => {
|
||||
TJWATER_GEOSERVER_WORKSPACE: "project-a",
|
||||
TJWATER_SERVER_API_BASE_URL: "https://server.example.test",
|
||||
TJWATER_AGENT_API_BASE_URL: "https://agent.example.test",
|
||||
TJWATER_WORKBENCH_RUNTIME_MODE: "backend",
|
||||
TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL: "https://peripheral.example.test",
|
||||
TJWATER_PERIPHERAL_SAMPLE_TIME_MODE: "recent",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_START: "2026-04-30T08:00:00Z",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_END: "2026-04-30T16:00:00Z",
|
||||
TJWATER_PERIPHERAL_SAMPLE_RECENT_HOURS: 6,
|
||||
TJWATER_ENABLE_DEV_PANEL: true,
|
||||
TJWATER_ENABLE_MSW: false
|
||||
});
|
||||
@@ -35,11 +47,24 @@ describe("runtime frontend configuration", () => {
|
||||
expect(parseRuntimeConfig({ TJWATER_AUTH_MODE: "disabled" })).toMatchObject({
|
||||
TJWATER_AUTH_MODE: "disabled",
|
||||
TJWATER_KEYCLOAK_CLIENT_ID: "next-tjwater",
|
||||
TJWATER_WORKBENCH_RUNTIME_MODE: "auto",
|
||||
TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL: "",
|
||||
TJWATER_PERIPHERAL_SAMPLE_TIME_MODE: "demo",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_START: "2026-09-17T00:00:00Z",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_END: "2026-09-17T12:00:00Z",
|
||||
TJWATER_PERIPHERAL_SAMPLE_RECENT_HOURS: 8,
|
||||
TJWATER_ENABLE_DEV_PANEL: false,
|
||||
TJWATER_ENABLE_MSW: false
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts the explicit backend history mode", () => {
|
||||
expect(parseRuntimeConfig({
|
||||
TJWATER_AUTH_MODE: "disabled",
|
||||
TJWATER_WORKBENCH_RUNTIME_MODE: "history"
|
||||
}).TJWATER_WORKBENCH_RUNTIME_MODE).toBe("history");
|
||||
});
|
||||
|
||||
it("requires a Realm issuer when authentication is enabled", () => {
|
||||
expect(() => parseRuntimeConfig({ TJWATER_AUTH_MODE: "required" })).toThrow();
|
||||
});
|
||||
@@ -51,7 +76,8 @@ describe("runtime frontend configuration", () => {
|
||||
it.each([
|
||||
["TJWATER_MAP_URL", "file:///etc/passwd"],
|
||||
["TJWATER_AGENT_API_BASE_URL", "https://user:secret@agent.example.test"],
|
||||
["TJWATER_AGENT_API_BASE_URL", "https://agent.example.test/#secret"]
|
||||
["TJWATER_AGENT_API_BASE_URL", "https://agent.example.test/#secret"],
|
||||
["TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL", "https://user:secret@peripheral.example.test"]
|
||||
])("rejects unsafe browser runtime address %s", (key, value) => {
|
||||
expect(() => parseRuntimeConfig({ TJWATER_AUTH_MODE: "disabled", [key]: value })).toThrow();
|
||||
});
|
||||
@@ -65,4 +91,17 @@ describe("runtime frontend configuration", () => {
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects an invalid or oversized peripheral demo window", () => {
|
||||
expect(() => parseRuntimeConfig({
|
||||
TJWATER_AUTH_MODE: "disabled",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_START: "2026-04-30T16:00:00Z",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_END: "2026-04-30T08:00:00Z"
|
||||
})).toThrow(/演示窗口/);
|
||||
expect(() => parseRuntimeConfig({
|
||||
TJWATER_AUTH_MODE: "disabled",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_START: "2026-04-01T00:00:00Z",
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_END: "2026-04-30T00:00:00Z"
|
||||
})).toThrow(/演示窗口/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,6 +22,19 @@ const browserHttpUrl = z
|
||||
}
|
||||
});
|
||||
|
||||
const optionalBrowserHttpUrl = z
|
||||
.string()
|
||||
.trim()
|
||||
.default("")
|
||||
.superRefine((value, context) => {
|
||||
if (!value) return;
|
||||
const parsed = browserHttpUrl.safeParse(value);
|
||||
if (!parsed.success) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "必须是安全的 HTTP(S) 地址" });
|
||||
}
|
||||
})
|
||||
.transform((value) => value.replace(/\/+$/, ""));
|
||||
|
||||
const keycloakIssuer = z
|
||||
.string()
|
||||
.trim()
|
||||
@@ -50,10 +63,27 @@ const runtimeConfigSchema = z
|
||||
TJWATER_GEOSERVER_WORKSPACE: z.string().trim().min(1).default("tjwater_next"),
|
||||
TJWATER_SERVER_API_BASE_URL: browserHttpUrl.default("http://127.0.0.1:8000"),
|
||||
TJWATER_AGENT_API_BASE_URL: browserHttpUrl.default("http://127.0.0.1:8787"),
|
||||
TJWATER_WORKBENCH_RUNTIME_MODE: z.enum(["auto", "demo", "history", "backend"]).default("auto"),
|
||||
TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL: optionalBrowserHttpUrl,
|
||||
TJWATER_PERIPHERAL_SAMPLE_TIME_MODE: z.enum(["demo", "recent"]).default("demo"),
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_START: z.string().datetime({ offset: true })
|
||||
.default("2026-09-17T00:00:00Z"),
|
||||
TJWATER_PERIPHERAL_SAMPLE_DEMO_END: z.string().datetime({ offset: true })
|
||||
.default("2026-09-17T12:00:00Z"),
|
||||
TJWATER_PERIPHERAL_SAMPLE_RECENT_HOURS: z.coerce.number().int().min(1).max(168).default(8),
|
||||
TJWATER_ENABLE_DEV_PANEL: runtimeBoolean(false),
|
||||
TJWATER_ENABLE_MSW: runtimeBoolean(false)
|
||||
})
|
||||
.superRefine((config, context) => {
|
||||
const demoStart = Date.parse(config.TJWATER_PERIPHERAL_SAMPLE_DEMO_START);
|
||||
const demoEnd = Date.parse(config.TJWATER_PERIPHERAL_SAMPLE_DEMO_END);
|
||||
if (demoEnd <= demoStart || demoEnd - demoStart > 7 * 24 * 60 * 60 * 1000) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["TJWATER_PERIPHERAL_SAMPLE_DEMO_END"],
|
||||
message: "外围演示窗口必须晚于开始时间且不超过 7 天"
|
||||
});
|
||||
}
|
||||
if (config.TJWATER_AUTH_MODE !== "required") return;
|
||||
if (!config.TJWATER_KEYCLOAK_ISSUER) {
|
||||
context.addIssue({
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { Checkbox } from "./checkbox";
|
||||
|
||||
it("retains checkbox semantics and label activation with a custom appearance", () => {
|
||||
const change = vi.fn();
|
||||
render(
|
||||
<label>
|
||||
确认范围
|
||||
<Checkbox onChange={change} />
|
||||
</label>
|
||||
);
|
||||
const input = screen.getByRole("checkbox", { name: "确认范围" });
|
||||
expect(input).not.toBeChecked();
|
||||
expect(input).toHaveClass("appearance-none");
|
||||
fireEvent.click(screen.getByText("确认范围"));
|
||||
expect(input).toBeChecked();
|
||||
expect(change).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves disabled checked state without emitting changes on render", () => {
|
||||
const change = vi.fn();
|
||||
render(<Checkbox aria-label="已确认" checked disabled onChange={change} />);
|
||||
expect(screen.getByRole("checkbox", { name: "已确认" })).toBeChecked();
|
||||
expect(screen.getByRole("checkbox", { name: "已确认" })).toBeDisabled();
|
||||
expect(change).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { forwardRef, type ComponentProps } from "react";
|
||||
import { Check } from "lucide-react";
|
||||
import { cn } from "./cn";
|
||||
|
||||
export const Checkbox = forwardRef<HTMLInputElement, Omit<ComponentProps<"input">, "type">>(
|
||||
function Checkbox({ className, ...props }, ref) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"relative inline-flex size-5 shrink-0 align-middle",
|
||||
props.disabled && "opacity-50"
|
||||
)}
|
||||
>
|
||||
<input
|
||||
{...props}
|
||||
ref={ref}
|
||||
type="checkbox"
|
||||
className={cn(
|
||||
"peer m-0 size-5 cursor-pointer appearance-none rounded-md border border-[var(--action-border)] bg-[var(--surface-reading)] shadow-xs transition-[background-color,border-color,scale] duration-150 checked:border-[var(--action-blue)] checked:bg-[var(--action-blue)] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[var(--action-focus-ring)] focus-visible:ring-offset-2 active:scale-90 motion-reduce:transition-none motion-reduce:active:scale-100 disabled:cursor-not-allowed",
|
||||
className
|
||||
)}
|
||||
/>
|
||||
<Check
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0 m-auto size-3.5 scale-75 text-white opacity-0 transition-[opacity,scale] duration-150 peer-checked:scale-100 peer-checked:opacity-100 motion-reduce:transition-none"
|
||||
strokeWidth={3}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,70 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { DateTimeField } from "@/shared/ui/date-time-field";
|
||||
import "@/test/radix-select-test-setup";
|
||||
|
||||
describe("DateTimeField", () => {
|
||||
it("does not change the controlled value when opening and cancelling", async () => {
|
||||
const onChange = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
render(<DateTimeField label="时窗开始" value="2026-09-17T08:00" onChange={onChange} />);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "时窗开始" }));
|
||||
expect(screen.getByRole("dialog", { name: "选择时窗开始" })).toBeVisible();
|
||||
await user.click(screen.getByRole("button", { name: "取消" }));
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("button", { name: "时窗开始" })).toHaveFocus();
|
||||
});
|
||||
|
||||
it("emits a minute-precision local datetime only after confirmation", async () => {
|
||||
const onChange = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
render(<DateTimeField label="时窗开始" value="2024-02-28T09:30" onChange={onChange} />);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "时窗开始" }));
|
||||
await user.click(screen.getByRole("gridcell", { name: "2024年2月29日" }));
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await user.click(screen.getByRole("button", { name: "确认" }));
|
||||
|
||||
expect(onChange).toHaveBeenCalledOnce();
|
||||
expect(onChange).toHaveBeenCalledWith("2024-02-29T09:30");
|
||||
});
|
||||
|
||||
it.each(["2025-02-29T12:00", "2024-04-31T12:00", "2024-02-29T12:00:30"])(
|
||||
"rejects invalid or unexpected source value %s",
|
||||
async (value) => {
|
||||
const user = userEvent.setup();
|
||||
render(<DateTimeField label="时窗开始" value={value} onChange={vi.fn()} />);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "时窗开始" }));
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("当前值格式无效");
|
||||
expect(screen.getByRole("button", { name: "确认" })).toBeDisabled();
|
||||
}
|
||||
);
|
||||
|
||||
it("renders the correct leap-month day count", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<DateTimeField label="时窗开始" value="2024-02-01T00:00" onChange={vi.fn()} />);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "时窗开始" }));
|
||||
expect(screen.getAllByRole("gridcell")).toHaveLength(29);
|
||||
expect(screen.getByRole("gridcell", { name: "2024年2月29日" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("cannot open or confirm while disabled", async () => {
|
||||
const onChange = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<DateTimeField label="时窗开始" value="2026-09-17T08:00" onChange={onChange} disabled />
|
||||
);
|
||||
|
||||
const trigger = screen.getByRole("button", { name: "时窗开始" });
|
||||
expect(trigger).toBeDisabled();
|
||||
await user.click(trigger);
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,399 @@
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
|
||||
import { Button } from "@/shared/ui/button";
|
||||
import { cn } from "@/shared/ui/cn";
|
||||
import { Dialog, DialogPortal, DialogTitle, DialogTrigger } from "@/shared/ui/dialog";
|
||||
import { FieldSelect } from "@/shared/ui/field-select";
|
||||
import { Input } from "@/shared/ui/input";
|
||||
|
||||
export interface DateTimeFieldProps {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
interface DateTimeParts {
|
||||
year: number;
|
||||
month: number;
|
||||
day: number;
|
||||
hour: number;
|
||||
minute: number;
|
||||
}
|
||||
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, index) => ({
|
||||
value: String(index + 1),
|
||||
label: `${index + 1}月`
|
||||
}));
|
||||
const HOUR_OPTIONS = Array.from({ length: 24 }, (_, hour) => ({
|
||||
value: pad(hour),
|
||||
label: pad(hour)
|
||||
}));
|
||||
const MINUTE_OPTIONS = Array.from({ length: 60 }, (_, minute) => ({
|
||||
value: pad(minute),
|
||||
label: pad(minute)
|
||||
}));
|
||||
const WEEKDAYS = ["一", "二", "三", "四", "五", "六", "日"];
|
||||
|
||||
function pad(value: number) {
|
||||
return String(value).padStart(2, "0");
|
||||
}
|
||||
|
||||
function daysInMonth(year: number, month: number) {
|
||||
const date = new Date(0);
|
||||
date.setHours(12, 0, 0, 0);
|
||||
date.setFullYear(year, month, 0);
|
||||
return date.getDate();
|
||||
}
|
||||
|
||||
function calendarDate(year: number, monthIndex: number, day: number) {
|
||||
const date = new Date(0);
|
||||
date.setHours(12, 0, 0, 0);
|
||||
date.setFullYear(year, monthIndex, day);
|
||||
return date;
|
||||
}
|
||||
|
||||
function isValidParts(parts: DateTimeParts) {
|
||||
return (
|
||||
Number.isInteger(parts.year) &&
|
||||
parts.year >= 1 &&
|
||||
parts.year <= 9999 &&
|
||||
parts.month >= 1 &&
|
||||
parts.month <= 12 &&
|
||||
parts.day >= 1 &&
|
||||
parts.day <= daysInMonth(parts.year, parts.month) &&
|
||||
parts.hour >= 0 &&
|
||||
parts.hour <= 23 &&
|
||||
parts.minute >= 0 &&
|
||||
parts.minute <= 59
|
||||
);
|
||||
}
|
||||
|
||||
function parseDateTimeValue(value: string): DateTimeParts | null {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(value);
|
||||
if (!match) return null;
|
||||
const parts = {
|
||||
year: Number(match[1]),
|
||||
month: Number(match[2]),
|
||||
day: Number(match[3]),
|
||||
hour: Number(match[4]),
|
||||
minute: Number(match[5])
|
||||
};
|
||||
return isValidParts(parts) ? parts : null;
|
||||
}
|
||||
|
||||
function formatValue(parts: DateTimeParts) {
|
||||
return `${String(parts.year).padStart(4, "0")}-${pad(parts.month)}-${pad(parts.day)}T${pad(parts.hour)}:${pad(parts.minute)}`;
|
||||
}
|
||||
|
||||
function todayParts(): DateTimeParts {
|
||||
const date = new Date();
|
||||
return {
|
||||
year: date.getFullYear(),
|
||||
month: date.getMonth() + 1,
|
||||
day: date.getDate(),
|
||||
hour: date.getHours(),
|
||||
minute: date.getMinutes()
|
||||
};
|
||||
}
|
||||
|
||||
function displayValue(value: string) {
|
||||
const parts = parseDateTimeValue(value);
|
||||
return parts
|
||||
? `${String(parts.year).padStart(4, "0")}-${pad(parts.month)}-${pad(parts.day)} ${pad(parts.hour)}:${pad(parts.minute)}`
|
||||
: value || "请选择日期和时间";
|
||||
}
|
||||
|
||||
function sameDay(parts: DateTimeParts, date: Date) {
|
||||
return (
|
||||
parts.year === date.getFullYear() &&
|
||||
parts.month === date.getMonth() + 1 &&
|
||||
parts.day === date.getDate()
|
||||
);
|
||||
}
|
||||
|
||||
function moveDay(parts: DateTimeParts, amount: number): DateTimeParts {
|
||||
const date = calendarDate(parts.year, parts.month - 1, parts.day + amount);
|
||||
const year = date.getFullYear();
|
||||
if (year < 1 || year > 9999) return parts;
|
||||
return { ...parts, year, month: date.getMonth() + 1, day: date.getDate() };
|
||||
}
|
||||
|
||||
export function DateTimeField({ label, value, onChange, disabled = false }: DateTimeFieldProps) {
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [draft, setDraft] = useState<DateTimeParts>(
|
||||
() => parseDateTimeValue(value) ?? todayParts()
|
||||
);
|
||||
const [yearText, setYearText] = useState(String(draft.year));
|
||||
const [sourceInvalid, setSourceInvalid] = useState(Boolean(value && !parseDateTimeValue(value)));
|
||||
const selectedDayRef = useRef<HTMLButtonElement>(null);
|
||||
const focusDayAfterNavigation = useRef(false);
|
||||
const validYear = /^\d{1,4}$/.test(yearText) && Number(yearText) >= 1;
|
||||
const canConfirm = !disabled && !sourceInvalid && validYear && isValidParts(draft);
|
||||
|
||||
const resetDraft = (nextValue: string) => {
|
||||
const parsed = parseDateTimeValue(nextValue);
|
||||
const next = parsed ?? todayParts();
|
||||
setDraft(next);
|
||||
setYearText(String(next.year));
|
||||
setSourceInvalid(Boolean(nextValue && !parsed));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open) resetDraft(value);
|
||||
}, [open, value]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!disabled) return;
|
||||
setOpen(false);
|
||||
}, [disabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!focusDayAfterNavigation.current) return;
|
||||
focusDayAfterNavigation.current = false;
|
||||
selectedDayRef.current?.focus();
|
||||
}, [draft.year, draft.month, draft.day]);
|
||||
|
||||
const updateDraft = (next: DateTimeParts) => {
|
||||
setDraft(next);
|
||||
setYearText(String(next.year));
|
||||
setSourceInvalid(false);
|
||||
};
|
||||
|
||||
const changeMonth = (amount: number) => {
|
||||
if (
|
||||
(amount < 0 && draft.year === 1 && draft.month === 1) ||
|
||||
(amount > 0 && draft.year === 9999 && draft.month === 12)
|
||||
)
|
||||
return;
|
||||
const date = calendarDate(draft.year, draft.month - 1 + amount, 1);
|
||||
const nextYear = date.getFullYear();
|
||||
const nextMonth = date.getMonth() + 1;
|
||||
updateDraft({
|
||||
...draft,
|
||||
year: nextYear,
|
||||
month: nextMonth,
|
||||
day: Math.min(draft.day, daysInMonth(nextYear, nextMonth))
|
||||
});
|
||||
};
|
||||
|
||||
const firstWeekday = (calendarDate(draft.year, draft.month - 1, 1).getDay() + 6) % 7;
|
||||
const dayCount = daysInMonth(draft.year, draft.month);
|
||||
const today = new Date();
|
||||
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<label id={`${id}-label`} className="mb-1 block text-xs font-medium text-slate-600">
|
||||
{label}
|
||||
</label>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (disabled && nextOpen) return;
|
||||
setOpen(nextOpen);
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
aria-labelledby={`${id}-label`}
|
||||
aria-describedby={`${id}-value`}
|
||||
className="flex h-10 w-full min-w-0 items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 text-left text-sm tabular-nums text-slate-800 shadow-xs transition-[border-color,box-shadow,scale] duration-150 [@media(hover:hover)]:hover:border-slate-300 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-500/30 active:scale-[0.99] motion-reduce:transition-none motion-reduce:active:scale-100 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
<CalendarDays className="size-4 shrink-0 text-slate-400" aria-hidden="true" />
|
||||
<span id={`${id}-value`} className={cn("min-w-0 truncate", !value && "text-slate-400")}>
|
||||
{displayValue(value)}
|
||||
</span>
|
||||
</button>
|
||||
</DialogTrigger>
|
||||
<DialogPortal>
|
||||
<DialogPrimitive.Overlay className="fixed inset-0 z-[80] bg-slate-950/20 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
|
||||
<DialogPrimitive.Content
|
||||
aria-describedby={undefined}
|
||||
className="fixed left-1/2 top-1/2 z-[85] max-h-[calc(100dvh-1.5rem)] w-[352px] max-w-[calc(100vw-1.5rem)] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-slate-200 bg-white p-4 shadow-[0_20px_60px_rgba(15,23,42,0.22)] outline-hidden data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
|
||||
onOpenAutoFocus={(event) => {
|
||||
if (sourceInvalid) return;
|
||||
event.preventDefault();
|
||||
requestAnimationFrame(() => selectedDayRef.current?.focus());
|
||||
}}
|
||||
>
|
||||
<DialogTitle className="pr-8 text-base text-slate-900">选择{label}</DialogTitle>
|
||||
<div className="mt-3 flex min-w-0 items-end gap-2">
|
||||
<FieldSelect
|
||||
label="月份"
|
||||
value={String(draft.month)}
|
||||
options={MONTH_OPTIONS}
|
||||
onValueChange={(month) => {
|
||||
const nextMonth = Number(month);
|
||||
updateDraft({
|
||||
...draft,
|
||||
month: nextMonth,
|
||||
day: Math.min(draft.day, daysInMonth(draft.year, nextMonth))
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<label className="min-w-0 flex-1 text-xs font-medium text-slate-600">
|
||||
年份
|
||||
<Input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
value={yearText}
|
||||
aria-invalid={!validYear}
|
||||
className="mt-1 h-10 rounded-lg border-slate-200 bg-white text-sm tabular-nums"
|
||||
onChange={(event) => {
|
||||
const nextText = event.target.value.replace(/\D/g, "").slice(0, 4);
|
||||
setYearText(nextText);
|
||||
const year = Number(nextText);
|
||||
if (year >= 1) {
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
year,
|
||||
day: Math.min(current.day, daysInMonth(year, current.month))
|
||||
}));
|
||||
setSourceInvalid(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-3 flex items-center justify-between">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="上个月"
|
||||
disabled={draft.year === 1 && draft.month === 1}
|
||||
onClick={() => changeMonth(-1)}
|
||||
>
|
||||
<ChevronLeft />
|
||||
</Button>
|
||||
<span className="text-sm font-semibold tabular-nums text-slate-800">
|
||||
{yearText || "----"}年 {draft.month}月
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="下个月"
|
||||
disabled={draft.year === 9999 && draft.month === 12}
|
||||
onClick={() => changeMonth(1)}
|
||||
>
|
||||
<ChevronRight />
|
||||
</Button>
|
||||
</div>
|
||||
<div
|
||||
className="mt-2 grid grid-cols-7 text-center text-[11px] font-medium text-slate-400"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{WEEKDAYS.map((weekday) => (
|
||||
<span key={weekday} className="py-1">
|
||||
{weekday}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
role="grid"
|
||||
aria-label={`${draft.year}年${draft.month}月`}
|
||||
className="grid grid-cols-7 gap-1"
|
||||
>
|
||||
{Array.from({ length: firstWeekday }, (_, index) => (
|
||||
<span key={`blank-${index}`} />
|
||||
))}
|
||||
{Array.from({ length: dayCount }, (_, index) => {
|
||||
const day = index + 1;
|
||||
const selected = day === draft.day;
|
||||
const isToday = sameDay({ ...draft, day }, today);
|
||||
return (
|
||||
<button
|
||||
key={day}
|
||||
ref={selected ? selectedDayRef : undefined}
|
||||
type="button"
|
||||
role="gridcell"
|
||||
tabIndex={selected ? 0 : -1}
|
||||
aria-selected={selected}
|
||||
aria-label={`${draft.year}年${draft.month}月${day}日`}
|
||||
className={cn(
|
||||
"aspect-square w-full min-w-0 rounded-lg text-xs tabular-nums text-slate-700 transition-[background-color,color,scale] duration-150 [@media(hover:hover)]:hover:bg-blue-50 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-500/40 active:scale-90 motion-reduce:transition-none motion-reduce:active:scale-100",
|
||||
isToday &&
|
||||
!selected &&
|
||||
"font-semibold text-blue-600 ring-1 ring-inset ring-blue-200",
|
||||
selected && "bg-blue-600 font-semibold text-white [@media(hover:hover)]:hover:bg-blue-700"
|
||||
)}
|
||||
onClick={() => updateDraft({ ...draft, day })}
|
||||
onKeyDown={(event) => {
|
||||
const offsets: Record<string, number> = {
|
||||
ArrowLeft: -1,
|
||||
ArrowRight: 1,
|
||||
ArrowUp: -7,
|
||||
ArrowDown: 7
|
||||
};
|
||||
if (event.key in offsets) {
|
||||
event.preventDefault();
|
||||
focusDayAfterNavigation.current = true;
|
||||
updateDraft(moveDay({ ...draft, day }, offsets[event.key]));
|
||||
} else if (event.key === "PageUp" || event.key === "PageDown") {
|
||||
event.preventDefault();
|
||||
focusDayAfterNavigation.current = true;
|
||||
changeMonth(event.key === "PageUp" ? -1 : 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{day}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-3 grid grid-cols-2 gap-2 border-t border-slate-100 pt-3">
|
||||
<FieldSelect
|
||||
label="小时"
|
||||
value={pad(draft.hour)}
|
||||
options={HOUR_OPTIONS}
|
||||
onValueChange={(hour) => {
|
||||
setDraft({ ...draft, hour: Number(hour) });
|
||||
setSourceInvalid(false);
|
||||
}}
|
||||
/>
|
||||
<FieldSelect
|
||||
label="分钟"
|
||||
value={pad(draft.minute)}
|
||||
options={MINUTE_OPTIONS}
|
||||
onValueChange={(minute) => {
|
||||
setDraft({ ...draft, minute: Number(minute) });
|
||||
setSourceInvalid(false);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{sourceInvalid ? (
|
||||
<p role="alert" className="mt-2 text-xs text-amber-700">
|
||||
当前值格式无效,请重新选择日期和时间。
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button type="button" variant="outline" size="sm">
|
||||
取消
|
||||
</Button>
|
||||
</DialogPrimitive.Close>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={!canConfirm}
|
||||
onClick={() => {
|
||||
if (!canConfirm) return;
|
||||
onChange(formatValue({ ...draft, year: Number(yearText) }));
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
确认
|
||||
</Button>
|
||||
</div>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useState, type ComponentProps, type ReactNode } from "react";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { cn } from "./cn";
|
||||
|
||||
export function Disclosure({
|
||||
label,
|
||||
children,
|
||||
className,
|
||||
initiallyOpen = false,
|
||||
onToggle,
|
||||
...props
|
||||
}: Omit<ComponentProps<"details">, "open"> & { label: ReactNode; initiallyOpen?: boolean }) {
|
||||
const [isOpen, setIsOpen] = useState(initiallyOpen);
|
||||
|
||||
return (
|
||||
<details
|
||||
{...props}
|
||||
open={isOpen}
|
||||
onToggle={(event) => {
|
||||
setIsOpen(event.currentTarget.open);
|
||||
onToggle?.(event);
|
||||
}}
|
||||
className={cn("min-w-0", className)}
|
||||
>
|
||||
<summary className="flex min-h-10 cursor-pointer list-none items-center gap-2 rounded-lg py-2 text-xs font-medium leading-5 text-slate-700 transition-[background-color,color] duration-150 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-[var(--action-focus-ring)] [@media(hover:hover)]:hover:text-slate-950 [&::-webkit-details-marker]:hidden">
|
||||
<span className="min-w-0 flex-1 break-words">{label}</span>
|
||||
<ChevronDown
|
||||
aria-hidden
|
||||
data-disclosure-indicator="accordion"
|
||||
className="disclosure-accordion-indicator size-5 shrink-0 rounded-md bg-slate-100 p-1 text-slate-500 transition-transform duration-150 motion-reduce:transition-none"
|
||||
/>
|
||||
</summary>
|
||||
{children}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { FieldSelect } from "@/shared/ui/field-select";
|
||||
import "@/test/radix-select-test-setup";
|
||||
|
||||
const options = [
|
||||
{ value: "normal", label: "正常" },
|
||||
{ value: "long", label: "名称很长但仍应完整换行显示的测点" },
|
||||
{ value: "disabled", label: "不可选", disabled: true }
|
||||
];
|
||||
|
||||
describe("FieldSelect", () => {
|
||||
it("clears a controlled selection back to its placeholder without a change event", () => {
|
||||
const onValueChange = vi.fn();
|
||||
const view = render(
|
||||
<FieldSelect
|
||||
label="运行"
|
||||
value="normal"
|
||||
onValueChange={onValueChange}
|
||||
options={options}
|
||||
placeholder="选择运行"
|
||||
/>
|
||||
);
|
||||
expect(screen.getByRole("combobox")).toHaveTextContent("正常");
|
||||
view.rerender(
|
||||
<FieldSelect
|
||||
label="运行"
|
||||
value=""
|
||||
onValueChange={onValueChange}
|
||||
options={options}
|
||||
placeholder="选择运行"
|
||||
/>
|
||||
);
|
||||
expect(screen.getByRole("combobox")).toHaveTextContent("选择运行");
|
||||
expect(onValueChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves the visible label and does not change value while opening", async () => {
|
||||
const onValueChange = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<FieldSelect label="场景" value="normal" onValueChange={onValueChange} options={options} />
|
||||
);
|
||||
|
||||
const trigger = screen.getByRole("combobox", { name: "场景" });
|
||||
expect(trigger).toHaveTextContent("正常");
|
||||
expect(onValueChange).not.toHaveBeenCalled();
|
||||
|
||||
trigger.focus();
|
||||
await user.keyboard(" ");
|
||||
expect(screen.getByRole("option", { name: options[1].label })).toBeVisible();
|
||||
expect(onValueChange).not.toHaveBeenCalled();
|
||||
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
|
||||
expect(trigger).toHaveFocus();
|
||||
expect(onValueChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("supports keyboard selection and skips empty-valued options", async () => {
|
||||
const onValueChange = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<FieldSelect
|
||||
label="测点"
|
||||
value=""
|
||||
placeholder="选择测点"
|
||||
onValueChange={onValueChange}
|
||||
options={[{ value: "", label: "无效空项" }, ...options]}
|
||||
/>
|
||||
);
|
||||
|
||||
const trigger = screen.getByRole("combobox", { name: "测点" });
|
||||
expect(trigger).toHaveTextContent("选择测点");
|
||||
expect(screen.queryByText("无效空项")).not.toBeInTheDocument();
|
||||
|
||||
trigger.focus();
|
||||
await user.keyboard(" ");
|
||||
await user.keyboard("{ArrowDown}{Enter}");
|
||||
expect(onValueChange).toHaveBeenCalledWith("long");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useId } from "react";
|
||||
|
||||
import { cn } from "@/shared/ui/cn";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/ui/select";
|
||||
|
||||
export interface FieldSelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface FieldSelectProps {
|
||||
label: string;
|
||||
value: string;
|
||||
onValueChange: (value: string) => void;
|
||||
options: FieldSelectOption[];
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
id?: string;
|
||||
}
|
||||
|
||||
export function FieldSelect({
|
||||
label,
|
||||
value,
|
||||
onValueChange,
|
||||
options,
|
||||
placeholder = "请选择",
|
||||
disabled,
|
||||
className,
|
||||
id
|
||||
}: FieldSelectProps) {
|
||||
const generatedId = useId();
|
||||
const triggerId = id ?? `field-select-${generatedId}`;
|
||||
const selectableOptions = options.filter((option) => option.value !== "");
|
||||
|
||||
return (
|
||||
<div className={cn("min-w-0", className)}>
|
||||
<label htmlFor={triggerId} className="mb-1.5 block text-xs font-medium leading-4 text-slate-600">
|
||||
{label}
|
||||
</label>
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={onValueChange}
|
||||
disabled={disabled || selectableOptions.length === 0}
|
||||
>
|
||||
<SelectTrigger
|
||||
id={triggerId}
|
||||
className="h-auto min-h-10 w-full min-w-0 gap-2 rounded-lg border-slate-200 bg-white px-3 text-sm shadow-xs transition-[border-color,box-shadow,background-color] [@media(hover:hover)]:hover:border-slate-300 focus:ring-2 focus:ring-[var(--action-focus-ring)] motion-reduce:transition-none [&>span]:line-clamp-none [&>span]:whitespace-normal [&>span]:break-words [&>span]:text-left [&>svg]:shrink-0"
|
||||
>
|
||||
<SelectValue placeholder={placeholder} />
|
||||
</SelectTrigger>
|
||||
<SelectContent
|
||||
position="popper"
|
||||
sideOffset={4}
|
||||
className="z-[90] max-w-[calc(100vw-1.5rem)]"
|
||||
>
|
||||
{selectableOptions.map((option) => (
|
||||
<SelectItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled={option.disabled}
|
||||
className="whitespace-normal py-2 leading-5 [&>span:last-child]:whitespace-normal [&>span:last-child]:break-words"
|
||||
>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user