FileList
Un mondo o un agente può mettere nei suoi dati un report, una tabella di risultati, un'immagine o qualsiasi altro file che la persona deve conservare. FileList elenca questi file con il loro tipo e la loro dimensione e dà a ognuno un link che lo salva sul dispositivo della persona.
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} />;
}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);Un file in world.data è un oggetto { name, type, url } con il nome del file (o null), un tipo MIME come 'text/csv' o 'application/pdf' e il contenuto come data URI in url (I dati del mondo). Il componente raccoglie ogni valore di questa forma (anche dentro gli array) e salta gli altri valori come il numero samples dell'esempio. Un file senza nome viene salvato con il nome della sua chiave nei dati e un'estensione presa dal suo type (plot.svg per un file singolo, plot-1.svg e plot-2.svg in un array). La dimensione si ricava dalla lunghezza del data URI e compare accanto al tipo.
Ogni link porta il nome del file in un attributo download (la webapp permette i download dalle viste). Il nome accessibile di un link è "Download nome del file" (per esempio "Download results.csv").
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo o l'agente restituito da useWorld. |
only | ogni file | Un array di nomi in world.data. La lista contiene solo i file che stanno sotto quei nomi. |
title | 'Files' | L'intestazione della lista. |
Parametri
fileList(container, world, options) disegna la lista dentro container e la disegna di nuovo ogni volta che i file cambiano.
| Parametro | Che cos'è |
|---|---|
container | L'elemento in cui disegnare. |
world | Il mondo o l'agente con cui si risolve connectToHost. |
options.only | Un array di nomi in world.data. La lista contiene solo i file che stanno sotto quei nomi. |
options.title | L'intestazione della lista. Predefinito 'Files'. |
Restituisce una funzione che annulla l'iscrizione al mondo e rimuove la lista.
Modificalo
- Apri un file invece di salvarlo. I browser non aprono un data URI in una nuova scheda. Crea un blob URL con
URL.createObjectURL(await (await fetch(file.url)).blob())e passalo awindow.openper mostrare un'immagine o un PDF in una nuova scheda. - Mostra l'anteprima di un'immagine con un piccolo
imgil cuisrcèfile.urlal posto dell'etichetta dell'estensione quandofile.typecomincia conimage/. - Mostra una tabella nella vista. Per un file CSV o JSON
await (await fetch(file.url)).text()restituisce il contenuto come stringa.
Vedi anche
- Scarica un file dai dati: la stessa idea in poche righe.
DataImage: un'immagine dei dati mostrata nella vista.- I dati del mondo.