FileButton
FileButton apre la finestra di scelta dei file e invia al mondo o all'agente il file scelto dalla persona (un CV per un ufficio che assume, la foto di uno scontrino, una tabella da far leggere a un agente). Un testo di stato accanto al pulsante mostra Sending… durante la chiamata e poi Sent o il motivo per cui il file non è stato inviato.
import { useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
/** What the person reads after a send, for each result of `send` and each error code. */
const WORDS = {
sent: 'Sent',
failed: 'Not sent. Try again.',
'not-allowed': 'You cannot send now.',
'too-big': 'This file is over 20 MB: pick a smaller one.',
'not-allowed-verb': 'This webapp cannot send files yet.',
};
/**
* FileButton: a button that lets the person pick a file and sends it to the
* world (or the agent), then says how it went: "Sending…", "Sent", or why not.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {string} [props.text] - Words sent with the file, for example 'My CV'.
* @param {string} [props.accept] - The kinds of file to offer, for example '.pdf,image/*' (every kind by default).
* @param {string} [props.label='Send a file'] - The words on the button.
*/
export function FileButton({ world, text, accept, label = 'Send a file' }) {
const inputRef = useRef(null);
const [status, setStatus] = useState('');
/** Sends the file the person picked. */
const onPick = async (event) => {
const file = event.target.files[0];
// Empty the field to let the person pick the same file again.
event.target.value = '';
if (!file) return;
setStatus('Sending…');
try {
// `send` takes the File as it is. Over 20 MB, it fails with the code 'too-big' before anything leaves.
const result = await world.send({ file, text });
setStatus(WORDS[result]);
} catch (error) {
setStatus(WORDS[error.code] ?? WORDS.failed);
}
};
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
{/* The file field stays hidden, because the button opens it. */}
<input ref={inputRef} type="file" accept={accept} onChange={onPick} hidden />
<button type="button" disabled={!world.canSend || status === 'Sending…'} onClick={() => inputRef.current.click()}>{label}</button>
{/* A status region, which screen readers say when it changes. */}
<span role="status" style={{ fontSize: 14 }}>{status}</span>
</div>
);
}
// Using it, on a fake world.
/** A small text file as `{ name, type, url }`, with a base64 data URI. `send` takes this shape too. */
const SAMPLE_FILE = { name: 'notes.txt', type: 'text/plain', url: 'data:text/plain;base64,TXkgbm90ZXMgZm9yIHRoZSBpbnRlcnZpZXcuCg==' };
// A fake world to build with: the person's file reaches it as `message.files`.
const hiringDesk = {
name: 'Hiring desk',
onMessage: (message) => {
const file = message.files?.[0];
return file ? `Thanks, I got ${file.name} (${file.type}).` : 'Please send your CV.';
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: hiringDesk } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// The newest answer of the world.
const answer = world.messages.filter((message) => !message.fromMe).at(-1);
return (
<div style={{ display: 'grid', gap: 12, maxWidth: 480 }}>
<FileButton world={world} text="My CV" accept=".pdf,.txt,image/*" />
{/* A test with no file to pick: the same send, with a file written in the code. */}
<button type="button" disabled={!world.canSend} onClick={() => world.send({ file: SAMPLE_FILE, text: 'My notes' }).catch(() => {})} style={{ justifySelf: 'start' }}>
Send a sample file
</button>
<p style={{ margin: 0 }}>{answer ? `${world.name}: ${answer.text}` : 'No answer yet.'}</p>
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/** What the person reads after a send, for each result of `send` and each error code. */
const WORDS = {
sent: 'Sent',
failed: 'Not sent. Try again.',
'not-allowed': 'You cannot send now.',
'too-big': 'This file is over 20 MB: pick a smaller one.',
'not-allowed-verb': 'This webapp cannot send files yet.',
};
/**
* Draws a button into `container` that lets the person pick a file and sends
* it to the world (or the agent), then says how it went: "Sending…", "Sent",
* or why not. The button waits while the person cannot send.
* @param {HTMLElement} container - Where to draw it.
* @param {object} world - The world, from connectToHost.
* @param {{text?: string, accept?: string, label?: string}} [options] - Words sent with the file (for example 'My CV'),
* the kinds of file to offer (for example '.pdf,image/*'), and the words on the button.
* @returns {() => void} Stops following the world and removes what it drew.
*/
export function fileButton(container, world, { text, accept, label = 'Send a file' } = {}) {
const box = document.createElement('div');
Object.assign(box.style, { display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' });
// The file field stays hidden, because the button opens it.
const input = document.createElement('input');
input.type = 'file';
input.hidden = true;
if (accept) input.accept = accept;
const button = document.createElement('button');
button.type = 'button';
button.textContent = label;
// A status region, which screen readers say when it changes.
const status = document.createElement('span');
status.setAttribute('role', 'status');
status.style.fontSize = '14px';
box.append(input, button, status);
container.append(box);
let isSending = false;
const update = () => {
button.disabled = !world.get().canSend || isSending;
};
button.onclick = () => input.click();
// Sends the file the person picked.
input.onchange = async () => {
const file = input.files[0];
// Empty the field to let the person pick the same file again.
input.value = '';
if (!file) return;
isSending = true;
update();
status.textContent = 'Sending…';
try {
// `send` takes the File as it is. Over 20 MB, it fails with the code 'too-big' before anything leaves.
const result = await world.send({ file, text });
status.textContent = WORDS[result];
} catch (error) {
status.textContent = WORDS[error.code] ?? WORDS.failed;
}
isSending = false;
update();
};
const stop = world.subscribe(update);
return () => {
stop();
box.remove();
};
}
// Using it, on a fake world.
/** A small text file as `{ name, type, url }`, with a base64 data URI. `send` takes this shape too. */
const SAMPLE_FILE = { name: 'notes.txt', type: 'text/plain', url: 'data:text/plain;base64,TXkgbm90ZXMgZm9yIHRoZSBpbnRlcnZpZXcuCg==' };
// A fake world to build with: the person's file reaches it as `message.files`.
const hiringDesk = {
name: 'Hiring desk',
onMessage: (message) => {
const file = message.files?.[0];
return file ? `Thanks, I got ${file.name} (${file.type}).` : 'Please send your CV.';
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: hiringDesk } });
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', maxWidth: '480px' });
const place = document.createElement('div');
// A test with no file to pick: the same send, with a file written in the code.
const sample = document.createElement('button');
sample.textContent = 'Send a sample file';
sample.style.justifySelf = 'start';
sample.onclick = () => world.send({ file: SAMPLE_FILE, text: 'My notes' }).catch(() => {});
const answer = document.createElement('p');
answer.style.margin = '0';
page.append(place, sample, answer);
document.body.append(page);
fileButton(place, world, { text: 'My CV', accept: '.pdf,.txt,image/*' });
// The newest answer of the world.
world.subscribe((node) => {
sample.disabled = !node.canSend;
const newest = node.messages.filter((message) => !message.fromMe).at(-1);
answer.textContent = newest ? `${node.name}: ${newest.text}` : 'No answer yet.';
});Il componente passa così com'è il File dell'input a world.send({ file, text }). send accetta anche un Blob qualsiasi o un oggetto { name, type, url } il cui url è un data URI base64. Oltre i 20 MB send viene rifiutata con il codice 'too-big' prima di inviare qualsiasi cosa e FileButton segnala l'errore nel suo testo di stato (Inviare un file).
Con 'sent' il mondo ha ricevuto il file. Il mondo lo passa ai suoi agenti e lo leggono solo gli agenti il cui codice gestisce i file. Quando nessun agente del tuo mondo gestisce i file, non mettere il pulsante nella tua vista perché nessuno leggerebbe il file. Durante lo sviluppo l'onMessage del mondo finto riceve il file in message.files e risponde con il suo nome. Il messaggio della persona contiene lo stesso file in message.files in modo che una MessageList lo mostri.
Send a sample file invia con la stessa send un piccolo file costruito nel codice. Esiste solo perché il controllo automatico di questa pagina non può scegliere un file in un input di tipo file. Non metterlo nella tua vista.
FileButton scrive un testo di stato per ogni risultato e per ogni codice di errore di send:
send | Testo di stato |
|---|---|
si risolve con 'sent' | Sent |
si risolve con 'not-allowed' (le regole ora non accettano un messaggio) | You cannot send now. |
si risolve con 'failed' | Not sent. Try again. |
viene rifiutata con 'too-big' (oltre 20 MB) | This file is over 20 MB: pick a smaller one. |
viene rifiutata con 'not-allowed-verb' (una webapp precedente all'invio dei file) | This webapp cannot send files yet. |
Qualsiasi altro rifiuto prende il testo di 'failed'. L'input di tipo file resta nascosto e il pulsante che lo apre si raggiunge dalla tastiera come qualsiasi altro pulsante. Il testo di stato sta in una regione role="status" i cui cambiamenti vengono annunciati dagli screen reader.
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo o l'agente restituito da useWorld. |
text | nessuno | Il testo inviato con il file (per esempio 'My CV'). |
accept | ogni tipo | I tipi di file offerti dalla finestra di scelta nella sintassi dell'attributo accept (per esempio '.pdf,image/*'). |
label | 'Send a file' | L'etichetta del pulsante. |
Parametri
fileButton(container, world, options) disegna il pulsante dentro container. Il pulsante è disattivato mentre world.canSend è false e mentre un file è in invio.
| Parametro | Che cos'è |
|---|---|
container | L'elemento in cui disegnare. |
world | Il mondo o l'agente con cui si risolve connectToHost. |
options.text | Il testo inviato con il file. |
options.accept | I tipi di file offerti dalla finestra di scelta. Predefinito ogni tipo. |
options.label | L'etichetta del pulsante. Predefinito 'Send a file'. |
Restituisce una funzione che annulla l'iscrizione al mondo e rimuove il pulsante.
Modificalo
- Accetta un file trascinato. Chiama
event.preventDefault()sudragovere sudrope inviaevent.dataTransfer.files[0]nel listener didrop. - Avvisa sulla dimensione prima dell'invio quando
file.size > 20 * 1024 * 1024è vero.sendcontrolla comunque la dimensione. - Invia con il file il testo della casella dei messaggi mettendo il pulsante accanto a
MessageBoxe passando cometextquello che la persona ha scritto. - Invia una foto a parte.
send({ image, file })si risolve con'failed'perché un messaggio porta un solo file e nessuna immagine insieme. Per una foto vedi Invia una foto dalla fotocamera.
Vedi anche
- Invia un file: la stessa idea in poche righe.
world.send: tutti i valori che accetta e i suoi errori.- Mostra i file di un messaggio: i file che arrivano.