cheogram-www

created pr with cheogram-www/new-chat2.1 on 2026-11-17T04:43:56Z · by 9e834e0d
commented on 2026-11-18T17:30:15Z · by 3c31bc8c
lgtm
cmds
checkout latest patchset:
ssh pr.pico.sh pull cheogram-www:new-chat2 | git am -3
checkout specific patchset revision:
ssh pr.pico.sh pull cheogram-www:new-chat2 [rev] | git am -3
add changes to patch request:
git format-patch main --stdout | ssh pr.pico.sh cheogram-www:new-chat2
add comment to patch request:
ssh pr.pico.sh comment cheogram-www:new-chat2 "lgtm!"

Patchset cheogram-www/new-chat2.1 on 2026-11-17T04:43:56Z · commit 6b60f84

+2 -88 src/components/Chats.tsx #
......@@ -14,14 +14,12 @@ import {
1414 FormControlLabel,
1515 Menu,
1616 MenuItem,
17- ListItemIcon,
1817 TextField,
1918 useMediaQuery,
2019 } from "@mui/material";
21-import { QRCanvas, frontalCamera } from "qr/dom.js";
2220 import { Virtuoso, VirtuosoHandle } from "react-virtuoso";
2321 import { useQueryState } from "nuqs";
24-import { useState, useEffect, useRef, useCallback, useContext } from "react";
22+import { useState, useEffect, useRef, useContext } from "react";
2523 import {
2624 Outlet,
2725 Navigate,
......@@ -45,7 +43,6 @@ import {
4543 VideoCallButton,
4644 VoiceCallButton,
4745 } from "@chatscope/chat-ui-kit-react";
48-import QrCodeScannerIcon from "@mui/icons-material/QrCodeScanner";
4946 import ArrowForward from "@mui/icons-material/ArrowForward";
5047 import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
5148 import {
......@@ -189,8 +186,6 @@ export const Chats = () => {
189186 q: "",
190187 chats: [] as borogove.AvailableChat[],
191188 });
192- const [addContactAnchorEl, setAddContactAnchorEl] =
193- useState<null | HTMLElement>(null);
194189 const [addRoleAnchorEl, setAddRoleAnchorEl] = useState<null | HTMLElement>(
195190 null,
196191 );
......@@ -198,49 +193,6 @@ export const Chats = () => {
198193
199194 const [popupMember, setPopupMember] = useState<borogove.Member | undefined>();
200195 const [newChatOpen, setNewChatOpen] = useState(false);
201- const [scanQRCode, setScanQRCode] = useState(false);
202- const [qrStatus, setQRStatus] = useState("Loading camera...");
203- const qrDecodeTimeout = useRef<number | null>(null);
204- const qrCamera = useRef<Awaited<ReturnType<typeof frontalCamera>> | null>(
205- null,
206- );
207- const qrScanVideo = useCallback(
208- (video: HTMLVideoElement) => {
209- if (qrDecodeTimeout.current) {
210- clearTimeout(qrDecodeTimeout.current);
211- qrDecodeTimeout.current = null;
212- }
213- if (qrCamera.current) {
214- qrCamera.current.stop();
215- qrCamera.current = null;
216- }
217- if (scanQRCode && video) {
218- const canvas = new QRCanvas({}, { cropToSquare: false });
219- frontalCamera(video).then((camera) => {
220- qrCamera.current = camera;
221- const checkForQR = () => {
222- const data = camera.readFrame(canvas);
223- if (data) {
224- if (data.startsWith("xmpp:")) {
225- setSearchQ(data);
226- setScanQRCode(false);
227- } else {
228- setQRStatus("Invalid QR Code found: " + data);
229- }
230- } else {
231- setQRStatus("No QR Code found");
232- }
233- qrDecodeTimeout.current = setTimeout(() => {
234- checkForQR();
235- }, 100);
236- };
237- checkForQR();
238- });
239- }
240- },
241- [scanQRCode, setSearchQ],
242- );
243-
244196 const startChat = (availableChat: borogove.AvailableChat, trust: boolean) => {
245197 const chat = client.startChat(availableChat);
246198 if (trust) chat.setTrusted(trust);
......@@ -578,37 +530,9 @@ export const Chats = () => {
578530 <Button
579531 title="Start a chat"
580532 icon={<FontAwesomeIcon icon={faPenToSquare} />}
581- onClick={(e) => setAddContactAnchorEl(e.currentTarget)}
533+ onClick={() => setNewChatOpen(true)}
582534 />
583535 )}
584- <Menu
585- open={!!addContactAnchorEl}
586- anchorEl={addContactAnchorEl}
587- onClose={() => setAddContactAnchorEl(null)}
588- >
589- <MenuItem
590- onClick={() => {
591- setNewChatOpen(true);
592- setAddContactAnchorEl(null);
593- }}
594- >
595- <ListItemIcon>
596- <FontAwesomeIcon icon={faComment} />
597- </ListItemIcon>
598- New Chat
599- </MenuItem>
600- <MenuItem
601- onClick={() => {
602- setScanQRCode(true);
603- setAddContactAnchorEl(null);
604- }}
605- >
606- <ListItemIcon>
607- <QrCodeScannerIcon />
608- </ListItemIcon>
609- Scan QR Code
610- </MenuItem>
611- </Menu>
612536 </ConversationHeader.Actions>
613537 </ConversationHeader>
614538 <AwaitOnce
......@@ -1268,16 +1192,6 @@ export const Chats = () => {
12681192 </form>
12691193 </Dialog>
12701194 )}
1271-
1272- <Dialog
1273- open={scanQRCode}
1274- onClose={() => setScanQRCode(false)}
1275- fullScreen={isMobile}
1276- onClick={() => setScanQRCode(false)}
1277- >
1278- <video ref={qrScanVideo}></video>
1279- <p style={{ textAlign: "center", marginTop: "1em" }}>{qrStatus}</p>
1280- </Dialog>
12811195 </MainContainer>
12821196 );
12831197 };
+57 -0 src/components/NewChatDialog.test.tsx #
......@@ -12,6 +12,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1212 import { mock } from "vitest-mock-extended";
1313 import { NewChatDialog } from "./NewChatDialog";
1414
15+vi.mock("./QRCodeScanner", () => ({
16+ QRCodeScanner: ({ onScanned }: { onScanned: (uri: string) => void }) => (
17+ <button onClick={() => onScanned("xmpp:alice@example.com")}>
18+ QR Result
19+ </button>
20+ ),
21+}));
22+
1523 beforeEach(() => localStorage.clear());
1624 afterEach(cleanup);
1725
......@@ -104,6 +112,55 @@ describe("NewChatDialog", () => {
104112 );
105113 });
106114
115+ it("selects the only chat found after scanning a QR code", async () => {
116+ const alice = availableChat("alice@example.com", "Alice");
117+ const { startChat, onStarted, chat } = setup([alice]);
118+
119+ fireEvent.click(screen.getByRole("button", { name: "Scan QR Code" }));
120+ fireEvent.click(screen.getByText("QR Result"));
121+
122+ await waitFor(() =>
123+ expect(
124+ (
125+ screen.getByRole("button", {
126+ name: "Start Chat",
127+ }) as HTMLButtonElement
128+ ).disabled,
129+ ).toBe(false),
130+ );
131+
132+ fireEvent.click(screen.getByRole("button", { name: "Start Chat" }));
133+
134+ await waitFor(() => expect(onStarted).toHaveBeenCalledWith(chat));
135+ expect(startChat).toHaveBeenCalledWith(alice);
136+ });
137+
138+ it("returns to search when QR scanning is cancelled", async () => {
139+ const { onClose } = setup();
140+
141+ fireEvent.click(screen.getByRole("button", { name: "Scan QR Code" }));
142+ expect(screen.getByText("QR Result")).toBeTruthy();
143+
144+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
145+
146+ expect(onClose).not.toHaveBeenCalled();
147+ expect(screen.getByRole("textbox")).toBeTruthy();
148+ });
149+
150+ it("shows results after scanning a QR code with several matches", async () => {
151+ const alice = availableChat("alice@example.com", "Alice");
152+ const bob = availableChat("bob@example.com", "Bob");
153+ setup([alice, bob]);
154+
155+ fireEvent.click(screen.getByRole("button", { name: "Scan QR Code" }));
156+ fireEvent.click(screen.getByText("QR Result"));
157+
158+ expect(await screen.findByText("Bob")).toBeTruthy();
159+ expect(screen.getByText("Alice")).toBeTruthy();
160+ expect(screen.queryByText("Starting a chat with:")).toBeNull();
161+ expect(screen.getByRole("textbox")).toBeTruthy();
162+ });
163+
107164 it("starts a chat when one result is selected", async () => {
108165 const alice = availableChat("alice@example.com", "Alice");
109166 const { startChat, onStarted, chat, findAvailableChats } = setup([alice]);
+112 -65 src/components/NewChatDialog.tsx #
......@@ -1,5 +1,5 @@
11 import * as borogove from "borogove";
2-import { useEffect, useState } from "react";
2+import { useEffect, useRef, useState } from "react";
33 import {
44 Button,
55 Chip,
......@@ -9,6 +9,7 @@ import {
99 DialogContent,
1010 DialogContentText,
1111 DialogTitle,
12+ IconButton,
1213 InputAdornment,
1314 List,
1415 ListItemButton,
......@@ -16,9 +17,11 @@ import {
1617 Stack,
1718 TextField,
1819 } from "@mui/material";
20+import QrCodeScannerIcon from "@mui/icons-material/QrCodeScanner";
1921 import { useDebounce } from "../hooks/use-debounce";
2022
2123 import { findAvailableChats } from "../util";
24+import { QRCodeScanner } from "./QRCodeScanner";
2225
2326 const CHEOGRAM_DOMAIN = "@cheogram.com";
2427
......@@ -51,6 +54,8 @@ export const NewChatDialog = ({
5154 const [selected, setSelected] = useState<borogove.AvailableChat[]>([]);
5255 const [channelName, setChannelName] = useState("");
5356 const [creatingChannel, setCreatingChannel] = useState(false);
57+ const [scanning, setScanning] = useState(false);
58+ const scanTarget = useRef<string | null>(null);
5459 const [starting, setStarting] = useState<"chat" | "channel" | null>(null);
5560 const [error, setError] = useState<string | null>(null);
5661 const [sources, setSources] = useState<string[]>([]);
......@@ -71,28 +76,39 @@ export const NewChatDialog = ({
7176
7277 (async () => {
7378 try {
74- await findAvailableChats(client, search, (availableChat) => {
75- if (!open) return;
76- if (!availableChat || availableChat.chatId === selfId) return;
79+ await findAvailableChats(
80+ client,
81+ scanTarget.current ?? search,
82+ (availableChat) => {
83+ if (!open) return;
84+ if (!availableChat || availableChat.chatId === selfId) return;
7785
78- setResults((existing) => {
79- const chats = existing.q === search ? existing.chats : [];
80- if (chats.some((c) => c.chatId === availableChat.chatId)) {
81- return existing;
82- }
86+ setResults((existing) => {
87+ const chats = existing.q === search ? existing.chats : [];
88+ if (chats.some((c) => c.chatId === availableChat.chatId)) {
89+ return existing;
90+ }
8391
84- return { q: search, chats: [...chats, availableChat] };
85- });
86- });
92+ return { q: search, chats: [...chats, availableChat] };
93+ });
94+ },
95+ );
8796 } catch (e) {
8897 if (open) {
8998 setError(e instanceof Error ? e.message : String(e));
9099 }
91100 }
92101 if (open) {
93- setResults((existing) =>
94- existing.q === search ? existing : { q: search, chats: [] },
95- );
102+ setResults((existing) => {
103+ if (
104+ scanTarget.current === existing.q &&
105+ existing.chats.length === 1
106+ ) {
107+ setSelected(existing.chats);
108+ }
109+ scanTarget.current = null;
110+ return existing.q === search ? existing : { q: search, chats: [] };
111+ });
96112 setCompletedQuery(search);
97113 }
98114 })();
......@@ -105,6 +121,8 @@ export const NewChatDialog = ({
105121 setSelected([]);
106122 setChannelName("");
107123 setCreatingChannel(false);
124+ setScanning(false);
125+ scanTarget.current = null;
108126 setStarting(null);
109127 setError(null);
110128 };
......@@ -115,6 +133,12 @@ export const NewChatDialog = ({
115133 onClose();
116134 };
117135
136+ const handleScanned = (uri: string) => {
137+ reset();
138+ scanTarget.current = uri;
139+ setQuery(uri);
140+ };
141+
118142 const isSelected = (availableChat: borogove.AvailableChat) => {
119143 return selected.some((c) => c.chatId === availableChat.chatId);
120144 };
......@@ -213,11 +237,17 @@ export const NewChatDialog = ({
213237 return (
214238 <Dialog open={open} onClose={close} fullWidth maxWidth="sm">
215239 <DialogTitle>
216- {creatingChannel ? "New Private Channel" : "New Chat"}
240+ {scanning
241+ ? "Scan QR Code"
242+ : creatingChannel
243+ ? "New Private Channel"
244+ : "New Chat"}
217245 </DialogTitle>
218246 <form onSubmit={startChat}>
219247 <DialogContent>
220- {creatingChannel ? (
248+ {scanning ? (
249+ <QRCodeScanner onScanned={handleScanned} />
250+ ) : creatingChannel ? (
221251 <>
222252 <DialogContentText>
223253 Create an invite-only channel.
......@@ -279,12 +309,25 @@ export const NewChatDialog = ({
279309 error={!!error}
280310 slotProps={{
281311 input: {
282- endAdornment:
283- currentQuery !== "" && !searchComplete && !error ? (
284- <InputAdornment position="end">
312+ endAdornment: (
313+ <InputAdornment position="end">
314+ {currentQuery !== "" && !searchComplete && !error && (
285315 <CircularProgress size={20} />
286- </InputAdornment>
287- ) : undefined,
316+ )}
317+ <IconButton
318+ aria-label="Scan QR Code"
319+ title="Scan QR Code"
320+ edge="end"
321+ onClick={() => {
322+ setScanning(true);
323+ setError(null);
324+ }}
325+ disabled={starting !== null}
326+ >
327+ <QrCodeScannerIcon />
328+ </IconButton>
329+ </InputAdornment>
330+ ),
288331 },
289332 }}
290333 />
......@@ -342,51 +385,55 @@ export const NewChatDialog = ({
342385 )}
343386 </DialogContent>
344387 <DialogActions>
345- <Button onClick={close} disabled={starting !== null}>
388+ <Button
389+ onClick={scanning ? () => setScanning(false) : close}
390+ disabled={starting !== null}
391+ >
346392 Cancel
347393 </Button>
348- {creatingChannel ? (
349- <Button
350- type="button"
351- variant="contained"
352- onClick={createPrivateChannel}
353- disabled={starting !== null}
354- >
355- {starting === "channel" ? "Creating..." : "Create Channel"}
356- </Button>
357- ) : (
358- <>
359- {!selected.some(
360- (availableChat) =>
361- isCheogramChat(availableChat) || availableChat.isChannel(),
362- ) && (
363- <Button
364- type="button"
365- variant={showStartChat ? "text" : "contained"}
366- onClick={() => {
367- setCreatingChannel(true);
368- setError(null);
369- }}
370- disabled={starting !== null}
371- >
372- Create Private Channel
373- </Button>
374- )}
375- {(showStartChat || allCheogram) && (
376- <Button
377- type="submit"
378- variant="contained"
379- disabled={starting !== null || selected.length === 0}
380- >
381- {starting === "chat"
382- ? "Starting..."
383- : allCheogram
384- ? "Start Group Text"
385- : "Start Chat"}
386- </Button>
387- )}
388- </>
389- )}
394+ {!scanning &&
395+ (creatingChannel ? (
396+ <Button
397+ type="button"
398+ variant="contained"
399+ onClick={createPrivateChannel}
400+ disabled={starting !== null}
401+ >
402+ {starting === "channel" ? "Creating..." : "Create Channel"}
403+ </Button>
404+ ) : (
405+ <>
406+ {!selected.some(
407+ (availableChat) =>
408+ isCheogramChat(availableChat) || availableChat.isChannel(),
409+ ) && (
410+ <Button
411+ type="button"
412+ variant={showStartChat ? "text" : "contained"}
413+ onClick={() => {
414+ setCreatingChannel(true);
415+ setError(null);
416+ }}
417+ disabled={starting !== null}
418+ >
419+ Create Private Channel
420+ </Button>
421+ )}
422+ {(showStartChat || allCheogram) && (
423+ <Button
424+ type="submit"
425+ variant="contained"
426+ disabled={starting !== null || selected.length === 0}
427+ >
428+ {starting === "chat"
429+ ? "Starting..."
430+ : allCheogram
431+ ? "Start Group Text"
432+ : "Start Chat"}
433+ </Button>
434+ )}
435+ </>
436+ ))}
390437 </DialogActions>
391438 </form>
392439 </Dialog>
+36 -0 src/components/QRCodeScanner.test.tsx #
......@@ -0,0 +1,36 @@
1+// @vitest-environment jsdom
2+
3+import { cleanup, render, waitFor } from "@testing-library/react";
4+import { afterEach, describe, expect, it, vi } from "vitest";
5+import { QRCodeScanner } from "./QRCodeScanner";
6+
7+const { frontalCamera, stop, readFrame } = vi.hoisted(() => ({
8+ frontalCamera: vi.fn(),
9+ stop: vi.fn(),
10+ readFrame: vi.fn(() => undefined),
11+}));
12+
13+vi.mock("qr/dom.js", () => ({
14+ QRCanvas: vi.fn(),
15+ frontalCamera,
16+}));
17+
18+afterEach(() => {
19+ cleanup();
20+ vi.clearAllMocks();
21+});
22+
23+describe("QRCodeScanner", () => {
24+ it("stops the camera when unmounted", async () => {
25+ frontalCamera.mockResolvedValue({ readFrame, stop });
26+
27+ const { unmount } = render(<QRCodeScanner onScanned={vi.fn()} />);
28+
29+ await waitFor(() =>
30+ expect(frontalCamera).toHaveBeenCalledWith(expect.anything()),
31+ );
32+ unmount();
33+
34+ await waitFor(() => expect(stop).toHaveBeenCalled());
35+ });
36+});
+76 -0 src/components/QRCodeScanner.tsx #
......@@ -0,0 +1,76 @@
1+import { useCallback, useEffect, useRef, useState } from "react";
2+import { QRCanvas, frontalCamera } from "qr/dom.js";
3+
4+export const QRCodeScanner = ({
5+ onScanned,
6+}: {
7+ onScanned: (uri: string) => void;
8+}) => {
9+ const [status, setStatus] = useState("Loading camera...");
10+ const decodeTimeout = useRef<number | null>(null);
11+ const camera = useRef<Awaited<ReturnType<typeof frontalCamera>> | null>(null);
12+ const cancelled = useRef(false);
13+ const onScannedRef = useRef(onScanned);
14+ useEffect(() => {
15+ onScannedRef.current = onScanned;
16+ }, [onScanned]);
17+
18+ const stop = useCallback(() => {
19+ cancelled.current = true;
20+ if (decodeTimeout.current) {
21+ clearTimeout(decodeTimeout.current);
22+ decodeTimeout.current = null;
23+ }
24+ if (camera.current) {
25+ camera.current.stop();
26+ camera.current = null;
27+ }
28+ }, []);
29+
30+ const videoRef = useCallback(
31+ (video: HTMLVideoElement | null) => {
32+ stop();
33+ if (video) {
34+ cancelled.current = false;
35+ setStatus("Loading camera...");
36+ const canvas = new QRCanvas({}, { cropToSquare: false });
37+ frontalCamera(video).then((cam) => {
38+ if (cancelled.current) {
39+ cam.stop();
40+ return;
41+ }
42+ camera.current = cam;
43+ const checkForQR = () => {
44+ const data = cam.readFrame(canvas);
45+ if (data) {
46+ onScannedRef.current(data);
47+ } else {
48+ setStatus("No QR Code found");
49+ decodeTimeout.current = setTimeout(() => {
50+ checkForQR();
51+ }, 100);
52+ }
53+ };
54+ checkForQR();
55+ });
56+ }
57+ },
58+ [stop],
59+ );
60+
61+ return (
62+ <>
63+ <video
64+ ref={videoRef}
65+ style={{
66+ display: "block",
67+ width: "100%",
68+ height: "auto",
69+ maxHeight: "70vh",
70+ objectFit: "contain",
71+ }}
72+ ></video>
73+ <p style={{ textAlign: "center", marginTop: "1em" }}>{status}</p>
74+ </>
75+ );
76+};
Back to top