-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathview.js
More file actions
3265 lines (3047 loc) · 103 KB
/
view.js
File metadata and controls
3265 lines (3047 loc) · 103 KB
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
///////////////////////////////////////////////////////////////////////////
// VIEW SUPPORT
///////////////////////////////////////////////////////////////////////////
var $ = require('jquery'),
filetype = require('filetype'),
tooltipster = require('tooltipster'),
see = require('see'),
droplet = require('droplet-editor'),
palette = require('palette'),
codescan = require('codescan'),
drawProtractor = require('draw-protractor'),
ZeroClipboard = require('ZeroClipboard'),
FontLoader = require('FontLoader');
function htmlEscape(s) {
return s.replace(/[<>&"]/g, function(c) {
return c=='<'?'<':c=='>'?'>':c=='&'?'&':'"';});
}
var downloadhtml;
var downloadcss;
// The view has three panes, #left, #right, and #back (the offscreen pane).
//
// Any of the three panes can show:
// - an editor
// Exposes set/get "current text", "editchange" event, "isdirty".
// on('editchange')
// - a directory listing
// Exposes "clicked on link" event (up, new, file, directory)
// on('linkclick')
// Exposes "hovered on link" event (for possible preview)
// on('linkhover')
// - an iframe run of a URL or of HTML text
// rotateRight / rotateLeft
//
// Preview management
// Method showPreview(on/off).
// - "isPreviewShown"
// on('previewtoggle')
//
// The top-button bar
// - Method showButtons([{html:, id:, enabled:}])
// Method blinkButton(id)
// Method enableButton(id, true/false)
// on(id)
//
// The renaming widget
// on('namechange')
// getNameText
// setNameText
//
// The middle run button
// showRunButton(true/false)
// on('run')
// showLoadingProgress
// Private view state
var state = {
nameText: $('#filename').text(),
previewMode: true,
callbacks: {},
subscribers: [],
depth: window.history.state && window.history.state.depth || 0,
aborting: false,
pane: {
alpha: initialPaneState(),
bravo: initialPaneState(),
charlie: initialPaneState()
}
}
var dropletMarkClassColors = {
'debugerror': '#F00',
'debugfocus': '#FFF',
'debugtrace': '#FF0'
}
//
// Zeroclipboard seems very flakey. The documentation says
// that this configuration should not be necessary but it seems to be
//
ZeroClipboard.config({
swfPath: '/lib/zeroclipboard/ZeroClipboard.swf',
trustedDomains: [window.location.hostname, window.pencilcode.domain],
allowScriptAccess: 'always'
});
window.pencilcode.view = {
// Listens to events
on: function(tag, cb) {
if (state.callbacks[tag] == null){
state.callbacks[tag] = []
}
state.callbacks[tag].push(cb);
},
// Simulate firing of an event
fireEvent: function(event, args) { fireEvent(event, args); },
// publish/subscribe for global events; all global events are broadcast
// to the parent frames using postMessage() if we are iframed
subscribe: function(callback){
state.subscribers.push(callback);
},
publish: publish,
// Sets up the text-editor in the view.
paneid: paneid,
panepos: panepos,
setPaneTitle: function(pane, html) {
$('#' + pane + 'title_text').html(html);
},
clearPane: clearPane,
setPaneEditorData: setPaneEditorData,
changePaneEditorText: function(pane, text) {
return changeEditorText(state.pane[pane], text);
},
getPaneEditorData: getPaneEditorData,
setPaneEditorBlockMode: setPaneEditorBlockMode,
getPaneEditorBlockMode: getPaneEditorBlockMode,
setPaneEditorBlockOptions: setPaneEditorBlockOptions,
getPaneEditorLanguage: getPaneEditorLanguage,
markPaneEditorLine: markPaneEditorLine,
clearPaneEditorLine: clearPaneEditorLine,
clearPaneEditorMarks: clearPaneEditorMarks,
notePaneEditorCleanData: notePaneEditorCleanData,
notePaneEditorCleanLineCount: notePaneEditorCleanLineCount,
noteNewFilename: noteNewFilename,
setPaneEditorReadOnly: setPaneEditorReadOnly,
isPaneEditorEmpty: isPaneEditorEmpty,
isPaneEditorDirty: isPaneEditorDirty,
setPaneLinkText: setPaneLinkText,
setPaneLinks: setPaneLinks,
setPaneRunHtml: setPaneRunHtml,
evalInRunningPane: evalInRunningPane,
showProtractor: showProtractor,
hideProtractor: hideProtractor,
setPrimaryFocus: setPrimaryFocus,
// setPaneRunUrl: setPaneRunUrl,
hideEditor: function(pane) {
$('#' + pane + 'title').hide();
$('#' + pane).hide();
},
showEditor: function(pane) {
$('#' + pane).show();
$('#' + pane + 'title').show();
},
// Mananges panes and preview mode
setPreviewMode: setPreviewMode,
getPreviewMode: function() { return state.previewMode; },
rotateRight: rotateRight,
rotateLeft: rotateLeft,
// Sets buttons.
showButtons: showButtons,
enableButton: enableButton,
// Notifications
flashNotification: flashNotification,
flashThumbnail: flashThumbnail,
dismissNotification: dismissNotification,
flashButton: flashButton,
// Show login (or create account) dialog.
showLoginDialog: showLoginDialog,
// Show share dialog.
showShareDialog: showShareDialog,
showDialog: showDialog,
// The run button
canShowMiddleButton: true,
showMiddleButton: function(which) {
if (window.pencilcode.view.canShowMiddleButton) {
$('#middle').show();
showMiddleButton(which);
} else {
$('#middle').hide();
}
},
showToggleButton: function(enable) {
$('body').toggleClass('notoggletab', !enable);
},
// Sets editable name.
setNameText: function(s) {
state.nameText = s;
$('#filename').text(s);
var title = s.replace(/\/$/, '').replace(/^.*\//, '');
var domain = window.location.hostname.replace(/\..*$/, '');
if (!title) { title = domain; } else { title += ' (' + domain + ')'; }
if (!title) title = 'Pencil Code Editor';
document.title = title;
},
getNameText: function() { return state.nameText; },
setNameTextReadOnly: function(b) {
if (!b) { $('#filename').attr('contentEditable', 'true'); }
else { $('#filename').removeAttr('contentEditable'); }
},
// Sets visible URL without navigating.
setVisibleUrl: setVisibleUrl,
// For other modules to fire view events.
fireEvent: fireEvent,
// For debugging only
_state: state
};
$(window).on('resize.editor', function() {
var pane;
$('.hpanel').trigger('panelsize');
});
function hasSubscribers() {
return state.subscribers.length > 0;
}
function publish(method, args, requestid){
for (var j = 0; j < state.subscribers.length; ++j) {
state.subscribers[j](method, args, requestid);
}
}
function paneid(position) {
return $('.' + position).find('.pane').attr('id');
}
function panepos(id) {
return $('#' + id).closest('.panebox').attr('class').replace(/\s|panebox/g, '');
}
function initialPaneState() {
return {
editor: null, // The ace editor instance.
changeHandler: null,// A closure listening to changes.
cleanText: null, // The last-saved copy of the text.
cleanLineCount: 0, // The last-run number of lines of text.
marked: {}, // Tracks highlighted lines (see markPaneEditorLine)
mimeType: null, // The current mime type.
dirtied: false, // Set if known to be dirty.
links: null, // Unused in this mode.
running: false // Unused in this mode.
};
}
function setOnCallback(tag, cb) {
if (state.callbacks[tag] == null) {
state.callbacks[tag] = [];
}
state.callbacks[tag].push(cb);
}
function fireEvent(tag, args) {
if (tag in state.callbacks) {
var cbs = state.callbacks[tag].slice();
//take a copy of the array in case other
//events are fired while you're indexing it.
for (j=0; j < cbs.length; j++) {
var cb = cbs[j];
if (cb) {
cb.apply(null, args);
}
}
}
}
function setVisibleUrl(targetUrl, addToHistory) {
var currentDepth = history.state && history.state.depth || 0;
var currentUrl = history.state && history.state.current || null;
var previousUrl = history.state && history.state.previous || null;
if (window.query && !/[\?#]/.test(targetUrl)) {
targetUrl += window.query;
}
if (addToHistory) {
if (window.history.pushState) {
window.history.pushState(
{depth: currentDepth + 1,
previous: currentUrl,
current: targetUrl}, document.title, targetUrl);
state.depth = currentDepth + 1;
}
} else {
if (window.history.replaceState) {
window.history.replaceState(
{depth: currentDepth,
previous: previousUrl,
current: targetUrl}, document.title, targetUrl);
state.depth = currentDepth;
}
}
}
$(window).on('popstate', function(e) {
var newDepth = window.history.state && window.history.state.depth || 0;
var undo = null;
if (Math.abs(newDepth - state.depth) == 1) {
if (newDepth > state.depth) {
undo = function() { state.aborting = true; window.history.back(); }
} else {
undo = function() { state.aborting = true; window.history.forward(); }
}
}
state.depth = newDepth;
if (state.aborting) {
state.aborting = false;
return;
}
fireEvent('popstate', [undo]);
});
// Calls preventDefault on an event if the event is not an editor.
function ignoreBackspace(e) {
if (!e || !e.target ||
e.target.isContentEditable ||
e.target.tagName == 'INPUT' || e.target.tagName == 'TEXTAREA') {
// In the above cases, let backspace pass through.
return;
}
// Otherwise, prevent backspace from doing the history "back" action.
e.preventDefault();
return false;
}
// Global hotkeys for this application. Ctrl- (or Command- or backspace) key functions.
var hotkeys = {
'\r': function() { fireEvent('run'); return false; },
'S': function() { fireEvent('save'); return false; },
'H': forwardCommandToEditor,
'F': forwardCommandToEditor,
// \x08 is the key code for backspace
'\x08': ignoreBackspace
};
// Capture global keyboard shortcuts.
$('body').on('keydown', function(e) {
if (e.ctrlKey || e.metaKey || e.which === 8) {
var handler = hotkeys[String.fromCharCode(e.which)];
if (handler) {
return handler(e);
}
}
});
function forwardCommandToEditor(keydown_event) {
// Only forward the command if an editor is present and it
// does not already have focus.
if (!$(document.activeElement).closest('.editor').length) {
var pane = paneid('left');
var paneState = state.pane[pane];
if (paneState.editor) {
var editor = paneState.editor;
editor.focus();
editor.onCommandKey(editor, 1, keydown_event.which);
return false;
}
}
}
///////////////////////////////////////////////////////////////////////////
// NOTIFICATIONS
///////////////////////////////////////////////////////////////////////////
$('#notification').on('click', 'a', function(e) {
if (e.target.id) {
fireEvent(e.target.id, []);
$(e.target).css('outline', '3px dotted blue');
$('body').off('.flashNotification');
$('#notification').delay(200).fadeOut();
return false;
}
});
function flashNotification(text, loading) {
var marker = Math.random();
var hidefunc = function(e) {
if ($('#notification').data('marker') == marker) {
dismissNotification();
}
};
// Centering with script.
if (loading) {
$('#notification').addClass('loading');
} else {
$('#notification').removeClass();
}
$('#notification').html(text).data('marker', marker).finish()
.css({opacity: 0,display: 'inline-block'})
.css({left:($(window).width() - $('#notification').outerWidth()) / 2})
.animate({opacity:1}, 200)
.queue(function(n) {
$('body').off('.flashNotification');
$(window).off('.flashNotification');
$('body').on('blur.flashNotification ' +
'mousedown.flashNotification keydown.flashNotification', hidefunc);
$(window).on('resize.flashNotification ' +
'popstate.flashNotification', hidefunc);
n();
});
}
function dismissNotification() {
if ($('#notification').is(':visible')) {
$('#notification').removeData('marker');
$('body').off('.flashNotification');
$('#notification').delay(200).fadeOut();
}
}
function flashButton(id) {
var button = $('#' + id).closest('button'),
bg = button.css('backgroundColor'),
j;
for (j = 0; j < 2; ++j) {
button.animate({opacity:1},
function(n){$(this).css({backgroundColor: 'dodgerblue'});})
.animate({opacity:1},
function(n){$(this).css({backgroundColor: bg});});
}
}
///////////////////////////////////////////////////////////////////////////
// FILENAME AND RENAMING
///////////////////////////////////////////////////////////////////////////
function selectEndOf(contentEditableElement)
{
var range,selection;
if (document.createRange) {
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
} else if (document.selection) {
range = document.body.createTextRange();
range.moveToElementText(contentEditableElement);
range.collapse(false);
range.select();
}
}
function setRangeStart(range, node, charsFromBegin) {
if (node.firstChild) {
var count = 0;
for (var child = node.firstChild; child; child = child.nextSibling) {
var chars = child.textContent.length;
if (chars > charsFromBegin) {
setRangeStart(range, child, charsFromBegin);
return;
}
charsFromBegin -= chars;
count += 1;
}
range.setStart(node, count);
} else {
var chars = node.textContent.length;
range.setStart(node, Math.min(chars, charsFromBegin));
}
}
function setRangeEnd(range, node, charsFromEnd) {
if (node.lastChild) {
var count = 0;
for (var child = node.lastChild; child; child = child.lastSibling) {
var chars = child.textContent.length;
if (chars > charsFromEnd) {
setRangeEnd(range, child, charsFromEnd);
return;
}
charsFromEnd -= chars;
count += 1;
}
range.setStart(node, count);
} else {
var chars = node.textContent.length;
range.setStart(node, chars - Math.min(chars, charsFromEnd));
}
}
function selectContentsOf(contentEditableElement, beginOffset, endOffset) {
var range,selection;
if (document.createRange) {
range = document.createRange();
range.selectNodeContents(contentEditableElement);
if ((beginOffset || endOffset) && contentEditableElement.textContent) {
if (beginOffset) {
setRangeStart(range, contentEditableElement, beginOffset);
}
if (endOffset) {
setRangeStart(range, contentEditableElement, endOffset);
}
}
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
} else if (document.selection) {
range = document.body.createTextRange();
range.moveToElementText(contentEditableElement);
range.select();
}
}
$('#filename').on('keypress keydown keyup input', function(e) {
if (e.charCode === '\r'.charCodeAt(0) || e.charCode === '\n'.charCodeAt(0)) {
$('#filename').blur();
return false;
}
if (e.charCode >= 20 && e.charCode <= 127 && !/[\w\/.-]/.test(
String.fromCharCode(e.charCode))) {
return false;
}
var sel = $('#filename');
var text = sel.text();
if (sel.children().length || (text != '\xa0' && /\s|\xa0/.test(text))) {
sel.text(text.replace(/\s|\xa0/g, ''));
selectEndOf(sel[0]);
}
if (text == '') { sel.html(' '); }
});
function fixTypedFilename(enteredtext) {
if (!enteredtext) { return enteredtext; }
return enteredtext.replace(/\s|\xa0|[^\w\/.-]/g, '')
.replace(/^\/*/, '').replace(/\/\/+/g, '/');
}
$('#filename').on('blur', function() {
var sel = $('#filename');
var enteredtext = sel.text();
var fixedtext = fixTypedFilename(enteredtext);
if (!fixedtext) {
fixedtext = state.nameText;
}
if (fixedtext != enteredtext) {
sel.text(fixedtext);
selectEndOf(sel[0]);
}
if (fixedtext != state.nameText) {
state.nameText = fixedtext;
fireEvent('rename', [fixedtext]);
}
});
///////////////////////////////////////////////////////////////////////////
// BUTTONS
///////////////////////////////////////////////////////////////////////////
$('#owner').on('click', function(e) {
if (!e.shiftKey && !e.ctrlKey && !e.metaKey) {
fireEvent('root', []);
e.preventDefault();
}
});
function fixParentLink(elt) {
var filename = window.location.pathname;
if (filename.indexOf('/') >= 0) {
filename = filename.replace(/\/[^\/]+\/?$/, '');
} else {
filename = '';
}
if (!filename) {
filename = '//' + window.pencilcode.domain + '/edit/';
} else {
filename += '/';
}
$(elt).closest('a').attr('href', filename);
}
$('#folder').on('mousemove', function(e) {
fixParentLink(this);
});
$('#folder').on('click', function(e) {
if (!e.shiftKey && !e.ctrlKey && !e.metaKey) {
fireEvent('done', []);
e.preventDefault();
} else {
fixParentLink(this);
}
});
// These buttons avoid taking focus when you click on them.
$('#buttonbar,#middle').on('mousedown', 'button', function(e) {
if (this.id) {
e.preventDefault();
$(this).addClass('pressed');
}
});
$('#buttonbar,#middle').on('mousemove', 'button', function(e) {
if (this.id) {
if (!e.which) {
$(this).removeClass('pressed');
}
}
});
$('#buttonbar,#middle').on('click', 'button,.splitmenu li', function(e) {
// First deal with rename if it's in progress.
if ($('#filename').is(document.activeElement)) {
$('#filename').blur();
}
var id = $(e.target).attr('id') || this.id;
if (id) {
$(this).removeClass('pressed');
$(this).tooltipster('hide');
fireEvent(id, []);
return false;
}
});
$('#buttonbar').on('change', 'input[type=checkbox]', function(e) {
if (e.target.id) {
fireEvent(e.target.id, [e.target.checked]);
}
});
// buttonlist should be
// [{label:, id:, callback:, checkbox:, checked:, disabled:, title:}]
function showButtons(buttonlist) {
var bar = $('#buttonbar');
var html = '';
for (var j = 0; j < buttonlist.length; ++j) {
if (buttonlist[j].checkbox) {
html += '<button' +
(buttonlist[j].disabled ? ' disabled' : '') +
'><label><input type="checkbox"' +
(buttonlist[j].id ? ' id="' + buttonlist[j].id + '"' : '') +
(buttonlist[j].checked ? ' checked' : '') +
(buttonlist[j].disabled ? ' disabled' : '') +
(buttonlist[j].title ? ' title="' + buttonlist[j].title + '"' : '') +
'>' + buttonlist[j].label + '</label></button>';
} else {
var submenu = '';
if (buttonlist[j].menu) {
submenu = ' <div class="droparrow">▾<ul>';
for (var k = 0; k < buttonlist[j].menu.length; ++k) {
var item = buttonlist[j].menu[k];
var title = item.title ? ' title="' + item.title + '"' : '';
submenu += '<li id="' + item.id + '"' + title +'>' +
item.label + '</li>';
}
submenu += '</ul></div>';
}
html += '<button' +
(buttonlist[j].id ? ' id="' + buttonlist[j].id + '"' : '') +
(buttonlist[j].menu ? ' class="splitmenu"' : '') +
(buttonlist[j].disabled ? ' disabled' : '') +
(buttonlist[j].title ? ' title="' + buttonlist[j].title + '"' : '') +
'>' + buttonlist[j].label + submenu + '</button>';
}
}
bar.html(html);
bar.find('.droparrow').each(function() {
var arrowwidth = $(this).outerWidth(),
buttonwidth = $(this).parent().outerWidth();
$(this).find('ul').css('left', arrowwidth - buttonwidth - 1);
});
bar.find('.droparrow').on('click', function(e) {
if (e.target == this) {
e.stopPropagation();
e.preventDefault();
return false;
}
});
// Enable tooltipster for any new buttons.
$('#buttonbar button').not('.splitmenu').tooltipster();
$('#buttonbar button.splitmenu').tooltipster({position: 'left'});
$('#buttonbar button.splitmenu li').tooltipster({position: 'left'});
}
function enableButton(id, enable) {
if (enable) {
var inp = $('#' + id).removeAttr('disabled');
} else {
var inp = $('#' + id).attr('disabled', true);
}
}
// Centers the middle button div using javascript.
function centerMiddle() {
var m = $('#middle');
// Horizontal center taking into account the button width.
m.css({marginRight: -m.outerWidth() / 2});
// Vertical center taking into the editor height and button height.
/*
m.css({top:($(window).height() -
($('.pane').height() + m.outerHeight()) / 2)})
*/
}
$(window).on('resize.middlebutton', centerMiddle);
function showMiddleButton(which) {
if (which == 'run') {
var html,
rightpane = state.pane[paneid('right')],
leftpane = state.pane[paneid('left')];
if (rightpane.running && leftpane.editor &&
rightpane.lastChangeTime >= leftpane.lastChangeTime) {
html = '<button id="run" class="quiet" ' +
'title="Restart program (Ctrl+Enter)">' +
'<div class="reload"></div></button>';
} else {
html = '<button id="run" title="Run program (Ctrl+Enter)">' +
'<div class="triangle"></div></button>';
}
$('#middle').find('div').eq(0).html(html);
if (state.previewMode) {
$('#middle').show();
centerMiddle();
}
} else if (which == 'stop') {
$('#middle').find('div').eq(0).html(
'<button id="stop" title="Stop program">' +
'<div class="square"></div></button>');
if (state.previewMode) {
$('#middle').show();
centerMiddle();
}
} else if (which == 'edit' && state.previewMode) {
$('#middle').find('div').eq(0).html(
'<button id="edit">◁</button>');
if (state.previewMode) {
$('#middle').show();
centerMiddle();
}
} else if (which == 'loading') {
$('#middle').find('div').eq(0).html(
'<div class="loading"></div>').show();
centerMiddle();
} else {
$('#middle').hide().find('div').eq(0).html('');
}
// Enable tooltipster on the middle button.
$('#middle button').tooltipster();
}
// Show thumbnail under the save button.
function flashThumbnail(imageDataUrl) {
if (!imageDataUrl) { return; }
// Destroy the original title tooltip once there is a thumbnail.
$('#screenshot').tooltipster('destroy');
$('#screenshot').tooltipster({
content: $('<img src=' + imageDataUrl + ' alt="thumbnail">'),
position: 'bottom',
theme: 'tooltipster-shadow',
interactive: true,
timer: 3000
});
// Flash the thumbnail for 3 seconds, then disable the timer,
// so that activation via hovering will not last for only 3 seconds.
$('#screenshot').tooltipster('show');
$('#screenshot').tooltipster('option', 'timer', 0);
}
///////////////////////////////////////////////////////////////////////////
// SHARE DIALOG
///////////////////////////////////////////////////////////////////////////
function showShareDialog(opts) {
if (!opts) {
opts = { };
}
// Adds a protocol ('http:') to a string path if it does not yet have one.
function addProtocol(path) {
if (/^\w+:/.test(path)) { return path; }
return 'http:' + path;
}
var newLines = '\r\n\r\n';
bodyText = 'Check out this program that I created on ' + window.pencilcode.domain
+ newLines;
if (opts.shareStageURL) {
bodyText += 'Posted program: ' + addProtocol(opts.shareStageURL) + newLines;
}
if (opts.shareRunURL) {
bodyText += 'Latest program: ' + addProtocol(opts.shareRunURL) + newLines;
}
if (opts.shareEditURL) {
bodyText += 'Program code: ' + addProtocol(opts.shareEditURL) + newLines;
}
subjectText = 'Pencilcode program: ' + opts.title;
// Need to escape the text since it will go into a url link
bodyText = escape(bodyText);
subjectText = escape(subjectText);
var embedText = null;
if (opts.shareRunURL && !/[>"]/.test(opts.shareRunURL)) {
embedText = '<iframe src="' + opts.shareRunURL + '" ' +
'width="640" height="640" frameborder="0" allowfullScreen></iframe>';
}
opts.prompt = (opts.prompt) ? opts.prompt : 'Shared ✓';
opts.content = (opts.content) ? opts.content :
'<div class="content">' +
(opts.shareStageURL ?
'<div class="field">' +
'<a target="_blank" ' +
'title="Posted on share.' + window.pencilcode.domain + '" href="' +
htmlEscape(addProtocol(opts.shareStageURL)) + '">See it here</a> ' +
'<input readonly type="text" value="' +
htmlEscape(addProtocol(opts.shareStageURL)) +
'"><button class="copy" data-clipboard-text="' +
htmlEscape(addProtocol(opts.shareStageURL)) +
'"><img src="/image/copy.png" title="Copy"></button>' +
'</div>' : '') +
((opts.shareRunURL && !opts.shareStageURL) ?
'<div class="field">' +
'<a target="_blank" ' +
'title="Run without showing code" href="' +
htmlEscape(opts.shareRunURL) + '">See it here</a> ' +
'<input readonly type="text" value="' +
htmlEscape(opts.shareRunURL) +
'"><button class="copy" data-clipboard-text="' +
htmlEscape(opts.shareRunURL) +
'"><img src="/image/copy.png" title="Copy"></button>' +
'</div>' : '') +
'<div class="field">' +
'<a target="_blank" ' +
'title="Link showing the code" href="' +
htmlEscape(opts.shareEditURL) + '">Share code</a> ' +
'<input readonly type="text" value="' +
htmlEscape(opts.shareEditURL) +
'"><button class="copy" data-clipboard-text="' +
htmlEscape(opts.shareEditURL) +
'"><img src="/image/copy.png" title="Copy"></button>' +
'</div>' +
(embedText ?
'<div class="field">' +
'<a target="_blank" ' +
'title="HTML code to embed" href="' +
htmlEscape(opts.shareRunURL) + '">Embed code</a> ' +
'<input readonly type="text" left="1" value="' +
htmlEscape(embedText) +
'"><button class="copy" data-clipboard-text="' +
htmlEscape(embedText) +
'"><img src="/image/copy.png" title="Copy"></button>' +
'</div>' : '') +
'</div><br>' +
'<button class="cancel">OK</button>' +
'<button class="ok" title="Share by email">Email</button>';
opts.init = function(dialog) {
dialog.find('a.quiet').tooltipster();
dialog.find('button.ok').tooltipster();
dialog.find('button.copy').tooltipster();
dialog.find('.field input').on('click', function() {
$(this).select();
}).each(function() {
if (!$(this).attr('left')) {
this.scrollLeft = this.scrollWidth;
}
});
var clipboardClient = new ZeroClipboard(dialog.find('button.copy'));
var tooltipTimer = null;
clipboardClient.on('ready', function() {
clipboardClient.on('copy', function(event) {
var button = event.target;
// Hide any other copy tooltips in this dialog.
dialog.find('button.copy').not(button).tooltipster('hide');
// Just flash tooltipster for a couple seconds, because mouseleave
// doesn't appear to work.
$(button).tooltipster('content', 'Copied!').tooltipster('show');
// Select the text in the copied field.
setTimeout(function() {
$(button).closest('.field').find('input').select();
}, 100);
clearTimeout(tooltipTimer);
tooltipTimer = setTimeout(function() {
$(button).tooltipster('hide');
}, 1500);
});
});
dialog.find('button.cancel').focus();
}
opts.done = function(state) {
window.open('mailto:?body='+bodyText+'&subject='+subjectText);
}
showDialog(opts);
}
function showDialog(opts) {
var overlay = $('#overlay');
if (!opts) { opts = {}; }
overlay.html('');
var classes = ['dialog'];
if (opts.center) { classes.push('center'); }
if (opts.leftopts) { classes.push('leftopts'); }
var dialogHTML =
'<div class="' + classes.join(' ') + '">' +
'<div class="prompt">' + (opts.prompt ? opts.prompt : '') +
'<div class="info">' + (opts.info ? opts.info : '') + '</div>' +
(opts.content ? opts.content : '') + '</div></div>';
var dialog = $(dialogHTML).appendTo(overlay);
// The following class shows the overlay and adjusts other page UI.
$('body').addClass('modal');
////////////////////////////////////////////////////////////////
//
// function: update
//
// Called from event handlers inside the dialog. The parameter
// is an anonymous object that contains information on what do do:
// up.cancel --> Close out the dialog
//
////////////////////////////////////////////////////////////////
function update(up) {
if (!up) return;
if (up.cancel) {
dialog.remove();
$('body').removeClass('modal');
if (opts.cancel) { opts.cancel(); }
return;
}
for (attr in up) {
if (attr == 'disable') {
if (up.disable) {
dialog.find('button.ok').attr('disabled', true);
} else {
dialog.find('button.ok').removeAttr('disabled');
}
} else {
var x = dialog.find('.' + attr);
if (x.prop('tagName') == "INPUT") {
if (x.prop('type') == 'checkbox') {
x.prop('checked', up[attr]);
} if (x.prop('type') == 'radio') {
x.find('[value=' + up[attr] + ']').prop('checked', true);
} else {
x.val(up[attr]);
}
}
else {
x.html(up[attr]);
}
}
}
}
function state() {
var retVal;
if (opts.retrieveState)
retVal = opts.retrieveState(dialog);
if (!retVal)
retVal = { };
retVal.update = update;
return retVal;
}
function validate(e) {
if (e && ($(e.target).attr('target') == '_blank')) {
// Don't validate on mousedown of a new-window hyperlink.
return true;
}
if (opts.validate) {
update(opts.validate(state(), e));
}
}
dialog.on('keyup mousedown change', validate);
dialog.find('button.ok').on('click', function() {
validate();
if (!dialog.find('button.ok').is(':disabled') &&
opts.done) {
opts.done(state());
}
});
overlay.on('click', function(e) {
if ($(e.target).hasClass('cancel') || overlay.is(e.target)) {
update({cancel:true});
}
if (opts.onclick) {
return opts.onclick(e, dialog, state());
}
});
dialog.on('keydown', function(e) {
if (e.which == 27) {
update({cancel:true});
return;
}
if (opts.onkeydown) {
return opts.onkeydown(e, dialog, state());
}
});
if (opts.init) {
opts.init(dialog);
}
validate();
}
////////////////////////////////////////////////////////////////////////////