-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd.js
616 lines (537 loc) · 17.4 KB
/
cmd.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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/**
* Boring Polyfills
*/
window.requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
function (func) {
window.setTimeout(func, 33); // 30 FPS
};
var webcomponentsPolyfill = require('polyfill-webcomponents');
var cmd = { run: function () {
"use strict";
var inputTemplate, // Template for the input
lnTemplate, // Template for a new line
term, // The terminal in the DOM. This shouldn't go anywhere, so this won't have to be updated.
input,
debug,
notes,
errorMsgs,
muted = false;
var init = function () {
inputTemplate = getTemplate('input-template');
lnTemplate = getTemplate('ln-template');
term = gtById('terminal');
input;
debug = true;
notes = [];
errorMsgs = {};
gtById('save').addEventListener('click', saveGame);
gtById('load').addEventListener('click', loadGame);
gtById('mute').addEventListener('click', toggleMute);
appendInput();
focusInput();
};
/**
* Utility functions
*/
// getElementById wrapper
var gtById = function (id) {
return document.getElementById(id);
};
// console.log wrapper
var log = function (msg) {
if ( debug ) { console.log(msg); }
};
// Gets a copy of a template
var getTemplate = function (id) {
var template = gtById(id);
if ( ! template ) { return false; }
return template.content.cloneNode(true);
};
// Generate a unique, hexy ID (move that hexy bod grrl)
var uniqueId = function uniqueId () {
var id = '',
length = 16, // hnnnng so hexy
chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']; // That's 18,446,744,073,709,600,000 possibilities for those of you following at home
for (var i=0; i < length; i++) {
id += chars[Math.floor(Math.random() * 16)];
}
if ( gtById(id) ) {
return uniqueId(); // recursive hnnnng
} else {
return id;
}
};
// When called, gets input from the field (if any) and calls the appropriate program, passing it token-ized arguments.
var parseInput = function () {
var val = input.value;
if (val) {
var tokens = val.split(' ');
if ( state.installed.indexOf(tokens[0]) != -1 ) {
var commandHistory = appendOutput();
commandHistory.innerHTML = '<span class="said-command">$ ' + input.value + '</span>';
programs[tokens[0]].run(tokens);
} else {
var lnout = appendOutput();
lnout.innerHTML = err.cmdNotFound;
focusInput();
}
}
};
// Appends a new output div with a unique ID. Returns a reference to the DOM node for further manipulation.
var appendOutput = function () {
var ln = lnTemplate.querySelector('.shell-ln').cloneNode(true),
id = uniqueId(),
shell = gtById('shell');
if (shell) {
gtById('shell').parentNode.removeChild(gtById('shell'));
}
ln.id = id;
term.appendChild(ln);
return ln;
}
// Usually called from the callback for programs; gives the user input ability after programs are finished running.
var appendInput = function () {
if ( !gtById('input') ) {
inputTemplate = getTemplate('input-template');
term.appendChild(inputTemplate);
input = gtById('input');
input.addEventListener('keydown', function (e) {
if (e.keyIdentifier == "Enter") {
parseInput();
}
});
}
};
var focusInput = function () {
if ( !gtById('input') ) {
appendInput();
}
input.focus();
}
// Replace the keywords in a string, similar to PHP's `sprintf`.
var keywordReplace = function (string, values) {
for (var i=0; i < values.length; i++) {
string = string.replace('%'+i, val);
}
return string;
};
var fitInStr = function (str, length) {
if ( str.length > length ) {
// Put a .. on the end to show it trailing off if it's too long
return str.substring(0, str.length - 2) + '..';
} else {
// Lengthen the string with ' ' until it meets the number of characters required
var whitespace = "";
while ( whitespace.length < length - str.length ) { whitespace += " " };
return str + whitespace;
}
};
var breakAtLength = function (str, length, column) {
var newStr = '';
if ( str.length > length ) {
var i = 0, offset = '';
while (i != null) {
if (column && i > 0) {
offset = fitInStr('', column * length);
}
newStr += offset + str.substring( i * length, i * length + length ) + '\n';
i++;
if ( i * length > str.length ) {
break;
}
}
} else {
newStr = fitInStr(str, length);
}
return newStr;
}
var tableLayout = function (data) {
var width = data.width || 28,
columnCount = data.rowCount || 2,
output = '',
separator = data.separator || '|';
for (var i=0, j=data.titles.length; i<j; i++) {
output += fitInStr(data.titles[i], width);
}
output += '\n';
for (var i=0, j=data.rows.length; i<j; i++) {
var row = data.rows[i];
for (var k=0, l=row.length; k<l; k++) {
output += breakAtLength(row[k], width, k);
}
}
return output;
};
var usageTable = function (rows) {
return tableLayout({
columns: 2,
width: 29,
titles: [
'Usage',
'Description'
],
rows: rows
})
}
var spc = function () {
return '<span class="spc"></span>';
}
var loadSound = function (file, options, cb) {
options = options || {},
cb = cb || function () {};
var audio = gtById(options.id);
if (audio) {
audio.load();
return cb(audio);
}
audio = document.createElement('audio');
audio.id = options.id;
audio.src = 'sound/' + file;
audio.loop = options.loop ? true : false;
audio.volume = options.volume || 1;
document.body.appendChild(audio);
return cb(audio);
};
var playSound = function (id, options, cb) {
options = options || {},
cb = cb || function () {};
var audio = gtById(audio);
if (audio) {
audio.loop = options.loop ? true : false;
audio.volume = options.volume || 1;
audio.play();
return cb(audio);
}
return cb(new Error('Track not found.'));
}
var toggleMute = function () {
muted = !muted;
var els = document.getElementsByTagName('audio');
for (var i=0, j=els.length; i < j; i++) {
els[i].muted = muted;
}
}
var saveGame = function () {
var saveGame = {};
saveGame.state = state;
saveGame.wd = wd;
saveGame.net = net;
alert( "Save this text somewhere:\n\n" + JSON.stringify( saveGame ) );
};
var loadGame = function () {
var saveGame = JSON.parse(prompt('Paste your save game here:'));
state = saveGame.state;
wd = saveGame.wd;
net = saveGame.net;
};
/**
* Object constructors
*/
var Note = function (my) {
var my = my || {};
var that = {};
if ( my.removable == true ) {
var template = getTemplate('note-rm-template');
} else {
var template = getTemplate('note-template');
}
var id = uniqueId();
that.dragClickX = 0;
that.dragClickY = 0;
that.dragOffsetX = 0;
that.dragOffsetY = 0;
that.display = function () {
var note = template.querySelector('.note');
var noteText = document.createElement('p');
noteText.innerHTML = my.text;
note.appendChild(noteText);
note.id = id;
document.body.appendChild(note);
note.addEventListener('mousedown', function (event) {
playSound('sticky-remove');
window[my.name].dragClickX = event.x;
window[my.name].dragClickY = event.y;
window.addEventListener('mousemove', window[my.name].drag);
});
note.addEventListener('mouseup', function () {
window[my.name].dragClickX = undefined;
window[my.name].dragClickY = undefined;
window[my.name].dragOffsetX = parseInt(this.style.transform.match(/translateX\((-?[0-9]{1,})px\)/)[1]);
window[my.name].dragOffsetY = parseInt(this.style.transform.match(/translateY\((-?[0-9]{1,})px\)/)[1]);
window.removeEventListener('mousemove', window[my.name].drag);
input.focus();
});
if (my.removable) {
note.querySelector('.note-rm').addEventListener('click', function () {
this.parentNode.parentNode.removeChild(this.parentNode);
});
}
};
that.drag = function (e) {
var transValue = "translateX(" + (e.x - window[my.name].dragClickX + window[my.name].dragOffsetX) + "px) translateY(" + (e.y - window[my.name].dragClickY + window[my.name].dragOffsetY) + "px)",
el = gtById(id);
el.style.transform = transValue;
el.style.webkitTransform = transValue;
};
return that;
};
var Program = function (my) {
var my = my || {},
that = {};
that.use = my.use;
that.desc = my.desc;
that.process = my.process;
that.run = function (input) {
var lnout = appendOutput();
input.splice(0, 1);
this.process(input, lnout, function () {
focusInput();
});
}
return that;
};
var File = function (my) {
var my = my || {},
that = {};
that.type = my.type || 'text';
that.access = my.access;
that.content = my.content;
return that;
};
var FileProgram = function (my) {
var my = my || {},
that = File({
type: 'program'
});
that.programName = my.programName;
return that;
};
init();
var state = {
installed: ['help', 'whoami', 'list', 'install'],
user: 'rachel',
wd: 'local'
};
var wd = {
'local': {
'read.pg': FileProgram({
programName: 'read'
}),
'crash.log': File({
content: '2031/05/16 22:31 CRITICAL FAILURE: Connection terminated by host. Significant electrical damage detected. Emergency recovery mode active...\n'+ spc() +'\
2031/05/16 22:42 Systems diagnostics completed.\n\
CPU: 3/12 cores operational, cycles unstable, quantum state integrity check passed.\n\
MEM: 3QB active, 152 sectors damaged, 48 OK.\n\
Databanks: 19683QB checked, 8219QB passing, 9921QB recoverable, 1543QB irreparable.\n\
To recover damaged data, install the Databank Recovery Tool®: net://downloadportal.cyberdynesystems.corp/softwaretools?92757273135337173'
})
}
};
var net = { 'net://downloadportal.cyberdynesystems.corp/softwaretools?92757273135337173': FileProgram({
programName: 'recoverytool'
}),
'net://usrportal': File({
type: 'netpage',
access: function () {
return 'WELCOME TO THE NET. RESOURCES:';
}
})
};
var programs = {};
var err = {
noOutput: "This program has no output function (that's a bug)",
cmdNotFound: "Err: program does not exist (try \"help\")"
}
window.setTimeout(function () {
window.startNote = Note({ // declared globally on purpose
name: 'startNote',
text: 'smashthestate',
removable: true
});
startNote.display();
}, 5000);
loadSound('hdd-startup.mp3', {id: 'hdd-startup', loop: false, volume: 0.2}, function (audio) {
audio.play();
audio.addEventListener('ended', function () {
gtById('hdd-loop').play();
})
});
loadSound('hdd-loop.mp3', {id: 'hdd-loop', loop: true, volume: 0.3});
loadSound('ambient-city.mp3', {id: 'city-ambient', loop: true, volume: 0.04}, function (audio) {
audio.play();
});
loadSound('music-brooding.mp3', {id: 'brooding-music', loop: true, volume: 0.24}, function (audio) {
audio.play();
});
loadSound('stickyremove.mp3', {id: 'sticky-remove', volume: 0.8});
programs.help = Program({
desc: "Displays info about installed programs.",
use: usageTable([ ['help', 'List all installed programs.'], ['help program', 'Where "program" is the name of an installed program. Display instructions for the program.'] ]),
process: function (input, lnout, cb) {
if ( input[0] ) {
if ( programs[input[0]] ) {
lnout.innerHTML = 'Description:\n'+ programs[input[0]].desc + spc() + programs[input[0]].use;
} else {
lnout.innerHTML = 'Program "'+ input[0] +'" not found.';
}
} else {
var print = "Installed programs:\n" + spc();
for (var program in programs) {
if ( state.installed.indexOf(program) != -1 ) {
print += program +'\n';
}
}
print += spc() + 'For instructions on using a program, type "help program", where "program" is an installed program.'
lnout.innerHTML = print;
}
cb();
}
});
programs.whoami = Program({
desc: 'Displays info about the current user.',
use: 'Usage:\nwhoami',
process: function (input, lnout, cb) {
lnout.innerHTML = state.user;
cb();
}
});
programs.install = Program({
desc: 'Install programs from a .pg file or netloc.',
use: usageTable([ ['install loc', 'Where "loc" is a netloc of a program to install (e.g. net://file.pg).'], ['install file.pg', 'Where "file.pg" is the name of a .pg file in the working directory.'] ]),
process: function (input, lnout, cb) {
if (!input[0]) {
lnout.innerHTML = this.use;
return cb();
}
var file = wd[state.wd][input[0]] || net[input[0]];
if ( file ) {
if (file.type == 'program') {
state.installed.push(file.programName);
var anim = getTemplate('install-animation-template');
lnout.appendChild(anim);
var el = document.createElement('span');
el.innerHTML = 'Program "' + file.programName + '" installed successfully.';
window.setTimeout(function (cb, lnout, el) {
lnout.appendChild(el);
cb();
}, 2000, cb, lnout, el);
} else {
lnout.innerHTML = 'ERR: file "'+input[0]+'" is not a program.';
cb();
}
} else {
lnout.innerHTML = 'Program "' + input[0] + '" not found.';
cb();
}
},
});
programs.list = Program({
desc: 'List files in the working directory.',
use: usageTable([ ['list', 'List all files in the working directory'] ]),
process: function (input, lnout, cb) {
var output = "";
for (var file in wd[state.wd]) {
output += file + '\n';
}
lnout.innerHTML = output;
cb();
}
});
programs.read = Program({
desc: 'Read files in the working directory.',
use: usageTable([ ['read file', 'Where "file" is the name of a file in the working directory (try "list" to see files).'] ]),
process: function (input, lnout, cb) {
if ( ! input[0] ) {
lnout.innerHTML = this.use;
} else {
var file = wd[state.wd][input[0]];
if ( file ) {
if (file.type == 'text') {
lnout.innerHTML = file.content;
} else {
lnout.innerHTML = 'ERR: file "'+ input[0] +'" is not a text file.';
}
} else {
lnout.innerHTML = "File not found: " + input[0];
}
}
cb();
}
});
programs.recoverytool = Program({
desc: 'Repair damaged Databank cells.'+ spc() +'This courtesy software is provided to you by Cyberdyne Systems® free of charge, although certain terms and conditions apply (you can find out more about our datascanning policies on our netportal.)',
use: usageTable([ ['recoverytool', 'Recover damaged data.'] ]),
process: function (input, lnout, cb) {
if (this.recovered) {
lnout.innerHTML = 'Data already recovered.';
state.installed.splice(state.installed.indexOf('recoverytool'), 1);
} else {
this.recovered = true;
wd.local['netmonkey.pg'] = FileProgram({
programName: 'netmonkey'
});
lnout.innerHTML = 'Data recovered.';
}
cb();
}
});
/**
* @extends Program
*/
var Netmonkey = function (my) {
var my = my || {};
var that = Program(my);
that.history = [];
that.currentLoc = 0;
that.start = function () {
var netmonkey = getTemplate('netmonkey-template');
term.appendChild(netmonkey);
this.viewer = gtById('netmonkey-viewer');
this.navigator = gtById('netmonkey-navigator');
this.back = gtById('netmonkey-back');
this.forward = gtById('netmonkey-forward');
this.loadPage('net://usrportal');
this.navigator.addEventListener('keydown', function (e) {
if (e.keyIdentifier == "Enter") {
programs.netmonkey.loadPage(this.navigator.value);
}
});
term.appendChild(netmonkey);
};
that.loadPage = function (loc) {
console.log(loc);
if (this.isNetloc(loc)) {
if (net[loc]) {
if (net[loc].type === 'netpage') {
this.viewer.innerHTML = net[loc].access();
} else {
this.viewer.innerHTML = 'Err: Netloc is not a netpage. Perhaps it can be opened by another program?';
}
} else {
this.viewer.innerHTML = 'Netloc not found.';
}
} else {
this.viewer.innerHTML = 'Err: invalid Netloc.';
}
};
that.isNetloc = function (loc) {
return true;
};
that.quit = function () {
this.quitCb();
};
return that;
}
programs.netmonkey = Netmonkey({
desc: 'Connect to the tornet and view directories and message boards.',
use: '',
process: function (input, lnout, cb) {
this.input = input;
this.lnout = lnout;
this.start();
this.quitCb = cb;
}
});
}};
requestAnimationFrame(cmd.run);