react-peer-chat 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,6 +11,7 @@ A simple-to-use React component for implementing peer-to-peer chatting, powered
11
11
  - Option to clear chat on command
12
12
  - Supports audio/voice chat with automatic mixing for multiple peers
13
13
  - Multiple peer connections. See [multi-peer usage](#multi-peer-usage)
14
+ - Automatic reconnection handling for network interruptions
14
15
  - Fully customizable. See [usage with FaC](#full-customization)
15
16
 
16
17
  ## Installation
@@ -100,8 +101,9 @@ export default function App() {
100
101
  style: { padding: "4px" },
101
102
  }}
102
103
  props={{ title: "React Peer Chat Component" }}
103
- onError={() => console.error("Browser not supported!")}
104
- onMicError={() => console.error("Microphone not accessible!")}
104
+ onError={(error) => console.error("Fatal error:", error)}
105
+ onPeerError={(error) => console.error("Peer error:", error.type, error)}
106
+ onNetworkError={(error) => console.log("Reconnecting...")}
105
107
  />
106
108
  );
107
109
  }
@@ -120,8 +122,8 @@ export default function App() {
120
122
  name='John Doe'
121
123
  peerId='my-unique-id'
122
124
  remotePeerId='remote-unique-id'
123
- onError={() => console.error('Browser not supported!')}
124
- onMicError={() => console.error('Microphone not accessible!')}
125
+ onError={(error) => console.error('Fatal error:', error)}
126
+ onPeerError={(error) => console.error('Peer error:', error.type, error)}
125
127
  >
126
128
  {({ remotePeers, messages, sendMessage, audio, setAudio }) => (
127
129
  <YourCustomComponent>
@@ -293,19 +295,20 @@ export default function App() {
293
295
 
294
296
  Here is the full API for the `useChat` hook, these options can be passed as parameters to the hook:
295
297
 
296
- | Parameter | Type | Required | Default | Description |
297
- | ------------------- | --------------------------------------------- | -------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
298
- | `name` | `string` | No | Anonymous User | Name of the peer which will be shown to the remote peer. |
299
- | `peerId` | `string` | Yes | - | It is the unique id that is alloted to a peer. It uniquely identifies a peer from other peers. |
300
- | `remotePeerId` | `string \| string[]` | No | - | Unique id(s) of remote peer(s) to connect to. Read at mount and when `peerId` changes; changes to this prop alone won't create new connections. |
301
- | `text` | `boolean` | No | `true` | Text chat will be enabled if this property is set to true. |
302
- | `recoverChat` | `boolean` | No | `false` | Old chats will be recovered upon reconnecting with the same peer(s). |
303
- | `audio` | `boolean` | No | `true` | Voice chat will be enabled if this property is set to true. Audio from multiple peers is automatically mixed. |
304
- | `peerOptions` | [`PeerOptions`](#peeroptions) | No | - | Options to customize peerjs Peer instance. |
305
- | `onError` | [`ErrorHandler`](#errorhandler) | No | `() => alert('Browser not supported! Try some other browser.')` | Function to be executed if browser doesn't support `WebRTC` |
306
- | `onMicError` | [`ErrorHandler`](#errorhandler) | No | `() => alert('Microphone not accessible!')` | Function to be executed when microphone is not accessible. |
307
- | `onMessageSent` | [`MessageEventHandler`](#messageeventhandler) | No | - | Function to be executed when a text message is sent to other peers. |
308
- | `onMessageReceived` | [`MessageEventHandler`](#messageeventhandler) | No | - | Function to be executed when a text message is received from other peers. |
298
+ | Parameter | Type | Required | Default | Description |
299
+ | ------------------- | --------------------------------------------- | -------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
300
+ | `name` | `string` | No | Anonymous User | Name of the peer which will be shown to the remote peer. |
301
+ | `peerId` | `string` | Yes | - | It is the unique id that is alloted to a peer. It uniquely identifies a peer from other peers. |
302
+ | `remotePeerId` | `string \| string[]` | No | - | Unique id(s) of remote peer(s) to connect to. Read at mount and when `peerId` changes; changes to this prop alone won't create new connections. |
303
+ | `text` | `boolean` | No | `true` | Text chat will be enabled if this property is set to true. |
304
+ | `recoverChat` | `boolean` | No | `false` | Old chats will be recovered upon reconnecting with the same peer(s). |
305
+ | `audio` | `boolean` | No | `true` | Voice chat will be enabled if this property is set to true. Audio from multiple peers is automatically mixed. |
306
+ | `peerOptions` | [`PeerOptions`](#peeroptions) | No | - | Options to customize peerjs Peer instance. |
307
+ | `onError` | [`ErrorHandler`](#errorhandler) | No | `console.error` | Function to be executed for fatal errors (browser not supported, microphone not accessible). |
308
+ | `onPeerError` | [`PeerErrorHandler`](#peererrorhandler) | No | `console.error` | Function to be executed for all peer runtime errors. The library automatically handles reconnection for network errors. |
309
+ | `onNetworkError` | [`PeerErrorHandler`](#peererrorhandler) | No | - | Function to be executed for network/server errors (which trigger automatic reconnection). Useful for showing "reconnecting..." UI. |
310
+ | `onMessageSent` | [`MessageEventHandler`](#messageeventhandler) | No | - | Function to be executed when a text message is sent to other peers. |
311
+ | `onMessageReceived` | [`MessageEventHandler`](#messageeventhandler) | No | - | Function to be executed when a text message is received from other peers. |
309
312
 
310
313
  ### Chat Component
311
314
 
@@ -363,7 +366,15 @@ type DivProps = DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement
363
366
  ### ErrorHandler
364
367
 
365
368
  ```typescript
366
- type ErrorHandler = () => void;
369
+ type ErrorHandler = (error: Error) => void;
370
+ ```
371
+
372
+ ### PeerErrorHandler
373
+
374
+ ```typescript
375
+ import type { PeerError, PeerErrorType } from "peerjs";
376
+
377
+ export type PeerErrorHandler = ErrorHandler<PeerError<`${PeerErrorType}`>>;
367
378
  ```
368
379
 
369
380
  ### MessageEventHandler
@@ -384,4 +395,4 @@ import type { PeerOptions } from "peerjs";
384
395
 
385
396
  ## License
386
397
 
387
- This project is licensed under the [MIT License](LICENSE).
398
+ This project is licensed under the [MIT License](LICENSE)
@@ -1,4 +1,4 @@
1
- import { useChat } from './chunk-L3CFU5IB.js';
1
+ import { useChat } from './chunk-FBLX5IM6.js';
2
2
  import { BiSolidMessageX, BiSolidMessageDetail, GrSend, BsFillMicFill, BsFillMicMuteFill } from './chunk-JJPIWKLG.js';
3
3
  import { __objRest, __spreadValues } from './chunk-LNEKYYG7.js';
4
4
  import React, { useRef, useState, useEffect } from 'react';
@@ -56,8 +56,9 @@ function useChat({
56
56
  text = true,
57
57
  recoverChat = false,
58
58
  audio: allowed = true,
59
- onError = () => alert("Browser not supported! Try some other browser."),
60
- onMicError = () => alert("Microphone not accessible!"),
59
+ onError = console.error,
60
+ onPeerError = console.error,
61
+ onNetworkError,
61
62
  onMessageSent,
62
63
  onMessageReceived
63
64
  }) {
@@ -113,9 +114,9 @@ function useChat({
113
114
  });
114
115
  conn.on("close", conn.removeAllListeners);
115
116
  }
116
- function handleError() {
117
+ function handleMediaError() {
117
118
  setAudio(false);
118
- onMicError();
119
+ onError(new Error("Microphone not accessible!"));
119
120
  }
120
121
  function receiveMessage(message) {
121
122
  addMessage(message);
@@ -141,9 +142,17 @@ function useChat({
141
142
  supports: { audioVideo, data }
142
143
  }
143
144
  }) => {
144
- if (!data || !audioVideo) return onError();
145
+ if (!data || !audioVideo) return onError(new Error("Browser not supported! Try some other browser."));
145
146
  const peer2 = new Peer(completePeerId, __spreadValues({ config: defaultConfig }, peerOptions));
146
147
  peer2.on("connection", handleConnection);
148
+ peer2.on("disconnected", () => peer2.reconnect());
149
+ peer2.on("error", (error) => {
150
+ if (error.type === "network" || error.type === "server-error") {
151
+ setTimeout(() => peer2.reconnect(), 1e3);
152
+ onNetworkError == null ? void 0 : onNetworkError(error);
153
+ }
154
+ onPeerError(error);
155
+ });
147
156
  setPeer(peer2);
148
157
  }
149
158
  );
@@ -159,8 +168,9 @@ function useChat({
159
168
  if (!text || !peer) return;
160
169
  const handleOpen = () => completeRemotePeerIds.forEach((id) => handleConnection(peer.connect(id)));
161
170
  if (peer.open) handleOpen();
162
- else peer.once("open", handleOpen);
171
+ peer.on("open", handleOpen);
163
172
  return () => {
173
+ peer.off("open", handleOpen);
164
174
  Object.values(connRef.current).forEach(closeConnection);
165
175
  connRef.current = {};
166
176
  };
@@ -168,30 +178,35 @@ function useChat({
168
178
  useEffect(() => {
169
179
  if (!audio || !peer) return;
170
180
  let localStream;
171
- const setupAudio = () => navigator.mediaDevices.getUserMedia({
172
- video: false,
173
- audio: {
174
- autoGainControl: true,
175
- noiseSuppression: true,
176
- echoCancellation: true
177
- }
178
- }).then((stream) => {
179
- localStream = stream;
180
- completeRemotePeerIds.forEach((id) => {
181
- if (callsRef.current[id]) return;
182
- const call = peer.call(id, stream);
183
- handleCall(call);
184
- });
185
- peer.on("call", (call) => {
186
- if (callsRef.current[call.peer]) return call.close();
187
- call.answer(stream);
188
- handleCall(call);
189
- });
190
- }).catch(handleError);
181
+ const setupAudio = () => {
182
+ if (!navigator.mediaDevices) return handleMediaError();
183
+ navigator.mediaDevices.getUserMedia({
184
+ video: false,
185
+ audio: {
186
+ autoGainControl: true,
187
+ noiseSuppression: true,
188
+ echoCancellation: true
189
+ }
190
+ }).then((stream) => {
191
+ localStream = stream;
192
+ completeRemotePeerIds.forEach((id) => {
193
+ if (callsRef.current[id]) return;
194
+ const call = peer.call(id, stream);
195
+ handleCall(call);
196
+ });
197
+ peer.on("call", (call) => {
198
+ if (callsRef.current[call.peer]) return call.close();
199
+ call.answer(stream);
200
+ handleCall(call);
201
+ });
202
+ }).catch(handleMediaError);
203
+ };
191
204
  if (peer.open) setupAudio();
192
- else peer.once("open", setupAudio);
205
+ peer.on("open", setupAudio);
193
206
  return () => {
194
207
  var _a;
208
+ peer.off("open", setupAudio);
209
+ peer.off("call");
195
210
  localStream == null ? void 0 : localStream.getTracks().forEach((track) => track.stop());
196
211
  Object.values(callsRef.current).forEach(closeConnection);
197
212
  callsRef.current = {};
@@ -1,5 +1,5 @@
1
- export { Chat as default } from './chunks/chunk-OB5LLPQI.js';
2
- import './chunks/chunk-L3CFU5IB.js';
1
+ export { Chat as default } from './chunks/chunk-6JONVNJK.js';
2
+ import './chunks/chunk-FBLX5IM6.js';
3
3
  import './chunks/chunk-JJPIWKLG.js';
4
4
  import './chunks/chunk-ZYFPSCFE.js';
5
5
  import './chunks/chunk-LNEKYYG7.js';
package/dist/hooks.d.ts CHANGED
@@ -2,7 +2,7 @@ import { SetStateAction } from 'react';
2
2
  import { UseChatProps, UseChatReturn, Message } from './types.js';
3
3
  import 'peerjs';
4
4
 
5
- declare function useChat({ peerId, name, remotePeerId, peerOptions, text, recoverChat, audio: allowed, onError, onMicError, onMessageSent, onMessageReceived, }: UseChatProps): UseChatReturn;
5
+ declare function useChat({ peerId, name, remotePeerId, peerOptions, text, recoverChat, audio: allowed, onError, onPeerError, onNetworkError, onMessageSent, onMessageReceived, }: UseChatProps): UseChatReturn;
6
6
  declare function useMessages(): readonly [Message[], (value: SetStateAction<Message[]>) => void, (message: Message) => void];
7
7
  declare function useStorage<T>(key: string, initialValue: T, local?: boolean): readonly [T, (value: SetStateAction<T>) => void];
8
8
  declare function useStorage<T>(key: string, initialValue?: T, local?: boolean): readonly [T | undefined, (value: SetStateAction<T | undefined>) => void];
package/dist/hooks.js CHANGED
@@ -1,3 +1,3 @@
1
- export { useAudio, useChat, useMessages, useStorage } from './chunks/chunk-L3CFU5IB.js';
1
+ export { useAudio, useChat, useMessages, useStorage } from './chunks/chunk-FBLX5IM6.js';
2
2
  import './chunks/chunk-ZYFPSCFE.js';
3
3
  import './chunks/chunk-LNEKYYG7.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export { Chat as default } from './chunks/chunk-OB5LLPQI.js';
2
- export { useChat } from './chunks/chunk-L3CFU5IB.js';
1
+ export { Chat as default } from './chunks/chunk-6JONVNJK.js';
2
+ export { useChat } from './chunks/chunk-FBLX5IM6.js';
3
3
  import './chunks/chunk-JJPIWKLG.js';
4
4
  export { clearChat } from './chunks/chunk-ZYFPSCFE.js';
5
5
  import './chunks/chunk-LNEKYYG7.js';
package/dist/types.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { PeerOptions, DataConnection, MediaConnection } from 'peerjs';
1
+ import { PeerOptions, PeerError, PeerErrorType, DataConnection, MediaConnection } from 'peerjs';
2
2
  export { PeerOptions } from 'peerjs';
3
3
  import { CSSProperties, DetailedHTMLProps, HTMLAttributes, SetStateAction, ReactNode } from 'react';
4
4
 
5
5
  type Connection = DataConnection | MediaConnection;
6
- type ErrorHandler = () => void;
6
+ type ErrorHandler<E = Error> = (error: E) => void;
7
7
  type InputMessage = {
8
8
  id: string;
9
9
  text: string;
@@ -12,6 +12,7 @@ type Message = InputMessage & {
12
12
  name: string;
13
13
  };
14
14
  type MessageEventHandler = (message: Message) => void;
15
+ type PeerErrorHandler = ErrorHandler<PeerError<`${PeerErrorType}`>>;
15
16
 
16
17
  type RemotePeerId = string | string[];
17
18
  type UseChatProps = {
@@ -23,7 +24,8 @@ type UseChatProps = {
23
24
  audio?: boolean;
24
25
  peerOptions?: PeerOptions;
25
26
  onError?: ErrorHandler;
26
- onMicError?: ErrorHandler;
27
+ onPeerError?: PeerErrorHandler;
28
+ onNetworkError?: PeerErrorHandler;
27
29
  onMessageSent?: MessageEventHandler;
28
30
  onMessageReceived?: MessageEventHandler;
29
31
  };
@@ -52,4 +54,4 @@ type DialogPosition = "left" | "center" | "right";
52
54
  type DivProps = DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
53
55
  type RemotePeers = Record<string, string>;
54
56
 
55
- export type { ChatProps, Children, ChildrenOptions, Connection, DialogOptions, DialogPosition, DivProps, ErrorHandler, IconProps, InputMessage, Message, MessageEventHandler, RemotePeerId, RemotePeers, UseChatProps, UseChatReturn };
57
+ export type { ChatProps, Children, ChildrenOptions, Connection, DialogOptions, DialogPosition, DivProps, ErrorHandler, IconProps, InputMessage, Message, MessageEventHandler, PeerErrorHandler, RemotePeerId, RemotePeers, UseChatProps, UseChatReturn };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-peer-chat",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "An easy to use react component for impleting peer-to-peer chatting.",
5
5
  "license": "MIT",
6
6
  "author": "Sahil Aggarwal <aggarwalsahil2004@gmail.com>",