All files index.ts

100% Statements 17/17
82.35% Branches 14/17
100% Functions 4/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                                                                                    1x 8x 8x 8x 28x           14x 14x 56x 19x 19x 19x 9x 9x   10x 10x 10x       37x                
import type { Plugin, Pluggable } from 'unified';
import type { Root, RootContent, Literal } from 'hast';
import { visit } from 'unist-util-visit';
 
/**
 * Raw string of HTML embedded into HTML AST.
 */
export interface Raw extends Literal {
  /**
   * Node type.
   */
  type: 'raw'
}
 
// Register nodes in content.
declare module 'hast' {
  interface RootContentMap {
    /**
     * Raw string of HTML embedded into HTML AST.
     */
    raw: Raw
  }
  interface ElementContentMap {
    /**
     * Raw string of HTML embedded into HTML AST.
     */
    raw: Raw
  }
}
 
 
export type RehypeIgnoreOptions = {
  /**
   *  Character to use for opening delimiter, by default `rehype:ignore:start`
   */
  openDelimiter?: string;
  /**
   * Character to use for closing delimiter, by default `rehype:ignore:end`
   */
  closeDelimiter?: string;
}
 
const rehypeIgnore: Plugin<[RehypeIgnoreOptions?], Root> = (options = {}) => {
  const { openDelimiter = 'rehype:ignore:start', closeDelimiter = 'rehype:ignore:end' } = options;
  return (tree) => {
    visit(tree, (node: Root | RootContent, index, parent) => {
      if (node.type === 'element' || node.type === 'root') {
        // const start = node.children.findIndex((item) => item.type === 'comment' && item.value === openDelimiter);
        // const end = node.children.findIndex((item) => item.type === 'comment' && item.value === closeDelimiter);
        // if (start > -1 && end > -1) {
        //   node.children = node.children.filter((_, idx) => idx < start || idx > end);
        // }
        let start = false;
        node.children = node.children.filter((item) => {
          if (item.type === 'raw' || item.type === 'comment') {
            let str =  (item.value || '').trim();
            str = str.replace(/^<!--(.*?)-->/, '$1')
            if (str === openDelimiter) {
                start = true;
                return false;
            }
            Eif (str === closeDelimiter) {
                start = false;
                return false;
            }
          }
          
          return !start;
        })
      }
    });
  }
}
 
export default rehypeIgnore;