summaryrefslogtreecommitdiff
path: root/packages/astro-parser/src/parse/state/codefence.ts
blob: 72867867c0b4777f62ab0b3134f11322c11d760d (plain) (blame)
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
// @ts-nocheck
import { Parser } from '../index.js';

export default function codefence(parser: Parser) {
  const start = parser.index;
  const open = parser.match_regex(/[`~]{3,}/);
  parser.index += open!.length;

  let raw = open + '';

  while (parser.index < parser.template.length && !parser.match(open)) {
    raw += parser.template[parser.index++];
  }

  parser.eat(open, true);
  raw += open;
  const trailingWhitespace = parser.read_until(/\S/);
  const { metadata, data } = extractCodeFence(raw);

  const node = {
    start,
    end: parser.index,
    type: 'CodeFence',
    raw: `${raw}` + trailingWhitespace,
    metadata,
    data,
  };

  parser.current().children.push(node);
}

/** Extract attributes on first line */
function extractCodeFence(str: string) {
  const [_, leadingLine] = str.match(/(^[^\n]*\r?\n)/m) ?? ['', ''];
  const metadata = leadingLine.trim();
  const data = str.slice(leadingLine.length);
  return { metadata, data };
}