选择、拖放或粘贴文件,校验它们,并随表单一起提交。

文件输入框保存用户选择、拖放或粘贴的文件,按你的规则校验它们,并随表单一起提交。把文件上传到服务器则由你的应用负责。

import "@ui-sdk/web/file-input"
import { createElement, File as FileIcon, Upload, X } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-file-input multiple>
      <ui-file-input-dropzone>
        ${createElement(Upload, { "aria-hidden": "true" }).outerHTML}
        <p>Drag and drop files here</p>
        <p data-slot="hint">Or paste them from your clipboard.</p>
        <ui-file-input-trigger><button>Browse Files</button></ui-file-input-trigger>
      </ui-file-input-dropzone>
      <ui-file-input-list aria-label="Files">
        <template>
          <ui-file-input-item>
            ${createElement(FileIcon, { "aria-hidden": "true" }).outerHTML}
            <span data-file="name"></span>
            <span data-file="size" data-slot="hint"></span>
            <ui-file-input-item-remove><button type="button">${createElement(X, { "aria-hidden": "true" }).outerHTML}</button></ui-file-input-item-remove>
          </ui-file-input-item>
        </template>
      </ui-file-input-list>
    </ui-file-input>
  `
}

export { mount }
按 Browse Files 或把几个文件拖放到区域上,然后移除一个。Tab 到列表,用方向键在文件之间移动,按 Delete 移除获得焦点的文件。

安装

npm install @ui-sdk/web @ui-sdk/core

导入组件来注册它的元素。这个导入在服务器上是安全的。

import "@ui-sdk/web/file-input"

组合

用下面的组合构建 ui-file-input:

ui-file-input
├── ui-file-input-trigger
│   └── button
├── ui-file-input-dropzone
└── ui-file-input-list
    └── template
        └── ui-file-input-item
            └── ui-file-input-item-remove
                └── button

触发器包装一个打开系统文件选择器的原生按钮。拖放区域接收拖放到它上面的文件,或焦点在它内部时粘贴的文件;请为使用键盘的人保留一个放在它旁边的触发器。列表为每个文件复制一次它 <template> 里的条目,条目的 file property 保存它的文件;条目里带有 data-file="name"、"size"、"type" 或 "path" 的元素会显示文件的对应信息。移除按钮包装一个移除它所在条目文件的原生按钮。

用法

导入部件并把它们组合起来:

<script type="module">
  import "@ui-sdk/web/file-input"
</script>

<ui-file-input name="attachments" multiple>
  <ui-file-input-dropzone>
    <p>Drag and drop files here</p>
    <ui-file-input-trigger><button>Browse Files</button></ui-file-input-trigger>
  </ui-file-input-dropzone>
  <ui-file-input-list aria-label="Files">
    <template>
      <ui-file-input-item>
        <span data-file="name"></span>
        <span data-file="size"></span>
        <ui-file-input-item-remove>
          <button type="button"><svg aria-hidden="true">…</svg></button>
        </ui-file-input-item-remove>
      </ui-file-input-item>
    </template>
  </ui-file-input-list>
</ui-file-input>

上传按钮

只需要系统的文件选择器时,一个触发器就够了。从 valuechange 事件里读取选中的文件,在按钮旁边显示它的名称。

<ui-file-input name="resume">
  <ui-file-input-trigger><button>Upload Resume</button></ui-file-input-trigger>
  <span>No file chosen</span>
</ui-file-input>
const input = document.querySelector("ui-file-input")!
input.addEventListener("valuechange", (event) => {
  input.querySelector("span")!.textContent =
    event.detail.value[0]?.name ?? "No file chosen"
})

接受的文件类型

accept 接受 MIME 类型、通配符和扩展名,以逗号分隔,比如 image/*,.pdf。它会检查来自选择器、拖放和粘贴的文件。扩展名按文件名匹配,即使操作系统报告的 MIME 类型不符合预期。

被拒绝的文件不会加入值。reject 事件的 detail.value 里有每个被拒绝的文件及其 reasons,比如 file-type,这样你就能说明它为什么被排除。当文件被拖到拖放区域上方时,data-drag-reject 会表示它们的类型不会被接受。

<ui-file-input multiple accept="image/*,.pdf"></ui-file-input>
input.addEventListener("reject", (event) => setRejected(event.detail.value))

限制

用 max-files 限制总数,用 min-size 或 max-size 限制每个文件的字节数。文件太多时,组件会接受通过其他检查的前几个,直到列表装满,并用 too-many-files 拒绝其余的。

<ui-file-input
  multiple
  max-files="3"
  min-size="1"
  max-size="5000000"
></ui-file-input>

单个文件

没有 multiple 时,新文件会替换当前文件。被拒绝的文件不会改变当前值。有 multiple 时,被接受的文件会加入列表。

<ui-file-input accept=".pdf">
  <ui-file-input-trigger><button>Choose a PDF</button></ui-file-input-trigger>
</ui-file-input>
input.addEventListener("valuechange", (event) => {
  input.querySelector("button")!.textContent = event.detail.value[0]
    ? "Replace PDF"
    : "Choose a PDF"
})

校验

设置 validate property 来做你自己的检查。返回原因字符串来拒绝文件,返回 null 来接受它。它的第二个参数的 accepted 保存同一次拖放中在这个文件之前已被接受的文件,因此重复检查能发现一次拖放里两个同名文件。它在内置的类型和大小检查之后运行,它的原因会和那些原因一样到达 reject 事件。在服务器上也要校验上传。

const input = document.querySelector("ui-file-input")!
input.validate = (file, { accepted }) =>
  [...input.value, ...accepted].some((other) => other.name === file.name)
    ? "duplicate"
    : null
input.addEventListener("reject", (event) => setRejected(event.detail.value))

文件列表

列表只有一个 Tab 停靠点。方向键、Home 和 End 在文件之间移动;Delete 或 Backspace 移除获得焦点的文件。移除按钮以它对应的文件命名,并且不在 Tab 顺序里。

要显示图片预览,在 template 里放一个 <img>,在条目被添加时从条目的 file 创建对象 URL,并在条目消失时撤销它:

<ui-file-input-list aria-label="Images">
  <template>
    <ui-file-input-item>
      <img alt="" />
      <span data-file="name"></span>
      <ui-file-input-item-remove>
        <button type="button"><svg aria-hidden="true">…</svg></button>
      </ui-file-input-item-remove>
    </ui-file-input-item>
  </template>
</ui-file-input-list>
const list = document.querySelector("ui-file-input-list")!
new MutationObserver((records) => {
  for (const { addedNodes, removedNodes } of records) {
    for (const node of addedNodes) {
      const image = (node as Element).querySelector?.("img")
      const file = (node as HTMLElement & { file?: File }).file
      if (image && file && !image.src) image.src = URL.createObjectURL(file)
    }
    for (const node of removedNodes) {
      const image = (node as Element).querySelector?.("img")
      if (image && !node.isConnected) URL.revokeObjectURL(image.src)
    }
  }
}).observe(list, { childList: true })

附件

把文本域放进拖放区域,把文件附加到消息上。paste-target 也会通过 CSS 选择器接收从文本域粘贴的文件;粘贴文字仍然保持正常行为。它也可以是 "document"。在脚本里,把 pasteTarget property 设为元素本身,或设为返回它的函数。

<ui-file-input multiple>
  <ui-file-input-dropzone paste-target="#message">
    <ui-file-input-list aria-label="Attachments">
      <template>
        <ui-file-input-item><span data-file="name"></span></ui-file-input-item>
      </template>
    </ui-file-input-list>
    <textarea id="message" aria-label="Message"></textarea>
    <ui-file-input-trigger>
      <button aria-label="Attach Files"><svg aria-hidden="true">…</svg></button>
    </ui-file-input-trigger>
  </ui-file-input-dropzone>
</ui-file-input>

全页拖放

设置 target="document" 来接收页面上任意位置拖放的文件。当文件拖到窗口内时,区域会显示 data-dragging,所以它可以作为全页浮层。拖放到另一个区域的文件仍归那个区域。

import "@ui-sdk/web/file-input"
import { createElement, File as FileIcon, Upload, X } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-file-input multiple>
      <div data-slot="row">
        <p data-slot="hint">Drop files anywhere.</p>
        <ui-file-input-trigger><button>Upload Files</button></ui-file-input-trigger>
      </div>
      <ui-file-input-dropzone target="document" data-variant="overlay">
        <div data-slot="stack">
          ${createElement(Upload, { "aria-hidden": "true" }).outerHTML}
          <p>Drop to attach</p>
        </div>
      </ui-file-input-dropzone>
      <ui-file-input-list aria-label="Attachments">
        <template>
          <ui-file-input-item>
            ${createElement(FileIcon, { "aria-hidden": "true" }).outerHTML}
            <span data-file="name"></span>
            <span data-file="size" data-slot="hint"></span>
            <ui-file-input-item-remove><button type="button">${createElement(X, { "aria-hidden": "true" }).outerHTML}</button></ui-file-input-item-remove>
          </ui-file-input-item>
        </template>
      </ui-file-input-list>
    </ui-file-input>
  `
}

export { mount }
把文件拖到页面内查看浮层,然后放下它。文件会加入 Attachments 列表;拖放到第一个示例区域上的文件仍留在那里。

拖放区域连接期间,把文件拖放到所有区域之外不会让页面跳转。拖放到原生文件输入框和普通的文字拖放仍保持它们的行为。

文件夹

directory 选择整个文件夹,并打开 multiple。拖放的文件夹会被递归读取,最多 1,000 个文件,跳过 .DS_Store 这类系统文件。data-file="path" 显示文件夹内的路径,与 @ui-sdk/web/file-input 里的 relativePath(file) 相同。

<ui-file-input directory>
  <ui-file-input-trigger
    ><button>Choose a Folder</button></ui-file-input-trigger
  >
  <ui-file-input-list aria-label="Files">
    <template>
      <ui-file-input-item><span data-file="path"></span></ui-file-input-item>
    </template>
  </ui-file-input-list>
</ui-file-input>

相机

用 capture="environment" 请求后置相机,用 "user" 请求前置相机。提供的选择器取决于设备和浏览器;桌面浏览器会打开文件选择器。

<ui-file-input accept="image/*" capture="environment">
  <ui-file-input-trigger><button>Take a Photo</button></ui-file-input-trigger>
</ui-file-input>

受控

