2022-11-27 18:34:45 +01:00
|
|
|
import type { ComponentInternalInstance } from 'vue'
|
|
|
|
import { onActivated, onDeactivated, ref } from 'vue'
|
2023-01-06 19:40:15 +01:00
|
|
|
import type { ActiveHeadEntry, HeadEntryOptions, UseHeadInput } from '@vueuse/head'
|
2023-03-21 05:20:36 +01:00
|
|
|
import type { SchemaAugmentations } from '@unhead/schema'
|
2023-01-06 19:40:15 +01:00
|
|
|
|
|
|
|
export const isHydrated = ref(false)
|
2022-11-27 18:34:45 +01:00
|
|
|
|
2023-01-15 09:38:02 +01:00
|
|
|
export const onHydrated = (cb: () => unknown) => {
|
|
|
|
watchOnce(isHydrated, () => cb(), { immediate: isHydrated.value })
|
|
|
|
}
|
|
|
|
|
2022-11-27 18:34:45 +01: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
|
|
|
|
*/
|
|
|
|
export function onReactivated(hook: Function, target?: ComponentInternalInstance | null): void {
|
|
|
|
const initial = ref(true)
|
|
|
|
onActivated(() => {
|
|
|
|
if (initial.value)
|
|
|
|
return
|
|
|
|
hook()
|
|
|
|
}, target)
|
|
|
|
onDeactivated(() => initial.value = false)
|
|
|
|
}
|
2023-01-06 19:40:15 +01:00
|
|
|
|
|
|
|
// TODO: Workaround for Nuxt bug: https://github.com/elk-zone/elk/pull/199#issuecomment-1329771961
|
2023-03-21 05:20:36 +01:00
|
|
|
export function useHeadFixed<T extends SchemaAugmentations>(input: UseHeadInput<T>, options?: HeadEntryOptions): ActiveHeadEntry<UseHeadInput<T>> | void {
|
2023-01-06 19:40:15 +01:00
|
|
|
const deactivated = useDeactivated()
|
2023-01-12 00:08:31 +01:00
|
|
|
if (input && typeof input === 'object' && !('value' in input)) {
|
|
|
|
const title = 'title' in input ? input.title : undefined
|
|
|
|
if (process.server && title) {
|
|
|
|
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-01-06 19:40:15 +01:00
|
|
|
return useHead(() => {
|
|
|
|
if (deactivated.value)
|
|
|
|
return {}
|
|
|
|
return resolveUnref(input)
|
|
|
|
}, options)
|
|
|
|
}
|