Add support for markdown-style headlines (lines beginning with #)
[blerg.git] / www / js / blerg.js
1 /* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
2  * BSD-style license.  Please see the COPYING file for details.
3  */
4
5 // Config
6 var baseURL = '';
7 var recordTemplate = new Template(
8     '<div class="record">#{data}<div class="info">Posted #{date}. <a href="/\##{author}/#{record}">[permalink]</a></div></div>'
9 );
10 var tagRecordTemplate = new Template(
11     '<div class="record">#{data}<div class="info">Posted by <a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> on #{date}</div></div>'
12 );
13 var latestRecordsTemplate = new Template(
14     '<div class="record"><a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> #{data}</div>'
15 );
16
17 // Page elements
18 var items;
19
20 // Other globals
21 var currentPager;
22 var loginStatus;
23
24 // Object to keep track of login status
25 function LoginStatus() {
26     var cookies = {};
27     document.cookie.split(/;\s+/).each(function(v) {
28         kv = v.split('=');
29         cookies[kv[0]] = kv[1];
30     });
31     if (cookies.auth && cookies.username) {
32         this.loggedIn = true;
33         this.username = cookies.username;
34     } else {
35         this.loggedIn = false;
36         this.username = null;
37     }
38     this.update();
39 }
40
41 LoginStatus.prototype.login = function(username, password) {
42     new Ajax.Request(baseURL + '/login', {
43         parameters: {
44             username: username,
45             password: password
46         },
47         onSuccess: function(r) {
48             var j = r.responseText.evalJSON();
49             if (j && j.status == 'success') {
50                 this.loggedIn = true;
51                 this.username = username;
52                 document.cookie = "username=" + username;
53                 $('login.password').value = '';
54                 this.update();
55             } else {
56                 alert("Could not log in");
57                 $('login.username').focus();
58             }
59         }.bind(this),
60         onFailure: function(r) {
61             alert("Could not log in");
62             $('login.username').focus();
63         }
64     });
65 }
66
67 LoginStatus.prototype.logout = function() {
68     new Ajax.Request(baseURL + '/logout', {
69         parameters: {
70             username: this.username
71         },
72         onSuccess: function(r) {
73             this.loggedIn = false;
74             document.cookie = "auth=; expires=1-Jan-1970 00:00:00 GMT";
75             this.update();
76         }.bind(this)
77     });
78     document.cookie = "username=; expires=1-Jan-1970 00:00:00 GMT";
79 }
80
81 LoginStatus.prototype.update = function() {
82     if (this.loggedIn) {
83         $('userlink').href = '/#' + this.username;
84         $('userlink').update('@' + this.username);
85         $('reflink').href = '/#/ref/' + this.username;
86         $('login').hide();
87         $('logout').show();
88     } else {
89         $('post').hide();
90         $('login').show();
91         $('logout').hide();
92     }
93 }
94
95 LoginStatus.prototype.post = function(msg) {
96     if (!this.loggedIn) {
97         alert("You are not logged in!");
98         return;
99     }
100
101     new Ajax.Request(baseURL + '/put', {
102         parameters: {
103             username: this.username,
104             data: msg
105         },
106         onSuccess: function(r) {
107             var j = r.responseText.evalJSON();
108             if (j && j.status == 'success') {
109                 $('post.content').value = '';
110                 if (location.hash != '#' + this.username) {
111                     qlink(this.username);
112                 } else {
113                     currentPager.itemCount++;
114                     currentPager.reload();
115                 }
116             } else {
117                 alert('Post failed!');
118             }
119         }.bind(this),
120         onFailure: function(r) {
121             alert('Post failed!');
122         }
123     });
124 }
125
126
127 // Base object for paged data
128 function Pager() {
129     this.itemsPerPage = 10;
130 }
131
132 Pager.prototype.initPager = function() {
133     this.itemCache = new Hash();
134     this.pageStart = null;
135 }
136
137 Pager.prototype.olderPage = function() {
138     if (this.pageStart >= this.itemsPerPage) {
139         qlink(this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage));
140     }
141 }
142
143 Pager.prototype.newerPage = function() {
144     if (this.pageStart + this.itemsPerPage < this.itemCount) {
145         qlink(this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage));
146     }
147 }
148
149 Pager.prototype.addItems = function(items) {
150     items.each(function(v) {
151         if (!this.itemCache[v.id])
152             this.itemCache[v.id] = v;
153     }.bind(this));
154 }
155
156 Pager.prototype.displayItems = function() {
157     if (this.pageStart == undefined)
158         this.pageStart == this.itemCount - 1;
159     items.update();
160
161     if (this.pageStart != undefined && this.itemCache[this.pageStart]) {
162         var end = (this.pageStart >= this.itemsPerPage ? this.pageStart - this.itemsPerPage + 1 : 0);
163         for (var i = this.pageStart; i >= end; i--) {
164             items.insert(this.itemCache[i].html);
165         }
166     } else {
167         items.insert("There doesn't seem to be anything here!");
168     }
169
170     if (this.pageStart < this.itemCount - 1) {
171         $('newer_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage);
172         $('newer_link').show();
173     } else {
174         $('newer_link').hide();
175     }
176
177     if (this.pageStart >= 10) {
178         $('older_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage);
179         $('older_link').show();
180     } else {
181         $('older_link').hide();
182     }
183
184     document.body.scrollTo();
185 }
186
187 Pager.prototype.reload = function() {
188     this.pageStart = null;
189     this.loadItems(null, null, Pager.prototype.showPageAt.bind(this, this.itemCount - 1));
190 }
191
192 Pager.prototype.showPageAt = function(r) {
193     var end = (r - 9 > 0 ? r - 9 : 0);
194     if (this.itemCache[r] && this.itemCache[end]) {
195         this.pageStart = r;
196         this.displayItems();
197     } else {
198         this.loadItems((r >= 49 ? r - 49 : 0), r, Pager.prototype.showPageAt.bind(this, r));
199     }
200 }
201
202 Pager.prototype.showRecord = function(r) {
203     if (this.itemCache[r]) {
204         $('older_link').hide();
205         $('newer_link').hide();
206         items.update(this.itemCache[r].html);
207     } else {
208         this.loadItems(r, r, Pager.prototype.showRecord.bind(this, r));
209     }
210 }
211
212
213 // Object to render user pages
214 function User(username) {
215     this.initPager();
216     this.username = username;
217     this.baseFrag = username;
218
219     $$('[name=user.subscribelink]').each(Element.hide);
220     $$('[name=user.unsubscribelink]').each(Element.hide);
221
222     if (loginStatus.loggedIn) {
223         new Ajax.Request(baseURL + '/feedinfo/' + username, {
224             method: 'post',
225             parameters: {
226                 username: loginStatus.username
227             },
228             onSuccess: function(r) {
229                 var json = r.responseText.evalJSON();
230                 if (json.subscribed) {
231                     $$('[name=user.subscribelink]').each(Element.hide);
232                     $$('[name=user.unsubscribelink]').each(Element.show);
233                 } else {
234                     $$('[name=user.subscribelink]').each(Element.show);
235                     $$('[name=user.unsubscribelink]').each(Element.hide);
236                 }
237             }
238         });
239     }
240
241     new Ajax.Request(baseURL + '/info/' + username, {
242         method: 'get',
243         onSuccess: function(r) {
244             var j = r.responseText.evalJSON();
245             if (j) {
246                 this.itemCount = parseInt(j.record_count);
247                 if (!this.pageStart)
248                     this.showPageAt(this.itemCount - 1);
249             }
250         }.bind(this)
251     });
252 }
253 User.prototype = new Pager();
254 User.prototype.constructor = User;
255
256 User.prototype.show = function() {
257     $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
258     $('welcome').hide();
259     items.show();
260     $('rss').show();
261     $('rsslink').href = '/rss/' + this.username;
262     $$('[name=user.reflink]').each(function(e) {
263         e.href = '/#/ref/' + this.username;
264     }.bind(this));
265     $('usercontrols').show();
266 }
267
268 User.prototype.loadItems = function(from, to, continuation) {
269     var url;
270     if (from != undefined && to != undefined) {
271         url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
272         this.pageStart = to;
273     } else {
274         url = baseURL + '/get/' + this.username;
275     }
276
277     new Ajax.Request(url, {
278         method: 'get',
279         onSuccess: function(r) {
280             var records = r.responseText.evalJSON();
281             if (records && records.length > 0) {
282                 records.each(function(v) {
283                     v.id = v.record;
284                     v.author = this.username;
285                     mangleRecord(v, recordTemplate);
286                 }.bind(this));
287                 this.addItems(records);
288                 if (!this.pageStart)
289                     this.pageStart = records[0].recInt;
290             }
291             continuation();
292         }.bind(this),
293         onFailure: function(r) {
294             this.displayItems();
295         }.bind(this),
296         on404: function(r) {
297             displayError('User not found');
298         }
299     });
300 }
301
302 function mangleRecord(record, template) {
303     record.recInt = parseInt(record.record);
304
305     var lines = record.data.split(/\r?\n/);
306     if (lines[lines.length - 1] == '')
307         lines.pop();
308
309     var out = ['<p>'];
310     var endpush = null;
311     var listMode = false;
312     lines.each(function(l) {
313         if (l == '') {
314             if (out[out.length - 1] == '<br>') {
315                 out[out.length - 1] = '<p>';
316             }
317             if (out[out.length - 1] == '</li>') {
318                 out.push('</ul>');
319                 out.push('<p>');
320                 listMode = false;
321             }
322             return;
323         }
324
325         // Put quoted material into a special paragraph
326         if (l[0] == '>') {
327             var pi = out.lastIndexOf('<p>');
328             if (pi != -1) {
329                 out[pi] = '<p class="quote">';
330                 l = l.replace(/^>\s*/, '');
331             }
332         }
333
334         // Sanitize HTML input
335         l = l.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
336
337         // Turn HTTP URLs into links
338         l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
339
340         // Turn markdown links into links
341         l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
342
343         // Turn *foo* into italics and **foo** into bold
344         l = l.replace(/([^\w\\]|^)\*\*(\w[^*]*)\*\*(\W|$)/g, '$1<b>$2</b>$3');
345         l = l.replace(/([^\w\\]|^)\*(\w[^*]*)\*(\W|$)/g, '$1<i>$2</i>$3');
346
347         // Remove backslashes from escaped metachars
348         l = l.replace(/\\([*\[\]])/g, '$1');
349
350         // Turn refs and tags into links
351         l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
352         l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
353
354         // Create lists when lines begin with *
355         if (l[0] == '*') {
356             if (!listMode) {
357                 var pi = out.lastIndexOf('<p>');
358                 out[pi] = '<ul>';
359                 listMode = true;
360             }
361             l = l.replace(/^\*\s*/, '');
362             out.push('<li>');
363             endpush = '</li>';
364         }
365
366         // Create headers when lines begin with = or #
367         if (l[0] == '=' || l[0] == '#') {
368             var m = l.match(/^([=#]+)/);
369             var depth = m[1].length;
370             if (depth <= 5) {
371                 l = l.replace(/^[=#]+\s*/, '').replace(/\s*[=#]+$/, '');
372                 out.push('<h' + depth + '>');
373                 endpush = '</h' + depth + '>';
374             }
375         }
376
377         out.push(l);
378         if (endpush) {
379             out.push(endpush);
380             endpush = null;
381         } else {
382             out.push('<br>');
383         }
384     });
385     while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
386         out.pop();
387     if (listMode)
388         out.push('</ul>');
389
390     record.data = out.join('');
391     record.date = (new Date(record.timestamp * 1000)).toString();
392     record.html = template.evaluate(record);
393 }
394
395 function displayError(msg) {
396     items.innerText = msg;
397 }
398
399
400 // Object for browsing tags
401 function Tag(type, tag) {
402     this.initPager();
403     this.type = type;
404     this.tag = tag;
405
406     var url = baseURL + "/tag/";
407     switch(type) {
408     case 'tag':
409         //url += '%23';
410         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
411         this.baseFrag = '/tag/' + tag;
412         break;
413     case 'ref':
414         url += '%40';
415         this.baseFrag = '/ref/' + tag;
416         break;
417     default:
418         alert('Invalid tag type: ' + type);
419         return;
420     }
421     url += tag;
422
423     new Ajax.Request(url, {
424         method: 'get',
425         onSuccess: function(r) {
426             var j = r.responseText.evalJSON();
427             if (j) {
428                 var maxid = j.length - 1;
429                 j.each(function(v, i) {
430                     v.id = maxid - i;
431                     mangleRecord(v, tagRecordTemplate)
432                 });
433                 this.addItems(j);
434                 this.pageStart = j.length - 1;
435                 this.itemCount = j.length;
436             }
437             this.displayItems();
438         }.bind(this),
439         onFailure: function(r) {
440             this.displayItems();
441         }.bind(this)
442     });
443
444 }
445 Tag.prototype = new Pager();
446 Tag.prototype.constructor = Tag;
447
448 Tag.prototype.show = function() {
449     var ctype = {ref: '@', tag: '#'}[this.type];
450
451     $$('[name=section]').each(function(v) {
452         v.update(' about ' + ctype + this.tag);
453     }.bind(this));
454     $('welcome').hide();
455     $('post').hide();
456     $('older_link').hide();
457     $('newer_link').hide();
458     $('rss').hide();
459     items.show();
460     $('usercontrols').hide();
461 }
462
463
464 // Pager for browsing subscription feeds
465 function Feed() {
466     this.initPager();
467     this.username = loginStatus.username;
468     this.baseFrag = '/feed';
469
470     new Ajax.Request(baseURL + '/feed', {
471         method: 'post',
472         parameters: {
473             username: loginStatus.username
474         },
475         onSuccess: function(r) {
476             var response = r.responseText.evalJSON();
477             if (response) {
478                 var maxid = response.length - 1;
479                 response.each(function(v, i) {
480                     v.id = maxid - i;
481                     mangleRecord(v, tagRecordTemplate)
482                 });
483                 this.addItems(response);
484                 this.pageStart = response.length - 1;
485                 this.itemCount = response.length;
486             }
487             this.displayItems();
488         }.bind(this),
489         onFailure: function(r) {
490             this.displayItems();
491         }.bind(this)
492     });
493 }
494 Feed.prototype = new Pager();
495 Feed.prototype.constructor = Feed;
496
497 Feed.prototype.show = function() {
498     $$('[name=section]').each(function(v) {
499         v.update(' ' + loginStatus.username + "'s spycam");
500     }.bind(this));
501     $('welcome').hide();
502     $('post').hide();
503     $('older_link').hide();
504     $('newer_link').hide();
505     $('rss').hide();
506     items.show();
507     $('usercontrols').hide();
508 }
509
510
511 function postPopup() {
512     if (loginStatus.loggedIn) {
513         var post = $('post');
514         if (post.visible()) {
515             post.hide();
516         } else {
517             post.show();
518             if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
519                 $('post.content').value = '@' + currentPager.username + ': ';
520             }
521             $('post.content').focus();
522         }
523     }
524 }
525
526 function signup() {
527     var username = $('signup.username').value;
528     var password = $('signup.password').value;
529
530     new Ajax.Request(baseURL + '/create', {
531         parameters: {
532             username: username,
533             password: password
534         },
535         onSuccess: function(r) {
536             $('signup').hide();
537             qlink(username);
538
539             loginStatus.login(username, password);
540         },
541         onFailure: function(r) {
542             alert("Failed to create user");
543         }
544     });
545 }
546
547 function signup_cancel() {
548     $('signup').hide();
549     hashSwitch();
550 }
551
552 function subscribe() {
553     new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
554         method: 'post',
555         parameters: {
556             username: loginStatus.username
557         },
558         onSuccess: function(r) {
559             var response = r.responseText.evalJSON();
560             if (response.status == 'success') {
561                 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
562                 $$('[name=user.subscribelink]').each(Element.hide);
563                 $$('[name=user.unsubscribelink]').each(Element.show);
564             } else {
565                 alert('Failed to subscribe. This is probably for the best');
566             }
567         },
568         onFailure: function(r) {
569             alert('Failed to subscribe. This is probably for the best');
570         }
571     });
572 }
573
574 function unsubscribe() {
575     new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
576         method: 'post',
577         parameters: {
578             username: loginStatus.username
579         },
580         onSuccess: function(r) {
581             var response = r.responseText.evalJSON();
582             if (response.status == 'success') {
583                 alert("You come to your senses.");
584                 $$('[name=user.subscribelink]').each(Element.show);
585                 $$('[name=user.unsubscribelink]').each(Element.hide);
586             } else {
587                 alert('You are unable to tear yourself away (because something failed on the server)');
588             }
589         },
590         onFailure: function(r) {
591             alert('You are unable to tear yourself away (because something failed on the server)');
592         }
593     });
594 }
595
596 var resizePostContentTimeout = null;
597 function resizePostContent() {
598     if (resizePostContentTimeout)
599         clearTimeout(resizePostContentTimeout);
600     resizePostContentTimeout = setTimeout(function() {
601         var c = $('post.content');
602         var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
603         var m = c.value.match(/\r?\n/g);
604         if (m)
605             lines += m.length;
606         if (lines <= 3) {
607             c.style.height = "";
608         } else {
609             c.style.height = (lines * 17) + "pt";
610         }
611         resizePostContentTimeout = null;
612     }, 150);
613 }
614
615 var tickerTimer = null;
616 var tickerHead, tickerTail;
617
618 function tickerFader(a, b, p) {
619     var p2 = 1 - p;
620
621     a.style.opacity = p;
622     a.style.lineHeight = (100 * p) + '%';
623
624     b.style.opacity = p2;
625     b.style.lineHeight = (100 * p2) + '%';
626     if (p == 1.0)
627         b.hide();
628 }
629
630 function ticker() {
631     tickerHead.show();
632     Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
633     tickerHead = tickerHead.nextSibling;
634     tickerTail = tickerTail.nextSibling;
635     if (tickerHead == null) {
636         stopTicker();
637         loadLatest.delay(10);
638     }
639 }
640
641 function startTicker() {
642     stopTicker();
643     for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
644         elem.hide();
645     }
646
647     // Show the first five
648     tickerHead = $('latest-posts').firstChild;
649     for (var i = 0; i < 10 && tickerHead; i++) {
650         tickerHead.show();
651         tickerHead = tickerHead.nextSibling;
652     }
653     tickerTail = $('latest-posts').firstChild;
654     tickerTimer = setInterval(ticker, 5000);
655 }
656
657 function stopTicker() {
658     if (tickerTimer)
659         clearInterval(tickerTimer);
660     tickerTimer = null;
661 }
662
663 function loadLatest() {
664     new Ajax.Request(baseURL + '/latest.json', {
665         onSuccess: function(r) {
666             var j = r.responseText.evalJSON();
667
668             $('latest-tags').update();
669             j.tags.each(function(v) {
670                 var a = new Element('a', {href: '/#/tag/' + v});
671                 a.insert('#' + v);
672                 a.onclick = "return qlink()";
673                 a.className = 'ref';
674                 $('latest-tags').insert(a);
675                 $('latest-tags').appendChild(document.createTextNode(' '));
676             });
677
678             $('latest-posts').update();
679             j.records.each(function(v) {
680                 v.data = v.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
681                 v.date = (new Date(v.timestamp * 1000)).toString();
682                 var html = latestRecordsTemplate.evaluate(v);
683                 $('latest-posts').insert(html);
684             });
685             startTicker();
686         }
687     });
688 }
689
690 function qlink(loc) {
691     if (loc) {
692         location.hash = loc;
693     } else if (event && event.target) {
694         location.href = event.target.href;
695     } else {
696         // Bogus qlink
697         return;
698     }
699     hashSwitch();
700     return false;
701 }
702
703 function hashSwitch() {
704     var m;
705     stopTicker();
706     if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
707         $('post').show();
708         $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
709     } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/)) {
710         if (!currentPager || !(currentPager instanceof Tag) || currentPager.type != m[1] || currentPager.tag != m[2])
711             currentPager = new Tag(m[1], m[2]);
712         currentPager.show();
713
714         if (m[3]) {
715             var r = parseInt(m[3]);
716             currentPager.showPageAt(r);
717         }
718     } else if (m = location.hash.match(/^#\/feed(?:\/p(\d+))?$/)) {
719         if (loginStatus.loggedIn) {
720             if (!currentPager || !(currentPager instanceof Feed) || currentPager.username != loginStatus.username)
721                 currentPager = new Feed();
722             currentPager.show();
723             if (m[3]) {
724                 var r = parseInt(m[3]);
725                 currentPager.showPageAt(r);
726             }
727         } else {
728             location.href = baseURL;
729         }
730     } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
731         if (!currentPager || !(currentPager instanceof User) || currentPager.username != m[1])
732             currentPager = new User(m[1]);
733         currentPager.show();
734         loginStatus.update();
735
736         if (m[3]) {
737             var r = parseInt(m[3]);
738             if (m[2] == 'p') {
739                 currentPager.showPageAt(r);
740             } else {
741                 currentPager.showRecord(r);
742             }
743         }
744         // Do nothing otherwise, the User constructor takes care of it
745     } else {
746         $$('[name=section]').each(function(v) { v.update('Welcome') });
747         $('signup').hide();
748         items.update();
749         items.hide();
750         $('newer_link').hide();
751         $('older_link').hide();
752         $('welcome').show();
753         $('rss').hide();
754         $('usercontrols').hide();
755         loadLatest();
756     }
757 }
758
759 var lastHash;
760 function hashCheck() {
761     if (location.hash != lastHash) {
762         lastHash = location.hash;
763         hashSwitch();
764     }
765 }
766
767 function init() {
768     items = $('items');
769     loginStatus = new LoginStatus();
770
771     lastHash = location.hash;
772     hashSwitch();
773
774     setInterval(hashCheck, 250);
775
776     document.body.observe('keyup', function(event) {
777         if (event.shiftKey && event.keyCode == 32) {
778             postPopup();
779             event.stop();
780         }
781     });
782     $('post.content').addEventListener('keyup', function(event) {
783         event.stopPropagation();
784     }, true);
785 }