-
Notifications
You must be signed in to change notification settings - Fork 0
/
story.js
618 lines (560 loc) · 21.9 KB
/
story.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
617
618
// Created with Squiffy 3.0.1
// https://github.com/textadventures/squiffy
(function(){
/* jshint quotmark: single */
/* jshint evil: true */
var squiffy = {};
(function () {
'use strict';
squiffy.story = {};
squiffy.story.begin = function () {
squiffy.ui.output.on('click', 'a.squiffy-link', function (event) {
if ($(this).hasClass('disabled')) return;
var passage = $(this).data('passage');
var section = $(this).data('section');
var rotateAttr = $(this).attr('data-rotate');
var sequenceAttr = $(this).attr('data-sequence');
if (passage) {
$(this).addClass('disabled');
squiffy.set('_turncount', squiffy.get('_turncount') + 1);
passage = processLink(passage);
if (passage) {
currentSection.append('<hr/>');
squiffy.story.passage(passage);
}
var turnPassage = '@' + squiffy.get('_turncount');
if (turnPassage in squiffy.story.section.passages) {
squiffy.story.passage(turnPassage);
}
}
else if (section) {
currentSection.append('<hr/>');
$(this).addClass('disabled');
section = processLink(section);
squiffy.story.go(section);
}
else if (rotateAttr || sequenceAttr) {
var result = rotate(rotateAttr || sequenceAttr, rotateAttr ? $(this).text() : '');
$(this).html(result[0].replace(/"/g, '"').replace(/'/g, '\''));
var dataAttribute = rotateAttr ? 'data-rotate' : 'data-sequence';
$(this).attr(dataAttribute, result[1]);
if (!result[1]) {
$(this).addClass('disabled');
}
if ($(this).attr('data-attribute')) {
squiffy.set($(this).attr('data-attribute'), result[0]);
}
squiffy.story.save();
}
});
squiffy.ui.output.on('mousedown', 'a.squiffy-link', function (event) {
event.preventDefault();
});
if (!squiffy.story.load()) {
squiffy.story.go(squiffy.story.start);
}
};
var processLink = function(link) {
var sections = link.split(',');
var first = true;
var target = null;
sections.forEach(function (section) {
section = section.trim();
if (startsWith(section, '@replace ')) {
replaceLabel(section.substring(9));
}
else {
if (first) {
target = section;
}
else {
setAttribute(section);
}
}
first = false;
});
return target;
};
var setAttribute = function(expr) {
var lhs, rhs, op, value;
var setRegex = /^([\w]*)\s*=\s*(.*)$/;
var setMatch = setRegex.exec(expr);
if (setMatch) {
lhs = setMatch[1];
rhs = setMatch[2];
if (isNaN(rhs)) {
squiffy.set(lhs, rhs);
}
else {
squiffy.set(lhs, parseFloat(rhs));
}
}
else {
var incDecRegex = /^([\w]*)\s*([\+\-])=\s*(.*)$/;
var incDecMatch = incDecRegex.exec(expr);
if (incDecMatch) {
lhs = incDecMatch[1];
op = incDecMatch[2];
rhs = parseFloat(incDecMatch[3]);
value = squiffy.get(lhs);
if (value === null) value = 0;
if (op == '+') {
value += rhs;
}
if (op == '-') {
value -= rhs;
}
squiffy.set(lhs, value);
}
else {
value = true;
if (startsWith(expr, 'not ')) {
expr = expr.substring(4);
value = false;
}
squiffy.set(expr, value);
}
}
};
var replaceLabel = function(expr) {
var regex = /^([\w]*)\s*=\s*(.*)$/;
var match = regex.exec(expr);
if (!match) return;
var label = match[1];
var text = match[2];
if (text in squiffy.story.section.passages) {
text = squiffy.story.section.passages[text].text;
}
else if (text in squiffy.story.sections) {
text = squiffy.story.sections[text].text;
}
var stripParags = /^<p>(.*)<\/p>$/;
var stripParagsMatch = stripParags.exec(text);
if (stripParagsMatch) {
text = stripParagsMatch[1];
}
var $labels = squiffy.ui.output.find('.squiffy-label-' + label);
$labels.fadeOut(1000, function() {
$labels.html(squiffy.ui.processText(text));
$labels.fadeIn(1000, function() {
squiffy.story.save();
});
});
};
squiffy.story.go = function(section) {
squiffy.set('_transition', null);
newSection();
squiffy.story.section = squiffy.story.sections[section];
if (!squiffy.story.section) return;
squiffy.set('_section', section);
setSeen(section);
var master = squiffy.story.sections[''];
if (master) {
squiffy.story.run(master);
squiffy.ui.write(master.text);
}
squiffy.story.run(squiffy.story.section);
// The JS might have changed which section we're in
if (squiffy.get('_section') == section) {
squiffy.set('_turncount', 0);
squiffy.ui.write(squiffy.story.section.text);
squiffy.story.save();
}
};
squiffy.story.run = function(section) {
if (section.clear) {
squiffy.ui.clearScreen();
}
if (section.attributes) {
processAttributes(section.attributes);
}
if (section.js) {
section.js();
}
};
squiffy.story.passage = function(passageName) {
var passage = squiffy.story.section.passages[passageName];
if (!passage) return;
setSeen(passageName);
var masterSection = squiffy.story.sections[''];
if (masterSection) {
var masterPassage = masterSection.passages[''];
if (masterPassage) {
squiffy.story.run(masterPassage);
squiffy.ui.write(masterPassage.text);
}
}
var master = squiffy.story.section.passages[''];
if (master) {
squiffy.story.run(master);
squiffy.ui.write(master.text);
}
squiffy.story.run(passage);
squiffy.ui.write(passage.text);
squiffy.story.save();
};
var processAttributes = function(attributes) {
attributes.forEach(function (attribute) {
if (startsWith(attribute, '@replace ')) {
replaceLabel(attribute.substring(9));
}
else {
setAttribute(attribute);
}
});
};
squiffy.story.restart = function() {
if (squiffy.ui.settings.persist && window.localStorage) {
var keys = Object.keys(localStorage);
$.each(keys, function (idx, key) {
if (startsWith(key, squiffy.story.id)) {
localStorage.removeItem(key);
}
});
}
else {
squiffy.storageFallback = {};
}
if (squiffy.ui.settings.scroll === 'element') {
squiffy.ui.output.html('');
squiffy.story.begin();
}
else {
location.reload();
}
};
squiffy.story.save = function() {
squiffy.set('_output', squiffy.ui.output.html());
};
squiffy.story.load = function() {
var output = squiffy.get('_output');
if (!output) return false;
squiffy.ui.output.html(output);
currentSection = $('#' + squiffy.get('_output-section'));
squiffy.story.section = squiffy.story.sections[squiffy.get('_section')];
var transition = squiffy.get('_transition');
if (transition) {
eval('(' + transition + ')()');
}
return true;
};
var setSeen = function(sectionName) {
var seenSections = squiffy.get('_seen_sections');
if (!seenSections) seenSections = [];
if (seenSections.indexOf(sectionName) == -1) {
seenSections.push(sectionName);
squiffy.set('_seen_sections', seenSections);
}
};
squiffy.story.seen = function(sectionName) {
var seenSections = squiffy.get('_seen_sections');
if (!seenSections) return false;
return (seenSections.indexOf(sectionName) > -1);
};
squiffy.ui = {};
var currentSection = null;
var screenIsClear = true;
var scrollPosition = 0;
var newSection = function() {
if (currentSection) {
$('.squiffy-link', currentSection).addClass('disabled');
}
var sectionCount = squiffy.get('_section-count') + 1;
squiffy.set('_section-count', sectionCount);
var id = 'squiffy-section-' + sectionCount;
currentSection = $('<div/>', {
id: id,
}).appendTo(squiffy.ui.output);
squiffy.set('_output-section', id);
};
squiffy.ui.write = function(text) {
screenIsClear = false;
scrollPosition = squiffy.ui.output.height();
currentSection.append($('<div/>').html(squiffy.ui.processText(text)));
squiffy.ui.scrollToEnd();
};
squiffy.ui.clearScreen = function() {
squiffy.ui.output.html('');
screenIsClear = true;
newSection();
};
squiffy.ui.scrollToEnd = function() {
var scrollTo, currentScrollTop, distance, duration;
if (squiffy.ui.settings.scroll === 'element') {
scrollTo = squiffy.ui.output[0].scrollHeight - squiffy.ui.output.height();
currentScrollTop = squiffy.ui.output.scrollTop();
if (scrollTo > currentScrollTop) {
distance = scrollTo - currentScrollTop;
duration = distance / 0.4;
squiffy.ui.output.stop().animate({ scrollTop: scrollTo }, duration);
}
}
else {
scrollTo = scrollPosition;
currentScrollTop = Math.max($('body').scrollTop(), $('html').scrollTop());
if (scrollTo > currentScrollTop) {
var maxScrollTop = $(document).height() - $(window).height();
if (scrollTo > maxScrollTop) scrollTo = maxScrollTop;
distance = scrollTo - currentScrollTop;
duration = distance / 0.5;
$('body,html').stop().animate({ scrollTop: scrollTo }, duration);
}
}
};
squiffy.ui.processText = function(text) {
function process(text, data) {
var containsUnprocessedSection = false;
var open = text.indexOf('{');
var close;
if (open > -1) {
var nestCount = 1;
var searchStart = open + 1;
var finished = false;
while (!finished) {
var nextOpen = text.indexOf('{', searchStart);
var nextClose = text.indexOf('}', searchStart);
if (nextClose > -1) {
if (nextOpen > -1 && nextOpen < nextClose) {
nestCount++;
searchStart = nextOpen + 1;
}
else {
nestCount--;
searchStart = nextClose + 1;
if (nestCount === 0) {
close = nextClose;
containsUnprocessedSection = true;
finished = true;
}
}
}
else {
finished = true;
}
}
}
if (containsUnprocessedSection) {
var section = text.substring(open + 1, close);
var value = processTextCommand(section, data);
text = text.substring(0, open) + value + process(text.substring(close + 1), data);
}
return (text);
}
function processTextCommand(text, data) {
if (startsWith(text, 'if ')) {
return processTextCommand_If(text, data);
}
else if (startsWith(text, 'else:')) {
return processTextCommand_Else(text, data);
}
else if (startsWith(text, 'label:')) {
return processTextCommand_Label(text, data);
}
else if (/^rotate[: ]/.test(text)) {
return processTextCommand_Rotate('rotate', text, data);
}
else if (/^sequence[: ]/.test(text)) {
return processTextCommand_Rotate('sequence', text, data);
}
else if (text in squiffy.story.section.passages) {
return process(squiffy.story.section.passages[text].text, data);
}
else if (text in squiffy.story.sections) {
return process(squiffy.story.sections[text].text, data);
}
return squiffy.get(text);
}
function processTextCommand_If(section, data) {
var command = section.substring(3);
var colon = command.indexOf(':');
if (colon == -1) {
return ('{if ' + command + '}');
}
var text = command.substring(colon + 1);
var condition = command.substring(0, colon);
var operatorRegex = /([\w ]*)(=|<=|>=|<>|<|>)(.*)/;
var match = operatorRegex.exec(condition);
var result = false;
if (match) {
var lhs = squiffy.get(match[1]);
var op = match[2];
var rhs = match[3];
if (op == '=' && lhs == rhs) result = true;
if (op == '<>' && lhs != rhs) result = true;
if (op == '>' && lhs > rhs) result = true;
if (op == '<' && lhs < rhs) result = true;
if (op == '>=' && lhs >= rhs) result = true;
if (op == '<=' && lhs <= rhs) result = true;
}
else {
var checkValue = true;
if (startsWith(condition, 'not ')) {
condition = condition.substring(4);
checkValue = false;
}
if (startsWith(condition, 'seen ')) {
result = (squiffy.story.seen(condition.substring(5)) == checkValue);
}
else {
var value = squiffy.get(condition);
if (value === null) value = false;
result = (value == checkValue);
}
}
var textResult = result ? process(text, data) : '';
data.lastIf = result;
return textResult;
}
function processTextCommand_Else(section, data) {
if (!('lastIf' in data) || data.lastIf) return '';
var text = section.substring(5);
return process(text, data);
}
function processTextCommand_Label(section, data) {
var command = section.substring(6);
var eq = command.indexOf('=');
if (eq == -1) {
return ('{label:' + command + '}');
}
var text = command.substring(eq + 1);
var label = command.substring(0, eq);
return '<span class="squiffy-label-' + label + '">' + process(text, data) + '</span>';
}
function processTextCommand_Rotate(type, section, data) {
var options;
var attribute = '';
if (section.substring(type.length, type.length + 1) == ' ') {
var colon = section.indexOf(':');
if (colon == -1) {
return '{' + section + '}';
}
options = section.substring(colon + 1);
attribute = section.substring(type.length + 1, colon);
}
else {
options = section.substring(type.length + 1);
}
var rotation = rotate(options.replace(/"/g, '"').replace(/'/g, '''));
if (attribute) {
squiffy.set(attribute, rotation[0]);
}
return '<a class="squiffy-link" data-' + type + '="' + rotation[1] + '" data-attribute="' + attribute + '">' + rotation[0] + '</a>';
}
var data = {
fulltext: text
};
return process(text, data);
};
squiffy.ui.transition = function(f) {
squiffy.set('_transition', f.toString());
f();
};
squiffy.storageFallback = {};
squiffy.set = function(attribute, value) {
if (typeof value === 'undefined') value = true;
if (squiffy.ui.settings.persist && window.localStorage) {
localStorage[squiffy.story.id + '-' + attribute] = JSON.stringify(value);
}
else {
squiffy.storageFallback[attribute] = JSON.stringify(value);
}
squiffy.ui.settings.onSet(attribute, value);
};
squiffy.get = function(attribute) {
var result;
if (squiffy.ui.settings.persist && window.localStorage) {
result = localStorage[squiffy.story.id + '-' + attribute];
}
else {
result = squiffy.storageFallback[attribute];
}
if (!result) return null;
return JSON.parse(result);
};
var startsWith = function(string, prefix) {
return string.substring(0, prefix.length) === prefix;
};
var rotate = function(options, current) {
var colon = options.indexOf(':');
if (colon == -1) {
return [options, current];
}
var next = options.substring(0, colon);
var remaining = options.substring(colon + 1);
if (current) remaining += ':' + current;
return [next, remaining];
};
var methods = {
init: function (options) {
var settings = $.extend({
scroll: 'body',
persist: true,
restartPrompt: true,
onSet: function (attribute, value) {}
}, options);
squiffy.ui.output = this;
squiffy.ui.restart = $(settings.restart);
squiffy.ui.settings = settings;
if (settings.scroll === 'element') {
squiffy.ui.output.css('overflow-y', 'auto');
}
squiffy.story.begin();
return this;
},
get: function (attribute) {
return squiffy.get(attribute);
},
set: function (attribute, value) {
squiffy.set(attribute, value);
},
restart: function () {
if (!squiffy.ui.settings.restartPrompt || confirm('Are you sure you want to restart?')) {
squiffy.story.restart();
}
}
};
$.fn.squiffy = function (methodOrOptions) {
if (methods[methodOrOptions]) {
return methods[methodOrOptions]
.apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof methodOrOptions === 'object' || ! methodOrOptions) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + methodOrOptions + ' does not exist');
}
};
})();
var get = squiffy.get;
var set = squiffy.set;
squiffy.story.start = '_default';
squiffy.story.id = '5a6a68ab20';
squiffy.story.sections = {
'_default': {
'text': "<p>You are the captain of the starship Granger. You always dreamed of being a dashing sharship captain exploring new galaxies, but the fact of the matter is that you are a glorified truck driver.<br></p>\n<p>One day, your communication officer turns to you as the ship nears Jupiter and says "Sir, I'm picking up a strange message from Europa."<br>\n"<a class=\"squiffy-link link-section\" data-section=\"ignore1\">Nothing for us to worry about</a>" you reply. Let the Space Patrol handle it.</p>",
'passages': {
},
},
'ignore1': {
'text': "<p>You continue on your way to Pluto, confident that the overworked space police will take care of it. besides you have a schedule to keep.<br></p>\n<p>However, the next day. you are passing the same way again, this time with a cargo hold full of aluminum ore.</p>\n<p>You write your story in a text file. Each choice is represented by a <a class=\"squiffy-link link-section\" data-section=\"new section\">new section</a>. You can create links to new sections by surrounding them in double square brackets.</p>",
'passages': {
},
},
'new section': {
'text': "<p>In addition to sections, Squiffy has the concept of passages. These are sections of text that don't advance the story. For example, you can click this <a class=\"squiffy-link link-passage\" data-passage=\"passage link\">passage link</a>, and this <a class=\"squiffy-link link-passage\" data-passage=\"other passage link\">other passage link</a>, but the story won't advance until you click this <a class=\"squiffy-link link-section\" data-section=\"section link\">section link</a>.</p>",
'passages': {
'passage link': {
'text': "<p>This is the text for the first passage link.</p>",
},
'other passage link': {
'text': "<p>This is the text for the second passage link.</p>",
},
},
},
'section link': {
'text': "<p>When a new section appears, any unclicked passage links from the previous section are disabled.</p>",
'passages': {
},
},
}
})();