-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate-article-links.ts
More file actions
65 lines (54 loc) · 1.91 KB
/
update-article-links.ts
File metadata and controls
65 lines (54 loc) · 1.91 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
import { buildArticleUrl } from './build-article-url';
import { ARTICLE_LINK_MAP } from '@/config/zendesk';
import { ZENDESK_ARTICLE_LINK_SELECTOR } from '@/constants/zendesk-selectors';
/**
* Updates article links in a document based on the provided mapping.
*
* @function updateArticleLinks
* @param {Document} doc - The document containing article links
*
* @returns {number} The number of links that were found and updated for retry
* logic
*/
export function updateArticleLinks(doc: Document): number {
// Create an array of article IDs
const articleIds = Object.keys(ARTICLE_LINK_MAP);
// Find all links with aria-label="View article:"
const anchorElements = doc.querySelectorAll<HTMLAnchorElement>(
ZENDESK_ARTICLE_LINK_SELECTOR,
);
let updatedCount = 0;
anchorElements.forEach((anchorEl) => {
const href = anchorEl.getAttribute('href');
if (!href) {
return;
}
// Find matching article ID in href
const matchedId = articleIds.find((id) => href.includes(id));
if (matchedId && ARTICLE_LINK_MAP[matchedId]) {
const newHref = buildArticleUrl(ARTICLE_LINK_MAP[matchedId]);
anchorEl.setAttribute('href', newHref);
// Prevent Zendesk's internal click handler from intercepting navigation.
// We use capture phase so our handler fires before Zendesk's handlers on
// the element. Guard against duplicate listeners on repeated calls.
if (!anchorEl.dataset.helpPageRewritten) {
anchorEl.dataset.helpPageRewritten = 'true';
anchorEl.addEventListener(
'click',
(event) => {
event.preventDefault();
event.stopImmediatePropagation();
window.open(
anchorEl.getAttribute('href') ?? newHref,
'_blank',
'noopener,noreferrer',
);
},
true,
);
}
updatedCount++;
}
});
return updatedCount;
}