Skip to content

FileList ​

A world or an agent can put in its data a report, a table of results, a picture or any other file for the person to keep. FileList lists these files with their type and size and gives each one a link that saves it on the device of the person.

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

// The component: copy this part.

/** The ending of a file name for some common types, when the world gives a file no name. */
const ENDINGS = { 'text/plain': '.txt', 'text/csv': '.csv', 'application/json': '.json', 'application/pdf': '.pdf', 'image/png': '.png', 'image/jpeg': '.jpg', 'image/svg+xml': '.svg' };

/** True for a file in the data of the world, `{ name, type, url }`. */
function isFile(value) {
	return Boolean(value) && typeof value === 'object' && typeof value.url === 'string';
}

/**
 * Finds the files in the data of the world, each with a name to save it with.
 * A value can be one file or a list of files.
 * @param {object} data - The data of the world.
 * @param {string[]} [only] - Only these names of the data.
 * @returns {Array<{key: string, fileName: string, file: object}>} The files.
 */
function filesIn(data, only) {
	const files = [];
	for (const [dataName, value] of Object.entries(data)) {
		if (only && !only.includes(dataName)) continue;
		const list = (Array.isArray(value) ? value : [value]).filter(isFile);
		list.forEach((file, index) => {
			const fileName = file.name || `${dataName}${list.length > 1 ? `-${index + 1}` : ''}${ENDINGS[file.type] ?? ''}`;
			files.push({ key: `${dataName}-${index}`, fileName, file });
		});
	}
	return files;
}

/** The size of a file in a data URI, in words ("12 KB"), or null when it cannot be told. */
function sizeOf(url) {
	if (!url.startsWith('data:')) return null;
	const comma = url.indexOf(',');
	const body = url.slice(comma + 1);
	let bytes;
	if (url.slice(0, comma).endsWith(';base64')) bytes = Math.floor((body.length * 3) / 4) - (body.match(/=*$/)[0].length);
	else {
		try {
			bytes = new TextEncoder().encode(decodeURIComponent(body)).length;
		} catch {
			return null;
		}
	}
	if (bytes < 1024) return `${bytes} B`;
	if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
	return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

/**
 * FileList: the files the world shows in its data (a report, a table, a
 * picture), each with its type, its size and a link to save it.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {string[]} [props.only] - Only these names of the data (every file by default).
 * @param {string} [props.title='Files'] - The heading of the list.
 */
export function FileList({ world, only, title = 'Files' }) {
	const files = filesIn(world.data, only);
	return (
		<section aria-label={title} style={{ display: 'grid', gap: 8, maxWidth: 480 }}>
			<h2 style={{ margin: 0, fontSize: 16 }}>{title}</h2>
			{files.length === 0 && <p style={{ margin: 0, opacity: 0.6 }}>No files yet.</p>}
			<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 6 }}>
				{files.map(({ key, fileName, file }) => {
					const ending = fileName.includes('.') ? fileName.split('.').pop().toUpperCase() : 'FILE';
					const size = sizeOf(file.url);
					return (
						<li key={key} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 12px', borderRadius: 12, border: '1px solid rgba(127, 127, 127, 0.3)' }}>
							<span aria-hidden="true" style={{ flex: 'none', width: 40, padding: '6px 0', borderRadius: 6, fontSize: 11, fontWeight: 700, textAlign: 'center', background: 'rgba(42, 84, 196, 0.15)' }}>{ending.slice(0, 4)}</span>
							<span style={{ flex: 1, minWidth: 0 }}>
								<span style={{ display: 'block', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fileName}</span>
								<span style={{ fontSize: 13, opacity: 0.7 }}>{[file.type, size].filter(Boolean).join(' · ')}</span>
							</span>
							{/* `download` saves the file under its name instead of opening it. */}
							<a href={file.url} download={fileName} aria-label={`Download ${fileName}`} style={{ fontWeight: 600 }}>Download</a>
						</li>
					);
				})}
			</ul>
		</section>
	);
}

// Using it, on a fake world.

/** A file as the world gives it: a name, a type, and its content as a data URI. */
function textFile(name, type, text) {
	return { name, type, url: `data:${type};charset=utf-8,${encodeURIComponent(text)}` };
}

