@morl99/slidev-addon-sync 0.0.0-stage → 1.0.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/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Smile.
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,253 @@
1
- # Temporary Holding Version
1
+ # slidev-addon-sync
2
+
3
+ Synchronize [Slidev](https://sli.dev/) presentations across browsers using Server-Sent Events (SSE) or WebSocket connections.
4
+
5
+ This is an updated fork of [Smile-SA/slidev-addon-sync](https://github.com/Smile-SA/slidev-addon-sync). Many thanks to Tony Cabaye and the upstream contributors for creating the original project.
6
+
7
+ Use it with [Morl99/slidev-sync-server](https://github.com/Morl99/slidev-sync-server). The presenter and viewers connect to the same server and group ID to share navigation and other configured state.
8
+
9
+ ## Installation
10
+
11
+ Install the public package from [npm](https://www.npmjs.com/package/@morl99/slidev-addon-sync):
12
+
13
+ ```bash
14
+ pnpm add @morl99/slidev-addon-sync
15
+ ```
16
+
17
+ No login or custom registry configuration is required. Check the supported
18
+ Node.js and Slidev versions in [package.json](package.json) and commit your
19
+ lockfile for reproducible installations.
20
+
21
+ If you previously configured GitHub Packages, remove
22
+ `@morl99:registry=https://npm.pkg.github.com` from your project or user `.npmrc`.
23
+ The same package name is now resolved from npmjs.org. When migrating an existing
24
+ installation, update the dependency lockfile so it no longer points to GitHub Packages.
25
+
26
+ The unscoped [`slidev-addon-sync` package on npm](https://www.npmjs.com/package/slidev-addon-sync) belongs to the original project and does not install this fork.
27
+
28
+ ### Install from source
29
+
30
+ To try the current source instead of a published release:
31
+
32
+ ```bash
33
+ pnpm add github:Morl99/slidev-addon-sync
34
+ ```
35
+
36
+ For a reproducible source dependency, append `#<commit-sha>` to the GitHub reference.
37
+
38
+ ## Releases
39
+
40
+ Published versions and generated change notes are listed in [GitHub Releases](https://github.com/Morl99/slidev-addon-sync/releases). Semantic Release determines versions from Conventional Commits after successful checks on `main` and publishes the public npm package, Git tag and GitHub Release automatically. Changes that do not require a release leave the published version unchanged.
41
+
42
+ For development and release conventions, see [CONTRIBUTING.md](CONTRIBUTING.md#dependencies-and-releases).
43
+
44
+ ## Slidev Configuration
45
+
46
+ Register the addon in your presentation.
47
+
48
+ In your slides metadata (using Front Matter):
49
+
50
+ ```yaml
51
+ ---
52
+ addons:
53
+ - "@morl99/slidev-addon-sync"
54
+ ---
55
+ ```
56
+
57
+ Or in your `package.json`:
58
+
59
+ ```json
60
+ {
61
+ "slidev": {
62
+ "addons": ["@morl99/slidev-addon-sync"]
63
+ }
64
+ }
65
+ ```
66
+
67
+ ## Server configuration
68
+
69
+ ### Define the Websocket or SSE server
70
+
71
+ You can use a Server Sent Events server or a WebSocket server to allow communication with multiple clients.
72
+
73
+ You can use [slidev-sync-server](https://github.com/Morl99/slidev-sync-server) or create your own implementation.
74
+
75
+ Set `syncSettings.server` in the same front matter as `addons`. Use a server address reachable from every viewer’s browser. The URL selects the transport: `http(s)://` for SSE, `ws(s)://` for WebSocket. Configure the server for the matching mode; see its [README](https://github.com/Morl99/slidev-sync-server#quick-start).
76
+
77
+ For HTTP Server Sent Events server:
78
+
79
+ ```yaml
80
+ ---
81
+ syncSettings:
82
+ server: http://localhost:8080
83
+ ---
84
+ ```
85
+
86
+ Or for WebSocket server:
87
+
88
+ ```yaml
89
+ ---
90
+ syncSettings:
91
+ server: ws://localhost:8080
92
+ ---
93
+ ```
94
+
95
+ Then, in the presentation, click on the connect icon.
96
+
97
+ ![Connect control icon](./assets/control-icon.png)
98
+
99
+ Enter a shared group ID and press Enter. Use the same ID on the presenter and viewer devices. The suggested ID is derived from the presentation content; you can replace it to create a separate group.
100
+
101
+ ![Connect control hash](./assets/control-hash.png)
102
+
103
+ You are connected!
104
+
105
+ ![Connected](./assets/connected.png)
106
+
107
+ ### Auto-connect
108
+
109
+ You can also use the `autoConnect` settings to automatically connect to the server:
110
+
111
+ ```yaml
112
+ ---
113
+ syncSettings:
114
+ autoConnect: true
115
+ ---
116
+ ```
117
+
118
+ Or provide a number of seconds. In that case you will need to connect the first time, and then if you refresh the page it will automatically reconnect you if the number of seconds since the last connection has not been elapsed:
119
+
120
+ ```yaml
121
+ ---
122
+ syncSettings:
123
+ autoConnect: 86400 # one day
124
+ ---
125
+ ```
126
+
127
+ ### Enabling
128
+
129
+ By default this addon will only be visible and enabled in your static build.
130
+
131
+ Slidev already handles synchronization through its development server. To test this addon locally, explicitly enable it in development mode.
132
+
133
+ If you still need to activate this addon in dev mode you can use:
134
+
135
+ ```yaml
136
+ ---
137
+ syncSettings:
138
+ enabled: true # It will be enabled for both dev and build modes
139
+ ---
140
+ ```
141
+
142
+ You can also pass `"dev"` to only enable it in dev mode or `false` to disable it entirely.
143
+
144
+ ## State configuration
145
+
146
+ ### State channels
147
+
148
+ By default this addon will synchronize all channels.
149
+
150
+ Channels are internal slidev states created with `createSyncState` and by default there are two channels:
151
+
152
+ * `shared`: state for navigation (pages and clicks) and cursor
153
+ * `drawings`: drawing state
154
+
155
+ To configure channel defaults explicitly, use:
156
+
157
+ ```yaml
158
+ ---
159
+ syncStates:
160
+ - drawings
161
+ # Or alternatively:
162
+ syncStates: ["drawings"]
163
+ ---
164
+ ```
165
+
166
+ ### State keys
167
+
168
+ In addition to selecting state channels you can also filter the keys of that channel to synchronize.
169
+
170
+ By default this addon will filter on the following keys:
171
+
172
+ * `shared`:
173
+ * `"page"`: the current navigation page
174
+ * `"clicks"`: the current navigation click
175
+ * `"cursor"`: the cursor position
176
+ * `"lastUpdate"`: used internally to synchronize page, clicks or cursor if the update comes from the presenter view
177
+ * `drawings`: no filter
178
+
179
+ For example if you don't want to synchronize the cursor you can set:
180
+
181
+ ```yaml
182
+ ---
183
+ syncStates:
184
+ shared: ["page", "clicks", "lastUpdate"]
185
+ drawings: true # true means "no filter"
186
+ ---
187
+ ```
188
+
189
+ **Note:** this configures matching channels; it is not an allowlist. Channels not listed still use the default behavior (all keys, presenter-only updates and initial state).
190
+
191
+ You can also use the alternative object syntax:
192
+
193
+ ```yaml
194
+ ---
195
+ syncStates:
196
+ shared:
197
+ keys: ["page", "clicks", "lastUpdate"]
198
+ drawings:
199
+ keys: true
200
+ ---
201
+ ```
202
+
203
+ ### Presenter
204
+
205
+ By default this addon will only send state updates to the server if you are in presenter view.
206
+
207
+ This is probably want you want if you only want to synchronize slidev states.
208
+
209
+ But other addons like [`slidev-component-poll`](https://github.com/Smile-SA/slidev-component-poll) also rely on `createSyncState` to synchronize states, but in this example you want everybody to be able to use the poll, so in other words, to send state updates.
210
+
211
+ In that case you case the `presenter` settings to specify the channels for which you want everyone to be able to send updates:
212
+
213
+ ```yaml
214
+ ---
215
+ syncStates:
216
+ poll:
217
+ presenter: false
218
+ ---
219
+ ```
220
+
221
+ ### State initialization
222
+
223
+ When you connect, this addon will, by default send the current state to the server.
224
+
225
+ This is probably what you want when your are presenting to other peoples, it will in that case send the drawings you have already made the current navigation...etc.
226
+
227
+ If you don't want this behavior, you can use the `init` settings:
228
+
229
+ ```yaml
230
+ ---
231
+ syncStates:
232
+ poll:
233
+ init: false
234
+ ---
235
+ ```
236
+
237
+ ## Connection tips
238
+
239
+ - By default, connect from a built presentation. For local testing, set `syncSettings.enabled: true` or `"dev"`.
240
+ - `localhost` points to each viewer’s own device. Use a shared hostname when connecting from different devices.
241
+ - For presentations served over HTTPS, use an HTTPS (SSE) or WSS (WebSocket) server URL.
242
+ - Use the same server URL and group ID on every device, and send navigation updates from the presenter view.
243
+ - A group ID identifies a synchronization session. Provide access control through your server deployment when needed.
244
+
245
+ ## Help and contributions
246
+
247
+ Questions, bug reports and suggestions are welcome in [Issues](https://github.com/Morl99/slidev-addon-sync/issues).
248
+ Want to contribute or run the example from source? See [CONTRIBUTING.md](CONTRIBUTING.md).
249
+
250
+ ## License
251
+
252
+ [MIT](LICENCE). Original authorship and license notices are retained.
2
253
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,80 @@
1
+ <script lang="ts" setup>
2
+ import { configs } from "@slidev/client";
3
+ import { computed, onMounted, ref, watch } from "vue";
4
+ import VerticalDivider from "@slidev/client/internals/VerticalDivider.vue";
5
+
6
+ import { autoConnect, connect, connectState, groupId } from "../services";
7
+ import { Status } from "../types";
8
+
9
+ const input = ref<HTMLInputElement>();
10
+ const isOpen = ref(false);
11
+ const title = computed(() => {
12
+ if (connectState.value === Status.DISCONNECTED) {
13
+ return "Disconnected";
14
+ } else if (connectState.value === Status.ERROR) {
15
+ return "Server unreachable";
16
+ } else if (connectState.value === Status.CONNECTED) {
17
+ return "Connected";
18
+ } else {
19
+ return "Connect with sync server";
20
+ }
21
+ });
22
+ const hasConnectionError = computed(
23
+ () =>
24
+ connectState.value === Status.DISCONNECTED ||
25
+ connectState.value === Status.ERROR,
26
+ );
27
+
28
+ watch(isOpen, () => {
29
+ if (isOpen.value) {
30
+ input.value?.focus();
31
+ }
32
+ });
33
+
34
+ function submit() {
35
+ connect();
36
+ isOpen.value = false;
37
+ }
38
+
39
+ onMounted(() => {
40
+ if (
41
+ configs.syncSettings?.autoConnect &&
42
+ (configs.syncSettings?.autoConnect === true ||
43
+ (autoConnect.value &&
44
+ new Date().getTime() - new Date(autoConnect.value).getTime() <
45
+ configs.syncSettings?.autoConnect * 1000))
46
+ ) {
47
+ connect();
48
+ }
49
+ });
50
+ </script>
51
+
52
+ <template>
53
+ <VerticalDivider />
54
+ <button class="slidev-icon-btn" @click="isOpen = !isOpen" :title="title">
55
+ <carbon:wifi-bridge-alt
56
+ :class="{
57
+ 'text-red-500': hasConnectionError,
58
+ 'text-green-500': connectState === Status.CONNECTED,
59
+ }"
60
+ />
61
+ </button>
62
+ <form
63
+ v-if="!hasConnectionError"
64
+ class="flex align-center py-2"
65
+ @submit.prevent="submit"
66
+ >
67
+ <input
68
+ border="~ transparent rounded gray-400 opacity-25"
69
+ class="px-2 text-sm transition-all bg-main"
70
+ placeholder="Type in ID to create or join"
71
+ ref="input"
72
+ :style="{
73
+ width: isOpen ? '200px' : 0,
74
+ padding: isOpen ? undefined : 0,
75
+ border: isOpen ? undefined : 0,
76
+ }"
77
+ v-model="groupId"
78
+ />
79
+ </form>
80
+ </template>
@@ -0,0 +1,15 @@
1
+ <script lang="ts" setup>
2
+ import { configs, mode } from "@slidev/client";
3
+ import { computed } from "vue";
4
+
5
+ const enabled = computed(
6
+ () => {
7
+ const enabledSettings = configs.syncSettings?.enabled ?? 'build'
8
+ return enabledSettings === true || enabledSettings === mode
9
+ }
10
+ );
11
+ </script>
12
+
13
+ <template>
14
+ <SyncConnect v-if="configs.syncSettings?.server && enabled" />
15
+ </template>
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@morl99/slidev-addon-sync",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Sync addon for Slidev",
5
+ "homepage": "https://github.com/Morl99/slidev-addon-sync",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Morl99/slidev-addon-sync.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/Morl99/slidev-addon-sync/issues"
12
+ },
13
+ "scripts": {
14
+ "dev": "slidev example.md --open",
15
+ "build": "slidev build example.md",
16
+ "preview": "vite preview",
17
+ "test": "vitest run"
18
+ },
19
+ "keywords": [
20
+ "vuejs",
21
+ "slidev",
22
+ "slidev-addon",
23
+ "sync"
24
+ ],
25
+ "author": {
26
+ "name": "Tony Cabaye",
27
+ "email": "tonai59+github@gmail.com",
28
+ "url": "https://github.com/tonai"
29
+ },
30
+ "license": "MIT",
31
+ "engines": {
32
+ "node": ">=24 <25",
33
+ "slidev": ">=53.1.0"
34
+ },
35
+ "peerDependencies": {
36
+ "@slidev/client": "^53.1.0",
37
+ "vue": "^3.5.45"
38
+ },
39
+ "devDependencies": {
40
+ "@slidev/cli": "^53.1.0",
41
+ "@slidev/theme-default": "^0.25.0",
42
+ "vitest": "^5.1.0"
43
+ },
44
+ "dependencies": {
45
+ "@vueuse/core": "^15.0.0",
46
+ "deep-object-diff": "^1.1.9",
47
+ "hashids": "^2.3.0",
48
+ "uuid": "^14.0.3"
49
+ },
50
+ "packageManager": "pnpm@12.18.0",
51
+ "publishConfig": {
52
+ "registry": "https://registry.npmjs.org",
53
+ "access": "public"
54
+ },
55
+ "files": [
56
+ "components/",
57
+ "services/",
58
+ "types/",
59
+ "custom-nav-controls.vue",
60
+ "README.md",
61
+ "LICENCE"
62
+ ]
63
+ }
@@ -0,0 +1,41 @@
1
+ import Hashids from "hashids";
2
+ import { configs } from "@slidev/client";
3
+ import { slides } from "#slidev/slides";
4
+
5
+ const hashids = new Hashids();
6
+
7
+ // https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
8
+ function cyrb53(str: string, seed = 0) {
9
+ let h1 = 0xdeadbeef ^ seed,
10
+ h2 = 0x41c6ce57 ^ seed;
11
+ for (let i = 0, ch; i < str.length; i++) {
12
+ ch = str.charCodeAt(i);
13
+ h1 = Math.imul(h1 ^ ch, 2654435761);
14
+ h2 = Math.imul(h2 ^ ch, 1597334677);
15
+ }
16
+
17
+ h1 =
18
+ Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^
19
+ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
20
+ h2 =
21
+ Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^
22
+ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
23
+
24
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
25
+ }
26
+
27
+ export function getHash() {
28
+ const slideRaws = slides.value
29
+ .map((route) => route?.meta?.slide?.content ?? "")
30
+ .join("\n");
31
+ return hashids.encode(cyrb53(slideRaws));
32
+ }
33
+
34
+ export function getSyncServer() {
35
+ if (configs.syncSettings?.server) {
36
+ return configs.syncSettings.server.endsWith("/")
37
+ ? configs.syncSettings.server.slice(0, -1)
38
+ : configs.syncSettings.server;
39
+ }
40
+ return "";
41
+ }
@@ -0,0 +1,3 @@
1
+ export * from './helper';
2
+ export * from './server';
3
+ export * from './store';
@@ -0,0 +1,160 @@
1
+ import type { UnwrapRef } from "vue";
2
+
3
+ import { addSyncMethod, configs } from "@slidev/client";
4
+ import { diff } from "deep-object-diff";
5
+ import { ref, toRaw } from "vue";
6
+
7
+ import {
8
+ Server,
9
+ State,
10
+ StateConfig,
11
+ States,
12
+ Status,
13
+ SyncState,
14
+ } from "../types";
15
+ import {
16
+ autoConnect,
17
+ connectState,
18
+ deviceId,
19
+ groupId,
20
+ isPresenter,
21
+ onMessages,
22
+ stateChannels,
23
+ } from "./store.ts";
24
+
25
+ let server: Server;
26
+ const states: States = {};
27
+ const importPromise = (async () => {
28
+ if (configs.syncSettings?.server) {
29
+ if (configs.syncSettings.server.startsWith("ws")) {
30
+ server = await import("./webSocket.ts");
31
+ } else {
32
+ server = await import("./sse.ts");
33
+ }
34
+ }
35
+ })();
36
+ const loadPromise = new Promise<void>((resolve) => {
37
+ if (document.readyState === "complete") {
38
+ resolve();
39
+ } else {
40
+ window.addEventListener("load", () => resolve());
41
+ }
42
+ });
43
+ const promises = Promise.all([importPromise, loadPromise]);
44
+
45
+ function copy(state: Partial<State>): Partial<State> {
46
+ return JSON.parse(JSON.stringify(state));
47
+ }
48
+
49
+ addSyncMethod({
50
+ init(
51
+ channelKey: string,
52
+ onUpdate: (data: Partial<State>) => void,
53
+ state: State,
54
+ ) {
55
+ const channel = getChannel(channelKey);
56
+ if (!channel) {
57
+ return;
58
+ }
59
+
60
+ if (channel.init) {
61
+ states[channelKey] = state;
62
+ }
63
+ const stateCopy = ref<Partial<State>>(
64
+ copy(getFilteredState(channel, state)),
65
+ );
66
+ onMessages.value.push((states: States, uid: string) => {
67
+ if (states && channelKey in states) {
68
+ const filteredState = getFilteredState(channel, state);
69
+ const stateDiff = diff(
70
+ filteredState,
71
+ states[channelKey],
72
+ ) as Partial<State>;
73
+ if (Object.keys(stateDiff).length > 0 && uid !== deviceId.value) {
74
+ onUpdate(
75
+ Object.fromEntries(
76
+ Object.entries(stateDiff)
77
+ .filter(([, value]) => value !== undefined)
78
+ .map(([key]) => [key, states[channelKey][key]]),
79
+ ) as Partial<State>,
80
+ );
81
+ }
82
+ }
83
+ });
84
+
85
+ return (state: State, updating = false) => {
86
+ if (canUpdate(channel) && !updating) {
87
+ const filteredState = getFilteredState(channel, state);
88
+ const stateDiff = diff(stateCopy.value as object, filteredState);
89
+ stateCopy.value = copy(filteredState) as UnwrapRef<Partial<State>>;
90
+ if (
91
+ Object.keys(stateDiff).length > 0 &&
92
+ connectState.value === Status.CONNECTED
93
+ ) {
94
+ server.patch(
95
+ channelKey,
96
+ Object.fromEntries(
97
+ Object.keys(stateDiff).map((key) => [
98
+ key,
99
+ filteredState[key as keyof typeof filteredState],
100
+ ]),
101
+ ),
102
+ );
103
+ }
104
+ }
105
+ };
106
+ },
107
+ });
108
+
109
+ function getChannel(channelKey: string): StateConfig | undefined {
110
+ const channels: Record<string, SyncState> =
111
+ stateChannels instanceof Array
112
+ ? Object.fromEntries(stateChannels.map((channel) => [channel, true]))
113
+ : stateChannels;
114
+ let channel = Object.entries(channels).find(([key]) =>
115
+ channelKey.endsWith(key),
116
+ )?.[1];
117
+ if (!(channel instanceof Object) || channel instanceof Array) {
118
+ return {
119
+ keys: channel ?? true,
120
+ presenter: true,
121
+ init: true,
122
+ };
123
+ }
124
+ return { keys: true, presenter: true, init: true, ...channel };
125
+ }
126
+
127
+ function getFilteredState(channel: StateConfig, state: State): Partial<State> {
128
+ const { keys } = channel;
129
+ if (keys === true) {
130
+ return toRaw(state);
131
+ }
132
+ return Object.fromEntries(
133
+ Object.entries(toRaw(state)).filter(([key]) => keys.includes(key)),
134
+ ) as Partial<State>;
135
+ }
136
+
137
+ function canUpdate(channel: StateConfig) {
138
+ return isPresenter.value || !channel.presenter;
139
+ }
140
+
141
+ function onClose() {
142
+ if (connectState.value === Status.IDLE) {
143
+ connectState.value = Status.ERROR;
144
+ } else {
145
+ connectState.value = Status.DISCONNECTED;
146
+ }
147
+ }
148
+
149
+ function onOpen() {
150
+ if (groupId.value) {
151
+ server.open(isPresenter.value ? states : undefined);
152
+ connectState.value = Status.CONNECTED;
153
+ }
154
+ }
155
+
156
+ export async function connect() {
157
+ await promises;
158
+ autoConnect.value = new Date().toISOString();
159
+ server.init(onOpen, onClose);
160
+ }
@@ -0,0 +1,53 @@
1
+ import { OnClose, OnOpen, States } from "../types";
2
+
3
+ import { getSyncServer } from "./helper.ts";
4
+ import { deviceId, groupId, onMessages } from "./store.ts";
5
+
6
+ let eventSource: EventSource;
7
+ const url = getSyncServer();
8
+
9
+ export function init(onOpen: OnOpen, onClose: OnClose) {
10
+ if (!eventSource) {
11
+ eventSource = new EventSource(`${url}/event?uid=${deviceId.value}`);
12
+ eventSource.addEventListener("error", onClose);
13
+ eventSource.addEventListener("open", onOpen);
14
+ const messageListener = (event: MessageEvent) => {
15
+ const { states, uid } = JSON.parse(event.data);
16
+ onMessages.value.forEach(onMessage => onMessage(states, uid));
17
+ }
18
+ eventSource.addEventListener("patch", messageListener);
19
+ eventSource.addEventListener("replace", messageListener);
20
+ } else {
21
+ onOpen();
22
+ }
23
+ }
24
+
25
+ export function open(states?: States) {
26
+ if (eventSource) {
27
+ fetch(`${url}/connect?uid=${deviceId.value}`, {
28
+ body: JSON.stringify({
29
+ id: groupId.value,
30
+ states,
31
+ }),
32
+ method: "POST",
33
+ headers: {
34
+ "content-type": "application/json",
35
+ },
36
+ });
37
+ }
38
+ }
39
+
40
+ export function patch(channelKey: string, state: unknown) {
41
+ if (eventSource) {
42
+ fetch(`${url}/patch?uid=${deviceId.value}`, {
43
+ body: JSON.stringify({
44
+ id: groupId.value,
45
+ states: { [channelKey]: state },
46
+ }),
47
+ method: "POST",
48
+ headers: {
49
+ "content-type": "application/json",
50
+ },
51
+ });
52
+ }
53
+ }
@@ -0,0 +1,20 @@
1
+ import { ref } from "vue";
2
+ import { configs, useNav } from "@slidev/client";
3
+ import { useStorage } from "@vueuse/core";
4
+ import { v4 as uuidv4 } from "uuid";
5
+
6
+ import { OnMessage, Status } from "../types/index.ts";
7
+
8
+ import { getHash } from "./helper.ts";
9
+
10
+ export const { isPresenter } = useNav();
11
+ export const deviceId = useStorage("slidev-addon-sync-device-id", uuidv4());
12
+ export const groupId = useStorage("slidev-addon-sync-group-id", getHash());
13
+ export const autoConnect = useStorage("slidev-addon-sync-auto-connect", "");
14
+ export const connectState = ref(Status.IDLE);
15
+ export const onMessages = ref<OnMessage[]>([]);
16
+
17
+ export const stateChannels = configs.syncStates ?? {
18
+ shared: ["page", "clicks", "cursor", "lastUpdate"],
19
+ drawings: true,
20
+ }
@@ -0,0 +1,54 @@
1
+ import { EventType, OnClose, OnOpen, States } from "../types";
2
+
3
+ import { getSyncServer } from "./helper.ts";
4
+ import { deviceId, groupId, onMessages } from "./store.ts";
5
+
6
+ interface SendState {
7
+ states: States;
8
+ type: EventType;
9
+ uid: string;
10
+ }
11
+
12
+ let webSocket: WebSocket;
13
+ const url = getSyncServer();
14
+
15
+ export function init(onOpen: OnOpen, onClose: OnClose) {
16
+ if (!webSocket) {
17
+ webSocket = new WebSocket(url);
18
+ webSocket.addEventListener("close", onClose);
19
+ webSocket.addEventListener("open", onOpen);
20
+ const messageListener = (event: MessageEvent) => {
21
+ const { states, uid } = JSON.parse(event.data) as SendState;
22
+ onMessages.value.forEach(onMessage => onMessage(states, uid));
23
+ }
24
+ webSocket.addEventListener("message", messageListener);
25
+ } else {
26
+ onOpen();
27
+ }
28
+ }
29
+
30
+ export function open(states?: States) {
31
+ if (webSocket) {
32
+ webSocket.send(
33
+ JSON.stringify({
34
+ id: groupId.value,
35
+ states,
36
+ type: "connect",
37
+ uid: deviceId.value,
38
+ }),
39
+ );
40
+ }
41
+ }
42
+
43
+ export function patch(channelKey: string, state: unknown) {
44
+ if (webSocket) {
45
+ webSocket.send(
46
+ JSON.stringify({
47
+ id: groupId.value,
48
+ states: { [channelKey]: state },
49
+ type: "patch",
50
+ uid: deviceId.value,
51
+ }),
52
+ );
53
+ }
54
+ };
package/types/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./promise";
2
+ export * from "./server";
3
+ export * from "./slidev";
4
+ export * from "./state";
@@ -0,0 +1 @@
1
+ export type Resolve = () => void
@@ -0,0 +1,29 @@
1
+ import { Resolve } from "./promise";
2
+ import { States } from "./state";
3
+
4
+ export enum Status {
5
+ CONNECTED,
6
+ DISCONNECTED,
7
+ ERROR,
8
+ IDLE,
9
+ }
10
+
11
+ export enum EventType {
12
+ PATCH = "patch",
13
+ REPLACE = "replace",
14
+ RESET = "reset",
15
+ }
16
+
17
+ export type OnMessage = (states: States, uid: string) => void;
18
+ export type OnOpen = () => void;
19
+ export type OnClose = () => void;
20
+
21
+ export type Init = (OnOpen: OnOpen, onClose: OnClose) => void;
22
+ export type Open = (states?: States) => void;
23
+ export type Patch = (channelKey: string, state: unknown) => void;
24
+
25
+ export interface Server {
26
+ init: Init;
27
+ open: Open;
28
+ patch: Patch;
29
+ }
@@ -0,0 +1,18 @@
1
+ export interface StateConfig {
2
+ keys: string[] | true
3
+ presenter: boolean
4
+ init: boolean
5
+ }
6
+
7
+ export type SyncState = string[] | true | Partial<StateConfig>
8
+
9
+ declare module "@slidev/types" {
10
+ export interface SlidevConfig {
11
+ syncSettings?: {
12
+ autoConnect?: boolean | number;
13
+ enabled?: boolean | 'dev' | 'build'
14
+ server?: string;
15
+ };
16
+ syncStates?: string[] | Record<string, SyncState>
17
+ }
18
+ }
package/types/state.ts ADDED
@@ -0,0 +1,3 @@
1
+ export type State = Record<string, unknown>;
2
+
3
+ export type States = Record<string, State>;