-
Notifications
You must be signed in to change notification settings - Fork 10
/
template.js
79 lines (68 loc) · 1.74 KB
/
template.js
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
'use strict';
const Engine = require('./engine');
const story = require('./story.json');
const Document = require('./document');
const handler = {
storageKey: 'kni',
shouldLog: true,
log(...args) {
if (this.shouldLog) {
console.log(...args);
}
},
load() {
if (window.location.hash.length > 1) {
const json = atob(window.location.hash.slice(1));
return JSON.parse(json);
}
const json = window.localStorage.getItem(this.storageKey);
if (json) {
const state = JSON.parse(json);
window.history.replaceState(state, '', '#' + btoa(json));
return state;
}
return null;
},
waypoint(waypoint) {
const json = JSON.stringify(waypoint);
window.history.pushState(waypoint, '', '#' + btoa(json));
localStorage.setItem(this.storageKey, json);
},
goto(label) {
this.log(label);
},
answer(text) {
this.log('>', text);
},
};
const doc = new Document(document.body);
const engine = new Engine({
story: story,
render: doc,
dialog: doc,
handler,
});
window.onpopstate = (event) => {
handler.log('>', 'back');
engine.resume(event.state);
};
window.onkeypress = (event) => {
const code = event.code;
const match = /^Digit(\d+)$/.exec(code);
if (match) {
engine.answer(match[1]);
} else if (code === 'KeyR') {
engine.reset();
}
};
const reset = document.querySelector(".reset");
if (reset) {
reset.onclick = () => { engine.reset() };
}
doc.clear();
try {
engine.resume(handler.load());
} catch (error) {
console.error('unable to load prior state, restarting', error);
engine.resume(null);
}