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