设置元素的 value property,并监听 valuechange。event.detail 里有作为 value 的文件、reason,以及 added、removed 和 rejected 文件。调用 event.preventDefault() 保留当前值。即使没有文件被接受,reject 事件也会报告被拒绝的文件。

const input = document.querySelector("ui-file-input")!
input.value = files
input.addEventListener("valuechange", (event) => setFiles(event.detail.value))

从任意位置打开

用 createFileInputController() 创建控制器,并设为元素的 controller property。用它打开选择器、添加或移除文件、清空值,或读取文件。从用户动作里打开选择器,比如按压按钮,这样浏览器才会允许。元素的 api property 有相同的方法。文件输入框之外的 ui-file-input-trigger 通过把 for 设为文件输入框的 id 来连接。

<button type="button" data-action="open">Choose Files</button>
<button type="button" data-action="clear">Clear</button>
<ui-file-input multiple></ui-file-input>
import { createFileInputController } from "@ui-sdk/web/file-input"

const attachments = createFileInputController()
document.querySelector("ui-file-input")!.controller = attachments
document
  .querySelector('[data-action="open"]')!
  .addEventListener("click", () => attachments.open())
document
  .querySelector('[data-action="clear"]')!
  .addEventListener("click", () => attachments.clear())

播报

组件通过礼貌的实时区域(polite live region)播报被接受、被移除和被拒绝的文件。设置 announcement property 来修改消息,或返回 null 跳过它。

input.announcement = ({ added, removed }) =>
  added.length
    ? `Added ${added.map((file) => file.name).join(", ")}.`
    : removed.length
      ? `Removed ${removed.map((file) => file.name).join(", ")}.`
      : null

表单

有了 name,元素在升级后会通过 ElementInternals 提交它的文件。表单重置会回到 defaultValue,这是你在连接元素之前从脚本里设置的 property。form 把文件输入框连接到页面上别处的表单。被拒绝的文件永远不会提交,disabled 既会让值不参与提交,也会阻止选择、拖放和粘贴。

