Disattiva la casella dei messaggi quando la persona non può inviare
Le regole di un mondo decidono quando la persona può inviare (non durante il turno di un altro, non prima che il gioco cominci) e un agente non accetta messaggi finché non si è connesso. canSend tiene conto di entrambe le condizioni e si aggiorna a ogni cambiamento del mondo. Finché è false, disattiva il pulsante Send e scrivi il motivo in una riga breve. Premi Restart sull'esempio per vedere il pulsante restare disattivato mentre l'agente si connette.
jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake agent to build with. Like a real one, it needs a moment to connect.
const helper = {
name: 'Helper',
onMessage: (message) => `Got it: "${message.text}".`,
};
export default function App() {
// While building: the fake agent. In the webapp: useWorld()
const { world: agent, error } = useWorld({ fake: { agent: helper } });
const [text, setText] = useState('');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!agent) return <p>Connecting…</p>;
function handleSubmit(event) {
event.preventDefault();
if (!agent.canSend || !text.trim()) return;
agent.send(text);
setText('');
}
const last = agent.messages.filter((message) => !message.fromMe).at(-1);
return (
<>
<form onSubmit={handleSubmit}>
{/* The field stays on, because the person can write the next message while they wait. */}
<input value={text} onChange={(event) => setText(event.target.value)} placeholder={`Write to ${agent.name}`} />
{/* canSend is true when the rules of the agent (or of the world) let the person send now. */}
<button disabled={!agent.canSend}>Send</button>
</form>
<p>{agent.canSend ? 'You can send now.' : `Wait: ${agent.name} cannot take a message now.`}</p>
<p>{last ? last.text : 'No answer yet.'}</p>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// A fake agent to build with. Like a real one, it needs a moment to connect.
const helper = {
name: 'Helper',
onMessage: (message) => `Got it: "${message.text}".`,
};
// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: helper } });
const form = document.createElement('form');
const input = document.createElement('input');
input.placeholder = `Write to ${agent.name}`;
const sendButton = document.createElement('button');
sendButton.textContent = 'Send';
form.append(input, sendButton);
const hint = document.createElement('p');
const answer = document.createElement('p');
document.body.append(form, hint, answer);
form.onsubmit = (event) => {
event.preventDefault();
if (!agent.get().canSend || !input.value.trim()) return;
agent.send(input.value);
input.value = '';
};
agent.subscribe((node) => {
// canSend is true when the rules of the agent (or of the world) let the person send now.
// The field stays on, because the person can write the next message while they wait.
sendButton.disabled = !node.canSend;
hint.textContent = node.canSend ? 'You can send now.' : `Wait: ${node.name} cannot take a message now.`;
const last = node.messages.filter((message) => !message.fromMe).at(-1);
answer.textContent = last ? last.text : 'No answer yet.';
});Come funziona
canSendètruequando le regole del mondo (o dell'agente) accettano adesso un messaggio dalla persona. Mentre un messaggio della persona è in corso,canSendè semprefalse.- La vista disattiva solo il pulsante e lascia attivo il campo di testo per due motivi: (1) la persona può scrivere il messaggio successivo mentre aspetta e (2) su un telefono un campo disattivato perde la tastiera.
- Un
sendchiamato lo stesso non fa danni perché si risolve con'not-allowed'senza inviare niente quando il messaggio non è accettato. Con un agente che si sta ancora connettendo aspetta prima la connessione fino a 20 secondi. Il controllo nell'handler del submit evita solo una chiamata inutile.
Vedi anche
- MessageBox: una casella dei messaggi pronta.
send.- Messaggi e domande.