Skip to content

Commit e7db943

Browse files
committed
improve text replacement logic
1 parent a309aba commit e7db943

1 file changed

Lines changed: 18 additions & 7 deletions

File tree

app/[locale]/components/AprilFools/AprilFools.tsx

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@
33
import { useEffect } from 'react'
44
import { usePathname } from 'next/navigation'
55

6+
function replaceInNode(root: Node) {
7+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
8+
let node: Node | null
9+
while ((node = walker.nextNode())) {
10+
if (node.textContent?.includes('WebGAL'))
11+
node.textContent = node.textContent.replace(/WebGAL/g, 'WebG@L')
12+
}
13+
}
14+
615
const AprilFools = () => {
716
const pathname = usePathname()
817

@@ -13,14 +22,16 @@ const AprilFools = () => {
1322
if (document.title.includes('WebGAL'))
1423
document.title = document.title.replace(/WebGAL/g, 'WebG@L')
1524

16-
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT)
17-
const textNodes: Text[] = []
18-
let node: Node | null
19-
while ((node = walker.nextNode())) textNodes.push(node as Text)
20-
textNodes.forEach(node => {
21-
if (node.textContent?.includes('WebGAL'))
22-
node.textContent = node.textContent.replace(/WebGAL/g, 'WebG@L')
25+
replaceInNode(document.body)
26+
27+
const observer = new MutationObserver((mutations) => {
28+
mutations.forEach(({ addedNodes }) =>
29+
addedNodes.forEach(node => replaceInNode(node))
30+
)
2331
})
32+
observer.observe(document.body, { childList: true, subtree: true })
33+
34+
return () => observer.disconnect()
2435
}, [pathname])
2536

2637
return null

0 commit comments

Comments
 (0)