@dotwire/react 0.0.0-stage → 0.2.1
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/LICENSE +176 -0
- package/README.md +133 -2
- package/dist/index.cjs +340 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +146 -0
- package/dist/index.d.ts +146 -0
- package/dist/index.js +301 -0
- package/dist/index.js.map +1 -0
- package/package.json +55 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or exemplary damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
CHANGED
|
@@ -1,3 +1,134 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dotwire/react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
For coding agents adding dotwire to an application, see the [SDK integration guide](https://github.com/pasztor-mark/dotwire/blob/main/docs/SDK_AGENT_GUIDE.md).
|
|
4
|
+
|
|
5
|
+
React hooks and a provider for [`@dotwire/client`](https://www.npmjs.com/package/@dotwire/client), the TypeScript/JavaScript SDK
|
|
6
|
+
for **dotwire**, the high-throughput, self-hosted real-time messaging infrastructure.
|
|
7
|
+
|
|
8
|
+
[](https://github.com/pasztor-mark/dotwire)
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @dotwire/react @dotwire/client react
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`react` (>= 18) and `@dotwire/client` are peer dependencies — install them alongside this
|
|
17
|
+
package. Every export in this package is client-only (it uses hooks and context); the bundle
|
|
18
|
+
carries a `"use client"` banner for React Server Components frameworks.
|
|
19
|
+
|
|
20
|
+
## Quickstart
|
|
21
|
+
|
|
22
|
+
```tsx
|
|
23
|
+
import { DotwireProvider, useRoom, useTyping, usePresence, useConnectionState } from '@dotwire/react';
|
|
24
|
+
|
|
25
|
+
const dotwireOptions = {
|
|
26
|
+
baseUrl: 'https://chat.yourdomain.com',
|
|
27
|
+
tokenUrl: '/api/auth/token'
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function App() {
|
|
31
|
+
return (
|
|
32
|
+
<DotwireProvider options={dotwireOptions}>
|
|
33
|
+
<Room roomId="a0000000-0000-0000-0000-000000000001" />
|
|
34
|
+
</DotwireProvider>
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function Room({ roomId }: { roomId: string }) {
|
|
39
|
+
const connectionState = useConnectionState();
|
|
40
|
+
const { messages, status, hasMore, loadOlder, send } = useRoom(roomId, { history: 50 });
|
|
41
|
+
const { typingUsers, notifyTyping, stopTyping } = useTyping(roomId);
|
|
42
|
+
const { present } = usePresence(roomId);
|
|
43
|
+
|
|
44
|
+
return (
|
|
45
|
+
<div>
|
|
46
|
+
<p>Connection: {connectionState}</p>
|
|
47
|
+
<p>Room: {status}</p>
|
|
48
|
+
{hasMore && <button onClick={loadOlder}>Load older</button>}
|
|
49
|
+
<ul>
|
|
50
|
+
{messages.map((m) => (
|
|
51
|
+
<li key={m.seq}>
|
|
52
|
+
#{m.seq} {m.senderId}: {m.content}
|
|
53
|
+
</li>
|
|
54
|
+
))}
|
|
55
|
+
</ul>
|
|
56
|
+
<p>Typing: {typingUsers.join(', ') || '—'}</p>
|
|
57
|
+
<p>Present: {present.join(', ') || '—'}</p>
|
|
58
|
+
<input
|
|
59
|
+
onChange={() => notifyTyping()}
|
|
60
|
+
onBlur={() => stopTyping()}
|
|
61
|
+
onKeyDown={(e) => {
|
|
62
|
+
if (e.key === 'Enter') {
|
|
63
|
+
void send(e.currentTarget.value);
|
|
64
|
+
e.currentTarget.value = '';
|
|
65
|
+
}
|
|
66
|
+
}}
|
|
67
|
+
/>
|
|
68
|
+
</div>
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## `<DotwireProvider>`
|
|
74
|
+
|
|
75
|
+
```tsx
|
|
76
|
+
<DotwireProvider options={dotwireOptions}>...</DotwireProvider>
|
|
77
|
+
// or, if you already manage a DotwireClient yourself:
|
|
78
|
+
<DotwireProvider client={existingClient}>...</DotwireProvider>
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- Give it `options` (a `DotwireClientOptions`, same shape as `new DotwireClient(options)`) and
|
|
82
|
+
it constructs and disposes the client for you. Construction happens inside a `useEffect`, so
|
|
83
|
+
it is safe to render `DotwireProvider` on the server (`react-dom/server`) — nothing
|
|
84
|
+
browser-only runs during the render pass itself. Pass a stable `options` reference (e.g. a
|
|
85
|
+
module-level constant, or memoized with `useMemo`/`useState`) — a new object identity on
|
|
86
|
+
every render tears down and rebuilds the client.
|
|
87
|
+
- Give it `client` instead and it never constructs or disposes anything — you own that
|
|
88
|
+
instance's lifecycle (including calling `client.dispose()` yourself).
|
|
89
|
+
- `useDotwireClient()` returns `null` until the provider's effect has produced a client (always
|
|
90
|
+
the case during SSR, and briefly on first client-side render).
|
|
91
|
+
|
|
92
|
+
## Hooks
|
|
93
|
+
|
|
94
|
+
- **`useDotwireClient()`** → `DotwireClient | null`.
|
|
95
|
+
Use `client.room(roomId).getParticipants()` to fetch member IDs, then resolve names and avatars through the host app.
|
|
96
|
+
- **`useConnectionState()`** → the client's live `ConnectionState`
|
|
97
|
+
(`'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'disconnecting'`).
|
|
98
|
+
- **`useRoom(roomId, { history = 50 })`** → `{ messages, status, error, hasMore, loadOlder, send }`.
|
|
99
|
+
Subscribes for the lifetime of the component, loads the initial history page, and applies
|
|
100
|
+
live messages, retractions, and revocation. `messages` is always sorted by `seq` and deduped.
|
|
101
|
+
`status` starts `'connecting'`, becomes `'ready'` once the initial subscribe resolves,
|
|
102
|
+
`'revoked'` on membership revocation, or `'error'` if subscribe/send throws. `loadOlder()`
|
|
103
|
+
pages backwards with `beforeSeq` and prepends the results; `hasMore` reflects whether an
|
|
104
|
+
older page might still exist. `send(content)` wraps `sendMessage`.
|
|
105
|
+
- **`useTyping(roomId)`** → `{ typingUsers, notifyTyping, stopTyping }`. A user drops out of
|
|
106
|
+
`typingUsers` either on an explicit "stopped typing" notification or after ~3.5s of silence
|
|
107
|
+
(time-based expiry, checked every second).
|
|
108
|
+
- **`usePresence(roomId)`** → `{ present }`, accumulated from `joined`/`left` deltas since this
|
|
109
|
+
hook mounted. **There is no presence snapshot endpoint on the server** — a component that
|
|
110
|
+
mounts this hook after other members already joined will not see them in `present` until the
|
|
111
|
+
*next* delta for that room (the next join or leave).
|
|
112
|
+
|
|
113
|
+
## Architecture
|
|
114
|
+
|
|
115
|
+
All state transitions (new message, retraction, revocation, typing start/stop/expiry, presence
|
|
116
|
+
deltas) live in pure, framework-free reducer functions in `src/reducers.ts` — each is unit
|
|
117
|
+
tested directly with Node's test runner (`test/reducers.test.ts`), with no React or DOM
|
|
118
|
+
involved. The hooks in `src/hooks.ts` are thin `useReducer` wrappers that wire the underlying
|
|
119
|
+
`DotwireClient`/room event callbacks to `dispatch` calls.
|
|
120
|
+
|
|
121
|
+
`useRoom`, `useTyping`, and `usePresence` can be mounted together for the same `roomId` (e.g. a
|
|
122
|
+
message list plus a typing indicator). `DotwireClient.subscribe`/`unsubscribe` track hub-group
|
|
123
|
+
membership per room without a refcount, so this package refcounts "leave the room" intent
|
|
124
|
+
itself (`src/subscription.ts`) — the underlying hub group is only actually left once every hook
|
|
125
|
+
watching that room has unmounted.
|
|
126
|
+
|
|
127
|
+
There is a `react-dom/server` smoke test (`test/ssr.test.tsx`) asserting `DotwireProvider`
|
|
128
|
+
renders without throwing when no browser APIs are available. Full DOM-based hook tests (e.g.
|
|
129
|
+
with `jsdom`) are intentionally not included — add a DOM testing library of your choice if you
|
|
130
|
+
want them.
|
|
131
|
+
|
|
132
|
+
## License
|
|
133
|
+
|
|
134
|
+
Apache-2.0
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.ts
|
|
22
|
+
var index_exports = {};
|
|
23
|
+
__export(index_exports, {
|
|
24
|
+
DotwireContext: () => DotwireContext,
|
|
25
|
+
DotwireProvider: () => DotwireProvider,
|
|
26
|
+
initialPresenceState: () => initialPresenceState,
|
|
27
|
+
initialRoomMessagesState: () => initialRoomMessagesState,
|
|
28
|
+
initialTypingState: () => initialTypingState,
|
|
29
|
+
presenceReducer: () => presenceReducer,
|
|
30
|
+
roomMessagesReducer: () => roomMessagesReducer,
|
|
31
|
+
typingReducer: () => typingReducer,
|
|
32
|
+
typingUsersOf: () => typingUsersOf,
|
|
33
|
+
useConnectionState: () => useConnectionState,
|
|
34
|
+
useDotwireClient: () => useDotwireClient,
|
|
35
|
+
usePresence: () => usePresence,
|
|
36
|
+
useRoom: () => useRoom,
|
|
37
|
+
useTyping: () => useTyping
|
|
38
|
+
});
|
|
39
|
+
module.exports = __toCommonJS(index_exports);
|
|
40
|
+
|
|
41
|
+
// src/provider.tsx
|
|
42
|
+
var import_react = require("react");
|
|
43
|
+
var import_client = require("@dotwire/client");
|
|
44
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
45
|
+
var DotwireContext = (0, import_react.createContext)(null);
|
|
46
|
+
function DotwireProvider(props) {
|
|
47
|
+
const { children, options, client: providedClient } = props;
|
|
48
|
+
const [managedClient, setManagedClient] = (0, import_react.useState)(null);
|
|
49
|
+
(0, import_react.useEffect)(() => {
|
|
50
|
+
if (providedClient || !options) {
|
|
51
|
+
return void 0;
|
|
52
|
+
}
|
|
53
|
+
const instance = new import_client.DotwireClient(options);
|
|
54
|
+
setManagedClient(instance);
|
|
55
|
+
return () => {
|
|
56
|
+
instance.dispose();
|
|
57
|
+
setManagedClient((current) => current === instance ? null : current);
|
|
58
|
+
};
|
|
59
|
+
}, [providedClient, options]);
|
|
60
|
+
const client = providedClient ?? managedClient;
|
|
61
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DotwireContext.Provider, { value: client, children });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/hooks.ts
|
|
65
|
+
var import_react2 = require("react");
|
|
66
|
+
|
|
67
|
+
// src/reducers.ts
|
|
68
|
+
var initialRoomMessagesState = {
|
|
69
|
+
messages: [],
|
|
70
|
+
status: "connecting",
|
|
71
|
+
error: null,
|
|
72
|
+
hasMore: false
|
|
73
|
+
};
|
|
74
|
+
function mergeMessages(existing, incoming) {
|
|
75
|
+
if (incoming.length === 0) return existing;
|
|
76
|
+
const last = existing[existing.length - 1];
|
|
77
|
+
if (incoming.length === 1 && (last === void 0 || incoming[0].seq > last.seq)) return [...existing, incoming[0]];
|
|
78
|
+
const bySeq = /* @__PURE__ */ new Map();
|
|
79
|
+
for (const message of existing) bySeq.set(message.seq, message);
|
|
80
|
+
for (const message of incoming) bySeq.set(message.seq, message);
|
|
81
|
+
return Array.from(bySeq.values()).sort((a, b) => a.seq - b.seq);
|
|
82
|
+
}
|
|
83
|
+
function roomMessagesReducer(state, action) {
|
|
84
|
+
switch (action.type) {
|
|
85
|
+
case "reset":
|
|
86
|
+
return initialRoomMessagesState;
|
|
87
|
+
case "subscribed":
|
|
88
|
+
return {
|
|
89
|
+
messages: mergeMessages(state.messages, action.page.messages),
|
|
90
|
+
status: "ready",
|
|
91
|
+
error: null,
|
|
92
|
+
hasMore: action.page.hasMore
|
|
93
|
+
};
|
|
94
|
+
case "message":
|
|
95
|
+
return { ...state, messages: mergeMessages(state.messages, [action.message]) };
|
|
96
|
+
case "retracted":
|
|
97
|
+
return { ...state, messages: state.messages.filter((m) => m.seq !== action.seq) };
|
|
98
|
+
case "revoked":
|
|
99
|
+
return { ...state, status: "revoked" };
|
|
100
|
+
case "error":
|
|
101
|
+
return { ...state, status: "error", error: action.error };
|
|
102
|
+
case "olderLoaded":
|
|
103
|
+
return {
|
|
104
|
+
...state,
|
|
105
|
+
messages: mergeMessages(state.messages, action.page.messages),
|
|
106
|
+
hasMore: action.page.hasMore
|
|
107
|
+
};
|
|
108
|
+
default:
|
|
109
|
+
return state;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
var initialTypingState = {};
|
|
113
|
+
function typingReducer(state, action) {
|
|
114
|
+
switch (action.type) {
|
|
115
|
+
case "notification": {
|
|
116
|
+
if (action.isTyping) {
|
|
117
|
+
return { ...state, [action.userId]: { updatedAt: action.now } };
|
|
118
|
+
}
|
|
119
|
+
if (!(action.userId in state)) return state;
|
|
120
|
+
const next = { ...state };
|
|
121
|
+
delete next[action.userId];
|
|
122
|
+
return next;
|
|
123
|
+
}
|
|
124
|
+
case "expire": {
|
|
125
|
+
let changed = false;
|
|
126
|
+
const next = {};
|
|
127
|
+
for (const [userId, entry] of Object.entries(state)) {
|
|
128
|
+
if (action.now - entry.updatedAt < action.ttlMs) {
|
|
129
|
+
next[userId] = entry;
|
|
130
|
+
} else {
|
|
131
|
+
changed = true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return changed ? next : state;
|
|
135
|
+
}
|
|
136
|
+
default:
|
|
137
|
+
return state;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function typingUsersOf(state) {
|
|
141
|
+
return Object.keys(state);
|
|
142
|
+
}
|
|
143
|
+
var initialPresenceState = [];
|
|
144
|
+
function presenceReducer(state, action) {
|
|
145
|
+
const set = new Set(state);
|
|
146
|
+
for (const id of action.left) set.delete(id);
|
|
147
|
+
for (const id of action.joined) set.add(id);
|
|
148
|
+
return Array.from(set).sort();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// src/subscription.ts
|
|
152
|
+
var refCounts = /* @__PURE__ */ new WeakMap();
|
|
153
|
+
function retainRoom(client, roomId) {
|
|
154
|
+
let rooms = refCounts.get(client);
|
|
155
|
+
if (!rooms) {
|
|
156
|
+
rooms = /* @__PURE__ */ new Map();
|
|
157
|
+
refCounts.set(client, rooms);
|
|
158
|
+
}
|
|
159
|
+
rooms.set(roomId, (rooms.get(roomId) ?? 0) + 1);
|
|
160
|
+
}
|
|
161
|
+
function releaseRoom(client, roomId) {
|
|
162
|
+
const rooms = refCounts.get(client);
|
|
163
|
+
if (!rooms) return true;
|
|
164
|
+
const next = (rooms.get(roomId) ?? 1) - 1;
|
|
165
|
+
if (next <= 0) {
|
|
166
|
+
rooms.delete(roomId);
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
rooms.set(roomId, next);
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/hooks.ts
|
|
174
|
+
function useDotwireClient() {
|
|
175
|
+
return (0, import_react2.useContext)(DotwireContext);
|
|
176
|
+
}
|
|
177
|
+
function useConnectionState() {
|
|
178
|
+
const client = useDotwireClient();
|
|
179
|
+
const [state, setState] = (0, import_react2.useState)(() => client?.getConnectionState() ?? "disconnected");
|
|
180
|
+
(0, import_react2.useEffect)(() => {
|
|
181
|
+
if (!client) {
|
|
182
|
+
setState("disconnected");
|
|
183
|
+
return void 0;
|
|
184
|
+
}
|
|
185
|
+
setState(client.getConnectionState());
|
|
186
|
+
return client.onStateChange(setState);
|
|
187
|
+
}, [client]);
|
|
188
|
+
return state;
|
|
189
|
+
}
|
|
190
|
+
function useRoom(roomId, options = {}) {
|
|
191
|
+
const history = options.history ?? 50;
|
|
192
|
+
const client = useDotwireClient();
|
|
193
|
+
const [state, dispatch] = (0, import_react2.useReducer)(roomMessagesReducer, initialRoomMessagesState);
|
|
194
|
+
const stateRef = (0, import_react2.useRef)(state);
|
|
195
|
+
stateRef.current = state;
|
|
196
|
+
const scopeRef = (0, import_react2.useRef)(null);
|
|
197
|
+
(0, import_react2.useEffect)(() => {
|
|
198
|
+
if (!client) return void 0;
|
|
199
|
+
const scope = {};
|
|
200
|
+
scopeRef.current = scope;
|
|
201
|
+
dispatch({ type: "reset" });
|
|
202
|
+
const room = client.room(roomId);
|
|
203
|
+
retainRoom(client, roomId);
|
|
204
|
+
let cancelled = false;
|
|
205
|
+
const unsubscribers = [
|
|
206
|
+
room.onMessage((message) => dispatch({ type: "message", message })),
|
|
207
|
+
room.onMessageRetracted(({ seq }) => dispatch({ type: "retracted", seq })),
|
|
208
|
+
room.onMembershipRevoked(() => dispatch({ type: "revoked" }))
|
|
209
|
+
];
|
|
210
|
+
room.subscribe({ history }).then((page) => {
|
|
211
|
+
if (cancelled) return;
|
|
212
|
+
dispatch({ type: "subscribed", page: page ?? { messages: [], hasMore: false } });
|
|
213
|
+
}).catch((error) => {
|
|
214
|
+
if (!cancelled) dispatch({ type: "error", error });
|
|
215
|
+
});
|
|
216
|
+
return () => {
|
|
217
|
+
cancelled = true;
|
|
218
|
+
if (scopeRef.current === scope) scopeRef.current = null;
|
|
219
|
+
for (const unsub of unsubscribers) unsub();
|
|
220
|
+
room.release();
|
|
221
|
+
if (releaseRoom(client, roomId)) {
|
|
222
|
+
client.unsubscribe(roomId).catch(() => {
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
}, [client, roomId, history]);
|
|
227
|
+
const loadOlder = (0, import_react2.useCallback)(async () => {
|
|
228
|
+
if (!client) return;
|
|
229
|
+
const oldest = stateRef.current.messages[0];
|
|
230
|
+
if (!oldest) return;
|
|
231
|
+
const scope = scopeRef.current;
|
|
232
|
+
try {
|
|
233
|
+
const page = await client.getHistory(roomId, { beforeSeq: oldest.seq, limit: history });
|
|
234
|
+
if (scopeRef.current === scope) dispatch({ type: "olderLoaded", page });
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (scopeRef.current === scope) dispatch({ type: "error", error });
|
|
237
|
+
}
|
|
238
|
+
}, [client, roomId, history]);
|
|
239
|
+
const send = (0, import_react2.useCallback)(
|
|
240
|
+
async (content) => {
|
|
241
|
+
if (!client) {
|
|
242
|
+
throw new Error("Dotwire client is not ready yet.");
|
|
243
|
+
}
|
|
244
|
+
try {
|
|
245
|
+
return await client.sendMessage(roomId, content);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
dispatch({ type: "error", error });
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
[client, roomId]
|
|
252
|
+
);
|
|
253
|
+
return {
|
|
254
|
+
messages: state.messages,
|
|
255
|
+
status: state.status,
|
|
256
|
+
error: state.error,
|
|
257
|
+
hasMore: state.hasMore,
|
|
258
|
+
loadOlder,
|
|
259
|
+
send
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
var TYPING_EXPIRY_MS = 3500;
|
|
263
|
+
var TYPING_EXPIRY_CHECK_INTERVAL_MS = 1e3;
|
|
264
|
+
function useTyping(roomId) {
|
|
265
|
+
const client = useDotwireClient();
|
|
266
|
+
const [state, dispatch] = (0, import_react2.useReducer)(typingReducer, initialTypingState);
|
|
267
|
+
const roomHandleRef = (0, import_react2.useRef)(null);
|
|
268
|
+
(0, import_react2.useEffect)(() => {
|
|
269
|
+
if (!client) return void 0;
|
|
270
|
+
const room = client.room(roomId);
|
|
271
|
+
roomHandleRef.current = room;
|
|
272
|
+
retainRoom(client, roomId);
|
|
273
|
+
room.subscribe().catch(() => {
|
|
274
|
+
});
|
|
275
|
+
const unsub = room.onTyping((notification) => {
|
|
276
|
+
dispatch({ type: "notification", userId: notification.userId, isTyping: notification.isTyping, now: Date.now() });
|
|
277
|
+
});
|
|
278
|
+
const interval = setInterval(() => {
|
|
279
|
+
dispatch({ type: "expire", now: Date.now(), ttlMs: TYPING_EXPIRY_MS });
|
|
280
|
+
}, TYPING_EXPIRY_CHECK_INTERVAL_MS);
|
|
281
|
+
return () => {
|
|
282
|
+
unsub();
|
|
283
|
+
clearInterval(interval);
|
|
284
|
+
roomHandleRef.current = null;
|
|
285
|
+
room.release();
|
|
286
|
+
if (releaseRoom(client, roomId)) {
|
|
287
|
+
client.unsubscribe(roomId).catch(() => {
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
}, [client, roomId]);
|
|
292
|
+
const notifyTyping = (0, import_react2.useCallback)(async () => {
|
|
293
|
+
await roomHandleRef.current?.notifyTyping();
|
|
294
|
+
}, []);
|
|
295
|
+
const stopTyping = (0, import_react2.useCallback)(async () => {
|
|
296
|
+
await roomHandleRef.current?.stopTyping();
|
|
297
|
+
}, []);
|
|
298
|
+
return { typingUsers: typingUsersOf(state), notifyTyping, stopTyping };
|
|
299
|
+
}
|
|
300
|
+
function usePresence(roomId) {
|
|
301
|
+
const client = useDotwireClient();
|
|
302
|
+
const [state, dispatch] = (0, import_react2.useReducer)(presenceReducer, initialPresenceState);
|
|
303
|
+
(0, import_react2.useEffect)(() => {
|
|
304
|
+
if (!client) return void 0;
|
|
305
|
+
const room = client.room(roomId);
|
|
306
|
+
retainRoom(client, roomId);
|
|
307
|
+
room.subscribe().catch(() => {
|
|
308
|
+
});
|
|
309
|
+
const unsub = room.onPresence((delta) => {
|
|
310
|
+
dispatch({ type: "delta", joined: delta.joined, left: delta.left });
|
|
311
|
+
});
|
|
312
|
+
return () => {
|
|
313
|
+
unsub();
|
|
314
|
+
room.release();
|
|
315
|
+
if (releaseRoom(client, roomId)) {
|
|
316
|
+
client.unsubscribe(roomId).catch(() => {
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
}, [client, roomId]);
|
|
321
|
+
return { present: state };
|
|
322
|
+
}
|
|
323
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
324
|
+
0 && (module.exports = {
|
|
325
|
+
DotwireContext,
|
|
326
|
+
DotwireProvider,
|
|
327
|
+
initialPresenceState,
|
|
328
|
+
initialRoomMessagesState,
|
|
329
|
+
initialTypingState,
|
|
330
|
+
presenceReducer,
|
|
331
|
+
roomMessagesReducer,
|
|
332
|
+
typingReducer,
|
|
333
|
+
typingUsersOf,
|
|
334
|
+
useConnectionState,
|
|
335
|
+
useDotwireClient,
|
|
336
|
+
usePresence,
|
|
337
|
+
useRoom,
|
|
338
|
+
useTyping
|
|
339
|
+
});
|
|
340
|
+
//# sourceMappingURL=index.cjs.map
|