Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pass current file as third argument? #2

Open
felixroos opened this issue Feb 12, 2023 · 1 comment
Open

pass current file as third argument? #2

felixroos opened this issue Feb 12, 2023 · 1 comment

Comments

@felixroos
Copy link

felixroos commented Feb 12, 2023

Hello, and thanks for creating this plugin! It was exactly what I needed. I found it through this comment
There was a little workaround required for my use case, and I thought it could be generally helpful.

I found myself needing to rewrite relative anchors to absolute ones, which only works when knowing the current path.
This is how I do it:

const base = '/';
function absoluteAnchors() {
  return (tree, file) => {
    const chunks = file.history[0].split('/src/pages/'); // file.history[0] is the file path
    const path = chunks[chunks.length - 1].slice(0, -4); // only path inside src/pages, without .mdx
    return rehypeUrls((url) => {
      if (!url.href.startsWith('#')) {
        return;
      }
      const absoluteUrl = base + path + url.href;
      // console.log(url.href + ' -> ', absoluteUrl);
      return absoluteUrl;
    })(tree);
  };
}

(I needed this because I am using a base href, which results in all relative anchor links pointing to the root path instead of the current page)

TLDR It would be handy if the function passed to the plugin would also pass a third parameter the current file, like

rehypeUrls((url, node, file) => /* ..*/);

I could also send a PR if you like

@brechtcs
Copy link
Owner

Sorry, this slipped through the cracks because I don't check Github as often as I used to.

It's been a while since I worked on any unified plugins, so the API is a bit hazy for me right now. If you already know how to implement it yourself though I'd be more than happy to accept a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants