Skip to content

Completa la vista ​

Una volta pubblicata la vista, possono andare storte tre cose: (1) l'agente non c'è, (2) Feeder non è raggiungibile e (3) un messaggio non viene consegnato. L'ultimo passo gestisce tutti e tre i casi e aggiunge due ritocchi (la conversazione scorre fino al messaggio più recente e la fotocamera si chiude dopo l'invio della foto).

Quando l'agente non c'è ​

Quando la vista viene aperta in una scheda del browser fuori dalla webapp, la Promise di connectToHost() viene rifiutata con il codice 'no-host'. La vista dice allora dove funziona:

jsx
if (error) {
  return <p>{error.code === 'no-host' ? 'This view works inside UNaIVERSE: open Feeder there.' : `Could not connect (${error.code}).`}</p>;
}

In JavaScript semplice connectToHost ora sta in un try e la vista parte solo quando c'è un agente. Ogni parte della vista è diventata una funzione che disegna nell'elemento che riceve e gira solo dopo il collegamento (showAgent, showAgentCamera, showMyCamera e showChat sono le stesse parti dei componenti React).

Il telefono simulato del passo 6 non c'è più e webapp segue di nuovo la tua pagina. Un commento nel codice indica la riga che riporta il telefono.

Quando Feeder non è raggiungibile ​

agent.status vale 'connecting' per un momento e poi 'online'. Con qualunque altro valore (per esempio 'offline' o 'unreachable') l'agente non c'è più. Finché l'agente non torna, la sua fotocamera non invia fotogrammi e canSend è false. Una riga sotto il suo nome lo dice alla persona:

js
function statusText(node) {
  if (node.status === 'online') return '';
  if (node.status === 'connecting') return `Connecting to ${node.name}…`;
  return `${node.name} is not reachable now. Its camera and its answers come back when it is.`;
}

Consegna e Retry ​

Ogni messaggio della persona ha uno status ('sending', 'sent' o 'failed') e un messaggio fallito ha retry() per inviarlo di nuovo:

jsx
{message.status === 'sending' && <i> Sending…</i>}
{message.status === 'failed' && (
  <>
    <i> Not delivered. </i>
    <button onClick={() => message.retry()}>Retry</button>
  </>
)}

L'agente finto ha failNext: true e fa fallire il primo messaggio che invii.

In JavaScript semplice la chiave che decide quando ricostruire la lista ora contiene lo stato di ogni messaggio oltre al suo id. Anche un cambio di stato ricostruisce quindi la lista.

Che cosa ti dice send ​

