Ordo UI
AI审阅与决策

HumanInputRequest

@mox-hub/patterns · AI · 审阅与决策 · canonical

human-input-request@mox-hub/patternsSemanticcanonicalsrc/components/human-input-request.tsx

变体轴

mode
textsinglemulti
变体演示human-input-request

要把这次改动应用到哪个环境?

Props API

Prop类型默认值说明
question*string——
description*string——
mode*HumanInputMode——
options*HumanInputOption[][]—
value*HumanInputValue——
onSubmit*(value: HumanInputValue) => void | Promise<void>——
onSkip*() => void——
busy*booleanfalse—
required*booleanfalse—
placeholder*string——
labels*Partial<HumanInputRequestLabels>——
className*string——

源码

packages/patterns/src/components/human-input-request.tsx
/**
 * HumanInputRequest - [AI] AI 向人澄清的问答件(治理方案 W4 P1 · B9)
 *
 * 与同目录两件的分工:
 * - `approval-card` 是**二值审批**(批准/拒绝已知行动);本件是**开放/枚举澄清**——
 *   AI 在执行前向人补问一个问题,答案可以是自由文本、单选或多选。
 * - `inline-diff` 处理文本变更裁决;本件与 diff 无关,只负责「问 + 收答案」这一小段闭环。
 *
 * - 三种模式:text = ui/input 单行文本;single = ui/radio-group;multi = ui/checkbox-group。
 * - **受控 / 非受控双模**:传 `value` 时由父级数据驱动(prop 变化同步到内部草稿);
 *   不传时完全由内部 state 持有。本件没有 onChange 出口,用户编辑先暂存,
 *   最终答案只在 `onSubmit` 时交还(单次澄清的收口语义)。
 * - **提交门禁**:text 必填时空值禁用;single 未选禁用;multi 必填时至少一项;
 *   `onSubmit` 返回 Promise 时进入 busy 态(提交/跳过/输入全部禁用)。
 * - **a11y**:根 role="group" + aria-labelledby 指向题面;描述、必填提示、无选项提示
 *   都经 aria-describedby 关联;busy 经 aria-busy 播报。
 * - 文案缺省中文常量(§16),消费方经 labels 覆写接入 i18n。不取数、不发请求。
 */
import { useId, useState } from 'react';
import { Checkbox } from '@mox-hub/ui/components/checkbox';
import { CheckboxGroup } from '@mox-hub/ui/components/checkbox-group';
import { Button } from '@mox-hub/ui/components/button';
import { Input } from '@mox-hub/ui/components/input';
import { RadioGroup, RadioGroupItem } from '@mox-hub/ui/components/radio-group';
import { cn } from '@mox-hub/ui';
import { usePatternLabels } from '../lib/i18n';

export type HumanInputMode = 'text' | 'single' | 'multi';

export interface HumanInputOption {
  value: string;
  label: string;
  /** 选项补充说明(可选;与控件经 aria-describedby 关联) */
  description?: string;
  disabled?: boolean;
}

export type HumanInputValue = string | string[];

/** 文案覆写(缺省中文常量,§16;消费方经 labels 覆写接入 i18n) */
export interface HumanInputRequestLabels {
  /** 提交答案 */
  submit: string;
  /** 跳过本题(onSkip 存在时渲染) */
  skip: string;
  /** 必填提示(视觉标签 + aria-describedby 关联) */
  required: string;
  /** text 模式缺省占位文案(placeholder prop 优先) */
  placeholder: string;
  /** single / multi 模式没有可选项时的提示 */
  emptyOptions: string;
}

const DEFAULT_LABELS: HumanInputRequestLabels = {
  submit: '提交',
  skip: '跳过',
  required: '必填',
  placeholder: '输入你的回答',
  emptyOptions: '暂无可选项',
};

/** 按模式把受控值/草稿归一为当前模式可用的形状(类型不匹配时退化为空值) */
function normalizeValue(
  value: HumanInputValue | undefined,
  mode: HumanInputMode,
): HumanInputValue {
  if (mode === 'multi') return Array.isArray(value) ? value : [];
  return typeof value === 'string' ? value : '';
}

/** 受控值变化比较:数组按内容比较,避免父级内联新数组导致草稿被反复重置 */
function isSameValue(
  a: HumanInputValue | undefined,
  b: HumanInputValue | undefined,
): boolean {
  if (Array.isArray(a) && Array.isArray(b)) {
    return a.length === b.length && a.every((item, index) => item === b[index]);
  }
  return a === b;
}

