CloudCannon / pagefind

Static low-bandwidth search at scale
https://pagefind.app
MIT License
3.24k stars 99 forks source link

Handle relative image URLs in the Pagefind UI #530

Open bglw opened 7 months ago

bglw commented 7 months ago

Discussed in https://github.com/CloudCannon/pagefind/discussions/529

Originally posted by **kenmorse** December 19, 2023 So for a page bundle, you might have something like this in your source: ![alt text](image.png) instead of a full path to the image like this: ![alt text](/full/path/to/image.png) This seems to be a problem for Pagefind though, as the search results panel won't have a full path to the image.
bglw commented 7 months ago

Workaround from discussion:

new PagefindUI({
    element: "#search",
    showSubResults: true,
    showImages: true,
    processResult: function (result) {
        if (result?.meta?.image) {
            let resultBase = new URL(result.url, window.location);
            let remappedImage = new URL(result.meta.image, resultBase);
            if (remappedImage.hostname !== window.location.hostname) {
                result.meta.image = remappedImage.toString();
            } else {
                result.meta.image = remappedImage.pathname;
            }
        }
    }
});

This can pretty much be rolled into the Default (and Modular) UI handling verbatim. I'm wary of adding it any earlier in the flow, as someone might be relying on the indexing and JS API to not mutate metadata.