A rewrite of Poly+, my quality-of-life browser extension for Polytoria. Built entirely fresh using the WXT extension framework, Typescript, and with added better overall code quality.
extension
1import { preferences } from "@/utils/storage";
2
3/**
4 * Detects any username mentions in a forum post and turns them into clickable links.
5 */
6export function forumMentions() {
7 const textBlocks = document.querySelectorAll('p:not(.text-muted):not(.mb-0)');
8 const regex = /@([\w.]+)/g;
9
10 textBlocks.forEach(text => {
11 const walker = document.createTreeWalker(text, NodeFilter.SHOW_TEXT, null);
12 let node;
13
14 while ((node = walker.nextNode())) {
15 const fragment = document.createDocumentFragment();
16 let lastIndex = 0;
17 let match;
18
19 while ((match = regex.exec(node.nodeValue!)) !== null) {
20 const username = match[1];
21 const link = document.createElement('a');
22 link.href = `/u/${username}`;
23 link.className = 'polyplus-mention';
24 link.textContent = match[0];
25
26 fragment.appendChild(document.createTextNode(node.nodeValue!.substring(lastIndex, match.index)));
27 fragment.appendChild(link);
28 lastIndex = match.index + match[0].length;
29 }
30
31 fragment.appendChild(document.createTextNode(node.nodeValue!.substring(lastIndex)));
32 node.parentNode!.replaceChild(fragment, node);
33 }
34 });
35}