| | import { useEffect } from 'react' |
| | import { useRouter } from 'next/router' |
| | import hljs from 'highlight.js/lib/core' |
| | import json from 'highlight.js/lib/languages/json' |
| | import javascript from 'highlight.js/lib/languages/javascript' |
| | import hljsCurl from 'highlightjs-curl' |
| |
|
| | |
| | |
| | hljs.registerLanguage('json', json) |
| | hljs.registerLanguage('javascript', javascript) |
| | hljs.registerLanguage('curl', hljsCurl) |
| | const SUPPORTED_LANGUAGES = ['json', 'javascript', 'curl'] |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | const CODE_ELEMENTS_PARENT_SELECTOR = '[data-highlight]' |
| | const CODE_SELECTOR = 'code' |
| |
|
| | export default function ClientSideHighlightJS() { |
| | const { asPath } = useRouter() |
| |
|
| | useEffect(() => { |
| | |
| | |
| | |
| | |
| | |
| | if (!window.IntersectionObserver) return |
| |
|
| | const intersectionObserver = new IntersectionObserver((entries) => { |
| | for (const entry of entries) { |
| | if (entry.isIntersecting) { |
| | const element = entry.target as HTMLElement |
| | if (!element.classList.contains('hljs')) { |
| | hljs.highlightElement(element) |
| | } |
| | } |
| | } |
| | }) |
| | const codeElementParents = Array.from( |
| | document.querySelectorAll<HTMLElement>(CODE_ELEMENTS_PARENT_SELECTOR), |
| | ) |
| | for (const parent of codeElementParents) { |
| | const language = parent.dataset.highlight || 'json' |
| | if (!SUPPORTED_LANGUAGES.includes(language)) { |
| | if (process.env.NODE_ENV === 'development') { |
| | console.warn( |
| | `For highlighting, only ${SUPPORTED_LANGUAGES} is supported. Not '${language}'.`, |
| | ) |
| | } |
| | continue |
| | } |
| | for (const element of Array.from(parent.querySelectorAll<HTMLElement>(CODE_SELECTOR))) { |
| | element.classList.add(`language-${language}`) |
| | intersectionObserver.observe(element) |
| | } |
| | } |
| |
|
| | return () => { |
| | intersectionObserver.disconnect() |
| | } |
| | }, [asPath]) |
| |
|
| | return null |
| | } |
| |
|