js-waku/examples/web-chat/src/App.tsx

217 lines
5.2 KiB
TypeScript
Raw Normal View History

2021-04-21 05:51:52 +00:00
import PeerId from 'peer-id';
2021-05-03 05:22:30 +00:00
import { useEffect, useState } from 'react';
2021-04-14 04:44:12 +00:00
import './App.css';
import {
getStatusFleetNodes,
Environment,
StoreCodec,
Waku,
WakuMessage,
} from 'js-waku';
import handleCommand from './command';
2021-04-16 01:32:00 +00:00
import Room from './Room';
2021-04-19 01:34:13 +00:00
import { WakuContext } from './WakuContext';
import { ThemeProvider } from '@livechat/ui-kit';
import { generate } from 'server-name-generator';
import { Message } from './Message';
2021-04-14 04:44:12 +00:00
const themes = {
AuthorName: {
css: {
fontSize: '1.1em',
},
},
Message: {
css: {
margin: '0em',
padding: '0em',
fontSize: '0.83em',
},
},
MessageText: {
css: {
margin: '0em',
padding: '0.1em',
paddingLeft: '1em',
fontSize: '1.1em',
},
},
MessageGroup: {
css: {
margin: '0em',
padding: '0.2em',
},
},
};
export const ChatContentTopic = '/toy-chat/2/huilong/proto';
2021-04-21 05:51:52 +00:00
2021-05-17 06:19:50 +00:00
async function retrieveStoreMessages(
waku: Waku,
peerId: PeerId,
setArchivedMessages: (value: Message[]) => void
2021-05-17 06:19:50 +00:00
): Promise<number> {
const callback = (wakuMessages: WakuMessage[]): void => {
const messages: Message[] = [];
wakuMessages
.map((wakuMsg) => Message.fromWakuMessage(wakuMsg))
.forEach((message) => {
if (message) {
messages.push(message);
}
});
2021-05-17 06:19:50 +00:00
setArchivedMessages(messages);
};
const res = await waku.store.queryHistory({
peerId,
contentTopics: [ChatContentTopic],
pageSize: 5,
callback,
});
return res ? res.length : 0;
}
export default function App() {
const [newMessages, setNewMessages] = useState<Message[]>([]);
const [archivedMessages, setArchivedMessages] = useState<Message[]>([]);
const [waku, setWaku] = useState<Waku | undefined>(undefined);
const [nick, setNick] = useState<string>(() => {
2021-06-04 05:15:07 +00:00
const persistedNick = window.localStorage.getItem('nick');
return persistedNick !== null ? persistedNick : generate();
});
const [fleetEnv, setFleetEnv] = useState<Environment>(defaultFleetEnv);
2021-06-04 05:15:07 +00:00
useEffect(() => {
localStorage.setItem('nick', nick);
}, [nick]);
2021-04-19 01:34:13 +00:00
2021-04-21 06:11:07 +00:00
useEffect(() => {
initWaku(fleetEnv, setWaku)
.then(() => console.log('Waku init done'))
.catch((e) => console.log('Waku init failed ', e));
}, [fleetEnv]);
useEffect(() => {
if (!waku) return;
2021-05-10 02:38:27 +00:00
const handleRelayMessage = (wakuMsg: WakuMessage) => {
console.log('Message received: ', wakuMsg);
const msg = Message.fromWakuMessage(wakuMsg);
if (msg) {
setNewMessages([msg]);
}
};
waku.relay.addObserver(handleRelayMessage, [ChatContentTopic]);
return function cleanUp() {
waku?.relay.deleteObserver(handleRelayMessage, [ChatContentTopic]);
};
}, [waku]);
useEffect(() => {
if (!waku) return;
const handleProtocolChange = async (
_waku: Waku,
{ peerId, protocols }: { peerId: PeerId; protocols: string[] }
) => {
if (protocols.includes(StoreCodec)) {
2021-05-07 00:37:53 +00:00
console.log(`${peerId.toB58String()}: retrieving archived messages}`);
try {
2021-05-17 06:19:50 +00:00
const length = await retrieveStoreMessages(
_waku,
peerId,
2021-05-17 06:19:50 +00:00
setArchivedMessages
);
console.log(`${peerId.toB58String()}: messages retrieved:`, length);
2021-05-07 00:37:53 +00:00
} catch (e) {
console.log(
`${peerId.toB58String()}: error encountered when retrieving archived messages`,
e
);
}
}
};
waku.libp2p.peerStore.on(
'change:protocols',
handleProtocolChange.bind({}, waku)
);
return function cleanUp() {
waku?.libp2p.peerStore.removeListener(
'change:protocols',
handleProtocolChange.bind({}, waku)
);
};
}, [waku]);
2021-04-21 05:51:52 +00:00
2021-04-21 06:11:07 +00:00
return (
2021-04-27 04:39:34 +00:00
<div
className="chat-app"
style={{ height: '100vh', width: '100vw', overflow: 'hidden' }}
>
<WakuContext.Provider value={{ waku: waku }}>
<ThemeProvider theme={themes}>
<Room
nick={nick}
newMessages={newMessages}
archivedMessages={archivedMessages}
commandHandler={(input: string) => {
const { command, response } = handleCommand(
input,
waku,
setNick,
fleetEnv,
setFleetEnv
);
const commandMessages = response.map((msg) => {
return Message.fromUtf8String(command, msg);
});
setNewMessages(commandMessages);
}}
/>
</ThemeProvider>
</WakuContext.Provider>
2021-04-21 06:11:07 +00:00
</div>
);
2021-04-14 04:44:12 +00:00
}
async function initWaku(fleetEnv: Environment, setter: (waku: Waku) => void) {
2021-04-27 01:05:35 +00:00
try {
const waku = await Waku.create({
libp2p: {
config: {
pubsub: {
enabled: true,
emitSelf: true,
},
2021-04-27 01:05:35 +00:00
},
},
});
setter(waku);
const nodes = await getStatusFleetNodes(fleetEnv);
await Promise.all(
nodes.map((addr) => {
return waku.dial(addr);
})
2021-05-07 00:38:08 +00:00
);
2021-04-27 01:05:35 +00:00
} catch (e) {
console.log('Issue starting waku ', e);
}
}
function defaultFleetEnv() {
// Works with react-scripts
if (process?.env?.NODE_ENV === 'development') {
return Environment.Test;
} else {
return Environment.Prod;
}
}