rehype-link-processor
v1.0.4
Published
rehype plugin to process links adding custom css class or attributes used by external or download links
Downloads
81
Maintainers
Readme
rehype-link-processor
rehype plugin to process links to
- add custom css classes
- detect external, download, same-page links
- set attributes like
rel
ortarget
- add custom attributes
Why
This package helps to decorate links usually in a markdown document where no extra attribute can be set.
Common scenarios:
- set external links to open in a new page
- decorate a link with a css class to style it, for example adding an icon next to it
- detect external links even when the url don't start with http(s)://
- detect download links
- identify links under some condition to add custom attributes
When you write links in markdown, you're limited with just the url, text and title. You cannot add custom attributes, for example a css class to style that specific link as you want.
This package helps to process and transform links.
Installation
This is package is module. So an ESM compatible runtime is required (node 14+, deno, ...)
npm i rehype-link-processor
# or
pnpm add rehype-link-processor
# or
yarn add rehype-link-processor
Integration
Within a unified
pipeline
Include rehype-link-processor in the pipeline:
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import rehypeLinkProcessor from "rehype-link-processor";
const file = await unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeLinkProcessor)
.process("...")
Within a mdx
compilation
Include rehype-link-processor in the rehype plugins:
import {compile} from "@mdx-js/mdx";
import rehypeLinkProcessor from "rehype-link-processor";
const file = '[download:Get the pdf](/assets/article.pdf)';
await compile(file, { rehypePlugins: [rehypeLinkProcessor] });
In an Astro website
Include rehype-link-processor as markdown rehype plugin in the astro.config.ts
:
//file: astro.config.ts
import { defineConfig } from "astro/config";
import rehypeLinkProcessor from "rehype-link-processor";
export default defineConfig({
markdown: {
rehypePlugins: [rehypeLinkProcessor()]
}
);
Configuration
The processor works with rules. If a rule matches, the action is applied (the link is transformed), and the processing ends.
So the rule order is important, as the first match wins.
The rules are set via the options argument:
rehypeLinkProcessor({
rules: [
// add rules here
]
})
This package provides some builtin rules covering common scenarios. You can also add custom rules to fit you needs.
There are three rule types:
- Builtin: identified by a name
- Match rule: defined by an
object
- Transform rule: defined by a
function
Builtin rules
All builtin rules are enabled by default.
Builtin rules can be disabled with useBuiltin
set to false
.
rehypeLinkProcessor({
useBuiltin: false
})
When you disable builtin rules, you can add the ones you like manually:
rehypeLinkProcessor({
rules: [
"external" // <-- enable the external link rule
]
})
or your use the helper R
when you need a configuration:
rehypeLinkProcessor({
rules: [
R.download({
skipExtension: ["html"] // exclude html to be considered a download
})
]
})
The builtin rules are:
external
looks for external links matching when one of:
- the url starts with
http:
orhttps
: - the url starts with the prefix
external:
- the text starts with the prefix
external:
if matched, the resulting
a
will have the attributes:class
= "external"target
= "_blank"rel
= "nofollow noopener"
Markdown:
[Github](https://github.com)
HTML:
<a href="https://github.com" class="external" target="_blank" rel="nofollow noopener">Github<a>
Markdown:
[external:Discussion on Github](/discussion)
HTML:
<a href="/discussion" class="external" target="_blank" rel="nofollow noopener">Discussion on Github</a>
- the url starts with
download
looks for download links matching when one of:
- the url starts with
http:
orhttps:
and the path ends with.<ext>
whereext
is [1-4] chars long (excluded:html
,htm
,md
,mdx
) - the url starts with the prefix
download:
- the text starts with the prefix
download:
if matched, the resulting
a
will have the attributes:class
= "download"download
= the filename extracted ortrue
when detected by the prefix
Markdown:
[Download the pdf](/assets/my-article.pdf)
HTML:
<a download="my-article.pd" href="/assets/my-article.pdf" class="download">Download the pdf<a>
Markdown:
[download:Get the Archive](/directory?format=zip)
HTML:
<a download href="/directory?format=zip" class="download">Get the Archive</a>
- the url starts with
email
looks for email links matching when one of:
- the url starts with
mailto:
- the url starts with the prefix
email:
- the text starts with the prefix
email:
if matched, the resulting
a
will have the attributes:class
= "email"
Markdown:
[Contact us]([email protected])
HTML:
<a href="mailto:[email protected]" class="email">Contact us<a>
Markdown:
[email:Send us a mail]([email protected])
HTML:
<a href="mailto:[email protected]" class="email">Send us a mail<a>
- the url starts with
same-page
detect navigation within the same page, aka fragment navigation
- checks if the url starts with
#
the resulting
a
will have the attributesclass
= "same-page"
Markdown:
[Chapter 2](#chapter-2)
HTML:
<a href="#chapter-2" class="same-page">Chapter 2<a>
- checks if the url starts with
Match rule
A match rule, works in two steps:
- the match: where you identify the link you want to process
- the action: where you specify what transformations you want to apply
rules: [
{
match: link => link.href.startWith("mailto:"),
action: { className: "email" }
}
]
If the match
returns a falsy value (false
, undefined
, ...). The rule is skipped.
You can specify multiple actions in an Array.
You can use the A
helper witch provides common actions.
// rule to correct GiThuB link casing
rules: [
{
match: link => link.text?.toLowerCase() === "github"
action: [
// add the class: the link can have preexisting class
A.mergeClass("brand-link"),
// another syntax for { text: "GitHub" }
A.set("text", "GitHub")
]
}
]
The match function can also return an object. It will be assigned over the link, overwriting the common fields.
It's useful in a scenario where you want to apply a transformation right away in the matching step.
rules: [
{
match: link => {
if(link.href.startsWith("http:")){
return { href: link.href.replace("http:", "https:") };
}
},
action: [
A.set("target", "_blank"),
]
}
]
Transform rule
With a transform rule you can analyze any like directly. The transform rule provides a function
based syntax to process links.
With the link as input, a transform rule can return:
- a falsy value, to skip the rule
- an object, to apply the patch: the object fields overwrite the link ones
You can add a transform rule like any other rule:
{
rules: [
link => {
if (link.href?.includes("github.com")) {
return { title: "GitHub: Where this code lives" };
}
}
]
}
Types
This package is built in typescript so it has full typings support.