Skip to content

Commit

Permalink
fix: fix issue that nav link may not create (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
Aarebecca authored Oct 29, 2023
1 parent c7ba8e4 commit 7b73ac3
Showing 1 changed file with 33 additions and 28 deletions.
61 changes: 33 additions & 28 deletions .dumi/theme/layouts/GlobalLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,37 @@ import React, { useState, useEffect } from 'react';
import { useIntl } from '../../hooks/useIntl';
import { isMobile as isMobileDevice } from 'react-device-detect';

// insert github and openKG in navbar
const createLink = (name: string, link: string, index: number) => {
const nav = document.getElementsByClassName('dumi-default-navbar')?.[0];
if (!nav) return;

const xpath = `//*[text()='${name}']`;
const element = document.evaluate(
xpath,
nav,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null,
).singleNodeValue;
if (element) return;

const li = document.createElement('li');
const a = document.createElement('a');
a.innerText = name;
a.href = link;
a.target = '_blank';
a.rel = 'noopener noreferrer';
li.appendChild(a);
nav.insertBefore(li, nav.childNodes[index]);

return true;
};

const GlobalLayout: React.FC = () => {
const { intl } = useIntl();
const outlet = useOutlet();
const createLinkIntervalRef = React.useRef<number>();
const [color] = usePrefersColor();
const [screenWidth, setScreenWidth] = useState(window.screen.availWidth);
const [isBtnVisible, setIsBtnVisible] = useState(true);
Expand All @@ -16,34 +44,11 @@ const GlobalLayout: React.FC = () => {
const isMobile = isMobileDevice && isMobileScreen;

useEffect(() => {
const nav = document.getElementsByClassName('dumi-default-navbar')?.[0];
if (!nav) return;

// insert github and openKG in navbar

const createLink = (name: string, link: string, index: number) => {
const xpath = `//*[text()='${name}']`;
const element = document.evaluate(
xpath,
nav,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null,
).singleNodeValue;
if (element) return;

const li = document.createElement('li');
const a = document.createElement('a');
a.innerText = name;
a.href = link;
a.target = '_blank';
a.rel = 'noopener noreferrer';
li.appendChild(a);
nav.insertBefore(li, nav.childNodes[index]);
};

createLink('Github', 'https://github.com/OpenSPG/openspg', 1);
createLink('OpenKG', 'http://openkg.cn/', 5);
createLinkIntervalRef.current = window.setInterval(() => {
createLink('Github', 'https://github.com/OpenSPG/openspg', 1);
const result = createLink('OpenKG', 'http://openkg.cn/', 5);
if (result) clearInterval(createLinkIntervalRef.current);
}, 500);
}, []);

useEffect(() => {
Expand Down

0 comments on commit 7b73ac3

Please sign in to comment.