文件上传区块是选择文件的地方,也呈现每个文件此后的经历:等待、上传、送达,或者没有送达并说明原因。选择文件的位置是一个文件拖放区;此后每个文件都是一个文件,带有自己的信息和自己的控件。
文件上传
<section class="sheet container-inline flex flex-col gap-lg w-full max-w(640) p-lg" data-example="file-upload" aria-labelledby="upload-title"> <header class="flex flex-col gap-2xs"> <h2 class="heading heading-sm" id="upload-title">Brand assets</h2> <p class="m(0) fg-text-muted">Logos and guidelines for Atlas Labs. Everyone in the workspace can download them.</p> </header> <label class="dropzone"> <input type="file" class="dropzone-input" name="assets" multiple accept="image/png,image/jpeg,application/pdf"> <svg class="icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M9.4989 2.6265A0.625 0.625 0 0 0 9.375 3L9.3758 12.0307A0.625 0.625 0 0 0 10.6182 12.0917L10.625 12L10.623 2.95A0.6252 0.6252 0 0 0 10.5011 2.6265Q10.2855 2.4578 10 2.4578Q9.7145 2.4578 9.4989 2.6265Z" fill="currentColor" stroke="none" fill-rule="evenodd" /> <path d="M6.5 6.5L9.8586 3.1414A0.2 0.2 0 0 1 10.1414 3.1414L13.5 6.5" /> <path d="M3 13.5L3 15.75A1.25 1.25 0 0 0 4.25 17L15.75 17A1.25 1.25 0 0 0 17 15.75L17 13.5" /> </svg> <span class="dropzone-title">Drop files here or choose them</span> <span class="dropzone-description">PNG, JPEG or PDF, up to 10 MB each</span> </label> <div data-upload-refused hidden> <div class="alert alert-warning" role="status"> <svg class="icon alert-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M8.8742 3.8235L13.4246 12.0144A1 1 0 0 1 12.5505 13.5L3.4495 13.5A1 1 0 0 1 2.5754 12.0144L7.1258 3.8235A1 1 0 0 1 8.8742 3.8235Z" /> <path d="M8 6.5L8 9" /> <circle cx="8" cy="11.5" r="0.5" fill="currentColor" stroke="none" /> </svg> <div class="alert-body"> <p class="alert-title" data-upload-refused-title>1 file cannot be uploaded</p> <p class="alert-description">Atlas takes PNG, JPEG and PDF files up to 10 MB. Remove what is marked below and choose it again in one of those formats.</p> </div> </div> </div> <div data-upload-queue hidden> <div class="flex flex-col gap-md"> <ul class="flex flex-col gap-xs m(0) p(0)" aria-label="Files" data-upload-list></ul> <div class="flex flex-wrap items-center justify-between gap-sm"> <p class="m(0) fg-text-muted" data-upload-summary></p> <button type="button" class="btn btn-primary btn-sm" data-upload-start disabled>Start upload</button> </div> </div> </div> <p class="sr-only" role="status" data-upload-status></p> <template data-upload-file> <li class="file"> <progress class="progress file-progress" max="100" value="0" aria-label="Upload"></progress> <span class="file-page" aria-hidden="true"></span> <div class="file-body"> <p class="file-name" tabindex="-1"></p> <p class="file-meta"></p> </div> <div class="file-end"> <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Retry" data-action="retry"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M2.1767 6.5674A5.9666 5.9666 0 0 1 12.3585 3.6514L13.7126 5.0075A0.5 0.5 0 0 1 13.8253 5.2444A0.7044 0.7044 0 0 1 13.2444 5.8253A0.5008 0.5008 0 0 1 12.9797 5.6869L11.6364 4.3432Q10.6813 3.3314 9.3396 2.9629Q7.9979 2.5945 6.66 2.9768Q5.3222 3.359 4.3776 4.3807Q3.4331 5.4023 3.1567 6.766A0.5 0.5 0 0 1 2.1667 6.6649A0.4988 0.4988 0 0 1 2.1767 6.5674Z" fill="currentColor" stroke="none" fill-rule="evenodd" /> <path d="M13.3333 2.3333L13.3333 5.1333A0.2 0.2 0 0 1 13.1333 5.3333L10.3333 5.3333" /> <path d="M2.1747 10.7556A0.5008 0.5008 0 0 0 2.3131 11.0203L3.6415 12.3486A5.9659 5.9659 0 0 0 13.8276 9.4084A0.5 0.5 0 0 0 12.8631 9.1632L12.8433 9.234Q12.5669 10.5977 11.6224 11.6193Q10.6778 12.641 9.34 13.0232Q8.0021 13.4055 6.6604 13.0371Q5.3187 12.6686 4.3636 11.6568L2.9925 10.2874A0.5 0.5 0 0 0 2.7556 10.1747A0.7044 0.7044 0 0 0 2.1747 10.7556Z" fill="currentColor" stroke="none" fill-rule="evenodd" /> <path d="M2.6667 13.6667L2.6667 10.8667A0.2 0.2 0 0 1 2.8667 10.6667L5.6667 10.6667" /> </svg> </button> <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Cancel upload of" data-action="cancel"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M4 4L12 12" /> <path d="M4 12L12 4" /> </svg> </button> <button type="button" class="btn btn-quiet btn-square btn-sm" aria-label="Remove" data-action="remove"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M4 4L12 12" /> <path d="M4 12L12 4" /> </svg> </button> </div> </li> </template></section>/** * Choosing files and following each one through an upload, with nothing uploaded. The dropzone's own input takes * a click and a drop; this module lists what was chosen, checks each file's type and size, and runs a progress * that a timer stands in for: every upload takes the same two seconds, so the example reads the same each time. * It never reads a file's content. A check here is feedback for the reader; the server still decides. * Returns the function that stops the timer and empties the list. */const LIMIT = 10 * 1024 * 1024const TYPES = ['image/png', 'image/jpeg', 'application/pdf']const EXTENSIONS = ['png', 'jpg', 'jpeg', 'pdf']/** What the list opens with: one file of each kind a reader will meet. */const SAMPLES = [ { name: 'atlas-logo.png', bytes: 188416, state: 'queued' }, { name: 'brand-guidelines.pdf', bytes: 2516582, state: 'done' }, { name: 'launch-hero.jpg', bytes: 7130317, state: 'failed' },]/** The buttons a file shows in each state. A refused file can only be removed: the fix is to choose another. */const ACTIONS = { queued: ['remove'], uploading: ['cancel'], done: ['remove'], failed: ['retry', 'remove'], canceled: ['retry', 'remove'], refused: ['remove'],}const NAMES = { retry: 'Retry', cancel: 'Cancel upload of', remove: 'Remove' }const size = (bytes) => bytes < 1024 ? `${bytes} B` : bytes < 1048576 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1048576).toFixed(1)} MB`const extension = (name) => name.includes('.') ? name.split('.').pop().toLowerCase() : ''const files = (count) => `${count} ${count === 1 ? 'file' : 'files'}`/** Why a file cannot be uploaded, or nothing. A browser that reports no type is judged by the name. */function refusal(file) { const known = file.type ? TYPES.includes(file.type) : EXTENSIONS.includes(extension(file.name)) if (!known) return 'Not a PNG, JPEG or PDF' if (file.size > LIMIT) return `${size(file.size)} · Over 10 MB` return ''}export function mount(root) { const controller = new AbortController() const { signal } = controller const doc = root.ownerDocument const input = root.querySelector('.dropzone-input') const refused = root.querySelector('[data-upload-refused]') const refusedTitle = root.querySelector('[data-upload-refused-title]') const queue = root.querySelector('[data-upload-queue]') const list = root.querySelector('[data-upload-list]') const summary = root.querySelector('[data-upload-summary]') const start = root.querySelector('[data-upload-start]') const status = root.querySelector('[data-upload-status]') const template = root.querySelector('[data-upload-file]') /** Every file in the list, in the order it was added. Two files of one name are two entries. */ let items = [] let timer = 0 const count = (state) => items.filter(item => item.state === state).length const say = (message) => { status.textContent = message } const facts = (item) => ({ queued: `${size(item.bytes)} · Ready`, uploading: `${size(item.bytes)} · Uploading ${item.progress}%`, done: `${size(item.bytes)} · Uploaded`, failed: `${size(item.bytes)} · Connection lost`, canceled: `${size(item.bytes)} · Canceled`, refused: item.reason, })[item.state] /** Draws one file from its state: its facts, its bar and its buttons. Focus stays in the row it was in. */ function paint(item) { const held = item.element.contains(doc.activeElement) item.element.classList.toggle('file-failed', item.state === 'failed' || item.state === 'refused') item.meta.textContent = facts(item) if (item.state === 'uploading') { item.bar.value = item.progress if (!item.bar.isConnected) item.element.prepend(item.bar) } else item.bar.remove() const buttons = ACTIONS[item.state].map(action => item.buttons[action]) if (buttons.length !== item.end.children.length || buttons.some((button, index) => button !== item.end.children[index])) item.end.replaceChildren(...buttons) // The button that had focus is gone. Focus stays in the row, on the file's name when what takes the button's // place would remove a file that has just been uploaded: Enter pressed a moment late must not delete it. if (held && !item.element.contains(doc.activeElement)) (item.state === 'done' ? item.label : buttons[0]).focus() } /** Everything that is counted: whether there is a list, what it adds up to, and whether the clock runs. */ function overview() { queue.hidden = !items.length start.disabled = !count('queued') // A file that was refused can never be uploaded, so it is not one of the files the count is out of. summary.textContent = `${count('done')} of ${files(items.length - count('refused'))} uploaded` refused.hidden = !count('refused') refusedTitle.textContent = `${files(count('refused'))} cannot be uploaded` if (count('uploading') && !timer) timer = setInterval(tick, 100) if (!count('uploading') && timer) timer = clearInterval(timer) ?? 0 } function add({ name, bytes, state, reason = '' }) { const element = template.content.firstElementChild.cloneNode(true) const item = { name, bytes, state, reason, progress: 0, element, bar: element.querySelector('.file-progress'), meta: element.querySelector('.file-meta'), label: element.querySelector('.file-name'), end: element.querySelector('.file-end'), buttons: Object.fromEntries([...element.querySelectorAll('[data-action]')].map(button => [button.dataset.action, button])), } // A file's name is the reader's text: it is set as text, never as markup. element.querySelector('.file-name').textContent = name element.querySelector('.file-page').textContent = extension(name).slice(0, 4) || 'file' item.bar.setAttribute('aria-label', `Upload of ${name}`) for (const [action, button] of Object.entries(item.buttons)) button.setAttribute('aria-label', `${NAMES[action]} ${name}`) items.push(item) list.append(element) paint(item) } function upload(item) { item.state = 'uploading' item.progress = 0 paint(item) } /** One step of every upload under way. Each step is the same size, so every run ends at the same moment. */ function tick() { const finished = [] for (const item of items.filter(item => item.state === 'uploading')) { item.progress += 5 if (item.progress >= 100) { item.state = 'done' finished.push(item.name) } paint(item) } // Uploads that started together end together: one message names them all, so none replaces another. if (finished.length) say(finished.length === 1 ? `${finished[0]} uploaded.` : `${files(finished.length)} uploaded: ${finished.join(', ')}.`) overview() } function remove(item) { // Focus goes to the file that takes this one's place, then to the one before, then to where files are chosen. const neighbor = item.element.nextElementSibling ?? item.element.previousElementSibling const held = item.element.contains(doc.activeElement) items = items.filter(other => other !== item) item.element.remove() overview() say(`${item.name} removed.`) if (held) (neighbor?.querySelector('.btn') ?? input).focus() } input.addEventListener('change', () => { const chosen = [...input.files] for (const file of chosen) { const reason = refusal(file) add({ name: file.name, bytes: file.size, state: reason ? 'refused' : 'queued', reason }) } // The input is emptied, so choosing the same file again is a change. input.value = '' overview() const marked = chosen.filter(refusal).length say(`${files(chosen.length)} added${marked ? `, ${marked} cannot be uploaded` : ''}.`) }, { signal }) start.addEventListener('click', () => { const waiting = items.filter(item => item.state === 'queued') waiting.forEach(upload) overview() say(`Uploading ${files(waiting.length)}.`) // The button is disabled now; focus moves to the first upload it started. waiting[0]?.buttons.cancel.focus() }, { signal }) list.addEventListener('click', (event) => { const button = event.target.closest('[data-action]') const item = button && items.find(item => item.element === button.closest('.file')) if (!item) return if (button.dataset.action === 'remove') return remove(item) if (button.dataset.action === 'retry') { upload(item) say(`Uploading ${item.name}.`) } else { item.state = 'canceled' paint(item) say(`Upload of ${item.name} canceled.`) } overview() }, { signal }) SAMPLES.forEach(add) overview() return () => { controller.abort() clearInterval(timer) items = [] list.replaceChildren() queue.hidden = true refused.hidden = true start.disabled = true say('') }}按“Start upload”(开始上传),取消其中一个再重试,移除一个文件,或者选择你自己的文件。不会上传任何内容:进度由计时器模拟,文件内容也从不会被读取。
区块提供可直接复制的标记,沿用页面的文字颜色和字号。预览在 body 上设置 fg-text-body text-sm。每个区块都是尺寸容器,会根据自身宽度重排,无论放在宽页面、侧边栏大小的空间还是对话框中。
#区块组成
- 一块保持阅读宽度的面板,
max-w(640):一个说明这些文件用途的标题、文件拖放区,然后是列表。文件名和它的控件始终在一眼可及的范围内。 - 文件拖放区在选择文件之前就说明限制。 “PNG, JPEG or PDF, up to 10 MB each”(PNG、JPEG 或 PDF,每个不超过 10 MB)是它的
dropzone-description,输入框的accept也把文件选择器限定为同样的类型。事后才告知的限制,已经让用户白试了一次。 - 每个文件是列表项上的一个
file:带扩展名的小页面图标、文件名,以及放在file-meta中的一行信息。这一行用文字写出大小和状态,例如“184 KB · Ready”(就绪),两者都只占一行,因此每种状态都要说得简短。 - 正在上传的文件,其面板会逐渐着色。 一个原生的
<progress class="progress file-progress">铺在文字下方,从起始侧边缘开始填充;百分比同时写在信息行中,因为着色只是对它的图示。 - 失败状态是
file-failed:轮廓和信息行使用危险墨色,信息行说明哪里出了问题。可以重试的失败提供“Retry”(重试);超出限制的文件只提供“Remove”(移除),因为再试一次也无济于事。 - 控件属于文件自身,放在
file-end中:每个操作一个低调的方形按钮,名称中带有文件名,例如“Remove atlas-logo.png”。控件随状态变化:等待时是“Remove”,上传时是“Cancel”(取消),停止后是“Retry”和“Remove”。 - 无法上传的情况在列表上方统一说明一次,使用一个行内提示,写明文件数量和处理办法;每个这样的文件再在各自的行中说明自己的原因。
- 数量和唯一的主按钮为区块收尾:行的起始侧是“1 of 3 files uploaded”(已上传 1 个,共 3 个文件),末尾侧是“Start upload”。没有文件等待上传时,按钮处于禁用状态。
#哪些操作需要脚本
文件拖放区不需要脚本:点击会打开文件选择器,拖到区域上的文件会进入它的输入框。此后的一切都由 main.js 负责。
- 它列出所选的文件。 输入框
files中的每个文件都成为一行,从标记中的<template>克隆而来,文件名作为文本写入。随后清空输入框,这样再次选择同一个文件仍然会触发 change 事件。两个同名文件是两行,各有各的状态。 - 它检查类型和大小,依据文件的 MIME 类型;浏览器没有报告类型时,依据扩展名。未通过检查的文件保留在列表中,加上标记并注明原因。这是给用户的反馈;服务器还会再检查一次。
- 它为每个文件保存一个状态,并据此绘制该行:信息行、进度条和按钮。数量、行内提示以及“Start upload”能否按下,都由同一份列表推导得出。
- 控件消失时,它会移动焦点。 “Remove”之后,焦点移到顶替其位置的文件;没有则移到前一个文件,再没有则移到文件拖放区。“Cancel”变成“Retry”时,焦点留在该行内。
- 它说明发生了什么,通过一行不绘制出来的
role="status"文字:“atlas-logo.png uploaded.”(atlas-logo.png 已上传。)“2 files added, 1 cannot be uploaded.”(已添加 2 个文件,1 个无法上传。)
示例中的上传本身是一个计时器:每个文件都用同样的两秒,也不会随机失败,因此区块每次呈现的过程都相同。在实际应用中,把 upload() 和 tick() 替换为请求,把请求进度写入 item.progress,并用服务器给出的原因设置 failed。mount 返回的函数会停止计时器并清空列表。
#无障碍
- 文件输入框就是控件:它接收焦点,按 Enter 和空格键打开文件选择器,焦点环由拖放区绘制。拖放区的标题和描述是它的标签。
- 列表是一个名为“Files”(文件)的
<ul>。每个按钮的名称都以所属文件的文件名结尾,因此不会出现五个一模一样的“Remove”。 - “Cancel”和“Remove”共用一个叉号,因为两者都是把文件拿开;它们的名称说明是哪一个操作。
- 进度条有名称,例如“Upload of launch-hero.jpg”(launch-hero.jpg 的上传进度),也有数值;同一个数字也写在文字中。
- 失败不只靠颜色表达:信息行指明了失败,行内提示统计了需要处理的文件数量。
- 状态行以 polite 方式播报。它报告文件已送达,不会报告途中的每一个百分比。
- 在减少动态效果的设置下,进度条仍会填充:它表示的是进度量,不是装饰。