forked from vueuse/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssr-handlers.ts
46 lines (40 loc) · 1.67 KB
/
ssr-handlers.ts
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
import type { Awaitable } from '@vueuse/shared'
export interface StorageLikeAsync {
getItem(key: string): Awaitable<string | null>
setItem(key: string, value: string): Awaitable<void>
removeItem(key: string): Awaitable<void>
}
export interface StorageLike {
getItem(key: string): string | null
setItem(key: string, value: string): void
removeItem(key: string): void
}
/**
* @experimental The API is not finalized yet. It might not follow semver.
*/
export interface SSRHandlersMap {
getDefaultStorage: () => StorageLike | undefined
getDefaultStorageAsync: () => StorageLikeAsync | undefined
updateHTMLAttrs: (selector: string, attribute: string, value: string) => void
}
const _global
= typeof globalThis !== 'undefined'
? globalThis
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: typeof self !== 'undefined' ? self : {}
const globalKey = '__vueuse_ssr_handlers__'
// @ts-expect-error inject global
_global[globalKey] = _global[globalKey] || {}
// @ts-expect-error inject global
const handlers: Partial<SSRHandlersMap> = _global[globalKey]
export function getSSRHandler<T extends keyof SSRHandlersMap>(key: T, fallback: SSRHandlersMap[T]): SSRHandlersMap[T]
export function getSSRHandler<T extends keyof SSRHandlersMap>(key: T, fallback: SSRHandlersMap[T] | undefined): SSRHandlersMap[T] | undefined
export function getSSRHandler<T extends keyof SSRHandlersMap>(key: T, fallback?: SSRHandlersMap[T]): SSRHandlersMap[T] | undefined {
return handlers[key] as SSRHandlersMap[T] || fallback
}
export function setSSRHandler<T extends keyof SSRHandlersMap>(key: T, fn: SSRHandlersMap[T]) {
handlers[key] = fn
}