// A fake world to build with: two files, a picture with no name, and a number (not a file).
const lab = {
	name: 'Lab',
	data: {
		report: textFile('report.txt', 'text/plain', 'The experiment ran for 3 hours.\nAll samples are fine.\n'),
		results: textFile('results.csv', 'text/csv', 'sample,value\nA,0.42\nB,0.37\nC,0.51\n'),
		plot: { name: null, type: 'image/svg+xml', url: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="60"><polyline points="0,50 30,20 60,35 100,5" fill="none" stroke="#2A54C4" stroke-width="3"/></svg>')}` },
		samples: 3,
	},
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return <FileList world={world} />;
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/** The ending of a file name for some common types, when the world gives a file no name. */
const ENDINGS = { 'text/plain': '.txt', 'text/csv': '.csv', 'application/json': '.json', 'application/pdf': '.pdf', 'image/png': '.png', 'image/jpeg': '.jpg', 'image/svg+xml': '.svg' };

/** True for a file in the data of the world, `{ name, type, url }`. */
function isFile(value) {
	return Boolean(value) && typeof value === 'object' && typeof value.url === 'string';
}

/**
 * Finds the files in the data of the world, each with a name to save it with.
 * A value can be one file or a list of files.
 * @param {object} data - The data of the world.
 * @param {string[]} [only] - Only these names of the data.
 * @returns {Array<{key: string, fileName: string, file: object}>} The files.
 */
function filesIn(data, only) {
	const files = [];
	for (const [dataName, value] of Object.entries(data)) {
		if (only && !only.includes(dataName)) continue;
		const list = (Array.isArray(value) ? value : [value]).filter(isFile);
		list.forEach((file, index) => {
			const fileName = file.name || `${dataName}${list.length > 1 ? `-${index + 1}` : ''}${ENDINGS[file.type] ?? ''}`;
			files.push({ key: `${dataName}-${index}`, fileName, file });
		});
	}
	return files;
}

/** The size of a file in a data URI, in words ("12 KB"), or null when it cannot be told. */
function sizeOf(url) {
	if (!url.startsWith('data:')) return null;
	const comma = url.indexOf(',');
	const body = url.slice(comma + 1);
	let bytes;
	if (url.slice(0, comma).endsWith(';base64')) bytes = Math.floor((body.length * 3) / 4) - (body.match(/=*$/)[0].length);
	else {
		try {
			bytes = new TextEncoder().encode(decodeURIComponent(body)).length;
		} catch {
			return null;
		}
	}
	if (bytes < 1024) return `${bytes} B`;
	if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
	return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

/**
 * Makes the row of one file: its type, name and size, and a link to save it.
 * @param {string} fileName - The name to save it with.
 * @param {{type: string|null, url: string}} file - The file.
 * @returns {HTMLLIElement} The row.
 */
function fileRow(fileName, file) {
	const row = document.createElement('li');
	Object.assign(row.style, { display: 'flex', alignItems: 'center', gap: '12px', padding: '8px 12px', borderRadius: '12px', border: '1px solid rgba(127, 127, 127, 0.3)' });
	const ending = document.createElement('span');
	ending.setAttribute('aria-hidden', 'true');
	ending.textContent = (fileName.includes('.') ? fileName.split('.').pop().toUpperCase() : 'FILE').slice(0, 4);
	Object.assign(ending.style, { flex: 'none', width: '40px', padding: '6px 0', borderRadius: '6px', fontSize: '11px', fontWeight: '700', textAlign: 'center', background: 'rgba(42, 84, 196, 0.15)' });
	const words = document.createElement('span');
	Object.assign(words.style, { flex: '1', minWidth: '0' });
	const name = document.createElement('span');
	name.textContent = fileName;
	Object.assign(name.style, { display: 'block', fontWeight: '600', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' });
	const about = document.createElement('span');
	about.textContent = [file.type, sizeOf(file.url)].filter(Boolean).join(' · ');
	Object.assign(about.style, { fontSize: '13px', opacity: '0.7' });
	words.append(name, about);
	// `download` saves the file under its name instead of opening it.
	const link = document.createElement('a');
	link.href = file.url;
	link.download = fileName;
	link.textContent = 'Download';
	link.setAttribute('aria-label', `Download ${fileName}`);
	link.style.fontWeight = '600';
	row.append(ending, words, link);
	return row;
}

/**
 * Draws into `container` the files that the world shows in its data (a report,
 * a table, a picture), each with its type, its size and a link to save it, and
 * draws them again when they change.
 * @param {HTMLElement} container - Where to draw them.
 * @param {object} world - The world, from connectToHost.
 * @param {{only?: string[], title?: string}} [options] - Only these names of the data (every file by
 *   default), and the heading of the list (default 'Files').
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function fileList(container, world, { only, title = 'Files' } = {}) {
	const section = document.createElement('section');
	section.setAttribute('aria-label', title);
	Object.assign(section.style, { display: 'grid', gap: '8px', maxWidth: '480px' });
	const heading = document.createElement('h2');
	heading.textContent = title;
	Object.assign(heading.style, { margin: '0', fontSize: '16px' });
	const empty = document.createElement('p');
	empty.textContent = 'No files yet.';
	Object.assign(empty.style, { margin: '0', opacity: '0.6' });
	const list = document.createElement('ul');
	Object.assign(list.style, { listStyle: 'none', margin: '0', padding: '0', display: 'grid', gap: '6px' });
	section.append(heading, empty, list);
	container.append(section);

	// The files drawn now. The list is made again only when they change.
	let drawn = '';
	const stop = world.subscribe((node) => {
		const files = filesIn(node.data, only);
		const shown = JSON.stringify(files.map(({ fileName, file }) => [fileName, file.url.length, file.url.slice(-32)]));
		if (shown === drawn) return;
		drawn = shown;
		empty.style.display = files.length === 0 ? 'block' : 'none';
		list.replaceChildren(...files.map(({ fileName, file }) => fileRow(fileName, file)));
	});

	return () => {
		stop();
		section.remove();
	};
}

// Using it, on a fake world.

/** A file as the world gives it: a name, a type, and its content as a data URI. */
function textFile(name, type, text) {
	return { name, type, url: `data:${type};charset=utf-8,${encodeURIComponent(text)}` };
}

// A fake world to build with: two files, a picture with no name, and a number (not a file).
const lab = {
	name: 'Lab',
	data: {
		report: textFile('report.txt', 'text/plain', 'The experiment ran for 3 hours.\nAll samples are fine.\n'),
		results: textFile('results.csv', 'text/csv', 'sample,value\nA,0.42\nB,0.37\nC,0.51\n'),
		plot: { name: null, type: 'image/svg+xml', url: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="60"><polyline points="0,50 30,20 60,35 100,5" fill="none" stroke="#2A54C4" stroke-width="3"/></svg>')}` },
		samples: 3,
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: lab } });
const place = document.createElement('div');
document.body.append(place);
fileList(place, world);
Live, on a fake world
Open

A file in world.data is a { name, type, url } object with the file name (or null), a MIME type such as 'text/csv' or 'application/pdf' and the content as a data URI in url (The data of the world). The component collects every value of that shape (also inside arrays) and skips the other values such as the number samples of the example. A file without a name is saved under the name of its data key with an extension taken from its type (plot.svg for a single file, plot-1.svg and plot-2.svg in an array). The size comes from the length of the data URI and appears next to the type.

Each link carries the file name in a download attribute (the webapp allows downloads from views). The accessible name of a link is "Download file name" (for example "Download results.csv").

Props ​

PropDefaultWhat it is
world(required)The world or agent returned by useWorld.
onlyevery fileAn array of names in world.data. Only the files under those names are listed.
title'Files'The heading of the list.

Parameters ​

fileList(container, world, options) renders the list into container and renders it again whenever the files change.

ParameterWhat it is
containerThe element to render into.
worldThe world or agent that connectToHost resolves with.
options.onlyAn array of names in world.data. Only the files under those names are listed.
options.titleThe heading of the list. Default 'Files'.

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

Change it ​

  • Open a file instead of saving it. Browsers do not open a data URI in a new tab. Create a blob URL with URL.createObjectURL(await (await fetch(file.url)).blob()) and pass it to window.open to show a picture or a PDF in a new tab.
  • Preview a picture with a small img whose src is file.url in place of the extension badge when file.type starts with image/.
  • Render a table in the view. For a CSV or JSON file await (await fetch(file.url)).text() returns the content as a string.

See also ​

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