@dammers/anchor-presence-react 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +140 -2
- package/dist/context-store.d.ts +8 -0
- package/dist/context-store.js +8 -0
- package/dist/context.d.ts +25 -0
- package/dist/context.js +10 -0
- package/dist/cursor.d.ts +66 -0
- package/dist/cursor.js +119 -0
- package/dist/hooks/index.d.ts +11 -0
- package/dist/hooks/index.js +10 -0
- package/dist/hooks/use-dom-binding.d.ts +9 -0
- package/dist/hooks/use-dom-binding.js +13 -0
- package/dist/hooks/use-local-context.d.ts +9 -0
- package/dist/hooks/use-local-context.js +25 -0
- package/dist/hooks/use-local-user.d.ts +9 -0
- package/dist/hooks/use-local-user.js +21 -0
- package/dist/hooks/use-peer-changes.d.ts +9 -0
- package/dist/hooks/use-peer-changes.js +19 -0
- package/dist/hooks/use-presence-client.d.ts +14 -0
- package/dist/hooks/use-presence-client.js +31 -0
- package/dist/hooks/use-presence-status.d.ts +8 -0
- package/dist/hooks/use-presence-status.js +17 -0
- package/dist/hooks/use-remote-cursors.d.ts +17 -0
- package/dist/hooks/use-remote-cursors.js +51 -0
- package/dist/hooks/use-remote-events.d.ts +9 -0
- package/dist/hooks/use-remote-events.js +19 -0
- package/dist/hooks/use-remote-presence.d.ts +10 -0
- package/dist/hooks/use-remote-presence.js +18 -0
- package/dist/hooks/use-remote-users.d.ts +21 -0
- package/dist/hooks/use-remote-users.js +77 -0
- package/dist/hooks/use-send-event.d.ts +8 -0
- package/dist/hooks/use-send-event.js +15 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +16 -0
- package/dist/provider.d.ts +50 -0
- package/dist/provider.js +96 -0
- package/dist/typed-hooks.d.ts +26 -0
- package/dist/typed-hooks.js +42 -0
- package/package.json +54 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DammersCode
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,141 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dammers/anchor-presence-react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@dammers/anchor-presence-react` is the React adapter for Anchor Presence. It gives you a provider component, a set of hooks, and two optional cursor components.
|
|
4
|
+
|
|
5
|
+
[](../../LICENSE)
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Install the adapter and the two packages that it uses:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
bun add @dammers/anchor-presence-react @dammers/anchor-presence-dom @dammers/anchor-presence-core
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The first sample uses the provider of `@dammers/anchor-presence-react`. The samples connect to the Bun relay of the [quick start](https://anchor-presence.vercel.app/docs/get-started/quick-start#connect-a-relay), on port 8788. This app creates the client in the provider `factory` and renders the remote cursors:
|
|
16
|
+
|
|
17
|
+
```tsx
|
|
18
|
+
import { createPresenceClient } from "@dammers/anchor-presence-core";
|
|
19
|
+
import { createWebSocketTransport } from "@dammers/anchor-presence-dom";
|
|
20
|
+
import { CursorLayer, PresenceProvider } from "@dammers/anchor-presence-react";
|
|
21
|
+
|
|
22
|
+
function DashboardButton() {
|
|
23
|
+
return <button data-anchor="nav.dashboard">Dashboard</button>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function App() {
|
|
27
|
+
return (
|
|
28
|
+
<PresenceProvider
|
|
29
|
+
factory={() => {
|
|
30
|
+
const transport = createWebSocketTransport({ port: 8788, path: "/?room=main" });
|
|
31
|
+
return createPresenceClient({ transport });
|
|
32
|
+
}}
|
|
33
|
+
>
|
|
34
|
+
<DashboardButton />
|
|
35
|
+
<CursorLayer />
|
|
36
|
+
</PresenceProvider>
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Boundary rule
|
|
42
|
+
|
|
43
|
+
`@dammers/anchor-presence-react` holds no cursor state of its own. It reads the `@dammers/anchor-presence-core` and `@dammers/anchor-presence-dom` stores with `useSyncExternalStore`. The package never touches the DOM at load time, so it is safe to import on a server.
|
|
44
|
+
|
|
45
|
+
## Main exports
|
|
46
|
+
|
|
47
|
+
The package exports these hooks and components:
|
|
48
|
+
|
|
49
|
+
| Hook or component | What it does |
|
|
50
|
+
| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
|
51
|
+
| `PresenceProvider` | Creates the client through `factory` or accepts one through `client`, and provides it with its `DomBinding` to the component tree |
|
|
52
|
+
| `useRemoteUsers()` | One entry per peer (another client in the same room): `clientId`, `user`, `session`, and `idle` |
|
|
53
|
+
| `useRemoteCursors()` | Resolved cursor snapshot for rendering |
|
|
54
|
+
| `useRemoteCursorsSelector(select, isEqual?)` | A derived value that rerenders only when it changes |
|
|
55
|
+
| `useRemotePresence()` | Raw remote presence list, stable per peer (without `sequence`) |
|
|
56
|
+
| `usePresenceStatus()` | Connection status |
|
|
57
|
+
| `usePresenceClient()` | The `PresenceClient` of the provider |
|
|
58
|
+
| `useDomBinding()` | The `DomBinding` of the provider, for example to call `invalidate()` |
|
|
59
|
+
| `useLocalContext()` | `[context, setContext]` |
|
|
60
|
+
| `useLocalUser()` | `[user, setUser]` for the local user value |
|
|
61
|
+
| `useRemoteEvents(listener)` | Calls `listener` for each one-shot event from a peer |
|
|
62
|
+
| `usePeerChanges(listener)` | Calls `listener` when a peer joins, leaves, or changes its `user` or `context` |
|
|
63
|
+
| `useSendEvent()` | A function that sends one-shot events |
|
|
64
|
+
| `createPresenceHooks()` | Returns a provider, every hook, and a `CursorLayer` with your context, user, and event types fixed |
|
|
65
|
+
| `CursorLayer` | Optional component that renders every visible remote cursor |
|
|
66
|
+
| `DefaultCursor` | Optional neutral cursor visual, used by `CursorLayer` by default |
|
|
67
|
+
|
|
68
|
+
## Hooks and render cost
|
|
69
|
+
|
|
70
|
+
A hook rerenders its component when the value that it returns changes, or when the provider value changes. `useSendEvent`, `usePresenceClient`, and `useDomBinding` rerender on any change of the provider value. Pick the hook that matches the value that you need.
|
|
71
|
+
|
|
72
|
+
| Hook | Rerenders when |
|
|
73
|
+
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
|
|
74
|
+
| `useRemoteCursors()` | the resolved-cursor snapshot changes (every cursor frame while cursors move) |
|
|
75
|
+
| `useRemoteCursorsSelector(select, isEqual?)` | only when the `select` output changes under `isEqual` |
|
|
76
|
+
| `useRemoteUsers()` | only when the set of peers, or the `user`, `session`, or `idle` field of one peer, changes |
|
|
77
|
+
| `useRemotePresence()` | only when the `cursor`, `context`, `user`, `pointer`, `session`, `idle`, or membership of a peer changes |
|
|
78
|
+
| `usePresenceStatus()` | only when the connection status changes |
|
|
79
|
+
| `useLocalContext()` | only when the local context value changes |
|
|
80
|
+
| `useLocalUser()` | only when the local user value changes |
|
|
81
|
+
|
|
82
|
+
Two more rules apply:
|
|
83
|
+
|
|
84
|
+
- A heartbeat that changes no field causes no rerender. A peer that turns idle or expires does cause one.
|
|
85
|
+
- A message that only advances `sequence` does not rerender `useRemotePresence` consumers. `sequence` is a wire-level ordering field and is not part of the stable snapshot. To read each `sequence` value, call `client.getRemoteSnapshot()` inside a `client.subscribeRemote()` callback.
|
|
86
|
+
|
|
87
|
+
`useRemoteCursors` rerenders every frame while cursors move. If your component needs less than the full snapshot, derive a smaller value with `useRemoteCursorsSelector`.
|
|
88
|
+
|
|
89
|
+
## Client lifecycle
|
|
90
|
+
|
|
91
|
+
Pass `PresenceProvider` a `factory`. The provider runs it once per mount, in an effect, and disposes the client that it created on unmount. It runs the factory only in the browser, so a server render creates no client. In development, React Strict Mode mounts the provider twice. The provider then creates two clients in sequence and disposes the first, so one live client remains. Before the effect runs, the provider renders its children with a `null` client, and every hook returns its server-safe value.
|
|
92
|
+
|
|
93
|
+
The sample in [Install](#install) creates the client in the factory.
|
|
94
|
+
|
|
95
|
+
The client connects the transport by default. To connect at a time that you choose, pass `autoConnect: false` to `createPresenceClient` and call `transport.connect()` yourself.
|
|
96
|
+
|
|
97
|
+
To bring your own client, pass the `client` prop instead. The provider then never disposes it. Call `dispose()` yourself, on an explicit user action such as logout. After `dispose()`, you cannot use the client again. Create a new client instead.
|
|
98
|
+
|
|
99
|
+
## Who is online
|
|
100
|
+
|
|
101
|
+
`useRemoteUsers` lists every peer. This component shows the number of peers in a presence bar:
|
|
102
|
+
|
|
103
|
+
```tsx
|
|
104
|
+
import { useRemoteUsers } from "@dammers/anchor-presence-react";
|
|
105
|
+
|
|
106
|
+
function OnlineBar() {
|
|
107
|
+
const users = useRemoteUsers();
|
|
108
|
+
return <span>{users.length} online</span>;
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`user` is the value that each peer passed to `createPresenceClient`, and it has the type `unknown` because a peer can send any value. This sample needs the provider of `@dammers/anchor-presence-react`. For a typed `user`, use the hooks of `createPresenceHooks` with the provider of the same call. Without `getLabel`, `CursorLayer` shows `user.name` when it is a string that is not empty. Without `getColor`, it picks one color per `clientId` from a palette of 8 colors. Check `user` before you render it.
|
|
113
|
+
|
|
114
|
+
## CursorLayer
|
|
115
|
+
|
|
116
|
+
`CursorLayer` is optional. It renders every visible remote cursor. You can style it with the props `getLabel`, `getColor`, `filterCursor`, and `getCursorProps`. You can replace its contents with `renderCursor`. This sample uses every prop. It takes `CursorLayer` from a `./presence` module that calls [`createPresenceHooks`](https://anchor-presence.vercel.app/docs/react/typed-hooks#usage) one time, so the app must use the `PresenceProvider` of that module:
|
|
117
|
+
|
|
118
|
+
```tsx
|
|
119
|
+
import { CursorLayer } from "./presence";
|
|
120
|
+
|
|
121
|
+
declare function MyCursorGlyph(props: { color: string; children: React.ReactNode }): React.JSX.Element;
|
|
122
|
+
|
|
123
|
+
const safeColor = (color?: string) =>
|
|
124
|
+
color !== undefined && /^#[0-9a-f]{6}$/iu.test(color) ? color : "#6b7280";
|
|
125
|
+
|
|
126
|
+
<CursorLayer
|
|
127
|
+
getLabel={(cursor) => cursor.user?.name ?? "Guest"}
|
|
128
|
+
getColor={(cursor) => safeColor(cursor.user?.color)}
|
|
129
|
+
filterCursor={(cursor) => cursor.tier !== "viewport"}
|
|
130
|
+
getCursorProps={() => ({ className: "my-cursor" })}
|
|
131
|
+
renderCursor={({ label, color }) => <MyCursorGlyph color={color}>{label}</MyCursorGlyph>}
|
|
132
|
+
zIndex={1000}
|
|
133
|
+
/>;
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
`CursorLayer` owns the position, the opacity, and the pointer events of each cursor element. A custom style or `renderCursor` cannot change them.
|
|
137
|
+
|
|
138
|
+
> [!WARNING]
|
|
139
|
+
> If you render `cursor.user`, check it first. A peer sends this data, and it can hold any value.
|
|
140
|
+
|
|
141
|
+
See the [React guide](https://anchor-presence.vercel.app/docs/react) for the full hook reference and more examples. For cursor motion, see [Motion](https://anchor-presence.vercel.app/docs/dom/motion).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PresenceClient } from "@dammers/anchor-presence-core";
|
|
2
|
+
type ContextStore<TContext> = {
|
|
3
|
+
getSnapshot(): TContext | undefined;
|
|
4
|
+
subscribe(listener: () => void): () => void;
|
|
5
|
+
setContext(next: TContext | undefined): void;
|
|
6
|
+
};
|
|
7
|
+
export declare function getContextStore<TContext, TUser, TEvents extends object>(client: PresenceClient<TContext, TUser, TEvents>): ContextStore<TContext>;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function getContextStore(client) {
|
|
2
|
+
// the client is the single notify source so a direct client.setContext() also reaches subscribers
|
|
3
|
+
return {
|
|
4
|
+
getSnapshot: () => client.getContext(),
|
|
5
|
+
subscribe: (listener) => client.subscribeContext(listener),
|
|
6
|
+
setContext: (next) => client.setContext(next),
|
|
7
|
+
};
|
|
8
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Context } from "react";
|
|
2
|
+
import type { EventMap, PresenceClient } from "@dammers/anchor-presence-core";
|
|
3
|
+
import type { DomBinding } from "@dammers/anchor-presence-dom";
|
|
4
|
+
/**
|
|
5
|
+
* The value the context carries.
|
|
6
|
+
*/
|
|
7
|
+
export type PresenceProviderValue<TContext = unknown, TUser = unknown, TEvents extends object = EventMap> = {
|
|
8
|
+
/** The presence client, or `null` when no provider is present or the client does not exist yet. */
|
|
9
|
+
client: PresenceClient<TContext, TUser, TEvents> | null;
|
|
10
|
+
/** The DOM binding, or `null` when none exists. */
|
|
11
|
+
binding: DomBinding<TContext, TUser> | null;
|
|
12
|
+
/** `true` while a provider `factory` has not created its client yet. */
|
|
13
|
+
clientPending?: boolean;
|
|
14
|
+
};
|
|
15
|
+
export type PresenceContext<TContext, TUser, TEvents extends object> = Context<PresenceProviderValue<TContext, TUser, TEvents>>;
|
|
16
|
+
/** The context value without a provider. Compare against it to detect a missing provider. */
|
|
17
|
+
export declare const PresenceProviderContextDefault: {
|
|
18
|
+
readonly client: null;
|
|
19
|
+
readonly binding: null;
|
|
20
|
+
};
|
|
21
|
+
export declare function createPresenceContext<TContext, TUser, TEvents extends object>(): PresenceContext<TContext, TUser, TEvents>;
|
|
22
|
+
/**
|
|
23
|
+
* The React context that carries the client and the binding.
|
|
24
|
+
*/
|
|
25
|
+
export declare const PresenceProviderContext: PresenceContext<unknown, unknown, EventMap>;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createContext } from "react";
|
|
2
|
+
/** The context value without a provider. Compare against it to detect a missing provider. */
|
|
3
|
+
export const PresenceProviderContextDefault = { client: null, binding: null };
|
|
4
|
+
export function createPresenceContext() {
|
|
5
|
+
return createContext(PresenceProviderContextDefault);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The React context that carries the client and the binding.
|
|
9
|
+
*/
|
|
10
|
+
export const PresenceProviderContext = createPresenceContext();
|
package/dist/cursor.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { ComponentPropsWithoutRef, CSSProperties, ReactNode } from "react";
|
|
2
|
+
import type { PointerType } from "@dammers/anchor-presence-core";
|
|
3
|
+
import { type ResolvedCursor } from "@dammers/anchor-presence-dom";
|
|
4
|
+
import type { PresenceContext } from "./context.js";
|
|
5
|
+
/**
|
|
6
|
+
* Props that `renderCursor` receives.
|
|
7
|
+
*/
|
|
8
|
+
export type CursorRenderProps<TContext = unknown, TUser = unknown> = {
|
|
9
|
+
/** The resolved cursor to render. */
|
|
10
|
+
cursor: ResolvedCursor<TContext, TUser>;
|
|
11
|
+
/** The label, from `getLabel`. `null` hides the label. */
|
|
12
|
+
label: ReactNode;
|
|
13
|
+
/** The color, from `getColor`. */
|
|
14
|
+
color: string;
|
|
15
|
+
/** The pointer type that moved the cursor. `undefined` when the sender sent no pointer type. */
|
|
16
|
+
pointerType?: PointerType | undefined;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Props for `CursorLayer`.
|
|
20
|
+
*/
|
|
21
|
+
export type CursorLayerProps<TContext = unknown, TUser = unknown> = {
|
|
22
|
+
/** Returns the label to show for one cursor. */
|
|
23
|
+
getLabel?: ((cursor: ResolvedCursor<TContext, TUser>) => ReactNode) | undefined;
|
|
24
|
+
/** Returns the color for one cursor. */
|
|
25
|
+
getColor?: ((cursor: ResolvedCursor<TContext, TUser>) => string) | undefined;
|
|
26
|
+
/** Hides a cursor when it returns `false`. Default: show every visible cursor. */
|
|
27
|
+
filterCursor?: ((cursor: ResolvedCursor<TContext, TUser>) => boolean) | undefined;
|
|
28
|
+
/** Returns extra props for the cursor element. */
|
|
29
|
+
getCursorProps?: ((cursor: ResolvedCursor<TContext, TUser>) => Omit<ComponentPropsWithoutRef<"div">, "children">) | undefined;
|
|
30
|
+
/** Renders one cursor. Default: the `DefaultCursor` component. */
|
|
31
|
+
renderCursor?: ((props: CursorRenderProps<TContext, TUser>) => ReactNode) | undefined;
|
|
32
|
+
/** The z-index for the cursor elements. Default `9999`. */
|
|
33
|
+
zIndex?: number | undefined;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Props for `DefaultCursor`.
|
|
37
|
+
*/
|
|
38
|
+
export type DefaultCursorProps = {
|
|
39
|
+
/** The label text to show next to the arrow. */
|
|
40
|
+
label?: ReactNode;
|
|
41
|
+
/** The arrow color. Default `#6b7280`. */
|
|
42
|
+
color?: string | undefined;
|
|
43
|
+
/** A class name for the outer element. */
|
|
44
|
+
className?: string | undefined;
|
|
45
|
+
/** Inline styles for the outer element. */
|
|
46
|
+
style?: (CSSProperties & Partial<Record<"--anchor-presence-cursor-color" | "--anchor-presence-cursor-size" | "--anchor-presence-cursor-label-color", string>>) | undefined;
|
|
47
|
+
/** A class name for the label element. */
|
|
48
|
+
labelClassName?: string | undefined;
|
|
49
|
+
/** Inline styles for the label element. */
|
|
50
|
+
labelStyle?: CSSProperties | undefined;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* The default cursor shape: an arrow with an optional label.
|
|
54
|
+
*/
|
|
55
|
+
export declare function DefaultCursor(props: DefaultCursorProps): ReactNode;
|
|
56
|
+
type CursorLayerInProps<TContext, TUser, TEvents extends object> = CursorLayerProps<TContext, TUser> & {
|
|
57
|
+
context: PresenceContext<TContext, TUser, TEvents>;
|
|
58
|
+
};
|
|
59
|
+
export declare function CursorLayerIn<TContext, TUser, TEvents extends object>(props: CursorLayerInProps<TContext, TUser, TEvents>): ReactNode;
|
|
60
|
+
/**
|
|
61
|
+
* Renders the visible remote cursors.
|
|
62
|
+
* The layer places each cursor at its resolved position.
|
|
63
|
+
* The `user` and `context` of a cursor have the type `unknown`. For typed render props, use `CursorLayer` from `createPresenceHooks`.
|
|
64
|
+
*/
|
|
65
|
+
export declare function CursorLayer(props: CursorLayerProps): ReactNode;
|
|
66
|
+
export {};
|
package/dist/cursor.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { memo, useCallback } from "react";
|
|
3
|
+
import { CURSOR_MARKER_ATTRIBUTE } from "@dammers/anchor-presence-dom";
|
|
4
|
+
import { PresenceProviderContext } from "./context.js";
|
|
5
|
+
import { useRemoteCursorsSelectorIn } from "./hooks/use-remote-cursors.js";
|
|
6
|
+
const DEFAULT_COLOR = "#6b7280";
|
|
7
|
+
const MAX_DEFAULT_LABEL_LENGTH = 32;
|
|
8
|
+
const DEFAULT_PALETTE = [
|
|
9
|
+
"#2563eb",
|
|
10
|
+
"#dc2626",
|
|
11
|
+
"#047857",
|
|
12
|
+
"#b45309",
|
|
13
|
+
"#7c3aed",
|
|
14
|
+
"#be185d",
|
|
15
|
+
"#0e7490",
|
|
16
|
+
"#4b5563",
|
|
17
|
+
];
|
|
18
|
+
const graphemeSegmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter(undefined, { granularity: "grapheme" }) : null;
|
|
19
|
+
function truncateLabel(name) {
|
|
20
|
+
const units = [];
|
|
21
|
+
const parts = graphemeSegmenter === null ? name : graphemeSegmenter.segment(name);
|
|
22
|
+
for (const part of parts) {
|
|
23
|
+
if (units.length === MAX_DEFAULT_LABEL_LENGTH)
|
|
24
|
+
break;
|
|
25
|
+
units.push(typeof part === "string" ? part : part.segment);
|
|
26
|
+
}
|
|
27
|
+
return units.join("");
|
|
28
|
+
}
|
|
29
|
+
function defaultLabel(cursor) {
|
|
30
|
+
const user = cursor.user;
|
|
31
|
+
const name = typeof user === "object" && user !== null && "name" in user ? user.name : undefined;
|
|
32
|
+
return typeof name === "string" && name !== "" ? truncateLabel(name) : null;
|
|
33
|
+
}
|
|
34
|
+
function defaultColor(cursor) {
|
|
35
|
+
let hash = 0;
|
|
36
|
+
for (const char of cursor.clientId)
|
|
37
|
+
hash = (hash * 31 + (char.codePointAt(0) ?? 0)) >>> 0;
|
|
38
|
+
return DEFAULT_PALETTE[hash % DEFAULT_PALETTE.length] ?? DEFAULT_COLOR;
|
|
39
|
+
}
|
|
40
|
+
const DEFAULT_Z_INDEX = 9999;
|
|
41
|
+
const IDLE_OPACITY = 0.4;
|
|
42
|
+
// JSX cannot name an attribute dynamically. The marker wins over consumer props.
|
|
43
|
+
const CURSOR_MARKER_PROPS = { [CURSOR_MARKER_ATTRIBUTE]: "" };
|
|
44
|
+
// One MediaQueryList per matchMedia implementation; .matches stays live, so no listener is needed.
|
|
45
|
+
let cachedMatchMedia;
|
|
46
|
+
let cachedReducedMotionQuery = null;
|
|
47
|
+
function prefersReducedMotion() {
|
|
48
|
+
const matchMedia = typeof window !== "undefined" ? window.matchMedia : undefined;
|
|
49
|
+
if (matchMedia !== cachedMatchMedia) {
|
|
50
|
+
cachedMatchMedia = matchMedia;
|
|
51
|
+
cachedReducedMotionQuery =
|
|
52
|
+
typeof matchMedia === "function" ? matchMedia("(prefers-reduced-motion: reduce)") : null;
|
|
53
|
+
}
|
|
54
|
+
return cachedReducedMotionQuery?.matches ?? false;
|
|
55
|
+
}
|
|
56
|
+
function sameCursors(a, b) {
|
|
57
|
+
return a.length === b.length && a.every((item, index) => item === b[index]);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The default cursor shape: an arrow with an optional label.
|
|
61
|
+
*/
|
|
62
|
+
export function DefaultCursor(props) {
|
|
63
|
+
const { label, color = DEFAULT_COLOR, className, style, labelClassName, labelStyle } = props;
|
|
64
|
+
const cssColor = `var(--anchor-presence-cursor-color, ${color})`;
|
|
65
|
+
const cssSize = "var(--anchor-presence-cursor-size, 20px)";
|
|
66
|
+
const cssLabelColor = "var(--anchor-presence-cursor-label-color, white)";
|
|
67
|
+
return (_jsxs("span", { className: className, dir: "ltr", style: { forcedColorAdjust: "none", ...style }, children: [_jsx("svg", { style: { width: cssSize, height: cssSize }, viewBox: "0 0 20 20", children: _jsx("path", { d: "M2 2 L18 9 L10.5 11 L8 18.5 Z", fill: cssColor, stroke: "white", strokeWidth: 1 }) }), label !== null && label !== undefined ? (_jsx("span", { dir: "auto", className: labelClassName, style: {
|
|
68
|
+
marginLeft: 12,
|
|
69
|
+
display: "inline-block",
|
|
70
|
+
borderRadius: 6,
|
|
71
|
+
padding: "2px 6px",
|
|
72
|
+
fontSize: "0.75rem",
|
|
73
|
+
fontWeight: 500,
|
|
74
|
+
color: cssLabelColor,
|
|
75
|
+
backgroundColor: cssColor,
|
|
76
|
+
maxWidth: "20rem",
|
|
77
|
+
overflow: "hidden",
|
|
78
|
+
textOverflow: "ellipsis",
|
|
79
|
+
whiteSpace: "nowrap",
|
|
80
|
+
...labelStyle,
|
|
81
|
+
}, children: label })) : null] }));
|
|
82
|
+
}
|
|
83
|
+
function CursorItem(props) {
|
|
84
|
+
const { cursor, getLabel, getColor, getCursorProps, renderCursor, zIndex } = props;
|
|
85
|
+
const label = getLabel ? getLabel(cursor) : defaultLabel(cursor);
|
|
86
|
+
const color = getColor ? getColor(cursor) : defaultColor(cursor);
|
|
87
|
+
const consumerProps = getCursorProps ? getCursorProps(cursor) : undefined;
|
|
88
|
+
const { style: consumerStyle, ...consumerRest } = consumerProps ?? {};
|
|
89
|
+
const style = {
|
|
90
|
+
...consumerStyle,
|
|
91
|
+
zIndex: zIndex ?? consumerStyle?.zIndex ?? DEFAULT_Z_INDEX,
|
|
92
|
+
position: "fixed",
|
|
93
|
+
left: 0,
|
|
94
|
+
top: 0,
|
|
95
|
+
pointerEvents: "none",
|
|
96
|
+
transform: `translate3d(${cursor.x}px, ${cursor.y}px, 0)`,
|
|
97
|
+
opacity: cursor.idle ? IDLE_OPACITY : 1,
|
|
98
|
+
...(prefersReducedMotion()
|
|
99
|
+
? null
|
|
100
|
+
: { transition: consumerStyle?.transition ?? "opacity 200ms ease-out" }),
|
|
101
|
+
};
|
|
102
|
+
return (_jsx("div", { ...consumerRest, ...CURSOR_MARKER_PROPS, style: style, "aria-hidden": "true", "data-anchor-presence-client-id": cursor.clientId, "data-anchor-presence-tier": cursor.tier, "data-anchor-presence-anchor": cursor.anchorId ?? "", "data-anchor-presence-idle": cursor.idle || undefined, children: renderCursor ? (renderCursor({ cursor, label, color, pointerType: cursor.pointerType })) : (_jsx(DefaultCursor, { label: label, color: color })) }));
|
|
103
|
+
}
|
|
104
|
+
// the resolver keeps result-object identity for unchanged cursors (spec §14.1), so memo skips static cursors for free
|
|
105
|
+
const MemoizedCursorItem = memo(CursorItem);
|
|
106
|
+
export function CursorLayerIn(props) {
|
|
107
|
+
const { context, getLabel, getColor, filterCursor, getCursorProps, renderCursor, zIndex } = props;
|
|
108
|
+
const select = useCallback((cursors) => cursors.filter((cursor) => cursor.visible && (filterCursor?.(cursor) ?? true)), [filterCursor]);
|
|
109
|
+
const filtered = useRemoteCursorsSelectorIn(context, select, sameCursors);
|
|
110
|
+
return (_jsx(_Fragment, { children: filtered.map((cursor) => (_jsx(MemoizedCursorItem, { cursor: cursor, getLabel: getLabel, getColor: getColor, getCursorProps: getCursorProps, renderCursor: renderCursor, zIndex: zIndex }, cursor.clientId))) }));
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Renders the visible remote cursors.
|
|
114
|
+
* The layer places each cursor at its resolved position.
|
|
115
|
+
* The `user` and `context` of a cursor have the type `unknown`. For typed render props, use `CursorLayer` from `createPresenceHooks`.
|
|
116
|
+
*/
|
|
117
|
+
export function CursorLayer(props) {
|
|
118
|
+
return _jsx(CursorLayerIn, { ...props, context: PresenceProviderContext });
|
|
119
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { useDomBinding } from "./use-dom-binding.js";
|
|
2
|
+
export { usePresenceClient } from "./use-presence-client.js";
|
|
3
|
+
export { useLocalContext } from "./use-local-context.js";
|
|
4
|
+
export { useRemoteEvents } from "./use-remote-events.js";
|
|
5
|
+
export { useLocalUser } from "./use-local-user.js";
|
|
6
|
+
export { usePeerChanges } from "./use-peer-changes.js";
|
|
7
|
+
export { useRemotePresence } from "./use-remote-presence.js";
|
|
8
|
+
export { usePresenceStatus } from "./use-presence-status.js";
|
|
9
|
+
export { useRemoteCursors, useRemoteCursorsSelector } from "./use-remote-cursors.js";
|
|
10
|
+
export { useRemoteUsers } from "./use-remote-users.js";
|
|
11
|
+
export type { RemoteUser } from "./use-remote-users.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { useDomBinding } from "./use-dom-binding.js";
|
|
2
|
+
export { usePresenceClient } from "./use-presence-client.js";
|
|
3
|
+
export { useLocalContext } from "./use-local-context.js";
|
|
4
|
+
export { useRemoteEvents } from "./use-remote-events.js";
|
|
5
|
+
export { useLocalUser } from "./use-local-user.js";
|
|
6
|
+
export { usePeerChanges } from "./use-peer-changes.js";
|
|
7
|
+
export { useRemotePresence } from "./use-remote-presence.js";
|
|
8
|
+
export { usePresenceStatus } from "./use-presence-status.js";
|
|
9
|
+
export { useRemoteCursors, useRemoteCursorsSelector } from "./use-remote-cursors.js";
|
|
10
|
+
export { useRemoteUsers } from "./use-remote-users.js";
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { DomBinding } from "@dammers/anchor-presence-dom";
|
|
2
|
+
import type { PresenceContext } from "../context.js";
|
|
3
|
+
export declare function useDomBindingIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): DomBinding<TContext, TUser> | null;
|
|
4
|
+
/**
|
|
5
|
+
* Returns the DOM binding from the nearest provider.
|
|
6
|
+
* Returns `null` before the provider creates the binding, and without a provider.
|
|
7
|
+
* Call `binding.invalidate()` when state that a `visibilityPolicy` reads changes.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useDomBinding(): DomBinding | null;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { PresenceProviderContext } from "../context.js";
|
|
2
|
+
import { usePresenceProviderContext } from "./use-presence-client.js";
|
|
3
|
+
export function useDomBindingIn(context) {
|
|
4
|
+
return usePresenceProviderContext(context).binding;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Returns the DOM binding from the nearest provider.
|
|
8
|
+
* Returns `null` before the provider creates the binding, and without a provider.
|
|
9
|
+
* Call `binding.invalidate()` when state that a `visibilityPolicy` reads changes.
|
|
10
|
+
*/
|
|
11
|
+
export function useDomBinding() {
|
|
12
|
+
return useDomBindingIn(PresenceProviderContext);
|
|
13
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { PresenceContext } from "../context.js";
|
|
2
|
+
export declare function useLocalContextIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): [TContext | undefined, (next: TContext | undefined) => void];
|
|
3
|
+
/**
|
|
4
|
+
* Reads the local context value and gives a setter.
|
|
5
|
+
* The value has the type `unknown`. For a typed value, use `useLocalContext` from `createPresenceHooks`.
|
|
6
|
+
* The setter calls `client.setContext`, which sends the value to remote peers.
|
|
7
|
+
* Returns `undefined` and a no-op setter on the server, and a no-op setter while no client exists.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useLocalContext(): [unknown, (next: unknown) => void];
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { useCallback, useMemo, useSyncExternalStore } from "react";
|
|
2
|
+
import { PresenceProviderContext } from "../context.js";
|
|
3
|
+
import { usePresenceProviderContext } from "./use-presence-client.js";
|
|
4
|
+
import { getContextStore } from "../context-store.js";
|
|
5
|
+
const getServerContext = () => { };
|
|
6
|
+
export function useLocalContextIn(context) {
|
|
7
|
+
const { client } = usePresenceProviderContext(context);
|
|
8
|
+
const store = useMemo(() => (client !== null ? getContextStore(client) : null), [client]);
|
|
9
|
+
const subscribe = useCallback((listener) => (store !== null ? store.subscribe(listener) : () => { }), [store]);
|
|
10
|
+
const getSnapshot = useCallback(() => (store !== null ? store.getSnapshot() : undefined), [store]);
|
|
11
|
+
const value = useSyncExternalStore(subscribe, getSnapshot, getServerContext);
|
|
12
|
+
const setContext = useCallback((next) => {
|
|
13
|
+
store?.setContext(next);
|
|
14
|
+
}, [store]);
|
|
15
|
+
return [value, setContext];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Reads the local context value and gives a setter.
|
|
19
|
+
* The value has the type `unknown`. For a typed value, use `useLocalContext` from `createPresenceHooks`.
|
|
20
|
+
* The setter calls `client.setContext`, which sends the value to remote peers.
|
|
21
|
+
* Returns `undefined` and a no-op setter on the server, and a no-op setter while no client exists.
|
|
22
|
+
*/
|
|
23
|
+
export function useLocalContext() {
|
|
24
|
+
return useLocalContextIn(PresenceProviderContext);
|
|
25
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { PresenceContext } from "../context.js";
|
|
2
|
+
export declare function useLocalUserIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): [TUser | undefined, (next: TUser | undefined) => void];
|
|
3
|
+
/**
|
|
4
|
+
* Reads the local user value and gives a setter.
|
|
5
|
+
* The value has the type `unknown`. For a typed value, use `useLocalUser` from `createPresenceHooks`.
|
|
6
|
+
* The setter calls `client.setUser`, which sends the value to remote peers.
|
|
7
|
+
* Returns `undefined` and a no-op setter without a client.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useLocalUser(): [unknown, (next: unknown) => void];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
2
|
+
import { PresenceProviderContext } from "../context.js";
|
|
3
|
+
import { usePresenceProviderContext } from "./use-presence-client.js";
|
|
4
|
+
export function useLocalUserIn(context) {
|
|
5
|
+
const { client } = usePresenceProviderContext(context);
|
|
6
|
+
const subscribe = useCallback((listener) => (client !== null ? client.subscribeUser(listener) : () => { }), [client]);
|
|
7
|
+
const getSnapshot = useCallback(() => client?.getUser(), [client]);
|
|
8
|
+
// oxlint-disable-next-line unicorn/no-useless-undefined -- the server snapshot function returns no user
|
|
9
|
+
const user = useSyncExternalStore(subscribe, getSnapshot, () => undefined);
|
|
10
|
+
const setUser = useCallback((next) => client?.setUser(next), [client]);
|
|
11
|
+
return [user, setUser];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Reads the local user value and gives a setter.
|
|
15
|
+
* The value has the type `unknown`. For a typed value, use `useLocalUser` from `createPresenceHooks`.
|
|
16
|
+
* The setter calls `client.setUser`, which sends the value to remote peers.
|
|
17
|
+
* Returns `undefined` and a no-op setter without a client.
|
|
18
|
+
*/
|
|
19
|
+
export function useLocalUser() {
|
|
20
|
+
return useLocalUserIn(PresenceProviderContext);
|
|
21
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { PeerChange } from "@dammers/anchor-presence-core";
|
|
2
|
+
import type { PresenceContext } from "../context.js";
|
|
3
|
+
export declare function usePeerChangesIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>, listener: (change: PeerChange<TContext, TUser>) => void): void;
|
|
4
|
+
/**
|
|
5
|
+
* Calls `listener` when a remote client joins, leaves, or changes its `user` or `context`.
|
|
6
|
+
* The `user` and `context` of a change have the type `unknown`. For typed values, use `usePeerChanges` from `createPresenceHooks`.
|
|
7
|
+
* The hook keeps one subscription per client, so an inline `listener` does not resubscribe.
|
|
8
|
+
*/
|
|
9
|
+
export declare function usePeerChanges(listener: (change: PeerChange) => void): void;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { useEffect, useRef } from "react";
|
|
2
|
+
import { PresenceProviderContext } from "../context.js";
|
|
3
|
+
import { usePresenceProviderContext } from "./use-presence-client.js";
|
|
4
|
+
export function usePeerChangesIn(context, listener) {
|
|
5
|
+
const { client } = usePresenceProviderContext(context);
|
|
6
|
+
const listenerRef = useRef(listener);
|
|
7
|
+
useEffect(() => {
|
|
8
|
+
listenerRef.current = listener;
|
|
9
|
+
});
|
|
10
|
+
useEffect(() => client?.subscribePeers((change) => listenerRef.current(change)), [client]);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Calls `listener` when a remote client joins, leaves, or changes its `user` or `context`.
|
|
14
|
+
* The `user` and `context` of a change have the type `unknown`. For typed values, use `usePeerChanges` from `createPresenceHooks`.
|
|
15
|
+
* The hook keeps one subscription per client, so an inline `listener` does not resubscribe.
|
|
16
|
+
*/
|
|
17
|
+
export function usePeerChanges(listener) {
|
|
18
|
+
usePeerChangesIn(PresenceProviderContext, listener);
|
|
19
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ConnectionStatus, PresenceClient } from "@dammers/anchor-presence-core";
|
|
2
|
+
import type { PresenceContext, PresenceProviderValue } from "../context.js";
|
|
3
|
+
export declare const EMPTY_CURSORS: never[];
|
|
4
|
+
export declare const EMPTY_PRESENCE: never[];
|
|
5
|
+
export declare function getServerCursors(): never[];
|
|
6
|
+
export declare function getServerPresence(): never[];
|
|
7
|
+
export declare function getServerStatus(): ConnectionStatus;
|
|
8
|
+
export declare function usePresenceProviderContext<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): PresenceProviderValue<TContext, TUser, TEvents>;
|
|
9
|
+
export declare function usePresenceClientIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): PresenceClient<TContext, TUser, TEvents> | null;
|
|
10
|
+
/**
|
|
11
|
+
* Returns the presence client from the nearest provider.
|
|
12
|
+
* Returns `null` when the hook runs without a provider.
|
|
13
|
+
*/
|
|
14
|
+
export declare function usePresenceClient(): PresenceClient | null;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { useContext } from "react";
|
|
2
|
+
import { warnOnce } from "@dammers/anchor-presence-core";
|
|
3
|
+
import { PresenceProviderContext, PresenceProviderContextDefault } from "../context.js";
|
|
4
|
+
export const EMPTY_CURSORS = [];
|
|
5
|
+
export const EMPTY_PRESENCE = [];
|
|
6
|
+
export function getServerCursors() {
|
|
7
|
+
return EMPTY_CURSORS;
|
|
8
|
+
}
|
|
9
|
+
export function getServerPresence() {
|
|
10
|
+
return EMPTY_PRESENCE;
|
|
11
|
+
}
|
|
12
|
+
export function getServerStatus() {
|
|
13
|
+
return "disconnected";
|
|
14
|
+
}
|
|
15
|
+
export function usePresenceProviderContext(context) {
|
|
16
|
+
const value = useContext(context);
|
|
17
|
+
if (value === PresenceProviderContextDefault) {
|
|
18
|
+
warnOnce("no-provider", "a hook or CursorLayer runs outside PresenceProvider, so it returns empty data. Wrap the tree in PresenceProvider; hooks from createPresenceHooks need the provider of the same call.");
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
export function usePresenceClientIn(context) {
|
|
23
|
+
return usePresenceProviderContext(context).client;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Returns the presence client from the nearest provider.
|
|
27
|
+
* Returns `null` when the hook runs without a provider.
|
|
28
|
+
*/
|
|
29
|
+
export function usePresenceClient() {
|
|
30
|
+
return usePresenceClientIn(PresenceProviderContext);
|
|
31
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ConnectionStatus } from "@dammers/anchor-presence-core";
|
|
2
|
+
import type { PresenceContext } from "../context.js";
|
|
3
|
+
export declare function usePresenceStatusIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): ConnectionStatus;
|
|
4
|
+
/**
|
|
5
|
+
* Returns the connection status of the client from the nearest provider.
|
|
6
|
+
* Returns `"connecting"` while a provider `factory` has not created its client, and `"disconnected"` without a client.
|
|
7
|
+
*/
|
|
8
|
+
export declare function usePresenceStatus(): ConnectionStatus;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
2
|
+
import { PresenceProviderContext } from "../context.js";
|
|
3
|
+
import { getServerStatus, usePresenceProviderContext } from "./use-presence-client.js";
|
|
4
|
+
export function usePresenceStatusIn(context) {
|
|
5
|
+
const { client, clientPending } = usePresenceProviderContext(context);
|
|
6
|
+
const noClientStatus = useCallback(() => (clientPending === true ? "connecting" : getServerStatus()), [clientPending]);
|
|
7
|
+
const subscribe = useCallback((listener) => (client !== null ? client.subscribeStatus(listener) : () => { }), [client]);
|
|
8
|
+
const getSnapshot = useCallback(() => (client !== null ? client.getStatus() : noClientStatus()), [client, noClientStatus]);
|
|
9
|
+
return useSyncExternalStore(subscribe, getSnapshot, noClientStatus);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Returns the connection status of the client from the nearest provider.
|
|
13
|
+
* Returns `"connecting"` while a provider `factory` has not created its client, and `"disconnected"` without a client.
|
|
14
|
+
*/
|
|
15
|
+
export function usePresenceStatus() {
|
|
16
|
+
return usePresenceStatusIn(PresenceProviderContext);
|
|
17
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ResolvedCursor } from "@dammers/anchor-presence-dom";
|
|
2
|
+
import type { PresenceContext } from "../context.js";
|
|
3
|
+
export declare function useRemoteCursorsIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): readonly ResolvedCursor<TContext, TUser>[];
|
|
4
|
+
/**
|
|
5
|
+
* Returns the resolved remote cursors.
|
|
6
|
+
* The `user` and `context` of a cursor have the type `unknown`. For typed values, use `useRemoteCursors` from `createPresenceHooks`.
|
|
7
|
+
* The hook rerenders on every new cursor snapshot.
|
|
8
|
+
* Returns an empty list on the server or without a binding.
|
|
9
|
+
*/
|
|
10
|
+
export declare function useRemoteCursors(): readonly ResolvedCursor[];
|
|
11
|
+
export declare function useRemoteCursorsSelectorIn<TSelected, TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>, select: (cursors: readonly ResolvedCursor<TContext, TUser>[]) => TSelected, isEqual?: (a: TSelected, b: TSelected) => boolean): TSelected;
|
|
12
|
+
/**
|
|
13
|
+
* Subscribes to the resolved-cursor snapshot through a selector, and rerenders only when the
|
|
14
|
+
* selected value changes under `isEqual`. Keep `select` and `isEqual` stable across renders.
|
|
15
|
+
* The `user` and `context` of a cursor have the type `unknown`. For typed values, use `useRemoteCursorsSelector` from `createPresenceHooks`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function useRemoteCursorsSelector<TSelected>(select: (cursors: readonly ResolvedCursor[]) => TSelected, isEqual?: (a: TSelected, b: TSelected) => boolean): TSelected;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { useCallback, useRef, useState, useSyncExternalStore } from "react";
|
|
2
|
+
import { PresenceProviderContext } from "../context.js";
|
|
3
|
+
import { EMPTY_CURSORS, getServerCursors, usePresenceProviderContext } from "./use-presence-client.js";
|
|
4
|
+
export function useRemoteCursorsIn(context) {
|
|
5
|
+
const { binding } = usePresenceProviderContext(context);
|
|
6
|
+
const subscribe = useCallback((listener) => (binding !== null ? binding.subscribe(listener) : () => { }), [binding]);
|
|
7
|
+
const getSnapshot = useCallback(() => (binding !== null ? binding.getSnapshot() : EMPTY_CURSORS), [binding]);
|
|
8
|
+
return useSyncExternalStore(subscribe, getSnapshot, getServerCursors);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Returns the resolved remote cursors.
|
|
12
|
+
* The `user` and `context` of a cursor have the type `unknown`. For typed values, use `useRemoteCursors` from `createPresenceHooks`.
|
|
13
|
+
* The hook rerenders on every new cursor snapshot.
|
|
14
|
+
* Returns an empty list on the server or without a binding.
|
|
15
|
+
*/
|
|
16
|
+
export function useRemoteCursors() {
|
|
17
|
+
return useRemoteCursorsIn(PresenceProviderContext);
|
|
18
|
+
}
|
|
19
|
+
export function useRemoteCursorsSelectorIn(context, select, isEqual = Object.is) {
|
|
20
|
+
const { binding } = usePresenceProviderContext(context);
|
|
21
|
+
const selectedRef = useRef(null);
|
|
22
|
+
// caches select's output by input array and callbacks, so a repeat snapshot probe skips select() entirely
|
|
23
|
+
const lastInputRef = useRef(null);
|
|
24
|
+
const subscribe = useCallback((listener) => (binding !== null ? binding.subscribe(listener) : () => { }), [binding]);
|
|
25
|
+
const getSnapshot = useCallback(() => {
|
|
26
|
+
const cursors = binding !== null ? binding.getSnapshot() : EMPTY_CURSORS;
|
|
27
|
+
const lastInput = lastInputRef.current;
|
|
28
|
+
if (lastInput?.cursors === cursors && lastInput.select === select && lastInput.isEqual === isEqual) {
|
|
29
|
+
return lastInput.value;
|
|
30
|
+
}
|
|
31
|
+
const next = select(cursors);
|
|
32
|
+
const previous = selectedRef.current;
|
|
33
|
+
// useSyncExternalStore compares by identity, so an equal selection must return the previous reference
|
|
34
|
+
const value = previous !== null && isEqual(previous.value, next) ? previous.value : next;
|
|
35
|
+
selectedRef.current = { value };
|
|
36
|
+
lastInputRef.current = { cursors, select, isEqual, value };
|
|
37
|
+
return value;
|
|
38
|
+
}, [binding, select, isEqual]);
|
|
39
|
+
// computed once: React may call the server snapshot repeatedly, and it compares by identity
|
|
40
|
+
const [serverValue] = useState(() => select(EMPTY_CURSORS));
|
|
41
|
+
const getServerSnapshot = useCallback(() => serverValue, [serverValue]);
|
|
42
|
+
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Subscribes to the resolved-cursor snapshot through a selector, and rerenders only when the
|
|
46
|
+
* selected value changes under `isEqual`. Keep `select` and `isEqual` stable across renders.
|
|
47
|
+
* The `user` and `context` of a cursor have the type `unknown`. For typed values, use `useRemoteCursorsSelector` from `createPresenceHooks`.
|
|
48
|
+
*/
|
|
49
|
+
export function useRemoteCursorsSelector(select, isEqual) {
|
|
50
|
+
return useRemoteCursorsSelectorIn(PresenceProviderContext, select, isEqual);
|
|
51
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { EventMap, TypedRemoteEvent } from "@dammers/anchor-presence-core";
|
|
2
|
+
import type { PresenceContext } from "../context.js";
|
|
3
|
+
export declare function useRemoteEventsIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>, listener: (event: TypedRemoteEvent<TEvents>) => void): void;
|
|
4
|
+
/**
|
|
5
|
+
* Calls `listener` for every one-shot event a remote peer sends with `client.sendEvent`.
|
|
6
|
+
* The `data` of an event has the type `unknown`. For typed events, use `useRemoteEvents` from `createPresenceHooks`.
|
|
7
|
+
* The hook keeps one subscription per client, so an inline `listener` does not resubscribe.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useRemoteEvents(listener: (event: TypedRemoteEvent<EventMap>) => void): void;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { useEffect, useRef } from "react";
|
|
2
|
+
import { PresenceProviderContext } from "../context.js";
|
|
3
|
+
import { usePresenceProviderContext } from "./use-presence-client.js";
|
|
4
|
+
export function useRemoteEventsIn(context, listener) {
|
|
5
|
+
const { client } = usePresenceProviderContext(context);
|
|
6
|
+
const listenerRef = useRef(listener);
|
|
7
|
+
useEffect(() => {
|
|
8
|
+
listenerRef.current = listener;
|
|
9
|
+
});
|
|
10
|
+
useEffect(() => client?.subscribeEvents((event) => listenerRef.current(event)), [client]);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Calls `listener` for every one-shot event a remote peer sends with `client.sendEvent`.
|
|
14
|
+
* The `data` of an event has the type `unknown`. For typed events, use `useRemoteEvents` from `createPresenceHooks`.
|
|
15
|
+
* The hook keeps one subscription per client, so an inline `listener` does not resubscribe.
|
|
16
|
+
*/
|
|
17
|
+
export function useRemoteEvents(listener) {
|
|
18
|
+
useRemoteEventsIn(PresenceProviderContext, listener);
|
|
19
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { RemotePresence } from "@dammers/anchor-presence-core";
|
|
2
|
+
import type { PresenceContext } from "../context.js";
|
|
3
|
+
export declare function useRemotePresenceIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): readonly RemotePresence<TContext, TUser>[];
|
|
4
|
+
/**
|
|
5
|
+
* Returns the stable list of remote presences, without `sequence`.
|
|
6
|
+
* The `user` and `context` of an entry have the type `unknown`. For typed values, use `useRemotePresence` from `createPresenceHooks`.
|
|
7
|
+
* The hook rerenders only when an observable field changes.
|
|
8
|
+
* Watch `sequence` with `client.getRemoteSnapshot()` and `client.subscribeRemote()`.
|
|
9
|
+
*/
|
|
10
|
+
export declare function useRemotePresence(): readonly RemotePresence[];
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
2
|
+
import { PresenceProviderContext } from "../context.js";
|
|
3
|
+
import { EMPTY_PRESENCE, getServerPresence, usePresenceProviderContext } from "./use-presence-client.js";
|
|
4
|
+
export function useRemotePresenceIn(context) {
|
|
5
|
+
const { client } = usePresenceProviderContext(context);
|
|
6
|
+
const subscribe = useCallback((listener) => (client !== null ? client.subscribeRemote(listener) : () => { }), [client]);
|
|
7
|
+
const getSnapshot = useCallback(() => (client !== null ? client.getRemotePresence() : EMPTY_PRESENCE), [client]);
|
|
8
|
+
return useSyncExternalStore(subscribe, getSnapshot, getServerPresence);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Returns the stable list of remote presences, without `sequence`.
|
|
12
|
+
* The `user` and `context` of an entry have the type `unknown`. For typed values, use `useRemotePresence` from `createPresenceHooks`.
|
|
13
|
+
* The hook rerenders only when an observable field changes.
|
|
14
|
+
* Watch `sequence` with `client.getRemoteSnapshot()` and `client.subscribeRemote()`.
|
|
15
|
+
*/
|
|
16
|
+
export function useRemotePresence() {
|
|
17
|
+
return useRemotePresenceIn(PresenceProviderContext);
|
|
18
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { PresenceContext } from "../context.js";
|
|
2
|
+
/**
|
|
3
|
+
* One remote user, keyed by client.
|
|
4
|
+
*/
|
|
5
|
+
export type RemoteUser<TUser = unknown> = {
|
|
6
|
+
/** The client that sent the user value. */
|
|
7
|
+
clientId: string;
|
|
8
|
+
/** The user value, or `undefined` when the sender sent none or sent `null`. */
|
|
9
|
+
user: TUser | undefined;
|
|
10
|
+
/** The session ID of the client. */
|
|
11
|
+
session: string;
|
|
12
|
+
/** `true` when the presence of the client has not changed for `idleAfterMs`. */
|
|
13
|
+
idle: boolean;
|
|
14
|
+
};
|
|
15
|
+
export declare function useRemoteUsersIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): readonly RemoteUser<TUser>[];
|
|
16
|
+
/**
|
|
17
|
+
* Returns the remote user values, one entry per client.
|
|
18
|
+
* Each `user` has the type `unknown`. For typed users, use `useRemoteUsers` from `createPresenceHooks`.
|
|
19
|
+
* The list, and each entry, keep identity across a presence snapshot that changes no user-relevant field.
|
|
20
|
+
*/
|
|
21
|
+
export declare function useRemoteUsers(): readonly RemoteUser[];
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { useCallback, useRef, useSyncExternalStore } from "react";
|
|
2
|
+
import { PresenceProviderContext } from "../context.js";
|
|
3
|
+
import { EMPTY_PRESENCE, usePresenceProviderContext } from "./use-presence-client.js";
|
|
4
|
+
const EMPTY_USERS = [];
|
|
5
|
+
// Keeps each RemoteUser's identity across presence snapshots that change only cursor position,
|
|
6
|
+
// so a consumer rendering a user list does not re-render on every remote pointer move.
|
|
7
|
+
// The per-client map is updated in place; the users array is rebuilt only when membership,
|
|
8
|
+
// order, or a user-relevant field changes. Cursor-only probes allocate nothing.
|
|
9
|
+
function projectRemoteUsers(snapshot, previousUsers, byClientId) {
|
|
10
|
+
let structureChanged = snapshot.length !== previousUsers.length;
|
|
11
|
+
if (!structureChanged) {
|
|
12
|
+
for (let i = 0; i < snapshot.length; i++) {
|
|
13
|
+
const next = snapshot[i];
|
|
14
|
+
const previous = previousUsers[i];
|
|
15
|
+
if (next === undefined || previous === undefined || next.clientId !== previous.clientId) {
|
|
16
|
+
structureChanged = true;
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
let fieldChanged = false;
|
|
22
|
+
for (const presence of snapshot) {
|
|
23
|
+
const user = presence.user === null ? undefined : presence.user;
|
|
24
|
+
const previous = byClientId.get(presence.clientId);
|
|
25
|
+
if (previous === undefined ||
|
|
26
|
+
previous.user !== user ||
|
|
27
|
+
previous.idle !== presence.idle ||
|
|
28
|
+
previous.session !== presence.session) {
|
|
29
|
+
byClientId.set(presence.clientId, {
|
|
30
|
+
clientId: presence.clientId,
|
|
31
|
+
user,
|
|
32
|
+
session: presence.session,
|
|
33
|
+
idle: presence.idle,
|
|
34
|
+
});
|
|
35
|
+
fieldChanged = true;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// prune clients that left the snapshot; O(n*m) but runs only when a client is gone
|
|
39
|
+
if (byClientId.size > snapshot.length) {
|
|
40
|
+
for (const clientId of Array.from(byClientId.keys())) {
|
|
41
|
+
if (!snapshot.some((p) => p.clientId === clientId))
|
|
42
|
+
byClientId.delete(clientId);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!structureChanged && !fieldChanged)
|
|
46
|
+
return previousUsers;
|
|
47
|
+
// every snapshot client has an entry: the update loop ran over the same snapshot right before
|
|
48
|
+
const users = [];
|
|
49
|
+
for (const presence of snapshot) {
|
|
50
|
+
const user = byClientId.get(presence.clientId);
|
|
51
|
+
if (user !== undefined)
|
|
52
|
+
users.push(user);
|
|
53
|
+
}
|
|
54
|
+
return users;
|
|
55
|
+
}
|
|
56
|
+
export function useRemoteUsersIn(context) {
|
|
57
|
+
const { client } = usePresenceProviderContext(context);
|
|
58
|
+
const previousUsersRef = useRef([]);
|
|
59
|
+
const byClientIdRef = useRef(new Map());
|
|
60
|
+
const subscribe = useCallback((listener) => (client !== null ? client.subscribeRemote(listener) : () => { }), [client]);
|
|
61
|
+
const getSnapshot = useCallback(() => {
|
|
62
|
+
const presence = client !== null ? client.getRemotePresence() : EMPTY_PRESENCE;
|
|
63
|
+
const nextUsers = projectRemoteUsers(presence, previousUsersRef.current, byClientIdRef.current);
|
|
64
|
+
previousUsersRef.current = nextUsers;
|
|
65
|
+
return nextUsers;
|
|
66
|
+
}, [client]);
|
|
67
|
+
const getServerSnapshot = useCallback(() => EMPTY_USERS, []);
|
|
68
|
+
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Returns the remote user values, one entry per client.
|
|
72
|
+
* Each `user` has the type `unknown`. For typed users, use `useRemoteUsers` from `createPresenceHooks`.
|
|
73
|
+
* The list, and each entry, keep identity across a presence snapshot that changes no user-relevant field.
|
|
74
|
+
*/
|
|
75
|
+
export function useRemoteUsers() {
|
|
76
|
+
return useRemoteUsersIn(PresenceProviderContext);
|
|
77
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { EventChannel, EventMap } from "@dammers/anchor-presence-core";
|
|
2
|
+
import type { PresenceContext } from "../context.js";
|
|
3
|
+
export declare function useSendEventIn<TContext, TUser, TEvents extends object>(context: PresenceContext<TContext, TUser, TEvents>): EventChannel<TEvents>["send"];
|
|
4
|
+
/**
|
|
5
|
+
* Returns `send` for one-shot events. It returns `false` and sends nothing until the client exists.
|
|
6
|
+
* Any event `type` is allowed. For a typed `send`, use `useSendEvent` from `createPresenceHooks`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function useSendEvent(): EventChannel<EventMap>["send"];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { useMemo } from "react";
|
|
2
|
+
import { createEventChannel } from "@dammers/anchor-presence-core";
|
|
3
|
+
import { PresenceProviderContext } from "../context.js";
|
|
4
|
+
import { usePresenceProviderContext } from "./use-presence-client.js";
|
|
5
|
+
export function useSendEventIn(context) {
|
|
6
|
+
const { client } = usePresenceProviderContext(context);
|
|
7
|
+
return useMemo(() => (client === null ? () => false : createEventChannel(client).send), [client]);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Returns `send` for one-shot events. It returns `false` and sends nothing until the client exists.
|
|
11
|
+
* Any event `type` is allowed. For a typed `send`, use `useSendEvent` from `createPresenceHooks`.
|
|
12
|
+
*/
|
|
13
|
+
export function useSendEvent() {
|
|
14
|
+
return useSendEventIn(PresenceProviderContext);
|
|
15
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export { PresenceProvider } from "./provider.js";
|
|
2
|
+
export type { PresenceProviderConfig, PresenceProviderProps } from "./provider.js";
|
|
3
|
+
export { PresenceProviderContext } from "./context.js";
|
|
4
|
+
export type { PresenceProviderValue } from "./context.js";
|
|
5
|
+
export { useDomBinding } from "./hooks/use-dom-binding.js";
|
|
6
|
+
export { usePresenceClient } from "./hooks/use-presence-client.js";
|
|
7
|
+
export { useLocalContext } from "./hooks/use-local-context.js";
|
|
8
|
+
export { useRemoteEvents } from "./hooks/use-remote-events.js";
|
|
9
|
+
export { useSendEvent } from "./hooks/use-send-event.js";
|
|
10
|
+
export { useLocalUser } from "./hooks/use-local-user.js";
|
|
11
|
+
export { usePeerChanges } from "./hooks/use-peer-changes.js";
|
|
12
|
+
export { useRemotePresence } from "./hooks/use-remote-presence.js";
|
|
13
|
+
export { usePresenceStatus } from "./hooks/use-presence-status.js";
|
|
14
|
+
export { useRemoteCursors, useRemoteCursorsSelector } from "./hooks/use-remote-cursors.js";
|
|
15
|
+
export { useRemoteUsers } from "./hooks/use-remote-users.js";
|
|
16
|
+
export { createPresenceHooks } from "./typed-hooks.js";
|
|
17
|
+
export type { RemoteUser } from "./hooks/use-remote-users.js";
|
|
18
|
+
export { CursorLayer, DefaultCursor } from "./cursor.js";
|
|
19
|
+
export type { CursorLayerProps, CursorRenderProps, DefaultCursorProps } from "./cursor.js";
|
|
20
|
+
export type { AnchorPoint, ConnectionStatus, CursorPosition, PresenceMessage, Interpolator, InterpolatorFactory, EventChannel, EventMap, PeerChange, PresenceClient, PresenceEvent, RemoteEvent, PointerType, RemotePresence, TypedRemoteEvent, } from "@dammers/anchor-presence-core";
|
|
21
|
+
export type { DomBinding, DomBindingOptions, ResolutionTier, ResolvedCursor, } from "@dammers/anchor-presence-dom";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
export { PresenceProvider } from "./provider.js";
|
|
3
|
+
export { PresenceProviderContext } from "./context.js";
|
|
4
|
+
export { useDomBinding } from "./hooks/use-dom-binding.js";
|
|
5
|
+
export { usePresenceClient } from "./hooks/use-presence-client.js";
|
|
6
|
+
export { useLocalContext } from "./hooks/use-local-context.js";
|
|
7
|
+
export { useRemoteEvents } from "./hooks/use-remote-events.js";
|
|
8
|
+
export { useSendEvent } from "./hooks/use-send-event.js";
|
|
9
|
+
export { useLocalUser } from "./hooks/use-local-user.js";
|
|
10
|
+
export { usePeerChanges } from "./hooks/use-peer-changes.js";
|
|
11
|
+
export { useRemotePresence } from "./hooks/use-remote-presence.js";
|
|
12
|
+
export { usePresenceStatus } from "./hooks/use-presence-status.js";
|
|
13
|
+
export { useRemoteCursors, useRemoteCursorsSelector } from "./hooks/use-remote-cursors.js";
|
|
14
|
+
export { useRemoteUsers } from "./hooks/use-remote-users.js";
|
|
15
|
+
export { createPresenceHooks } from "./typed-hooks.js";
|
|
16
|
+
export { CursorLayer, DefaultCursor } from "./cursor.js";
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
import type { EventMap, PresenceClient } from "@dammers/anchor-presence-core";
|
|
3
|
+
import type { DomBinding, DomBindingOptions } from "@dammers/anchor-presence-dom";
|
|
4
|
+
import type { PresenceProviderValue } from "./context.js";
|
|
5
|
+
/**
|
|
6
|
+
* Every `PresenceProvider` prop except `children`.
|
|
7
|
+
* Use it for a wrapper component: `Omit` on `PresenceProviderProps` loses the `client` or `factory` rule.
|
|
8
|
+
*/
|
|
9
|
+
export type PresenceProviderConfig<TContext = unknown, TUser = unknown, TEvents extends object = EventMap> = ({
|
|
10
|
+
/** A client you own; the provider never disposes it. `null` provides no client. */
|
|
11
|
+
client: PresenceClient<TContext, TUser, TEvents> | null;
|
|
12
|
+
factory?: never;
|
|
13
|
+
} | {
|
|
14
|
+
/**
|
|
15
|
+
* Creates the client the provider owns.
|
|
16
|
+
* The provider runs it once per mount, in an effect, and disposes the client on unmount.
|
|
17
|
+
*/
|
|
18
|
+
factory: () => PresenceClient<TContext, TUser, TEvents>;
|
|
19
|
+
client?: never;
|
|
20
|
+
}) & ({
|
|
21
|
+
/** A binding you created. Omit to let the provider create one. */
|
|
22
|
+
binding?: DomBinding<TContext, TUser> | undefined;
|
|
23
|
+
bindingOptions?: never;
|
|
24
|
+
} | {
|
|
25
|
+
binding?: never;
|
|
26
|
+
/** Options for the binding the provider creates. */
|
|
27
|
+
bindingOptions?: DomBindingOptions<NoInfer<TContext>, NoInfer<TUser>> | undefined;
|
|
28
|
+
}) & {
|
|
29
|
+
/** Change this value to dispose the client `factory` made and create a new one, for example to join another room. */
|
|
30
|
+
clientKey?: unknown;
|
|
31
|
+
/** Change this value to rebuild the binding with the current `bindingOptions`. The client stays connected. */
|
|
32
|
+
bindingKey?: unknown;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Props for `PresenceProvider`.
|
|
36
|
+
*/
|
|
37
|
+
export type PresenceProviderProps<TContext = unknown, TUser = unknown, TEvents extends object = EventMap> = PresenceProviderConfig<TContext, TUser, TEvents> & {
|
|
38
|
+
/** The tree below the provider. */
|
|
39
|
+
children?: ReactNode;
|
|
40
|
+
};
|
|
41
|
+
export declare function usePresenceProviderValue<TContext, TUser, TEvents extends object>(props: PresenceProviderProps<TContext, TUser, TEvents>): PresenceProviderValue<TContext, TUser, TEvents>;
|
|
42
|
+
/**
|
|
43
|
+
* Provides the presence client and the binding to the tree below.
|
|
44
|
+
* The provider creates and disposes the client from `factory`; a `client` prop stays yours to dispose.
|
|
45
|
+
* The provider creates a DOM binding when you do not pass one.
|
|
46
|
+
* The provider reads `bindingOptions` when it creates the binding. Change `bindingKey` to create a new binding with the latest options, without touching the client.
|
|
47
|
+
* The hooks below it return `unknown` for `user`, `context` and event data, and the provider takes only an untyped client.
|
|
48
|
+
* Use `createPresenceHooks` for typed access.
|
|
49
|
+
*/
|
|
50
|
+
export declare function PresenceProvider(props: PresenceProviderProps): ReactNode;
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { warnOnce } from "@dammers/anchor-presence-core";
|
|
4
|
+
import { createDomBinding } from "@dammers/anchor-presence-dom";
|
|
5
|
+
import { PresenceProviderContext } from "./context.js";
|
|
6
|
+
function isBrowser() {
|
|
7
|
+
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
8
|
+
}
|
|
9
|
+
export function usePresenceProviderValue(props) {
|
|
10
|
+
const { factory, client: providedClient, binding: providedBinding, bindingOptions, bindingKey, clientKey, } = props;
|
|
11
|
+
const [ownClient, setOwnClient] = useState(null);
|
|
12
|
+
// The factory runs once per mount and once more each time clientKey changes. Other factory and client changes are ignored.
|
|
13
|
+
const factoryRef = useRef(factory);
|
|
14
|
+
const providedClientRef = useRef(providedClient);
|
|
15
|
+
useEffect(() => {
|
|
16
|
+
factoryRef.current = factory;
|
|
17
|
+
providedClientRef.current = providedClient;
|
|
18
|
+
});
|
|
19
|
+
useEffect(() => {
|
|
20
|
+
// oxlint-disable-next-line react/refs -- one-shot creation: skip when the mount render had a client prop
|
|
21
|
+
if (providedClientRef.current !== undefined)
|
|
22
|
+
return;
|
|
23
|
+
// oxlint-disable-next-line react/refs -- one-shot creation path
|
|
24
|
+
const create = factoryRef.current;
|
|
25
|
+
if (create === undefined)
|
|
26
|
+
return;
|
|
27
|
+
if (typeof create !== "function") {
|
|
28
|
+
throw new TypeError("PresenceProvider: factory must be a function that returns a client; pass a client with the client prop");
|
|
29
|
+
}
|
|
30
|
+
if (!isBrowser())
|
|
31
|
+
return;
|
|
32
|
+
const created = create();
|
|
33
|
+
setOwnClient(created);
|
|
34
|
+
return () => {
|
|
35
|
+
created.dispose();
|
|
36
|
+
setOwnClient(null);
|
|
37
|
+
};
|
|
38
|
+
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- clientKey is the deliberate re-create trigger
|
|
39
|
+
}, [clientKey]);
|
|
40
|
+
const client = providedClient ?? ownClient;
|
|
41
|
+
if (factory === undefined && providedClient === undefined) {
|
|
42
|
+
warnOnce("provider-without-client", "PresenceProvider got neither `client` nor `factory`, so it renders without presence.");
|
|
43
|
+
}
|
|
44
|
+
if (factory !== undefined && providedClient !== undefined) {
|
|
45
|
+
warnOnce("provider-client-and-factory", "PresenceProvider got both `client` and `factory`; it ignores `factory`.");
|
|
46
|
+
}
|
|
47
|
+
if (providedBinding !== undefined && bindingOptions !== undefined) {
|
|
48
|
+
warnOnce("binding-and-options", "PresenceProvider got both `binding` and `bindingOptions`; it ignores `bindingOptions`.");
|
|
49
|
+
}
|
|
50
|
+
// set on unmount only, so a bindingKey rebuild keeps the local cursor and an unmount clears it
|
|
51
|
+
const unmountingRef = useRef(false);
|
|
52
|
+
useEffect(() => {
|
|
53
|
+
unmountingRef.current = false;
|
|
54
|
+
return () => {
|
|
55
|
+
unmountingRef.current = true;
|
|
56
|
+
};
|
|
57
|
+
}, []);
|
|
58
|
+
const [ownBinding, setOwnBinding] = useState(null);
|
|
59
|
+
// bindingOptions changes are ignored until bindingKey changes. The binding is created once per client and key.
|
|
60
|
+
const bindingOptionsRef = useRef(bindingOptions);
|
|
61
|
+
useEffect(() => {
|
|
62
|
+
bindingOptionsRef.current = bindingOptions;
|
|
63
|
+
});
|
|
64
|
+
useEffect(() => {
|
|
65
|
+
if (providedBinding !== undefined)
|
|
66
|
+
return;
|
|
67
|
+
if (client === null)
|
|
68
|
+
return;
|
|
69
|
+
if (!isBrowser())
|
|
70
|
+
return;
|
|
71
|
+
const created = createDomBinding(client, bindingOptionsRef.current);
|
|
72
|
+
setOwnBinding(created);
|
|
73
|
+
return () => {
|
|
74
|
+
// oxlint-disable-next-line react/refs -- read at cleanup time on purpose
|
|
75
|
+
created.dispose({ keepLocalCursor: !unmountingRef.current });
|
|
76
|
+
setOwnBinding(null);
|
|
77
|
+
};
|
|
78
|
+
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- bindingKey is the deliberate rebuild trigger
|
|
79
|
+
}, [client, providedBinding, bindingKey]);
|
|
80
|
+
const activeBinding = providedBinding ?? ownBinding;
|
|
81
|
+
const clientPending = factory !== undefined && providedClient === undefined && ownClient === null;
|
|
82
|
+
const value = useMemo(() => ({ client, binding: activeBinding, clientPending }), [client, activeBinding, clientPending]);
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Provides the presence client and the binding to the tree below.
|
|
87
|
+
* The provider creates and disposes the client from `factory`; a `client` prop stays yours to dispose.
|
|
88
|
+
* The provider creates a DOM binding when you do not pass one.
|
|
89
|
+
* The provider reads `bindingOptions` when it creates the binding. Change `bindingKey` to create a new binding with the latest options, without touching the client.
|
|
90
|
+
* The hooks below it return `unknown` for `user`, `context` and event data, and the provider takes only an untyped client.
|
|
91
|
+
* Use `createPresenceHooks` for typed access.
|
|
92
|
+
*/
|
|
93
|
+
export function PresenceProvider(props) {
|
|
94
|
+
const value = usePresenceProviderValue(props);
|
|
95
|
+
return _jsx(PresenceProviderContext.Provider, { value: value, children: props.children });
|
|
96
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
import type { EventMap, PeerChange, TypedRemoteEvent } from "@dammers/anchor-presence-core";
|
|
3
|
+
import type { ResolvedCursor } from "@dammers/anchor-presence-dom";
|
|
4
|
+
import type { CursorLayerProps } from "./cursor.js";
|
|
5
|
+
import type { PresenceProviderProps } from "./provider.js";
|
|
6
|
+
/**
|
|
7
|
+
* Returns a provider, the hooks and a `CursorLayer` whose types follow the client you give that provider.
|
|
8
|
+
* The hooks read only the provider of the same call, so a client of other types fails to compile.
|
|
9
|
+
* Call it once at module level and export the result.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createPresenceHooks<TContext = unknown, TUser = unknown, TEvents extends object = EventMap>(): {
|
|
12
|
+
PresenceProvider: (props: PresenceProviderProps<TContext, TUser, TEvents>) => ReactNode;
|
|
13
|
+
CursorLayer: (props: CursorLayerProps<TContext, TUser>) => ReactNode;
|
|
14
|
+
useDomBinding: () => import("@dammers/anchor-presence-dom").DomBinding<TContext, TUser> | null;
|
|
15
|
+
usePresenceClient: () => import("@dammers/anchor-presence-core").PresenceClient<TContext, TUser, TEvents> | null;
|
|
16
|
+
useLocalContext: () => [TContext | undefined, (next: TContext | undefined) => void];
|
|
17
|
+
useRemoteEvents: (listener: (event: TypedRemoteEvent<TEvents>) => void) => void;
|
|
18
|
+
useSendEvent: () => <K extends keyof TEvents & string>(type: K, ...data: undefined extends TEvents[K] ? [data?: TEvents[K]] : [data: TEvents[K]]) => boolean;
|
|
19
|
+
useLocalUser: () => [TUser | undefined, (next: TUser | undefined) => void];
|
|
20
|
+
usePeerChanges: (listener: (change: PeerChange<TContext, TUser>) => void) => void;
|
|
21
|
+
useRemotePresence: () => readonly import("@dammers/anchor-presence-core").RemotePresence<TContext, TUser>[];
|
|
22
|
+
usePresenceStatus: () => import("@dammers/anchor-presence-core").ConnectionStatus;
|
|
23
|
+
useRemoteCursors: () => readonly ResolvedCursor<TContext, TUser>[];
|
|
24
|
+
useRemoteCursorsSelector: <TSelected>(select: (cursors: readonly ResolvedCursor<TContext, TUser>[]) => TSelected, isEqual?: (a: TSelected, b: TSelected) => boolean) => TSelected;
|
|
25
|
+
useRemoteUsers: () => readonly import("./index.js").RemoteUser<TUser>[];
|
|
26
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createElement } from "react";
|
|
2
|
+
import { createPresenceContext } from "./context.js";
|
|
3
|
+
import { CursorLayerIn } from "./cursor.js";
|
|
4
|
+
import { usePresenceProviderValue } from "./provider.js";
|
|
5
|
+
import { useDomBindingIn } from "./hooks/use-dom-binding.js";
|
|
6
|
+
import { useLocalContextIn } from "./hooks/use-local-context.js";
|
|
7
|
+
import { useLocalUserIn } from "./hooks/use-local-user.js";
|
|
8
|
+
import { usePeerChangesIn } from "./hooks/use-peer-changes.js";
|
|
9
|
+
import { usePresenceClientIn } from "./hooks/use-presence-client.js";
|
|
10
|
+
import { usePresenceStatusIn } from "./hooks/use-presence-status.js";
|
|
11
|
+
import { useRemoteCursorsIn, useRemoteCursorsSelectorIn } from "./hooks/use-remote-cursors.js";
|
|
12
|
+
import { useRemoteEventsIn } from "./hooks/use-remote-events.js";
|
|
13
|
+
import { useRemotePresenceIn } from "./hooks/use-remote-presence.js";
|
|
14
|
+
import { useRemoteUsersIn } from "./hooks/use-remote-users.js";
|
|
15
|
+
import { useSendEventIn } from "./hooks/use-send-event.js";
|
|
16
|
+
/**
|
|
17
|
+
* Returns a provider, the hooks and a `CursorLayer` whose types follow the client you give that provider.
|
|
18
|
+
* The hooks read only the provider of the same call, so a client of other types fails to compile.
|
|
19
|
+
* Call it once at module level and export the result.
|
|
20
|
+
*/
|
|
21
|
+
export function createPresenceHooks() {
|
|
22
|
+
const context = createPresenceContext();
|
|
23
|
+
return {
|
|
24
|
+
PresenceProvider: (props) => {
|
|
25
|
+
const value = usePresenceProviderValue(props);
|
|
26
|
+
return createElement(context.Provider, { value }, props.children);
|
|
27
|
+
},
|
|
28
|
+
CursorLayer: (props) => createElement(CursorLayerIn, { ...props, context }),
|
|
29
|
+
useDomBinding: () => useDomBindingIn(context),
|
|
30
|
+
usePresenceClient: () => usePresenceClientIn(context),
|
|
31
|
+
useLocalContext: () => useLocalContextIn(context),
|
|
32
|
+
useRemoteEvents: (listener) => useRemoteEventsIn(context, listener),
|
|
33
|
+
useSendEvent: () => useSendEventIn(context),
|
|
34
|
+
useLocalUser: () => useLocalUserIn(context),
|
|
35
|
+
usePeerChanges: (listener) => usePeerChangesIn(context, listener),
|
|
36
|
+
useRemotePresence: () => useRemotePresenceIn(context),
|
|
37
|
+
usePresenceStatus: () => usePresenceStatusIn(context),
|
|
38
|
+
useRemoteCursors: () => useRemoteCursorsIn(context),
|
|
39
|
+
useRemoteCursorsSelector: (select, isEqual) => useRemoteCursorsSelectorIn(context, select, isEqual),
|
|
40
|
+
useRemoteUsers: () => useRemoteUsersIn(context),
|
|
41
|
+
};
|
|
42
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dammers/anchor-presence-react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React hooks, provider, and optional configurable cursor components for anchor-presence",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "DammersCode",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/DammersCode/anchor-presence.git",
|
|
10
|
+
"directory": "packages/react"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/DammersCode/anchor-presence#readme",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"live-cursors",
|
|
15
|
+
"presence",
|
|
16
|
+
"collaboration",
|
|
17
|
+
"multiplayer",
|
|
18
|
+
"cursor",
|
|
19
|
+
"realtime"
|
|
20
|
+
],
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"import": "./dist/index.js",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist"
|
|
38
|
+
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "rm -rf dist tsconfig.tsbuildinfo && tsc --build"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@dammers/anchor-presence-core": "0.1.0",
|
|
44
|
+
"@dammers/anchor-presence-dom": "0.1.0"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"react": ">=18"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/react": "^19.2.18",
|
|
51
|
+
"@types/react-dom": "^19.2.7",
|
|
52
|
+
"react": "^19.2.8",
|
|
53
|
+
"react-dom": "^19.2.8",
|
|
54
|
+
"valibot": "^1.5.0"
|
|
55
|
+
}
|
|
56
|
+
}
|