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