搜索标红效果

This commit is contained in:
tangly1024
2022-03-03 11:40:29 +08:00
parent 636e7be12a
commit 180b0245bd
4 changed files with 18 additions and 12 deletions

View File

@@ -49,7 +49,6 @@ export async function getAllPosts ({ notionPageData, from, pageType }) {
})
if (!posts || posts.length === 0) {
console.warn('文章列表为空')
const cacheKey = 'page_block_' + BLOG.NOTION_PAGE_ID
await delCacheData(cacheKey)
}

View File

@@ -110,18 +110,16 @@ async function filterByMemCache (allPosts, keyword) {
// console.log('搜索是否命中缓存', page !== null, indexContent)
post.results = []
let hitCount = 0
const re = new RegExp(`${keyword}`, 'gim')
for (const i in indexContent) {
const c = indexContent[i]
const index = c.toLowerCase().indexOf(keyword.toLowerCase())
const referText = c?.replace(re, `<span class='text-red-500'>${keyword}</span>`)
if (index > -1) {
hit = true
hitCount += 1
post.results.push(`<span>${referText}</span>`)
post.results.push(c)
} else {
if ((post.results.length - 1) / hitCount < 3 || i === 0) {
post.results.push(`<span>${referText}</span>`)
post.results.push(c)
}
}
}

View File

@@ -2,11 +2,21 @@ import LayoutBase from './LayoutBase'
import StickyBar from './components/StickyBar'
import BlogPostListScroll from './components/BlogPostListScroll'
import { useGlobal } from '@/lib/global'
import { useEffect } from 'react'
export const LayoutSearch = (props) => {
const { locale } = useGlobal()
const { posts } = props
const { posts, keyword } = props
useEffect(() => {
setTimeout(() => {
const container = document.getElementById('container')
if (container && container.innerHTML) {
const re = new RegExp(`${keyword}`, 'gim')
container.innerHTML = container.innerHTML.replace(re, `<span class='text-red-500 border-b border-dashed'>${keyword}</span>`)
}
},
100)
})
return (
<LayoutBase {...props} >
<StickyBar>

View File

@@ -12,8 +12,8 @@ const BlogPostCard = ({ post, showSummary }) => {
const { locale } = useGlobal()
const showPreview = CONFIG_NEXT.POST_LIST_PREVIEW && post.blockMap
return (
<Card className='w-full'>
<div key={post.id} className='animate__animated animate__fadeIn flex flex-col-reverse justify-between duration-300'>
<Card className='w-full animate__animated animate__fadeIn'>
<div key={post.id} className='flex flex-col-reverse justify-between duration-300'>
<div className='lg:p-8 p-4 flex flex-col w-full'>
<Link href={`${BLOG.PATH}/article/${post.slug}`} passHref>
@@ -47,9 +47,8 @@ const BlogPostCard = ({ post, showSummary }) => {
{/* 搜索结果 */}
{post.results && <p className='mt-4 text-gray-700 dark:text-gray-300 text-sm font-light leading-7'>
{post.results.map(r => <span key={r}><span dangerouslySetInnerHTML={{ __html: r }}/>...</span>)}
</p>
}
{post.results.map(r => <span key={r}>{r}</span>)}
</p> }
{showPreview && post?.blockMap && <div className='overflow-ellipsis truncate'>
<NotionRenderer