Skip to content

Commit 82d24ae

Browse files
fix: fix links handling in the content
1 parent caf50d1 commit 82d24ae

1 file changed

Lines changed: 12 additions & 27 deletions

File tree

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

Lines changed: 12 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,32 @@
1-
const useHash = process.env.VITE_REACT_APP_USE_HASH_LINKS;
1+
const useHash = process.env.VITE_REACT_APP_USE_HASH_LINKS === "true" || false;
22

3+
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);
7+
}
8+
return url.substr(url.indexOf("/wp") + 3);
9+
}
10+
return "";
11+
};
312

413
export const replaceLink = (url, locale) => {
5-
//console.log("--------- replaceLink--------------")
6-
//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)
13-
}
14+
return localReplaceLink(url, locale)
1415
}
1516

1617
export const replaceHTMLinks = (html, locale) => {
1718
//console.log("--------- replaceHTMLinks--------------")
1819
// 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");
2120

2221
let link;
2322
let regex = /href\s*=\s*(['"])(https?:\/\/.+?)\1/ig;
2423

2524
let newHtml = html
2625
while ((link = regex.exec(html)) !== null) {
2726
let href = link[2]
28-
let newLink
29-
if (useHash) {
30-
newLink = href.replace(all, '#' + locale) //TODO:fix it!
31-
} else {
32-
newLink = href.replace(all, '' + locale) //TODO:fix it!
33-
}
27+
let newLink = localReplaceLink(href, locale)
3428
newHtml = newHtml.replaceAll(link[2], newLink)
3529
}
36-
if (useHash) {
37-
let anchor = /href="#([^"]*)"/ig;
38-
let re2 = new RegExp(anchor, "i");
39-
while ((link = anchor.exec(html)) !== null) {
40-
let href = link[0]
41-
let newLink = href.replace(re2, 'href="javascript:document.getElementById(\'' + link[1] + '\').scrollIntoView({block: \'start\', behavior: \'smooth\'})"')
42-
newHtml = newHtml.replaceAll(link[0], newLink)
43-
}
44-
}
4530
return newHtml;
4631
}
4732

0 commit comments

Comments
 (0)