npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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

Readme

rehype-link-processor

rehype plugin to process links to

  • add custom css classes
  • detect external, download, same-page links
  • set attributes like rel or target
  • 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 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: or https:
    • 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>

  • download

    looks for download links matching when one of:

    • the url starts with http: or https: and the path ends with .<ext> where ext 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 or true 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>

  • 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>

  • same-page

    detect navigation within the same page, aka fragment navigation

    • checks if the url starts with #

    the resulting a will have the attributes

    • class = "same-page"

    Markdown: [Chapter 2](#chapter-2)

    HTML: <a href="#chapter-2" class="same-page">Chapter 2<a>

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.

License

MIT © Giuseppe La Torre