summaryrefslogtreecommitdiff
path: root/app.js
blob: f335dba18e9277d360361273699aeecfe8ece6a2 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
(() => {
  let state = {};
  let isLoading = 0;
  let loading = (val) => {
    isLoading = val;
    loader.$cls(isLoading ? "" : "hide");
  }
  loader.$click(() => loading(0));

  let error = null;
  let setError = (err) => {
    error = String(err);
    app.reload();
  }
  window.onerror = (message) => {
    setError(message);
  };
  window.onunhandledrejection = (e) => {
    setError(e.reason);
  };
  let parsetxt = (data) => fromEntries(data.split("\n").map(x=>x.trim()).filter(x=>x).map(x=>x.split("=")));
  let buildtxt = (data) => entries(data).map(([k,v])=>`${k}=${v}\n`).join("");
  let resptext = r => {
    if (!r.ok){
      throw new Error(r.statusText);
    }
    return r.text();
  };
  let getconfig = () => fetch("/cgi-bin/getconfig").then(resptext).then(x => parsetxt(x));
  let cmd = (body) => fetch("/cgi-bin/cmd",{method:"POST",body}).then(resptext);
  let setconfig = (data) => {
    loading(1);
    cmd(buildtxt(data)+"save\n")
      .finally(() => loading(0))
  };
  let loadconfig = () => {
    loading(1);
    getconfig("/cgi-bin/getconfig")
      .then(x => {
        state = {...state, ...x};
        app.reload();
      })
      .finally(() => loading(0));
  }
  let reboot = (data) => {
    let ok = 0;
    loading(1);
    cmd("reboot\n")
      .then(() => {
        ok = 1;
      })
      .finally(() => {
        setTimeout(() => {
          loading(0);
          app.reload();
        }, ok?10000:0);
      })
  };

  function CErr(text) {
    let el = div(
      div("✖").$cls("close").$click(errClose),
      span("⚠ "),
      text,
    ).$cls("err");
    function errClose() {
      error = null;
      el.remove();
    };
    return el;
  }
  function CNav(navs) {
    return (h) => nav(
      labelfor("showmenu", span("☰"), " Menu"),
      input("checkbox").$attr("id", "showmenu"),
      ...navs.map(([href,txt]) => ahref(href,txt).$cls(href.substring(1)===h?"active":""))
    );
  }
  function CRouter(routes) {
    return (h) => {
      let p = h.substr(1) || "/";
      let r = p in routes ? p : "";
      return routes[r]();
    }
  }

  function CSettingInput(f) {
    let inp = input("text")
      .$attr("id","form__"+f.id)
      .$attr("name",f.id)
      .$value(state[f.id]??null)
      .$change2state(state, f.id);
    if (f.required) {
      inp.$attr("required","required");
    }
    if (f.pattern) {
      inp.$attr("pattern", f.pattern);
    }
    if (f.invalidmsg) {
      inp.oninvalid = () => inp.setCustomValidity(f.invalidmsg);
    }
    inp.$attr("placeholder", f.hint??"");
    return tr(
      td(labelfor(inp.id, f.title)).$cls("title"),
      td(inp),
    );
  }

  function CSettings(section) {
    let s = config.sections[section];
    let f = form(
      table(...s.fields.map(x => CSettingInput(x))),
      input("submit").$value("Save")
    );
    f.onsubmit = (e) => {
      e.preventDefault();
      setconfig(fromEntries(new FormData(f)));
    }
    return div(
      h1(s.title),
      f,
    )
  }
  let navbar = CNav([
    ["/#", "Home"],
    ...entries(config.sections).map(([id, x]) => [`/#/${id}`, x.title]),
  ]);
  let router = CRouter({
    "/": () => div(
      h1("Information"),
      table(
        tr(td("Device:").$cls("title"), td(config.device)),
        tr(td("Software Version:").$cls("title"), td(config.swVersion)),
        tr(td("Hardware Version:").$cls("title"), td(config.hwVersion)),
      ),
      h1("Controls"),
      p(
        button("Reboot").$click(reboot),
      ).$cls("center"),
    ),
    ...fromEntries(entries(config.sections).map(([id, _]) => [`/${id}`, () => CSettings(id)])),
    "": () => div(
      h1("Not Found"),
      p("The requested page is not available.")
    ),
  });
  let CApp = (h) => {
    loading(isLoading);
    return [
      div(error && CErr(String(error))),
      main(
        navbar(h),
        section(router(h))
      ),
    ];
  };

  mount(app, CApp);
  loadconfig();
})();