Skip to content

World's first open-source enterprise world model.

Associate visible field labels with their text controls (#1156)

Rudy Mizrahi Celekli40983e08a310
diff --git a/web/src/fieldLabels.test.ts b/web/src/fieldLabels.test.ts
new file mode 100644
index 00000000..86f75770
--- /dev/null
+++ b/web/src/fieldLabels.test.ts
@@ -0,0 +1,22 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+import { Field, Input, Textarea } from "./ui";
+
+describe("field labels", () => {
+ it.each([createElement(Input), createElement(Textarea)])("associates a label with its text control", (control) => {
+ const html = renderToStaticMarkup(createElement(Field, {
+ label: "Name", children: control,
+ }));
+ const labelId = /<label[^>]*for="([^"]+)"/.exec(html)?.[1];
+ expect(labelId).toBeTruthy();
+ expect(html).toContain(`id="${labelId}"`);
+ });
+ it("retains an existing control id", () => {
+ const html = renderToStaticMarkup(createElement(Field, {
+ label: "Name", children: createElement(Input, { id: "existing-name" }),
+ }));
+ expect(html).toContain('for="existing-name"');
+ expect(html).toContain('id="existing-name"');
+ });
+});
diff --git a/web/src/ui/field.tsx b/web/src/ui/field.tsx
index f464ab59..fa8f2976 100644
--- a/web/src/ui/field.tsx
+++ b/web/src/ui/field.tsx
@@ -1,7 +1,7 @@
/* 表单项:标签 + 控件 + 一句提示或一句错误。间距在这里定一次,
页面里不再有 mb-3 / mt-1 各写各的。 */
-import type { ReactNode } from "react";
-import { cn } from "./index";
+import { cloneElement, isValidElement, useId, type ReactNode } from "react";
+import { cn, Input, Textarea } from "./index";
export function Field({
label,
@@ -20,12 +20,18 @@ export function Field({
className?: string;
children: ReactNode;
}) {
+ const generatedId = useId();
+ const textControl = isValidElement<{ id?: string }>(children) &&
+ (children.type === Input || children.type === Textarea || children.type === "input" || children.type === "textarea");
+ // Most callers omit htmlFor; keep the visible label usable for their text control.
+ const controlId = textControl ? children.props.id ?? htmlFor ?? generatedId : undefined;
+ const control = textControl && !children.props.id ? cloneElement(children, { id: controlId }) : children;
return (
<div className={cn("mb-4", className)}>
- <label htmlFor={htmlFor} className="mb-1 block text-small font-medium text-ink-2">
+ <label htmlFor={htmlFor ?? controlId} className="mb-1 block text-small font-medium text-ink-2">
{label}
</label>
- {children}
+ {control}
{(error || hint) && (
<p className={cn("mt-1 text-fine", error ? "text-danger" : "text-ink-2")}>
{error ?? hint}