<form method="post" enctype="multipart/form-data">
  <ui-file-input name="attachments" multiple>
    <ui-file-input-trigger><button>Attach Files</button></ui-file-input-trigger>
  </ui-file-input>
  <button type="submit">Send</button>
  <button type="reset">Reset</button>
</form>
input.defaultValue = [coverLetter]

字段

把文件输入框包进 Field,连接它的标签、描述和校验消息。触发器会成为字段的控件,按压标签会打开选择器。required 在没有文件时阻止表单提交。

<ui-field>
  <ui-field-label>Proof of address</ui-field-label>
  <ui-file-input name="proof" required accept="image/*,.pdf">
    <ui-file-input-trigger
      ><button>Choose a File</button></ui-file-input-trigger
    >
  </ui-file-input>
  <ui-field-description
    >A utility bill or bank statement from the last 3
    months.</ui-field-description
  >
  <ui-field-error match="valueMissing">Add a scan to continue.</ui-field-error>
</ui-field>

自定义渲染

部件没有渲染函数:每个元素就是部件,触发器和移除部件包装你自己的按钮。给部件它自己的属性,比如用 role 和 aria-label 代替 <section>,并用它的数据属性显示内容,比如 Tailwind 里的 in-data-drag-reject:inline。列表的 <template> 是每个文件的标记:

<ui-file-input-dropzone role="region" aria-label="Gallery upload">
  <span class="hidden in-data-drag-reject:inline">Images only</span>
  <span class="hidden in-data-drag-accept:inline">Release to add</span>
  <span class="in-data-dragging:hidden">Drag images here</span>
</ui-file-input-dropzone>
<ui-file-input-list aria-label="Images">
  <template>
    <ui-file-input-item><span data-file="name"></span></ui-file-input-item>
  </template>
</ui-file-input-list>

样式

在拖放区域上使用 data-dragging、data-drag-accept 和 data-drag-reject,显示拖放会有什么效果。是否接受拖放取决于浏览器在放下文件之前给出的文件信息。在 Field 内部,触发器还会得到字段的属性,比如 data-invalid。

每个元素都有一个 data-slot,比如 file-input-dropzone,它的状态属性列在数据属性下。

数据属性

<ui-file-input>

[data-slot="file-input"]

属性含义
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-requiredPresent when a file is required.
data-draggingPresent while files are dragged over one of its drop zones.

<ui-file-input-trigger>

[data-slot="file-input-trigger"]

属性含义
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-requiredPresent when a file is required.

<ui-file-input-dropzone>

[data-slot="file-input-dropzone"]

属性含义
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-draggingPresent while files are dragged over the zone, or the window with target="document".
data-drag-acceptPresent while dragged files look acceptable, from their types and count.
data-drag-rejectPresent while a dragged file has a type accept rules out, or there are too many.

<ui-file-input-list>

[data-slot="file-input-list"]

属性含义
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-requiredPresent when a file is required.

<ui-file-input-item>

[data-slot="file-input-item"]

属性含义
data-disabledPresent when disabled, by its own prop or a <fieldset>.

<ui-file-input-item-remove>

[data-slot="file-input-item-remove"]

属性含义
data-disabledPresent when disabled, by its own prop or a <fieldset>.

API 参考

Props 是 kebab 命名的属性,比如 max-size。accept 以逗号分隔,paste-target 是 "document" 或 CSS 选择器。validate、announcement、controller 和 defaultValue 是从脚本设置的 property,value 是文件。onValueChange 是 valuechange 事件:detail.value 保存文件,旁边还有 reason、added、removed 和 rejected。调用 preventDefault() 取消。onReject 是 reject 事件。

FileInput

