Skip to content

Commit 01ce53a

Browse files
authored
Merge pull request #1980 from dscho/better-relative-urls-support
Better relative urls support
2 parents 2da58bf + 9b59a30 commit 01ce53a

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

assets/js/application.js

+15-5
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,12 @@ popped = 'state' in window.history;
2121
initialURL = location.href;
2222

2323
const baseURLPrefix = (() => {
24-
const scripts = document.getElementsByTagName('script');
25-
const index = scripts.length - 1;
26-
const thisScript = scripts[index];
27-
return thisScript.src.replace(/^.*:\/\/[^/]*(.*\/)(assets|js)\/[^/]+.js(\?.*)?$/, '$1');
24+
const thisScriptSrc =
25+
Array.from(document.getElementsByTagName('script'))
26+
.pop()
27+
.getAttribute('src');
28+
return thisScriptSrc
29+
.replace(/^(?:[a-z]*:\/\/[^/]*)?(.*\/)(assets|js)\/[^/]+.js(\?.*)?$/, '$1');
2830
})();
2931

3032
$(document).ready(function() {
@@ -338,7 +340,15 @@ var Search = {
338340
return;
339341
}
340342
(async () => {
341-
Search.pagefind = await import(`${baseURLPrefix}pagefind/pagefind.js`);
343+
const pagefindURL =
344+
`${baseURLPrefix}pagefind/pagefind.js`
345+
// adjust the `baseURLPrefix` if it is relative: the `import`
346+
// is relative to the _script URL_ here, which is in /js/.
347+
// That is different from other uses of `baseURLPrefix`, which
348+
// replace `href` and `src` attributes which are relative to the
349+
// page itself that is outside of /js/.
350+
.replace(/^\.\//, '../')
351+
Search.pagefind = await import(pagefindURL);
342352
const options = {
343353
ranking: {
344354
pageLength: 0.1, // boost longer pages

script/serve-public.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ const handler = (request, response) => {
4949
} catch(e) {
5050
console.log(`Could not read ${filename}`);
5151
response.writeHead(404, {'Content-Type': 'text/html'});
52-
fs.createReadStream(path.join(basePath, '404.html')).pipe(response);
52+
// insert <base> to fix styling
53+
const html = fs.readFileSync(path.join(basePath, '404.html'), 'utf-8')
54+
.replace(/<head>/, '\n <base href="/" />')
55+
response.write(html)
56+
response.end()
5357
return;
5458
}
5559
};

0 commit comments

Comments
 (0)