MCPcopy Create free account
hub / github.com/github/docs / ClientSideHighlightJS

Function ClientSideHighlightJS

components/ClientSideHighlightJS.tsx:31–76  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

29const CODE_SELECTOR = 'div code' || 'pre code'
30
31export default function ClientSideHighlightJS() {
32 const { asPath } = useRouter()
33
34 useEffect(() => {
35 // Hi Internet Explorer!
36 // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#browser_compatibility
37 // If intersectionObserver isn't supported, let's not bother doing
38 // anything. If your browser is that behind, syntax highlight is probably
39 // your least concern.
40 if (!window.IntersectionObserver) return
41
42 const intersectionObserver = new IntersectionObserver((entries) => {
43 for (const entry of entries) {
44 if (entry.isIntersecting) {
45 const element = entry.target as HTMLElement
46 if (!element.classList.contains('hljs')) {
47 hljs.highlightElement(element)
48 }
49 }
50 }
51 })
52 for (const parent of Array.from(
53 document.querySelectorAll<HTMLElement>(CODE_ELEMENTS_PARENT_SELECTOR)
54 )) {
55 const language = parent.dataset.highlight || 'json'
56 if (!SUPPORTED_LANGUAGES.includes(language)) {
57 if (process.env.NODE_ENV === 'development') {
58 console.warn(
59 `For highlighting, only ${SUPPORTED_LANGUAGES} is supported. Not '${language}'.`
60 )
61 }
62 continue
63 }
64 for (const element of Array.from(parent.querySelectorAll<HTMLElement>(CODE_SELECTOR))) {
65 element.classList.add(`language-${language}`)
66 intersectionObserver.observe(element)
67 }
68 }
69
70 return () => {
71 intersectionObserver.disconnect()
72 }
73 }, [asPath])
74
75 return null
76}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected