gladevise / remark-link-card

remark-link-card-gladevise.vercel.app
MIT License
26 stars 7 forks source link

I would like an option to automatically add target="_blank" to the a tag. #15

Open satoru2727 opened 10 months ago

satoru2727 commented 10 months ago

Hi there, I'm just wondering if you have any suggestions for me. Your plugin is crazy awesome. I have one request to make this great plugin better. I would like an option to automatically add target="_blank" to the a tag.

gladevise commented 6 months ago

Sorry for the delayed reply.

I think it's great that there is an option to change the target element as you say. However, to go into more detail, I think it would be better to open internal links without the target element (i.e. target="_self"), and external links with target="_blank".

However, I'm not sure if it's appropriate to do this attribute conversion within the remark plugin. The same behavior could be achieved by writing an MDX component that distinguishes whether a link is internal or external and modifies the target element.

I can't judge which implementation is better at this point. I would appreciate your opinion.

laddge commented 2 months ago

Thank you for making such an awesome plugin. I was thinking the same thing, but how about resolving it on the rehype side? For example, this can be resolved by combining rehype-raw and rehype-external-links as follows:

import {unified} from 'unified'
import remarkParse from 'remark-parse'
import rlc from 'remark-link-card'
import remarkRehype from 'remark-rehype'
import rehypeRaw from 'rehype-raw'
import rehypeExternalLinks from 'rehype-external-links'
import rehypeStringify from 'rehype-stringify'

const html = await unified()
  .use(remarkParse)
  .use(rlc)
  .use(remarkRehype, { allowDangerousHtml: true })
  .use(rehypeRaw)
  .use(rehypeExternalLinks, { target: '_blank' })                 
  .use(rehypeStringify)
  .process('https://github.com/')

console.log(html.toString())

Output:

<a class="rlc-container" href="https://github.com/" rel="nofollow" target="_blank">
  <div class="rlc-info">
    <div class="rlc-title">GitHub: Let’s build from here</div>
    <div class="rlc-description">GitHub is where over 100 million developers shape the future of software, together. Contribute to the open source community, manage your Git repositories, review code like a pro, track bugs and fea...</div>
    <div class="rlc-url-container">
      <img class="rlc-favicon" src="https://www.google.com/s2/favicons?domain=github.com" alt="GitHub: Let’s build from here favicon" width="16" height="16">
      <span class="rlc-url">https://github.com/</span>
    </div>
  </div>
  <div class="rlc-image-container">
    <img class="rlc-image" src="https://github.githubassets.com/assets/campaign-social-031d6161fa10.png" alt="GitHub: Let’s build from here">
  </div>
</a>