Scorri fino al messaggio più recente
In una lista di messaggi dentro un contenitore scorrevole, i messaggi nuovi si aggiungono sotto l'area visibile. Quando arriva un messaggio, scorri il contenitore fino alla fine solo se era già alla fine. Chi è risalito a leggere messaggi più vecchi mantiene così la sua posizione. Per provarlo, invia qualche messaggio al pappagallo, scorri verso l'alto e inviane un altro.
jsx
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';
// The fake agent repeats what you say.
const parrot = {
name: 'Parrot',
onMessage: (message) => `Polly says: ${message.text}! ${message.text}!`,
};
// The conversation in a box that scrolls and follows the newest message.
function MessageList({ messages }) {
const list = useRef(null);
const isAtBottom = useRef(true); // false while the person reads older messages
// Scroll to a new message, unless the person scrolled up to read.
useEffect(() => {
if (isAtBottom.current) list.current.scrollTop = list.current.scrollHeight;
}, [messages.length]);
function handleScroll() {
const box = list.current;
isAtBottom.current = box.scrollHeight - box.scrollTop - box.clientHeight < 40;
}
return (
<div ref={list} onScroll={handleScroll} style={{ height: 160, overflowY: 'auto', border: '1px solid #8888', padding: '0 8px' }}>
{messages.map((message) => (
<p key={message.id}><b>{message.fromMe ? 'You' : message.from}:</b> {message.text}</p>
))}
</div>
);
}
export default function App() {
// While building: the fake agent. In the webapp: useWorld()
const { world: agent, error } = useWorld({ fake: { agent: parrot } });
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 (!text.trim()) return;
agent.send(text);
setText('');
}
return (
<>
<MessageList messages={agent.messages} />
<form onSubmit={handleSubmit}>
<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Say something" />
<button disabled={!agent.canSend}>Send</button>
</form>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// The fake agent repeats what you say.
const parrot = {
name: 'Parrot',
onMessage: (message) => `Polly says: ${message.text}! ${message.text}!`,
};
// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: parrot } });
// The conversation in a box that scrolls, and a box to write.
const list = document.createElement('div');
list.style.cssText = 'height: 160px; overflow-y: auto; border: 1px solid #8888; padding: 0 8px;';
const form = document.createElement('form');
const input = document.createElement('input');
input.placeholder = 'Say something';
const sendButton = document.createElement('button');
sendButton.textContent = 'Send';
form.append(input, sendButton);
document.body.append(list, form);
form.onsubmit = (event) => {
event.preventDefault();
if (!input.value.trim()) return;
agent.send(input.value);
input.value = '';
};
let isAtBottom = true; // false while the person reads older messages
list.onscroll = () => {
isAtBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 40;
};
let shownCount = 0;
agent.subscribe((node) => {
sendButton.disabled = !node.canSend;
if (node.messages.length === shownCount) return;
shownCount = node.messages.length;
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;
}));
// Scroll to a new message, unless the person scrolled up to read.
if (isAtBottom) list.scrollTop = list.scrollHeight;
});Come funziona
- Il contenitore ha un'altezza fissa e
overflow-y: auto.box.scrollTop = box.scrollHeightlo porta alla fine. - Un listener di
scrollregistra se il contenitore è a meno di 40 pixel dalla fine. Solo in quel caso un messaggio nuovo lo fa scorrere. - A far scattare lo scorrimento è un cambio nel numero dei messaggi. In React
messages.lengthè la dipendenza dell'effetto. In JavaScript semplice il codice lo confronta con l'ultimo conteggio visto. Gli altri cambiamenti del mondo lasciano la posizione invariata. scrollTopfa scorrere solo il contenitore e lascia ferma la pagina della webapp.
Vedi anche
- MessageList: una lista di messaggi pronta.
- Carica i messaggi precedenti.
- Raggruppa i messaggi per mittente.