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.
7 var recordTemplate = new Template(
8 '<div class="record">#{data}<div class="info">Posted #{date}. <a href="/\##{author}/#{record}">[permalink]</a></div></div>'
10 var tagRecordTemplate = new Template(
11 '<div class="record">#{data}<div class="info">Posted by <a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> on #{date}</div></div>'
13 var latestRecordsTemplate = new Template(
14 '<div class="record"><a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> #{data}</div>'
24 // Object to keep track of login status
25 function LoginStatus() {
27 document.cookie.split(/;\s+/).each(function(v) {
29 cookies[kv[0]] = kv[1];
31 if (cookies.auth && cookies.username) {
33 this.username = cookies.username;
35 this.loggedIn = false;
41 LoginStatus.prototype.login = function(username, password) {
42 new Ajax.Request(baseURL + '/login', {
47 onSuccess: function(r) {
48 var j = r.responseText.evalJSON();
49 if (j && j.status == 'success') {
51 this.username = username;
52 document.cookie = "username=" + username;
53 $('login.password').value = '';
56 alert("Could not log in");
57 $('login.username').focus();
60 onFailure: function(r) {
61 alert("Could not log in");
62 $('login.username').focus();
67 LoginStatus.prototype.logout = function() {
68 new Ajax.Request(baseURL + '/logout', {
70 username: this.username
72 onSuccess: function(r) {
73 this.loggedIn = false;
74 document.cookie = "auth=; expires=1-Jan-1970 00:00:00 GMT";
78 document.cookie = "username=; expires=1-Jan-1970 00:00:00 GMT";
81 LoginStatus.prototype.update = function() {
83 $('userlink').href = '/#' + this.username;
84 $('userlink').update('@' + this.username);
85 $('reflink').href = '/#/ref/' + this.username;
95 LoginStatus.prototype.post = function(msg) {
97 alert("You are not logged in!");
101 new Ajax.Request(baseURL + '/put', {
103 username: this.username,
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 qlink(this.username);
113 currentPager.itemCount++;
114 currentPager.reload();
117 alert('Post failed!');
120 onFailure: function(r) {
121 alert('Post failed!');
127 // Base object for paged data
129 this.itemsPerPage = 10;
132 Pager.prototype.initPager = function() {
133 this.itemCache = new Hash();
134 this.pageStart = null;
137 Pager.prototype.olderPage = function() {
138 if (this.pageStart >= this.itemsPerPage) {
139 qlink(this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage));
143 Pager.prototype.newerPage = function() {
144 if (this.pageStart + this.itemsPerPage < this.itemCount) {
145 qlink(this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage));
149 Pager.prototype.addItems = function(items) {
150 items.each(function(v) {
151 if (!this.itemCache[v.id])
152 this.itemCache[v.id] = v;
156 Pager.prototype.displayItems = function() {
157 if (this.pageStart == undefined)
158 this.pageStart == this.itemCount - 1;
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);
167 items.insert("There doesn't seem to be anything here!");
170 if (this.pageStart < this.itemCount - 1) {
171 $('newer_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage);
172 $('newer_link').show();
174 $('newer_link').hide();
177 if (this.pageStart >= 10) {
178 $('older_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage);
179 $('older_link').show();
181 $('older_link').hide();
184 document.body.scrollTo();
187 Pager.prototype.reload = function() {
188 this.pageStart = null;
189 this.loadItems(null, null, Pager.prototype.showPageAt.bind(this, this.itemCount - 1));
192 Pager.prototype.showPageAt = function(r) {
193 var end = (r - 9 > 0 ? r - 9 : 0);
194 if (this.itemCache[r] && this.itemCache[end]) {
198 this.loadItems((r >= 49 ? r - 49 : 0), r, Pager.prototype.showPageAt.bind(this, r));
202 Pager.prototype.showRecord = function(r) {
203 if (this.itemCache[r]) {
204 $('older_link').hide();
205 $('newer_link').hide();
206 items.update(this.itemCache[r].html);
208 this.loadItems(r, r, Pager.prototype.showRecord.bind(this, r));
213 // Object to render user pages
214 function User(username) {
216 this.username = username;
217 this.baseFrag = username;
219 $$('[name=user.subscribelink]').each(Element.hide);
220 $$('[name=user.unsubscribelink]').each(Element.hide);
222 if (loginStatus.loggedIn) {
223 new Ajax.Request(baseURL + '/feedinfo/' + username, {
226 username: loginStatus.username
228 onSuccess: function(r) {
229 var json = r.responseText.evalJSON();
230 if (json.subscribed) {
231 $$('[name=user.subscribelink]').each(Element.hide);
232 $$('[name=user.unsubscribelink]').each(Element.show);
234 $$('[name=user.subscribelink]').each(Element.show);
235 $$('[name=user.unsubscribelink]').each(Element.hide);
241 new Ajax.Request(baseURL + '/info/' + username, {
243 onSuccess: function(r) {
244 var j = r.responseText.evalJSON();
246 this.itemCount = parseInt(j.record_count);
248 this.showPageAt(this.itemCount - 1);
253 User.prototype = new Pager();
254 User.prototype.constructor = User;
256 User.prototype.show = function() {
257 $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
261 $('rsslink').href = '/rss/' + this.username;
262 $$('[name=user.reflink]').each(function(e) {
263 e.href = '/#/ref/' + this.username;
265 $('usercontrols').show();
268 User.prototype.loadItems = function(from, to, continuation) {
270 if (from != undefined && to != undefined) {
271 url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
274 url = baseURL + '/get/' + this.username;
277 new Ajax.Request(url, {
279 onSuccess: function(r) {
280 var records = r.responseText.evalJSON();
281 if (records && records.length > 0) {
282 records.each(function(v) {
284 v.author = this.username;
285 mangleRecord(v, recordTemplate);
287 this.addItems(records);
289 this.pageStart = records[0].recInt;
293 onFailure: function(r) {
297 displayError('User not found');
302 function mangleRecord(record, template) {
303 record.recInt = parseInt(record.record);
305 var lines = record.data.split(/\r?\n/);
306 if (lines[lines.length - 1] == '')
311 var listMode = false;
312 lines.each(function(l) {
314 if (out[out.length - 1] == '<br>') {
315 out[out.length - 1] = '<p>';
317 if (out[out.length - 1] == '</li>') {
325 // Put quoted material into a special paragraph
327 var pi = out.lastIndexOf('<p>');
329 out[pi] = '<p class="quote">';
330 l = l.replace(/^>\s*/, '');
334 // Sanitize HTML input
335 l = l.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
337 // Turn HTTP URLs into links
338 l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
340 // Turn markdown links into links
341 l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
343 // Turn *foo* into italics and **foo** into bold
344 l = l.replace(/(\W|^)\*\*(\w[^*]*)\*\*(\W|$)/g, '$1<b>$2</b>$3');
345 l = l.replace(/(\W|^)\*(\w[^*]*)\*(\W|$)/g, '$1<i>$2</i>$3');
347 // Turn refs and tags into links
348 l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
349 l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
351 // Create lists when lines begin with *
354 var pi = out.lastIndexOf('<p>');
358 l = l.replace(/^\*\s*/, '');
363 // Create headers when lines begin with =
365 var m = l.match(/^(=+)/);
366 var depth = m[1].length;
368 l = l.replace(/^=+\s*/, '').replace(/\s*=+$/, '');
369 out.push('<h' + depth + '>');
370 endpush = '</h' + depth + '>';
382 while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
387 record.data = out.join('');
388 record.date = (new Date(record.timestamp * 1000)).toString();
389 record.html = template.evaluate(record);
392 function displayError(msg) {
393 items.innerText = msg;
397 // Object for browsing tags
398 function Tag(type, tag) {
403 var url = baseURL + "/tag/";
407 url += 'H'; // apache is eating the hash, even encoded. Probably a security feature.
408 this.baseFrag = '/tag/' + tag;
412 this.baseFrag = '/ref/' + tag;
415 alert('Invalid tag type: ' + type);
420 new Ajax.Request(url, {
422 onSuccess: function(r) {
423 var j = r.responseText.evalJSON();
425 var maxid = j.length - 1;
426 j.each(function(v, i) {
428 mangleRecord(v, tagRecordTemplate)
431 this.pageStart = j.length - 1;
432 this.itemCount = j.length;
436 onFailure: function(r) {
442 Tag.prototype = new Pager();
443 Tag.prototype.constructor = Tag;
445 Tag.prototype.show = function() {
446 var ctype = {ref: '@', tag: '#'}[this.type];
448 $$('[name=section]').each(function(v) {
449 v.update(' about ' + ctype + this.tag);
453 $('older_link').hide();
454 $('newer_link').hide();
457 $('usercontrols').hide();
461 // Pager for browsing subscription feeds
464 this.username = loginStatus.username;
465 this.baseFrag = '/feed';
467 new Ajax.Request(baseURL + '/feed', {
470 username: loginStatus.username
472 onSuccess: function(r) {
473 var response = r.responseText.evalJSON();
475 var maxid = response.length - 1;
476 response.each(function(v, i) {
478 mangleRecord(v, tagRecordTemplate)
480 this.addItems(response);
481 this.pageStart = response.length - 1;
482 this.itemCount = response.length;
486 onFailure: function(r) {
491 Feed.prototype = new Pager();
492 Feed.prototype.constructor = Feed;
494 Feed.prototype.show = function() {
495 $$('[name=section]').each(function(v) {
496 v.update(' ' + loginStatus.username + "'s spycam");
500 $('older_link').hide();
501 $('newer_link').hide();
504 $('usercontrols').hide();
508 function postPopup() {
509 if (loginStatus.loggedIn) {
510 var post = $('post');
511 if (post.visible()) {
515 if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
516 $('post.content').value = '@' + currentPager.username + ': ';
518 $('post.content').focus();
524 var username = $('signup.username').value;
525 var password = $('signup.password').value;
527 new Ajax.Request(baseURL + '/create', {
532 onSuccess: function(r) {
536 loginStatus.login(username, password);
538 onFailure: function(r) {
539 alert("Failed to create user");
544 function signup_cancel() {
549 function subscribe() {
550 new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
553 username: loginStatus.username
555 onSuccess: function(r) {
556 var response = r.responseText.evalJSON();
557 if (response.status == 'success') {
558 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
559 $$('[name=user.subscribelink]').each(Element.hide);
560 $$('[name=user.unsubscribelink]').each(Element.show);
562 alert('Failed to subscribe. This is probably for the best');
565 onFailure: function(r) {
566 alert('Failed to subscribe. This is probably for the best');
571 function unsubscribe() {
572 new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
575 username: loginStatus.username
577 onSuccess: function(r) {
578 var response = r.responseText.evalJSON();
579 if (response.status == 'success') {
580 alert("You come to your senses.");
581 $$('[name=user.subscribelink]').each(Element.show);
582 $$('[name=user.unsubscribelink]').each(Element.hide);
584 alert('You are unable to tear yourself away (because something failed on the server)');
587 onFailure: function(r) {
588 alert('You are unable to tear yourself away (because something failed on the server)');
593 var resizePostContentTimeout = null;
594 function resizePostContent() {
595 if (resizePostContentTimeout)
596 clearTimeout(resizePostContentTimeout);
597 resizePostContentTimeout = setTimeout(function() {
598 var c = $('post.content');
599 var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
600 var m = c.value.match(/\r?\n/g);
606 c.style.height = (lines * 17) + "pt";
608 resizePostContentTimeout = null;
612 var tickerTimer = null;
613 var tickerHead, tickerTail;
615 function tickerFader(a, b, p) {
619 a.style.lineHeight = (100 * p) + '%';
621 b.style.opacity = p2;
622 b.style.lineHeight = (100 * p2) + '%';
629 Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
630 tickerHead = tickerHead.nextSibling;
631 tickerTail = tickerTail.nextSibling;
632 if (tickerHead == null) {
634 loadLatest.delay(10);
638 function startTicker() {
640 for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
644 // Show the first five
645 tickerHead = $('latest-posts').firstChild;
646 for (var i = 0; i < 10 && tickerHead; i++) {
648 tickerHead = tickerHead.nextSibling;
650 tickerTail = $('latest-posts').firstChild;
651 tickerTimer = setInterval(ticker, 5000);
654 function stopTicker() {
656 clearInterval(tickerTimer);
660 function loadLatest() {
661 new Ajax.Request(baseURL + '/latest.json', {
662 onSuccess: function(r) {
663 var j = r.responseText.evalJSON();
665 $('latest-tags').update();
666 j.tags.each(function(v) {
667 var a = new Element('a', {href: '/#/tag/' + v});
669 a.onclick = "return qlink()";
671 $('latest-tags').insert(a);
672 $('latest-tags').appendChild(document.createTextNode(' '));
675 $('latest-posts').update();
676 j.records.each(function(v) {
677 v.data = v.data.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
678 v.date = (new Date(v.timestamp * 1000)).toString();
679 var html = latestRecordsTemplate.evaluate(v);
680 $('latest-posts').insert(html);
687 function qlink(loc) {
690 } else if (event && event.target) {
691 location.href = event.target.href;
700 function hashSwitch() {
703 if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
705 $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
706 } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/)) {
707 if (!currentPager || !(currentPager instanceof Tag) || currentPager.type != m[1] || currentPager.tag != m[2])
708 currentPager = new Tag(m[1], m[2]);
712 var r = parseInt(m[3]);
713 currentPager.showPageAt(r);
715 } else if (m = location.hash.match(/^#\/feed(?:\/p(\d+))?$/)) {
716 if (loginStatus.loggedIn) {
717 if (!currentPager || !(currentPager instanceof Feed) || currentPager.username != loginStatus.username)
718 currentPager = new Feed();
721 var r = parseInt(m[3]);
722 currentPager.showPageAt(r);
725 location.href = baseURL;
727 } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
728 if (!currentPager || !(currentPager instanceof User) || currentPager.username != m[1])
729 currentPager = new User(m[1]);
731 loginStatus.update();
734 var r = parseInt(m[3]);
736 currentPager.showPageAt(r);
738 currentPager.showRecord(r);
741 // Do nothing otherwise, the User constructor takes care of it
743 $$('[name=section]').each(function(v) { v.update('Welcome') });
747 $('newer_link').hide();
748 $('older_link').hide();
751 $('usercontrols').hide();
757 function hashCheck() {
758 if (location.hash != lastHash) {
759 lastHash = location.hash;
766 loginStatus = new LoginStatus();
768 lastHash = location.hash;
771 setInterval(hashCheck, 250);
773 document.body.observe('keyup', function(event) {
774 if (event.shiftKey && event.keyCode == 32) {
779 $('post.content').addEventListener('keyup', function(event) {
780 event.stopPropagation();