Ordo UI
AI助手与对话

AttachmentInput

@mox-hub/patterns · AI · 助手与对话 · canonical

attachment-input@mox-hub/patternsControlscanonicalsrc/components/attachment-input.tsx
变体演示attachment-input
拖到此处上传
  • 设计稿.pdf242 KB已就绪
  • 接口文档.md31.3 KB
    42%

Props API

Prop类型默认值说明
value*AttachmentItem[]——
onFilesChange*(files: File[]) => void——
onRemove*(id: string) => void——
accept*string——
multiple*booleantrue—
maxSize*number——
onReject*(reason: "type" | "size", file: File) => void——
disabled*booleanfalse—
labels*Partial<AttachmentInputLabels>——
className*string——

源码

packages/patterns/src/components/attachment-input.tsx
import {
  useEffect,
  useId,
  useRef,
  useState,
  type DragEvent,
} from 'react';
import { AlertCircle, FileText, Paperclip, X } from 'lucide-react';

import { cn } from '@mox-hub/ui';
import { Button } from '@mox-hub/ui/components/button';
import { RawButton } from '@mox-hub/ui/components/raw/raw-button';
import { Spinner } from '@mox-hub/ui/components/spinner';
import { formatBytes } from '@mox-hub/ui/format';

import { usePatternLabels } from '../lib/i18n';

/**
 * AttachmentInput —— AI 输入区附件选择 / 拖拽件(W4 B1)。
 *
 * 只负责「选择 → 校验 → 去重 → 交给消费方」这一段;文件列表(含上传中/失败/完成
 * 三态)、进度与错误文案都由 `value` 受控注入。
 *
 * **本件不做上传,上传由消费方持有**:组件不取数、不发请求、不弹 toast;
 * 拒收只通过 `onReject` 回调与本地 aria-live 标签提示传达。
 *
 * 交互要点:
 * - 隐藏 file input + 可见 Button(Button 自身可聚焦,键盘可达);
 * - 根容器接 onDragOver / onDragLeave / onDrop,拖入时用语义 token 高亮;
 * - accept 支持扩展名(`.pdf`)、MIME(`application/pdf`)与通配(`image/*`);
 * - 同名 + 同大小 + 同 lastModified 的文件不重复加入;
 * - 未传 `onRemove` 时不渲染移除钮(纯展示用法)。
 */
export interface AttachmentItem {
  id: string;
  name: string;
  size?: number;
  type?: string;
  status?: 'pending' | 'ready' | 'error';
  /** 0-100,pending 时可选 */
  progress?: number;
  error?: string;
}

export interface AttachmentInputLabels {
  attach: string;
  dropHere: string;
  remove: (name: string) => string;
  pending: string;
  error: string;
  ready: string;
  tooLarge: (name: string, max: string) => string;
  wrongType: (name: string) => string;
  empty: string;
}

export const ATTACHMENT_INPUT_DEFAULT_LABELS: AttachmentInputLabels = {
  attach: '添加附件',
  dropHere: '拖到此处上传',
  remove: (name) => `移除附件 ${name}`,
  pending: '上传中',
  error: '上传失败',
  ready: '已就绪',
  tooLarge: (name, max) => `${name} 超过大小上限 ${max}`,
  wrongType: (name) => `${name} 类型不支持`,
  empty: '暂无附件',
};

export interface AttachmentInputProps {
  value: AttachmentItem[];
  onFilesChange: (files: File[]) => void;
  onRemove?: (id: string) => void;
  accept?: string;
  multiple?: boolean;
  /** 单文件大小上限(字节) */
  maxSize?: number;
  onReject?: (reason: 'size' | 'type', file: File) => void;
  disabled?: boolean;
  labels?: Partial<AttachmentInputLabels>;
  className?: string;
}

/** accept 的简单匹配:扩展名 / 精确 MIME / `type/*` 通配(不追求完整 RFC 语法)。 */
function matchesAccept(file: File, accept?: string): boolean {
  const tokens = accept
    ?.split(',')
    .map((token) => token.trim().toLowerCase())
    .filter(Boolean);
  if (!tokens || tokens.length === 0) return true;

  const name = file.name.toLowerCase();
  const mime = (file.type || '').toLowerCase();

  return tokens.some((token) => {
    if (token.startsWith('.')) return name.endsWith(token);
    if (token.endsWith('/*')) return mime.startsWith(token.slice(0, -1));
    if (token.includes('/')) return mime === token;
    return name.endsWith(`.${token}`);
  });
}