send si risolve con uno di tre risultati: (1) 'sent', (2) 'failed' (il messaggio lo mostra con Retry) o (3) 'not-allowed' (l'agente ora non accetta un messaggio). Nella webapp la Promise può anche essere rifiutata con un errore il cui code dà la causa ('failed' quando la webapp non è riuscita a eseguire la chiamata).

La casella dei messaggi e il pulsante che invia la foto usano la stessa funzione per trasformare ogni esito in un testo per la persona:

js
async function sendAndExplain(agent, value) {
  try {
    const result = await agent.send(value);
    if (result === 'not-allowed') return `${agent.name} cannot take a message now. Try again in a moment.`;
    return '';
  } catch (error) {
    return `Your message could not be sent (${error.code}). Try again in a moment.`;
  }
}

Due ritocchi ​

  • Il messaggio più recente. Quando arriva un messaggio la vista fa scorrere main fino alla fine con main.scrollTop = main.scrollHeight. In React lo fa un effect ogni volta che cambia il numero dei messaggi.
  • La fotocamera si chiude. Appena la Promise di send si è risolta con 'sent' o 'failed', la vista ferma la fotocamera della persona e la sua spia si spegne. Una foto non consegnata resta nella conversazione con il suo pulsante Retry come qualunque altro messaggio.

La vista completa ​

jsx
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';

// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
	const x = 170 + 70 * Math.sin(time / 800);
	const y = 120 - Math.abs(25 * Math.sin(time / 300));
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake agent to build with. Its camera sends a new picture every 100 ms,
// and the agent answers every message, a photo included.
const feeder = {
	name: 'Feeder',
	profile: { description: 'A camera at a bird feeder, in a garden.' },
	data: { camera: { every: 100, value: frameAt } },
	onMessage: async (message) => {
		if (!message.image) return 'A robin is at the feeder right now. It comes every morning.';
		// A real agent would look at the photo, but this fake one only measures it.
		const photo = new Image();
		photo.src = message.image;
		await photo.decode();
		return `Thanks! I got your photo, ${photo.naturalWidth} × ${photo.naturalHeight} pixels. I will watch for that bird.`;
	},
	// The first message fails, to let you try "Retry".
	failNext: true,
};

// A sample picture of a blue tit, drawn as an SVG picture, for a person with no camera.
const SAMPLE_PICTURE = `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="320" height="240">
<rect width="320" height="240" fill="#e3f1d9"/><rect x="0" y="180" width="320" height="10" fill="#8b5a2b"/>
<polygon points="110,140 50,150 110,165" fill="#3d7ab8"/><ellipse cx="160" cy="145" rx="60" ry="38" fill="#f2cf3a"/>
<circle cx="205" cy="105" r="30" fill="#3d7ab8"/><circle cx="212" cy="112" r="16" fill="#ffffff"/>
<circle cx="216" cy="106" r="4" fill="#1b1b1b"/><polygon points="233,108 248,112 233,116" fill="#444444"/>
</svg>`)}`;

// Pictures get narrower on a narrow phone.
const FIT_WIDTH = { maxWidth: '100%', height: 'auto' };

// Sends as the person and returns what went wrong in words, or '' when all went well.
async function sendAndExplain(agent, value) {
	try {
		const result = await agent.send(value);
		// 'failed' shows on the message itself, with Retry. 'not-allowed' means the rules of the agent say not now.
		if (result === 'not-allowed') return `${agent.name} cannot take a message now. Try again in a moment.`;
		return '';
	} catch (error) {
		// The webapp could not send it. The code says why, for example 'failed' when something went wrong in the webapp.
		return `Your message could not be sent (${error.code}). Try again in a moment.`;
	}
}

// What to say about the connection of the agent, or nothing while it is online.
function statusText(agent) {
	if (agent.status === 'online') return '';
	if (agent.status === 'connecting') return `Connecting to ${agent.name}…`;
	return `${agent.name} is not reachable now. Its camera and its answers come back when it is.`;
}

// The camera of the agent, apart from the rest, with its picture, a caption and a button to pause it.
function AgentCamera({ agent }) {
	const picture = useRef(null);
	const [isPaused, setIsPaused] = useState(false);
	const [framesPerSecond, setFramesPerSecond] = useState(null);

	useEffect(() => {
		if (isPaused) return undefined;
		let frames = 0;
		// onData calls this with every new picture of `camera`, and for nothing else.
		// The picture goes straight into the <img>, with no state and no new render.
		const stop = agent.onData('camera', (frame) => {
			picture.current.src = frame;
			frames += 1;
		});
		// Once a second, show how many pictures arrived.
		const timer = setInterval(() => {
			setFramesPerSecond(frames);
			frames = 0;
		}, 1000);
		// A pause stops both, and the picture stays on the last frame.
		return () => {
			stop();
			clearInterval(timer);
		};
		// Start again only after a pause, because `onData` works from any copy of `agent`.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isPaused]);

	let caption = `Live: ${framesPerSecond} frames a second`;
	if (isPaused) caption = 'Paused';
	else if (framesPerSecond === null) caption = `Waiting for ${agent.name}'s camera…`;
	return (
		<>
			<img ref={picture} alt={`${agent.name}'s camera`} width="320" height="180" style={FIT_WIDTH} />
			<p>{caption}</p>
			<button onClick={() => setIsPaused(!isPaused)}>{isPaused ? 'Play' : 'Pause'}</button>
		</>
	);
}

