-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathbeforePyret.js
1421 lines (1304 loc) · 47 KB
/
beforePyret.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global $ jQuery CPO CodeMirror storageAPI Q createProgramCollectionAPI makeShareAPI */
var shareAPI = makeShareAPI(process.env.CURRENT_PYRET_RELEASE);
var url = require('url.js');
var modalPrompt = require('./modal-prompt.js');
window.modalPrompt = modalPrompt;
const LOG = true;
window.ct_log = function(/* varargs */) {
if (window.console && LOG) {
console.log.apply(console, arguments);
}
};
window.ct_error = function(/* varargs */) {
if (window.console && LOG) {
console.error.apply(console, arguments);
}
};
var initialParams = url.parse(document.location.href);
var params = url.parse("/?" + initialParams["hash"]);
window.highlightMode = "mcmh"; // what is this for?
window.clearFlash = function() {
$(".notificationArea").empty();
}
window.whiteToBlackNotification = function() {
/*
$(".notificationArea .active").css("background-color", "white");
$(".notificationArea .active").animate({backgroundColor: "#111111" }, 1000);
*/
};
window.stickError = function(message, more) {
CPO.sayAndForget(message);
clearFlash();
var err = $("<span>").addClass("error").text(message);
if(more) {
err.attr("title", more);
}
err.tooltip();
$(".notificationArea").prepend(err);
whiteToBlackNotification();
};
window.flashError = function(message) {
CPO.sayAndForget(message);
clearFlash();
var err = $("<span>").addClass("error").text(message);
$(".notificationArea").prepend(err);
whiteToBlackNotification();
err.fadeOut(7000);
};
window.flashMessage = function(message) {
CPO.sayAndForget(message);
clearFlash();
var msg = $("<span>").addClass("active").text(message);
$(".notificationArea").prepend(msg);
whiteToBlackNotification();
msg.fadeOut(7000);
};
window.stickMessage = function(message) {
CPO.sayAndForget(message);
clearFlash();
var msg = $("<span>").addClass("active").text(message);
$(".notificationArea").prepend(msg);
whiteToBlackNotification();
};
window.stickRichMessage = function(content) {
CPO.sayAndForget(content.text());
clearFlash();
$(".notificationArea").prepend($("<span>").addClass("active").append(content));
whiteToBlackNotification();
};
window.mkWarningUpper = function(){return $("<div class='warning-upper'>");}
window.mkWarningLower = function(){return $("<div class='warning-lower'>");}
var Documents = function() {
function Documents() {
this.documents = new Map();
}
Documents.prototype.has = function (name) {
return this.documents.has(name);
};
Documents.prototype.get = function (name) {
return this.documents.get(name);
};
Documents.prototype.set = function (name, doc) {
if(logger.isDetailed)
logger.log("doc.set", {name: name, value: doc.getValue()});
return this.documents.set(name, doc);
};
Documents.prototype.delete = function (name) {
if(logger.isDetailed)
logger.log("doc.del", {name: name});
return this.documents.delete(name);
};
Documents.prototype.forEach = function (f) {
return this.documents.forEach(f);
};
return Documents;
}();
var VERSION_CHECK_INTERVAL = 120000 + (30000 * Math.random());
function checkVersion() {
$.get("/current-version").then(function(resp) {
resp = JSON.parse(resp);
if(resp.version && resp.version !== process.env.CURRENT_PYRET_RELEASE) {
window.flashMessage("A new version of Pyret is available. Save and reload the page to get the newest version.");
}
});
}
window.setInterval(checkVersion, VERSION_CHECK_INTERVAL);
window.CPO = {
save: function() {},
autoSave: function() {},
documents : new Documents()
};
$(function() {
const CONTEXT_FOR_NEW_FILES = "use context starter2024\n";
const CONTEXT_PREFIX = /^use context\s+/;
function merge(obj, extension) {
var newobj = {};
Object.keys(obj).forEach(function(k) {
newobj[k] = obj[k];
});
Object.keys(extension).forEach(function(k) {
newobj[k] = extension[k];
});
return newobj;
}
var animationDiv = null;
function closeAnimationIfOpen() {
if(animationDiv) {
animationDiv.empty();
animationDiv.dialog("destroy");
animationDiv = null;
}
}
CPO.makeEditor = function(container, options) {
var initial = "";
if (options.hasOwnProperty("initial")) {
initial = options.initial;
}
var textarea = jQuery("<textarea aria-hidden='true'>");
textarea.val(initial);
container.append(textarea);
var runFun = function (code, replOptions) {
options.run(code, {cm: CM}, replOptions);
};
var useLineNumbers = !options.simpleEditor;
var useFolding = !options.simpleEditor;
var gutters = !options.simpleEditor ?
["help-gutter", "CodeMirror-linenumbers", "CodeMirror-foldgutter"] :
[];
function reindentAllLines(cm) {
var last = cm.lineCount();
cm.operation(function() {
for (var i = 0; i < last; ++i) cm.indentLine(i);
});
}
var CODE_LINE_WIDTH = 100;
var rulers, rulersMinCol;
// place a vertical line in code editor, and not repl
if (options.simpleEditor) {
rulers = [];
} else{
rulers = [{color: "#317BCF", column: CODE_LINE_WIDTH, lineStyle: "dashed", className: "hidden"}];
rulersMinCol = CODE_LINE_WIDTH;
}
const mac = CodeMirror.keyMap.default === CodeMirror.keyMap.macDefault;
const modifier = mac ? "Cmd" : "Ctrl";
defaultKeyMap = CodeMirror.normalizeKeyMap({
"Shift-Enter": function(cm) { runFun(cm.getValue()); },
"Shift-Ctrl-Enter": function(cm) { runFun(cm.getValue()); },
"Tab": "indentAuto",
"Ctrl-I": reindentAllLines,
"Alt-Left": "goBackwardSexp",
"Alt-Right": "goForwardSexp",
"Ctrl-Left": "goBackwardToken",
"Ctrl-Right": "goForwardToken",
[`${modifier}-/`]: "toggleComment",
});
CPO.noVimKeyMap = CodeMirror.normalizeKeyMap({
"Esc Left": "goBackwardSexp",
"Esc Right": "goForwardSexp",
});
var cmOptions = {
extraKeys: defaultKeyMap,
indentUnit: 2,
tabSize: 2,
viewportMargin: Infinity,
lineNumbers: useLineNumbers,
matchKeywords: true,
matchBrackets: true,
styleSelectedText: true,
foldGutter: useFolding,
gutters: gutters,
lineWrapping: true,
logging: true,
rulers: rulers,
rulersMinCol: rulersMinCol,
scrollPastEnd: true,
};
cmOptions = merge(cmOptions, options.cmOptions || {});
var CM = CodeMirror.fromTextArea(textarea[0], cmOptions);
// we do this separately so we can more easily add and remove it for vim mode
CM.addKeyMap(CPO.noVimKeyMap);
function firstLineIsNamespace() {
const firstline = CM.getLine(0);
const match = firstline.match(CONTEXT_PREFIX);
return match !== null;
}
let namespacemark = null;
function setContextLine(newContextLine) {
var hasNamespace = firstLineIsNamespace();
if(!hasNamespace && namespacemark !== null) {
namespacemark.clear();
}
if(!hasNamespace) {
CM.replaceRange(newContextLine, { line:0, ch: 0}, {line: 0, ch: 0});
}
else {
CM.replaceRange(newContextLine, { line:0, ch: 0}, {line: 1, ch: 0});
}
}
if(!options.simpleEditor) {
const gutterQuestionWrapper = document.createElement("div");
gutterQuestionWrapper.className = "gutter-question-wrapper";
const gutterTooltip = document.createElement("span");
gutterTooltip.className = "gutter-question-tooltip";
gutterTooltip.innerText = "The use context line tells Pyret to load tools for a specific class context. It can be changed through the main Pyret menu. Most of the time you won't need to change this at all.";
const gutterQuestion = document.createElement("img");
gutterQuestion.src = "/img/question.png";
gutterQuestion.className = "gutter-question";
gutterQuestionWrapper.appendChild(gutterQuestion);
gutterQuestionWrapper.appendChild(gutterTooltip);
CM.setGutterMarker(0, "help-gutter", gutterQuestionWrapper);
CM.getWrapperElement().onmouseleave = function(e) {
CM.clearGutter("help-gutter");
}
// NOTE(joe): This seems to be the best way to get a hover on a mark: https://github.com/codemirror/CodeMirror/issues/3529
CM.getWrapperElement().onmousemove = function(e) {
var lineCh = CM.coordsChar({ left: e.clientX, top: e.clientY });
var markers = CM.findMarksAt(lineCh);
if (markers.length === 0) {
CM.clearGutter("help-gutter");
}
if (lineCh.line === 0 && markers[0] === namespacemark) {
CM.setGutterMarker(0, "help-gutter", gutterQuestionWrapper);
}
else {
CM.clearGutter("help-gutter");
}
}
CM.on("change", function(change) {
function doesNotChangeFirstLine(c) { return c.from.line !== 0; }
if(change.curOp.changeObjs && change.curOp.changeObjs.every(doesNotChangeFirstLine)) { return; }
var hasNamespace = firstLineIsNamespace();
if(hasNamespace) {
if(namespacemark) { namespacemark.clear(); }
namespacemark = CM.markText({line: 0, ch: 0}, {line: 1, ch: 0}, { attributes: { useline: true }, className: "useline", atomic: true, inclusiveLeft: true, inclusiveRight: false });
}
});
}
if (useLineNumbers) {
CM.display.wrapper.appendChild(mkWarningUpper()[0]);
CM.display.wrapper.appendChild(mkWarningLower()[0]);
}
getTopTierMenuitems();
return {
cm: CM,
setContextLine: setContextLine,
refresh: function() { CM.refresh(); },
run: function() {
runFun(CM.getValue());
},
focus: function() { CM.focus(); },
focusCarousel: null //initFocusCarousel
};
};
CPO.RUN_CODE = function() {
console.log("Running before ready", arguments);
};
function setUsername(target) {
return gwrap.load({name: 'plus',
version: 'v1',
}).then((api) => {
api.people.get({ userId: "me" }).then(function(user) {
var name = user.displayName;
if (user.emails && user.emails[0] && user.emails[0].value) {
name = user.emails[0].value;
}
target.text(name);
});
});
}
storageAPI.then(function(api) {
api.collection.then(function() {
$(".loginOnly").show();
$(".logoutOnly").hide();
setUsername($("#username"));
});
api.collection.fail(function() {
$(".loginOnly").hide();
$(".logoutOnly").show();
});
});
storageAPI = storageAPI.then(function(api) { return api.api; });
$("#fullConnectButton").click(function() {
reauth(
false, // Don't do an immediate load (this will require login)
true // Use the full set of scopes for this login
);
});
$("#connectButton").click(function() {
$("#connectButton").text("Connecting...");
$("#connectButton").attr("disabled", "disabled");
$('#connectButtonli').attr('disabled', 'disabled');
$("#connectButton").attr("tabIndex", "-1");
//$("#topTierUl").attr("tabIndex", "0");
getTopTierMenuitems();
storageAPI = createProgramCollectionAPI("code.pyret.org", false);
storageAPI.then(function(api) {
api.collection.then(function() {
$(".loginOnly").show();
$(".logoutOnly").hide();
document.activeElement.blur();
$("#bonniemenubutton").focus();
setUsername($("#username"));
if(params["get"] && params["get"]["program"]) {
var toLoad = api.api.getFileById(params["get"]["program"]);
console.log("Logged in and has program to load: ", toLoad);
loadProgram(toLoad);
programToSave = toLoad;
} else {
programToSave = Q.fcall(function() { return null; });
}
});
api.collection.fail(function() {
$("#connectButton").text("Connect to Google Drive");
$("#connectButton").attr("disabled", false);
$('#connectButtonli').attr('disabled', false);
//$("#connectButton").attr("tabIndex", "0");
document.activeElement.blur();
$("#connectButton").focus();
//$("#topTierUl").attr("tabIndex", "-1");
});
});
storageAPI = storageAPI.then(function(api) { return api.api; });
});
/*
initialProgram holds a promise for a Drive File object or null
It's null if the page doesn't have a #share or #program url
If the url does have a #program or #share, the promise is for the
corresponding object.
*/
var initialProgram = storageAPI.then(function(api) {
var programLoad = null;
if(params["get"] && params["get"]["program"]) {
enableFileOptions();
programLoad = api.getFileById(params["get"]["program"]);
programLoad.then(function(p) { showShareContainer(p); });
}
else if(params["get"] && params["get"]["share"]) {
logger.log('shared-program-load',
{
id: params["get"]["share"]
});
programLoad = api.getSharedFileById(params["get"]["share"]);
programLoad.then(function(file) {
// NOTE(joe): If the current user doesn't own or have access to this file
// (or isn't logged in) this will simply fail with a 401, so we don't do
// any further permission checking before showing the link.
file.getOriginal().then(function(response) {
console.log("Response for original: ", response);
var original = $("#open-original").show().off("click");
var id = response.result.value;
original.removeClass("hidden");
original.click(function() {
window.open(window.APP_BASE_URL + "/editor#program=" + id, "_blank");
});
});
});
}
else {
programLoad = null;
}
if(programLoad) {
programLoad.fail(function(err) {
console.error(err);
window.stickError("The program failed to load.");
});
return programLoad;
} else {
return null;
}
});
function setTitle(progName) {
document.title = progName + " - code.pyret.org";
$("#showFilename").text("File: " + progName);
}
CPO.setTitle = setTitle;
var filename = false;
$("#download a").click(function() {
var downloadElt = $("#download a");
var contents = CPO.editor.cm.getValue();
var downloadBlob = window.URL.createObjectURL(new Blob([contents], {type: 'text/plain'}));
if(!filename) { filename = 'untitled_program.arr'; }
if(filename.indexOf(".arr") !== (filename.length - 4)) {
filename += ".arr";
}
downloadElt.attr({
download: filename,
href: downloadBlob
});
$("#download").append(downloadElt);
});
function showModal(currentContext) {
function drawElement(input) {
const element = $("<div>");
const greeting = $("<p>");
const shared = $("<tt>shared-gdrive(...)</tt>");
const currentContextElt = $("<tt>" + currentContext + "</tt>");
greeting.append("Enter the context to use for the program, or choose “Cancel” to keep the current context of ", currentContextElt, ".");
const essentials = $("<tt>starter2024</tt>");
const list = $("<ul>")
.append($("<li>").append("The default is ", essentials, "."))
.append($("<li>").append("You might use something like ", shared, " if one was provided as part of a course."));
element.append(greeting);
element.append($("<p>").append(list));
const useContext = $("<tt>use context</tt>").css({ 'flex-grow': '0', 'padding-right': '1em' });
const inputWrapper = $("<div>").append(input).css({ 'flex-grow': '1' });
const entry = $("<div>").css({
display: 'flex',
'flex-direction': 'row',
'justify-content': 'flex-start',
'align-items': 'baseline'
});
entry.append(useContext).append(inputWrapper);
element.append(entry);
return element;
}
const namespaceResult = new modalPrompt({
title: "Choose a Context",
style: "text",
options: [
{
drawElement: drawElement,
submitText: "Change Namespace",
defaultValue: currentContext
}
]
});
namespaceResult.show((result) => {
if(!result) { return; }
CPO.editor.setContextLine("use context " + result.trim() + "\n");
});
}
$("#choose-context").on("click", function() {
const firstLine = CPO.editor.cm.getLine(0);
const contextLen = firstLine.match(CONTEXT_PREFIX);
showModal(contextLen === null ? "" : firstLine.slice(contextLen[0].length));
});
var TRUNCATE_LENGTH = 20;
function truncateName(name) {
if(name.length <= TRUNCATE_LENGTH + 1) { return name; }
return name.slice(0, TRUNCATE_LENGTH / 2) + "…" + name.slice(name.length - TRUNCATE_LENGTH / 2, name.length);
}
function updateName(p) {
filename = p.getName();
$("#filename").text(" (" + truncateName(filename) + ")");
setTitle(filename);
showShareContainer(p);
}
function loadProgram(p) {
programToSave = p;
return p.then(function(prog) {
if(prog !== null) {
updateName(prog);
if(prog.shared) {
window.stickMessage("You are viewing a shared program. Any changes you make will not be saved. You can use File -> Save a copy to save your own version with any edits you make.");
}
return prog.getContents();
}
else {
if(params["get"]["editorContents"] && !(params["get"]["program"] || params["get"]["share"])) {
return params["get"]["editorContents"];
}
else {
return CONTEXT_FOR_NEW_FILES;
}
}
});
}
function say(msg, forget) {
if (msg === "") return;
var announcements = document.getElementById("announcementlist");
var li = document.createElement("LI");
li.appendChild(document.createTextNode(msg));
announcements.insertBefore(li, announcements.firstChild);
if (forget) {
setTimeout(function() {
announcements.removeChild(li);
}, 1000);
}
}
function sayAndForget(msg) {
console.log('doing sayAndForget', msg);
say(msg, true);
}
function cycleAdvance(currIndex, maxIndex, reverseP) {
var nextIndex = currIndex + (reverseP? -1 : +1);
nextIndex = ((nextIndex % maxIndex) + maxIndex) % maxIndex;
return nextIndex;
}
function populateFocusCarousel(editor) {
if (!editor.focusCarousel) {
editor.focusCarousel = [];
}
var fc = editor.focusCarousel;
var docmain = document.getElementById("main");
if (!fc[0]) {
var toolbar = document.getElementById('Toolbar');
fc[0] = toolbar;
//fc[0] = document.getElementById("headeronelegend");
//getTopTierMenuitems();
//fc[0] = document.getElementById('bonniemenubutton');
}
if (!fc[1]) {
var docreplMain = docmain.getElementsByClassName("replMain");
var docreplMain0;
if (docreplMain.length === 0) {
docreplMain0 = undefined;
} else if (docreplMain.length === 1) {
docreplMain0 = docreplMain[0];
} else {
for (var i = 0; i < docreplMain.length; i++) {
if (docreplMain[i].innerText !== "") {
docreplMain0 = docreplMain[i];
}
}
}
fc[1] = docreplMain0;
}
if (!fc[2]) {
var docrepl = docmain.getElementsByClassName("repl");
var docreplcode = docrepl[0].getElementsByClassName("prompt-container")[0].
getElementsByClassName("CodeMirror")[0];
fc[2] = docreplcode;
}
if (!fc[3]) {
fc[3] = document.getElementById("announcements");
}
}
function cycleFocus(reverseP) {
//console.log('doing cycleFocus', reverseP);
var editor = this.editor;
populateFocusCarousel(editor);
var fCarousel = editor.focusCarousel;
var maxIndex = fCarousel.length;
var currentFocusedElt = fCarousel.find(function(node) {
if (!node) {
return false;
} else {
return node.contains(document.activeElement);
}
});
var currentFocusIndex = fCarousel.indexOf(currentFocusedElt);
var nextFocusIndex = currentFocusIndex;
var focusElt;
do {
nextFocusIndex = cycleAdvance(nextFocusIndex, maxIndex, reverseP);
focusElt = fCarousel[nextFocusIndex];
//console.log('trying focusElt', focusElt);
} while (!focusElt);
var focusElt0;
if (focusElt.classList.contains('toolbarregion')) {
//console.log('settling on toolbar region')
getTopTierMenuitems();
focusElt0 = document.getElementById('bonniemenubutton');
} else if (focusElt.classList.contains("replMain") ||
focusElt.classList.contains("CodeMirror")) {
//console.log('settling on defn window')
var textareas = focusElt.getElementsByTagName("textarea");
//console.log('txtareas=', textareas)
//console.log('txtarea len=', textareas.length)
if (textareas.length === 0) {
//console.log('I')
focusElt0 = focusElt;
} else if (textareas.length === 1) {
//console.log('settling on inter window')
focusElt0 = textareas[0];
} else {
//console.log('settling on defn window')
/*
for (var i = 0; i < textareas.length; i++) {
if (textareas[i].getAttribute('tabIndex')) {
focusElt0 = textareas[i];
}
}
*/
focusElt0 = textareas[textareas.length-1];
focusElt0.removeAttribute('tabIndex');
}
} else {
//console.log('settling on announcement region', focusElt)
focusElt0 = focusElt;
}
document.activeElement.blur();
focusElt0.click();
focusElt0.focus();
//console.log('(cf)docactelt=', document.activeElement);
}
var programLoaded = loadProgram(initialProgram);
var programToSave = initialProgram;
function showShareContainer(p) {
//console.log('called showShareContainer');
if(!p.shared) {
$("#shareContainer").empty();
$('#publishli').show();
$("#shareContainer").append(shareAPI.makeShareLink(p));
getTopTierMenuitems();
}
}
function nameOrUntitled() {
return filename || "Untitled";
}
function autoSave() {
programToSave.then(function(p) {
if(p !== null && !p.shared) { save(); }
});
}
function enableFileOptions() {
$("#filemenuContents *").removeClass("disabled");
}
function menuItemDisabled(id) {
return $("#" + id).hasClass("disabled");
}
function newEvent(e) {
window.open(window.APP_BASE_URL + "/editor");
}
function saveEvent(e) {
if(menuItemDisabled("save")) { return; }
return save();
}
/*
save : string (optional) -> undef
If a string argument is provided, create a new file with that name and save
the editor contents in that file.
If no filename is provided, save the existing file referenced by the editor
with the current editor contents. If no filename has been set yet, just
set the name to "Untitled".
*/
function save(newFilename) {
var useName, create;
if(newFilename !== undefined) {
useName = newFilename;
create = true;
}
else if(filename === false) {
filename = "Untitled";
create = true;
}
else {
useName = filename; // A closed-over variable
create = false;
}
window.stickMessage("Saving...");
var savedProgram = programToSave.then(function(p) {
if(p !== null && p.shared && !create) {
return p; // Don't try to save shared files
}
if(create) {
programToSave = storageAPI
.then(function(api) { return api.createFile(useName); })
.then(function(p) {
// showShareContainer(p); TODO(joe): figure out where to put this
history.pushState(null, null, "#program=" + p.getUniqueId());
updateName(p); // sets filename
enableFileOptions();
return p;
});
return programToSave.then(function(p) {
return save();
});
}
else {
return programToSave.then(function(p) {
if(p === null) {
return null;
}
else {
return p.save(CPO.editor.cm.getValue(), false);
}
}).then(function(p) {
if(p !== null) {
window.flashMessage("Program saved as " + p.getName());
}
return p;
});
}
});
savedProgram.fail(function(err) {
window.stickError("Unable to save", "Your internet connection may be down, or something else might be wrong with this site or saving to Google. You should back up any changes to this program somewhere else. You can try saving again to see if the problem was temporary, as well.");
console.error(err);
});
return savedProgram;
}
function saveAs() {
if(menuItemDisabled("saveas")) { return; }
programToSave.then(function(p) {
var name = p === null ? "Untitled" : p.getName();
var saveAsPrompt = new modalPrompt({
title: "Save a copy",
style: "text",
submitText: "Save",
narrow: true,
options: [
{
message: "The name for the copy:",
defaultValue: name
}
]
});
return saveAsPrompt.show().then(function(newName) {
if(newName === null) { return null; }
window.stickMessage("Saving...");
return save(newName);
}).
fail(function(err) {
console.error("Failed to rename: ", err);
window.flashError("Failed to rename file");
});
});
}
function rename() {
programToSave.then(function(p) {
var renamePrompt = new modalPrompt({
title: "Rename this file",
style: "text",
narrow: true,
submitText: "Rename",
options: [
{
message: "The new name for the file:",
defaultValue: p.getName()
}
]
});
// null return values are for the "cancel" path
return renamePrompt.show().then(function(newName) {
if(newName === null) {
return null;
}
window.stickMessage("Renaming...");
programToSave = p.rename(newName);
return programToSave;
})
.then(function(p) {
if(p === null) {
return null;
}
updateName(p);
window.flashMessage("Program saved as " + p.getName());
})
.fail(function(err) {
console.error("Failed to rename: ", err);
window.flashError("Failed to rename file");
});
})
.fail(function(err) {
console.error("Unable to rename: ", err);
});
}
$("#runButton").click(function() {
CPO.autoSave();
});
$("#new").click(newEvent);
$("#save").click(saveEvent);
$("#rename").click(rename);
$("#saveas").click(saveAs);
var focusableElts = $(document).find('#header .focusable');
//console.log('focusableElts=', focusableElts)
var theToolbar = $(document).find('#Toolbar');
function getTopTierMenuitems() {
//console.log('doing getTopTierMenuitems')
var topTierMenuitems = $(document).find('#header ul li.topTier').toArray();
topTierMenuitems = topTierMenuitems.
filter(elt => !(elt.style.display === 'none' ||
elt.getAttribute('disabled') === 'disabled'));
var numTopTierMenuitems = topTierMenuitems.length;
for (var i = 0; i < numTopTierMenuitems; i++) {
var ithTopTierMenuitem = topTierMenuitems[i];
var iChild = $(ithTopTierMenuitem).children().first();
//console.log('iChild=', iChild);
iChild.find('.focusable').
attr('aria-setsize', numTopTierMenuitems.toString()).
attr('aria-posinset', (i+1).toString());
}
return topTierMenuitems;
}
function updateEditorHeight() {
var toolbarHeight = document.getElementById('topTierUl').offsetHeight;
// gets bumped to 67 on initial resize perturbation, but actual value is indeed 40
if (toolbarHeight < 80) toolbarHeight = 40;
toolbarHeight += 'px';
document.getElementById('REPL').style.paddingTop = toolbarHeight;
var docMain = document.getElementById('main');
var docReplMain = docMain.getElementsByClassName('replMain');
if (docReplMain.length !== 0) {
docReplMain[0].style.paddingTop = toolbarHeight;
}
}
$(window).on('resize', updateEditorHeight);
function insertAriaPos(submenu) {
//console.log('doing insertAriaPos', submenu)
var arr = submenu.toArray();
//console.log('arr=', arr);
var len = arr.length;
for (var i = 0; i < len; i++) {
var elt = arr[i];
//console.log('elt', i, '=', elt);
elt.setAttribute('aria-setsize', len.toString());
elt.setAttribute('aria-posinset', (i+1).toString());
}
}
document.addEventListener('click', function () {
hideAllTopMenuitems();
});
theToolbar.click(function (e) {
e.stopPropagation();
});
theToolbar.keydown(function (e) {
//console.log('toolbar keydown', e);
//most any key at all
var kc = e.keyCode;
if (kc === 27) {
// escape
hideAllTopMenuitems();
//console.log('calling cycleFocus from toolbar')
CPO.cycleFocus();
e.stopPropagation();
} else if (kc === 9 || kc === 37 || kc === 38 || kc === 39 || kc === 40) {
// an arrow
var target = $(this).find('[tabIndex=-1]');
getTopTierMenuitems();
document.activeElement.blur(); //needed?
target.first().focus(); //needed?
//console.log('docactelt=', document.activeElement);
e.stopPropagation();
} else {
hideAllTopMenuitems();
}
});
function clickTopMenuitem(e) {
hideAllTopMenuitems();
var thisElt = $(this);
//console.log('doing clickTopMenuitem on', thisElt);
var topTierUl = thisElt.closest('ul[id=topTierUl]');
if (thisElt[0].hasAttribute('aria-hidden')) {
return;
}
if (thisElt[0].getAttribute('disabled') === 'disabled') {
return;
}
//var hiddenP = (thisElt[0].getAttribute('aria-expanded') === 'false');
//hiddenP always false?
var thisTopMenuitem = thisElt.closest('li.topTier');
//console.log('thisTopMenuitem=', thisTopMenuitem);
var t1 = thisTopMenuitem[0];
var submenuOpen = (thisElt[0].getAttribute('aria-expanded') === 'true');
if (!submenuOpen) {
//console.log('hiddenp true branch');
hideAllTopMenuitems();
thisTopMenuitem.children('ul.submenu').attr('aria-hidden', 'false').show();
thisTopMenuitem.children().first().find('[aria-expanded]').attr('aria-expanded', 'true');
} else {
//console.log('hiddenp false branch');
thisTopMenuitem.children('ul.submenu').attr('aria-hidden', 'true').hide();
thisTopMenuitem.children().first().find('[aria-expanded]').attr('aria-expanded', 'false');
}
e.stopPropagation();
}
var expandableElts = $(document).find('#header [aria-expanded]');
expandableElts.click(clickTopMenuitem);
function hideAllTopMenuitems() {
//console.log('doing hideAllTopMenuitems');
var topTierUl = $(document).find('#header ul[id=topTierUl]');
topTierUl.find('[aria-expanded]').attr('aria-expanded', 'false');
topTierUl.find('ul.submenu').attr('aria-hidden', 'true').hide();
}
var nonexpandableElts = $(document).find('#header .topTier > div > button:not([aria-expanded])');
nonexpandableElts.click(hideAllTopMenuitems);
function switchTopMenuitem(destTopMenuitem, destElt) {
//console.log('doing switchTopMenuitem', destTopMenuitem, destElt);
//console.log('dtmil=', destTopMenuitem.length);
hideAllTopMenuitems();
if (destTopMenuitem && destTopMenuitem.length !== 0) {
var elt = destTopMenuitem[0];
var eltId = elt.getAttribute('id');
destTopMenuitem.children('ul.submenu').attr('aria-hidden', 'false').show();
destTopMenuitem.children().first().find('[aria-expanded]').attr('aria-expanded', 'true');
}
if (destElt) {
//destElt.attr('tabIndex', '0').focus();
destElt.focus();
}
}
var showingHelpKeys = false;
function showHelpKeys() {
showingHelpKeys = true;
$('#help-keys').fadeIn(100);
reciteHelp();
}
focusableElts.keydown(function (e) {
//console.log('focusable elt keydown', e);