Files
djledda-web/app/useHead.ts
Daniel Ledda 9eb1701250 update
2024-11-02 15:49:07 +01:00

38 lines
1.4 KiB
TypeScript

import { watch, toValue, type MaybeRefOrGetter } from 'vue';
import useDJSSRContext from "@/useDJSSRContext.ts";
import { h } from "@/util.ts";
export default function useHead(params: {
title: MaybeRefOrGetter<string>,
metatags?: MaybeRefOrGetter<Array<{ name: string, content: string }>>
}) {
const context = useDJSSRContext();
if (context) {
context.head.title = params.title;
context.head.metatags = params.metatags ?? [];
} else {
watch([() => toValue(params.title), () => toValue(params.metatags) ?? []], ([newTitle, newMetatags]) => {
if (newTitle) {
document.title = newTitle;
}
const currMetatags = document.head.querySelectorAll('meta');
const existing = new Set<string>();
for (const currMetatag of currMetatags) {
const match = newMetatags.find(_ => _.name === currMetatag.name);
if (!match) {
currMetatag.remove();
} else {
existing.add(match.name);
currMetatag.content = match.content;
}
}
for (const newMetatag of newMetatags) {
if (!existing.has(newMetatag.name)) {
document.head.appendChild(h('meta', newMetatag));
}
}
}, { immediate: true });
}
}