2022-11-27 20:34:45 +03:00
|
|
|
import type { ComponentInternalInstance } from 'vue'
|
|
|
|
import { onActivated, onDeactivated, ref } from 'vue'
|
2023-09-05 15:55:03 +03:00
|
|
|
import type { ActiveHeadEntry, UseHeadInput, UseHeadOptions } from '@unhead/vue'
|
2023-04-16 22:33:51 +03:00
|
|
|
import type { SchemaAugmentations } from '@unhead/schema'
|
2023-01-06 21:40:15 +03:00
|
|
|
|
|
|
|
export const isHydrated = ref(false)
|
2022-11-27 20:34:45 +03:00
|
|
|
|
2023-03-30 22:01:24 +03:00
|
|
|
export function onHydrated(cb: () => unknown) {
|
2023-01-15 11:38:02 +03:00
|
|
|
watchOnce(isHydrated, () => cb(), { immediate: isHydrated.value })
|
|
|
|
}
|
|
|
|
|
2022-11-27 20:34:45 +03:00
|
|
|
/**
|
|
|
|
* ### Whether the current component is running in the background
|
|
|
|
*
|
|
|
|
* for handling problems caused by the keepalive function
|
|
|
|
*/
|
|
|
|
export function useDeactivated() {
|
|
|
|
const deactivated = ref(false)
|
|
|
|
onActivated(() => deactivated.value = false)
|
|
|
|
onDeactivated(() => deactivated.value = true)
|
|
|
|
|
|
|
|
return deactivated
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* ### When the component is restored from the background
|
|
|
|
*
|
|
|
|
* for handling problems caused by the keepalive function
|
2024-01-21 11:30:15 +03:00
|
|
|
*
|
|
|
|
* @param hook
|
|
|
|
* @param target
|
2022-11-27 20:34:45 +03:00
|
|
|
*/
|
2023-08-02 13:28:18 +03:00
|
|
|
export function onReactivated(hook: () => void, target?: ComponentInternalInstance | null): void {
|
2022-11-27 20:34:45 +03:00
|
|
|
const initial = ref(true)
|
|
|
|
onActivated(() => {
|
|
|
|
if (initial.value)
|
|
|
|
return
|
|
|
|
hook()
|
|
|
|
}, target)
|
|
|
|
onDeactivated(() => initial.value = false)
|
|
|
|
}
|
2023-04-16 22:33:51 +03:00
|
|
|
|
2023-09-05 15:55:03 +03:00
|
|
|
export function useHydratedHead<T extends SchemaAugmentations>(input: UseHeadInput<T>, options?: UseHeadOptions): ActiveHeadEntry<UseHeadInput<T>> | void {
|
2023-04-16 22:33:51 +03:00
|
|
|
if (input && typeof input === 'object' && !('value' in input)) {
|
|
|
|
const title = 'title' in input ? input.title : undefined
|
2024-02-24 19:46:14 +03:00
|
|
|
if (import.meta.server && title) {
|
2023-04-16 22:33:51 +03:00
|
|
|
input.meta = input.meta || []
|
|
|
|
if (Array.isArray(input.meta)) {
|
|
|
|
input.meta.push(
|
|
|
|
{ property: 'og:title', content: (typeof input.title === 'function' ? input.title() : input.title) as string },
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else if (title) {
|
|
|
|
(input as any).title = () => isHydrated.value ? typeof title === 'function' ? title() : title : ''
|
|
|
|
}
|
|
|
|
}
|
2023-05-02 02:58:55 +03:00
|
|
|
return useHead((() => {
|
2023-04-16 22:33:51 +03:00
|
|
|
if (!isHydrated.value)
|
|
|
|
return {}
|
|
|
|
return resolveUnref(input)
|
2023-05-02 02:58:55 +03:00
|
|
|
}) as UseHeadInput<T>, options)
|
2023-04-16 22:33:51 +03:00
|
|
|
}
|