ファイルアップロードブロックは、ファイルを選ぶ場所であり、その後それぞれのファイルに何が起きるかを示す場所でもあります。ファイルは待機し、アップロードされ、届きます。届かなければ、その理由を伝えます。選ぶ場所はドロップゾーンです。その後の各ファイルは、それぞれの情報と操作を持つファイルです。
ファイルアップロード
<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」(アップロードを開始)を押す、1 件をキャンセルして再試行する、ファイルを削除する、手元のファイルを選ぶ、といった操作を試せます。実際には何もアップロードされません。進捗はタイマーで、ファイルの内容が読み取られることはありません。
ブロックはコピーして使えるマークアップです。文字色と文字サイズはページから引き継ぎます。プレビューでは body に fg-text-body text-sm を設定しています。各ブロックはサイズコンテナーで、広いページでも、サイドバーほどの幅でも、ダイアログ内でも、自身の幅に応じて配置が変わります。
#構成
- 読みやすい幅にした 1 枚のシート。
max-w(640)にします。ファイルの用途を伝えるタイトル、ドロップゾーン、その後にリストを置きます。ファイルの名前とその操作は、ひと目で見渡せる範囲に収まります。 - ドロップゾーンは、ファイルを選ぶ前に制限を伝えます。 「PNG, JPEG or PDF, up to 10 MB each」(PNG、JPEG または PDF、各 10 MB まで)がその
dropzone-descriptionで、入力のacceptがファイル選択ダイアログを同じ種類に絞り込みます。後になって初めて知らされる制限は、すでに 1 回分の試行を無駄にさせています。 - 各ファイルは、リスト項目に付けた
fileです。 拡張子の入った小さなページの絵、名前、file-metaに入れた 1 行の情報で構成します。その行はサイズと状態を言葉で示す「184 KB · Ready」(184 KB · 準備完了)で、どちらも 1 行に収めるため、各状態は短く表現します。 - アップロード中は、面に色が付いていきます。 ネイティブの
<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>を複製した 1 行になり、名前はテキストとして設定されます。その後、入力を空にするため、同じファイルをもう一度選んでも変更として扱われます。同じ名前のファイルが 2 つあれば 2 行になり、それぞれが自身の状態を持ちます。 - 種類とサイズを確認します。 ファイルの MIME タイプで判定し、ブラウザーが種類を報告しない場合は拡張子で判定します。確認に通らなかったファイルはリストに残し、印を付けて、その理由を示します。これは読み手へのフィードバックです。サーバーは改めて確認します。
- ファイルごとに 1 つの状態を保ち、そこから行を描画します。情報の行、バー、ボタンです。件数、アラート、「Start upload」を押せるかどうかは、すべて同じリストから導きます。
- 操作がなくなるときは、フォーカスを移します。 「Remove」の後、フォーカスはその位置に繰り上がったファイルへ移ります。それがなければ 1 つ前のファイルへ、それもなければドロップゾーンへ移ります。「Cancel」が「Retry」に変わるとき、フォーカスはその行にとどまります。
- 何が起きたかを伝えます。 描画されない 1 行の
role="status"で、「atlas-logo.png uploaded.」や「2 files added, 1 cannot be uploaded.」のように伝えます。
例では、アップロードそのものはタイマーです。どのファイルにも同じ 2 秒がかかり、偶然に失敗することはないため、ブロックは毎回同じように動きます。アプリケーションでは、upload() と tick() を実際のリクエストに置き換え、その進捗を item.progress に書き込み、サーバーが返した理由とともに failed を設定します。mount が返す関数は、タイマーを止めてリストを空にします。
#アクセシビリティ
- ファイル入力がコントロールです。フォーカスを受け取り、Enter キーと Space キーでファイル選択ダイアログが開き、ゾーンがフォーカスリングを描きます。ゾーンのタイトルと説明が、入力のラベルになります。
- リストは「Files」という名前の
<ul>です。各ボタンの名前はそのファイルの名前で終わるため、「Remove」が 5 つのうちのどれか分からなくなることはありません。 - 「Cancel」と「Remove」は、どちらもファイルを取り除く操作なので、同じバツ印を使います。どちらなのかは名前が伝えます。
- 進捗バーには「Upload of launch-hero.jpg」という名前と値があります。同じ数値はテキストにも書かれています。
- 失敗を色だけで伝えることはしません。情報の行が失敗を言葉で示し、アラートが対処の必要な件数を数えます。
- ステータス行は polite です。ファイルが届いたことを知らせ、途中の 1 パーセントごとの変化は知らせません。
- 動きを抑える設定でも、バーは満ちていきます。これは量を表すもので、装飾ではないからです。