diff --git a/themes/heo/components/CustomContextMenu.js b/themes/heo/components/CustomContextMenu.js new file mode 100644 index 00000000..f7de5418 --- /dev/null +++ b/themes/heo/components/CustomContextMenu.js @@ -0,0 +1,145 @@ +import Link from 'next/link' +import { useRouter } from 'next/router' +import { useEffect, useState, useRef } from 'react' +import { useGlobal } from '@/lib/global' +import { saveDarkModeToCookies } from '@/themes/theme' + +/** + * 自定义右键菜单 + * @param {*} props + * @returns + */ +export default function CustomContextMenu(props) { + const [position, setPosition] = useState({ x: '0px', y: '0px' }) + const [show, setShow] = useState(false) + const { isDarkMode, updateDarkMode } = useGlobal() + const menuRef = useRef(null) + + const { latestPosts } = props + const router = useRouter() + function handleJumpToRandomPost() { + const randomIndex = Math.floor(Math.random() * latestPosts.length) + const randomPost = latestPosts[randomIndex] + router.push(randomPost.slug) + } + + useEffect(() => { + const handleContextMenu = (event) => { + event.preventDefault() + setPosition({ y: `${event.clientY}px`, x: `${event.clientX}px` }) + setShow(true) + } + + const handleClick = (event) => { + if (menuRef.current && !menuRef.current.contains(event.target)) { + setShow(false) + } + } + + window.addEventListener('contextmenu', handleContextMenu) + window.addEventListener('click', handleClick) + + return () => { + window.removeEventListener('contextmenu', handleContextMenu) + window.removeEventListener('click', handleClick) + } + }, []) + + function handleBack() { + window.history.back() + } + + function handleForward() { + window.history.forward() + } + + function handleRefresh() { + window.location.reload() + } + + function handleScrollTop() { + window.scrollTo({ top: 0, behavior: 'smooth' }) + setShow(false) + } + + function handleCopyLink() { + const url = window.location.href + navigator.clipboard.writeText(url) + .then(() => { + console.log('页面地址已复制') + }) + .catch((error) => { + console.error('复制页面地址失败:', error) + }) + setShow(false) + } + + function handleChangeDarkMode() { + const newStatus = !isDarkMode + saveDarkModeToCookies(newStatus) + updateDarkMode(newStatus) + const htmlElement = document.getElementsByTagName('html')[0] + htmlElement.classList?.remove(newStatus ? 'light' : 'dark') + htmlElement.classList?.add(newStatus ? 'dark' : 'light') + } + + return ( +