| 1 | import type { ResolvedSlidevOptions, SlidevPluginOptions } from '@slidev/types' |
| 2 | import ServerRef from 'vite-plugin-vue-server-ref' |
| 3 | import { loadDrawings, writeDrawings } from '../integrations/drawings' |
| 4 | import { loadSnapshots, writeSnapshots } from '../integrations/snapshots' |
| 5 | |
| 6 | const serverRefStates = new WeakMap<ResolvedSlidevOptions, Record<string, any>>() |
| 7 | |
| 8 | /** |
| 9 | * Access the server-side state shared with the clients via |
| 10 | * `vite-plugin-vue-server-ref` (e.g. `nav` holds the current position of the |
| 11 | * live presentation). |
| 12 | */ |
| 13 | export function getServerRefState(options: ResolvedSlidevOptions): Record<string, any> | undefined { |
| 14 | return serverRefStates.get(options) |
| 15 | } |
| 16 | |
| 17 | export async function createServerRefPlugin( |
| 18 | options: ResolvedSlidevOptions, |
| 19 | pluginOptions: SlidevPluginOptions, |
| 20 | ) { |
| 21 | const state: Record<string, any> = { |
| 22 | sync: false, |
| 23 | nav: { |
| 24 | page: 0, |
| 25 | clicks: 0, |
| 26 | timer: { |
| 27 | status: 'stopped', |
| 28 | slides: {}, |
| 29 | startedAt: 0, |
| 30 | pausedAt: 0, |
| 31 | }, |
| 32 | }, |
| 33 | drawings: await loadDrawings(options), |
| 34 | snapshots: await loadSnapshots(options), |
| 35 | ...pluginOptions.serverRef?.state, |
| 36 | } |
| 37 | serverRefStates.set(options, state) |
| 38 | |
| 39 | return ServerRef({ |
| 40 | debug: false, // process.env.NODE_ENV === 'development', |
| 41 | state, |
| 42 | onChanged(key, data, patch, timestamp) { |
| 43 | pluginOptions.serverRef?.onChanged?.(key, data, patch, timestamp) |
| 44 | |
| 45 | if (options.data.config.drawings.persist && key === 'drawings') |
| 46 | writeDrawings(options, patch ?? data) |
| 47 | |
| 48 | if (key === 'snapshots') |
| 49 | writeSnapshots(options, data) |
| 50 | }, |
| 51 | }) |
| 52 | } |
| 53 |