// The conversation with the agent, oldest first, and the delivery of each message of the person.
function MessageList({ agent }) {
	if (agent.messages.length === 0) return <div>No messages yet. Ask {agent.name} about the birds.</div>;
	return (
		<div>
			{agent.messages.map((message) => (
				<p key={message.id}>
					<b>{message.fromMe ? 'You' : message.from}:</b> {message.text}
					{/* A message can carry a picture, as an image source ready for an <img>. */}
					{message.image && <><br /><img src={message.image} alt="Photo" width="160" /></>}
					{/* Only the person's messages have a status ('sending', 'sent' or 'failed'). */}
					{message.status === 'sending' && <i> Sending…</i>}
					{message.status === 'failed' && (
						<>
							<i> Not delivered. </i>
							{/* retry() sends the same message again. */}
							<button onClick={() => message.retry()}>Retry</button>
						</>
					)}
				</p>
			))}
		</div>
	);
}

// The box to write to the agent, at the bottom of the view.
function MessageBox({ agent }) {
	const [text, setText] = useState('');
	const [notice, setNotice] = useState('');

	async function handleSubmit(event) {
		event.preventDefault();
		setText('');
		setNotice(await sendAndExplain(agent, text));
	}

	return (
		<>
			{notice && <p style={{ margin: '8px 16px 0' }}>{notice}</p>}
			<form onSubmit={handleSubmit} style={{ display: 'flex', gap: 8, padding: '8px 16px' }}>
				<input value={text} onChange={(event) => setText(event.target.value)} placeholder={`Ask ${agent.name}`} style={{ flex: 1 }} />
				{/* canSend is false while the agent cannot take a message (still connecting, or busy). */}
				<button disabled={!agent.canSend || !text.trim()}>Send</button>
			</form>
		</>
	);
}

// The person's camera, to show the agent a bird, or a sample picture.
function MyCamera({ agent }) {
	const video = useRef(null);
	const sample = useRef(null);
	const stream = useRef(null); // the person's camera, while it is open
	const [source, setSource] = useState(null); // 'camera', 'sample' or null before a choice
	const [note, setNote] = useState('');
	const [photo, setPhoto] = useState(null); // the photo taken, as an image source

	function closeCamera() {
		stream.current?.getTracks().forEach((track) => track.stop());
		stream.current = null;
	}

	// Close the camera when this part of the page goes away.
	useEffect(() => closeCamera, []);

	async function openCamera() {
		setNote('');
		try {
			// In the webapp, the person allows the camera for your view first.
			if (!agent.webapp.allowed.includes('camera')) await agent.askFor(['camera']);
			// Then the browser opens it (and asks the person, the first time).
			stream.current = await navigator.mediaDevices.getUserMedia({ video: true });
			video.current.srcObject = stream.current;
			setSource('camera');
		} catch (error) {
			// No camera here, or the person said no. After a no, `askFor` fails with the code 'declined'.
			const reason = error.code === 'declined' ? 'You did not allow the camera.' : 'Your camera could not open.';
			setNote(`${reason} You can use a sample picture instead.`);
		}
	}

	function showSample() {
		closeCamera();
		setSource('sample');
		setNote('A sample picture of a blue tit.');
	}

	// To take a photo, draw what is shown (the camera or the sample) on a canvas, then read the canvas as a JPEG.
	function takePhoto() {
		const canvas = document.createElement('canvas');
		canvas.width = 320;
		canvas.height = 240;
		canvas.getContext('2d').drawImage(source === 'camera' ? video.current : sample.current, 0, 0, canvas.width, canvas.height);
		setPhoto(canvas.toDataURL('image/jpeg', 0.8));
	}

	async function sendPhoto() {
		// send() takes a picture too, as an image source (here a data URI) with a few words.
		const problem = await sendAndExplain(agent, { image: photo, text: 'What bird is this?' });
		if (problem) {
			setNote(problem);
			return;
		}
		// The photo has left, and the camera can close. A failed photo waits in the conversation with Retry.
		closeCamera();
		setPhoto(null);
		setSource(null);
		setNote('Your photo is in the conversation.');
	}

	return (
		<>
			<h2>Show {agent.name} a bird</h2>
			{/* Always on the page, to be there when the camera opens, and hidden until then. */}
			<video ref={video} autoPlay playsInline muted width="320" height="240" style={FIT_WIDTH} hidden={source !== 'camera'} />
			{source === 'sample' && <img ref={sample} src={SAMPLE_PICTURE} alt="A sample picture of a blue tit" width="320" height="240" style={FIT_WIDTH} />}
			{note && <p>{note}</p>}
			<button onClick={openCamera}>Open my camera</button>
			<button onClick={showSample}>Use a sample picture</button>
			<button onClick={takePhoto} disabled={!source}>Take a photo</button>
			{/* Once taken, the photo shows as a small copy next to a button that sends it. */}
			{photo && (
				<p>
					<img src={photo} alt="Your photo" width="160" height="120" />
					<button onClick={sendPhoto}>Send to {agent.name}</button>
				</p>
			)}
		</>
	);
}

export default function App() {
	// While building: the fake agent. In the webapp: useWorld()
	// To try a phone, add: webapp: { keyboard: 300, insets: { top: 0, right: 0, bottom: 34, left: 0 } }
	const { world: agent, error } = useWorld({ fake: { agent: feeder } });
	const main = useRef(null);
	const messageCount = agent ? agent.messages.length : 0;

	// When a message arrives, scroll to it at the bottom of the view.
	useEffect(() => {
		if (main.current) main.current.scrollTop = main.current.scrollHeight;
	}, [messageCount]);

	if (error) {
		// When the view is opened alone, outside the webapp, there is no agent and the code is 'no-host'.
		return <p>{error.code === 'no-host' ? 'This view works inside UNaIVERSE: open Feeder there.' : `Could not connect (${error.code}).`}</p>;
	}
	if (!agent) return <p>Connecting…</p>;

	// Keep clear of the edges of the phone (`insets`) and of its keyboard (`keyboard`), both in pixels.
	// The keyboard covers the bottom of the view, home bar included. Stay above the larger of the two.
	const { insets, keyboard } = agent.webapp;
	const padding = `${insets.top}px ${insets.right}px ${Math.max(insets.bottom, keyboard)}px ${insets.left}px`;
	const status = statusText(agent);
	return (
		// The whole view, with a part that scrolls and the message box at the bottom.
		<div style={{ position: 'fixed', inset: 0, display: 'flex', flexDirection: 'column', padding }}>
			<main ref={main} style={{ flex: 1, overflowY: 'auto', padding: '0 16px' }}>
				<h1>{agent.name}</h1>
				{status && <p><b>{status}</b></p>}
				<p>{agent.profile.description}</p>
				<AgentCamera agent={agent} />
				<MyCamera agent={agent} />
				<MessageList agent={agent} />
			</main>
			<MessageBox agent={agent} />
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
	const x = 170 + 70 * Math.sin(time / 800);
	const y = 120 - Math.abs(25 * Math.sin(time / 300));
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake agent to build with. Its camera sends a new picture every 100 ms,
// and the agent answers every message, a photo included.
const feeder = {
	name: 'Feeder',
	profile: { description: 'A camera at a bird feeder, in a garden.' },
	data: { camera: { every: 100, value: frameAt } },
	onMessage: async (message) => {
		if (!message.image) return 'A robin is at the feeder right now. It comes every morning.';
		// A real agent would look at the photo, but this fake one only measures it.
		const photo = new Image();
		photo.src = message.image;
		await photo.decode();
		return `Thanks! I got your photo, ${photo.naturalWidth} × ${photo.naturalHeight} pixels. I will watch for that bird.`;
	},
	// The first message fails, to let you try "Retry".
	failNext: true,
};

// A sample picture of a blue tit, drawn as an SVG picture, for a person with no camera.
const SAMPLE_PICTURE = `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="320" height="240">
<rect width="320" height="240" fill="#e3f1d9"/><rect x="0" y="180" width="320" height="10" fill="#8b5a2b"/>
<polygon points="110,140 50,150 110,165" fill="#3d7ab8"/><ellipse cx="160" cy="145" rx="60" ry="38" fill="#f2cf3a"/>
<circle cx="205" cy="105" r="30" fill="#3d7ab8"/><circle cx="212" cy="112" r="16" fill="#ffffff"/>
<circle cx="216" cy="106" r="4" fill="#1b1b1b"/><polygon points="233,108 248,112 233,116" fill="#444444"/>
</svg>`)}`;

// Sends as the person and returns what went wrong in words, or '' when all went well.
async function sendAndExplain(agent, value) {
	try {
		const result = await agent.send(value);
		// 'failed' shows on the message itself, with Retry. 'not-allowed' means the rules of the agent say not now.
		if (result === 'not-allowed') return `${agent.name} cannot take a message now. Try again in a moment.`;
		return '';
	} catch (error) {
		// The webapp could not send it. The code says why, for example 'failed' when something went wrong in the webapp.
		return `Your message could not be sent (${error.code}). Try again in a moment.`;
	}
}

// What to say about the connection of the agent, or nothing while it is online.
function statusText(node) {
	if (node.status === 'online') return '';
	if (node.status === 'connecting') return `Connecting to ${node.name}…`;
	return `${node.name} is not reachable now. Its camera and its answers come back when it is.`;
}

// ── The whole view, with a part that scrolls and the message box at the bottom ──
function makeLayout(agent) {
	const layout = document.createElement('div');
	layout.style.cssText = 'position: fixed; inset: 0; display: flex; flex-direction: column;';
	const main = document.createElement('main');
	main.style.cssText = 'flex: 1; overflow-y: auto; padding: 0 16px;';
	layout.append(main);
	document.body.append(layout);

	// Keep clear of the edges of the phone (`insets`) and of its keyboard (`keyboard`), both in pixels.
	agent.subscribe((node) => {
		const { insets, keyboard } = node.webapp;
		layout.style.paddingTop = `${insets.top}px`;
		layout.style.paddingRight = `${insets.right}px`;
		layout.style.paddingLeft = `${insets.left}px`;
		// The keyboard covers the bottom of the view, home bar included. Stay above the larger of the two.
		layout.style.paddingBottom = `${Math.max(insets.bottom, keyboard)}px`;
	});
	return { layout, main };
}

// ── The agent, with its name, its connection and what it is ──
function showAgent(container, agent) {
	const title = document.createElement('h1');
	const status = document.createElement('p');
	status.style.fontWeight = 'bold';
	const description = document.createElement('p');
	container.append(title, status, description);

	// Everything but the camera. This listener runs at every change, a new picture included, and must stay light.
	agent.subscribe((node) => {
		title.textContent = node.name;
		status.textContent = statusText(node);
		status.hidden = !status.textContent;
		description.textContent = node.profile.description ?? '';
	});
}

// ── The camera of the agent, with its picture, a caption and a button to pause it ──
function showAgentCamera(container, agent) {
	const picture = document.createElement('img');
	picture.alt = `${agent.name}'s camera`;
	picture.width = 320;
	picture.height = 180;
	picture.style.cssText = 'max-width: 100%; height: auto;'; // narrower on a narrow phone
	const caption = document.createElement('p');
	const pauseButton = document.createElement('button');
	container.append(picture, caption, pauseButton);

	let frames = 0; // pictures since the last count
	let framesPerSecond = null; // the last count, or null before the first one
	let stopCamera = null; // stops following the camera, or null while paused

	function drawCaption() {
		if (!stopCamera) caption.textContent = 'Paused';
		else if (framesPerSecond === null) caption.textContent = `Waiting for ${agent.name}'s camera…`;
		else caption.textContent = `Live: ${framesPerSecond} frames a second`;
		pauseButton.textContent = stopCamera ? 'Pause' : 'Play';
	}

	function play() {
		// onData calls this with every new picture of `camera`, and for nothing else.
		stopCamera = agent.onData('camera', (frame) => {
			picture.src = frame;
			frames += 1;
		});
		drawCaption();
	}

	function pause() {
		stopCamera(); // the picture stays on the last frame
		stopCamera = null;
		drawCaption();
	}

	pauseButton.onclick = () => (stopCamera ? pause() : play());
	play();

	// Once a second, show how many pictures arrived.
	setInterval(() => {
		if (stopCamera) framesPerSecond = frames;
		frames = 0;
		drawCaption();
	}, 1000);
}

