合并CommenHead;

调整Algolia样式
This commit is contained in:
tangly1024
2023-07-28 20:42:35 +08:00
parent 66f568ad94
commit beeed7f632
16 changed files with 156 additions and 68 deletions

View File

@@ -1,7 +1,10 @@
import { useState, useImperativeHandle } from 'react'
import { useState, useImperativeHandle, useRef } from 'react'
import BLOG from '@/blog.config'
import algoliasearch from 'algoliasearch'
import replaceSearchResult from '@/components/Mark'
import Link from 'next/link'
import { useGlobal } from '@/lib/global'
import throttle from 'lodash/throttle'
/**
* 结合 Algolia 实现的弹出式搜索框
@@ -11,6 +14,12 @@ import replaceSearchResult from '@/components/Mark'
export default function AlgoliaSearchModal({ cRef }) {
const [searchResults, setSearchResults] = useState([])
const [isModalOpen, setIsModalOpen] = useState(false)
const [page, setPage] = useState(0)
const [keyword, setKeyword] = useState(null)
const [totalPage, setTotalPage] = useState(0)
const [totalHit, setTotalHit] = useState(0)
const [useTime, setUseTime] = useState(0)
/**
* 对外暴露方法
*/
@@ -22,40 +31,80 @@ export default function AlgoliaSearchModal({ cRef }) {
}
})
if (!BLOG.ALGOLIA_APP_ID) {
return <></>
}
const client = algoliasearch(BLOG.ALGOLIA_APP_ID, BLOG.ALGOLIA_SEARCH_ONLY_APP_KEY)
const index = client.initIndex(BLOG.ALGOLIA_INDEX)
const handleSearch = async (query) => {
/**
* 搜索
* @param {*} query
*/
const handleSearch = async (query, page) => {
setKeyword(query)
setPage(page)
setSearchResults([])
setUseTime(0)
setTotalPage(0)
setTotalHit(0)
if (!query || query === '') {
return
}
try {
const res = await index.search(query)
console.log(res)
const { hits } = res
const res = await index.search(query, { page, hitsPerPage: 10 })
const { hits, nbHits, nbPages, processingTimeMS } = res
setUseTime(processingTimeMS)
setTotalPage(nbPages)
setTotalHit(nbHits)
setSearchResults(hits)
const doms = document.getElementById('search-wrapper').getElementsByClassName('replace')
replaceSearchResult({
doms,
search: query,
target: {
element: 'span',
className: 'text-blue-600 border-b border-dashed'
}
})
setTimeout(() => {
replaceSearchResult({
doms,
search: query,
target: {
element: 'span',
className: 'text-blue-600 border-b border-dashed'
}
})
}, 150)
} catch (error) {
console.error('Algolia search error:', error)
}
}
const throttledHandleSearch = useRef(throttle(handleSearch, 300)) // 设置节流延迟时间
// 修改input的onChange事件处理函数
const handleInputChange = (e) => {
const query = e.target.value
throttledHandleSearch.current(query, 0)
}
/**
* 切换页码
* @param {*} page
*/
const switchPage = (page) => {
throttledHandleSearch.current(keyword, page)
}
/**
* 关闭弹窗
*/
const closeModal = () => {
setIsModalOpen(false)
}
if (!BLOG.ALGOLIA_APP_ID) {
return <></>
}
return (
<div id='search-wrapper' className={`${isModalOpen ? 'opacity-100' : 'invisible opacity-0 pointer-events-none'} fixed h-screen w-screen left-0 top-0 flex items-center justify-center`}>
{/* 内容 */}
<div id='search-wrapper' className={`${isModalOpen ? 'opacity-100' : 'invisible opacity-0 pointer-events-none'} fixed h-screen w-screen left-0 top-0 mt-12 flex items-start justify-center`}>
{/* 模态框 */}
<div className={`${isModalOpen ? 'opacity-100' : 'invisible opacity-0 translate-y-10'} flex flex-col justify-between w-full min-h-[10rem] max-w-xl dark:bg-hexo-black-gray dark:border-gray-800 bg-white dark:bg- p-5 rounded-lg z-50 shadow border hover:border-blue-600 duration-300 transition-all `}>
<div className='flex justify-between items-center'>
@@ -63,12 +112,12 @@ export default function AlgoliaSearchModal({ cRef }) {
<div><i class="text-gray-600 fa-solid fa-xmark p-1 cursor-pointer hover:text-blue-600" onClick={closeModal} ></i></div>
</div>
<input type="text" placeholder="在这里输入搜索关键词..." onChange={(e) => handleSearch(e.target.value)}
<input type="text" placeholder="在这里输入搜索关键词..." onChange={(e) => handleInputChange(e)}
className="bg-gray-50 dark:bg-gray-600 outline-blue-500 w-full px-4 my-2 py-1 mb-4 border rounded-md" />
{/* 标签组 */}
<div>
<div className='mb-4'>
<TagGroups/>
</div>
<ul>
@@ -81,7 +130,9 @@ export default function AlgoliaSearchModal({ cRef }) {
))}
</ul>
<div className='text-gray-600'><i class="fa-brands fa-algolia"></i> Algolia </div>
<Pagination totalPage={totalPage} page={page} switchPage={switchPage}/>
<div>{totalHit > 0 && <div>共搜索到 {totalHit} 条结果用时 {useTime} 毫秒</div> }</div>
<div className='text-gray-600 mt-2'><span><i class="fa-brands fa-algolia"></i> Algolia </span> </div>
</div>
{/* 遮罩 */}
@@ -90,3 +141,59 @@ export default function AlgoliaSearchModal({ cRef }) {
</div>
)
}
/**
* 标签组
*/
function TagGroups(props) {
const { tagOptions } = useGlobal()
// 获取tagOptions数组前十个
const firstTenTags = tagOptions.slice(0, 10)
return <div id='tags-group' className='dark:border-gray-700 space-y-2'>
{
firstTenTags?.map((tag, index) => {
return <Link passHref
key={index}
href={`/tag/${encodeURIComponent(tag.name)}`}
className={'cursor-pointer inline-block whitespace-nowrap'}>
<div className={' flex items-center hover:bg-blue-600 dark:hover:bg-yellow-600 hover:scale-110 hover:text-white rounded-lg px-2 py-0.5 duration-150 transition-all'}>
<div className='text-lg'>{tag.name} </div>{tag.count ? <sup className='relative ml-1'>{tag.count}</sup> : <></>}
</div>
</Link>
})
}
</div>
}
/**
* 分页
* @param {*} param0
*/
function Pagination(props) {
const { totalPage, page, switchPage } = props
if (totalPage <= 0) {
return <></>
}
const pagesElement = []
for (let i = 0; i < totalPage; i++) {
const selected = page === i
pagesElement.push(getPageElement(i, selected, switchPage))
}
return <div className='flex space-x-1 w-full justify-center py-1'>
{pagesElement.map(p => p)}
</div>
}
/**
* 获取分页按钮
* @param {*} i
* @param {*} selected
*/
function getPageElement(i, selected, switchPage) {
return <div onClick={() => switchPage(i)} className={`${selected ? 'font-bold text-white bg-blue-600 rounded' : 'hover:text-blue-600 hover:font-bold'} text-center cursor-pointer w-6 h-6 `}>
{i + 1}
</div>
}