accept?string | readonly string[]
The files to accept, like the accept attribute: MIME types ("image/png"), wildcards ("image/*") and extensions (".pdf"), in a comma-separated string or an array. Without it, any file.
maxFiles?number
The most files accepted at a time. The first ones that pass the other checks are accepted, and the rest are rejected.
maxSize?number
The largest size accepted, in bytes.
minSize?number
The smallest size accepted, in bytes.
validate?((file: File, batch: { accepted: readonly File[]; }) => string | null | undefined | void)
A check of your own. Return a reason, like "duplicate", to reject the file, or nothing to accept it. accepted holds the files of the same choice, drop or paste accepted before this one.
value?File[]
The files, to control the file input.
defaultValue?File[]
The files at first, when uncontrolled. A form reset returns to them.
valuechange event
Runs when files are added or removed, with what changed in the details. details.cancel() stops it.
reject event
Runs when files fail the checks, after valuechange, with every reason each failed, even when none were accepted.
multiple?boolean
Holds more than one file. New files join the ones it has, up to maxFiles in all. Without it, a new file replaces the one it has.
directory?boolean
Picks a whole folder, with every file inside it. Turns on multiple.
capture?"environment" | "user" | boolean
Opens the camera on phones instead of the files: "user" for the front camera, "environment" for the back one, or true for the default one.
name?string
The name the files submit under. Without one, nothing is submitted.
form?string
The id of a form to belong to, when it isn't inside that form.
required?boolean
Blocks form submission until it holds a file, with the browser's own message.
disabled?boolean
Disables it like a native control: the trigger can't be focused or used, drops and pastes are ignored, and nothing is submitted.
announcement?((change: FileInputChange) => string | null | undefined)
What screen readers hear after a change. Return null for nothing.
controller?object
Adds and removes files from anywhere. Create one with createFileInputController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

FileInputTrigger

controller?object
Connects a trigger outside the file input, like one in a toolbar, to the file input with this controller.

FileInputDropzone

target?FileInputDropzoneTarget
Where it takes drops. "document" takes files dropped anywhere on the page, and the zone shows data-dragging while files are over the window, so it can be a full-page overlay.
pasteTarget?FileInputPasteTarget
Somewhere else to take pasted files from, on top of pastes while focus is inside the zone: "document", an element, a CSS selector, or a function that returns an element, like a prompt's text area. Text pastes are left alone.

FileInputList

为每个文件复制一次它 <template> 里的条目。没有 template 时,每个条目显示文件的名称和一个移除按钮。

FileInputItem

fileFile
The file this item shows. The list passes it to the items it renders.

FileInputItemRemove

包装一个移除它所在条目文件的按钮。它以对应的文件命名,并且不在 Tab 顺序里。

状态

根部件、触发器和列表的状态:

valuereadonly File[]
The files it holds.
disabledboolean
Whether it's disabled, by itself or by a <fieldset>.
requiredboolean
Whether a form won't submit while it holds no files.
draggingboolean
Whether files are being dragged over one of its drop zones.

拖放区域的状态:

draggingboolean
Whether files are being dragged over it, or over the page for a page-wide zone.
dragAcceptboolean
Whether the dragged files look acceptable, from their types and count.
dragRejectboolean
Whether a dragged file has a type accept rules out, or there are too many.
disabledboolean
Whether the file input is disabled, by itself or by a <fieldset>, so drops and pastes are ignored.

条目的状态:

fileFile
The file this item shows: the one its FileInputList renders it for, or its file prop.
indexnumber
Where it is in the value, from 0.
disabledboolean
Whether the file input is disabled, so the item can't be removed.

移除按钮的状态:

disabledboolean
Whether the file input is disabled, so the button can't remove its file.

原因

pickerEvent
Files were chosen in the system's file picker. Its input's change event.
dropDragEvent
Files were dropped on a drop zone, or text and tokens on a token input.
pasteClipboardEvent
Files were pasted, like a screenshot, or text and tokens into a token input.
remove-pressMouseEvent | KeyboardEvent
A chip's remove part was pressed, or Backspace or Delete removed a chip or a span.
resetnone
A form reset.
imperativenone
A controller or api call.

被拒绝的文件会带有一个或多个这样的原因,或来自你的 validate 的原因:file-type、file-too-large、file-too-small 和 too-many-files。

控制器

用 createFileInputController() 创建一个,并设为 controller property。元素的 api property 有相同的方法。

