Skip to content

Commit

Permalink
sanitizeAllHtmlButMark
Browse files Browse the repository at this point in the history
  • Loading branch information
abernier committed Aug 24, 2024
1 parent 2cded1f commit f572cb4
Show file tree
Hide file tree
Showing 3 changed files with 153 additions and 12 deletions.
125 changes: 124 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@types/node": "^18.19.44",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/sanitize-html": "^2.13.0",
"autoprefixer": "^10.4.20",
"eslint": "^8.57.0",
"eslint-config-next": "^14.2.5",
Expand Down Expand Up @@ -41,6 +42,7 @@
"rehype-github-alerts": "^3.0.0",
"rehype-prism-plus": "^2.0.0",
"remark-gfm": "^4.0.0",
"sanitize-html": "^2.13.0",
"tailwind-merge": "^2.5.2"
},
"scripts": {
Expand Down
38 changes: 27 additions & 11 deletions src/components/Search/SearchItem.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Icon from '@/components/Icon'
import { highlight } from '@/utils/text'
import Link from 'next/link'
import sanitizeHtml from 'sanitize-html'

export interface SearchResult {
title: string
Expand All @@ -14,6 +15,11 @@ export interface SearchItemProps {
search: string
result: SearchResult
}
function sanitizeAllHtmlButMark(str: string) {
return sanitizeHtml(str, {
allowedTags: ['mark'],
})
}

function SearchItem({ search, result }: SearchItemProps) {
return (
Expand All @@ -24,18 +30,28 @@ function SearchItem({ search, result }: SearchItemProps) {
>
<li className="px-2 py-1">
<div className="interactive-bg-surface-container-high flex items-center justify-between rounded-md p-4 py-5 transition-colors">
<span
<div
className="break-all pr-3"
dangerouslySetInnerHTML={{
__html: `
<span class="block text-xs text-on-surface-variant/50 pb-1">${result.label}</span>
${highlight(result.title, search)}
<span class="block text-sm text-on-surface-variant/50 pt-2">
${highlight(result.content, search)}
</span>
`,
}}
/>
// dangerouslySetInnerHTML={{
// __html: `

// `,
// }}
>
<div className="block pb-1 text-xs text-on-surface-variant/50">${result.label}</div>
<span
dangerouslySetInnerHTML={{
__html: sanitizeAllHtmlButMark(highlight(result.title, search)),
}}
/>
<div className="block pt-2 text-sm text-on-surface-variant/50">
<span
dangerouslySetInnerHTML={{
__html: sanitizeAllHtmlButMark(highlight(result.content, search)),
}}
/>
</div>
</div>
{result.image ? (
// eslint-disable-next-line @next/next/no-img-element
<img className="max-w-[40%] rounded" src={result.image} alt={result.title} />
Expand Down

0 comments on commit f572cb4

Please sign in to comment.