Files
djledda-web/app/util.ts
Daniel Ledda 51e44db779 big updats
2025-12-20 00:10:42 +01:00

61 lines
1.8 KiB
TypeScript

import { type InjectionKey, inject } from 'vue';
import useDjSSRContext from "@/useDjSSRContext.ts";
export function gid(id: string, doc: (Document | ShadowRoot) | undefined) {
return ((doc ?? document).getElementById(id));
}
export function qs(query: string, sub: (HTMLElement | ShadowRoot) | undefined) {
return ((sub ?? document).querySelector(query));
}
export function qsa(query: string, sub?: (HTMLElement | ShadowRoot) | undefined) {
return ((sub ?? document).querySelectorAll(query));
}
export function h<T extends keyof HTMLElementTagNameMap>(
tag: T,
opts?: Partial<HTMLElementTagNameMap[T]> | undefined,
children?: Node[],
) {
const newEl = Object.assign(document.createElement(tag), opts ?? {});
if (children) {
newEl.append(...children);
}
return newEl;
}
export function html(strs: TemplateStringsArray, ...vals: string[]) {
let result = strs[0];
for (let i = 1; i < strs.length; i++) {
result += vals[i] + strs[i];
}
const template = document.createElement("template");
template.innerHTML = result;
return template;
}
export function css(strs: TemplateStringsArray, ...vals: string[]) {
let result = strs[0];
for (let i = 1; i < strs.length; i++) {
result += vals[i] + strs[i];
}
return result;
}
export const cssRegistry = Symbol('css-registry') as InjectionKey<Set<string>>;
export function addCSS(key: string, css: string) {
const context = useDjSSRContext();
if (context && !context.styles[key]) {
context.styles[key] = css;
} else {
const registry = inject(cssRegistry);
if (!registry?.has(key)) {
const stylesheet = new CSSStyleSheet();
stylesheet.replace(css);
document.adoptedStyleSheets.push(stylesheet);
}
}
}