@dammers/anchor-presence-dom 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 +83 -2
- package/dist/auto-register.d.ts +14 -0
- package/dist/auto-register.js +154 -0
- package/dist/binding.d.ts +112 -0
- package/dist/binding.js +154 -0
- package/dist/broadcast-transport.d.ts +14 -0
- package/dist/broadcast-transport.js +79 -0
- package/dist/dom-tree.d.ts +3 -0
- package/dist/dom-tree.js +15 -0
- package/dist/frame-cache.d.ts +21 -0
- package/dist/frame-cache.js +62 -0
- package/dist/geometry.d.ts +10 -0
- package/dist/geometry.js +2 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +4 -0
- package/dist/internal/signals.d.ts +20 -0
- package/dist/internal/signals.js +259 -0
- package/dist/occlusion.d.ts +6 -0
- package/dist/occlusion.js +61 -0
- package/dist/pointer.d.ts +21 -0
- package/dist/pointer.js +176 -0
- package/dist/registry.d.ts +14 -0
- package/dist/registry.js +72 -0
- package/dist/resolver.d.ts +101 -0
- package/dist/resolver.js +299 -0
- package/dist/scheduler.d.ts +67 -0
- package/dist/scheduler.js +144 -0
- package/dist/transport.d.ts +84 -0
- package/dist/transport.js +320 -0
- package/package.json +43 -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,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dammers/anchor-presence-dom
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@dammers/anchor-presence-dom` is the browser layer of Anchor Presence. It registers anchors, samples the pointer, measures elements, and turns remote cursor data into screen positions.
|
|
4
|
+
|
|
5
|
+
[](../../LICENSE)
|
|
6
|
+
|
|
7
|
+
This sample binds a client to the page and draws each visible remote cursor:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createPresenceClient } from "@dammers/anchor-presence-core";
|
|
11
|
+
import { createDomBinding } from "@dammers/anchor-presence-dom";
|
|
12
|
+
|
|
13
|
+
const client = createPresenceClient({ transport: myTransport });
|
|
14
|
+
const binding = createDomBinding(client);
|
|
15
|
+
|
|
16
|
+
// <button data-anchor="nav.dashboard"></button> is a live anchor.
|
|
17
|
+
|
|
18
|
+
binding.subscribe(() => {
|
|
19
|
+
for (const cursor of binding.getSnapshot()) {
|
|
20
|
+
if (cursor.visible) renderCursor(cursor.clientId, cursor.x, cursor.y);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Boundary rule
|
|
26
|
+
|
|
27
|
+
`@dammers/anchor-presence-dom` is the package that reads the DOM layout and the pointer with `getBoundingClientRect`, `ResizeObserver`, `MutationObserver`, `requestAnimationFrame`, and pointer events. `@dammers/anchor-presence-core` has no DOM code and listens only for `visibilitychange`. Framework adapters read from `@dammers/anchor-presence-dom`, never from the browser directly.
|
|
28
|
+
|
|
29
|
+
## Main exports
|
|
30
|
+
|
|
31
|
+
| Export | What it does |
|
|
32
|
+
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
33
|
+
| `createDomBinding(client, options?)` | Connects anchor auto-registration, pointer sampling, geometry scheduling, and remote resolution to a `PresenceClient`. Returns a `DomBinding`. |
|
|
34
|
+
| `DomBinding` | `invalidate(reason?)` marks the layout dirty for the next frame. `getSnapshot()`, `subscribe(listener)`, and `dispose()` read and manage resolved cursors. `getAnchorElement(anchorId)` returns the element of an anchor, or `null`. |
|
|
35
|
+
| `createWebSocketTransport(options?)` | Native WebSocket transport for the bundled relay or a compatible relay. It has `bufferedBytes()` and a random delay between reconnect attempts. |
|
|
36
|
+
| `createBroadcastChannelTransport(channelName)` | `BroadcastChannel` transport for the tabs and iframes of one origin. It needs no server. |
|
|
37
|
+
| `DomBindingOptions`, `ResolutionOptions`, `EnvironmentOptions` | Binding configuration types |
|
|
38
|
+
| `WebSocketTransportOptions` | WebSocket transport configuration types |
|
|
39
|
+
| `ResolvedCursor`, `ResolutionTier`, `VisibilityPolicy` | Resolution types |
|
|
40
|
+
|
|
41
|
+
## Binding options
|
|
42
|
+
|
|
43
|
+
`createDomBinding` always watches the DOM for anchor elements. The binding options have this shape:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
type DomBindingOptions = {
|
|
47
|
+
anchorAttribute?: string;
|
|
48
|
+
privateAttribute?: string;
|
|
49
|
+
maxSentAnchors?: number;
|
|
50
|
+
resolution?: ResolutionOptions;
|
|
51
|
+
environment?: EnvironmentOptions;
|
|
52
|
+
capturePointer?: boolean;
|
|
53
|
+
captureFocus?: boolean;
|
|
54
|
+
};
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The `anchorAttribute` field names the attribute whose value is the anchor ID. The default is `"data-anchor"`. The name must start with a letter and contain only letters, digits, and single hyphens, for example `"id"` or `"data-presence"`. For another name, such as `"data_anchor"`, `createDomBinding` throws a `TypeError`.
|
|
58
|
+
|
|
59
|
+
The `privateAttribute` field names the attribute that keeps the cursor private. The default is `"data-anchor-private"`. Over an element with it, and over its descendants, the binding sends no cursor. It follows the same name rule as `anchorAttribute`.
|
|
60
|
+
|
|
61
|
+
The `resolution` group (`ResolutionOptions`) controls how remote cursors turn into screen positions. It holds `visibilityPolicy`, `interpolatorFactory`, and `hitTest`.
|
|
62
|
+
|
|
63
|
+
The `environment` group (`EnvironmentOptions`) supplies the DOM and timing hosts: `root`, `window`, `raf`, `caf`, `ResizeObserverCtor`, and `MutationObserverCtor`. Each field defaults to the matching browser global. Tests can replace one host without touching the others.
|
|
64
|
+
|
|
65
|
+
`capturePointer` defaults to `true`. If it is `false`, the local pointer publishes no cursor, and context and user still reach peers (other clients in the same room). `captureFocus` defaults to `false`. If it is `true` and local capture is on, a focus change publishes a cursor at the center of the focused element.
|
|
66
|
+
|
|
67
|
+
### Anchor attributes
|
|
68
|
+
|
|
69
|
+
An element is an anchor when it has a non-empty value for the configured attribute. This binding reads anchors from `data-presence`:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
const binding = createDomBinding(client, {
|
|
73
|
+
anchorAttribute: "data-presence",
|
|
74
|
+
maxSentAnchors: 4,
|
|
75
|
+
resolution: { hitTest: true },
|
|
76
|
+
environment: { raf, caf },
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// <div data-presence="nav.dashboard"></div> is a live anchor.
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The binding ignores an empty value or a value with only whitespace. A change of the attribute value registers the element again under the new ID. If you remove the attribute or the element, the binding unregisters the anchor. For a duplicate anchor ID, the binding uses the newest registration and warns one time in development.
|
|
83
|
+
|
|
84
|
+
See [How it works](https://anchor-presence.vercel.app/docs/get-started/concepts/how-it-works) and [Responsive layouts](https://anchor-presence.vercel.app/docs/get-started/concepts/responsive-layouts) for full guides.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AnchorRegistry } from "./registry.js";
|
|
2
|
+
import type { MutationObserverCtor } from "./scheduler.js";
|
|
3
|
+
export type AutoRegisterOptions = {
|
|
4
|
+
attribute: string;
|
|
5
|
+
root?: ParentNode | undefined;
|
|
6
|
+
registry: AnchorRegistry;
|
|
7
|
+
MutationObserverCtor?: MutationObserverCtor | undefined;
|
|
8
|
+
};
|
|
9
|
+
export type AutoRegisterHandle = {
|
|
10
|
+
setEnabled(enabled: boolean): void;
|
|
11
|
+
handleRecords(records?: MutationRecord[]): void;
|
|
12
|
+
dispose(): void;
|
|
13
|
+
};
|
|
14
|
+
export declare function startAutoRegister(options: AutoRegisterOptions): AutoRegisterHandle;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { isDevMode } from "@dammers/anchor-presence-core";
|
|
2
|
+
function defaultMutationObserverCtor() {
|
|
3
|
+
return typeof MutationObserver !== "undefined" ? MutationObserver : undefined;
|
|
4
|
+
}
|
|
5
|
+
function isElement(node) {
|
|
6
|
+
return node.nodeType === 1;
|
|
7
|
+
}
|
|
8
|
+
export function startAutoRegister(options) {
|
|
9
|
+
const attribute = options.attribute;
|
|
10
|
+
const root = options.root ?? document;
|
|
11
|
+
const registry = options.registry;
|
|
12
|
+
const MutationObserverImpl = options.MutationObserverCtor ?? defaultMutationObserverCtor();
|
|
13
|
+
const autoAnchors = new Map();
|
|
14
|
+
const warnedEmpty = new WeakSet();
|
|
15
|
+
let disposed = false;
|
|
16
|
+
let enabled = true;
|
|
17
|
+
const observer = MutationObserverImpl !== undefined ? new MutationObserverImpl((records) => handleRecords(records)) : null;
|
|
18
|
+
function connectObserver() {
|
|
19
|
+
if (disposed || !enabled || observer === null)
|
|
20
|
+
return;
|
|
21
|
+
observer.observe(root, {
|
|
22
|
+
childList: true,
|
|
23
|
+
subtree: true,
|
|
24
|
+
attributes: true,
|
|
25
|
+
attributeFilter: [attribute],
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function disconnectObserver() {
|
|
29
|
+
observer?.disconnect();
|
|
30
|
+
}
|
|
31
|
+
function handleRecords(records) {
|
|
32
|
+
if (disposed)
|
|
33
|
+
return;
|
|
34
|
+
if (records === undefined || records.length === 0) {
|
|
35
|
+
sync();
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const replacedIds = new Set();
|
|
39
|
+
for (const record of records) {
|
|
40
|
+
if (record.type === "attributes") {
|
|
41
|
+
if (record.attributeName === attribute && isElement(record.target)) {
|
|
42
|
+
const previous = autoAnchors.get(record.target);
|
|
43
|
+
syncElement(record.target);
|
|
44
|
+
if (previous !== undefined && autoAnchors.get(record.target)?.id !== previous.id)
|
|
45
|
+
replacedIds.add(previous.id);
|
|
46
|
+
}
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
for (const node of Array.from(record.removedNodes))
|
|
50
|
+
releaseNode(node, replacedIds);
|
|
51
|
+
for (const node of Array.from(record.addedNodes))
|
|
52
|
+
adoptNode(node);
|
|
53
|
+
}
|
|
54
|
+
// one querySelectorAll pass for every id a removal replaced, instead of one pass per id
|
|
55
|
+
if (replacedIds.size > 0)
|
|
56
|
+
resyncIds(replacedIds);
|
|
57
|
+
}
|
|
58
|
+
function warnEmpty(element) {
|
|
59
|
+
if (!isDevMode() || warnedEmpty.has(element))
|
|
60
|
+
return;
|
|
61
|
+
warnedEmpty.add(element);
|
|
62
|
+
console.warn(`[anchor-presence] empty ${attribute} value ignored`, { attribute, element });
|
|
63
|
+
}
|
|
64
|
+
function autoUnregister(element) {
|
|
65
|
+
const entry = autoAnchors.get(element);
|
|
66
|
+
if (entry === undefined)
|
|
67
|
+
return;
|
|
68
|
+
autoAnchors.delete(element);
|
|
69
|
+
entry.unregister();
|
|
70
|
+
}
|
|
71
|
+
function registerAuto(element, id) {
|
|
72
|
+
const unregister = registry.register(id, element);
|
|
73
|
+
autoAnchors.set(element, { id, unregister });
|
|
74
|
+
}
|
|
75
|
+
function syncElement(element) {
|
|
76
|
+
const id = element.getAttribute(attribute)?.trim() ?? "";
|
|
77
|
+
if (id === "") {
|
|
78
|
+
autoUnregister(element);
|
|
79
|
+
warnEmpty(element);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const existing = autoAnchors.get(element);
|
|
83
|
+
if (existing === undefined || existing.id !== id || registry.get(id) === null) {
|
|
84
|
+
autoUnregister(element);
|
|
85
|
+
registerAuto(element, id);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// one querySelectorAll pass covers every id in `ids`, instead of one pass per id
|
|
89
|
+
function resyncIds(ids) {
|
|
90
|
+
for (const element of Array.from(root.querySelectorAll(`[${attribute}]`))) {
|
|
91
|
+
const id = element.getAttribute(attribute)?.trim() ?? "";
|
|
92
|
+
if (ids.has(id))
|
|
93
|
+
syncElement(element);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function adoptNode(node) {
|
|
97
|
+
if (!isElement(node))
|
|
98
|
+
return;
|
|
99
|
+
if (node.hasAttribute(attribute))
|
|
100
|
+
syncElement(node);
|
|
101
|
+
for (const element of Array.from(node.querySelectorAll(`[${attribute}]`)))
|
|
102
|
+
syncElement(element);
|
|
103
|
+
}
|
|
104
|
+
// accumulates the ids this removal frees into `replacedIds`; the caller resyncs them in one pass
|
|
105
|
+
function releaseNode(node, replacedIds) {
|
|
106
|
+
if (!isElement(node))
|
|
107
|
+
return;
|
|
108
|
+
const release = (element) => {
|
|
109
|
+
const entry = autoAnchors.get(element);
|
|
110
|
+
if (entry !== undefined)
|
|
111
|
+
replacedIds.add(entry.id);
|
|
112
|
+
autoUnregister(element);
|
|
113
|
+
};
|
|
114
|
+
release(node);
|
|
115
|
+
for (const element of Array.from(node.querySelectorAll(`[${attribute}]`)))
|
|
116
|
+
release(element);
|
|
117
|
+
}
|
|
118
|
+
function sync() {
|
|
119
|
+
if (disposed)
|
|
120
|
+
return;
|
|
121
|
+
const live = new Set(Array.from(root.querySelectorAll(`[${attribute}]`)));
|
|
122
|
+
for (const element of autoAnchors.keys()) {
|
|
123
|
+
if (!live.has(element))
|
|
124
|
+
autoUnregister(element);
|
|
125
|
+
}
|
|
126
|
+
for (const element of live)
|
|
127
|
+
syncElement(element);
|
|
128
|
+
}
|
|
129
|
+
connectObserver();
|
|
130
|
+
sync();
|
|
131
|
+
return {
|
|
132
|
+
setEnabled(next) {
|
|
133
|
+
if (disposed || enabled === next)
|
|
134
|
+
return;
|
|
135
|
+
enabled = next;
|
|
136
|
+
if (enabled) {
|
|
137
|
+
connectObserver();
|
|
138
|
+
sync();
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
disconnectObserver();
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
handleRecords,
|
|
145
|
+
dispose() {
|
|
146
|
+
if (disposed)
|
|
147
|
+
return;
|
|
148
|
+
disposed = true;
|
|
149
|
+
disconnectObserver();
|
|
150
|
+
for (const element of autoAnchors.keys())
|
|
151
|
+
autoUnregister(element);
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { EventMap, InterpolatorFactory, PresenceClient } from "@dammers/anchor-presence-core";
|
|
2
|
+
import type { CafLike, MutationObserverCtor, RafLike, ResizeObserverCtor } from "./scheduler.js";
|
|
3
|
+
import type { ResolvedCursor, VisibilityPolicy } from "./resolver.js";
|
|
4
|
+
/**
|
|
5
|
+
* How remote cursors turn into screen positions.
|
|
6
|
+
*/
|
|
7
|
+
export type ResolutionOptions<TContext = unknown, TUser = unknown> = {
|
|
8
|
+
/**
|
|
9
|
+
* Shows or hides one cursor.
|
|
10
|
+
* @default hides a cursor that does not resolve
|
|
11
|
+
*/
|
|
12
|
+
visibilityPolicy?: VisibilityPolicy<TContext, TUser> | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* Creates the interpolator per remote client.
|
|
15
|
+
* @default `linearInterpolator`, or `noneInterpolator` when the OS prefers reduced motion
|
|
16
|
+
*/
|
|
17
|
+
interpolatorFactory?: InterpolatorFactory | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* Runs a DOM hit test on the resolved point.
|
|
20
|
+
* @default false
|
|
21
|
+
*/
|
|
22
|
+
hitTest?: boolean | undefined;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* The DOM and timing hosts the binding runs against.
|
|
26
|
+
* Every field defaults to the browser globals.
|
|
27
|
+
*/
|
|
28
|
+
export type EnvironmentOptions = {
|
|
29
|
+
/** The document root to watch. Default: the global `document`. */
|
|
30
|
+
root?: Document | undefined;
|
|
31
|
+
/** The window for pointer and scroll events. Default: the global `window`. */
|
|
32
|
+
window?: Window | undefined;
|
|
33
|
+
/** The requestAnimationFrame function to use. Default: the global one. */
|
|
34
|
+
raf?: RafLike | undefined;
|
|
35
|
+
/** The cancelAnimationFrame function to use. Default: the global one. */
|
|
36
|
+
caf?: CafLike | undefined;
|
|
37
|
+
/** The ResizeObserver constructor to use. Default: the global one. */
|
|
38
|
+
ResizeObserverCtor?: ResizeObserverCtor | undefined;
|
|
39
|
+
/** The MutationObserver constructor to use. Default: the global one. */
|
|
40
|
+
MutationObserverCtor?: MutationObserverCtor | undefined;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Options for `createDomBinding`.
|
|
44
|
+
*/
|
|
45
|
+
export type DomBindingOptions<TContext = unknown, TUser = unknown> = {
|
|
46
|
+
/**
|
|
47
|
+
* Attribute whose value is the anchor ID.
|
|
48
|
+
* @default "data-anchor"
|
|
49
|
+
*/
|
|
50
|
+
anchorAttribute?: string | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Attribute that keeps the cursor private: over the element and its descendants the binding sends no cursor.
|
|
53
|
+
* @default "data-anchor-private"
|
|
54
|
+
*/
|
|
55
|
+
privateAttribute?: string | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* Maximum anchors in the outbound fallback chain, clamped to `1` through `8`.
|
|
58
|
+
* @default 4
|
|
59
|
+
*/
|
|
60
|
+
maxSentAnchors?: number | undefined;
|
|
61
|
+
/** Settings for how remote cursors resolve. Omit for the defaults. */
|
|
62
|
+
resolution?: ResolutionOptions<TContext, TUser> | undefined;
|
|
63
|
+
/** The DOM and timing hosts the binding runs against. Omit for the browser globals. */
|
|
64
|
+
environment?: EnvironmentOptions | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Whether the local pointer publishes a cursor.
|
|
67
|
+
* When `false` the client stays presence-only: context and user still flow, no local cursor.
|
|
68
|
+
* @default true
|
|
69
|
+
*/
|
|
70
|
+
capturePointer?: boolean | undefined;
|
|
71
|
+
/**
|
|
72
|
+
* Publish a cursor at the focused element's center on focus changes.
|
|
73
|
+
* Ignored when `capturePointer` is `false`.
|
|
74
|
+
* @default false
|
|
75
|
+
*/
|
|
76
|
+
captureFocus?: boolean | undefined;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* The resolved-cursor surface of one client.
|
|
80
|
+
*/
|
|
81
|
+
export type DomBinding<TContext = unknown, TUser = unknown> = {
|
|
82
|
+
/**
|
|
83
|
+
* Marks the layout as dirty.
|
|
84
|
+
* The binding re-resolves the cursors on the next frame.
|
|
85
|
+
* @param reason An optional name for the trigger.
|
|
86
|
+
*/
|
|
87
|
+
invalidate(reason?: string): void;
|
|
88
|
+
/** Returns the last resolved cursors. */
|
|
89
|
+
getSnapshot(): readonly ResolvedCursor<TContext, TUser>[];
|
|
90
|
+
/** Returns the element the resolver uses for an anchor id: the newest one when ids repeat, `null` when none is connected. */
|
|
91
|
+
getAnchorElement(anchorId: string): Element | null;
|
|
92
|
+
/**
|
|
93
|
+
* Adds a listener for new cursor snapshots.
|
|
94
|
+
* @returns A function that removes the listener.
|
|
95
|
+
*/
|
|
96
|
+
subscribe(listener: () => void): () => void;
|
|
97
|
+
/**
|
|
98
|
+
* Stops the binding, then sends one final empty snapshot to its listeners and clears them.
|
|
99
|
+
* It also clears the local cursor on the client, unless you pass `keepLocalCursor`, for example when you rebuild the binding.
|
|
100
|
+
*/
|
|
101
|
+
dispose(options?: {
|
|
102
|
+
keepLocalCursor?: boolean | undefined;
|
|
103
|
+
}): void;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* Creates the DOM side of one client.
|
|
107
|
+
* The binding watches local anchors, remote presences, and layout changes, then publishes resolved cursors.
|
|
108
|
+
* @param client The client the binding reads from.
|
|
109
|
+
* @param options Optional binding settings.
|
|
110
|
+
* @returns The binding.
|
|
111
|
+
*/
|
|
112
|
+
export declare function createDomBinding<TContext = unknown, TUser = unknown, TEvents extends object = EventMap>(client: PresenceClient<TContext, TUser, TEvents>, options?: DomBindingOptions<TContext, TUser>): DomBinding<TContext, TUser>;
|
package/dist/binding.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Top-level wiring: registry, pointer, scheduler, and resolver. The React adapter consumes it.
|
|
2
|
+
import { linearInterpolator, noneInterpolator, reportListenerError } from "@dammers/anchor-presence-core";
|
|
3
|
+
import { createAnchorRegistry } from "./registry.js";
|
|
4
|
+
import { attachPointerSource } from "./pointer.js";
|
|
5
|
+
import { createGeometryScheduler } from "./scheduler.js";
|
|
6
|
+
import { startAutoRegister } from "./auto-register.js";
|
|
7
|
+
import { RemoteResolver } from "./resolver.js";
|
|
8
|
+
const ANCHOR_ATTRIBUTE_PATTERN = /^[A-Za-z][A-Za-z0-9]*(-[A-Za-z0-9]+)*$/u;
|
|
9
|
+
const DEFAULT_ANCHOR_ATTRIBUTE = "data-anchor";
|
|
10
|
+
const DEFAULT_PRIVATE_ATTRIBUTE = "data-anchor-private";
|
|
11
|
+
const DEFAULT_SENT_ANCHORS = 4;
|
|
12
|
+
const PROTOCOL_MAX_ANCHORS = 8;
|
|
13
|
+
// evaluated lazily inside createDomBinding, never at import time, so this stays SSR-safe
|
|
14
|
+
function prefersReducedMotion(win) {
|
|
15
|
+
const target = win ?? (typeof window !== "undefined" ? window : undefined);
|
|
16
|
+
return target?.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
|
|
17
|
+
}
|
|
18
|
+
function defaultInterpolatorFactory(win) {
|
|
19
|
+
return prefersReducedMotion(win) ? noneInterpolator : linearInterpolator;
|
|
20
|
+
}
|
|
21
|
+
const EMPTY_SNAPSHOT = [];
|
|
22
|
+
/**
|
|
23
|
+
* Creates the DOM side of one client.
|
|
24
|
+
* The binding watches local anchors, remote presences, and layout changes, then publishes resolved cursors.
|
|
25
|
+
* @param client The client the binding reads from.
|
|
26
|
+
* @param options Optional binding settings.
|
|
27
|
+
* @returns The binding.
|
|
28
|
+
*/
|
|
29
|
+
export function createDomBinding(client, options = {}) {
|
|
30
|
+
const { resolution = {}, environment = {} } = options;
|
|
31
|
+
const anchorAttribute = options.anchorAttribute ?? DEFAULT_ANCHOR_ATTRIBUTE;
|
|
32
|
+
if (!ANCHOR_ATTRIBUTE_PATTERN.test(anchorAttribute)) {
|
|
33
|
+
throw new TypeError(`createDomBinding: anchorAttribute must be letters and digits in hyphen-separated groups, such as data-anchor, got "${anchorAttribute}"`);
|
|
34
|
+
}
|
|
35
|
+
const privateAttribute = options.privateAttribute ?? DEFAULT_PRIVATE_ATTRIBUTE;
|
|
36
|
+
if (!ANCHOR_ATTRIBUTE_PATTERN.test(privateAttribute)) {
|
|
37
|
+
throw new TypeError(`createDomBinding: privateAttribute must be letters and digits in hyphen-separated groups, such as data-anchor-private, got "${privateAttribute}"`);
|
|
38
|
+
}
|
|
39
|
+
let sentAnchors = DEFAULT_SENT_ANCHORS;
|
|
40
|
+
if (options.maxSentAnchors !== undefined) {
|
|
41
|
+
if (!Number.isInteger(options.maxSentAnchors)) {
|
|
42
|
+
throw new TypeError(`createDomBinding: maxSentAnchors must be a finite integer, got ${String(options.maxSentAnchors)}`);
|
|
43
|
+
}
|
|
44
|
+
sentAnchors = Math.min(PROTOCOL_MAX_ANCHORS, Math.max(1, options.maxSentAnchors));
|
|
45
|
+
}
|
|
46
|
+
const registry = createAnchorRegistry();
|
|
47
|
+
const autoOptions = {
|
|
48
|
+
attribute: anchorAttribute,
|
|
49
|
+
registry,
|
|
50
|
+
};
|
|
51
|
+
if (environment.root !== undefined)
|
|
52
|
+
autoOptions.root = environment.root;
|
|
53
|
+
if (environment.MutationObserverCtor !== undefined)
|
|
54
|
+
autoOptions.MutationObserverCtor = environment.MutationObserverCtor;
|
|
55
|
+
const autoHandle = startAutoRegister(autoOptions);
|
|
56
|
+
const interpolatorFactory = resolution.interpolatorFactory ?? defaultInterpolatorFactory(environment.window);
|
|
57
|
+
const resolver = new RemoteResolver({ registry, ...resolution, interpolatorFactory });
|
|
58
|
+
let snapshot = EMPTY_SNAPSHOT;
|
|
59
|
+
const snapshotListeners = new Set();
|
|
60
|
+
function notifySnapshotListeners() {
|
|
61
|
+
for (const listener of snapshotListeners) {
|
|
62
|
+
try {
|
|
63
|
+
listener();
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
reportListenerError(error);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// while our own connection is down, remote cursors are ghosts: hide them until it is back
|
|
71
|
+
const isLive = () => {
|
|
72
|
+
const status = client.getStatus();
|
|
73
|
+
return status !== "reconnecting" && status !== "disconnected";
|
|
74
|
+
};
|
|
75
|
+
const scheduler = createGeometryScheduler({
|
|
76
|
+
hasActiveCursors: () => isLive() &&
|
|
77
|
+
(client.hasActiveCursors?.() ??
|
|
78
|
+
client.getRemoteSnapshot().some((presence) => presence.cursor !== null)),
|
|
79
|
+
compute(readState, timestampMs) {
|
|
80
|
+
const idleClientIds = new Set();
|
|
81
|
+
for (const presence of client.getRemotePresence()) {
|
|
82
|
+
if (presence.idle)
|
|
83
|
+
idleClientIds.add(presence.clientId);
|
|
84
|
+
}
|
|
85
|
+
const { cursors, unsettled, activeAnchors } = resolver.resolveAll(isLive() ? client.getRemoteSnapshot() : [], readState, timestampMs, (clientId) => idleClientIds.has(clientId));
|
|
86
|
+
const documentElement = (environment.root ?? document).documentElement;
|
|
87
|
+
activeAnchors.push(documentElement);
|
|
88
|
+
return { snapshot: cursors, activeAnchors, needsAnotherFrame: unsettled };
|
|
89
|
+
},
|
|
90
|
+
notify(next) {
|
|
91
|
+
snapshot = next;
|
|
92
|
+
notifySnapshotListeners();
|
|
93
|
+
},
|
|
94
|
+
onRegistryChange: (listener) => registry.onChange(listener),
|
|
95
|
+
onRemoteData: (listener) => {
|
|
96
|
+
const stopRemote = client.subscribeRemote(listener);
|
|
97
|
+
const stopStatus = client.subscribeStatus(() => listener());
|
|
98
|
+
return () => {
|
|
99
|
+
stopRemote();
|
|
100
|
+
stopStatus();
|
|
101
|
+
};
|
|
102
|
+
},
|
|
103
|
+
onMutationRecords: (records) => autoHandle.handleRecords(records),
|
|
104
|
+
onAttach: () => autoHandle.setEnabled(false),
|
|
105
|
+
onDetach: () => autoHandle.setEnabled(true),
|
|
106
|
+
...environment,
|
|
107
|
+
});
|
|
108
|
+
const pointerHandle = options.capturePointer !== false
|
|
109
|
+
? attachPointerSource(client, registry, {
|
|
110
|
+
maxAnchors: sentAnchors,
|
|
111
|
+
root: environment.root,
|
|
112
|
+
window: environment.window,
|
|
113
|
+
getCachedRect: (element) => scheduler.getCachedRect(element),
|
|
114
|
+
captureFocus: options.captureFocus ?? false,
|
|
115
|
+
privateAttribute,
|
|
116
|
+
})
|
|
117
|
+
: { detach() { } };
|
|
118
|
+
// a closed tab never disposes the client: tell peers on pagehide, and the next publish rejoins
|
|
119
|
+
const pageWindow = environment.window ?? (typeof window === "undefined" ? undefined : window);
|
|
120
|
+
const leaveOnPageHide = () => client.leave();
|
|
121
|
+
pageWindow?.addEventListener("pagehide", leaveOnPageHide);
|
|
122
|
+
let disposed = false;
|
|
123
|
+
let unregisterTeardown;
|
|
124
|
+
function dispose(disposeOptions) {
|
|
125
|
+
if (disposed)
|
|
126
|
+
return;
|
|
127
|
+
disposed = true;
|
|
128
|
+
// a consumer-owned client stays alive: do not leave the last cursor on peers
|
|
129
|
+
if (disposeOptions?.keepLocalCursor !== true)
|
|
130
|
+
client.setLocalCursor(null);
|
|
131
|
+
pageWindow?.removeEventListener("pagehide", leaveOnPageHide);
|
|
132
|
+
unregisterTeardown?.();
|
|
133
|
+
autoHandle?.dispose();
|
|
134
|
+
scheduler.dispose();
|
|
135
|
+
pointerHandle.detach();
|
|
136
|
+
// final empty snapshot so subscribers render cursors gone before the signals go quiet
|
|
137
|
+
snapshot = EMPTY_SNAPSHOT;
|
|
138
|
+
notifySnapshotListeners();
|
|
139
|
+
snapshotListeners.clear();
|
|
140
|
+
}
|
|
141
|
+
unregisterTeardown = client.registerTeardown(dispose);
|
|
142
|
+
return {
|
|
143
|
+
invalidate: (reason) => scheduler.invalidate(reason),
|
|
144
|
+
getSnapshot: () => snapshot,
|
|
145
|
+
getAnchorElement: (anchorId) => registry.get(anchorId),
|
|
146
|
+
subscribe(listener) {
|
|
147
|
+
snapshotListeners.add(listener);
|
|
148
|
+
return () => {
|
|
149
|
+
snapshotListeners.delete(listener);
|
|
150
|
+
};
|
|
151
|
+
},
|
|
152
|
+
dispose,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ConnectionStatus, PresenceTransport } from "@dammers/anchor-presence-core";
|
|
2
|
+
/** A transport that connects and disconnects on demand, with required status members. */
|
|
3
|
+
export type BroadcastChannelTransport = PresenceTransport & {
|
|
4
|
+
connect(): void;
|
|
5
|
+
disconnect(): void;
|
|
6
|
+
subscribeStatus(listener: (status: ConnectionStatus) => void): () => void;
|
|
7
|
+
getStatus(): ConnectionStatus;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Creates a `PresenceTransport` over `BroadcastChannel`. It links tabs and iframes of one origin, with no server.
|
|
11
|
+
* Each transport ignores its own messages, so two clients in one tab need two transports.
|
|
12
|
+
* Any script of the same origin can post on the channel, so keep the default shape check on.
|
|
13
|
+
*/
|
|
14
|
+
export declare function createBroadcastChannelTransport(channelName: string): BroadcastChannelTransport;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { reportListenerError, warnOnce } from "@dammers/anchor-presence-core";
|
|
2
|
+
function toBytes(value) {
|
|
3
|
+
if (!ArrayBuffer.isView(value))
|
|
4
|
+
return null;
|
|
5
|
+
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Creates a `PresenceTransport` over `BroadcastChannel`. It links tabs and iframes of one origin, with no server.
|
|
9
|
+
* Each transport ignores its own messages, so two clients in one tab need two transports.
|
|
10
|
+
* Any script of the same origin can post on the channel, so keep the default shape check on.
|
|
11
|
+
*/
|
|
12
|
+
export function createBroadcastChannelTransport(channelName) {
|
|
13
|
+
const selfId = Math.random().toString(36).slice(2);
|
|
14
|
+
const listeners = new Set();
|
|
15
|
+
const statusListeners = new Set();
|
|
16
|
+
let channel = null;
|
|
17
|
+
let status = "disconnected";
|
|
18
|
+
const setStatus = (next) => {
|
|
19
|
+
status = next;
|
|
20
|
+
for (const listener of statusListeners) {
|
|
21
|
+
try {
|
|
22
|
+
listener(next);
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
reportListenerError(error);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const onMessage = (event) => {
|
|
30
|
+
const message = event.data;
|
|
31
|
+
if (typeof message !== "object" || message === null || message.from === selfId)
|
|
32
|
+
return;
|
|
33
|
+
const bytes = toBytes(message.data);
|
|
34
|
+
if (bytes === null)
|
|
35
|
+
return;
|
|
36
|
+
for (const listener of listeners) {
|
|
37
|
+
try {
|
|
38
|
+
listener(bytes);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
reportListenerError(error);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
connect() {
|
|
47
|
+
if (channel !== null)
|
|
48
|
+
return;
|
|
49
|
+
channel = new BroadcastChannel(channelName);
|
|
50
|
+
channel.addEventListener("message", onMessage);
|
|
51
|
+
setStatus("connected");
|
|
52
|
+
},
|
|
53
|
+
disconnect() {
|
|
54
|
+
channel?.close();
|
|
55
|
+
channel = null;
|
|
56
|
+
setStatus("disconnected");
|
|
57
|
+
},
|
|
58
|
+
send(data) {
|
|
59
|
+
if (channel === null) {
|
|
60
|
+
warnOnce("broadcast-send-while-disconnected", "a BroadcastChannel transport dropped a message because it is not connected.");
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel has no target origin
|
|
64
|
+
channel.postMessage({ from: selfId, data });
|
|
65
|
+
},
|
|
66
|
+
subscribe(listener) {
|
|
67
|
+
listeners.add(listener);
|
|
68
|
+
return () => listeners.delete(listener);
|
|
69
|
+
},
|
|
70
|
+
subscribeStatus(listener) {
|
|
71
|
+
listener(status);
|
|
72
|
+
statusListeners.add(listener);
|
|
73
|
+
return () => statusListeners.delete(listener);
|
|
74
|
+
},
|
|
75
|
+
getStatus() {
|
|
76
|
+
return status;
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
package/dist/dom-tree.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Shared internal tree walk — used by occlusion (§10), registry (§8), and resolver (§10)
|
|
2
|
+
/** Walks up one step through ancestors, crossing shadow boundaries via `host`. */
|
|
3
|
+
export function parentAcrossShadow(element) {
|
|
4
|
+
const parent = element.parentElement;
|
|
5
|
+
if (parent !== null)
|
|
6
|
+
return parent;
|
|
7
|
+
const root = element.getRootNode();
|
|
8
|
+
if (isShadowRoot(root))
|
|
9
|
+
return root.host;
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
// nodeType instead of instanceof: a node of an iframe belongs to another realm
|
|
13
|
+
export function isShadowRoot(node) {
|
|
14
|
+
return node.nodeType === 11 && "host" in node;
|
|
15
|
+
}
|