/
App.jsx
86 lines (78 loc) · 2.34 KB
/
App.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { createSignal, onCleanup, onMount } from "solid-js";
import { Key } from "@solid-primitives/keyed";
import Cursor from "./components/Cursor.jsx";
import styles from "./App.module.css";
const COLORS = [
"#E57373",
"#9575CD",
"#4FC3F7",
"#81C784",
"#FFF176",
"#FF8A65",
"#F06292",
"#7986CB",
];
function App({ room }) {
const [currentUser, setCurrentUser] = createSignal(room.getPresence());
const [users, setUsers] = createSignal([]);
onMount(() => {
const unsubscribePresence = room.subscribe("my-presence", (presence) => {
setCurrentUser(presence);
});
const unsubscribeOthers = room.subscribe("others", (others) => {
const othersWithPresence = others
.toArray()
.filter((other) => other?.presence);
setUsers(othersWithPresence);
});
onCleanup(() => {
unsubscribePresence();
unsubscribeOthers();
});
});
return (
<main
class={styles.App}
onPointerMove={(event) => {
// Update the user cursor position on every pointer move
room.updatePresence({
cursor: {
x: Math.round(event.clientX),
y: Math.round(event.clientY),
},
});
}}
onPointerLeave={() =>
// When the pointer leaves, set cursor to null
room.updatePresence({
cursor: null,
})
}
>
<div class={styles.Text}>
{currentUser().cursor
? `${currentUser().cursor.x} × ${currentUser().cursor.y}`
: "Move your cursor to broadcast its position to other people in the room."}
</div>
{/*
<For> will fully rerender components on each update and break animations.
This is because it uses referential equality, and we're creating new
objects every render inside `room.subscribe`. Here we're using a keyed loop
from @solid-primitives with `user => user.connectionId` as the key, to
retain the elements and their animations.
*/}
<Key each={users()} by="connectionId">
{(user) => (
<Show when={user().presence?.cursor}>
<Cursor
x={user().presence.cursor.x}
y={user().presence.cursor.y}
color={COLORS[user().connectionId % COLORS.length]}
/>
</Show>
)}
</Key>
</main>
);
}
export default App;