world.send(value)
Invia un messaggio al mondo a nome della persona: un testo, un'immagine, un file o una domanda con un modulo.
const result = await world.send('left');Parametri
value: un SendValue, cioè uno di questi:
| Valore | Messaggio |
|---|---|
string | Un testo. |
{ image, text? } | Un'immagine. image è un data URI o un URL (data:image/jpeg;base64,...). |
{ file, text? } | Un file di al massimo 20 MB. file è un File, un Blob o un FileToSend { name, type, url } il cui url è un data URI base64. |
{ text, form } | Una domanda. form è un FormSpec mostrato dopo text. |
Un messaggio porta al massimo un allegato e non può avere insieme image e file.
Valore restituito
Una Promise che si risolve con un SendResult:
| Risultato | Significato |
|---|---|
'sent' | Consegnato. Per un file vuol dire che è arrivato al mondo e non che un agente lo legge (Avvertenze). |
'failed' | Non consegnato. Il messaggio resta in messages con status: 'failed'. retry() lo invia di nuovo. send lo restituisce anche quando value contiene un'immagine insieme a un file o un file che non si riesce a leggere. In questi due casi non viene inviato niente e messages non cambia. |
'not-allowed' | Non è stato inviato niente. canSend è false, value è vuoto o l'agente non è raggiungibile. |
La Promise viene rifiutata con un errore il cui code è 'too-big' (un file oltre i 20 MB), 'not-allowed-verb' (una webapp precedente all'invio dei file) oppure 'failed' (la webapp non è riuscita a eseguire la chiamata). Vedi Risoluzione dei problemi.
Uso
Inviare un testo e vedere ogni risultato
Il mondo finto fa fallire il primo messaggio (failNext: true). Con la casella vuota Send dà 'not-allowed', il primo testo dà 'failed' e quello dopo dà 'sent'.
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world that answers every message. `failNext` makes the first message fail
// to let you see each result of `send`.
const arena = {
name: 'Arena',
failNext: true,
onMessage: (message) => `Got ${message.text}`,
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
const [text, setText] = useState('');
const [result, setResult] = useState('Nothing sent yet.');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// `send` resolves when the message is delivered ('sent'), not delivered ('failed'),
// or not sent at all ('not-allowed', when it is empty or not the person's turn).
const onSend = async () => {
const outcome = await world.send(text);
setResult(`Result: ${outcome}`);
};
return (
<>
<input placeholder="Message" value={text} onChange={(event) => setText(event.target.value)} />
<button onClick={onSend}>Send</button>
<p>{result}</p>
<ul>
{world.messages.map((message) => (
<li key={message.id}>
{message.from}: {message.text}{message.fromMe ? ` (${message.status})` : ''}
</li>
))}
</ul>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that answers every message. `failNext` makes the first message fail
// to let you see each result of `send`.
const arena = {
name: 'Arena',
failNext: true,
onMessage: (message) => `Got ${message.text}`,
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
const input = document.createElement('input');
input.placeholder = 'Message';
const button = document.createElement('button');
button.textContent = 'Send';
const result = document.createElement('p');
result.textContent = 'Nothing sent yet.';
const list = document.createElement('ul');
document.body.append(input, button, result, list);
// `send` resolves when the message is delivered ('sent'), not delivered ('failed'),
// or not sent at all ('not-allowed', when it is empty or not the person's turn).
button.onclick = async () => {
const outcome = await world.send(input.value);
result.textContent = `Result: ${outcome}`;
};
// The messages, with the delivery status of those the person sent.
world.subscribe((node) => {
list.replaceChildren(...node.messages.map((message) => {
const item = document.createElement('li');
const delivery = message.fromMe ? ` (${message.status})` : '';
item.textContent = `${message.from}: ${message.text}${delivery}`;
return item;
}));
});Il messaggio entra subito in messages con status: 'sending' e passa a 'sent' o 'failed' quando la Promise si risolve.
Inviare solo quando la persona può
canSend è true quando le regole del mondo accettano un messaggio dalla persona. Disattiva i tuoi controlli finché vale false:
world.subscribe((node) => {
sendButton.disabled = !node.canSend;
});Inviare un'immagine
Codifica un canvas in JPEG:
const image = canvas.toDataURL('image/jpeg', 0.8);
await world.send({ image, text: 'My drawing' });Inviare un file
{ file, text } invia un file. L'esempio costruisce il file dal testo della casella. Il secondo pulsante invia un file oltre i 20 MB per provocare 'too-big'. Il mondo finto legge il file da message.files e risponde con il suo nome e il suo tipo.
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world that finds the file the person sent in `message.files` and answers with its name and type.
const desk = {
name: 'Desk',
onMessage: (message) => {
const file = message.files?.[0];
return file ? `Got ${file.name} (${file.type})` : 'Send me a file.';
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: desk } });
const [notes, setNotes] = useState('');
const [result, setResult] = useState('Nothing sent yet.');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// Sends a file with words and shows how it ended.
async function sendFile(file, text) {
try {
const outcome = await world.send({ file, text });
setResult(`Result: ${outcome}`);
} catch (sendError) {
// 'too-big' means that the file is over 20 MB and nothing was sent.
setResult(`Error: ${sendError.code}`);
}
}
return (
<>
<textarea placeholder="Notes" value={notes} onChange={(event) => setNotes(event.target.value)} />
{/* The page makes this file. A File from a file field or a drop is sent the same way. */}
<button onClick={() => sendFile(new File([notes], 'notes.txt', { type: 'text/plain' }), 'My notes')}>Send as a file</button>
<button onClick={() => sendFile(new Blob([new Uint8Array(21 * 1024 * 1024)]), 'A big file')}>Send a 21 MB file</button>
<p>{result}</p>
<ul>
{world.messages.map((message) => <MessageLine key={message.id} message={message} />)}
</ul>
</>
);
}
// One message, with the names of its files.
function MessageLine({ message }) {
// Read `files` with a fallback, because an older webapp leaves it out.
const names = (message.files ?? []).map((file) => file.name ?? 'a file');
const attached = names.length > 0 ? ` [${names.join(', ')}]` : '';
return <li>{message.fromMe ? 'You' : message.from}: {message.text ?? ''}{attached}</li>;
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that finds the file the person sent in `message.files` and answers with its name and type.
const desk = {
name: 'Desk',
onMessage: (message) => {
const file = message.files?.[0];
return file ? `Got ${file.name} (${file.type})` : 'Send me a file.';
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: desk } });
const notes = document.createElement('textarea');
notes.placeholder = 'Notes';
const sendButton = document.createElement('button');
sendButton.textContent = 'Send as a file';
const bigButton = document.createElement('button');
bigButton.textContent = 'Send a 21 MB file';
const result = document.createElement('p');
result.textContent = 'Nothing sent yet.';
const list = document.createElement('ul');
document.body.append(notes, sendButton, bigButton, result, list);
// Sends a file with words and shows how it ended.
async function sendFile(file, text) {
try {
const outcome = await world.send({ file, text });
result.textContent = `Result: ${outcome}`;
} catch (error) {
// 'too-big' means that the file is over 20 MB and nothing was sent.
result.textContent = `Error: ${error.code}`;
}
}
// The page makes this file. A File from a file field or a drop is sent the same way.
sendButton.onclick = () => sendFile(new File([notes.value], 'notes.txt', { type: 'text/plain' }), 'My notes');
bigButton.onclick = () => sendFile(new Blob([new Uint8Array(21 * 1024 * 1024)]), 'A big file');
// The messages, with the names of their files.
world.subscribe((node) => {
list.replaceChildren(...node.messages.map((message) => {
// Read `files` with a fallback, because an older webapp leaves it out.
const names = (message.files ?? []).map((file) => file.name ?? 'a file');
const item = document.createElement('li');
item.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
if (names.length > 0) item.textContent += ` [${names.join(', ')}]`;
return item;
}));
});Il messaggio della persona entra subito in messages e contiene il file in files come { name, type, url }.
Inviare un file scelto dalla persona
Passa così com'è il File di un input di tipo file:
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = '.pdf'; // only what the world takes, if you know it
picker.onchange = async () => {
const file = picker.files[0];
if (!file) return;
try {
await world.send({ file, text: file.name });
} catch (error) {
showError(error.code === 'too-big' ? 'Pick a file under 20 MB.' : error.code);
}
picker.value = ''; // so that the same file can be picked again
};Per un file trascinato sulla vista passa allo stesso modo event.dataTransfer.files[0].
Fare una domanda con un modulo
Chi riceve trova un messaggio con form e risponde con answer:
await world.send({
text: 'Where shall we meet?',
form: { fields: [{ name: 'place', type: 'select', options: ['Square', 'Station'] }] },
});Avvertenze
- Un messaggio alla volta.
canSendèfalsementre un messaggio è in corso. Un secondosendprima che il primo si risolva dà'not-allowed'con un mondo e resta in attesa con un agente. Usaawaitsu ogni chiamata o disattiva il controllo finché non si risolve. - La
Promiseaspetta la consegna. Un messaggio la cui consegna non viene confermata entro 20 secondi si risolve con'failed'. - Gli agenti vengono aspettati e i mondi no. Subito dopo l'avvio della vista un agente può essere ancora
'connecting'. In quel casosendlo aspetta fino a 20 secondi e si risolve con'not-allowed'se l'agente non è ancora pronto. Con un mondo che non accetta il messaggiosendsi risolve subito con'not-allowed'. - Il messaggio è della persona. La persona lo vede anche nella vista UNaIVERSE del mondo senza nessun segno della tua vista. Invia solo quello che la persona ha chiesto.
- Le immagini grandi sono lente. Riducile su un canvas prima di inviarle.
- Un modulo non valido arriva come testo. Un
formche non rispettaFormSpecarriva come testo semplice. Chi lo riceve non ha nessun modulo da compilare.
File
'sent'non vuol dire che il file venga letto. Lo leggono solo gli agenti con un input di tipo file ('file'o'all'). Gli altri lo ignorano senza errori e lasciano la persona senza risposta. Un mondo accetta file quando il proprietario dà un input del genere a uno dei suoi agenti. Il pulsante per i file va offerto solo in quei mondi.- Un allegato per messaggio. Un'immagine insieme a un file si risolve con
'failed'e non viene inviato niente. Invia due messaggi. - Un'immagine inviata come
fileè un file. Arriva con il suo nome agli agenti che accettano file e mai a quelli che accettano immagini. Per mostrarla al mondo inviala comeimage. - La dimensione viene controllata per prima. Oltre i 20 MB
sendviene rifiutata con'too-big'prima di leggere qualsiasi cosa e lasciamessagesinvariato. Anche sotto il limite un file grande resta lento da leggere e da trasferire. Su un telefono lo è ancora di più. - Il file resta solo finché la vista è aperta. Dopo un ricaricamento della webapp il messaggio conserva
nameetypedel file mentre il suourldiventanull. retry()invia di nuovo lo stesso file.- Un
FileToSendrichiede un data URI base64 (data:...;base64,...). Con qualsiasi altrourlsi risolve con'failed'.
Risoluzione dei problemi
| Codice | Causa | Soluzione |
|---|---|---|
'too-big' | Il file supera i 20 MB. Non è stato inviato niente. | Chiedi un file più piccolo. Controlla file.size > 20 * 1024 * 1024 prima dell'invio. |
'not-allowed-verb' | La webapp è precedente all'invio dei file. Non sono stati inviati né il file né il testo. | Nascondi il pulsante per i file. Testo e immagini funzionano ancora. |
'failed' | La webapp non è riuscita a eseguire la chiamata (raro). | Mostra un errore e lascia riprovare la persona. |
'failed' e 'not-allowed' sono valori con cui la Promise si risolve e non errori. Anche per un'immagine inviata insieme a un file send si risolve con 'failed' senza errore.
try {
const result = await world.send(text);
if (result === 'failed') showRetry();
if (result === 'not-allowed') showNotYourTurn();
} catch (error) {
if (error.code === 'too-big') showError('The file is over 20 MB.');
else showError(error.code);
}Vedi anche
message.retry(): invia di nuovo un messaggio fallito.message.answer(values): risponde a una domanda.GuiFile: un file in un messaggio.- Messaggi e domande e la ricetta Mostra se un messaggio è stato consegnato.