4d56790802125a42c504febc1b2c7f01246c09f0
[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 href="/\##{author}">@#{author}</a> on #{date}</div></div>'
12 );
13
14 // Page elements
15 var items;
16
17 // Other globals
18 var currentPager;
19 var loginStatus;
20
21 // Object to keep track of login status
22 function LoginStatus() {
23     var cookies = {};
24     document.cookie.split(/;\s+/).each(function(v) {
25         kv = v.split('=');
26         cookies[kv[0]] = kv[1];
27     });
28     if (cookies.auth && cookies.username) {
29         this.loggedIn = true;
30         this.username = cookies.username;
31     } else {
32         this.loggedIn = false;
33         this.username = null;
34     }
35     this.update();
36 }
37
38 LoginStatus.prototype.login = function(username, password) {
39     new Ajax.Request(baseURL + '/login', {
40         parameters: {
41             username: username,
42             password: password
43         },
44         onSuccess: function(r) {
45             var j = r.responseText.evalJSON();
46             if (j && j.status == 'success') {
47                 this.loggedIn = true;
48                 this.username = username;
49                 document.cookie = "username=" + username;
50                 $('login.password').value = '';
51                 this.update();
52             } else {
53                 alert("Could not log in");
54                 $('login.username').focus();
55             }
56         }.bind(this),
57         onFailure: function(r) {
58             alert("Could not log in");
59             $('login.username').focus();
60         }
61     });
62 }
63
64 LoginStatus.prototype.logout = function() {
65     new Ajax.Request(baseURL + '/logout', {
66         parameters: {
67             username: this.username
68         },
69         onSuccess: function(r) {
70             this.loggedIn = false;
71             document.cookie = "auth=; expires=1-Jan-1970 00:00:00 GMT";
72             this.update();
73         }.bind(this)
74     });
75     document.cookie = "username=; expires=1-Jan-1970 00:00:00 GMT";
76 }
77
78 LoginStatus.prototype.update = function() {
79     if (this.loggedIn) {
80         $('userlink').href = '/#' + this.username;
81         $('userlink').update('@' + this.username);
82         $('login').hide();
83         $('logout').show();
84     } else {
85         $('post').hide();
86         $('login').show();
87         $('logout').hide();
88     }
89 }
90
91 LoginStatus.prototype.post = function(msg) {
92     if (!this.loggedIn) {
93         alert("You are not logged in!");
94         exit(0);
95     }
96
97     new Ajax.Request(baseURL + '/put', {
98         parameters: {
99             username: this.username,
100             data: msg
101         },
102         onSuccess: function(r) {
103             var j = r.responseText.evalJSON();
104             if (j && j.status == 'success') {
105                 $('post.content').value = '';
106                 if (location.hash != '#' + this.username) {
107                     location.href = '/#' + this.username;
108                     hashSwitch();
109                 } else {
110                     currentPager.itemCount++;
111                     currentPager.pageStart = null;
112                     currentPager.loadItems();
113                 }
114             } else {
115                 alert('Post failed!');
116             }
117         }.bind(this),
118         onFailure: function(r) {
119             alert('Post failed!');
120         }
121     });
122 }
123
124
125 // Base object for paged data
126 function Pager() {
127     this.itemsPerPage = 10;
128 }
129
130 Pager.prototype.initPager = function() {
131     this.itemCache = new Hash();
132     this.pageStart = null;
133 }
134
135 Pager.prototype.olderPage = function() {
136     if (this.pageStart >= this.itemsPerPage) {
137         this.pageStart -= this.itemsPerPage;
138         this.displayItems();
139     }
140 }
141
142 Pager.prototype.newerPage = function() {
143     if (this.pageStart + this.itemsPerPage < this.itemCount) {
144         this.pageStart += this.itemsPerPage;
145         this.displayItems();
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').show();
172     else
173         $('newer_link').hide();
174
175     if (this.pageStart >= 10)
176         $('older_link').show();
177     else
178         $('older_link').hide();
179 }
180
181
182 // Object to render user pages
183 function User(username) {
184     this.initPager();
185     this.username = username;
186
187     new Ajax.Request(baseURL + '/info/' + username, {
188         method: 'get',
189         onSuccess: function(r) {
190             var j = r.responseText.evalJSON();
191             if (j) {
192                 this.itemCount = parseInt(j.record_count);
193                 this.displayItems();
194             }
195         }.bind(this)
196     });
197 }
198 User.prototype = new Pager();
199 User.prototype.constructor = User;
200
201 User.prototype.show = function() {
202     $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
203     $('welcome').hide();
204     items.show();
205     $('reflink').href = '/#ref/' + this.username;
206     $('rss').show();
207     $('rsslink').href = '/rss/' + this.username;
208 }
209
210 User.prototype.loadItems = function(from, to) {
211     var url;
212     if (from != undefined && to != undefined) {
213         url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
214         this.pageStart = to;
215     } else {
216         url = baseURL + '/get/' + this.username;
217     }
218
219     new Ajax.Request(url, {
220         method: 'get',
221         onSuccess: function(r) {
222             var records = r.responseText.evalJSON();
223             if (records && records.length > 0) {
224                 records.each(function(v) {
225                     v.id = v.record;
226                     mangleRecord(v, recordTemplate);
227                 });
228                 this.addItems(records);
229                 if (!this.pageStart)
230                     this.pageStart = records[0].recInt;
231             }
232             this.displayItems();
233         }.bind(this),
234         onFailure: function(r) {
235             this.displayItems();
236         }.bind(this),
237         on404: function(r) {
238             displayError('User not found');
239         }
240     });
241 }
242
243 function mangleRecord(record, template) {
244     record.recInt = parseInt(record.record);
245
246     // Sanitize HTML input
247     record.data = record.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
248
249     // Turn HTTP URLs into links
250     record.data = record.data.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
251
252     // Turn markdown links into links
253     record.data = record.data.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
254
255     // Turn *foo* into italics and **foo** into bold
256     record.data = record.data.replace(/(\s)\*\*([^*]+)\*\*(\s)/g, '$1<b>$2</b>$3');
257     record.data = record.data.replace(/(\s)\*([^*]+)\*(\s)/g, '$1<i>$2</i>$3');
258
259     // Turn refs and tags into links
260     record.data = record.data.replace(/(\s|^)#(\w+)/g, '$1<a href="#tag/$2">#$2</a>');
261     record.data = record.data.replace(/(\s|^)@(\w+)/g, '$1<a href="#$2">@$2</a>');
262
263     // Turn newlines into linebreaks and paragraphs
264     record.data = record.data.replace(/\r?\n\r?\n/g, "<p>").replace(/\r?\n/g, "<br>");
265
266     record.date = (new Date(record.timestamp * 1000)).toString();
267     record.html = template.evaluate(record);
268 }
269
270 function displayError(msg) {
271     items.innerText = msg;
272 }
273
274
275 // Object for browsing tags
276 function Tag(type, tag) {
277     this.initPager();
278     this.type = type;
279     this.tag = tag;
280
281     var url = baseURL + "/tag/";
282     switch(type) {
283     case 'tag':
284         //url += '%23';
285         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
286         break;
287     case 'ref':
288         url += '%40';
289         break;
290     default:
291         alert('Invalid tag type: ' + type);
292         return;
293     }
294     url += tag;
295
296     new Ajax.Request(url, {
297         method: 'get',
298         onSuccess: function(r) {
299             var j = r.responseText.evalJSON();
300             if (j) {
301                 var maxid = j.length - 1;
302                 j.each(function(v, i) {
303                     v.id = maxid - i;
304                     mangleRecord(v, tagRecordTemplate)
305                 });
306                 this.addItems(j);
307                 this.pageStart = j.length - 1;
308             }
309             this.displayItems();
310         }.bind(this),
311         onFailure: function(r) {
312             this.displayItems();
313         }.bind(this)
314     });
315
316 }
317 Tag.prototype = new Pager();
318 Tag.prototype.constructor = Tag;
319
320 Tag.prototype.show = function() {
321     var ctype = {ref: '@', tag: '#'}[this.type];
322
323     $$('[name=section]').each(function(v) {
324         v.update(' about ' + ctype + this.tag);
325     }.bind(this));
326     $('welcome').hide();
327     $('post').hide();
328     $('older_link').hide();
329     $('newer_link').hide();
330     $('rss').hide();
331     items.show();
332 }
333
334 function postPopup() {
335     if (loginStatus.loggedIn) {
336         var post = $('post');
337         if (post.visible()) {
338             post.hide();
339         } else {
340             post.show();
341             if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
342                 $('post.content').value = '@' + currentPager.username + ': ';
343             }
344             $('post.content').focus();
345         }
346     }
347 }
348
349 function signup() {
350     var username = $('signup.username').value;
351     var password = $('signup.password').value;
352
353     new Ajax.Request(baseURL + '/create', {
354         parameters: {
355             username: username,
356             password: password
357         },
358         onSuccess: function(r) {
359             $('signup').hide();
360             location.href = '/#' + username;
361             hashSwitch();
362
363             loginStatus.login(username, password);
364         },
365         onFailure: function(r) {
366             alert("Failed to create user");
367         }
368     });
369 }
370
371 function signup_cancel() {
372     $('signup').hide();
373     hashSwitch();
374 }
375
376 function newer_page() {
377     if (currentPager)
378         currentPager.newerPage();
379 }
380
381 function older_page() {
382     if (currentPager)
383         currentPager.olderPage();
384 }
385
386 var resizePostContentTimeout = null;
387 function resizePostContent() {
388     if (resizePostContentTimeout)
389         clearTimeout(resizePostContentTimeout);
390     resizePostContentTimeout = setTimeout(function() {
391         var c = $('post.content');
392         var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
393         var m = c.value.match(/\r?\n/g);
394         if (m)
395             lines += m.length;
396         if (lines <= 3) {
397             c.style.height = "";
398         } else {
399             c.style.height = (lines * 17) + "pt";
400         }
401         resizePostContentTimeout = null;
402     }, 150);
403 }
404
405 function hashSwitch() {
406     var m;
407     if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
408         $('post').show();
409         $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
410     } else if (m = location.hash.match(/^#(ref|tag)\/(\w+)$/)) {
411         currentPager = new Tag(m[1], m[2]);
412         currentPager.show();
413     } else if (m = location.hash.match(/^#(\w+)(:(\d+))?$/)) {
414         if (!currentPager || currentPager.username != m[1])
415             currentPager = new User(m[1]);
416         currentPager.show();
417         loginStatus.update();
418
419         if (m[3]) {
420             var r = parseInt(m[3]);
421             currentPager.showRecord = r;
422             if (currentPager.recordCache[r]) {
423                 currentPager.displayItems();
424             } else {
425                 currentPager.loadItems((r >= 49 ? r - 49 : 0), r);
426             }
427         } else {
428             currentPager.pageStart = currentPager.itemCount - 1;
429             currentPager.loadItems();
430         }
431     } else {
432         $$('[name=section]').each(function(v) { v.update('Welcome') });
433         $('signup').hide();
434         items.update();
435         items.hide();
436         $('newer_link').hide();
437         $('older_link').hide();
438         $('welcome').show();
439         $('rss').hide();
440     }
441 }
442
443 var lastHash;
444 function hashCheck() {
445     if (location.hash != lastHash) {
446         lastHash = location.hash;
447         hashSwitch();
448     }
449 }
450
451 function init() {
452     items = $('items');
453     loginStatus = new LoginStatus();
454
455     lastHash = location.hash;
456     hashSwitch();
457
458     setInterval(hashCheck, 250);
459
460     document.body.observe('keyup', function(event) {
461         if (event.shiftKey && event.keyCode == '32') {
462             postPopup();
463             event.stop();
464         }
465     });
466     $('post.content').addEventListener('keyup', function(event) {
467         event.stopPropagation();
468     }, true);
469 }