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