Last active
November 19, 2024 23:32
-
Star
(177)
You must be signed in to star a gist -
Fork
(15)
You must be signed in to fork a gist
-
-
Save JohnPhamous/ecaa69a4f64acac8e02b9baea826863e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const chaosTestStrings = (): void => { | |
const textNodes = getAllTextNodes(document.body); | |
for (const node of textNodes) { | |
const textNodeLength = node.textContent ? node.textContent.length : 0; | |
if (node.textContent === null) { | |
return; | |
} | |
if (node.parentElement instanceof Element) { | |
if (node.parentElement.dataset.originalText === undefined) { | |
node.parentElement.dataset.originalText = node.textContent; | |
node.textContent = generateRandomString(textNodeLength * 3); | |
} else { | |
node.textContent = node.parentElement.dataset.originalText; | |
node.parentElement.removeAttribute('data-original-text'); | |
} | |
} | |
} | |
}; | |
const PARENT_TAGS_TO_EXCLUDE = new Set(['STYLE', 'SCRIPT', 'TITLE']); | |
const RANDOM_CHARACTERS = | |
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '; | |
function* walkDOMTree( | |
root: Node, | |
whatToShow: number = NodeFilter.SHOW_ALL, | |
{ | |
inspect, | |
collect, | |
callback, | |
}: { | |
inspect?: (node: Node) => boolean; | |
collect?: (node: Node) => boolean; | |
callback?: (node: Node) => void; | |
} = {}, | |
): Generator<Node, void> { | |
const walker = document.createTreeWalker(root, whatToShow, { | |
acceptNode(node) { | |
if (inspect && !inspect(node)) { | |
return NodeFilter.FILTER_REJECT; | |
} | |
if (collect && !collect(node)) { | |
return NodeFilter.FILTER_SKIP; | |
} | |
return NodeFilter.FILTER_ACCEPT; | |
}, | |
}); | |
let n; | |
while ((n = walker.nextNode())) { | |
callback?.(n); | |
yield n; | |
} | |
} | |
function* getAllTextNodes(el: Node): Generator<Node, void> { | |
yield* walkDOMTree(el, NodeFilter.SHOW_TEXT, { | |
inspect: (textNode: Node) => | |
!PARENT_TAGS_TO_EXCLUDE.has(textNode.parentElement?.nodeName || ''), | |
}); | |
} | |
function generateRandomString(length: number): string { | |
return Array.from( | |
{ length }, | |
() => | |
RANDOM_CHARACTERS[Math.floor(Math.random() * RANDOM_CHARACTERS.length)], | |
).join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment