Chat
A Slack-like chat with channels, reactions and threads, built with React and Yorkie JS SDK. The rail shows who is in which channel, two people reacting at once both count, and a pane switched offline catches up when it returns.
App.tsx
1import './App.css';23import { useCallback, useEffect, useMemo, useRef, useState } from 'react';4import {5 type Document,6 DocumentProvider,7 SyncMode,8 useDocument,9 useYorkie,10 YorkieProvider,11} from '@yorkie-js/react';12import ExampleHeader, { type Status } from './ExampleHeader';13import ChannelRail from './ChannelRail';14import ChannelView from './ChannelView';15import {16 channelKey,17 type ChannelRoot,18 type ChatPresence,19 defaultChannels,20 makeUser,21 readChannels,22 resolveIdentity,23 roomPrefix,24 seedRoot,25 type WorkspaceRoot,26} from './model';2728// One person per page load, made outside React so StrictMode's double render29// does not make two.30const prefix = roomPrefix(window.location.search, new Date());31const initialPresence: ChatPresence = {32 ...makeUser(),33 channelId: 'general',34 typing: false,35};3637// "Open another tab" must land in this room even after midnight UTC, when a38// fresh load would pick the next day's key.39const roomUrl = (() => {40 const url = new URL(window.location.href);41 url.searchParams.set('key', prefix);42 return url.toString();43})();4445/**46 * `App` connects to Yorkie and attaches the workspace document, which stays47 * attached for the whole session: its root is the channel list and its48 * presence is who is in which channel and who is typing.49 */50export default function App() {51 return (52 <YorkieProvider53 apiKey={import.meta.env.VITE_YORKIE_API_KEY}54 rpcAddr={import.meta.env.VITE_YORKIE_API_ADDR}55 >56 <DocumentProvider<WorkspaceRoot, ChatPresence>57 docKey={prefix}58 initialRoot={{ channels: defaultChannels } as WorkspaceRoot}59 initialPresence={initialPresence}60 >61 <Workspace />62 </DocumentProvider>63 </YorkieProvider>64 );65}6667function Workspace() {68 const { client } = useYorkie();69 const {70 doc: workspaceDoc,71 root,72 presences,73 update,74 connection,75 loading,76 error,77 } = useDocument<WorkspaceRoot, ChatPresence>();78 const [openId, setOpenId] = useState(initialPresence.channelId);79 const [railOpen, setRailOpen] = useState(false);80 const [offline, setOffline] = useState(false);81 const [switching, setSwitching] = useState(false);82 const [pendingIds, setPendingIds] = useState<Set<string>>(() => new Set());83 const [channelReady, setChannelReady] = useState(false);84 const [switchFailed, setSwitchFailed] = useState(false);85 const [focusSwitch, setFocusSwitch] = useState(false);86 const offlineRef = useRef(false);87 const typing = useRef(false);88 const channelDoc = useRef<Document<ChannelRoot> | undefined>(undefined);89 const railTrigger = useRef<HTMLButtonElement | undefined>(undefined);9091 const people = useMemo(92 () => presences.map(({ presence }) => presence),93 [presences],94 );95 const me = useMemo<ChatPresence>(96 () =>97 people.find((p) => p.userId === initialPresence.userId) ?? {98 ...initialPresence,99 channelId: openId,100 },101 [people, openId],102 );103104 // Whenever someone arrives: if we clash with someone who joined earlier,105 // move to a free name and color. Panes opened together cannot see each106 // other when they pick, so this cannot be done only once.107 useEffect(() => {108 if (loading || offline) return;109 const others = people.filter((p) => p.userId !== me.userId);110 const next = resolveIdentity(me, others);111 if (next.name !== me.name || next.color !== me.color) {112 update((_, presence) => presence.set(next));113 }114 }, [loading, offline, people, me, update]);115116 const closeRail = useCallback(() => {117 setRailOpen(false);118 railTrigger.current?.focus();119 }, []);120121 const openChannel = useCallback(122 (channelId: string) => {123 if (channelId === openId) {124 closeRail();125 return;126 }127 // The trigger belongs to the channel view being replaced: the new one128 // takes focus on its own channel button instead.129 setFocusSwitch(railOpen);130 setRailOpen(false);131 setOpenId(channelId);132 typing.current = false;133 update((_, presence) => presence.set({ channelId, typing: false }));134 },135 [closeRail, openId, railOpen, update],136 );137138 // Presence changes go to everyone, so only send the typing flag when it139 // flips, not on every keystroke, and not at all while offline, where it140 // would arrive late.141 const setTyping = useCallback(142 (next: boolean) => {143 if (offlineRef.current || typing.current === next) return;144 typing.current = next;145 update((_, presence) => presence.set({ typing: next }));146 },147 [update],148 );149150 const onWrite = useCallback((id: string) => {151 if (offlineRef.current) setPendingIds((ids) => new Set(ids).add(id));152 }, []);153154 const onDoc = useCallback((doc: Document<ChannelRoot> | undefined) => {155 channelDoc.current = doc;156 setChannelReady(!!doc);157 }, []);158159 // Back online, marks come off once the channel's changes are actually160 // pushed, which can be later than the switch when the server is slow.161 useEffect(() => {162 const ch = channelDoc.current;163 if (offline || pendingIds.size === 0 || !ch || !channelReady) return;164 return ch.subscribe('sync', (event) => {165 if (event.value === 'synced' && !ch.hasLocalChanges()) {166 setPendingIds(new Set());167 }168 });169 }, [offline, pendingIds, channelReady]);170171 /**172 * Offline pauses both documents with `SyncMode.Manual`. That ends their173 * watch streams, so the others see this pane leave and it sees only itself;174 * what it writes meanwhile waits locally. Back online, both resume175 * `Realtime` and the waiting changes are pushed.176 */177 const toggleOffline = async () => {178 const ch = channelDoc.current;179 const ws = workspaceDoc;180 if (!client || !ch || !ws) return;181 setSwitching(true);182 setSwitchFailed(false);183 if (!offlineRef.current) {184 // From here on, write as if offline: no typing flags, and what is sent185 // is marked until it is pushed.186 offlineRef.current = true;187 try {188 // Clear "is typing" first, while the others can still hear it.189 typing.current = false;190 update((_, presence) => presence.set({ typing: false }));191 await client.sync(ws);192 await client.changeSyncMode(ch, SyncMode.Manual);193 await client.changeSyncMode(ws, SyncMode.Manual);194 setOffline(true);195 } catch (err) {196 console.error('Could not go offline', err);197 offlineRef.current = false;198 setSwitchFailed(true);199 await Promise.allSettled([200 client.changeSyncMode(ch, SyncMode.Realtime),201 client.changeSyncMode(ws, SyncMode.Realtime),202 ]);203 }204 } else {205 try {206 await client.changeSyncMode(ch, SyncMode.Realtime);207 await client.changeSyncMode(ws, SyncMode.Realtime);208 } catch (err) {209 // Stay offline as a whole rather than half online.210 console.error('Could not go online', err);211 setSwitchFailed(true);212 await Promise.allSettled([213 client.changeSyncMode(ch, SyncMode.Manual),214 client.changeSyncMode(ws, SyncMode.Manual),215 ]);216 setSwitching(false);217 return;218 }219 offlineRef.current = false;220 setOffline(false);221 // Realtime pushes what waited; this sync only tells us when. If it222 // fails, the marks stay until a later sync succeeds (effect above).223 const [pushed] = await Promise.allSettled([224 client.sync(ch),225 client.sync(ws),226 ]);227 if (pushed.status === 'fulfilled' && !ch.hasLocalChanges()) {228 setPendingIds(new Set());229 }230 }231 setSwitching(false);232 };233234 const channels = useMemo(() => readChannels(root.channels), [root.channels]);235 const channel = channels.find((c) => c.id === openId) ?? channels[0];236 const channelSeed = useMemo(237 () => seedRoot(channel.id, new Date()),238 [channel.id],239 );240241 let status: Status = 'offline';242 if (error) status = 'error';243 else if (loading) status = 'connecting';244 else if (offline) status = 'offline';245 else if (connection === 'connected') status = 'connected';246247 return (248 <div className="chat">249 <ExampleHeader title="React Chat" status={status} href={roomUrl}>250 {!loading && !error && (251 <button252 type="button"253 className="switch"254 data-online={!offline || undefined}255 disabled={switching || !channelReady}256 title={257 !channelReady && !switching258 ? 'Wait for the channel to open'259 : undefined260 }261 onClick={toggleOffline}262 >263 <span className="switch__track" aria-hidden="true">264 <span className="switch__thumb" />265 </span>266 {offline ? 'Go online' : 'Go offline'}267 </button>268 )}269 {switchFailed && (270 <span className="switch__error" role="alert">271 Couldn’t switch. Try again.272 </span>273 )}274 </ExampleHeader>275 {error ? (276 <p className="state-message" role="alert">277 Couldn’t reach the Yorkie server at{' '}278 {import.meta.env.VITE_YORKIE_API_ADDR}. Check that it’s running,279 then reload.280 </p>281 ) : loading ? (282 <p className="state-message">Joining the workspace…</p>283 ) : (284 <div className="chat__body" data-rail-open={railOpen || undefined}>285 <ChannelRail286 channels={channels}287 people={people}288 me={me}289 openId={openId}290 onOpen={openChannel}291 offline={offline}292 busy={switching || !channelReady}293 open={railOpen}294 onClose={closeRail}295 />296 {railOpen && (297 <button298 type="button"299 className="scrim"300 aria-label="Close channels"301 tabIndex={-1}302 onClick={closeRail}303 />304 )}305 <DocumentProvider<ChannelRoot>306 key={channel.id}307 docKey={channelKey(prefix, channel.id)}308 initialRoot={channelSeed}309 disablePresence310 >311 <ChannelView312 channel={channel}313 me={me}314 people={people}315 offline={offline}316 switching={switching}317 focusSwitch={focusSwitch}318 pendingIds={pendingIds}319 setTyping={setTyping}320 onWrite={onWrite}321 onDoc={onDoc}322 onShowChannels={(trigger) => {323 railTrigger.current = trigger;324 setRailOpen(true);325 }}326 />327 </DocumentProvider>328 </div>329 )}330 </div>331 );332}
Two clients on the same document. Edit in one and watch the other.This is one client. Open the example in another tab or on another device to watch edits sync.
- User 1