-
Notifications
You must be signed in to change notification settings - Fork 45
/
runme.js
1769 lines (1488 loc) · 58.7 KB
/
runme.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
// ChiliPeppr Runme.js
// You should right-click and choose "Run" inside Cloud9 to run this
// Node.js server script. Then choose "Preview" to load the main HTML page
// of the script in a new tab.
// When you run the main HTML page of this script it does all sorts
// of convenient stuff for you like generate documenation, generate
// your final auto-generated-widget.html file, and push your latest
// changes to your backing github repo.
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var qs = require('querystring');
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"
};
console.log("Starting...");
if (process.env.PORT == undefined) {
process.env.PORT = 9002;
console.log("Port undefined from env var so setting to " + process.env.PORT);
}
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
console.log("URL being requested:", uri);
if (uri == "/") {
res.writeHead(200, {
'Content-Type': 'text/html'
});
//var html = getMainPage();
var htmlDocs = generateWidgetDocs();
var notes = "";
notes += "<p>Click refresh to regenerate README.md, auto-generated-widget.html, and push updates to Github.</p>";
generateWidgetReadme();
notes += "<p>Generated a new README.md file...</p>";
generateInlinedFile();
notes += "<p>Generated a new auto-generated-widget.html file...</p>";
//pushToGithub();
//pushToGithubSync();
pushToGithubAsync();
notes += "<p>Pushed updates to Github...</p>";
//html = html + htmlDocs;
var finalHtml = htmlDocs.replace(/<!-- pre-notes -->/, notes);
res.end(finalHtml);
}
else if (uri == "/uploadscreenshot") {
console.log("screenshot being uploaded. ");
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function () {
//console.log("body:", body);
var POST = qs.parse(body);
// use POST
console.log("done with POST:", POST);
var data_url = POST.imgBase64;
var matches = data_url.match(/.*?;base64,(.*)$/);
//var ext = matches[1];
var base64_data = matches[1];
var buffer = new Buffer(base64_data, 'base64');
console.log("about to write file...");
fs.writeFile("screenshot.png", buffer, function (err) {
if (err) throw err;
//res.send('success');
var json = {
success: true,
desc: "Saved screenshot.png",
//log: stdout
}
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(json));
console.log('done uploading screenshot');
});
});
}
}
else if (uri == "/pushtogithub") {
var url_parts = url.parse(req.url,true);
console.log(url_parts.query);
console.log("/pushtogithub called");
var stdout = pushToGithubSync(url_parts.query.message)
var json = {
success: true,
desc: "Pushed to Github",
log: stdout
}
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(json));
}
else if (uri == "/pullfromgithub") {
console.log("/pullfromgithub called");
var stdout = pullFromGithubSync();
var json = {
success: true,
desc: "Pulled from Github",
log: stdout
}
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(json));
}
else if (uri == "/mergeFromCpTemplateRepo") {
console.log("/mergeFromCpTemplateRepo called");
var stdout = mergeFromCpTemplateRepo();
var json = {
success: true,
desc: "Merged the latest ChiliPeppr Template to this repo. Please check for merge conflicts. You can run \"git status\" for a summary of conflicts, if any.",
log: stdout
}
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(json));
} else {
var filename = path.join(process.cwd(), unescape(uri));
var stats;
try {
stats = fs.lstatSync(filename); // throws if path doesn't exist
}
catch (e) {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.write('404 Not Found\n');
res.end();
return;
}
if (stats.isFile()) {
// path exists, is a file
var mimeType = mimeTypes[path.extname(filename).split(".").reverse()[0]];
res.writeHead(200, {
'Content-Type': mimeType
});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
}
else if (stats.isDirectory()) {
// path exists, is a directory
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('Index of ' + uri + '\n');
res.write('TODO, show index?\n');
res.end();
}
else {
// Symbolic link, other?
// TODO: follow symlinks? security?
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.write('500 Internal server error\n');
res.end();
}
}
}).listen(process.env.PORT);
String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
var widgetSrc, widget, id, deps, cpdefine, requirejs, cprequire_test;
var widgetDocs = {};
/**
* This method will actually eval your widget.js to bring it into memory
* so it can be iterated and parsed using standard javascript. This lets
* us generate docs. If your js doesn't eval, this method will crash.
*/
var isEvaled = false;
var evalWidgetJs = function() {
if (isEvaled) return;
// This method reads in your widget.js and evals it to
// figure out all the info from it to generate docs and sample
// code to make your life easy
widgetSrc = fs.readFileSync('widget.js')+'';
// fill in some auto fill stuff
/*
var widgetUrl = 'http://' +
process.env.C9_PROJECT + '-' + process.env.C9_USER +
'.c9users.io/widget.html';
var editUrl = 'http://ide.c9.io/' +
process.env.C9_USER + '/' +
process.env.C9_PROJECT;
var github = getGithubUrl();
*/
var urls = getAllUrls();
var reUrl = /(url\s*:\s*['"]?)\(auto fill by runme\.js\)/;
//console.log("reUrl:", reUrl);
widgetSrc = widgetSrc.replace(reUrl, "$1" + urls.cpload);
widgetSrc = widgetSrc.replace(/(fiddleurl\s*:\s*['"]?)\(auto fill by runme\.js\)/, "$1" + urls.edit);
widgetSrc = widgetSrc.replace(/(githuburl\s*:\s*['"]?)\(auto fill by runme\.js\)/, "$1" + urls.github);
widgetSrc = widgetSrc.replace(/(testurl\s*:\s*['"]?)\(auto fill by runme\.js\)/, "$1" + urls.test);
// rewrite the javascript
//fs.writeFileSync('widget.js', widgetSrc);
eval(widgetSrc);
//console.log("evaled the widget.js");
//isEvaled = true;
// generate docs
for (var key in widget) {
var obj = widget[key];
widgetDocs[key] = {
type: typeof obj,
property: false,
method: false,
descSrc: "",
descHtml: "",
descMd: "", // markdown
};
var objDoc = widgetDocs[key];
if (typeof obj === 'function') {
// grab first line of source code
var srcFirstLine = obj.toString().substring(0, obj.toString().indexOf("\n"));
// drop {
srcFirstLine = srcFirstLine.replace(/\{/, "");
//srcFirstLine = srcFirstLine.replace(/function\s*\(\s*\)\s*\{/, "");
objDoc.descHtml = srcFirstLine; // + "<br><br>";
objDoc.descMd = srcFirstLine; // + "\n\n";
// we have the source code for the function, so go find it, but then
// look at the comments above it
//var indx = widgetSrc.indexOf(obj.toString());
var indx = widgetSrc.regexIndexOf(new RegExp(key + "\\s*?:\\s*?function"));
if (indx > 0) {
//s += "found index " + indx;
// extract docs from above this method
var docItem = extractDocs(indx);
if (docItem.html.length > 0) {
if (objDoc.descHtml.length > 0) objDoc.descHtml += '<br><br>';
objDoc.descHtml += docItem.html;
}
if (docItem.md.length > 0) {
if (objDoc.descMd.length > 0) objDoc.descMd += '\n\n';
objDoc.descMd += docItem.md;
}
objDoc.descSrc += docItem.src;
}
} else if (typeof obj === 'string') {
objDoc.descSrc = JSON.stringify(obj);
// if there's a default value then put it in docs
if (obj.length > 0) {
//objDoc.descHtml += "Default value: " + JSON.stringify(obj);
objDoc.descHtml += JSON.stringify(obj);
objDoc.descMd += JSON.stringify(obj);
}
// see if any docs in src code
var indx = widgetSrc.regexIndexOf(new RegExp(key + "\\s*?:"));
if (indx > 0) {
// extract docs from above this method
var docItem = extractDocs(indx);
if (docItem.html.length > 0) {
if (objDoc.descHtml.length > 0) objDoc.descHtml += '<br><br>';
objDoc.descHtml += docItem.html;
}
if (docItem.md.length > 0) {
if (objDoc.descMd.length > 0) objDoc.descMd += '\n\n';
objDoc.descMd += docItem.md;
}
objDoc.descSrc += docItem.src;
}
} else {
objDoc.descSrc = JSON.stringify(obj, null, " ");
if (key.match(/publish|subscribe|foreignPublish|foreignSubscribe/)) {
objDoc.descHtml += "Please see docs above.";
}
// look for description above or at end of line of source code
var indx = widgetSrc.regexIndexOf(new RegExp(key + "\\s*?:"));
if (indx > 0) {
// extract docs from above this method
var docItem = extractDocs(indx);
if (docItem.html.length > 0) {
if (objDoc.descHtml.length > 0) objDoc.descHtml += '<br><br>';
objDoc.descHtml += docItem.html;
}
if (docItem.md.length > 0) {
if (objDoc.descMd.length > 0) objDoc.descMd += '\n\n';
objDoc.descMd += docItem.md;
}
objDoc.descSrc += docItem.src;
}
}
}
}
// We are passed in an indx which is where we start in the overall
// widgetSrc. We look backwards, i.e. line/lines above for comments
var extractDocs = function(indx) {
var o = {
html: "", // html docs
src: "", // src docs
md: "" // markdown docs
}
// if there is a */ up to this indx we've got a comment
// reverse string to search backwards
var partial = widgetSrc.substring(0, indx);
var widgetSrcRev = reverseStr(partial);
//console.log("candidate for " + key + ":", widgetSrcRev.substring(0, 100));
// if the next item in rev str is /* then we have a comment
if (widgetSrcRev.match(/^[\s\r\n]+\/\*/)) {
// search to **/ which is /**
var indx2 = widgetSrcRev.indexOf("**/");
var comment = widgetSrcRev.substring(0, indx2);
comment = reverseStr(comment);
//console.log("comment for " + key + ":", comment);
o.src = comment;
// cleanup
comment = comment.replace(/[\r\n\s\*\/]+$/, ""); // cleanup end
var lines = comment.split(/\r?\n/);
var newlines = [];
for (var ctr in lines) {
var line = lines[ctr];
line = line.replace(/^[\s\*]+/g, "");
newlines.push(line);
}
comment = newlines.join("\n");
comment = comment.replace(/^[\s\r\n]/, ""); // cleanup beginning
// convert two newlines to <br><br>
comment = comment.replace(/\n\n/g, "<br><br>");
// put more space in front of @param
comment = comment.replace(/\@param\s+?(\S+)\s+?(\S+)\s*?\-?\s*?/g, "<br><br><b>$2</b> ($1) ");
//console.log("clean comment for " + key + " " + comment);
o.html += comment;
// make it work for markdown
o.md += comment.replace("<br><br>", "\n\n").replace(/<b>|<\/b>/g, "");
}
return o;
}
// create our own version of cpdefine so we can use the evalWidgetJs above
cpdefine = function(myid, mydeps, callback) {
widget = callback();
id = myid;
deps = mydeps;
//console.log("cool, our own cpdefine got called. id:", id, "deps:", deps);
}
// define other top-level methods just to avoid errors
requirejs = function() {}
requirejs.config = function() {};
cprequire_test = function() {};
var generateWidgetReadme = function() {
// First we have to eval so stuff is in memory
evalWidgetJs();
// Spit out Markdown docs
var md = `# $widget-id
$widget-desc
$widget-img
## ChiliPeppr $widget-name
All ChiliPeppr widgets/elements are defined using cpdefine() which is a method
that mimics require.js. Each defined object must have a unique ID so it does
not conflict with other ChiliPeppr widgets.
| Item | Value |
| ------------- | ------------- |
| ID | $widget-id |
| Name | $widget-name |
| Description | $widget-desc |
| chilipeppr.load() URL | $widget-cpurl |
| Edit URL | $widget-editurl |
| Github URL | $widget-giturl |
| Test URL | $widget-testurl |
## Example Code for chilipeppr.load() Statement
You can use the code below as a starting point for instantiating this widget
inside a workspace or from another widget. The key is that you need to load
your widget inlined into a div so the DOM can parse your HTML, CSS, and
Javascript. Then you use cprequire() to find your widget's Javascript and get
back the instance of it.
\`\`\`javascript
$widget-cploadjs
\`\`\`
## Publish
This widget/element publishes the following signals. These signals are owned by this widget/element and are published to all objects inside the ChiliPeppr environment that listen to them via the
chilipeppr.subscribe(signal, callback) method.
To better understand how ChiliPeppr's subscribe() method works see amplify.js's documentation at http://amplifyjs.com/api/pubsub/
<table id="com-chilipeppr-elem-pubsubviewer-pub" class="table table-bordered table-striped">
<thead>
<tr>
<th style="">Signal</th>
<th style="">Description</th>
</tr>
</thead>
<tbody>
$row-publish-start
<tr valign="top"><td colspan="2">(No signals defined in this widget/element)</td></tr>
$row-publish-end
</tbody>
</table>
## Subscribe
This widget/element subscribes to the following signals. These signals are owned by this widget/element. Other objects inside the ChiliPeppr environment can publish to these signals via the chilipeppr.publish(signal, data) method.
To better understand how ChiliPeppr's publish() method works see amplify.js's documentation at http://amplifyjs.com/api/pubsub/
<table id="com-chilipeppr-elem-pubsubviewer-sub" class="table table-bordered table-striped">
<thead>
<tr>
<th style="">Signal</th>
<th style="">Description</th>
</tr>
</thead>
<tbody>
$row-subscribe-start
<tr valign="top"><td colspan="2">(No signals defined in this widget/element)</td></tr>
$row-subscribe-end
</tbody>
</table>
## Foreign Publish
This widget/element publishes to the following signals that are owned by other objects.
To better understand how ChiliPeppr's subscribe() method works see amplify.js's documentation at http://amplifyjs.com/api/pubsub/
<table id="com-chilipeppr-elem-pubsubviewer-foreignpub" class="table table-bordered table-striped">
<thead>
<tr>
<th style="">Signal</th>
<th style="">Description</th>
</tr>
</thead>
<tbody>
$row-foreign-publish-start
<tr><td colspan="2">(No signals defined in this widget/element)</td></tr>
$row-foreign-publish-end
</tbody>
</table>
## Foreign Subscribe
This widget/element publishes to the following signals that are owned by other objects.
To better understand how ChiliPeppr's publish() method works see amplify.js's documentation at http://amplifyjs.com/api/pubsub/
<table id="com-chilipeppr-elem-pubsubviewer-foreignsub" class="table table-bordered table-striped">
<thead>
<tr>
<th style="">Signal</th>
<th style="">Description</th>
</tr>
</thead>
<tbody>
$row-foreign-subscribe-start
<tr><td colspan="2">(No signals defined in this widget/element)</td></tr>
$row-foreign-subscribe-end
</tbody>
</table>
## Methods / Properties
The table below shows, in order, the methods and properties inside the widget/element.
<table id="com-chilipeppr-elem-methodsprops" class="table table-bordered table-striped">
<thead>
<tr>
<th style="">Method / Property</th>
<th>Type</th>
<th style="">Description</th>
</tr>
</thead>
<tbody>
$row-methods-start
<tr><td colspan="2">(No methods or properties defined in this widget/element)</td></tr>
$row-methods-end
</tbody>
</table>
## About ChiliPeppr
[ChiliPeppr](http://chilipeppr.com) is a hardware fiddle, meaning it is a
website that lets you easily
create a workspace to fiddle with your hardware from software. ChiliPeppr provides
a [Serial Port JSON Server](https://github.com/johnlauer/serial-port-json-server)
that you run locally on your computer, or remotely on another computer, to connect to
the serial port of your hardware like an Arduino or other microcontroller.
You then create a workspace at ChiliPeppr.com that connects to your hardware
by starting from scratch or forking somebody else's
workspace that is close to what you are after. Then you write widgets in
Javascript that interact with your hardware by forking the base template
widget or forking another widget that
is similar to what you are trying to build.
ChiliPeppr is massively capable such that the workspaces for
[TinyG](http://chilipeppr.com/tinyg) and [Grbl](http://chilipeppr.com/grbl) CNC
controllers have become full-fledged CNC machine management software used by
tens of thousands.
ChiliPeppr has inspired many people in the hardware/software world to use the
browser and Javascript as the foundation for interacting with hardware. The
Arduino team in Italy caught wind of ChiliPeppr and now
ChiliPeppr's Serial Port JSON Server is the basis for the
[Arduino's new web IDE](https://create.arduino.cc/). If the Arduino team is excited about building on top
of ChiliPeppr, what
will you build on top of it?
`;
/*
var widgetUrl = 'http://' +
process.env.C9_PROJECT + '-' + process.env.C9_USER +
'.c9users.io/widget.html';
var testUrl = 'https://preview.c9users.io/' +
process.env.C9_USER + '/' +
process.env.C9_PROJECT + '/widget.html';
var editUrl = 'http://ide.c9.io/' +
process.env.C9_USER + '/' +
process.env.C9_PROJECT;
var github = getGithubUrl();
*/
md = md.replace(/\$widget-id/g, widget.id);
md = md.replace(/\$widget-name/g, widget.name);
md = md.replace(/\$widget-desc/g, widget.desc);
/*
md = md.replace(/\$widget-cpurl/g, github.rawurl);
md = md.replace(/\$widget-editurl/g, editUrl);
md = md.replace(/\$widget-giturl/g, github.url);
md = md.replace(/\$widget-testurl/g, testUrl);
*/
md = md.replace(/\$widget-cpurl/g, widget.url);
md = md.replace(/\$widget-editurl/g, widget.fiddleurl);
md = md.replace(/\$widget-giturl/g, widget.githuburl);
md = md.replace(/\$widget-testurl/g, widget.testurl);
var cpload = generateCpLoadStmt();
md = md.replace(/\$widget-cploadjs/g, cpload);
// see if there is a screenshot, if so use it
var img = "";
if (fs.existsSync("screenshot.png")) {
img = "![alt text]" +
"(screenshot.png \"Screenshot\")";
}
md = md.replace(/\$widget-img/g, img);
/*
// now generate methods/properties
//$widget-methprops
var s = "";
for (var key in widget) {
var obj = widget[key];
s += '| ' + key +
' | ' + typeof obj +
' | ';
s += widgetDocs[key].descHtml.replace(/[\r\n]/g, "");
s += ' |\n';
}
//console.log("adding markdown:", s);
md = md.replace(/\$widget-methprops/g, s);
// now do pubsub signals
var s;
s = appendKeyValForMarkdown(widget.publish);
md = md.replace(/\$widget-publish/, s);
s = appendKeyValForMarkdown(widget.subscribe);
md = md.replace(/\$widget-subscribe/, s);
s = appendKeyValForMarkdown(widget.foreignPublish);
md = md.replace(/\$widget-foreignpublish/, s);
s = appendKeyValForMarkdown(widget.foreignSubscribe);
md = md.replace(/\$widget-foreignsubscribe/, s);
*/
// do the properties and methods
var s = "";
for (var key in widget) {
var txt = widgetDocs[key].descHtml + '';
// get rid of spaces and returns after closing pre tags cuz it messes up github markdown
txt = txt.replace(/<\/pre>[\s\r\n]*/ig, "</pre>");
// convert double newlines to <br><br> tags
txt = txt.replace(/\n\s*\n\s*/g, "<br><br>");
var obj = widget[key];
s += '<tr valign="top"><td>' + key +
'</td><td>' + typeof obj +
'</td><td>';
s += txt;
s += '</td></tr>';
}
md = md.replace(/\$row-methods-start[\s\S]+?\$row-methods-end/g, s);
// now do pubsub signals
var s;
s = appendKeyVal(widget.publish);
md = md.replace(/\$row-publish-start[\s\S]+?\$row-publish-end/, s);
s = appendKeyVal(widget.subscribe);
md = md.replace(/\$row-subscribe-start[\s\S]+?\$row-subscribe-end/g, s);
s = appendKeyVal(widget.foreignPublish);
md = md.replace(/\$row-foreign-publish-start[\s\S]+?\$row-foreign-publish-end/, s);
s = appendKeyVal(widget.foreignSubscribe);
md = md.replace(/\$row-foreign-subscribe-start[\s\S]+?\$row-foreign-subscribe-end/g, s);
// now write out the auto-gen file
fs.writeFileSync("README.md", md);
console.log("Rewrote README.md");
}
var appendKeyValForMarkdown = function(data, id) {
var str = "";
if (data != null && typeof data === 'object' && Object.keys(data).length > 0) {
//var keys = Object.keys(data);
for (var key in data) {
str += '| /' + widget.id + "" + key + ' | ' + data[key].replace(/\n/, "<br>") + ' |';
}
} else {
str = '| (No signals defined in this widget/element) |';
}
return str;
}
var generateWidgetDocs = function() {
// First we have to eval so stuff is in memory
evalWidgetJs();
// Spit out docs
var html = "";
html += `
<html>
<head>
<title>$pubsub-name</title>
<!-- ChiliPeppr is based on bootstrap CSS. -->
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script type="text/javascript" charset="utf-8" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" charset="utf-8" src="//i2dcui.appspot.com/js/bootstrap/bootstrap_3_1_1.min.js"></script>
<style type='text/css'>
div#editor-box {
border: 2px dashed #7f7f7f;
text-align: center;
vertical-align: middle;
padding: 10px 10px 10px 10px;
line-height: 10px;
max-height: 500px;
max-width: 100%;
}
div#editor-box > img {
max-width: 500px;
max-height: 500px;
}
.contain {
background-size: 100%;
background-repeat: no-repeat;
}
</style>
<script type='text/javascript'>
//<![CDATA[
$(function() {
function ajaxPushToGithub() {
var message = prompt("Please enter your push message", "");
console.log("pushing to github...");
$('.ajax-results').removeClass('hidden').html("Pushing your changes to Github");
$.ajax({
url: "pushtogithub",
data: { message: message }
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Data back from pushtogithub:", data );
if (data && data.success) {
// success
$('.ajax-results').html(data.desc + "<br><br>" + "<pre>" + data.log + "</pre>");
} else {
// error
$('.ajax-results').html("<pre>ERROR:" + JSON.stringify(data, null, "\t") + "</pre>");
}
}
});
}
function ajaxPullFromGithub() {
console.log("pushing to github...");
$('.ajax-results').removeClass('hidden').html("Pulling your changes from Github");
$.ajax({
url: "pullfromgithub"
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Data back from pushtogithub:", data );
if (data && data.success) {
// success
$('.ajax-results').html(data.desc + "<br><br>" + "<pre>" + data.log + "</pre>");
} else {
// error
$('.ajax-results').html("<pre>ERROR:" + JSON.stringify(data, null, "\t") + "</pre>");
}
}
});
}
function ajaxMergeFromCpTemplateRepo() {
console.log("ajaxMergeFromCpTemplateRepo to github...");
$('.ajax-results').removeClass('hidden').html("Merging the latest changes (if any) from the ChiliPeppr Template to your fork");
$.ajax({
url: "mergeFromCpTemplateRepo"
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Data back from ajaxMergeFromCpTemplateRepo:", data );
if (data && data.success) {
// success
$('.ajax-results').html(data.desc + "<br><br>" + "<pre>" + data.log + "</pre>");
} else {
// error
$('.ajax-results').html("<pre>ERROR:" + JSON.stringify(data, null, "\t") + "</pre>");
}
}
});
}
function ajaxUploadScreenshot() {
//var canvas = document.getElementById('canvas' + index);
//var dataURL = canvas.toDataURL();
var dataURL = $('#editor-box').css('background-image');
console.log("ajaxUploadScreenshot..., data:", dataURL);
$('.ajax-results').removeClass('hidden').html("Uploading screenshot. ");
$.ajax({
type: "POST",
url: "uploadscreenshot",
data: {
imgBase64: dataURL
}
}).done(function(data) {
console.log('all_saved');
if (data && data.success) {
// success
$('.ajax-results').html(data.desc);
} else {
// error
$('.ajax-results').html("<pre>ERROR:" + JSON.stringify(data, null, "\t") + "</pre>");
}
});
}
// Created by STRd6
// MIT License
// jquery.paste_image_reader.js
(function ($) {
var defaults;
$.event.fix = (function (originalFix) {
return function (event) {
event = originalFix.apply(this, arguments);
if (event.type.indexOf('copy') === 0 || event.type.indexOf('paste') === 0) {
event.clipboardData = event.originalEvent.clipboardData;
}
return event;
};
})($.event.fix);
defaults = {
callback: $.noop,
matchType: /image.*/
};
return $.fn.pasteImageReader = function (options) {
if (typeof options === "function") {
options = {
callback: options
};
}
options = $.extend({}, defaults, options);
return this.each(function () {
var $this, element;
element = this;
$this = $(this);
return $this.bind('paste', function (event) {
var clipboardData, found;
found = false;
clipboardData = event.clipboardData;
return Array.prototype.forEach.call(clipboardData.types, function (type, i) {
var file, reader;
if (found) {
return;
}
if (type.match(options.matchType) || clipboardData.items[i].type.match(options.matchType)) {
file = clipboardData.items[i].getAsFile();
reader = new FileReader();
reader.onload = function (evt) {
return options.callback.call(element, {
dataURL: evt.target.result,
event: evt,
file: file,
name: file.name
});
};
reader.readAsDataURL(file);
//snapshoot();
return found = true;
}
backgroundImage
});
});
});
};
})(jQuery);
$("html").pasteImageReader(function (results) {
var dataURL, filename;
filename = results.filename, dataURL = results.dataURL;
$data.text(dataURL);
$size.val(results.file.size);
$type.val(results.file.type);
$test.attr('href', dataURL);
var img = document.createElement('img');
img.src = dataURL;
var w = img.width;
var h = img.height;
$width.val(w); $height.val(h);
$("div#editor-box").height(h);
return $(".active").css({
backgroundImage: "url(" + dataURL + ")"
}).data({ 'width': w, 'height': h });
});
var $data, $size, $type, $test, $width, $height;
$(function () {
$data = $('.data');
$size = $('.size');
$type = $('.type');
$test = $('#test');
$width = $('#width');
$height = $('#height');
$('.target').on('click', function () {
var $this = $(this);
var bi = $this.css('background-image');
if (bi != 'none') {
$data.text(bi.substr(4, bi.length - 6));
}
$('.active').removeClass('active');
$this.addClass('active');
$this.toggleClass('contain');
$width.val($this.data('width'));
$height.val($this.data('height'));
if ($this.hasClass('contain')) {
$this.css({ 'width': $this.data('width'), 'height': $this.data('height'), 'z-index': '10' });
} else {
$this.css({ 'width': '', 'height': '', 'z-index': '' });
}
});
});
function init() {
$('.btn-pushtogithub').click(ajaxPushToGithub);
$('.btn-pullfromgithub').click(ajaxPullFromGithub);
$('.btn-mergetemplate').click(ajaxMergeFromCpTemplateRepo);
$('.btn-uploadscreenshot').click(ajaxUploadScreenshot);
console.log("Init complete");
}
init();
});
//]]>
</script>
</head>
<body style="padding:20px;">
<!-- pre-notes -->
<button class="btn btn-xs btn-default btn-pushtogithub">Push to Github</button>
<button class="btn btn-xs btn-default btn-pullfromgithub">Pull from Github</button>
<button class="btn btn-xs btn-default btn-mergetemplate">Merge the ChiliPeppr Template to this Repo</button>
<div class="hidden well ajax-results" style="margin-bottom:0;">
Results
</div>
<p style="padding-top:20px;">Note: Paste image from clipboard here to generate screenshot of widget for docs.</p>
<button class="btn btn-xs btn-default btn-uploadscreenshot" style="margin-bottom:5px;">Upload Screenshot</button>
<div id="editor-box" class="target" contenteditable="true">
</div>
<h1 class="page-header" style="margin-top:20px;">$pubsub-id</h1>
<p>$pubsub-desc</p>
<h2>ChiliPeppr Widget Docs</h2>
<p>The content below is auto generated as long as you follow the standard
template for a ChiliPeppr widget from
<a href="">http://github.com/chilipeppr/widget-template</a>.</p>
<table class="table table-bordered table-striped">