Skip to content

Commit 3f8d553

Browse files
committed
AMP-31064: Fix link generation.
1 parent 5dbbfa6 commit 3f8d553

1 file changed

Lines changed: 28 additions & 9 deletions

File tree

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

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,42 @@
11
const useHash = process.env.VITE_REACT_APP_USE_HASH_LINKS;
2+
const WP_ROOT = process.env.VITE_REACT_APP_WP || '/wp';
23

4+
// Escapes special regex metacharacters in a literal string.
5+
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
6+
7+
// Builds a regex that matches the scheme + configured WP hostname(s) + optional WP
8+
// subdirectory path (e.g. /wp), so the entire origin prefix can be replaced with the
9+
// locale slug in one step.
10+
// Returns null when no valid hosts are configured — callers must treat null as "skip".
11+
const buildUrlRegex = () => {
12+
const hosts = process.env.VITE_REACT_APP_WP_HOSTS
13+
?.split(",").map(h => h.trim()).filter(Boolean) || [];
14+
if (!hosts.length) return null;
15+
const hostsPattern = hosts.map(escapeRegex).join('|');
16+
const wpRootPattern = escapeRegex(WP_ROOT);
17+
return new RegExp(`^(http|https)://(${hostsPattern})(${wpRootPattern})?`, 'ig');
18+
};
319

420
export const replaceLink = (url, locale) => {
521
//console.log("--------- replaceLink--------------")
622
//console.log(process.env.REACT_APP_WP_HOSTS)
7-
const replacementTarget = process.env.VITE_REACT_APP_WP_HOSTS.split(",")
8-
let all = new RegExp("^(http|https)://(" + replacementTarget.join('|') + ")", "ig");
9-
if (useHash && url) {
10-
return url.replaceAll(all, "#" + locale)
11-
} else if (url) {
12-
return url.replaceAll(all, "/" + locale)
23+
if (!url) return url;
24+
const all = buildUrlRegex();
25+
// Guard: if WP_HOSTS is not configured the regex would be wrong — return unchanged.
26+
if (!all) return url;
27+
if (useHash) {
28+
return url.replaceAll(all, '#' + locale);
1329
}
30+
return url.replaceAll(all, '/' + locale);
1431
}
1532

1633
export const replaceHTMLinks = (html, locale) => {
1734
//console.log("--------- replaceHTMLinks--------------")
1835
// console.log(process.env.REACT_APP_WP_HOSTS)
19-
const replacementTarget = process.env.VITE_REACT_APP_WP_HOSTS?.split(",") || []
20-
let all = new RegExp("^(http|https)://(" + replacementTarget.join('|') + ")", "ig");
36+
if (!html) return html;
37+
const all = buildUrlRegex();
38+
// Guard: if WP_HOSTS is not configured the regex would be wrong — return unchanged.
39+
if (!all) return html;
2140

2241
let link;
2342
let regex = /href\s*=\s*(['"])(https?:\/\/.+?)\1/ig;
@@ -58,4 +77,4 @@ export const removePatternBrackets = (html) => {
5877
}
5978
};
6079

61-
export default {replaceHTMLinks, replaceLink}
80+
export default {replaceHTMLinks, replaceLink}

0 commit comments

Comments
 (0)