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}</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.pageStart = null;
115 currentPager.loadItems();
118 alert('Post failed!');
121 onFailure: function(r) {
122 alert('Post failed!');
128 // Base object for paged data
130 this.itemsPerPage = 10;
133 Pager.prototype.initPager = function() {
134 this.itemCache = new Hash();
135 this.pageStart = null;
138 Pager.prototype.olderPage = function() {
139 if (this.pageStart >= this.itemsPerPage) {
140 qlink(this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage));
144 Pager.prototype.newerPage = function() {
145 if (this.pageStart + this.itemsPerPage < this.itemCount) {
146 qlink(this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage));
150 Pager.prototype.addItems = function(items) {
151 items.each(function(v) {
152 if (!this.itemCache[v.id])
153 this.itemCache[v.id] = v;
157 Pager.prototype.displayItems = function() {
158 if (this.pageStart == undefined)
159 this.pageStart == this.itemCount - 1;
162 if (this.pageStart != undefined && this.itemCache[this.pageStart]) {
163 var end = (this.pageStart >= this.itemsPerPage ? this.pageStart - this.itemsPerPage + 1 : 0);
164 for (var i = this.pageStart; i >= end; i--) {
165 items.insert(this.itemCache[i].html);
168 items.insert("There doesn't seem to be anything here!");
171 if (this.pageStart < this.itemCount - 1) {
172 $('newer_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage);
173 $('newer_link').show();
175 $('newer_link').hide();
178 if (this.pageStart >= 10) {
179 $('older_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage);
180 $('older_link').show();
182 $('older_link').hide();
186 Pager.prototype.showPageAt = function(r) {
187 if (this.itemCache[r] && this.itemCache[r - 9]) {
191 this.loadItems((r >= 49 ? r - 49 : 0), r);
195 Pager.prototype.showRecord = function(r) {
200 // Object to render user pages
201 function User(username) {
203 this.username = username;
204 this.baseFrag = username;
206 $$('[name=user.subscribelink]').each(Element.hide);
207 $$('[name=user.unsubscribelink]').each(Element.hide);
209 if (loginStatus.loggedIn) {
210 new Ajax.Request(baseURL + '/feedinfo/' + username, {
213 username: loginStatus.username
215 onSuccess: function(r) {
216 var json = r.responseText.evalJSON();
217 if (json.subscribed) {
218 $$('[name=user.subscribelink]').each(Element.hide);
219 $$('[name=user.unsubscribelink]').each(Element.show);
221 $$('[name=user.subscribelink]').each(Element.show);
222 $$('[name=user.unsubscribelink]').each(Element.hide);
228 new Ajax.Request(baseURL + '/info/' + username, {
230 onSuccess: function(r) {
231 var j = r.responseText.evalJSON();
233 this.itemCount = parseInt(j.record_count);
239 User.prototype = new Pager();
240 User.prototype.constructor = User;
242 User.prototype.show = function() {
243 $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
247 $('rsslink').href = '/rss/' + this.username;
248 $$('[name=user.reflink]').each(function(e) {
249 e.href = '/#/ref/' + this.username;
251 $('usercontrols').show();
254 User.prototype.loadItems = function(from, to) {
256 if (from != undefined && to != undefined) {
257 url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
260 url = baseURL + '/get/' + this.username;
263 new Ajax.Request(url, {
265 onSuccess: function(r) {
266 var records = r.responseText.evalJSON();
267 if (records && records.length > 0) {
268 records.each(function(v) {
270 mangleRecord(v, recordTemplate);
272 this.addItems(records);
274 this.pageStart = records[0].recInt;
278 onFailure: function(r) {
282 displayError('User not found');
287 function mangleRecord(record, template) {
288 record.recInt = parseInt(record.record);
290 var lines = record.data.split(/\r?\n/);
291 if (lines[lines.length - 1] == '')
296 var listMode = false;
297 lines.each(function(l) {
299 if (out[out.length - 1] == '<br>') {
300 out[out.length - 1] = '<p>';
302 if (out[out.length - 1] == '</li>') {
310 // Put quoted material into a special paragraph
312 var pi = out.lastIndexOf('<p>');
314 out[pi] = '<p class="quote">';
315 l = l.replace(/^>\s*/, '');
319 // Sanitize HTML input
320 l = l.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
322 // Turn HTTP URLs into links
323 l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
325 // Turn markdown links into links
326 l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
328 // Turn *foo* into italics and **foo** into bold
329 l = l.replace(/(\W|^)\*\*([^*]+)\*\*(\W|$)/g, '$1<b>$2</b>$3');
330 l = l.replace(/(\W|^)\*([^*]+)\*(\W|$)/g, '$1<i>$2</i>$3');
332 // Turn refs and tags into links
333 l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
334 l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
336 // Create lists when lines begin with *
339 var pi = out.lastIndexOf('<p>');
343 l = l.replace(/^\*\s*/, '');
348 // Create headers when lines begin with =
350 var m = l.match(/^(=+)/);
351 var depth = m[1].length;
353 l = l.replace(/^=+\s*/, '').replace(/\s*=+$/, '');
354 out.push('<h' + depth + '>');
355 endpush = '</h' + depth + '>';
367 while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
372 record.data = out.join('');
373 record.date = (new Date(record.timestamp * 1000)).toString();
374 record.html = template.evaluate(record);
377 function displayError(msg) {
378 items.innerText = msg;
382 // Object for browsing tags
383 function Tag(type, tag) {
388 var url = baseURL + "/tag/";
392 url += 'H'; // apache is eating the hash, even encoded. Probably a security feature.
393 this.baseFrag = '/tag/' + tag;
397 this.baseFrag = '/ref/' + tag;
400 alert('Invalid tag type: ' + type);
405 new Ajax.Request(url, {
407 onSuccess: function(r) {
408 var j = r.responseText.evalJSON();
410 var maxid = j.length - 1;
411 j.each(function(v, i) {
413 mangleRecord(v, tagRecordTemplate)
416 this.pageStart = j.length - 1;
420 onFailure: function(r) {
426 Tag.prototype = new Pager();
427 Tag.prototype.constructor = Tag;
429 Tag.prototype.show = function() {
430 var ctype = {ref: '@', tag: '#'}[this.type];
432 $$('[name=section]').each(function(v) {
433 v.update(' about ' + ctype + this.tag);
437 $('older_link').hide();
438 $('newer_link').hide();
441 $('usercontrols').hide();
445 // Pager for browsing subscription feeds
448 this.baseFrag = '/feed';
450 new Ajax.Request(baseURL + '/feed', {
453 username: loginStatus.username
455 onSuccess: function(r) {
456 var response = r.responseText.evalJSON();
458 var maxid = response.length - 1;
459 response.each(function(v, i) {
461 mangleRecord(v, tagRecordTemplate)
463 this.addItems(response);
464 this.pageStart = response.length - 1;
468 onFailure: function(r) {
473 Feed.prototype = new Pager();
474 Feed.prototype.constructor = Feed;
476 Feed.prototype.show = function() {
477 $$('[name=section]').each(function(v) {
478 v.update(' ' + loginStatus.username + "'s spycam");
482 $('older_link').hide();
483 $('newer_link').hide();
486 $('usercontrols').hide();
490 function postPopup() {
491 if (loginStatus.loggedIn) {
492 var post = $('post');
493 if (post.visible()) {
497 if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
498 $('post.content').value = '@' + currentPager.username + ': ';
500 $('post.content').focus();
506 var username = $('signup.username').value;
507 var password = $('signup.password').value;
509 new Ajax.Request(baseURL + '/create', {
514 onSuccess: function(r) {
518 loginStatus.login(username, password);
520 onFailure: function(r) {
521 alert("Failed to create user");
526 function signup_cancel() {
531 function subscribe() {
532 new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
535 username: loginStatus.username
537 onSuccess: function(r) {
538 var response = r.responseText.evalJSON();
539 if (response.status == 'success') {
540 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
541 $$('[name=user.subscribelink]').each(Element.hide);
542 $$('[name=user.unsubscribelink]').each(Element.show);
544 alert('Failed to subscribe. This is probably for the best');
547 onFailure: function(r) {
548 alert('Failed to subscribe. This is probably for the best');
553 function unsubscribe() {
554 new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
557 username: loginStatus.username
559 onSuccess: function(r) {
560 var response = r.responseText.evalJSON();
561 if (response.status == 'success') {
562 alert("You come to your senses.");
563 $$('[name=user.subscribelink]').each(Element.show);
564 $$('[name=user.unsubscribelink]').each(Element.hide);
566 alert('You are unable to tear yourself away (because something failed on the server)');
569 onFailure: function(r) {
570 alert('You are unable to tear yourself away (because something failed on the server)');
575 var resizePostContentTimeout = null;
576 function resizePostContent() {
577 if (resizePostContentTimeout)
578 clearTimeout(resizePostContentTimeout);
579 resizePostContentTimeout = setTimeout(function() {
580 var c = $('post.content');
581 var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
582 var m = c.value.match(/\r?\n/g);
588 c.style.height = (lines * 17) + "pt";
590 resizePostContentTimeout = null;
594 var tickerTimer = null;
595 var tickerHead, tickerTail;
597 function tickerFader(a, b, p) {
601 a.style.lineHeight = (100 * p) + '%';
603 b.style.opacity = p2;
604 b.style.lineHeight = (100 * p2) + '%';
611 Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
612 tickerHead = tickerHead.nextSibling;
613 tickerTail = tickerTail.nextSibling;
614 if (tickerHead == null) {
616 loadLatest.delay(10);
620 function startTicker() {
622 for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
626 // Show the first five
627 tickerHead = $('latest-posts').firstChild;
628 for (var i = 0; i < 10 && tickerHead; i++) {
630 tickerHead = tickerHead.nextSibling;
632 tickerTail = $('latest-posts').firstChild;
633 tickerTimer = setInterval(ticker, 5000);
636 function stopTicker() {
638 clearInterval(tickerTimer);
642 function loadLatest() {
643 new Ajax.Request(baseURL + '/latest.json', {
644 onSuccess: function(r) {
645 var j = r.responseText.evalJSON();
647 $('latest-tags').update();
648 j.tags.each(function(v) {
649 var a = new Element('a', {href: '/#/tag/' + v});
653 $('latest-tags').insert(a);
654 $('latest-tags').appendChild(document.createTextNode(' '));
657 $('latest-posts').update();
658 j.records.each(function(v) {
659 v.data = v.data.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
660 v.date = (new Date(v.timestamp * 1000)).toString();
661 var html = latestRecordsTemplate.evaluate(v);
662 $('latest-posts').insert(html);
669 function qlink(loc) {
672 } else if (event && event.target) {
673 location.href = event.target.href;
682 function hashSwitch() {
685 if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
687 $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
688 } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)$/)) {
689 currentPager = new Tag(m[1], m[2]);
691 } else if (m = location.hash.match(/^#\/feed/)) {
692 if (loginStatus.loggedIn) {
693 currentPager = new Feed();
696 location.href = baseURL;
698 } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
699 if (!currentPager || currentPager.username != m[1])
700 currentPager = new User(m[1]);
702 loginStatus.update();
705 var r = parseInt(m[3]);
707 currentPager.showPageAt(r);
709 currentPager.showRecord(r);
712 currentPager.pageStart = currentPager.itemCount - 1;
713 currentPager.loadItems();
716 $$('[name=section]').each(function(v) { v.update('Welcome') });
720 $('newer_link').hide();
721 $('older_link').hide();
724 $('usercontrols').hide();
730 function hashCheck() {
731 if (location.hash != lastHash) {
732 lastHash = location.hash;
739 loginStatus = new LoginStatus();
741 lastHash = location.hash;
744 setInterval(hashCheck, 250);
746 document.body.observe('keyup', function(event) {
747 if (event.shiftKey && event.keyCode == 32) {
752 $('post.content').addEventListener('keyup', function(event) {
753 event.stopPropagation();