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