markdown icon indicating copy to clipboard operation
markdown copied to clipboard

Plain-text "summary" RDMD export method.

Open rafegoldberg opened this issue 4 years ago • 0 comments

Let's add a previewText export method to the RDMD engine to loop through the AST and remove any non-paragraph nodes. Then we can transform that to plain-text, and do the truncation in the top-level method. So it'd look something like:

import remarkToPlainText from 'remark-plain-text';
import visit from 'unist-util-flatmap';

const pTagFilter = node => node.type==='paragraph' ? node : null);
//^Our custom p tag filter "plugin"; this is all
// pseudo code, but it works something like this!

export function previewText(text, truncateAt, opts = {}) {
  if (!text) return null;
  [text, opts] = setup(text, opts);

  text = processor(opts)
    .use(tree => visit(tree, pTagFilter))
    .use(remarkToPlainText)
    .use(rehypeStringify)
    .processSync(text)
    .contents;

  return text.slice(0, truncateAt).trim() + '...';
}

rafegoldberg avatar Apr 28 '20 19:04 rafegoldberg