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 User.prototype = new Pager();
220 User.prototype.constructor = User;
222 User.prototype.show = function() {
223 $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
227 $('rsslink').href = '/rss/' + this.username;
228 $$('[name=user.reflink]').each(function(e) {
229 e.href = '/#/ref/' + this.username;
231 $('usercontrols').show();
234 User.prototype.reload = function() {
235 this.pageStart = null;
237 $$('[name=user.subscribelink]').each(Element.hide);
238 $$('[name=user.unsubscribelink]').each(Element.hide);
240 if (loginStatus.loggedIn) {
241 new Ajax.Request(baseURL + '/feedinfo/' + username, {
244 username: loginStatus.username
246 onSuccess: function(r) {
247 var json = r.responseText.evalJSON();
248 if (json.subscribed) {
249 $$('[name=user.subscribelink]').each(Element.hide);
250 $$('[name=user.unsubscribelink]').each(Element.show);
252 $$('[name=user.subscribelink]').each(Element.show);
253 $$('[name=user.unsubscribelink]').each(Element.hide);
259 new Ajax.Request(baseURL + '/info/' + this.username, {
261 onSuccess: function(r) {
262 var j = r.responseText.evalJSON();
264 this.itemCount = parseInt(j.record_count);
266 this.showPageAt(this.itemCount - 1);
272 User.prototype.loadItems = function(from, to, continuation) {
274 if (from != undefined && to != undefined) {
275 url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
278 url = baseURL + '/get/' + this.username;
281 new Ajax.Request(url, {
283 onSuccess: function(r) {
284 var records = r.responseText.evalJSON();
285 if (records && records.length > 0) {
286 records.each(function(v) {
288 v.author = this.username;
289 mangleRecord(v, recordTemplate);
291 this.addItems(records);
293 this.pageStart = records[0].recInt;
297 onFailure: function(r) {
301 displayError('User not found');
306 function mangleRecord(record, template) {
307 record.recInt = parseInt(record.record);
309 var lines = record.data.split(/\r?\n/);
310 if (lines[lines.length - 1] == '')
315 var listMode = false;
316 lines.each(function(l) {
318 if (out[out.length - 1] == '<br>') {
319 out[out.length - 1] = '<p>';
321 if (out[out.length - 1] == '</li>') {
329 // Put quoted material into a special paragraph
331 var pi = out.lastIndexOf('<p>');
333 out[pi] = '<p class="quote">';
334 l = l.replace(/^>\s*/, '');
338 // Sanitize HTML input
339 l = l.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
341 // Turn HTTP URLs into links
342 l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
344 // Turn markdown links into links
345 l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
347 // Turn *foo* into italics and **foo** into bold
348 l = l.replace(/([^\w\\]|^)\*\*(\w[^*]*)\*\*(\W|$)/g, '$1<b>$2</b>$3');
349 l = l.replace(/([^\w\\]|^)\*(\w[^*]*)\*(\W|$)/g, '$1<i>$2</i>$3');
351 // Remove backslashes from escaped metachars
352 l = l.replace(/\\([*\[\]])/g, '$1');
354 // Turn refs and tags into links
355 l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
356 l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
358 // Create lists when lines begin with *
361 var pi = out.lastIndexOf('<p>');
365 l = l.replace(/^\*\s*/, '');
370 // Create headers when lines begin with = or #
371 if (l[0] == '=' || l[0] == '#') {
372 var m = l.match(/^([=#]+)/);
373 var depth = m[1].length;
375 l = l.replace(/^[=#]+\s*/, '').replace(/\s*[=#]+$/, '');
376 out.push('<h' + depth + '>');
377 endpush = '</h' + depth + '>';
389 while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
394 record.data = out.join('');
395 record.date = (new Date(record.timestamp * 1000)).toString();
396 record.html = template.evaluate(record);
399 function displayError(msg) {
400 items.innerText = msg;
404 // Object for browsing tags
405 function Tag(type, tag) {
410 var url = baseURL + "/tag/";
414 url += 'H'; // apache is eating the hash, even encoded. Probably a security feature.
415 this.baseFrag = '/tag/' + tag;
419 this.baseFrag = '/ref/' + tag;
422 alert('Invalid tag type: ' + type);
427 new Ajax.Request(url, {
429 onSuccess: function(r) {
430 var j = r.responseText.evalJSON();
432 var maxid = j.length - 1;
433 j.each(function(v, i) {
435 mangleRecord(v, tagRecordTemplate)
438 this.pageStart = j.length - 1;
439 this.itemCount = j.length;
443 onFailure: function(r) {
449 Tag.prototype = new Pager();
450 Tag.prototype.constructor = Tag;
452 Tag.prototype.show = function() {
453 var ctype = {ref: '@', tag: '#'}[this.type];
455 $$('[name=section]').each(function(v) {
456 v.update(' about ' + ctype + this.tag);
460 $('older_link').hide();
461 $('newer_link').hide();
464 $('usercontrols').hide();
468 // Pager for browsing subscription feeds
471 this.username = loginStatus.username;
472 this.baseFrag = '/feed';
474 new Ajax.Request(baseURL + '/feed', {
477 username: loginStatus.username
479 onSuccess: function(r) {
480 var response = r.responseText.evalJSON();
482 var maxid = response.length - 1;
483 response.each(function(v, i) {
485 mangleRecord(v, tagRecordTemplate)
487 this.addItems(response);
488 this.pageStart = response.length - 1;
489 this.itemCount = response.length;
493 onFailure: function(r) {
498 Feed.prototype = new Pager();
499 Feed.prototype.constructor = Feed;
501 Feed.prototype.show = function() {
502 $$('[name=section]').each(function(v) {
503 v.update(' ' + loginStatus.username + "'s spycam");
507 $('older_link').hide();
508 $('newer_link').hide();
511 $('usercontrols').hide();
515 function postPopup() {
516 if (loginStatus.loggedIn) {
517 var post = $('post');
518 if (post.visible()) {
522 if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
523 $('post.content').value = '@' + currentPager.username + ': ';
525 $('post.content').focus();
531 var username = $('signup.username').value;
532 var password = $('signup.password').value;
534 new Ajax.Request(baseURL + '/create', {
539 onSuccess: function(r) {
543 loginStatus.login(username, password);
545 onFailure: function(r) {
546 alert("Failed to create user");
551 function signup_cancel() {
556 function subscribe() {
557 new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
560 username: loginStatus.username
562 onSuccess: function(r) {
563 var response = r.responseText.evalJSON();
564 if (response.status == 'success') {
565 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
566 $$('[name=user.subscribelink]').each(Element.hide);
567 $$('[name=user.unsubscribelink]').each(Element.show);
569 alert('Failed to subscribe. This is probably for the best');
572 onFailure: function(r) {
573 alert('Failed to subscribe. This is probably for the best');
578 function unsubscribe() {
579 new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
582 username: loginStatus.username
584 onSuccess: function(r) {
585 var response = r.responseText.evalJSON();
586 if (response.status == 'success') {
587 alert("You come to your senses.");
588 $$('[name=user.subscribelink]').each(Element.show);
589 $$('[name=user.unsubscribelink]').each(Element.hide);
591 alert('You are unable to tear yourself away (because something failed on the server)');
594 onFailure: function(r) {
595 alert('You are unable to tear yourself away (because something failed on the server)');
600 var resizePostContentTimeout = null;
601 function resizePostContent() {
602 if (resizePostContentTimeout)
603 clearTimeout(resizePostContentTimeout);
604 resizePostContentTimeout = setTimeout(function() {
605 var c = $('post.content');
606 var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
607 var m = c.value.match(/\r?\n/g);
613 c.style.height = (lines * 17) + "pt";
615 resizePostContentTimeout = null;
619 var tickerTimer = null;
620 var tickerHead, tickerTail;
622 function tickerFader(a, b, p) {
626 a.style.lineHeight = (100 * p) + '%';
628 b.style.opacity = p2;
629 b.style.lineHeight = (100 * p2) + '%';
636 Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
637 tickerHead = tickerHead.nextSibling;
638 tickerTail = tickerTail.nextSibling;
639 if (tickerHead == null) {
641 loadLatest.delay(10);
645 function startTicker() {
647 for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
651 // Show the first five
652 tickerHead = $('latest-posts').firstChild;
653 for (var i = 0; i < 10 && tickerHead; i++) {
655 tickerHead = tickerHead.nextSibling;
657 tickerTail = $('latest-posts').firstChild;
658 tickerTimer = setInterval(ticker, 5000);
661 function stopTicker() {
663 clearInterval(tickerTimer);
667 function loadLatest() {
668 new Ajax.Request(baseURL + '/latest.json', {
669 onSuccess: function(r) {
670 var j = r.responseText.evalJSON();
672 $('latest-tags').update();
673 j.tags.each(function(v) {
674 var a = new Element('a', {href: '/#/tag/' + v});
676 a.onclick = "return qlink()";
678 $('latest-tags').insert(a);
679 $('latest-tags').appendChild(document.createTextNode(' '));
682 $('latest-posts').update();
683 j.records.each(function(v) {
684 v.data = v.data.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
685 v.date = (new Date(v.timestamp * 1000)).toString();
686 var html = latestRecordsTemplate.evaluate(v);
687 $('latest-posts').insert(html);
694 function qlink(loc) {
697 } else if (event && event.target) {
698 location.href = event.target.href;
707 function hashSwitch() {
710 if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
712 $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
713 } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/)) {
714 if (!currentPager || !(currentPager instanceof Tag) || currentPager.type != m[1] || currentPager.tag != m[2])
715 currentPager = new Tag(m[1], m[2]);
719 var r = parseInt(m[3]);
720 currentPager.showPageAt(r);
722 } else if (m = location.hash.match(/^#\/feed(?:\/p(\d+))?$/)) {
723 if (loginStatus.loggedIn) {
724 if (!currentPager || !(currentPager instanceof Feed) || currentPager.username != loginStatus.username)
725 currentPager = new Feed();
728 var r = parseInt(m[3]);
729 currentPager.showPageAt(r);
732 location.href = baseURL;
734 } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
735 if (!currentPager || !(currentPager instanceof User) || currentPager.username != m[1])
736 currentPager = new User(m[1]);
738 loginStatus.update();
741 var r = parseInt(m[3]);
743 currentPager.showPageAt(r);
745 currentPager.showRecord(r);
748 currentPager.reload();
751 $$('[name=section]').each(function(v) { v.update('Welcome') });
755 $('newer_link').hide();
756 $('older_link').hide();
759 $('usercontrols').hide();
765 function hashCheck() {
766 if (location.hash != lastHash) {
767 lastHash = location.hash;
774 loginStatus = new LoginStatus();
776 lastHash = location.hash;
779 setInterval(hashCheck, 250);
781 document.body.observe('keyup', function(event) {
782 if (event.shiftKey && event.keyCode == 32) {
787 $('post.content').addEventListener('keyup', function(event) {
788 event.stopPropagation();