generated from lindsaykwardell/vite-elm-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
94 lines (82 loc) · 2.98 KB
/
index.ts
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
// use indexedDB for storage
import * as db from "idb-keyval";
import CodeMirror from "codemirror";
import "codemirror/theme/material.css";
import "codemirror/lib/codemirror.css";
import "./src/codemirror/pseudolisp";
import "codemirror/addon/edit/matchbrackets";
import "codemirror/addon/edit/closebrackets";
type ElmPagesInit = {
load: (elmLoaded: Promise<unknown>) => Promise<void>;
flags: unknown;
};
const config: ElmPagesInit = {
load: async function (elmLoaded) {
const app = await elmLoaded;
console.log("App loaded", app);
let cm = null;
// wait for Elm to load in #editor for us to initialize code mirror
app.ports.initialize.subscribe((val) => {
const editor = document.getElementById("editor");
if (!editor) {
console.error("Failed to find editor element!");
return;
}
cm = CodeMirror(editor, {
value: val,
// custom defined mode, derived from commonlisp
mode: "pseudolisp",
lineNumbers: true,
lineWrapping: true,
theme: "material",
autofocus: true,
autoCloseBrackets: true,
matchBrackets: true,
});
cm.on("change", (_) => {
app.ports.updatedEditor.send(cm.getValue());
});
app.ports.updateCode.subscribe((val) => {
cm.setValue(val);
});
// Elm gives us a page to store
app.ports.sendPages.subscribe(async (pages) => {
try {
await db.clear();
console.log("DB cleared");
if (pages.length === 0) {
console.log("No pages to store!");
} else {
console.log(`Storing pages: ${pages.map((p) => p[0])}`);
await db.setMany(pages);
console.log("Stored pages");
}
} catch (e) {
console.error("Failure storing pages!");
console.log(e);
}
});
app.ports.fetchPage.subscribe((n) => {
db.get(n)
.then((val) => {
console.log(`JS: Got page ${n}`);
app.ports.fetchPageResponse.send([n, val]);
})
.catch((err) => {
console.log(`Failed to fetch page ${n}`, err);
});
});
app.ports.log.subscribe((str) => {
console.info(`From ELM: ${str}`);
});
window.onblur = () => {
console.log("blur");
app.ports.blurs.send(null);
};
});
},
flags: function () {
return "You can decode this in Shared.elm using Json.Decode.string!";
},
};
export default config;