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