electronjs.org-old icon indicating copy to clipboard operation
electronjs.org-old copied to clipboard

autolink fully-qualified URLs

Open zeke opened this issue 8 years ago • 6 comments

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 avatar Jul 16 '17 04:07 zeke

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?

zeke avatar Nov 16 '17 21:11 zeke

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>

wooorm avatar Nov 16 '17 21:11 wooorm

That was fast! Care to package it up?

zeke avatar Nov 16 '17 21:11 zeke

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!

wooorm avatar Nov 16 '17 21:11 wooorm

Sure. Is there a remark org?

zeke avatar Nov 17 '17 00:11 zeke

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

wooorm avatar Nov 17 '17 00:11 wooorm