-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
339 lines (301 loc) · 11.8 KB
/
main.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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import * as inkjs from 'inkjs';
import { Mixer } from './sound';
import { Activity } from './activity';
import storyContent from '../temp/studierzimmer.json';
class StoryRunner {
private story: inkjs.Story;
private theme: string = "dark";
private savePoint: string = "";
private storyContainer: HTMLElement;
private rewindButton: HTMLElement;
private saveButton: HTMLElement;
private loadButton: HTMLElement;
private activitySpan: HTMLElement;
private mixer: Mixer = new Mixer();
private loadPromises: Record<string, Promise<void>> = {};
private activityTracker: Activity = new Activity();
private ctag: string = "p";
private trusted: boolean = false;
private saveSlot: HTMLSelectElement;
constructor(storyContent: any) {
this.story = new inkjs.Story(storyContent);
this.story.BindExternalFunction("setTheme", this.updateTheme.bind(this));
this.story.BindExternalFunction("createSlot", this.createSlot.bind(this));
this.story.BindExternalFunction("loadSound", this.loadSound.bind(this));
this.story.BindExternalFunction("playSound", this.playSound.bind(this));
this.story.BindExternalFunction("playSoundS", this.playSoundS.bind(this));
this.story.BindExternalFunction("playSoundV", this.playSoundV.bind(this));
this.story.BindExternalFunction("stopSound", this.stopSound.bind(this));
this.story.BindExternalFunction("currentSound", this.currentSound.bind(this));
this.story.BindExternalFunction("stopAllSounds", this.stopAllSounds.bind(this));
this.story.BindExternalFunction("stopGroup", this.stopGroup.bind(this));
this.story.BindExternalFunction("setFadeTime", this.setFadeTime.bind(this));
this.story.BindExternalFunction("keepSoundAlive", this.keepSoundAlive.bind(this));
this.story.BindExternalFunction("hasFrontend", this.hasFrontend.bind(this), true);
this.story.BindExternalFunction("activity", this.activity.bind(this));
this.story.BindExternalFunction("cap", this.capitalize.bind(this), true);
this.storyContainer = document.querySelector("#target") as HTMLElement;
this.rewindButton = document.querySelector("#rewind") as HTMLElement;
this.saveButton = document.querySelector("#save") as HTMLElement;
this.saveSlot = document.querySelector("#saveSlot") as HTMLSelectElement;
this.loadButton = document.querySelector("#load") as HTMLElement;
this.activitySpan = document.querySelector("#activity") as HTMLElement;
const scroll = document.querySelector("#outerContainer") as HTMLElement;
scroll.addEventListener("scroll", this.activityTracker.track.bind(this.activityTracker));
this.wireButtons();
this.globalTags();
}
public init(): void {
this.renderParagraphs();
this.storyContainer.innerHTML = "";
this.load();
this.run();
}
private run(): void {
this.savePoint = this.story.state.toJson();
this.renderParagraphs();
this.renderChoices();
this.show();
}
private globalTags(): void {
const globalTags = this.story.globalTags;
if (globalTags) {
globalTags.forEach((tag: string) => {
const { key, value } = this.processTag(tag);
switch (key.toLowerCase()) {
case 'title':
this.setInnerHTML("#title", value);
break;
case 'author':
this.setInnerHTML("#byline", "von " + value);
break;
case 'theme':
this.updateTheme(value);
break;
default:
console.warn(`Unhandled Tag - ${key}: ${value}`);
}
});
}
}
private parseTags(tags: string[] | null, customClasses: string[]): Set<string> {
const flags: Set<string> = new Set();
if (tags) {
tags.forEach((tag: string) => {
const { key, value } = this.processTag(tag);
switch (key.toLowerCase()) {
case 'cl':
case 'class':
customClasses.push(value);
break;
case 'ctag':
this.ctag = value;
break;
case 'flag':
flags.add(value.toLowerCase());
break;
// Ignore global tags - ink will repeat thems
case 'title':
case 'author':
case 'theme':
break;
default:
console.warn(`Unhandled Tag - ${key}: ${value}`);
}
});
}
return flags;
}
private renderParagraphs(): void {
while (this.story.canContinue) {
const paragraph = this.story.Continue();
const customClasses: string[] = [];
this.parseTags(this.story.currentTags, customClasses);
if (!paragraph || !paragraph.trim()) {
continue;
}
const el = document.createElement('p');
el.classList.add("blend");
el.classList.add("hide");
el.innerHTML = paragraph;
customClasses.forEach(cls => el.classList.add(cls));
this.storyContainer.appendChild(el);
}
const hr = document.createElement('hr');
this.storyContainer.appendChild(hr);
}
private renderChoices(): void {
let lastTag: string | null = null;
this.story.currentChoices.forEach((choice: any) => {
const customClasses: string[] = [];
const flags = this.parseTags(choice.tags, customClasses);
const cel = document.createElement(this.ctag);
cel.classList.add("blend");
cel.classList.add("choice");
let prefix = ""
if (flags.has("space")) {
prefix = " ";
}
else if (this.ctag == "span" && lastTag == "span") {
prefix = ", ";
}
lastTag = this.ctag;
cel.innerHTML = prefix + `<a>${choice.text}</a>`;
customClasses.forEach(cls => cel.classList.add(cls));
cel.classList.add("hide");
this.storyContainer.appendChild(cel);
cel.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'nearest',
});
const ael = cel.querySelector("a");
if (ael && !flags.has("no_click")) {
ael.classList.add("link");
ael.addEventListener("click", (event: MouseEvent) => {
this.trusted = true;
this.removeAll(".choice");
this.story.ChooseChoiceIndex(choice.index);
this.run();
});
}
});
}
// Helpers
private wireButtons(): void {
this.rewindButton.addEventListener("click", (event: MouseEvent) => {
this.trusted = true;
this.restart();
});
this.rewindButton.classList.add("link");
this.saveButton.addEventListener("click", (event: MouseEvent) => {
this.trusted = true;
this.save();
});
this.saveButton.classList.add("link");
this.loadButton.addEventListener("click", (event: MouseEvent) => {
this.trusted = true;
this.init();
});
this.loadButton.classList.add("link");
}
private restart(): void {
this.activityTracker.reset();
this.storyContainer.innerHTML = "";
this.story.ResetState();
this.mixer.stopAll();
this.run();
}
public load(): void {
const slot = this.saveSlot.value;
const activity = window.localStorage.getItem('activity' + slot);
if (activity) {
this.activityTracker.set(Number(activity));
}
const savedState = window.localStorage.getItem('save-state' + slot);
if (savedState) {
this.story.state.LoadJson(savedState);
} else {
this.story.ResetState();
this.activityTracker.reset();
}
}
private save(): void {
const slot = this.saveSlot.value;
window.localStorage.setItem('activity' + slot, this.activityTracker.activity().toString());
window.localStorage.setItem('save-state' + slot, this.savePoint);
}
private show(): void {
this.activitySpan.innerHTML = (this.activityTracker.activity() / 60).toFixed(2);
const elements = document.querySelectorAll(".hide");
if (elements) {
const el = elements.item(0);
if (el) {
el.classList.remove("hide");
setTimeout(this.show.bind(this), 200);
}
}
}
private removeAll(selector: string): void {
const allElements = this.storyContainer.querySelectorAll(selector);
allElements.forEach(el => el.parentNode?.removeChild(el));
}
private setInnerHTML(query: string, value: string): void {
const tag = document.querySelector(query);
if (tag) {
tag.innerHTML = value;
}
}
private processTag(tag: string): { key: string; value: string } {
const [key, value] = tag.split(':').map(part => part.trim());
return { key, value };
}
private updateTheme(theme: string): void {
const cl = document.documentElement.classList;
cl.add("switched");
cl.remove("theme-" + this.theme);
cl.add("theme-" + theme);
this.theme = theme;
}
// Bindings
private keepSoundAlive(): void {
this.mixer.startDummy();
}
private createSlot(name: string, loop: boolean = false, groupList: string = ""): void {
const list = groupList.split(",").map(item => item.trim());
this.mixer.createSlot(name, loop, list);
}
private loadSound(slotName: string, soundName: string, url: string): void {
const name = slotName + soundName;
const promise = this.mixer.load(slotName, soundName, url);
this.loadPromises[name] = promise;
}
private playSoundS(slotName: string, soundName: string): void {
this.playSound(slotName, soundName);
}
private playSoundV(slotName: string, soundName: string, volume: number = 1): void {
this.playSound(slotName, soundName, volume);
}
private playSound(slotName: string, soundName: string, volume: number = 1, crossFade: boolean = true): void {
if (!this.trusted) {
return;
}
(async () => {
const name = slotName + soundName;
await this.loadPromises[name];
this.mixer.play(slotName, soundName, volume, crossFade);
})();
}
private stopSound(slotName: string): void {
this.mixer.stop(slotName);
}
private currentSound(slotName: string): string {
return this.mixer.current(slotName);
}
private stopAllSounds(): void {
this.mixer.stopAll();
}
private stopGroup(groupName: string): void {
this.mixer.stopGroup(groupName);
}
private setFadeTime(time: number): void {
this.mixer.setFadeTime(time);
}
private hasFrontend(): boolean {
return true;
}
private activity(): number {
return this.activityTracker.activity();
}
private capitalize(input: string): string {
if (!input) {
return "";
}
return input.charAt(0).toUpperCase() + input.slice(1);
}
}
function runStory(): void {
const runner = new StoryRunner(storyContent);
runner.init();
}
export { runStory };