Skip to content

Mostra i file di un messaggio ​

Un messaggio può portare dei file (un report, una tabella, una registrazione). message.files li elenca come oggetti { name, type, url } (la stessa forma di un file in data) il cui url porta il contenuto del file come data URI. Mostra ogni file come un link che lo salva. I file inviati da un agente non hanno un nome e la tua vista deve dargliene uno. Nell'esempio il commercialista ti invia i tuoi report quando glieli chiedi.

jsx
import { useWorld } from './useWorld.js';

// Two small files: a table and a note.
const table = 'month,paid\nJanuary,1200\nFebruary,950\n';
const note = 'Paid: 3 of 4 invoices.';

// A fake accountant answers with the two files, as base64 data URIs.
// As from a real agent, they arrive with no name.
const accountant = {
	name: 'Accountant',
	onMessage: () => ({
		text: 'Here are your reports.',
		files: [
			{ type: 'text/csv', url: `data:text/csv;base64,${btoa(table)}` },
			{ type: 'text/plain', url: `data:text/plain;base64,${btoa(note)}` },
		],
	}),
};

// On the page, a file shows its name (or words that say it has none) and its type.
function labelOf(file) {
	return `${file.name ?? 'A file with no name'} (${file.type ?? 'unknown type'})`;
}

// Each file of a message becomes a link that saves it, or only its name when its content was not kept.
function FileView({ file }) {
	// Once the view is loaded again, only the name of a file the person sent is kept.
	if (!file.url) return <p>{labelOf(file)}, not kept on this device</p>;
	// `download` saves the file under this name, instead of opening it.
	return <p><a href={file.url} download={file.name ?? 'file'}>{labelOf(file)}</a></p>;
}

export default function App() {
	// While building: the fake agent. In the webapp: useWorld()
	const { world: agent, error } = useWorld({ fake: { agent: accountant } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!agent) return <p>Connecting…</p>;
	return (
		<>
			{agent.messages.map((message) => (
				<div key={message.id}>
					<p>{message.fromMe ? 'You' : message.from}: {message.text}</p>
					{/* An older webapp gives no `files`, and the view then counts on an empty list. */}
					{(message.files ?? []).map((file, index) => <FileView key={index} file={file} />)}
				</div>
			))}
			<button onClick={() => agent.send('My reports, please')} disabled={!agent.canSend}>Ask for the reports</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// Two small files: a table and a note.
const table = 'month,paid\nJanuary,1200\nFebruary,950\n';
const note = 'Paid: 3 of 4 invoices.';

// A fake accountant answers with the two files, as base64 data URIs.
// As from a real agent, they arrive with no name.
const accountant = {
	name: 'Accountant',
	onMessage: () => ({
		text: 'Here are your reports.',
		files: [
			{ type: 'text/csv', url: `data:text/csv;base64,${btoa(table)}` },
			{ type: 'text/plain', url: `data:text/plain;base64,${btoa(note)}` },
		],
	}),
};

// On the page, a file shows its name (or words that say it has none) and its type.
function labelOf(file) {
	return `${file.name ?? 'A file with no name'} (${file.type ?? 'unknown type'})`;
}

// Each file of a message becomes a link that saves it, or only its name when its content was not kept.
function fileView(file) {
	const paragraph = document.createElement('p');
	if (!file.url) {
		// Once the view is loaded again, only the name of a file the person sent is kept.
		paragraph.textContent = `${labelOf(file)}, not kept on this device`;
		return paragraph;
	}
	const link = document.createElement('a');
	link.href = file.url;
	// `download` saves the file under this name, instead of opening it.
	link.download = file.name ?? 'file';
	link.textContent = labelOf(file);
	paragraph.append(link);
	return paragraph;
}

// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: accountant } });

const list = document.createElement('div');
const ask = document.createElement('button');
ask.textContent = 'Ask for the reports';
ask.onclick = () => agent.send('My reports, please');
document.body.append(list, ask);

agent.subscribe((node) => {
	ask.disabled = !node.canSend;
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('div');
		const line = document.createElement('p');
		line.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
		item.append(line);
		// An older webapp gives no `files`, and the view then counts on an empty list.
		for (const file of message.files ?? []) item.append(fileView(file));
		return item;
	}));
});
Live, on a fake world
Open

Come funziona ​

  • Il link <a href={file.url} download={file.name ?? 'file'}> salva il file con quel nome invece di aprirlo e non chiede alcun permesso alla persona (I download).
  • Un agente invia i suoi file con name: null (GuiFile). Per un file del genere labelOf mostra "A file with no name" seguito dal type. Quando sai che cosa invia il mondo, scegli tu un nome migliore ('report.csv' per 'text/csv').
  • Dopo che la vista è stata caricata di nuovo, un file inviato dalla persona conserva solo il suo nome. Il suo url è allora null e l'esempio mostra il nome senza link.
  • I file vengono dalla persona, da un agente o da un membro di un mondo e mai dalle note delle regole di un mondo.
  • Con una webapp più vecchia che non ha il campo files, message.files ?? [] dà una lista vuota.
  • La risposta di un agente finto può portare files: [{ type, url }] con un data URI come nell'esempio. Questi file arrivano senza nome come quelli di un agente vero.

Vedi anche ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.