1
0
mirror of https://github.com/elk-zone/elk synced 2024-11-30 15:58:06 +09:00
elk/composables/vue.ts

64 lines
1.9 KiB
TypeScript
Raw Normal View History

import type { ComponentInternalInstance } from 'vue'
import { onActivated, onDeactivated, ref } from 'vue'
import type { ActiveHeadEntry, UseHeadInput, UseHeadOptions } from '@unhead/vue'
import type { SchemaAugmentations } from '@unhead/schema'
2023-01-07 03:40:15 +09:00
export const isHydrated = ref(false)
export function onHydrated(cb: () => unknown) {
2023-01-15 17:38:02 +09:00
watchOnce(isHydrated, () => cb(), { immediate: isHydrated.value })
}
/**
* ### 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 17:30:15 +09:00
*
* @param hook
* @param target
*/
export function onReactivated(hook: () => void, target?: ComponentInternalInstance | null): void {
const initial = ref(true)
onActivated(() => {
if (initial.value)
return
hook()
}, target)
onDeactivated(() => initial.value = false)
}
export function useHydratedHead<T extends SchemaAugmentations>(input: UseHeadInput<T>, options?: UseHeadOptions): ActiveHeadEntry<UseHeadInput<T>> | void {
if (input && typeof input === 'object' && !('value' in input)) {
const title = 'title' in input ? input.title : undefined
2024-02-25 01:46:14 +09:00
if (import.meta.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-05-02 08:58:55 +09:00
return useHead((() => {
if (!isHydrated.value)
return {}
return resolveUnref(input)
2023-05-02 08:58:55 +09:00
}) as UseHeadInput<T>, options)
}