getValue()() => readonly File[]
The files it holds.
setValue(files, options?)(files: readonly File[], options?: FileInputChangeOptions | undefined) => boolean
Replaces the files, without checking them. Returns false when canceled.
addFiles(files, options?)(files: readonly File[] | FileList, options?: FileInputChangeOptions | undefined) => boolean
Runs files through the checks and adds the accepted ones, like a drop. Returns false when disabled or canceled.
removeFile(file, options?)(file: File, options?: FileInputChangeOptions | undefined) => boolean
Removes one file. Returns false when it isn't there, or the change is canceled.
clear(options?)(options?: FileInputChangeOptions | undefined) => boolean
Removes every file.
open()() => boolean
Opens the file picker. Browsers only allow it during a user action, like a click. Returns false when disabled.
focus()() => void
Moves focus to the trigger.
isDragging()() => boolean
Whether files are being dragged over a drop zone.

无障碍

为使用键盘或屏幕阅读器的人保留一个放在拖放区域旁边的触发器。变更会通过礼貌的实时区域播报,文件列表支持键盘导航和移除。

Drops and pastes
  • Dropped files are reported, the rejected ones with every reason.
  • Files over the zone show data-dragging and data-drag-accept until they leave.
  • A type the file input doesn't accept shows data-drag-reject.
  • More files than the file input takes show data-drag-reject.
  • The drag state holds while the drag crosses the zone's children.
  • Text dragged over the zone is ignored.
  • A drag that started in the page is ignored, even with files.
  • The first files up to maxFiles are accepted and the rest rejected.
  • MaxFiles counts the files the file input already holds.
  • Without multiple, the first file is accepted, and a new one replaces it.
  • A disabled file input takes no drops and shows no drag state.
  • Files dropped outside the zone don't open in the browser.
  • Pasting files while focus is inside the zone reports them.
  • Pasting text is left alone.
  • Pasting files into the paste target reports them.
  • A page-wide zone shows while files are over the window.
  • A page-wide zone takes files dropped anywhere.
  • A drop on a zone doesn't reach a page-wide zone.
  • Render functions get the drag state. 仅在 React 和 Vue 运行。
The picker
  • A trigger alone opens the file picker, and the chosen file is reported.
  • Files the accept list rules out are rejected.
  • An unnamed file input empties its input after each choice, so the same file can be chosen again.
  • A folder picker reports every file inside the folder.
  • The input carries accept, capture, multiple and directory.
  • The input stays out of the tab order and the accessibility tree.
  • With multiple, chosen files join the ones dropped before.
Forms
  • A named file input submits the chosen files with its form.
  • Rejected files are never submitted.
  • A named file input with no files submits an empty file, like a native input.
  • Files dropped on the zone go in the form.
  • Canceling a change keeps its files out of the form.
  • A form reset clears the files.
  • A required file input blocks submission and shows the field's error.
  • Files set from script update the field even when the announcement throws. 仅在 Web components 运行。
  • The field's label and the button's text name the trigger, and its description describes it.
  • A press on the field's label opens the picker.
  • A disabled file input disables its trigger.

运行于 React、Vue 和 web components。

  • Each file shows as an item in the list, in order.
  • A remove button is named after its file, and removes it.
  • The list is one tab stop, and arrow keys, Home and End move between items.
  • Backspace on a focused item removes it and focuses the next one.
  • A removal is announced politely.
  • A canceled change leaves the list as it was.
  • A form reset empties the list.
  • A controlled file input shows the value it's given. 仅在 React 和 Vue 运行。
  • A removal a controlled owner ignores keeps the item and its focus. 仅在 React 和 Vue 运行。
  • The value property sets the files quietly on web components, and the api reports. 仅在 Web components 运行。
  • The remove buttons are out of the tab order.

运行于 React、Vue 和 web components。

  • No axe violations at first.
  • No axe violations while dragging.
  • No axe violations with files in the list.
  • No axe violations with the field's error showing.
  • No axe violations when disabled.
  • The zone isn't a control: the trigger inside it is the one tab stop.
  • The accessibility tree is the same everywhere.
  • Accepted and rejected counts are announced politely.
  • A choice from the picker is announced too.

运行于 React、Vue 和 web components。