Small JS fixups for stupid JS parsers; disable shift-space popup while you're typing
[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.hash = 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('&', '&amp;').replace('<', '&lt;').replace('>', '&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](\/[^)]*?)?)\)/, '$1<a href="$3">$2</a>');
254
255     // Turn refs and tags into links
256     record.data = record.data.replace(/(\s|^)#(\w+)/g, '$1<a href="#tag/$2">#$2</a>');
257     record.data = record.data.replace(/(\s|^)@(\w+)/g, '$1<a href="#$2">@$2</a>');
258
259     // Turn newlines into linebreaks and paragraphs
260     record.data = record.data.replace(/\r?\n\r?\n/g, "<p>").replace(/\r?\n/g, "<br>");
261
262     record.date = (new Date(record.timestamp * 1000)).toString();
263     record.html = template.evaluate(record);
264 }
265
266 function displayError(msg) {
267     items.innerText = msg;
268 }
269
270
271 // Object for browsing tags
272 function Tag(type, tag) {
273     this.initPager();
274     this.type = type;
275     this.tag = tag;
276
277     var url = baseURL + "/tag/";
278     switch(type) {
279     case 'tag':
280         //url += '%23';
281         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
282         break;
283     case 'ref':
284         url += '%40';
285         break;
286     default:
287         alert('Invalid tag type: ' + type);
288         return;
289     }
290     url += tag;
291
292     new Ajax.Request(url, {
293         method: 'get',
294         onSuccess: function(r) {
295             var j = r.responseText.evalJSON();
296             if (j) {
297                 var maxid = j.length - 1;
298                 j.each(function(v, i) {
299                     v.id = maxid - i;
300                     mangleRecord(v, tagRecordTemplate)
301                 });
302                 this.addItems(j);
303                 this.pageStart = j.length - 1;
304             }
305             this.displayItems();
306         }.bind(this),
307         onFailure: function(r) {
308             this.displayItems();
309         }.bind(this)
310     });
311
312 }
313 Tag.prototype = new Pager();
314 Tag.prototype.constructor = Tag;
315
316 Tag.prototype.show = function() {
317     var ctype = {ref: '@', tag: '#'}[this.type];
318
319     $$('[name=section]').each(function(v) {
320         v.update(' about ' + ctype + this.tag);
321     }.bind(this));
322     $('welcome').hide();
323     $('post').hide();
324     $('older_link').hide();
325     $('newer_link').hide();
326     $('rss').hide();
327     items.show();
328 }
329
330 function postPopup() {
331     if (loginStatus.loggedIn) {
332         var post = $('post');
333         if (post.visible()) {
334             post.hide();
335         } else {
336             post.show();
337             if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
338                 $('post.content').value = '@' + currentPager.username + ': ';
339             }
340             $('post.content').focus();
341         }
342     }
343 }
344
345 function signup() {
346     var username = $('signup.username').value;
347     var password = $('signup.password').value;
348
349     new Ajax.Request(baseURL + '/create', {
350         parameters: {
351             username: username,
352             password: password
353         },
354         onSuccess: function(r) {
355             $('signup').hide();
356             location.hash = username;
357             hashSwitch();
358
359             loginStatus.login(username, password);
360         },
361         onFailure: function(r) {
362             alert("Failed to create user");
363         }
364     });
365 }
366
367 function signup_cancel() {
368     $('signup').hide();
369     hashSwitch();
370 }
371
372 function newer_page() {
373     if (currentPager)
374         currentPager.newerPage();
375 }
376
377 function older_page() {
378     if (currentPager)
379         currentPager.olderPage();
380 }
381
382 var resizePostContentTimeout = null;
383 function resizePostContent() {
384     if (resizePostContentTimeout)
385         clearTimeout(resizePostContentTimeout);
386     resizePostContentTimeout = setTimeout(function() {
387         var c = $('post.content');
388         var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
389         var m = c.value.match(/\r?\n/g);
390         if (m)
391             lines += m.length;
392         if (lines <= 3) {
393             c.style.height = "";
394         } else {
395             c.style.height = (lines * 17) + "pt";
396         }
397         resizePostContentTimeout = null;
398     }, 150);
399 }
400
401 function hashSwitch() {
402     var m;
403     if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
404         $('post').show();
405         $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
406     } else if (m = location.hash.match(/^#(ref|tag)\/(\w+)$/)) {
407         currentPager = new Tag(m[1], m[2]);
408         currentPager.show();
409     } else if (m = location.hash.match(/^#(\w+)(:(\d+))?$/)) {
410         if (!currentPager || currentPager.username != m[1])
411             currentPager = new User(m[1]);
412         currentPager.show();
413         loginStatus.update();
414
415         if (m[3]) {
416             var r = parseInt(m[3]);
417             currentPager.showRecord = r;
418             if (currentPager.recordCache[r]) {
419                 currentPager.displayItems();
420             } else {
421                 currentPager.loadItems((r >= 49 ? r - 49 : 0), r);
422             }
423         } else {
424             currentPager.pageStart = currentPager.itemCount - 1;
425             currentPager.loadItems();
426         }
427     } else {
428         $$('[name=section]').each(function(v) { v.update('Welcome') });
429         $('signup').hide();
430         items.update();
431         items.hide();
432         $('newer_link').hide();
433         $('older_link').hide();
434         $('welcome').show();
435         $('rss').hide();
436     }
437 }
438
439 var lastHash;
440 function hashCheck() {
441     if (location.hash != lastHash) {
442         lastHash = location.hash;
443         hashSwitch();
444     }
445 }
446
447 function init() {
448     items = $('items');
449     loginStatus = new LoginStatus();
450
451     lastHash = location.hash;
452     hashSwitch();
453
454     setInterval(hashCheck, 250);
455
456     document.body.observe('keyup', function(event) {
457         if (event.shiftKey && event.keyCode == '32') {
458             postPopup();
459             event.stop();
460         }
461     });
462     $('post.content').addEventListener('keyup', function(event) {
463         event.stopPropagation();
464     }, true);
465 }