export interface HumanInputRequestProps {
  /** 题面(AI 要澄清的问题) */
  question: string;
  /** 题面补充说明(可选;与题面一并关联到控件) */
  description?: string;
  /** text = 自由文本 / single = 单选 / multi = 多选 */
  mode: HumanInputMode;
  /** single / multi 的候选项(text 模式忽略) */
  options?: HumanInputOption[];
  /** 受控答案:传了即受控(prop 变化同步内部草稿),否则由内部 state 持有 */
  value?: HumanInputValue;
  /** 提交回调;返回 Promise 时进入 busy 态,落定前提交/跳过/输入禁用 */
  onSubmit: (value: HumanInputValue) => void | Promise<void>;
  /** 跳过本题(可选;不传不渲染跳过钮) */
  onSkip?: () => void;
  /** 外部进行中态:禁用提交/跳过/输入并 aria-busy */
  busy?: boolean;
  /** 必填:text 空值禁用提交;multi 至少一项;single 恒需选中 */
  required?: boolean;
  /** text 模式占位文案(覆写 labels.placeholder) */
  placeholder?: string;
  /** 文案覆写(缺省中文常量) */
  labels?: Partial<HumanInputRequestLabels>;
  className?: string;
}

export function HumanInputRequest({
  question,
  description,
  mode,
  options = [],
  value,
  onSubmit,
  onSkip,
  busy = false,
  required = false,
  placeholder,
  labels,
  className,
}: HumanInputRequestProps) {
  const providerLabels = usePatternLabels('humanInputRequest', DEFAULT_LABELS);
  const l: HumanInputRequestLabels = { ...providerLabels, ...labels };
  const baseId = useId();
  const questionId = `${baseId}-question`;
  const descriptionId = `${baseId}-description`;
  const requiredId = `${baseId}-required`;
  const emptyId = `${baseId}-empty`;
  // CheckboxGroup 以 name + value 识别成员;每个实例独立命名,避免多实例互相串值
  const fieldName = `${baseId}-value`;

  // 受控 / 非受控:内部草稿始终存在;value prop 变化时同步(React 认可的渲染期调整模式)。
  // 受控模式下仍允许本地编辑——API 没有 onChange 出口,若严格拒绝本地输入,用户将无法作答;
  // 最终交还以 onSubmit 的草稿为准,父级换 value 时再整体覆盖。
  const [draft, setDraft] = useState<HumanInputValue>(() => normalizeValue(value, mode));
  const [prevValue, setPrevValue] = useState(value);
  if (!isSameValue(prevValue, value)) {
    setPrevValue(value);
    setDraft(normalizeValue(value, mode));
  }

  const [pending, setPending] = useState(false);
  const busyState = busy || pending;

  const textValue = typeof draft === 'string' ? draft : '';
  const multiValue = Array.isArray(draft) ? draft : [];
  const hasOptions = options.length > 0;
  const needsOptions = mode !== 'text';
  const showEmptyOptions = needsOptions && !hasOptions;

  // 描述 + 必填提示 + 无选项提示都经 aria-describedby 关联到控件
  const describedBy =
    [
      description ? descriptionId : null,
      required ? requiredId : null,
      showEmptyOptions ? emptyId : null,
    ]
      .filter(Boolean)
      .join(' ') || undefined;

  const canSubmit = !busyState
    ? mode === 'text'
      ? !required || textValue.trim() !== ''
      : mode === 'single'
        ? hasOptions && textValue !== ''
        : hasOptions && (!required || multiValue.length > 0)
    : false;

  const handleSubmit = () => {
    if (!canSubmit) return;
    const payload: HumanInputValue = mode === 'multi' ? multiValue : textValue;
    const result = onSubmit(payload);
    if (result && typeof (result as Promise<void>).then === 'function') {
      // 落定前禁重复提交;reject 视为未落定,恢复可操作(错误呈现归消费方)
      setPending(true);
      void (result as Promise<void>).then(
        () => setPending(false),
        () => setPending(false),
      );
    }
  };

  const optionDescriptionId = (index: number) =>
    `${baseId}-option-${index}-description`;

  return (
    <div
      data-slot="human-input-request"
      data-ai-component="human-input-request"
      data-mode={mode}
      data-controlled={value !== undefined ? 'true' : 'false'}
      role="group"
      aria-labelledby={questionId}
      aria-describedby={describedBy}
      aria-busy={busyState || undefined}
      className={cn('rounded-lg border bg-card px-4 py-3', className)}
    >
      <div className="flex flex-col gap-1">
        <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
          <p id={questionId} className="text-sm font-medium text-content-text">
            {question}
          </p>
          {required ? (
            <span id={requiredId} className="text-xs font-medium text-accent-red">
              {l.required}
            </span>
          ) : null}
        </div>
        {description ? (
          <p id={descriptionId} className="text-xs leading-normal text-content-text-secondary">
            {description}
          </p>
        ) : null}
      </div>

      <div className="mt-3">
        {mode === 'text' ? (
          <Input
            value={textValue}
            onChange={(event) => setDraft(event.target.value)}
            placeholder={placeholder ?? l.placeholder}
            disabled={busyState}
            required={required}
            aria-labelledby={questionId}
            aria-describedby={describedBy}
          />
        ) : showEmptyOptions ? (
          <p id={emptyId} className="text-xs text-content-text-muted">
            {l.emptyOptions}
          </p>
        ) : mode === 'single' ? (
          <RadioGroup
            value={textValue}
            onValueChange={(next: string) => setDraft(next)}
            disabled={busyState}
            aria-labelledby={questionId}
            aria-describedby={describedBy}
            aria-required={required || undefined}
            className="gap-2"
          >
            {options.map((option, index) => {
              const descriptionIdForOption = option.description
                ? optionDescriptionId(index)
                : undefined;
              return (
                <label
                  key={option.value}
                  className={cn(
                    'flex items-start gap-2 text-sm',
                    option.disabled && 'opacity-50',
                  )}
                >
                  <RadioGroupItem
                    value={option.value}
                    disabled={option.disabled || busyState}
                    aria-label={option.label}
                    aria-describedby={descriptionIdForOption}
                    className="mt-0.5"
                  />
                  <span className="flex min-w-0 flex-col gap-0.5">
                    <span className="text-content-text">{option.label}</span>
                    {option.description ? (
                      <span
                        id={descriptionIdForOption}
                        className="text-xs text-content-text-muted"
                      >
                        {option.description}
                      </span>
                    ) : null}
                  </span>
                </label>
              );
            })}
          </RadioGroup>
        ) : (
          // CheckboxGroup 自身渲染 role="group";名字由外层已标注的 group 提供,
          // 内层不重复 aria-labelledby,避免可访问名重复(嵌套组仍共享题面语境)。
          <CheckboxGroup
            value={multiValue}
            onValueChange={(next: string[]) => setDraft(next)}
            disabled={busyState}
            aria-describedby={describedBy}
            aria-required={required || undefined}
            className="gap-2"
          >
            {options.map((option, index) => {
              const descriptionIdForOption = option.description
                ? optionDescriptionId(index)
                : undefined;
              return (
                <label
                  key={option.value}
                  className={cn(
                    'flex items-start gap-2 text-sm',
                    option.disabled && 'opacity-50',
                  )}
                >
                  <Checkbox
                    name={fieldName}
                    value={option.value}
                    disabled={option.disabled || busyState}
                    aria-label={option.label}
                    aria-describedby={descriptionIdForOption}
                    className="mt-0.5"
                  />
                  <span className="flex min-w-0 flex-col gap-0.5">
                    <span className="text-content-text">{option.label}</span>
                    {option.description ? (
                      <span
                        id={descriptionIdForOption}
                        className="text-xs text-content-text-muted"
                      >
                        {option.description}
                      </span>
                    ) : null}
                  </span>
                </label>
              );
            })}
          </CheckboxGroup>
        )}
      </div>

      <div className="mt-3 flex flex-wrap items-center justify-end gap-2 border-t border-border/60 pt-3">
        {onSkip ? (
          <Button
            type="button"
            variant="ghost"
            size="xs"
            disabled={busyState}
            onClick={onSkip}
            data-ai-action="human-input-request.skip"
          >
            {l.skip}
          </Button>
        ) : null}
        <Button
          type="button"
          size="xs"
          disabled={!canSubmit}
          onClick={handleSubmit}
          data-ai-action="human-input-request.submit"
        >
          {l.submit}
        </Button>
      </div>
    </div>
  );
}

可访问性与 RTL

  • 键盘:交互件保留:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。
  • RTL:间距、对齐与方向性图标使用逻辑属性 (ms-* /text-start /rtl:-scale-x-100);通过 ThemeProvider 或I18nProvider 的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。
  • 文案:优先用组件labels /translate /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

人机澄清请求:text/single/multi 三模式,必填与提交态,onSubmit 返回 Promise 时 busy;区别于审批卡的批准/拒绝。