forked from w3c/csswg-wiki
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabbr.js
More file actions
89 lines (76 loc) · 2.39 KB
/
abbr.js
File metadata and controls
89 lines (76 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Wrap known abbreviations in <abbr> tags with tooltips
(function() {
const abbreviations = {
'CSS': 'Cascading Style Sheets',
'HTML': 'HyperText Markup Language',
'W3C': 'World Wide Web Consortium',
'IRC': 'Internet Relay Chat',
'URL': 'Uniform Resource Locator',
'GUI': 'Graphical User Interface'
};
// Build regex pattern matching whole words only
const pattern = new RegExp(
'\\b(' + Object.keys(abbreviations).join('|') + ')\\b',
'g'
);
function processTextNode(node) {
const text = node.textContent;
if (!pattern.test(text)) return;
// Reset regex lastIndex
pattern.lastIndex = 0;
const fragment = document.createDocumentFragment();
let lastIndex = 0;
let match;
while ((match = pattern.exec(text)) !== null) {
// Add text before match
if (match.index > lastIndex) {
fragment.appendChild(
document.createTextNode(text.slice(lastIndex, match.index))
);
}
// Create <abbr> element
const abbr = document.createElement('abbr');
abbr.textContent = match[1];
abbr.title = abbreviations[match[1]];
fragment.appendChild(abbr);
lastIndex = pattern.lastIndex;
}
// Add remaining text
if (lastIndex < text.length) {
fragment.appendChild(document.createTextNode(text.slice(lastIndex)));
}
node.parentNode.replaceChild(fragment, node);
}
function walkTextNodes(root) {
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
// Skip script, style, code, pre, abbr elements
const parent = node.parentNode;
const tag = parent.tagName;
if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'CODE' ||
tag === 'PRE' || tag === 'ABBR' || tag === 'A') {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
const nodes = [];
while (walker.nextNode()) {
nodes.push(walker.currentNode);
}
// Process in reverse to avoid index issues
nodes.forEach(processTextNode);
}
// Run when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function() {
walkTextNodes(document.querySelector('main'));
});
} else {
walkTextNodes(document.querySelector('main'));
}
})();