remarkable icon indicating copy to clipboard operation
remarkable copied to clipboard

Add icon to external links using custom plugin

Open farskid opened this issue 5 years ago • 0 comments

I'm trying to write a custom remarkable plugin to add an icon to all links that are external. The approach I took is to mutate the tokens array passed to the renderer rule by pushing a new token of type htmltag right after the token at link_open, but it appears to be failing.

Is this even possible in the scope of a plugin?


const externalLinkIcon = `<svg>...</svg>`;

function ExternalLinkPlugin(domain) {
  if (!domain) {
    throw Error("missing domain in externalLink plugin");
  }

  return function (remarkable) {
    const originalOpen = remarkable.renderer.rules.link_open;

    remarkable.renderer.rules.link_open = function (tokens, idx, options = {}) {
      const link = tokens[idx];
      const isExternal = isExternalLink(link.href, domain);

      if (isExternal) {
		
        tokens = tokens
          .slice(0, idx + 1)
          .concat({ type: "htmltag", content: externalLinkIcon, level: 1 })
          .concat(tokens.slice(idx + 2));

        return `<a href="${escapeHtml(
          link.href
        )}" title="${escapeHtml(link.title || link.href)}">`;
      }

      return originalOpen(tokens, idx, options);
    };
  };
};

farskid avatar Apr 17 '20 00:04 farskid