feat: 适配管理自定义注入样式&脚本

This commit is contained in:
Forget 2024-12-04 13:08:00 +08:00
parent ec26bc6ff0
commit 8020c76183

View File

@ -4,7 +4,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { fetchLoginUser, fetchSetting } from "@/lib/nezha-api";
import { useQuery } from "@tanstack/react-query";
import { DateTime } from "luxon";
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState, useCallback } from "react";
import { LanguageSwitcher } from "./LanguageSwitcher";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
@ -22,10 +22,52 @@ function Header() {
const siteName = settingData?.data?.site_name;
const InjectContext = useCallback((content: string) => {
const tempDiv = document.createElement("div");
tempDiv.innerHTML = content;
const handlers: { [key: string]: (element: HTMLElement) => void } = {
SCRIPT: (element) => {
const script = document.createElement("script");
if ((element as HTMLScriptElement).src) {
script.src = (element as HTMLScriptElement).src;
} else {
script.textContent = element.textContent;
}
document.body.appendChild(script);
},
STYLE: (element) => {
const style = document.createElement("style");
style.textContent = element.textContent;
document.head.appendChild(style);
},
DEFAULT: (element) => {
document.body.appendChild(element);
},
};
Array.from(tempDiv.childNodes).forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const element = node as HTMLElement;
(handlers[element.tagName] || handlers.DEFAULT)(element);
} else if (node.nodeType === Node.TEXT_NODE) {
document.body.appendChild(
document.createTextNode(node.textContent || "")
);
}
});
}, []);
useEffect(() => {
document.title = siteName || "NEZHA";
}, [siteName]);
useEffect(() => {
if (settingData?.data?.custom_code) {
InjectContext(settingData?.data?.custom_code);
}
}, [settingData?.data?.custom_code]);
return (
<div className="mx-auto w-full max-w-5xl">
<section className="flex items-center justify-between">
@ -113,7 +155,7 @@ function Overview() {
const timeOption = DateTime.TIME_SIMPLE;
timeOption.hour12 = true;
const [timeString, setTimeString] = useState(
DateTime.now().setLocale("en-US").toLocaleString(timeOption),
DateTime.now().setLocale("en-US").toLocaleString(timeOption)
);
useInterval(() => {
setTimeString(DateTime.now().setLocale("en-US").toLocaleString(timeOption));