Carica i messaggi precedenti
All'inizio messages contiene solo la parte recente della conversazione. Un pulsante Load older messages sopra il primo messaggio chiama loadMore() per caricare il resto. Quando una pressione non aggiunge messaggi, al posto del pulsante compare la nota This is the start of the conversation. Un agente finto non conserva messaggi precedenti e per questo nell'esempio già la prima pressione arriva all'inizio.
import { useLayoutEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake agent to build with. Since it keeps no older messages, loadMore() finds none.
const diary = {
name: 'Diary',
onMessage: (message) => `Noted: ${message.text}`,
};
export default function App() {
// While building: the fake agent. In the webapp: useWorld()
const { world: agent, error } = useWorld({ fake: { agent: diary } });
const [isLoading, setIsLoading] = useState(false);
const [isAtStart, setIsAtStart] = useState(false); // true once there is nothing older
// The messages scroll inside their own box, and the distance of the scroll position
// from its bottom is kept while older messages arrive at the top.
const box = useRef(null);
const keptFromBottom = useRef(null);
const count = agent ? agent.messages.length : 0;
useLayoutEffect(() => {
// After React draws the older messages, scroll back to the same distance from the bottom.
if (keptFromBottom.current !== null && box.current) {
box.current.scrollTop = box.current.scrollHeight - keptFromBottom.current;
keptFromBottom.current = null;
}
}, [count]);
if (error) return <p>Could not connect ({error.code}).</p>;
if (!agent) return <p>Connecting…</p>;
async function loadOlder() {
setIsLoading(true);
// Older messages go on top: keep the distance from the bottom, so that what the person reads stays put.
keptFromBottom.current = box.current.scrollHeight - box.current.scrollTop;
// loadMore() adds older messages at the start of `messages`, and says how many.
const added = await agent.loadMore();
setIsLoading(false);
if (added === 0) {
keptFromBottom.current = null;
setIsAtStart(true);
}
}
return (
<>
{isAtStart ? (
<p><i>This is the start of the conversation.</i></p>
) : (
<button onClick={loadOlder} disabled={isLoading}>{isLoading ? 'Loading…' : 'Load older messages'}</button>
)}
<div ref={box} style={{ maxHeight: 160, overflowY: 'auto' }}>
{agent.messages.map((message) => (
<p key={message.id}><b>{message.fromMe ? 'You' : message.from}:</b> {message.text}</p>
))}
</div>
<button onClick={() => agent.send('Fed the cat')} disabled={!agent.canSend}>Write "Fed the cat"</button>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake agent to build with. Since it keeps no older messages, loadMore() finds none.
const diary = {
name: 'Diary',
onMessage: (message) => `Noted: ${message.text}`,
};
// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: diary } });
const olderButton = document.createElement('button');
olderButton.textContent = 'Load older messages';
// The messages scroll inside their own box.
const list = document.createElement('div');
list.style.cssText = 'max-height: 160px; overflow-y: auto';
const writeButton = document.createElement('button');
writeButton.textContent = 'Write "Fed the cat"';
writeButton.onclick = () => agent.send('Fed the cat');
document.body.append(olderButton, list, writeButton);
// The distance of the scroll position from the bottom of the box, kept while older messages arrive.
let keptFromBottom = null;
olderButton.onclick = async () => {
olderButton.disabled = true;
olderButton.textContent = 'Loading…';
// Older messages go on top: keep the distance from the bottom, so that what the person reads stays put.
keptFromBottom = list.scrollHeight - list.scrollTop;
// loadMore() adds older messages at the start of `messages`, and says how many.
const added = await agent.loadMore();
if (added === 0) keptFromBottom = null;
olderButton.disabled = false;
olderButton.textContent = 'Load older messages';
if (added === 0) {
// When there is nothing older, say so in place of the button.
const start = document.createElement('p');
const words = document.createElement('i');
words.textContent = 'This is the start of the conversation.';
start.append(words);
olderButton.replaceWith(start);
}
};
agent.subscribe((node) => {
writeButton.disabled = !node.canSend;
list.replaceChildren(...node.messages.map((message) => {
const line = document.createElement('p');
const sender = document.createElement('b');
sender.textContent = `${message.fromMe ? 'You' : message.from}:`;
line.append(sender, ` ${message.text ?? ''}`);
return line;
}));
// After drawing the older messages, scroll back to the same distance from the bottom.
if (keptFromBottom !== null) {
list.scrollTop = list.scrollHeight - keptFromBottom;
keptFromBottom = null;
}
});Come funziona
await world.loadMore() aggiunge i messaggi precedenti all'inizio di messages nello stesso ordine dal più vecchio al più recente e si risolve con il numero dei messaggi aggiunti (0 quando non ce ne sono altri). La tua vista li mostra come qualsiasi altro cambiamento perché subscribe chiama di nuovo il suo listener (in React il componente che chiama useWorld fa di nuovo il render). L'esempio disattiva il pulsante mentre loadMore è in corso perché un doppio clic non carichi due volte gli stessi messaggi. Prima della chiamata salva la distanza della posizione di scorrimento dal fondo del contenitore dei messaggi. Dopo aver disegnato in cima i messaggi più vecchi torna a quella distanza in modo che quello che la persona stava leggendo resti al suo posto. loadMore si limita a leggere e non invia niente al mondo a nome della persona.