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> <a href="#" onclick="postPopup(\'@#{author}/#{record}: \'); return false">[reply]</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}. <a href="/\##{author}/#{record}">[permalink]</a> <a href="#" onclick="postPopup(\'@#{author}/#{record}: \'); return false">[reply]</a></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));
212 Pager.prototype.loadItems = function(from, to, continuation) { }
215 // Object to render user pages
216 function User(username) {
218 this.username = username;
219 this.baseFrag = username;
221 User.prototype = new Pager();
222 User.prototype.constructor = User;
224 User.prototype.show = function() {
225 $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
229 $('rsslink').href = '/rss/' + this.username;
230 $$('[name=user.reflink]').each(function(e) {
231 e.href = '/#/ref/' + this.username;
233 $('usercontrols').show();
236 User.prototype.reload = function() {
237 this.pageStart = null;
239 $$('[name=user.subscribelink]').each(Element.hide);
240 $$('[name=user.unsubscribelink]').each(Element.hide);
242 if (loginStatus.loggedIn) {
243 new Ajax.Request(baseURL + '/feedinfo/' + this.username, {
246 username: loginStatus.username
248 onSuccess: function(r) {
249 var json = r.responseText.evalJSON();
250 if (json.subscribed) {
251 $$('[name=user.subscribelink]').each(Element.hide);
252 $$('[name=user.unsubscribelink]').each(Element.show);
254 $$('[name=user.subscribelink]').each(Element.show);
255 $$('[name=user.unsubscribelink]').each(Element.hide);
261 new Ajax.Request(baseURL + '/info/' + this.username, {
263 onSuccess: function(r) {
264 var j = r.responseText.evalJSON();
266 this.itemCount = parseInt(j.record_count);
268 this.showPageAt(this.itemCount - 1);
274 User.prototype.loadItems = function(from, to, continuation) {
276 if (from != undefined && to != undefined) {
277 url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
280 url = baseURL + '/get/' + this.username;
283 new Ajax.Request(url, {
285 onSuccess: function(r) {
286 var records = r.responseText.evalJSON();
287 if (records && records.length > 0) {
288 records.each(function(v) {
290 v.author = this.username;
291 mangleRecord(v, recordTemplate);
293 this.addItems(records);
295 this.pageStart = records[0].recInt;
299 onFailure: function(r) {
303 displayError('User not found');
308 function mangleRecord(record, template) {
309 record.recInt = parseInt(record.record);
311 var lines = record.data.split(/\r?\n/);
312 if (lines[lines.length - 1] == '')
317 var listMode = false;
318 lines.each(function(l) {
320 if (out[out.length - 1] == '<br>') {
321 out[out.length - 1] = '<p>';
323 if (out[out.length - 1] == '</li>') {
331 // Put quoted material into a special paragraph
333 var pi = out.lastIndexOf('<p>');
335 out[pi] = '<p class="quote">';
336 l = l.replace(/^>\s*/, '');
340 // Sanitize HTML input
341 l = l.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
343 // Turn HTTP URLs into links
344 l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
346 // Turn markdown links into links
347 l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
349 // Turn *foo* into italics and **foo** into bold
350 l = l.replace(/([^\w\\]|^)\*\*(\w[^*]*)\*\*(\W|$)/g, '$1<b>$2</b>$3');
351 l = l.replace(/([^\w\\]|^)\*(\w[^*]*)\*(\W|$)/g, '$1<i>$2</i>$3');
353 // Turn refs and tags into links
354 l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
355 l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)(\/\d+)?/g, '$1<a href="#$2$3" class="ref" onclick="return qlink()">@$2</a>');
357 // Create lists when lines begin with *
360 var pi = out.lastIndexOf('<p>');
364 l = l.replace(/^\*\s*/, '');
369 // Create headers when lines begin with = or #
370 if (l[0] == '=' || l[0] == '#') {
371 var m = l.match(/^([=#]+)/);
372 var depth = m[1].length;
374 l = l.replace(/^[=#]+\s*/, '').replace(/\s*[=#]+$/, '');
375 out.push('<h' + depth + '>');
376 endpush = '</h' + depth + '>';
380 // Remove backslashes from escaped metachars
381 l = l.replace(/\\([*\[\]@#])/g, '$1');
391 while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
396 record.data = out.join('');
397 record.date = (new Date(record.timestamp * 1000)).toString();
398 record.html = template.evaluate(record);
401 function displayError(msg) {
402 items.innerText = msg;
406 // Object for browsing tags
407 function Tag(type, tag) {
412 var url = baseURL + "/tag/";
416 url += 'H'; // apache is eating the hash, even encoded. Probably a security feature.
417 this.baseFrag = '/tag/' + tag;
421 this.baseFrag = '/ref/' + tag;
424 alert('Invalid tag type: ' + type);
429 new Ajax.Request(url, {
431 onSuccess: function(r) {
432 var j = r.responseText.evalJSON();
434 var maxid = j.length - 1;
435 j.each(function(v, i) {
437 mangleRecord(v, tagRecordTemplate)
440 this.pageStart = j.length - 1;
441 this.itemCount = j.length;
445 onFailure: function(r) {
451 Tag.prototype = new Pager();
452 Tag.prototype.constructor = Tag;
454 Tag.prototype.show = function() {
455 var ctype = {ref: '@', tag: '#'}[this.type];
457 $$('[name=section]').each(function(v) {
458 v.update(' about ' + ctype + this.tag);
462 $('older_link').hide();
463 $('newer_link').hide();
466 $('usercontrols').hide();
470 // Pager for browsing subscription feeds
473 this.username = loginStatus.username;
474 this.baseFrag = '/feed';
476 new Ajax.Request(baseURL + '/feed', {
479 username: loginStatus.username
481 onSuccess: function(r) {
482 var response = r.responseText.evalJSON();
484 var maxid = response.length - 1;
485 response.each(function(v, i) {
487 mangleRecord(v, tagRecordTemplate)
489 this.addItems(response);
490 this.pageStart = response.length - 1;
491 this.itemCount = response.length;
495 onFailure: function(r) {
500 Feed.prototype = new Pager();
501 Feed.prototype.constructor = Feed;
503 Feed.prototype.show = function() {
504 $$('[name=section]').each(function(v) {
505 v.update(' ' + loginStatus.username + "'s spycam");
509 $('older_link').hide();
510 $('newer_link').hide();
513 $('usercontrols').hide();
517 function postPopup(initial) {
518 if (loginStatus.loggedIn || initial) {
519 var post = $('post');
520 if (post.visible()) {
525 $('post.content').value = initial;
526 } else if (!$('post.content').value && currentPager.username && currentPager.username != loginStatus.username) {
527 $('post.content').value = '@' + currentPager.username + ': ';
529 $('post.content').focus();
535 var username = $('signup.username').value;
536 var password = $('signup.password').value;
538 new Ajax.Request(baseURL + '/create', {
543 onSuccess: function(r) {
547 loginStatus.login(username, password);
549 onFailure: function(r) {
550 alert("Failed to create user");
555 function signup_cancel() {
560 function subscribe() {
561 new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
564 username: loginStatus.username
566 onSuccess: function(r) {
567 var response = r.responseText.evalJSON();
568 if (response.status == 'success') {
569 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
570 $$('[name=user.subscribelink]').each(Element.hide);
571 $$('[name=user.unsubscribelink]').each(Element.show);
573 alert('Failed to subscribe. This is probably for the best');
576 onFailure: function(r) {
577 alert('Failed to subscribe. This is probably for the best');
582 function unsubscribe() {
583 new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
586 username: loginStatus.username
588 onSuccess: function(r) {
589 var response = r.responseText.evalJSON();
590 if (response.status == 'success') {
591 alert("You come to your senses.");
592 $$('[name=user.subscribelink]').each(Element.show);
593 $$('[name=user.unsubscribelink]').each(Element.hide);
595 alert('You are unable to tear yourself away (because something failed on the server)');
598 onFailure: function(r) {
599 alert('You are unable to tear yourself away (because something failed on the server)');
604 var resizePostContentTimeout = null;
605 function resizePostContent() {
606 if (resizePostContentTimeout)
607 clearTimeout(resizePostContentTimeout);
608 resizePostContentTimeout = setTimeout(function() {
609 var c = $('post.content');
610 var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
611 var m = c.value.match(/\r?\n/g);
617 c.style.height = (lines * 17) + "pt";
619 resizePostContentTimeout = null;
623 var tickerTimer = null;
624 var tickerHead, tickerTail;
626 function tickerFader(a, b, p) {
630 a.style.lineHeight = (100 * p) + '%';
632 b.style.opacity = p2;
633 b.style.lineHeight = (100 * p2) + '%';
640 Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
641 tickerHead = tickerHead.nextSibling;
642 tickerTail = tickerTail.nextSibling;
643 if (tickerHead == null) {
645 loadLatest.delay(10);
649 function startTicker() {
651 for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
655 // Show the first five
656 tickerHead = $('latest-posts').firstChild;
657 for (var i = 0; i < 10 && tickerHead; i++) {
659 tickerHead = tickerHead.nextSibling;
661 tickerTail = $('latest-posts').firstChild;
662 tickerTimer = setInterval(ticker, 5000);
665 function stopTicker() {
667 clearInterval(tickerTimer);
671 function loadLatest() {
672 new Ajax.Request(baseURL + '/latest.json', {
673 onSuccess: function(r) {
674 var j = r.responseText.evalJSON();
676 $('latest-tags').update();
677 j.tags.each(function(v) {
678 var a = new Element('a', {href: '/#/tag/' + v});
680 a.onclick = "return qlink()";
682 $('latest-tags').insert(a);
683 $('latest-tags').appendChild(document.createTextNode(' '));
686 $('latest-posts').update();
687 j.records.each(function(v) {
688 v.data = v.data.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
689 v.date = (new Date(v.timestamp * 1000)).toString();
690 var html = latestRecordsTemplate.evaluate(v);
691 $('latest-posts').insert(html);
698 function qlink(loc) {
701 } else if (event && event.target) {
702 location.href = event.target.href;
711 function hashSwitch() {
714 if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
716 $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
717 } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/)) {
718 if (!currentPager || !(currentPager instanceof Tag) || currentPager.type != m[1] || currentPager.tag != m[2])
719 currentPager = new Tag(m[1], m[2]);
723 var r = parseInt(m[3]);
724 currentPager.showPageAt(r);
726 currentPager.showPageAt(currentPager.itemCount - 1);
728 } else if (m = location.hash.match(/^#\/feed(?:\/p(\d+))?$/)) {
729 if (loginStatus.loggedIn) {
730 if (!currentPager || !(currentPager instanceof Feed) || currentPager.username != loginStatus.username)
731 currentPager = new Feed();
734 var r = parseInt(m[3]);
735 currentPager.showPageAt(r);
737 currentPager.showPageAt(currentPager.itemCount - 1);
740 location.href = baseURL;
742 } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
743 if (!currentPager || !(currentPager instanceof User) || currentPager.username != m[1])
744 currentPager = new User(m[1]);
746 loginStatus.update();
749 var r = parseInt(m[3]);
751 currentPager.showPageAt(r);
753 currentPager.showRecord(r);
756 currentPager.reload();
759 $$('[name=section]').each(function(v) { v.update('Welcome') });
763 $('newer_link').hide();
764 $('older_link').hide();
767 $('usercontrols').hide();
773 function hashCheck() {
774 if (location.hash != lastHash) {
775 lastHash = location.hash;
782 loginStatus = new LoginStatus();
784 lastHash = location.hash;
787 setInterval(hashCheck, 250);
789 document.body.observe('keyup', function(event) {
790 if (event.shiftKey && event.keyCode == 32) {
795 $('post.content').addEventListener('keyup', function(event) {
796 event.stopPropagation();