Welcome to mirror list, hosted at ThFree Co, Russian Federation.

parse_source_file.js « services « static_site_editor « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f32c693411fe615fbee20d6173f11b5d109ddf4b (plain)
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
const parseSourceFile = raw => {
  const frontMatterRegex = /(^---$[\s\S]*?^---$)/m;
  const preGroupedRegex = /([\s\S]*?)(^---$[\s\S]*?^---$)(\s*)([\s\S]*)/m; // preFrontMatter, frontMatter, spacing, and content
  let initial;
  let editable;

  const hasFrontMatter = source => frontMatterRegex.test(source);

  const buildPayload = (source, header, spacing, body) => {
    return { raw: source, header, spacing, body };
  };

  const parse = source => {
    if (hasFrontMatter(source)) {
      const match = source.match(preGroupedRegex);
      const [, preFrontMatter, frontMatter, spacing, content] = match;
      const header = preFrontMatter + frontMatter;

      return buildPayload(source, header, spacing, content);
    }

    return buildPayload(source, '', '', source);
  };

  const computedRaw = () => `${editable.header}${editable.spacing}${editable.body}`;

  const syncBody = () => {
    /*
    We re-parse as markdown editing could have added non-body changes (preFrontMatter, frontMatter, or spacing).
    Re-parsing additionally gets us the desired body that was extracted from the mutated editable.raw
    Additionally we intentionally mutate the existing editable's key values as opposed to reassigning the object itself so consumers of the potentially reactive property stay in sync.
    */
    Object.assign(editable, parse(editable.raw));
  };

  const syncRaw = () => {
    editable.raw = computedRaw();
  };

  const isModifiedRaw = () => initial.raw !== editable.raw;
  const isModifiedBody = () => initial.raw !== computedRaw();

  initial = parse(raw);
  editable = parse(raw);

  return {
    editable,
    isModifiedRaw,
    isModifiedBody,
    syncRaw,
    syncBody,
  };
};

export default parseSourceFile;