Skip to content

Commit ae10314

Browse files
committed
feat: highlight keyword
1 parent 37c0dbe commit ae10314

4 files changed

Lines changed: 68 additions & 6 deletions

File tree

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,13 @@
1010
},
1111
"dependencies": {
1212
"react": "^18.2.0",
13-
"react-dom": "^18.2.0"
13+
"react-dom": "^18.2.0",
14+
"react-highlight-words": "^0.20.0"
1415
},
1516
"devDependencies": {
1617
"@types/react": "^18.2.7",
1718
"@types/react-dom": "^18.2.4",
19+
"@types/react-highlight-words": "^0.16.4",
1820
"@vitejs/plugin-react": "^4.0.0",
1921
"typescript": "^5.0.4",
2022
"vite": "^4.3.9",

pnpm-lock.yaml

Lines changed: 48 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/App.css

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,10 @@
9090
color: var(--text1);
9191
}
9292

93+
#comment-search-root .comment-item-highlight {
94+
background-color: #f8eec2;
95+
}
96+
9397
#comment-search-root .comment-item-time {
9498
color: var(--text3);
9599
margin-top: 4px;

src/App.tsx

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import { useRef, useState } from 'react'
2+
import Highlighter from 'react-highlight-words'
23
import { fetchComments } from './api'
34
import { Reply } from './reply'
45
import { extractVideoId, formatDateTime } from './utils'
56

67
import './App.css'
78

9+
let keyword = ''
10+
811
export default function App() {
912
const dialogRef = useRef<HTMLDialogElement>(null)
1013
const [comments, setComments] = useState<Reply[]>()
@@ -22,10 +25,11 @@ export default function App() {
2225
if (e.key === 'Enter' && promiseRef.current) {
2326
e.preventDefault()
2427
// `e.currentTarget` will be null after `await`
25-
const keyword = e.currentTarget.value
28+
const _keyword = e.currentTarget.value
29+
keyword = _keyword
2630
promiseRef.current
2731
.then((allComments) => {
28-
const comments = searchComments(allComments, keyword)
32+
const comments = searchComments(allComments, _keyword)
2933
setComments(comments)
3034
})
3135
.catch((e) => {
@@ -87,9 +91,13 @@ const CommentTree: React.FC<CommentProps> = ({ comments, sub = false }) => {
8791
<span className='comment-item-username'>
8892
{comment.member.uname}
8993
</span>
90-
<span className='comment-item-message'>
91-
{comment.content.message}
92-
</span>
94+
<Highlighter
95+
className='comment-item-message'
96+
highlightClassName='comment-item-highlight'
97+
searchWords={[keyword]}
98+
autoEscape={true}
99+
textToHighlight={comment.content.message}
100+
/>
93101
<div className='comment-item-time'>
94102
{formatDateTime(comment.ctime)}
95103
</div>

0 commit comments

Comments
 (0)