-
Notifications
You must be signed in to change notification settings - Fork 44
/
team.html
846 lines (737 loc) · 42.2 KB
/
team.html
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
<!DOCTYPE html>
<html style="height:100%">
<head>
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="https://woofjs.com/create">
<meta name="twitter:title" content="WoofJS">
<meta name="twitter:description" content="WoofJS is a Scratch-inspired Javascript library for making games.">
<meta name="twitter:image" content="./images/qIgC8Ae.png">
<meta property="og:image" content="./images/qIgC8Ae.png">
<meta property="og:title" content="WoofJS">
<meta property="og:description" content="WoofJS is a Scratch-inspired Javascript library for making games.">
<script src="//load.sumome.com/" data-sumo-site-id="44245233c319d8fe9fb7ce8c7ed64db9381aa56477888a10319261f655cfffe2" async="async"></script>
<meta charset="utf-8">
<title>WoofJS</title>
<link rel="shortcut icon" type="image/png" href="./favicon.png"/>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.4.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/ui/live/0.5/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/live/0.5/firebase-ui-auth.css" />
<script type="text/javascript" src="https://rawcdn.githack.com/showdownjs/showdown/984942e239c9bda522b9c5544aba72647983b3f1/dist/showdown.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="./vendor/codemirror/codemirror.css">
<script type="text/javascript" src="./vendor/codemirror/codemirror.js"></script>
<script type="text/javascript" src="./vendor/codemirror/javascript.js"></script>
<script type="text/javascript" src="./vendor/codemirror/closebrackets.js"></script>
<script type="text/javascript" src="./vendor/codemirror/javascript-hint.js"></script>
<script type="text/javascript" src="./vendor/codemirror/javascript-lint.js"></script>
<script type="text/javascript" src="./vendor/codemirror/matchbrackets.js"></script>
<script type="text/javascript" src="./vendor/codemirror/search.js"></script>
<script type="text/javascript" src="./vendor/codemirror/searchcursor.js"></script>
<script type="text/javascript" src="./vendor/codemirror/show-hint.js"></script>
<script type="text/javascript" src="./vendor/codemirror/comment.js"></script>
<script type="text/javascript" src="./vendor/codemirror/sublime.js"></script>
<script type="text/javascript" src="./vendor/codemirror/foldcode.js"></script>
<link rel="stylesheet" href="./vendor/codemirror/foldgutter.css" />
<script src="./vendor/codemirror/foldcode.js"></script>
<script src="./vendor/codemirror/foldgutter.js"></script>
<script src="./vendor/codemirror/brace-fold.js"></script>
<script src="./vendor/codemirror/comment-fold.js"></script>
<link rel="stylesheet" href="./vendor/codemirror/dialog.css">
<link rel="stylesheet" href="./vendor/codemirror/show-hint.css">
<script src="./vendor/codemirror/dialog.js"></script>
<link rel="stylesheet" href="./vendor/codemirror/lint.css">
<script src="./vendor/codemirror/jshint.min.js"></script>
<script src="./vendor/codemirror/lint.js"></script>
<script src="./vendor/codemirror/scrollpastend.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script data-presets="es2015" src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.14.0/babel.min.js"></script>
<script src="https://rawcdn.githack.com/beautify-web/js-beautify/1b52eb1f90daaefa6ff0fa7736f97fbfc58093c1/js/lib/beautify.js"></script>
<!-- Firepad -->
<link rel="stylesheet" href="https://cdn.firebase.com/libs/firepad/1.4.0/firepad.css" />
<script src="https://cdn.firebase.com/libs/firepad/1.4.0/firepad.min.js"></script>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
#page {
position: relative;
display: flex;
flex-flow: row wrap;
align-items: stretch;
align-content: stretch;
height: 100%;
}
body {
background-color: #fff;
font-family: sans-serif;
}
h1 {
font-weight: normal;
font-size: 25px;
}
.CodeMirror {
font-size: 13px;
flex: 1 0 auto;
display: flex;
flex-flow: column wrap;
align-items: stretch;
align-content: stretch;
width: 100%;
}
.CodeMirror-scroll {
display: flex;
flex-flow: column wrap;
align-items: stretch;
align-content: stretch;
flex: 1 0 auto;
overflow: auto;
width: 100%;
}
iframe {
border: none;
flex: 1 0 auto;
width: 100%;
}
#navbar {
background-color: #6DC0F2;
position: absolute;
width: 100%;
z-index: 1;
top: 0;
height: 55px;
display: flex;
align-items: center;
justify-content: space-between;
}
#clean-up {
background-color: #80CFFF;
border: none;
color: white;
}
.btn-default {
background-color: #49A6DF;
border: none;
color: white;
}
#container {
width: 100%;
display: flex;
flex-direction: row;
margin-top: 55px;
}
#previewbar, #docsbar, #projectbar, #codebar {
flex-grow: 0.65;
align-items: center;
display: none;
width: 25px;
flex-direction: column;
justify-content: center;
}
#output, #docs, #projects, #code {
flex-flow: column;
resize: none;
flex: 10 1 25%;
}
#code {
word-wrap: break-word;
width: 25%;
}
#PreviewNav, #DocsNav, #ProjectsNav, #CodeNav {
height: 25px;
text-align: center;
color: white;
font-size: 1.1em;
display: flex;
justify-content: space-between;
}
#previewbar, #PreviewNav {
background-color:#4875D1;
}
#docsbar, #DocsNav {
background-color: #7F68D5;
}
#projectbar, #ProjectsNav {
background-color: #AD5FC2;
}
#codebar, #CodeNav {
background-color: #49A6DF;
}
@media all and (max-width: 600px) {
#login {
margin-right: 5px;
}
fieldset {
display: none;
}
}
#pop {
cursor: pointer;
}
@keyframes glowing {
0% { background-color: #B20000; box-shadow: 0 0 1px #c9302c; }
50% { background-color: #FF0000; box-shadow: 0 0 2px #FF0000; }
100% { background-color: #B20000; box-shadow: 0 0 1px #c9302c; }
}
#error {
display: none;
color: white;
margin-right: 5px;
}
.rotate {
color: #FFFFFF;
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);
}
a.powered-by-firepad {
display: none;
}
#saveStatus {
transition: color 2s;
}
</style>
</head>
<body>
<div id="page">
<div id="navbar">
<button style="background-color: #80CFFF; color: white; border-radius:4px; border:none; margin:8px" class="btn btn-medium btn-info" type="button" id="login" onclick="window.open('./login.html', 'Sign In', 'width=500,height=500')">Login / Sign Up</button>
<div style="margin-left: 5px" id="logggedin" class="hide dropdown">
<button class="btn btn-medium btn-info dropdown-toggle" type="button" id="loggedin-name" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"></button>
<ul class="dropdown-menu" aria-labelledby="loggedin-name">
<li><a href="./create.html">New Project</a></li>
<li><a href="./team.html">New Team Project <span class="label label-success">beta</span></a></li>
<li><a target="_blank" id="login-projects">My Projects</a></li>
<li onclick="firebase.auth().signOut()"><a>Logout</a></li>
<li role="separator" class="divider"></li>
<li class="dropdown-header">Recent Projects</li>
<li v-for="project in projects.slice(0,10)"><a :href="'/create.html#' + project.key">{{project.key}}</a></li>
</ul>
</div>
<img style= "width:160px; height: 40px;" src="./images/logowhite.png">
<span style="margin:8px" id="save">
<button id="clean-up" class="btn btn-medium btn-default" @click="cleanAll()" style="display: none" :style="{display: canClean ? 'inline-block' : 'none'}"><span class="glyphicon glyphicon-align-left"></span> Clean Code</button>
<button id="error" class="btn btn-danger" @click="showError()" :style="{display: error ? 'inline-block' : 'none', animation: seenError ? 'none' : 'glowing 1200ms infinite'}"><span class="glyphicon glyphicon-exclamation-sign"></span> Error</button>
<span id="saveStatus" :style="{display: 'inline-block', color: status != 'DIRTY' ? 'green' : 'yellow'}" style="display: none; margin: 10px"><span class="glyphicon" :class="styles" style="margin-right: 5px;"></span>{{ status != "DIRTY" ? 'Saved' : 'Not Saved' }}</span>
<!--<button style="display: none" :style="{display: 'inline-block'}" style="margin-right: 5px; background-color: purple !important; ; border:none; color:white; " class="btn btn-medium" :class="styles" onclick="save()"><span class="glyphicon glyphicon-upload"></span> Publish</button>-->
</span>
</div>
<div id="container">
<div id="previewbar" v-show="previewbar" @click="previewbar= !previewbar" :style="{display: 'flex'}">
<span class="rotate" style="font-size: 1.65em">Preview</span>
</div>
<div v-show="outputPane" :style="{display: !previewbar ? 'flex' : 'none'}" id="output">
<div id="PreviewNav">
<span style="margin-left:8px; margin-top:4px">Preview</span>
<span style="margin-right:8px">
<span style="display: none; font-family: monospace; font-size: 11px" :style="{display: status ? 'inline-block' : 'none'}">mouseX: {{mouseX}}</span>
<span style="display: none; font-family: monospace; font-size: 11px" :style="{display: status ? 'inline-block' : 'none'}">mouseY: {{mouseY}}</span>
<img onclick="runCode(); focusPreview()" id="pop" style="margin: 2px; width: 17px; height:17px" src="./images/refresh.png" title="Reload">
<img onclick="popout()" id="pop" style="margin: 2px; width: 17px; height:17px" src="./images/pop.png" title="Open in new tab">
<img @click="previewbar = !previewbar" style="margin: 5px; width: 16px; height:18px; cursor:pointer" src="./images/minimize.png" title="Minimize">
</span>
</div>
<iframe scrolling="no" id="preview"></iframe>
</div>
<div id="docsbar" v-show="docsbar" @click="docsbar= !docsbar" :style="{display: 'flex'}">
<span class="rotate" style="font-size: 1.65em">Documentation</span>
</div>
<div v-show="docsPane" :style="{display: !docsbar ? 'flex' : 'none'}" id="docs">
<div id="DocsNav">
<span style="margin-left:8px; margin-top:4px">Documentation</span>
<span style="margin-right:8px">
<img @click="docsbar = !docsbar" style="margin-left:5px; width: 16px; height:18px; cursor:pointer" src="./images/minimize.png" title="Minimize">
</span>
</div>
<iframe src="./docs/index.html" id="scratch"></iframe>
</div>
<div id="projectbar" v-show="projectbar" @click="projectbar= !projectbar" :style="{display: 'flex'}" @click="projectsPane = !projectsPane">
<span class="rotate" style="font-size:1.65em">Tutorials</span>
</div>
<div v-show="projectsPane" :style="{display: !projectbar ? 'flex' : 'none'}" :style="{display: 'flex'}" id="projects">
<div id="ProjectsNav">
<span style="margin-left:8px; margin-top:4px">Tutorials</span>
<span style="margin-right:8px">
<img @click="projectbar = !projectbar" style="margin: 5px; width: 16px; height:18px; cursor:pointer" src="./images/minimize.png" title="Minimize">
</span>
</div>
<iframe id="projectsIframe" src="//coding.space/woof/index.html"></iframe>
</div>
<div id="codebar" v-show="codebar" @click="codebar= !codebar" :style="{display: 'flex'}">
<span class="rotate" style="font-size:1.65em">Code</span>
</div>
<div v-show="codePane" :style="{display: !codebar ? 'flex' : 'none'}" id="code">
<div id="CodeNav">
<span style="margin-left:8px; margin-top:4px">Code</span>
<span style="margin-right:8px">
<img @click="codebar = !codebar" style="margin: 5px; width: 16px; height:18px; cursor:pointer" src="./images/minimize.png" title="Minimize">
</span>
</div>
</div>
</div>
</div>
<script>
// TODO check if the name exists on creating new project
// TODO backwards / forwards in edits
// TODO blog post
var getID = function() {
// returns the name of a project, not inlcuding the current revision
return window.location.hash.substring(1, window.location.hash.length).split("/")[0];
}
var getIDWithRevision = function() {
// returns the name of a project, not inlcuding the current revision
return window.location.hash.substring(1, window.location.hash.length);
}
var getCurrentRevisionCode = function(revisions) {
// returns the code that corresponds to the current project and revision
var revision = parseInt(window.location.hash.substring(1, window.location.hash.length).split("/")[1])
var keys = Object.keys(revisions)
if (keys.length > 1){
keys = keys.slice(1, keys.length)
}
var key
if (!isNaN(revision) && (revision !== 0 && revision !== -1 * keys.length) && Math.abs(revision) < keys.length + 1){
if (revision < 0){
revision = keys.length + revision // -1 gives the previous revision
}
key = keys[revision - 1]
} else {
key = keys[keys.length - 1]
}
return revisions[key].code
}
var currentHash = window.location.hash
var app = new Vue({
el: '#page',
data: {
code: "",
status: "NEW",
error: undefined,
projects: [],
codePane: true,
outputPane: true,
projectsPane: false,
docsPane: true,
projectbar: true,
previewbar: false,
docsbar:false,
codebar:false,
mouseX: 0,
mouseY: 0,
seenError: true,
},
computed: {
styles : function() { return {
// styles for the "Save" icon
'glyphicon-floppy-remove': this.status == 'DIRTY',
'glyphicon-floppy-saved': this.status == 'SAVED' || this.status == "NEW"
} },
canClean: function(){
// whether or not the code can be "cleaned" or if its already pristine
return !this.error && this.code != js_beautify(this.code, {space_after_anon_function: true, indent_size: 2, indent_with_tabs: false })
},
},
methods: {
getID: getID,
showError: function(){
this.seenError = true
if (this.error.message.includes('Uncaught ReferenceError: sprite1 is not defined')) {
var spriteName = prompt("Error on line " + this.error.lineno + "\n\n" + "You need to rename 'sprite1'. What would you like to name it?", "unicornSprite");
if (spriteName !== null) {
editor.setValue(editor.getValue().replace(/sprite1/g, spriteName));
}
}
else if (this.error.message.includes("Uncaught ReferenceError")) {
var message = this.error.message.replace("Uncaught ReferenceError: ", "")
alert("Error on line " + this.error.lineno + "\n\n" + message + ". Check the spelling of your variable definitions.")
}
else {
alert("Error on line " + this.error.lineno + "\n\n" + this.error.message)
}
},
cleanAll: function(){
var beautiful = js_beautify(editor.getValue(), {space_after_anon_function: true, indent_size: 2, indent_with_tabs: false })
editor.setValue(beautiful)
},
},
watch: {
error: function(newError) {
if (newError && newError.lineno) {
CodeMirror.commands.markGutter(editor, "error", newError.lineno, newError.message)
}
}
}
})
var myCode = false
scratch.src = scratch.src // the documentation sometimes doesn't load unless you remind it to here, strange VueJS bug
projectsIframe.src = projectsIframe.src // ditto for the project's iframe
var config = {
apiKey: "AIzaSyBYHv7dCiD0bWiHRlcp4VIZCIqzoMnB4yY",
authDomain: "woofjs-d1b27.firebaseapp.com",
databaseURL: "https://woofjs-d1b27.firebaseio.com",
storageBucket: "woofjs-d1b27.appspot.com",
messagingSenderId: "397293370524"
};
firebase.initializeApp(config);
function handleLogin(userName, uid) {
$('#loggedin-name').html(userName + ' <span class="caret"></span>')
$('#login-projects').attr("href", "./user.html#" + uid )
$('#logggedin').removeClass("hide")
$('#login').addClass('hide')
}
function handleLogout() {
$('#logggedin').addClass("hide")
$('#login').removeClass("hide")
myCode = false
}
var authChanged = false
firebase.auth().onAuthStateChanged(function(user) {
if (!authChanged){
authChanged = true
}
if (user){
ga('set', 'userId', user.uid);
firepad.setUserId(user.uid)
handleLogin(user.displayName, user.uid)
firebase.database().ref('/user/' + user.uid).once('value').then(function(snapshot) {
var userVal = snapshot.val()
// if the user is logged in, and we don't have their name/email in our database, save it now
if (!userVal) {
firebase.database().ref("/user/" + user.uid).set({
displayName: user.displayName,
email: user.email,
createdDate: firebase.database.ServerValue.TIMESTAMP
})
}
if (userVal && userVal.team && Object.values(userVal.team).includes(getID())) {
// do nothing because we've already added this project to the user
} else {
firebase.database().ref("/user/" + user.uid + "/team/").push(getID())
}
})
// this puts the user's most recent project under their name
firebase.database().ref('/code/').orderByChild("--uid").equalTo(user.uid).once('value').then(function(snapshot) {
if (snapshot.val()){
app.projects = []
for (var key in snapshot.val()) {
var project = snapshot.val()[key]
var versions = Object.keys(project)
var t = project[versions[versions.length-1]].time
app.projects.push({key: key, time: t, code: project.code})
}
}
// sort the proejcts by most recently touched
app.projects.sort(function(a,b) {
if (a.time < b.time)
return 1;
if (a.time > b.time)
return -1;
return 0;
})
});
} else {
handleLogout()
}
});
var makeClean = function() {
app.status = "SAVED"
currentHash = window.location.hash
}
var makeDirty = function() {
app.status = "DIRTY"
}
var popout = function() {
if (app.status != "DIRTY"){
window.open("./team-full.html#" + getIDWithRevision(), "_blank")
} else {
alert("You must save your project to open it in a new window.")
}
}
// we add the project name to the hash on save
// this code prevents that from triggering a page reload
window.addEventListener("hashchange", function() {
if (currentHash != window.location.hash) {
window.location.reload()
}
})
var save = function(){
if (app.status == "SAVED") { return }
if (editor.getValue().startsWith("// Loading...")){
return // don't allow students to save projects that haven't loaded
}
var name
if (myCode) {
name = getID()
} else {
name = window.prompt('Choose a name for your project. You cannot include ".", "#", "$", "[", "]", or spaces in the name of your project.', "my-project") || '';
}
if (name.includes('.') || name.includes('/') || name.includes('$') || name.includes("#") || name.includes("[") || name.includes("]") || name.includes(" ")){
alert('You cannot include ".", "#", "$", "[", "]", or spaces in the name of your project. Try to save again.')
} else if (name) {
firebase.database().ref('/code/' + name).limitToLast(1).once('value').then(function(snapshot) {
if (snapshot.val()){
if (firebase.auth().currentUser && snapshot.val()[Object.keys(snapshot.val())[0]].uid == firebase.auth().currentUser.uid) {
// if the project exists and you own it, push the new code as a revision
firebase.database().ref().child("/code/" + name).push({
code: editor.getValue(),
time: firebase.database.ServerValue.TIMESTAMP,
uid: firebase.auth().currentUser && firebase.auth().currentUser.uid
}).then(function(){
window.location.hash = name
makeClean()
}).catch(function(error){
alert("Unable to save project: " + error)
});
} else {
alert("That project name has already been taken. Try another one.")
}
} else {
// else create a new project and push this code as the first revision
firebase.database().ref().child("/code/" + name + "/--uid").set(firebase.auth().currentUser && firebase.auth().currentUser.uid)
firebase.database().ref().child("/code/" + name).push({
code: editor.getValue(),
time: firebase.database.ServerValue.TIMESTAMP,
uid: firebase.auth().currentUser && firebase.auth().currentUser.uid
}).then(function(){
window.location.hash = name
myCode = firebase.auth().currentUser
makeClean()
}).catch(function(error){
alert("Unable to save project: " + error)
});
}
});
}
};
// keyboard shortcuts
var mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
var ctrl = mac ? "Cmd-" : "Ctrl-";
var keymap = {}
keymap[ctrl + "B"] = function(cm) {
var beautiful = js_beautify(cm.getSelection(), {space_after_anon_function: true, indent_size: 2, indent_with_tabs: false })
cm.replaceSelection(beautiful)
}
keymap.Tab = function(cm) {
var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
cm.replaceSelection(spaces, "end", "+input");
}
var editor = CodeMirror(document.getElementById('code'), {
mode: "javascript",
//value: editorVal,
lineNumbers: true,
lineWrapping: false,
theme: "eclipse",
tabSize: 2,
indentUnit: 2,
indentWithTabs: false,
electricChars: true,
keyMap: "sublime",
autoCloseBrackets: true,
matchBrackets: true,
autofocus: true,
smartIndent: true,
foldGutter: true,
gutters: ["CodeMirror-lint-markers", "CodeMirror-foldgutter"],
extraKeys: keymap,
lint: {
delay: 800,
options: {
"esnext": true,
"asi": true
}
},
});
// It's probably a bad idea to have a super large data structure like this in JS
// One bad side effect is that it turns off syntax highlighting in the code below it
const adjs = ["adorable","beautiful","clean","drab","elegant","fancy","glamorous","handsome","long","magnificent","old-fashioned","plain","quaint","sparkling","ugliest","unsightly","wide-eyed","red","orange","yellow","green","blue","purple","gray","black","white","alive","better","careful","clever","dead","easy","famous","gifted","helpful","important","inexpensive","mushy","odd","powerful","rich","shy","tender","uninterested","vast","wrong","angry","clumsy","defeated","embarrassed","fierce","grumpy","helpless","jealous","lazy","mysterious","nervous","obnoxious","panicky","repulsive","scary","thoughtless","uptight","worried","agreeable","brave","calm","delightful","eager","faithful","gentle","happy","jolly","kind","lively","nice","obedient","proud","relieved","silly","thankful","victorious","witty","zealous","broad","chubby","crooked","curved","deep","flat","high","hollow","low","narrow","round","shallow","skinny","square","steep","straight","wide","big","colossal","fat","gigantic","great","huge","immense","large","little","mammoth","massive","miniature","petite","puny","scrawny","short","small","tall","teeny","teeny-tiny","tiny","cooing","deafening","faint","hissing","loud","melodic","noisy","purring","quiet","raspy","screeching","thundering","voiceless","whispering","ancient","brief","early","fast","late","long","modern","old","old-fashioned","quick","rapid","short","slow","swift","young","bitter","delicious","fresh","greasy","juicy","hot","icy","loose","melted","nutritious","prickly","rainy","rotten","salty","sticky","strong","sweet","tart","tasteless","uneven","weak","wet","wooden","yummy","boiling","breeze","broken","bumpy","chilly","cold","cool","creepy","crooked","cuddly","curly","damaged","damp","dirty","dry","dusty","filthy","flaky","fluffy","freezing","hot","warm","wet","abundant","empty","few","full","heavy","light","many","numerous","sparse","substantial"]
const nouns = ["aardvark","air","airplane","airport","alarm","alligator","almond","alphabet","ambulance","animal","ankle","ant","anteater","antelope","ape","apple","arm","armchair","arrow","asparagus","baby","back","backbone","bacon","badge","badger","bag","bagpipe","bait","bakery","ball","balloon","bamboo","banana","band","bandana","banjo","bank","baseball","basket","basketball","bat","bath","bathroom","bathtub","battery","battle","bay","beach","bead","bean","bear","beard","beast","beat","beauty","beaver","bed","bedroom","bee","beef","beetle","bell","belt","bench","beret","berry","bicycle","bike","bird","birthday","bite","blade","blanket","blob","block","blood","blouse","boar","board","bus","bush","butter","button","cabbage","cactus","cafe","cake","calculator","calendar","calf","camel","camera","camp","candle","canoe","canvas","cap","captain","car","card","cardboard","cardigan","carpenter","carrot","carton","cartoon","cat","caterpillar","cathedral","cattle","cauliflower","cave","CD","ceiling","celery","cello","cement","cemetery","cereal","boat","bobcat","body","bone","bonsai","book","bookcase","booklet","boot","border","bottle","bottom","boundary","bow","bowling","box","boy","brain","brake","branch","brass","bread","break","breakfast","breath","brick","bridge","broccoli","brochure","brother","brush","bubble","bucket","bug","building","bulb","bull","bulldozer","bun","butter","chain","chair","chalk","channel","character","cheek","cheese","cheetah","cherry","chess","chest","chick","chicken","children","chimpanzee","chin","chip","chive","chocolate","church","cicada","cinema","circle","city","clam","clarinet","click","clip","clock","closet","cloth","cloud","coach","coal","coast","coat","cobweb","cockroach","cocoa","coffee","coil","coin","coke","collar","college","colt","comb","comics","comma","computer","cone","copy","corn","cotton","couch","cougar","country","course","court","cousin","cow","crab","crack","cracker","crate","crayfish","crayon","cream","creek","cricket","crocodile","crop","crow","crowd","crown","crumb","cucumber","cup","cupboard","curtain","curve","cushion","cyclone","dad","daffodil","daisy","dance","daughter","deer","denim","dentist","desert","desk","dessert","detective","dew","diamond","dictionary","dinghy","dinosaur","dirt","dish","dock","dog","doll","dollar","door","dragon","dragonfly","drain","drawer","drawing","dress","dresser","drill","drink","drum","dryer","duck","duckling","dungeon","dust","eagle","ear","earth","earthquake","eel","egg","eggplant","elbow","elephant","energy","engine","equipment","eye","eyebrow","face","fact","factory","fairies","family","fan","fang","farm","fat","fear","feast","feather","feet","ferryboat","field","finger","fire","fireplace","fish","fist","flag","flame","flood","floor","flower","flute","fly","foam","fog","food","foot","football","forehead","forest","fork","fountain","fox","frame","freckle","freezer","frog","frost","fruit","fuel","fur","furniture","game","garage","garden","garlic","gas","gate","gear","ghost","giraffe","girl","glass","glove","glue","goal","goat","gold","goldfish","golf","gorilla","government","grape","grass","grasshopper","grater","grease","grill","grin","group","guitar","gum","gym","gymnast","hail","hair","haircut","hall","ham","hamburger","hammer","hamster","hand","handball","handle","hardware","harmonica","harmony","hat","hawk","head","headlight","heart","heat","hedge","height","helicopter","helmet","hem","hen","hill","hip","hippopotamus","hockey","hog","hole","home","honey","hood","hook","horn","horse","hose","hospital","house","hurricane","hyena","ice","icicle","ink","insect","instrument","iron","island","jacket","jade","jaguar","jail","jam","jar","jaw","jeans","jeep","jelly","jellyfish","jet","jewel","joke","journey","judge","judo","juice","jump","jumper","kangaroo","karate","kayak","kettle","key","keyboard","kick","kiss","kitchen","kite","kitten","knee","knife","knight","knot","lace","ladybug","lake","lamb","lamp","land","lasagna","laugh","laundry","leaf","leather","leek","leg","lemonade","leopard","letter","lettuce","library","lift","light","lightning","lily","line","lion","lip","lipstick","liquid","list","litter","lizard","loaf","lobster","lock","locket","locust","look","lotion","love","lunch","lynx","macaroni","machine","magazine","magic","magician","mail","mailbox","mailman","makeup","map","marble","mark","market","mascara","mask","match","meal","meat","mechanic","medicine","memory","men","menu","message","metal","mice","middle","milk","milkshake","mint","minute","mirror","mist","mistake","mitten","Monday","money","monkey","month","moon","morning","mosquito","motorboat","motorcycle","mountain","mouse","moustache","mouth","music","mustard","nail","name","napkin","neck","needle","nest","net","news","night","noise","noodle","nose","note","notebook","number","nut","oak","oatmeal","ocean","octopus","office","oil","olive","onion","orange","orchestra","ostrich","otter","oven","owl","ox","oxygen","oyster","packet","page","pail","pain","paint","pair","pajama","pamphlet","pan","pancake","panda","pansy","panther","pants","paper","parcel","parent","park","parrot","party","pasta","paste","pastry","patch","path","pea","peace","peanut","pear","pedestrian","pelican","pen","pencil","pepper","perfume","person","pest","pet","phone","piano","pickle","picture","pie","pig","pigeon","pillow","pilot","pimple","pin","pipe","pizza","plane","plant","plantation","plastic","plate","playground","plot","pocket","poison","police","policeman","pollution","pond","popcorn","poppy","porcupine","postage","postbox","pot","potato","poultry","powder","power","price","printer","prison","pumpkin","puppy","pyramid","queen","question","quicksand","quill","quilt","rabbit","radio","radish","raft","rail","railway","rain","rainbow","raincoat","rainstorm","rake","rat","ravioli","ray","recorder","rectangle","refrigerator","reindeer","relatives","restaurant","reward","rhinoceros","rice","riddle","ring","river","road","roast","rock","roll","roof","room","rooster","rose","rowboat","rubber","sack","sail","sailboat","sailor","salad","salmon","salt","sand","sandwich","sardine","sauce","sausage","saw","saxophone","scarecrow","scarf","school","scissors","scooter","scorpion","screw","screwdriver","sea","seagull","seal","seaplane","seashore","season","seat","second","seed","sentence","servant","shade","shadow","shallot","shampoo","shark","shears","sheep","sheet","shelf","shell","shield","ship","shirt","shoe","shoemaker","shop","shorts","shoulder","shovel","show","side","sidewalk","sign","signature","silk","silver","singer","sink","sister","skin","skirt","sky","sled","slippers","slope","smoke","snail","snake","sneeze","snow","snowflake","snowman","soap","soccer","sock","sofa","softball","soldier","son","song","sound","soup","soybean","space","spade","spaghetti","spark","sparrow","spear","speedboat","spider","spike","spinach","sponge","spoon","spot","sprout","spy","square","squash","squid","squirrel","stage","staircase","stamp","star","station","steam","steel","stem","step","stew","stick","stitch","stinger","stomach","stone","stool","stopsign","stopwatch","store","storm","story","stove","stranger","straw","stream","string","submarine","sugar","suit","summer","sun","sunshine","sunflower","supermarket","surfboard","surname","surprise","sushi","swallow","swamp","swan","sweater","sweatshirt","sweets","swing","switch","sword","swordfish","syrup","table","tabletop","tadpole","tail","target","tax","taxi","tea","teacher","team","teeth","television","tennis","tent","textbook","theater","thistle","thought","thread","throat","throne","thumb","thunder","thunderstorm","ticket","tie","tiger","tile","time","tire","toad","toast","toe","toilet","tomato","tongue","tooth","toothbrush","toothpaste","top","tornado","tortoise","tower","town","toy","tractor","traffic","trail","train","transport","tray","tree","triangle","trick","trip","trombone","trouble","trousers","truck","trumpet","trunk","t-shirt","tub","tuba","tugboat","tulip","tuna","tune","turkey","turnip","turtle","tv","twig","twilight","twine","umbrella","valley","van","vase","vegetable","veil","vein","vessel","vest","violin","volcano","volleyball","vulture","wagon","wall","wallaby","walnut","walrus","washer","wasp","waste","watch","watchmaker","water","wave","wax","weasel","weather","web","wedge","well","whale","wheat","wheel","wheelchair","whip","whisk","whistle","wilderness","willow","wind","wind chime","window","windscreen","wing","winter","wire","wish","wolf","woman","wood","wool","word","workshop","worm","wound","wren","wrench","wrinkles","wrist","xylophone","yacht","yak","yard"]
const adjLength = adjs.length
const nounLength = nouns.length
function randomName(){
const randomAdj = adjs[Math.floor(Math.random()*adjLength)]
const randomNoun = nouns[Math.floor(Math.random()*nounLength)]
return randomAdj + "-" + randomNoun
}
var editorVal = ""
if (getID() == '') {
const name = randomName()
window.location.hash = name
makeClean() // prevents page reload
editorVal += "// Welcome to team " + name + "!\n//\n"
editorVal += "// Share this link to collaborate:\n//\n"
editorVal += "// woofjs.com/team#" + name + "\n\n"
// editorVal += "// Press the Publish button to create a private project that nobody else can edit"
editorVal += "setBackdropURL('./docs/images/nyc.jpg')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
}
var firepadRef = firebase.database().ref('/team/' + getID());
var firepad = Firepad.fromCodeMirror(firepadRef, editor, {
defaultText: editorVal,
});
onkeydown = function(e){
if(e.ctrlKey && e.key == '/'){
e.preventDefault();
}
if((e.metaKey || e.ctrlKey) && e.keyCode == 'S'.charCodeAt(0)){
e.preventDefault();
save();
}
}
function WoofJSLint(){
if (app.error) { return }
const code = js_beautify(app.code, {space_after_anon_function: true, indent_size: 2, indent_with_tabs: false})
const regEx = / ((\w)*\.)?(ready|onKeyDown|onKeyUp|onMouseDown|onMouseUp|onMouseMove)/g // matches any event indented with two spaces
var result;
while ((result = regEx.exec(code)) !== null) {
var lineNumber = code.substring(0, result.index).split('\n').length
CodeMirror.commands.markGutter(editor, "warning", lineNumber, "We reccomend moving this " + result[3] + " event outside all loops and other events.")
}
}
firepad.on('synced', function(isSynced) {
// isSynced will be false immediately after the user edits the pad,
// and true when their edit has been saved to Firebase.
if (isSynced) {
makeClean()
}
else {
makeDirty()
}
});
// run the code (debounced) on every change to the editor
editor.on("change", function(){
debouncedRunCode()
setTimeout(function() {WoofJSLint()}, 1000);
});
runCode()
// focus on the preview when refreshed
function focusPreview() {
document.getElementById('preview').focus();
};
editor.on('inputRead', function(cm, e){
if (e.text.length == 1 && e.text[0].length == 1 && /^[a-zA-Z\.]/.test(e.text[0])) {
// constantly show autocomplete suggestions
CodeMirror.commands.autocomplete(editor);
}
});
// warns the user when they try to close the page without saving
window.onbeforeunload = function(e) {
if (app.status == "DIRTY") {
var dialogText = 'Make sure to copy and paste your work somewhere safe.';
e.returnValue = dialogText;
return dialogText;
}
};
function tryRunningCode() {
app.code = editor.getValue()
app.error = undefined
try {
var result = Babel.transform(editor.getValue(), {
presets: [['es2015', {'modules': false}]], // modules: false to remove strict mode
retainLines: true
})
var code = result.code
try {
document.getElementById('preview').contentWindow.addEventListener("mousemove", function(event) {
app.mouseX = Math.round(document.getElementById('preview').contentWindow.mouseX)
if (app.mouseX >= Math.round(document.getElementById('preview').contentWindow.maxX - 2)) {
app.mouseX += " (maxX)"
}
if (app.mouseX <= Math.round(document.getElementById('preview').contentWindow.minX + 1)) {
app.mouseX += " (minX)"
}
app.mouseY = Math.round(document.getElementById('preview').contentWindow.mouseY)
if (app.mouseY >= Math.round(document.getElementById('preview').contentWindow.maxY - 1)) {
app.mouseY += " (maxY)"
}
if (app.mouseY <= Math.round(document.getElementById('preview').contentWindow.minY + 3)) {
app.mouseY += " (minY)"
}
})
document.getElementById('preview').contentWindow.addEventListener("error", function(event) {
var error = event.error
app.seenError = false
if (error.type == "ImageLoadError") {
app.error = {message: "There is a problem with your image URL: " + error.url, lineno: code.substring(0, code.indexOf(error.url)).split('\n').length}
} else {
app.error = event
}
});
var script = document.createElement("script");
script.type = "text/javascript";
script.crossorigin = "anonymous"
script.text = code
document.getElementById('preview').contentDocument.body.appendChild(script)
}
catch (e) {
app.seenError = false
app.error = e;
}
}
catch (e) {
app.seenError = false
app.error = e
}
}
function runCode() {
document.getElementById("preview").remove();
var iframe = document.createElement("iframe");
iframe.id = "preview";
document.getElementById("output").appendChild(iframe);
setTimeout(function() {
// add doctype to iframe
iframe.contentWindow.document.open();
iframe.contentWindow.document.write('<!DOCTYPE html>');
iframe.contentWindow.document.close();
// add a base tag to the page so it knows where to pull relative image urls
var base = iframe.contentWindow.document.createElement("base");
base.href = document.baseURI
iframe.contentWindow.document.body.appendChild(base);
// then we create a script tag with the woof code and add it to the page
var script = iframe.contentWindow.document.createElement("script");
script.type = "text/javascript";
script.src = "./woof.js";
iframe.contentWindow.document.body.appendChild(script);
script.onload = function() {
// when the woof.js library loads, run the user's code
var evt = document.createEvent('Event');
evt.initEvent('load', false, false);
iframe.contentWindow.dispatchEvent(evt);
tryRunningCode();
}
}, 10)
}
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// helper function to prevent runCode from running too often
var debouncedRunCode = debounce(runCode, 1000, false)
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-82374072-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>