function clampProgress(progress: number): number {
  return Math.max(0, Math.min(100, Math.round(progress)));
}

function fileFingerprint(file: File): string {
  return `${file.name}\u0000${file.size}\u0000${file.lastModified}`;
}

export function AttachmentInput({
  value,
  onFilesChange,
  onRemove,
  accept,
  multiple = true,
  maxSize,
  onReject,
  disabled = false,
  labels,
  className,
}: AttachmentInputProps) {
  const D = usePatternLabels(
    'attachmentInput',
    ATTACHMENT_INPUT_DEFAULT_LABELS,
  );
  const text: AttachmentInputLabels = {
    attach: labels?.attach ?? D.attach,
    dropHere: labels?.dropHere ?? D.dropHere,
    remove: labels?.remove ?? D.remove,
    pending: labels?.pending ?? D.pending,
    error: labels?.error ?? D.error,
    ready: labels?.ready ?? D.ready,
    tooLarge: labels?.tooLarge ?? D.tooLarge,
    wrongType: labels?.wrongType ?? D.wrongType,
    empty: labels?.empty ?? D.empty,
  };

  const inputId = useId();
  const inputRef = useRef<HTMLInputElement>(null);
  /** 已加入过的文件指纹;value 清空后复位,便于重新添加同一文件 */
  const seenFilesRef = useRef<Set<string>>(new Set());
  const [dragActive, setDragActive] = useState(false);
  const [rejections, setRejections] = useState<string[]>([]);

  useEffect(() => {
    if (value.length === 0) seenFilesRef.current.clear();
  }, [value.length]);

  const collectFiles = (incoming: File[]) => {
    if (incoming.length === 0) return;

    const existing = new Set(
      value.map((item) => `${item.name}\u0000${item.size ?? -1}`),
    );
    const batch = new Set<string>();
    const messages: string[] = [];
    const accepted: File[] = [];

    for (const file of incoming) {
      if (!matchesAccept(file, accept)) {
        onReject?.('type', file);
        messages.push(text.wrongType(file.name));
        continue;
      }

      if (maxSize !== undefined && file.size > maxSize) {
        onReject?.('size', file);
        messages.push(text.tooLarge(file.name, formatBytes(maxSize)));
        continue;
      }

      const fingerprint = fileFingerprint(file);
      if (
        seenFilesRef.current.has(fingerprint) ||
        batch.has(fingerprint) ||
        existing.has(`${file.name}\u0000${file.size}`)
      ) {
        continue;
      }

      batch.add(fingerprint);
      accepted.push(file);
    }

    const next = multiple ? accepted : accepted.slice(0, 1);
    for (const file of next) {
      seenFilesRef.current.add(fileFingerprint(file));
    }

    // 每次选择/拖入都刷新拒收提示;成功时清掉上一轮提示
    setRejections(messages);
    if (next.length > 0) onFilesChange(next);
  };

  const handleDragOver = (event: DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    if (disabled) return;
    if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
    if (!dragActive) setDragActive(true);
  };

  const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
    if (
      event.relatedTarget &&
      event.currentTarget.contains(event.relatedTarget as Node)
    ) {
      return;
    }
    setDragActive(false);
  };

  const handleDrop = (event: DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    setDragActive(false);
    if (disabled) return;
    const files = event.dataTransfer?.files;
    if (files && files.length > 0) collectFiles(Array.from(files));
  };

  return (
    <div
      role="group"
      aria-label={text.dropHere}
      aria-disabled={disabled || undefined}
      data-ai-component="attachment.input"
      className={cn(
        'flex w-full flex-col gap-2 rounded-lg border border-dashed border-border p-3 transition-colors duration-fast',
        dragActive &&
          !disabled &&
          'border-accent-blue bg-accent-blue-light/40',
        disabled && 'opacity-60',
        className,
      )}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
    >
      <div className="flex min-w-0 flex-wrap items-center gap-2">
        <input
          ref={inputRef}
          id={inputId}
          type="file"
          accept={accept}
          multiple={multiple}
          disabled={disabled}
          aria-hidden="true"
          tabIndex={-1}
          className="sr-only"
          onChange={(event) => {
            const files = event.target.files;
            if (files && files.length > 0) collectFiles(Array.from(files));
            event.target.value = '';
          }}
        />
        <Button
          type="button"
          variant="outline"
          size="sm"
          disabled={disabled}
          aria-label={text.attach}
          onClick={() => inputRef.current?.click()}
        >
          <Paperclip aria-hidden />
          {text.attach}
        </Button>
        <span className="text-2xs text-content-text-muted">
          {text.dropHere}
        </span>
      </div>

      {rejections.length > 0 ? (
        <div role="alert" className="flex flex-col gap-1">
          {rejections.map((message, index) => (
            <span
              key={`${message}-${index}`}
              className="flex items-center gap-1 text-2xs text-accent-red"
            >
              <AlertCircle aria-hidden className="size-3 shrink-0" />
              {message}
            </span>
          ))}
        </div>
      ) : null}

      {value.length > 0 ? (
        <ul className="flex flex-col gap-1.5">
          {value.map((item) => {
            const status = item.status ?? 'ready';
            const progress =
              item.progress === undefined
                ? undefined
                : clampProgress(item.progress);

            return (
              <li
                key={item.id}
                className="flex min-w-0 items-center gap-2 rounded-md border border-content-border bg-background px-2 py-1.5"
              >
                <FileText
                  aria-hidden
                  className="size-4 shrink-0 text-content-text-muted"
                />
                <div className="flex min-w-0 flex-1 flex-col gap-0.5">
                  <div className="flex min-w-0 items-center gap-2">
                    <span
                      className="truncate text-xs text-content-text"
                      title={item.name}
                    >
                      {item.name}
                    </span>
                    {item.size !== undefined ? (
                      <span className="shrink-0 text-2xs tabular-nums text-content-text-muted">
                        {formatBytes(item.size)}
                      </span>
                    ) : null}
                    {status === 'ready' ? (
                      <span className="sr-only">{text.ready}</span>
                    ) : null}
                  </div>

                  {status === 'pending' ? (
                    progress !== undefined ? (
                      <span className="flex items-center gap-1.5">
                        <span
                          role="progressbar"
                          aria-label={text.pending}
                          aria-valuemin={0}
                          aria-valuemax={100}
                          aria-valuenow={progress}
                          className="h-1 min-w-16 flex-1 overflow-hidden rounded-full bg-content-bg-secondary"
                        >
                          <span
                            className="block h-full rounded-full bg-accent-blue transition-[width] duration-normal"
                            style={{ width: `${progress}%` }}
                          />
                        </span>
                        <span className="shrink-0 text-2xs tabular-nums text-content-text-muted">
                          {progress}%
                        </span>
                      </span>
                    ) : (
                      <Spinner
                        size="sm"
                        label={text.pending}
                        className="size-3"
                      />
                    )
                  ) : null}

                  {status === 'error' ? (
                    <span className="flex items-center gap-1 text-2xs text-accent-red">
                      <AlertCircle aria-hidden className="size-3 shrink-0" />
                      <span className="truncate">
                        {item.error ?? text.error}
                      </span>
                    </span>
                  ) : null}
                </div>

                {onRemove ? (
                  <RawButton
                    aria-label={text.remove(item.name)}
                    disabled={disabled}
                    onClick={() => onRemove(item.id)}
                    className="shrink-0 rounded-sm p-1 text-content-text-muted transition-colors duration-fast hover:bg-muted hover:text-content-text focus-visible:ring-2 focus-visible:ring-ring/50"
                  >
                    <X aria-hidden className="size-3" />
                  </RawButton>
                ) : null}
              </li>
            );
          })}
        </ul>
      ) : (
        <p className="text-2xs text-content-text-muted">{text.empty}</p>
      )}
    </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。

用法说明

AI 输入区附件件:拖拽/选择、大小与类型过滤、上传中/失败/完成三态、移除;本件不做上传,File[] 由消费方接管。