// ── Your camera, to show the agent a bird, take a photo and send it ──
function showMyCamera(container, agent) {
	const heading = document.createElement('h2');
	heading.textContent = `Show ${agent.name} a bird`;
	const video = document.createElement('video');
	video.autoplay = true;
	video.playsInline = true;
	video.muted = true;
	video.width = 320;
	video.height = 240;
	video.hidden = true;
	video.style.cssText = 'max-width: 100%; height: auto;';
	const sample = document.createElement('img');
	sample.src = SAMPLE_PICTURE;
	sample.alt = 'A sample picture of a blue tit';
	sample.width = 320;
	sample.height = 240;
	sample.hidden = true;
	sample.style.cssText = 'max-width: 100%; height: auto;';
	const note = document.createElement('p');
	const openButton = document.createElement('button');
	openButton.textContent = 'Open my camera';
	const sampleButton = document.createElement('button');
	sampleButton.textContent = 'Use a sample picture';
	const takeButton = document.createElement('button');
	takeButton.textContent = 'Take a photo';
	takeButton.disabled = true;
	// Once taken, the photo shows as a small copy next to a button that sends it.
	const photoBox = document.createElement('p');
	photoBox.hidden = true;
	const preview = document.createElement('img');
	preview.alt = 'Your photo';
	preview.width = 160;
	preview.height = 120;
	const sendPhotoButton = document.createElement('button');
	sendPhotoButton.textContent = `Send to ${agent.name}`;
	photoBox.append(preview, sendPhotoButton);
	container.append(heading, video, sample, note, openButton, sampleButton, takeButton, photoBox);

	let stream = null; // the person's camera, while it is open
	let photo = null; // the photo taken, as an image source

	function closeCamera() {
		stream?.getTracks().forEach((track) => track.stop());
		stream = null;
	}

	openButton.onclick = async () => {
		note.textContent = '';
		try {
			// In the webapp, the person allows the camera for your view first.
			if (!agent.webapp.allowed.includes('camera')) await agent.askFor(['camera']);
			// Then the browser opens it (and asks the person, the first time).
			stream = await navigator.mediaDevices.getUserMedia({ video: true });
			video.srcObject = stream;
			video.hidden = false;
			sample.hidden = true;
			takeButton.disabled = false;
		} catch (error) {
			// No camera here, or the person said no. After a no, `askFor` fails with the code 'declined'.
			const reason = error.code === 'declined' ? 'You did not allow the camera.' : 'Your camera could not open.';
			note.textContent = `${reason} You can use a sample picture instead.`;
		}
	};

	sampleButton.onclick = () => {
		closeCamera();
		video.hidden = true;
		sample.hidden = false;
		takeButton.disabled = false;
		note.textContent = 'A sample picture of a blue tit.';
	};

	// To take a photo, draw what is shown (the camera or the sample) on a canvas, then read the canvas as a JPEG.
	takeButton.onclick = () => {
		const canvas = document.createElement('canvas');
		canvas.width = 320;
		canvas.height = 240;
		canvas.getContext('2d').drawImage(stream ? video : sample, 0, 0, canvas.width, canvas.height);
		photo = canvas.toDataURL('image/jpeg', 0.8);
		preview.src = photo;
		photoBox.hidden = false;
	};

	sendPhotoButton.onclick = async () => {
		// send() takes a picture too, as an image source (here a data URI) with a few words.
		const problem = await sendAndExplain(agent, { image: photo, text: 'What bird is this?' });
		if (problem) {
			note.textContent = problem;
			return;
		}
		// The photo has left, and the camera can close. A failed photo waits in the conversation with Retry.
		closeCamera();
		photo = null;
		video.hidden = true;
		sample.hidden = true;
		photoBox.hidden = true;
		takeButton.disabled = true;
		note.textContent = 'Your photo is in the conversation.';
	};
}

