summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/static_site_editor/services/parse_source_file.js
blob: 39126eb7bcc19219b6ce044cab85f10878af981f (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
import { frontMatterify, stringify } from './front_matterify';

const parseSourceFile = raw => {
  let editable;

  const syncContent = (newVal, isBody) => {
    if (isBody) {
      editable.content = newVal;
    } else {
      try {
        editable = frontMatterify(newVal);
        editable.isMatterValid = true;
      } catch (e) {
        editable.isMatterValid = false;
      }
    }
  };

  const content = (isBody = false) => (isBody ? editable.content : stringify(editable));

  const matter = () => editable.matter;

  const syncMatter = settings => {
    editable.matter = settings;
  };

  const isModified = () => stringify(editable) !== raw;

  const hasMatter = () => editable.hasMatter;

  const isMatterValid = () => editable.isMatterValid;

  syncContent(raw);

  return {
    matter,
    isMatterValid,
    syncMatter,
    content,
    syncContent,
    isModified,
    hasMatter,
  };
};

export default parseSourceFile;