檔案上傳區塊是選擇檔案的地方,也呈現每個檔案之後的遭遇:等待、上傳中、送達,或者沒有送達並說明原因。選擇檔案的地方是檔案拖放區;之後的每個檔案都是一個檔案,帶有自己的資訊和自己的控制項。
檔案上傳
<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」(3 個檔案中已上傳 1 個)位於列的開頭側,「Start upload」位於結尾側。沒有檔案在等待時,按鈕會停用。
#哪些功能需要腳本
檔案拖放區不需要腳本:點一下會開啟選擇器,拖放到區域上的檔案會進入它的輸入欄位。之後的一切都由 main.js 負責。
- 它列出所選的檔案。 輸入欄位
files中的每個檔案都會成為一列,由標記中的<template>複製而來,檔名以純文字設定。接著清空輸入欄位,因此再次選擇同一個檔案仍然算是一次變更。兩個同名的檔案是兩列,各有自己的狀態。 - 它檢查類型和大小,依據檔案的 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 方式播報。它回報檔案已送達,而不是途中的每一個百分比。
- 在減少動態效果的設定下,進度條仍然會填滿:它呈現的是進度的多寡,不是裝飾。