Add a way of seeing other users' chatter
[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" href="/\##{author}">@#{author}</a> on #{date}</div></div>'
12 );
13 var latestRecordsTemplate = new Template(
14     '<div class="record"><a class="author" 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     new Ajax.Request(baseURL + '/info/' + username, {
192         method: 'get',
193         onSuccess: function(r) {
194             var j = r.responseText.evalJSON();
195             if (j) {
196                 this.itemCount = parseInt(j.record_count);
197                 this.displayItems();
198             }
199         }.bind(this)
200     });
201 }
202 User.prototype = new Pager();
203 User.prototype.constructor = User;
204
205 User.prototype.show = function() {
206     $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
207     $('welcome').hide();
208     items.show();
209     $('rss').show();
210     $('rsslink').href = '/rss/' + this.username;
211     $$('[name=user.reflink]').each(function(e) {
212         e.href = '/#ref/' + this.username;
213     }.bind(this));
214     $('usercontrols').show();
215 }
216
217 User.prototype.loadItems = function(from, to) {
218     var url;
219     if (from != undefined && to != undefined) {
220         url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
221         this.pageStart = to;
222     } else {
223         url = baseURL + '/get/' + this.username;
224     }
225
226     new Ajax.Request(url, {
227         method: 'get',
228         onSuccess: function(r) {
229             var records = r.responseText.evalJSON();
230             if (records && records.length > 0) {
231                 records.each(function(v) {
232                     v.id = v.record;
233                     mangleRecord(v, recordTemplate);
234                 });
235                 this.addItems(records);
236                 if (!this.pageStart)
237                     this.pageStart = records[0].recInt;
238             }
239             this.displayItems();
240         }.bind(this),
241         onFailure: function(r) {
242             this.displayItems();
243         }.bind(this),
244         on404: function(r) {
245             displayError('User not found');
246         }
247     });
248 }
249
250 function mangleRecord(record, template) {
251     record.recInt = parseInt(record.record);
252
253     // Sanitize HTML input
254     record.data = record.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
255
256     // Turn HTTP URLs into links
257     record.data = record.data.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
258
259     // Turn markdown links into links
260     record.data = record.data.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
261
262     // Turn *foo* into italics and **foo** into bold
263     record.data = record.data.replace(/(\s)\*\*([^*]+)\*\*(\s)/g, '$1<b>$2</b>$3');
264     record.data = record.data.replace(/(\s)\*([^*]+)\*(\s)/g, '$1<i>$2</i>$3');
265
266     // Turn refs and tags into links
267     record.data = record.data.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#tag/$2">#$2</a>');
268     record.data = record.data.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2">@$2</a>');
269
270     // Turn newlines into linebreaks and paragraphs
271     record.data = record.data.replace(/\r?\n\r?\n/g, "<p>").replace(/\r?\n/g, "<br>");
272
273     record.date = (new Date(record.timestamp * 1000)).toString();
274     record.html = template.evaluate(record);
275 }
276
277 function displayError(msg) {
278     items.innerText = msg;
279 }
280
281
282 // Object for browsing tags
283 function Tag(type, tag) {
284     this.initPager();
285     this.type = type;
286     this.tag = tag;
287
288     var url = baseURL + "/tag/";
289     switch(type) {
290     case 'tag':
291         //url += '%23';
292         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
293         break;
294     case 'ref':
295         url += '%40';
296         break;
297     default:
298         alert('Invalid tag type: ' + type);
299         return;
300     }
301     url += tag;
302
303     new Ajax.Request(url, {
304         method: 'get',
305         onSuccess: function(r) {
306             var j = r.responseText.evalJSON();
307             if (j) {
308                 var maxid = j.length - 1;
309                 j.each(function(v, i) {
310                     v.id = maxid - i;
311                     mangleRecord(v, tagRecordTemplate)
312                 });
313                 this.addItems(j);
314                 this.pageStart = j.length - 1;
315             }
316             this.displayItems();
317         }.bind(this),
318         onFailure: function(r) {
319             this.displayItems();
320         }.bind(this)
321     });
322
323 }
324 Tag.prototype = new Pager();
325 Tag.prototype.constructor = Tag;
326
327 Tag.prototype.show = function() {
328     var ctype = {ref: '@', tag: '#'}[this.type];
329
330     $$('[name=section]').each(function(v) {
331         v.update(' about ' + ctype + this.tag);
332     }.bind(this));
333     $('welcome').hide();
334     $('post').hide();
335     $('older_link').hide();
336     $('newer_link').hide();
337     $('rss').hide();
338     items.show();
339     $('usercontrols').hide();
340 }
341
342 function postPopup() {
343     if (loginStatus.loggedIn) {
344         var post = $('post');
345         if (post.visible()) {
346             post.hide();
347         } else {
348             post.show();
349             if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
350                 $('post.content').value = '@' + currentPager.username + ': ';
351             }
352             $('post.content').focus();
353         }
354     }
355 }
356
357 function signup() {
358     var username = $('signup.username').value;
359     var password = $('signup.password').value;
360
361     new Ajax.Request(baseURL + '/create', {
362         parameters: {
363             username: username,
364             password: password
365         },
366         onSuccess: function(r) {
367             $('signup').hide();
368             location.href = '/#' + username;
369             hashSwitch();
370
371             loginStatus.login(username, password);
372         },
373         onFailure: function(r) {
374             alert("Failed to create user");
375         }
376     });
377 }
378
379 function signup_cancel() {
380     $('signup').hide();
381     hashSwitch();
382 }
383
384 function newer_page() {
385     if (currentPager)
386         currentPager.newerPage();
387 }
388
389 function older_page() {
390     if (currentPager)
391         currentPager.olderPage();
392 }
393
394 var resizePostContentTimeout = null;
395 function resizePostContent() {
396     if (resizePostContentTimeout)
397         clearTimeout(resizePostContentTimeout);
398     resizePostContentTimeout = setTimeout(function() {
399         var c = $('post.content');
400         var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
401         var m = c.value.match(/\r?\n/g);
402         if (m)
403             lines += m.length;
404         if (lines <= 3) {
405             c.style.height = "";
406         } else {
407             c.style.height = (lines * 17) + "pt";
408         }
409         resizePostContentTimeout = null;
410     }, 150);
411 }
412
413 var tickerTimer = null;
414 var tickerHead, tickerTail;
415
416 function tickerFader(a, b, p) {
417     var p2 = 1 - p;
418
419     a.style.opacity = p;
420     a.style.lineHeight = (100 * p) + '%';
421
422     b.style.opacity = p2;
423     b.style.lineHeight = (100 * p2) + '%';
424     if (p == 1.0)
425         b.hide();
426 }
427
428 function fadeOut(p) {
429 }
430
431 function ticker() {
432     tickerHead.show();
433     Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
434     tickerHead = tickerHead.nextSibling;
435     tickerTail = tickerTail.nextSibling;
436     if (tickerHead == null) {
437         stopTicker();
438         loadLatest.delay(10);
439     }
440 }
441
442 function startTicker() {
443     stopTicker();
444     for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
445         elem.hide();
446     }
447
448     // Show the first five
449     tickerHead = $('latest-posts').firstChild;
450     for (var i = 0; i < 5 && tickerHead; i++) {
451         tickerHead.show();
452         tickerHead = tickerHead.nextSibling;
453     }
454     tickerTail = $('latest-posts').firstChild;
455     tickerTimer = setInterval(ticker, 5000);
456 }
457
458 function stopTicker() {
459     if (tickerTimer)
460         clearInterval(tickerTimer);
461     tickerTimer = null;
462 }
463
464 function loadLatest() {
465     new Ajax.Request(baseURL + '/latest.json', {
466         onSuccess: function(r) {
467             var j = r.responseText.evalJSON();
468
469             $('latest-tags').update();
470             j.tags.each(function(v) {
471                 var a = new Element('a', {href: '/#tag/' + v});
472                 a.insert('#' + v);
473                 $('latest-tags').insert(a);
474                 $('latest-tags').appendChild(document.createTextNode(' '));
475             });
476
477             $('latest-posts').update();
478             j.records.each(function(v) {
479                 v.data = v.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
480                 v.date = (new Date(v.timestamp * 1000)).toString();
481                 var html = latestRecordsTemplate.evaluate(v);
482                 $('latest-posts').insert(html);
483             });
484             startTicker();
485         }
486     });
487 }
488
489 function hashSwitch() {
490     var m;
491     stopTicker();
492     if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
493         $('post').show();
494         $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
495     } else if (m = location.hash.match(/^#(ref|tag)\/([A-Za-z0-9_-]+)$/)) {
496         currentPager = new Tag(m[1], m[2]);
497         currentPager.show();
498     } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(:(\d+))?$/)) {
499         if (!currentPager || currentPager.username != m[1])
500             currentPager = new User(m[1]);
501         currentPager.show();
502         loginStatus.update();
503
504         if (m[3]) {
505             var r = parseInt(m[3]);
506             currentPager.showRecord = r;
507             if (currentPager.recordCache[r]) {
508                 currentPager.displayItems();
509             } else {
510                 currentPager.loadItems((r >= 49 ? r - 49 : 0), r);
511             }
512         } else {
513             currentPager.pageStart = currentPager.itemCount - 1;
514             currentPager.loadItems();
515         }
516     } else {
517         $$('[name=section]').each(function(v) { v.update('Welcome') });
518         $('signup').hide();
519         items.update();
520         items.hide();
521         $('newer_link').hide();
522         $('older_link').hide();
523         $('welcome').show();
524         $('rss').hide();
525         $('usercontrols').hide();
526         loadLatest();
527     }
528 }
529
530 var lastHash;
531 function hashCheck() {
532     if (location.hash != lastHash) {
533         lastHash = location.hash;
534         hashSwitch();
535     }
536 }
537
538 function init() {
539     items = $('items');
540     loginStatus = new LoginStatus();
541
542     lastHash = location.hash;
543     hashSwitch();
544
545     setInterval(hashCheck, 250);
546
547     document.body.observe('keyup', function(event) {
548         if (event.shiftKey && event.keyCode == '32') {
549             postPopup();
550             event.stop();
551         }
552     });
553     $('post.content').addEventListener('keyup', function(event) {
554         event.stopPropagation();
555     }, true);
556 }