This commit is contained in:
Daniel Ledda
2024-11-02 15:49:07 +01:00
parent 0ae2811eeb
commit 9eb1701250
12 changed files with 303 additions and 134 deletions

View File

@@ -1,19 +1,37 @@
import { watchEffect, toValue, type MaybeRefOrGetter } from 'vue';
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 {
watchEffect(() => {
const newTitle = toValue(params.title);
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 });
}
}