electron / electronjs.org-old

Electron website
https://electronjs.org
MIT License
1.61k stars 651 forks source link

autolink fully-qualified URLs #760

Closed zeke closed 1 year ago

zeke commented 7 years ago

URLs in text content should automatically be turned into links, where appropriate.

For extra readability, it would be nice to display a schemeless URL for the link text.

Input:

I love https://electron.atom.io

Output:

<p>
  I love <a href="https://electron.atom.io">electron.atom.io</a>
</p>

See https://github.com/electron/electron/pull/9968

zeke commented 7 years ago

If we still want to do this, the place to implement it would be in hubdown, the library that does our markdown parsing now: https://github.com/zeke/hubdown

Did a little searching on https://github.com/wooorm/remark/blob/master/doc/plugins.md but didn't see a remark plugin for this.

@wooorm do you know of one?

wooorm commented 7 years ago

Nope, not supported yet, but interesting, so I whipped this v0.0.1 up:

var url = require('url');
var visit = require('unist-util-visit');
var toString = require('mdast-util-to-string');
var report = require('vfile-reporter');
var unified = require('unified');
var markdown = require('remark-parse');
var remark2rehype = require('remark-rehype');
var html = require('rehype-stringify');

var doc = [
  'I love https://electron.atom.io',
  'I love http://test.example.com:3000/users/search',
  'I love [https://electron.atom.io](https://some.other.url)'
].join('\n');

unified()
  .use(markdown)
  .use(prettyLinks)
  .use(remark2rehype)
  .use(html)
  .process(doc, function (err, file) {
    console.error(report(err || file));
    console.log(String(file));
  });

function prettyLinks() {
  return transformer;
}
function transformer(tree) {
  visit(tree, 'link', prettify);
}
function prettify(node) {
  var value = toString(node);
  var schema;

  if (node.url === value) {
    schema = url.parse(node.url);
    schema.protocol = '';
    schema.slashes = false;

    if (schema.pathname === '/') {
      schema.pathname = '';
    }

    node.children = [{
      type: 'text',
      value: url.format(schema)
    }];
  }
}

Yields:

no issues found
<p>I love <a href="https://electron.atom.io">electron.atom.io</a>
I love <a href="http://test.example.com:3000/users/search">test.example.com:3000/users/search</a>
I love <a href="https://some.other.url">https://electron.atom.io</a></p>
zeke commented 7 years ago

That was fast! Care to package it up?

wooorm commented 7 years ago

I was hoping you would! You’d just need to module.exports prettyLinks, and it needs some tests (I’m sure it isn’t perfect around the url part).

Is that okay? Let me know if I can help!

zeke commented 7 years ago

Sure. Is there a remark org?

wooorm commented 7 years ago

Soon, in a few days I think! Could you add me? I’ll make sure to migrate it when it’s there!