Skip to content

Commit a5c0561

Browse files
fix(SNR-217): enhance link handling in wp-react-lib utility functions
1 parent 7558929 commit a5c0561

File tree

1 file changed

+38
-10
lines changed

1 file changed

+38
-10
lines changed

wp-react-lib/src/util/index.js

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,59 @@
1-
const useHash = process.env.VITE_REACT_APP_USE_HASH_LINKS === "true" || false;
1+
const _useHash = process.env.VITE_REACT_APP_USE_HASH_LINKS === "true" || false;
22

33
const localReplaceLink = (url, locale) => {
4-
if (url) {
5-
if (!url.substr(url.indexOf("/wp") + 3).startsWith("/" + locale)) {
6-
return "/" + locale + url.substr(url.indexOf("/wp") + 3);
4+
if (!url) {
5+
return "";
6+
}
7+
const safeLocale = locale || "en";
8+
9+
try {
10+
let pathname = url;
11+
12+
// If absolute URL, extract pathname and ignore origin
13+
if (/^https?:\/\//i.test(url)) {
14+
const parsed = new URL(url);
15+
pathname = parsed.pathname + (parsed.search || "") + (parsed.hash || "");
716
}
8-
return url.substr(url.indexOf("/wp") + 3);
17+
18+
if (!pathname.startsWith("/wp/")) {
19+
return url; // Not a WordPress path, leave unchanged
20+
}
21+
22+
const afterWp = pathname.slice(3); // remove '/wp'
23+
24+
if (!afterWp.startsWith("/" + safeLocale)) {
25+
return "/" + safeLocale + afterWp;
26+
}
27+
28+
return afterWp;
29+
} catch (e) {
30+
console.error("Error parsing URL:", e);
31+
return url;
932
}
10-
return "";
1133
};
1234

1335
export const replaceLink = (url, locale) => {
14-
return localReplaceLink(url, locale)
36+
if (!url) {
37+
return "";
38+
}
39+
return localReplaceLink(url, locale);
1540
}
1641

1742
export const replaceHTMLinks = (html, locale) => {
1843
//console.log("--------- replaceHTMLinks--------------")
1944
// console.log(process.env.REACT_APP_WP_HOSTS)
2045

2146
let link;
22-
let regex = /href\s*=\s*(['"])(https?:\/\/.+?)\1/ig;
47+
// Match both absolute (http/https) and relative WP links in a single pass
48+
let linkRegex = /href\s*=\s*(['"])(https?:\/\/.+?|\/wp\/[^'"\s>]+)\1/ig;
2349

2450
let newHtml = html
25-
while ((link = regex.exec(html)) !== null) {
51+
while ((link = linkRegex.exec(html)) !== null) {
2652
let href = link[2]
2753
let newLink = localReplaceLink(href, locale)
28-
newHtml = newHtml.replaceAll(link[2], newLink)
54+
if (newLink !== href) {
55+
newHtml = newHtml.replaceAll(href, newLink)
56+
}
2957
}
3058
return newHtml;
3159
}

0 commit comments

Comments
 (0)