21d7d34b407f7274852ec97167a83340e2187db1
[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         // Turn refs and tags into links
348         l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
349         l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
350
351         // Create lists when lines begin with *
352         if (l[0] == '*') {
353             if (!listMode) {
354                 var pi = out.lastIndexOf('<p>');
355                 out[pi] = '<ul>';
356                 listMode = true;
357             }
358             l = l.replace(/^\*\s*/, '');
359             out.push('<li>');
360             endpush = '</li>';
361         }
362
363         // Create headers when lines begin with =
364         if (l[0] == '=') {
365             var m = l.match(/^(=+)/);
366             var depth = m[1].length;
367             if (depth <= 5) {
368                 l = l.replace(/^=+\s*/, '').replace(/\s*=+$/, '');
369                 out.push('<h' + depth + '>');
370                 endpush = '</h' + depth + '>';
371             }
372         }
373
374         out.push(l);
375         if (endpush) {
376             out.push(endpush);
377             endpush = null;
378         } else {
379             out.push('<br>');
380         }
381     });
382     while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
383         out.pop();
384     if (listMode)
385         out.push('</ul>');
386
387     record.data = out.join('');
388     record.date = (new Date(record.timestamp * 1000)).toString();
389     record.html = template.evaluate(record);
390 }
391
392 function displayError(msg) {
393     items.innerText = msg;
394 }
395
396
397 // Object for browsing tags
398 function Tag(type, tag) {
399     this.initPager();
400     this.type = type;
401     this.tag = tag;
402
403     var url = baseURL + "/tag/";
404     switch(type) {
405     case 'tag':
406         //url += '%23';
407         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
408         this.baseFrag = '/tag/' + tag;
409         break;
410     case 'ref':
411         url += '%40';
412         this.baseFrag = '/ref/' + tag;
413         break;
414     default:
415         alert('Invalid tag type: ' + type);
416         return;
417     }
418     url += tag;
419
420     new Ajax.Request(url, {
421         method: 'get',
422         onSuccess: function(r) {
423             var j = r.responseText.evalJSON();
424             if (j) {
425                 var maxid = j.length - 1;
426                 j.each(function(v, i) {
427                     v.id = maxid - i;
428                     mangleRecord(v, tagRecordTemplate)
429                 });
430                 this.addItems(j);
431                 this.pageStart = j.length - 1;
432                 this.itemCount = j.length;
433             }
434             this.displayItems();
435         }.bind(this),
436         onFailure: function(r) {
437             this.displayItems();
438         }.bind(this)
439     });
440
441 }
442 Tag.prototype = new Pager();
443 Tag.prototype.constructor = Tag;
444
445 Tag.prototype.show = function() {
446     var ctype = {ref: '@', tag: '#'}[this.type];
447
448     $$('[name=section]').each(function(v) {
449         v.update(' about ' + ctype + this.tag);
450     }.bind(this));
451     $('welcome').hide();
452     $('post').hide();
453     $('older_link').hide();
454     $('newer_link').hide();
455     $('rss').hide();
456     items.show();
457     $('usercontrols').hide();
458 }
459
460
461 // Pager for browsing subscription feeds
462 function Feed() {
463     this.initPager();
464     this.username = loginStatus.username;
465     this.baseFrag = '/feed';
466
467     new Ajax.Request(baseURL + '/feed', {
468         method: 'post',
469         parameters: {
470             username: loginStatus.username
471         },
472         onSuccess: function(r) {
473             var response = r.responseText.evalJSON();
474             if (response) {
475                 var maxid = response.length - 1;
476                 response.each(function(v, i) {
477                     v.id = maxid - i;
478                     mangleRecord(v, tagRecordTemplate)
479                 });
480                 this.addItems(response);
481                 this.pageStart = response.length - 1;
482                 this.itemCount = response.length;
483             }
484             this.displayItems();
485         }.bind(this),
486         onFailure: function(r) {
487             this.displayItems();
488         }.bind(this)
489     });
490 }
491 Feed.prototype = new Pager();
492 Feed.prototype.constructor = Feed;
493
494 Feed.prototype.show = function() {
495     $$('[name=section]').each(function(v) {
496         v.update(' ' + loginStatus.username + "'s spycam");
497     }.bind(this));
498     $('welcome').hide();
499     $('post').hide();
500     $('older_link').hide();
501     $('newer_link').hide();
502     $('rss').hide();
503     items.show();
504     $('usercontrols').hide();
505 }
506
507
508 function postPopup() {
509     if (loginStatus.loggedIn) {
510         var post = $('post');
511         if (post.visible()) {
512             post.hide();
513         } else {
514             post.show();
515             if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
516                 $('post.content').value = '@' + currentPager.username + ': ';
517             }
518             $('post.content').focus();
519         }
520     }
521 }
522
523 function signup() {
524     var username = $('signup.username').value;
525     var password = $('signup.password').value;
526
527     new Ajax.Request(baseURL + '/create', {
528         parameters: {
529             username: username,
530             password: password
531         },
532         onSuccess: function(r) {
533             $('signup').hide();
534             qlink(username);
535
536             loginStatus.login(username, password);
537         },
538         onFailure: function(r) {
539             alert("Failed to create user");
540         }
541     });
542 }
543
544 function signup_cancel() {
545     $('signup').hide();
546     hashSwitch();
547 }
548
549 function subscribe() {
550     new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
551         method: 'post',
552         parameters: {
553             username: loginStatus.username
554         },
555         onSuccess: function(r) {
556             var response = r.responseText.evalJSON();
557             if (response.status == 'success') {
558                 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
559                 $$('[name=user.subscribelink]').each(Element.hide);
560                 $$('[name=user.unsubscribelink]').each(Element.show);
561             } else {
562                 alert('Failed to subscribe. This is probably for the best');
563             }
564         },
565         onFailure: function(r) {
566             alert('Failed to subscribe. This is probably for the best');
567         }
568     });
569 }
570
571 function unsubscribe() {
572     new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
573         method: 'post',
574         parameters: {
575             username: loginStatus.username
576         },
577         onSuccess: function(r) {
578             var response = r.responseText.evalJSON();
579             if (response.status == 'success') {
580                 alert("You come to your senses.");
581                 $$('[name=user.subscribelink]').each(Element.show);
582                 $$('[name=user.unsubscribelink]').each(Element.hide);
583             } else {
584                 alert('You are unable to tear yourself away (because something failed on the server)');
585             }
586         },
587         onFailure: function(r) {
588             alert('You are unable to tear yourself away (because something failed on the server)');
589         }
590     });
591 }
592
593 var resizePostContentTimeout = null;
594 function resizePostContent() {
595     if (resizePostContentTimeout)
596         clearTimeout(resizePostContentTimeout);
597     resizePostContentTimeout = setTimeout(function() {
598         var c = $('post.content');
599         var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
600         var m = c.value.match(/\r?\n/g);
601         if (m)
602             lines += m.length;
603         if (lines <= 3) {
604             c.style.height = "";
605         } else {
606             c.style.height = (lines * 17) + "pt";
607         }
608         resizePostContentTimeout = null;
609     }, 150);
610 }
611
612 var tickerTimer = null;
613 var tickerHead, tickerTail;
614
615 function tickerFader(a, b, p) {
616     var p2 = 1 - p;
617
618     a.style.opacity = p;
619     a.style.lineHeight = (100 * p) + '%';
620
621     b.style.opacity = p2;
622     b.style.lineHeight = (100 * p2) + '%';
623     if (p == 1.0)
624         b.hide();
625 }
626
627 function ticker() {
628     tickerHead.show();
629     Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
630     tickerHead = tickerHead.nextSibling;
631     tickerTail = tickerTail.nextSibling;
632     if (tickerHead == null) {
633         stopTicker();
634         loadLatest.delay(10);
635     }
636 }
637
638 function startTicker() {
639     stopTicker();
640     for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
641         elem.hide();
642     }
643
644     // Show the first five
645     tickerHead = $('latest-posts').firstChild;
646     for (var i = 0; i < 10 && tickerHead; i++) {
647         tickerHead.show();
648         tickerHead = tickerHead.nextSibling;
649     }
650     tickerTail = $('latest-posts').firstChild;
651     tickerTimer = setInterval(ticker, 5000);
652 }
653
654 function stopTicker() {
655     if (tickerTimer)
656         clearInterval(tickerTimer);
657     tickerTimer = null;
658 }
659
660 function loadLatest() {
661     new Ajax.Request(baseURL + '/latest.json', {
662         onSuccess: function(r) {
663             var j = r.responseText.evalJSON();
664
665             $('latest-tags').update();
666             j.tags.each(function(v) {
667                 var a = new Element('a', {href: '/#/tag/' + v});
668                 a.insert('#' + v);
669                 a.onclick = "return qlink()";
670                 a.className = 'ref';
671                 $('latest-tags').insert(a);
672                 $('latest-tags').appendChild(document.createTextNode(' '));
673             });
674
675             $('latest-posts').update();
676             j.records.each(function(v) {
677                 v.data = v.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
678                 v.date = (new Date(v.timestamp * 1000)).toString();
679                 var html = latestRecordsTemplate.evaluate(v);
680                 $('latest-posts').insert(html);
681             });
682             startTicker();
683         }
684     });
685 }
686
687 function qlink(loc) {
688     if (loc) {
689         location.hash = loc;
690     } else if (event && event.target) {
691         location.href = event.target.href;
692     } else {
693         // Bogus qlink
694         return;
695     }
696     hashSwitch();
697     return false;
698 }
699
700 function hashSwitch() {
701     var m;
702     stopTicker();
703     if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
704         $('post').show();
705         $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
706     } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/)) {
707         if (!currentPager || !(currentPager instanceof Tag) || currentPager.type != m[1] || currentPager.tag != m[2])
708             currentPager = new Tag(m[1], m[2]);
709         currentPager.show();
710
711         if (m[3]) {
712             var r = parseInt(m[3]);
713             currentPager.showPageAt(r);
714         }
715     } else if (m = location.hash.match(/^#\/feed(?:\/p(\d+))?$/)) {
716         if (loginStatus.loggedIn) {
717             if (!currentPager || !(currentPager instanceof Feed) || currentPager.username != loginStatus.username)
718                 currentPager = new Feed();
719             currentPager.show();
720             if (m[3]) {
721                 var r = parseInt(m[3]);
722                 currentPager.showPageAt(r);
723             }
724         } else {
725             location.href = baseURL;
726         }
727     } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
728         if (!currentPager || !(currentPager instanceof User) || currentPager.username != m[1])
729             currentPager = new User(m[1]);
730         currentPager.show();
731         loginStatus.update();
732
733         if (m[3]) {
734             var r = parseInt(m[3]);
735             if (m[2] == 'p') {
736                 currentPager.showPageAt(r);
737             } else {
738                 currentPager.showRecord(r);
739             }
740         }
741         // Do nothing otherwise, the User constructor takes care of it
742     } else {
743         $$('[name=section]').each(function(v) { v.update('Welcome') });
744         $('signup').hide();
745         items.update();
746         items.hide();
747         $('newer_link').hide();
748         $('older_link').hide();
749         $('welcome').show();
750         $('rss').hide();
751         $('usercontrols').hide();
752         loadLatest();
753     }
754 }
755
756 var lastHash;
757 function hashCheck() {
758     if (location.hash != lastHash) {
759         lastHash = location.hash;
760         hashSwitch();
761     }
762 }
763
764 function init() {
765     items = $('items');
766     loginStatus = new LoginStatus();
767
768     lastHash = location.hash;
769     hashSwitch();
770
771     setInterval(hashCheck, 250);
772
773     document.body.observe('keyup', function(event) {
774         if (event.shiftKey && event.keyCode == 32) {
775             postPopup();
776             event.stop();
777         }
778     });
779     $('post.content').addEventListener('keyup', function(event) {
780         event.stopPropagation();
781     }, true);
782 }