mkdocs / mkdocs-redirects

Open source plugin for Mkdocs page redirects
MIT License
181 stars 28 forks source link

Feature request: Heading-based redirects. #69

Open rudolfbyker opened 4 days ago

rudolfbyker commented 4 days ago

I use a custom scraper that runs in my CI to detect when I break any URLs that might exist in search engines, or that have been shared by users. Then I use mkdocs-redirects to fix those links before deploying the next version of my docs. This works well, until I have to split a page into two separate pages.

Since we're doing client-side redirects anyway, could we support heading-based redirects? Heading-based redirects are not possible in the context of SSR, because the anchor (the #foo part of the URL) is not sent to the server. But the browser knows what it is, so with a little bit of JS, we can easily detect which heading is desired, and redirect based on that.

Currently, the following script is generated:

var anchor=window.location.hash.substr(1);
location.href="destination.html"+(anchor?"#"+anchor:"")

This could easily be expanded with a simple switch statement:

var anchor=window.location.hash.substr(1);
switch (anchor) {
  case 'heading1':
    location.href="page1.html"
    break;
  case 'heading2':
    location.href="page2.html"
    break;
  default:
    location.href="page3.html"
}

The mkdocs.yaml config could look something like this:

plugins:
  - redirects:
      redirect_maps:
        "original.md#heading1": page1.md
        "original.md#heading2": page2.md
        "original.md": page3.md

or, if you don't like the flat structure:

plugins:
  - redirects:
      redirect_maps:
        "original.md":
          "#heading1": page1.md
          "#heading2": page2.md
          "default": page3.md

or, if you want to keep the door open for other types of redirects (which I can't conceive of now):

plugins:
  - redirects:
      redirect_maps:
        "original.md":
          "anchors":
            "heading1": page1.md
            "heading2": page2.md
          "default": page3.md
pawamoy commented 4 days ago

Thanks for the request @rudolfbyker. That would be a nice addition, similar to #64.

I worry that users will expect such redirections to work in existing pages. But the plugin would have to modify the existing page to add the relevant headings and JS code, which is not trivial. This could definitely be documented as a limitation though.

The flat structure would mean the plugin must now iterate on all redirections in a first step, to reconcile page redirects and page+heading redirects.

rudolfbyker commented 4 days ago

Sounds more complicated to implement than I anticipated.

pawamoy commented 3 days ago

Sorry, not sure what I was thinking, but surely the plugin wouldn't have to add any heading, just JS code, to redirect depending on the anchor in the URL. So, a bit less complicated :)