the-mvm / the-mvm.github.io

The Minimum Viable Model website and Jekyll theme.
https://the-mvm.github.io
GNU General Public License v3.0
87 stars 398 forks source link

IPFS relative paths not working #7

Closed amaynez closed 3 years ago

amaynez commented 3 years ago

https://ipfs.fleek.co/ipfs/QmSgnSv88oTcXg3tzPc3ZyakL4ofgRJVaTYx2nD2rp4aHu/

amaynez commented 3 years ago

The nature of IPFS makes short absolute paths for website resources (like images, css and javascript files) inoperative; the easiest fix for this is to use relative paths, however the same relative path that works for the root directory (i.e. /index.html) does not work for links inside directories (i.e. /tags/), and since the site is static, while generating it, one must make the distinction between the different directory levels for the page to be rendered correctly. At first I tried a simple (but brute force solution):

# determine the level of the current file
{% assign lvl = page.url | append:'X' | split:'/' | size %}
# create the relative base (i.e. "../")
{% capture relativebase %}{% for i in (3..lvl) %}../{% endfor %}{% endcapture %}
{% if relativebase == '' %}
    {% assign relativebase = './' %}
{% endif %}
...
# Eliminate unecesary double backslashes
{% capture post_url %}{{ relativebase }}{{ post.url }}{% endcapture %}
{% assign post_url = post_url | replace: "//", "/" %}

This jekyll/liquid code was executed in every page (or include) that needed to reference a resource hosted in the same server.

But this fix did not work for the search function, because it relies on a search.json file (also generated programmatically to be served as a static file), therefore when generating this file one either uses the relative path for the root directory or for a nested directory, thus the search results will only link correctly the corresponding pages if the page where the user searched for something is in the corresponding scope.

So the final solution was to make the whole site flat, meaning to live in a single directory. All pages and posts will live under the root directory, and by doing so, I can control how to address the relative paths for resources.

This solution covered almost all cases except for the 404 file when pointing to a file not found within a subdirectory, which of course brakes all relative paths, for this a javascript function was written to:

  1. check the directory level of the file not found
  2. construct a relative base, for example "../../"
  3. replace the relative base with the new one in all document elements required to render the page correctly. code here

Infinite Scroll and Search javascripts had to be updated as well.