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}. <a href="/\##{author}/#{record}">[permalink]</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/' + 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 // Remove backslashes from escaped metachars
354 l = l.replace(/\\([*\[\]])/g, '$1');
356 // Turn refs and tags into links
357 l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
358 l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
360 // Create lists when lines begin with *
363 var pi = out.lastIndexOf('<p>');
367 l = l.replace(/^\*\s*/, '');
372 // Create headers when lines begin with = or #
373 if (l[0] == '=' || l[0] == '#') {
374 var m = l.match(/^([=#]+)/);
375 var depth = m[1].length;
377 l = l.replace(/^[=#]+\s*/, '').replace(/\s*[=#]+$/, '');
378 out.push('<h' + depth + '>');
379 endpush = '</h' + depth + '>';
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() {
518 if (loginStatus.loggedIn) {
519 var post = $('post');
520 if (post.visible()) {
524 if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
525 $('post.content').value = '@' + currentPager.username + ': ';
527 $('post.content').focus();
533 var username = $('signup.username').value;
534 var password = $('signup.password').value;
536 new Ajax.Request(baseURL + '/create', {
541 onSuccess: function(r) {
545 loginStatus.login(username, password);
547 onFailure: function(r) {
548 alert("Failed to create user");
553 function signup_cancel() {
558 function subscribe() {
559 new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
562 username: loginStatus.username
564 onSuccess: function(r) {
565 var response = r.responseText.evalJSON();
566 if (response.status == 'success') {
567 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
568 $$('[name=user.subscribelink]').each(Element.hide);
569 $$('[name=user.unsubscribelink]').each(Element.show);
571 alert('Failed to subscribe. This is probably for the best');
574 onFailure: function(r) {
575 alert('Failed to subscribe. This is probably for the best');
580 function unsubscribe() {
581 new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
584 username: loginStatus.username
586 onSuccess: function(r) {
587 var response = r.responseText.evalJSON();
588 if (response.status == 'success') {
589 alert("You come to your senses.");
590 $$('[name=user.subscribelink]').each(Element.show);
591 $$('[name=user.unsubscribelink]').each(Element.hide);
593 alert('You are unable to tear yourself away (because something failed on the server)');
596 onFailure: function(r) {
597 alert('You are unable to tear yourself away (because something failed on the server)');
602 var resizePostContentTimeout = null;
603 function resizePostContent() {
604 if (resizePostContentTimeout)
605 clearTimeout(resizePostContentTimeout);
606 resizePostContentTimeout = setTimeout(function() {
607 var c = $('post.content');
608 var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
609 var m = c.value.match(/\r?\n/g);
615 c.style.height = (lines * 17) + "pt";
617 resizePostContentTimeout = null;
621 var tickerTimer = null;
622 var tickerHead, tickerTail;
624 function tickerFader(a, b, p) {
628 a.style.lineHeight = (100 * p) + '%';
630 b.style.opacity = p2;
631 b.style.lineHeight = (100 * p2) + '%';
638 Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
639 tickerHead = tickerHead.nextSibling;
640 tickerTail = tickerTail.nextSibling;
641 if (tickerHead == null) {
643 loadLatest.delay(10);
647 function startTicker() {
649 for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
653 // Show the first five
654 tickerHead = $('latest-posts').firstChild;
655 for (var i = 0; i < 10 && tickerHead; i++) {
657 tickerHead = tickerHead.nextSibling;
659 tickerTail = $('latest-posts').firstChild;
660 tickerTimer = setInterval(ticker, 5000);
663 function stopTicker() {
665 clearInterval(tickerTimer);
669 function loadLatest() {
670 new Ajax.Request(baseURL + '/latest.json', {
671 onSuccess: function(r) {
672 var j = r.responseText.evalJSON();
674 $('latest-tags').update();
675 j.tags.each(function(v) {
676 var a = new Element('a', {href: '/#/tag/' + v});
678 a.onclick = "return qlink()";
680 $('latest-tags').insert(a);
681 $('latest-tags').appendChild(document.createTextNode(' '));
684 $('latest-posts').update();
685 j.records.each(function(v) {
686 v.data = v.data.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
687 v.date = (new Date(v.timestamp * 1000)).toString();
688 var html = latestRecordsTemplate.evaluate(v);
689 $('latest-posts').insert(html);
696 function qlink(loc) {
699 } else if (event && event.target) {
700 location.href = event.target.href;
709 function hashSwitch() {
712 if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
714 $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
715 } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/)) {
716 if (!currentPager || !(currentPager instanceof Tag) || currentPager.type != m[1] || currentPager.tag != m[2])
717 currentPager = new Tag(m[1], m[2]);
721 var r = parseInt(m[3]);
722 currentPager.showPageAt(r);
724 currentPager.showPageAt(currentPager.itemCount - 1);
726 } else if (m = location.hash.match(/^#\/feed(?:\/p(\d+))?$/)) {
727 if (loginStatus.loggedIn) {
728 if (!currentPager || !(currentPager instanceof Feed) || currentPager.username != loginStatus.username)
729 currentPager = new Feed();
732 var r = parseInt(m[3]);
733 currentPager.showPageAt(r);
735 currentPager.showPageAt(currentPager.itemCount - 1);
738 location.href = baseURL;
740 } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
741 if (!currentPager || !(currentPager instanceof User) || currentPager.username != m[1])
742 currentPager = new User(m[1]);
744 loginStatus.update();
747 var r = parseInt(m[3]);
749 currentPager.showPageAt(r);
751 currentPager.showRecord(r);
754 currentPager.reload();
757 $$('[name=section]').each(function(v) { v.update('Welcome') });
761 $('newer_link').hide();
762 $('older_link').hide();
765 $('usercontrols').hide();
771 function hashCheck() {
772 if (location.hash != lastHash) {
773 lastHash = location.hash;
780 loginStatus = new LoginStatus();
782 lastHash = location.hash;
785 setInterval(hashCheck, 250);
787 document.body.observe('keyup', function(event) {
788 if (event.shiftKey && event.keyCode == 32) {
793 $('post.content').addEventListener('keyup', function(event) {
794 event.stopPropagation();