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

front_matterify.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: cbf0fffd515c56fdea4e6f030b6a4b6f78ae4ac6 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import jsYaml from 'js-yaml';

const NEW_LINE = '\n';

const hasMatter = (firstThreeChars, fourthChar) => {
  const isYamlDelimiter = firstThreeChars === '---';
  const isFourthCharNewline = fourthChar === NEW_LINE;
  return isYamlDelimiter && isFourthCharNewline;
};

export const frontMatterify = source => {
  let index = 3;
  let offset;
  const delimiter = source.slice(0, index);
  const type = 'yaml';
  const NO_FRONTMATTER = {
    source,
    matter: null,
    spacing: null,
    content: source,
    delimiter: null,
    type: null,
  };

  if (!hasMatter(delimiter, source.charAt(index))) {
    return NO_FRONTMATTER;
  }

  offset = source.indexOf(delimiter, index);

  // Finds the end delimiter that starts at a new line
  while (offset !== -1 && source.charAt(offset - 1) !== NEW_LINE) {
    index = offset + delimiter.length;
    offset = source.indexOf(delimiter, index);
  }

  if (offset === -1) {
    return NO_FRONTMATTER;
  }

  const matterStr = source.slice(index, offset);
  const matter = jsYaml.safeLoad(matterStr);

  let content = source.slice(offset + delimiter.length);
  let spacing = '';
  let idx = 0;
  while (content.charAt(idx).match(/(\s|\n)/)) {
    spacing += content.charAt(idx);
    idx += 1;
  }
  content = content.replace(spacing, '');

  return {
    source,
    matter,
    spacing,
    content,
    delimiter,
    type,
  };
};

export const stringify = ({ matter, spacing, content, delimiter }, newMatter) => {
  const matterObj = newMatter || matter;

  if (!matterObj) {
    return content;
  }

  const header = `${delimiter}${NEW_LINE}${jsYaml.safeDump(matterObj)}${delimiter}`;
  const body = `${spacing}${content}`;
  return `${header}${body}`;
};