From cdc8c1faed4d86da67e1019f6a629f73583590ad Mon Sep 17 00:00:00 2001 From: Robert Kaussow Date: Sun, 16 Jan 2022 16:03:31 +0100 Subject: [PATCH] fix: fix asset loading on subfolder deployments (#287) --- layouts/partials/search.html | 1 + src/js/search.js | 26 +++++++++++++++++++++++++- webpack.config.js | 1 - 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/layouts/partials/search.html b/layouts/partials/search.html index dad65c4..352d3f3 100644 --- a/layouts/partials/search.html +++ b/layouts/partials/search.html @@ -8,6 +8,7 @@ placeholder="Search..." aria-label="Search" maxlength="64" + data-site-base-url="{{ .Site.BaseURL }}" /> diff --git a/src/js/search.js b/src/js/search.js index 6e93058..221ea04 100644 --- a/src/js/search.js +++ b/src/js/search.js @@ -5,6 +5,7 @@ const { Validator } = require("@cfworker/json-schema") document.addEventListener("DOMContentLoaded", function (event) { const input = document.querySelector("#gdoc-search-input") const results = document.querySelector("#gdoc-search-results") + const basePath = urlPath(input ? input.dataset.siteBaseUrl : "") const configSchema = { type: "object", @@ -23,7 +24,9 @@ document.addEventListener("DOMContentLoaded", function (event) { } const validator = new Validator(configSchema) - getJson("/search/config.min.json", function (searchConfig) { + if (!input) return + + getJson(combineURLs(basePath, "/search/config.min.json"), function (searchConfig) { const validationResult = validator.validate(searchConfig) if (!validationResult.valid) @@ -193,3 +196,24 @@ function flattenHits(results) { return items } + +function urlPath(rawURL) { + var parser = document.createElement("a") + parser.href = rawURL + + return parser.pathname +} + +/** + * Part of [axios](https://github.com/axios/axios/blob/master/lib/helpers/combineURLs.js). + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") + : baseURL +} diff --git a/webpack.config.js b/webpack.config.js index b5f048c..56cc150 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -27,7 +27,6 @@ var config = { filename: "js/[name]-[contenthash:8].bundle.min.js", chunkFilename: "js/[name]-[contenthash:8].chunk.min.js", path: path.join(__dirname, "static"), - publicPath: "/", clean: true }, watchOptions: {