View File

@@ -9,10 +9,7 @@ export default async function replaceSearchResult({ doms, search, target }) {
}
try {
const url = await loadExternalResource('https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js', 'js')
console.log('markjs 加载成功', url, window.Mark)
console.log('------', doms)
await loadExternalResource('https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js', 'js')
const Mark = window.Mark
if (doms instanceof HTMLCollection) {
for (const container of doms) {

View File

@@ -14,7 +14,9 @@ const GlobalContext = createContext()
* @returns {JSX.Element}
* @constructor
*/
export function GlobalContextProvider({ children }) {
export function GlobalContextProvider(props) {
console.log('global', props)
const { children, siteInfo, categoryOptions, tagOptions } = props
const router = useRouter()
const [lang, updateLang] = useState(BLOG.LANG) // 默认语言
const [locale, updateLocale] = useState(generateLocaleDict(BLOG.LANG)) // 默认语言
@@ -75,7 +77,10 @@ export function GlobalContextProvider({ children }) {
updateDarkMode,
theme,
setTheme,
switchTheme
switchTheme,
siteInfo,
categoryOptions,
tagOptions
}}>
{children}
</GlobalContext.Provider>

View File

@@ -17,6 +17,7 @@ import dynamic from 'next/dynamic'
// 自定义样式css和js引入
import ExternalScript from '@/components/ExternalScript'
import CommonHead from '@/components/CommonHead'
// 各种扩展插件 动画等
const ExternalPlugins = dynamic(() => import('@/components/ExternalPlugins'))
@@ -25,9 +26,11 @@ const MyApp = ({ Component, pageProps }) => {
useEffect(() => {
AOS.init()
}, [])
const { meta } = pageProps
return (
<GlobalContextProvider>
<GlobalContextProvider {...pageProps}>
<CommonHead meta={meta}/>
<ExternalScript />
<Component {...pageProps} />
<ExternalPlugins {...pageProps} />

View File

@@ -2,7 +2,6 @@
import BLOG from '@/blog.config'
import CONFIG from './config'
import CommonHead from '@/components/CommonHead'
import { useEffect } from 'react'
import { Header } from './components/Header'
import { Nav } from './components/Nav'
@@ -36,7 +35,7 @@ import { Style } from './style'
* @constructor
*/
const LayoutBase = props => {
const { children, meta, slotTop } = props
const { children, slotTop } = props
const { onLoading } = useGlobal()
// 增加一个状态以触发 Transition 组件的动画
@@ -49,8 +48,6 @@ const LayoutBase = props => {
return (
<div id='theme-example' className='dark:text-gray-300 bg-white dark:bg-black'>
{/* 网页SEO信息 */}
<CommonHead meta={meta} />
<Style/>
{/* 页头 */}

View File

@@ -1,7 +1,6 @@
'use client'
import CONFIG from './config'
import CommonHead from '@/components/CommonHead'
import TopNav from './components/TopNav'
import AsideLeft from './components/AsideLeft'
import BLOG from '@/blog.config'
@@ -43,7 +42,7 @@ export const useFukasawaGlobal = () => useContext(ThemeGlobalFukasawa)
* @constructor
*/
const LayoutBase = (props) => {
const { children, headerSlot, meta } = props
const { children, headerSlot } = props
const leftAreaSlot = <Live2D />
const { onLoading } = useGlobal()
@@ -66,7 +65,6 @@ const LayoutBase = (props) => {
<ThemeGlobalFukasawa.Provider value={{ isCollapsed, setIsCollapse }}>
<div id='theme-fukasawa'>
<CommonHead meta={meta} />
<Style/>
<TopNav {...props} />

View File

@@ -4,7 +4,6 @@ import CONFIG from './config'
import { useRouter } from 'next/router'
import { useEffect, useState, createContext, useContext } from 'react'
import { isBrowser } from '@/lib/utils'
import CommonHead from '@/components/CommonHead'
import Footer from './components/Footer'
import InfoCard from './components/InfoCard'
import RevolverMaps from './components/RevolverMaps'
@@ -43,7 +42,7 @@ export const useGitBookGlobal = () => useContext(ThemeGlobalGitbook)
* @constructor
*/
const LayoutBase = (props) => {
const { children, meta, post, allNavPages, slotLeft, slotRight, slotTop } = props
const { children, post, allNavPages, slotLeft, slotRight, slotTop } = props
const { onLoading } = useGlobal()
const router = useRouter()
const [tocVisible, changeTocVisible] = useState(false)
@@ -58,7 +57,6 @@ const LayoutBase = (props) => {
return (
<ThemeGlobalGitbook.Provider value={{ tocVisible, changeTocVisible, filteredPostGroups, setFilteredPostGroups, allNavPages, pageNavVisible, changePageNavVisible }}>
<CommonHead meta={meta} />
<Style/>
<div id='theme-gitbook' className='bg-white dark:bg-hexo-black-gray w-full h-full min-h-screen justify-center dark:text-gray-300'>

View File

@@ -143,9 +143,9 @@ const NavBar = props => {
</div>
{/* 右侧固定 */}
<div className='flex flex-shrink-0 justify-center items-center space-x-1'>
<div className='flex flex-shrink-0 justify-center items-center'>
<RandomPostButton {...props} />
<SearchButton />
<SearchButton {...props}/>
{!JSON.parse(BLOG.THEME_SWITCH) && <div className='hidden md:block'><DarkModeButton {...props} /></div>}
<ReadingProgress />

View File

@@ -8,7 +8,7 @@ import { useRef } from 'react'
* 搜索按钮
* @returns
*/
export default function SearchButton() {
export default function SearchButton(props) {
const { locale } = useGlobal()
const router = useRouter()
const searchModal = useRef(null)
@@ -25,6 +25,6 @@ export default function SearchButton() {
<div onClick={handleSearch} title={locale.NAV.SEARCH} alt={locale.NAV.SEARCH} className='cursor-pointer hover:bg-black hover:bg-opacity-10 rounded-full w-10 h-10 flex justify-center items-center duration-200 transition-all'>
<i title={locale.NAV.SEARCH} className="fa-solid fa-magnifying-glass" />
</div>
<AlgoliaSearchModal cRef={searchModal} />
<AlgoliaSearchModal cRef={searchModal} {...props}/>
</>
}

View File

@@ -39,12 +39,10 @@ import LazyImage from '@/components/LazyImage'
* @constructor
*/
const LayoutBase = props => {
const { children, headerSlot, slotTop, slotRight, meta, siteInfo, className } = props
const { children, headerSlot, slotTop, slotRight, siteInfo, className } = props
return (
<div id='theme-heo' className='bg-[#f7f9fe] dark:bg-[#18171d] h-full min-h-screen flex flex-col'>
{/* 网页SEO */}
<CommonHead meta={meta} siteInfo={siteInfo} />
<Style />
{/* 顶部嵌入 导航栏首页放hero文章页放文章详情 */}

View File

@@ -1,6 +1,5 @@
import CONFIG from './config'
import CommonHead from '@/components/CommonHead'
import { useState, createContext, useContext, useEffect } from 'react'
import Footer from './components/Footer'
import InfoCard from './components/InfoCard'
@@ -48,7 +47,7 @@ export const useMediumGlobal = () => useContext(ThemeGlobalMedium)
* @constructor
*/
const LayoutBase = props => {
const { children, meta, showInfoCard = true, slotRight, slotTop, siteInfo, notice } = props
const { children, showInfoCard = true, slotRight, slotTop, siteInfo, notice } = props
const { locale } = useGlobal()
const router = useRouter()
const [tocVisible, changeTocVisible] = useState(false)
@@ -56,8 +55,6 @@ const LayoutBase = props => {
return (
<ThemeGlobalMedium.Provider value={{ tocVisible, changeTocVisible }}>
{/* SEO相关 */}
<CommonHead meta={meta} />
{/* CSS样式 */}
<Style/>

View File

@@ -1,6 +1,4 @@
import CONFIG from './config'
import CommonHead from '@/components/CommonHead'
import FloatDarkModeButton from './components/FloatDarkModeButton'
import Footer from './components/Footer'
import JumpToBottomButton from './components/JumpToBottomButton'
@@ -34,7 +32,7 @@ import replaceSearchResult from '@/components/Mark'
* @constructor
*/
const LayoutBase = (props) => {
const { children, headerSlot, meta, floatSlot, rightAreaSlot, siteInfo } = props
const { children, headerSlot, floatSlot, rightAreaSlot, siteInfo } = props
const { onLoading } = useGlobal()
const targetRef = useRef(null)
const floatButtonGroup = useRef(null)
@@ -71,8 +69,6 @@ const LayoutBase = (props) => {
return (
<div id='theme-next'>
{/* SEO相关 */}
<CommonHead meta={meta} />
<Style/>
{/* 移动端顶部导航栏 */}

View File

@@ -1,6 +1,5 @@
import BLOG from '@/blog.config'
import CONFIG from './config'
import CommonHead from '@/components/CommonHead'
import React, { useEffect, useState } from 'react'
import Nav from './components/Nav'
import { Footer } from './components/Footer'
@@ -32,7 +31,7 @@ import replaceSearchResult from '@/components/Mark'
* @constructor
*/
const LayoutBase = props => {
const { children, meta, post, topSlot } = props
const { children, post, topSlot } = props
const fullWidth = post?.fullWidth ?? false
const { onLoading } = useGlobal()
@@ -40,7 +39,6 @@ const LayoutBase = props => {
return (
<div id='theme-nobelium' className='nobelium relative dark:text-gray-300 w-full bg-white dark:bg-black min-h-screen'>
{/* SEO相关 */}
<CommonHead meta={meta} />
<Style/>
{/* 顶部导航栏 */}

View File

@@ -1,6 +1,5 @@
import CONFIG from './config'
import CommonHead from '@/components/CommonHead'
import React, { createContext, useContext, useEffect, useState } from 'react'
import { createContext, useContext, useEffect, useState } from 'react'
import Header from './components/Nav'
import { useGlobal } from '@/lib/global'
@@ -35,7 +34,7 @@ export const usePlogGlobal = () => useContext(ThemeGlobalPlog)
* @constructor
*/
const LayoutBase = props => {
const { children, meta, topSlot } = props
const { children, topSlot } = props
const { onLoading, updateDarkMode } = useGlobal()
const [showModal, setShowModal] = useState(false)
const [modalContent, setModalContent] = useState(null)
@@ -59,8 +58,6 @@ const LayoutBase = props => {
return (
<ThemeGlobalPlog.Provider value={{ showModal, setShowModal, modalContent, setModalContent }}>
<div id='theme-plog' className='plog relative dark:text-gray-300 w-full bg-black min-h-screen'>
{/* SEO相关 */}
<CommonHead meta={meta} />
<Style/>
{/* 移动端顶部导航栏 */}

View File

@@ -12,7 +12,6 @@ import ArticleAround from './components/ArticleAround'
import ShareBar from '@/components/ShareBar'
import { AdSlot } from '@/components/GoogleAdsense'
import Link from 'next/link'
import CommonHead from '@/components/CommonHead'
import { TopBar } from './components/TopBar'
import { Header } from './components/Header'
import { NavBar } from './components/NavBar'
@@ -33,7 +32,7 @@ import replaceSearchResult from '@/components/Mark'
* @returns
*/
const LayoutBase = props => {
const { children, meta, slotTop } = props
const { children, slotTop } = props
const { onLoading } = useGlobal()
if (isBrowser()) {
@@ -41,7 +40,6 @@ const LayoutBase = props => {
}
return (
<div id='theme-simple' className='min-h-screen flex flex-col dark:text-gray-300 bg-white dark:bg-black'>
<CommonHead meta={meta} />
<Style/>
{CONFIG.TOP_BAR && <TopBar {...props} />}

View File

@@ -61,7 +61,6 @@ export const getLayoutNameByPath = (path) => {
* @description 读取cookie中存的用户主题
*/
export const initDarkMode = (updateDarkMode) => {
console.log('检查深色模式')
// 查看用户设备浏览器是否深色模型
let newDarkMode = isPreferDark()