// ── The conversation, with its messages and the message box at the bottom of the view ──
function showChat(main, layout, agent) {
	const list = document.createElement('div');
	main.append(list);
	const notice = document.createElement('p');
	notice.style.margin = '8px 16px 0';
	notice.hidden = true;
	const form = document.createElement('form');
	form.style.cssText = 'display: flex; gap: 8px; padding: 8px 16px;';
	const input = document.createElement('input');
	input.placeholder = `Ask ${agent.name}`;
	input.style.flex = '1';
	const sendButton = document.createElement('button');
	sendButton.textContent = 'Send';
	form.append(input, sendButton);
	layout.append(notice, form);

	let canSend = false;
	function drawSendButton() {
		// canSend is false while the agent cannot take a message (still connecting, or busy).
		sendButton.disabled = !canSend || !input.value.trim();
	}
	input.oninput = drawSendButton;

	form.onsubmit = async (event) => {
		event.preventDefault();
		const text = input.value;
		input.value = '';
		drawSendButton();
		notice.textContent = await sendAndExplain(agent, text);
		notice.hidden = !notice.textContent;
	};

	// One message, with who sent it, its words, its picture and how its delivery went.
	function messageElement(message) {
		const line = document.createElement('p');
		const sender = document.createElement('b');
		sender.textContent = `${message.fromMe ? 'You' : message.from}:`;
		line.append(sender, ` ${message.text ?? ''}`);
		// A message can carry a picture, as an image source ready for an <img>.
		if (message.image) {
			const image = document.createElement('img');
			image.src = message.image;
			image.alt = 'Photo';
			image.width = 160;
			line.append(document.createElement('br'), image);
		}
		// Only the person's messages have a status ('sending', 'sent' or 'failed').
		if (message.status === 'sending') {
			const sending = document.createElement('i');
			sending.textContent = ' Sending…';
			line.append(sending);
		}
		if (message.status === 'failed') {
			const failed = document.createElement('i');
			failed.textContent = ' Not delivered. ';
			const retryButton = document.createElement('button');
			retryButton.textContent = 'Retry';
			// retry() sends the same message again.
			retryButton.onclick = () => message.retry();
			line.append(failed, retryButton);
		}
		return line;
	}

	let shownMessages = null; // the ids and statuses of the messages on the page
	let shownCount = 0;
	agent.subscribe((node) => {
		canSend = node.canSend;
		drawSendButton();
		// This runs for every picture too, and it draws the messages again only when they changed.
		const key = node.messages.map((message) => `${message.id}:${message.status}`).join(' ');
		if (key === shownMessages) return;
		shownMessages = key;
		if (node.messages.length === 0) list.textContent = `No messages yet. Ask ${node.name} about the birds.`;
		else list.replaceChildren(...node.messages.map(messageElement));
		// When a message arrives, scroll to it at the bottom of the view.
		if (node.messages.length > shownCount) main.scrollTop = main.scrollHeight;
		shownCount = node.messages.length;
	});
}

// ── Connect first, then show the view or say why there is none ──
const loading = document.createElement('p');
loading.textContent = 'Connecting…';
document.body.append(loading);

let agent = null;
try {
	// While building: the fake agent. In the webapp: agent = await connectToHost();
	// To try a phone, add: webapp: { keyboard: 300, insets: { top: 0, right: 0, bottom: 34, left: 0 } }
	agent = await connectToHost({ fake: { agent: feeder } });
} catch (error) {
	// When the view is opened alone, outside the webapp, there is no agent and the code is 'no-host'.
	loading.textContent = error.code === 'no-host'
		? 'This view works inside UNaIVERSE: open Feeder there.'
		: `Could not connect (${error.code}).`;
}

if (agent) {
	loading.remove();
	const { layout, main } = makeLayout(agent);
	showAgent(main, agent);
	showAgentCamera(main, agent);
	showMyCamera(main, agent);
	showChat(main, layout, agent);
}
Live, on a fake world
Open

Invia un messaggio e premi Retry quando fallisce. Poi invia una foto a Feeder.

Prossimi passi ​

Hai costruito una vista completa per un agente con la fotocamera. Queste pagine la portano più avanti:

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.