Skip to content

FileButton ​

FileButton opens the file picker and sends the file the person picks to the world or the agent (a CV for a hiring desk, a photo of a receipt, a table for an agent to read). A status text next to the button shows Sending… during the call and then Sent or the reason why the file was not sent.

jsx
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>
	);
}
js
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.';
});
Live, on a fake world
Open

The component passes the File of the input to world.send({ file, text }) as it is. send also accepts any Blob or a { name, type, url } object whose url is a base64 data URI. Over 20 MB send rejects with the code 'too-big' before sending anything and FileButton reports the error in its status text (Send a file).

On 'sent' the world has received the file. The world passes it on to its agents and only the agents whose code handles files read it. When no agent of your world handles files, leave the button out of your view because nobody would read the file. During development the onMessage of the fake world receives the file in message.files and replies with its name. The message of the person holds the same file in message.files for a MessageList to render.

Send a sample file sends a small file built in the code through the same send. It exists only because the automatic check of this page cannot pick a file in a file input. Leave it out of your view.

FileButton writes one status text for each result and error code of send:

sendStatus text
resolves 'sent'Sent
resolves 'not-allowed' (the rules do not accept a message now)You cannot send now.
resolves 'failed'Not sent. Try again.
rejects with 'too-big' (over 20 MB)This file is over 20 MB: pick a smaller one.
rejects with 'not-allowed-verb' (a webapp that predates file sending)This webapp cannot send files yet.

Any other rejection gets the text of 'failed'. The file input stays hidden and the button that opens it is reachable from the keyboard like any other button. The status text sits in a role="status" region whose changes screen readers announce.

Props ​

PropDefaultWhat it is
world(required)The world or agent returned by useWorld.
textnoneThe text sent with the file (for example 'My CV').
acceptevery typeThe file types the picker offers in the syntax of the accept attribute (for example '.pdf,image/*').
label'Send a file'The label of the button.

Parameters ​

fileButton(container, world, options) renders the button into container. The button is disabled while world.canSend is false and while a file is being sent.

ParameterWhat it is
containerThe element to render into.
worldThe world or agent that connectToHost resolves with.
options.textThe text sent with the file.
options.acceptThe file types the picker offers. Default: every type.
options.labelThe label of the button. Default 'Send a file'.

It returns a function that unsubscribes from the world and removes the button.

Change it ​

  • Accept a dropped file. Call event.preventDefault() on dragover and drop and send event.dataTransfer.files[0] in the drop listener.
  • Warn about the size before sending when file.size > 20 * 1024 * 1024 is true. send checks the size anyway.
  • Send the text of the message box with the file by placing the button next to MessageBox and passing what the person wrote as text.
  • Send a photo separately. send({ image, file }) resolves 'failed' since a message carries one file and no image with it. For a photo see Send a photo from the camera.

See also ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.