Skip to content

Commit

Permalink
Merge pull request #9 from dr-forget/custom_code
Browse files Browse the repository at this point in the history
feat: 适配管理自定义注入样式&脚本
  • Loading branch information
hamster1963 authored Dec 4, 2024
2 parents 97b5ff3 + 8020c76 commit 79e4014
Showing 1 changed file with 44 additions and 2 deletions.
46 changes: 44 additions & 2 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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">
Expand Down Expand Up @@ -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));
Expand Down

0 comments on commit 79e4014

Please sign in to comment.