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="' + baseURL + '/\##{author}/#{record}" onclick="return qlink()">[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="' + baseURL + '/\##{author}/#{record}" onclick="return qlink()">[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="' + baseURL + '/\##{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 onComplete: 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 = baseURL + '/#' + this.username;
84 $('userlink').update('@' + this.username);
85 $('reflink').href = baseURL + '/#/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;
130 this.itemCache = new Hash();
131 this.pageStart = null;
134 Pager.prototype.updateState = function(m) {
138 Pager.prototype.show = function() {
142 Pager.prototype.hide = function() {
145 $('newer_link').hide();
146 $('older_link').hide();
149 Pager.prototype.olderPage = function() {
150 if (this.pageStart >= this.itemsPerPage) {
151 qlink(this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage));
155 Pager.prototype.newerPage = function() {
156 if (this.pageStart + this.itemsPerPage < this.itemCount) {
157 qlink(this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage));
161 Pager.prototype.addItems = function(items) {
162 items.each(function(v) {
163 if (!this.itemCache[v.id])
164 this.itemCache[v.id] = v;
168 Pager.prototype.displayItems = function() {
169 if (this.pageStart == undefined)
170 this.pageStart == this.itemCount - 1;
173 if (this.pageStart != undefined && this.itemCache[this.pageStart]) {
174 var end = (this.pageStart >= this.itemsPerPage ? this.pageStart - this.itemsPerPage + 1 : 0);
175 for (var i = this.pageStart; i >= end; i--) {
176 items.insert(this.itemCache[i].html);
179 items.insert("There doesn't seem to be anything here!");
182 if (this.pageStart < this.itemCount - 1) {
183 $('newer_link').href = baseURL + '/#' + this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage);
184 $('newer_link').show();
186 $('newer_link').hide();
189 if (this.pageStart >= 10) {
190 $('older_link').href = baseURL + '/#' + this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage);
191 $('older_link').show();
193 $('older_link').hide();
196 document.body.scrollTo();
199 Pager.prototype.reload = function() {
200 this.pageStart = null;
201 this.loadItems(null, null, Pager.prototype.showPageAt.bind(this, this.itemCount - 1));
204 Pager.prototype.showPageAt = function(r) {
205 var end = (r - 9 > 0 ? r - 9 : 0);
206 if (this.itemCache[r] && this.itemCache[end]) {
210 this.loadItems((r >= 49 ? r - 49 : 0), r, Pager.prototype.showPageAt.bind(this, r));
214 Pager.prototype.showRecord = function(r) {
215 if (this.itemCache[r]) {
216 $('older_link').hide();
217 $('newer_link').hide();
218 items.update(this.itemCache[r].html);
220 this.loadItems(r, r, Pager.prototype.showRecord.bind(this, r));
224 Pager.prototype.loadItems = function(from, to, continuation) { }
227 // Object to render user pages
230 this.username = m[1];
231 this.baseFrag = m[1];
232 this.permalink = (m[2] != 'p');
233 this.pageStart = parseInt(m[3]);
235 User.prototype = new Pager();
236 User.prototype.constructor = User;
238 User.prototype.updateState = function(m) {
239 if (m[1] != this.username)
242 this.permalink = (m[2] != 'p');
243 this.pageStart = parseInt(m[3]);
249 User.prototype.show = function() {
250 Pager.prototype.show.call(this);
252 $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
254 $('rsslink').href = '/rss/' + this.username;
255 $$('[name=user.reflink]').each(function(e) {
256 e.href = baseURL + '/#/ref/' + this.username;
258 $('usercontrols').show();
260 if (this.permalink && this.pageStart >= 0) {
261 this.showRecord(this.pageStart);
262 } else if (this.pageStart >= 0) {
263 this.showPageAt(this.pageStart);
269 User.prototype.hide = function() {
270 Pager.prototype.hide.call(this);
273 $('usercontrols').hide();
276 User.prototype.reload = function() {
277 this.pageStart = null;
279 $$('[name=user.subscribelink]').each(Element.hide);
280 $$('[name=user.unsubscribelink]').each(Element.hide);
282 if (loginStatus.loggedIn) {
283 new Ajax.Request(baseURL + '/feedinfo/' + this.username, {
286 username: loginStatus.username
288 onSuccess: function(r) {
289 var json = r.responseText.evalJSON();
290 if (json.subscribed) {
291 $$('[name=user.subscribelink]').each(Element.hide);
292 $$('[name=user.unsubscribelink]').each(Element.show);
294 $$('[name=user.subscribelink]').each(Element.show);
295 $$('[name=user.unsubscribelink]').each(Element.hide);
301 new Ajax.Request(baseURL + '/info/' + this.username, {
303 onSuccess: function(r) {
304 var response = r.responseText.evalJSON();
306 this.itemCount = parseInt(response.record_count);
307 this.showPageAt(this.itemCount - 1);
313 User.prototype.loadItems = function(from, to, continuation) {
318 if (from != undefined && to != undefined) {
319 url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
322 url = baseURL + '/get/' + this.username;
325 new Ajax.Request(url, {
327 onSuccess: function(r) {
328 var records = r.responseText.evalJSON();
329 if (records && records.length > 0) {
330 records.each(function(v) {
332 v.author = this.username;
333 mangleRecord(v, recordTemplate);
335 this.addItems(records);
337 this.pageStart = records[0].recInt;
341 onFailure: function(r) {
345 displayError('User not found');
350 function mangleRecord(record, template) {
351 record.recInt = parseInt(record.record);
353 var lines = record.data.split(/\r?\n/);
354 if (lines[lines.length - 1] == '')
359 var listMode = false;
360 lines.each(function(l) {
362 if (out[out.length - 1] == '<br>') {
363 out[out.length - 1] = '<p>';
365 if (out[out.length - 1] == '</li>') {
373 // Put quoted material into a special paragraph
375 var pi = out.lastIndexOf('<p>');
377 out[pi] = '<p class="quote">';
378 l = l.replace(/^>\s*/, '');
382 // Sanitize HTML input
383 l = l.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
385 // Turn HTTP URLs into links
386 l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
388 // Turn markdown links into links
389 l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
391 // Turn *foo* into italics and **foo** into bold
392 l = l.replace(/([^\w\\]|^)\*\*(\w[^*]*)\*\*(\W|$)/g, '$1<b>$2</b>$3');
393 l = l.replace(/([^\w\\]|^)\*(\w[^*]*)\*(\W|$)/g, '$1<i>$2</i>$3');
395 // Turn refs and tags into links
396 l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
397 l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)(\/\d+)?/g, '$1<a href="#$2$3" class="ref" onclick="return qlink()">@$2</a>');
399 // Create lists when lines begin with *
402 var pi = out.lastIndexOf('<p>');
406 l = l.replace(/^\*\s*/, '');
411 // Create headers when lines begin with = or #
412 if (l[0] == '=' || l[0] == '#') {
413 var m = l.match(/^([=#]+)/);
414 var depth = m[1].length;
416 l = l.replace(/^[=#]+\s*/, '').replace(/\s*[=#]+$/, '');
417 out.push('<h' + depth + '>');
418 endpush = '</h' + depth + '>';
422 // Remove backslashes from escaped metachars
423 l = l.replace(/\\([*\[\]@#])/g, '$1');
433 while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
438 record.data = out.join('');
439 record.date = (new Date(record.timestamp * 1000)).toString();
440 record.html = template.evaluate(record);
443 function displayError(msg) {
444 items.innerText = msg;
448 // Object for browsing tags
453 this.pageStart = parseInt(m[3]);
455 var url = baseURL + "/tag/";
459 url += 'H'; // apache is eating the hash, even encoded. Probably a security feature.
460 this.baseFrag = '/tag/' + this.tag;
464 this.baseFrag = '/ref/' + this.tag;
467 alert('Invalid tag type: ' + this.type);
472 new Ajax.Request(url, {
474 onSuccess: function(r) {
475 var j = r.responseText.evalJSON();
477 var maxid = j.length - 1;
478 j.each(function(v, i) {
480 mangleRecord(v, tagRecordTemplate)
484 this.pageStart = j.length - 1;
485 this.itemCount = j.length;
489 onFailure: function(r) {
495 Tag.prototype = new Pager();
496 Tag.prototype.constructor = Tag;
498 Tag.prototype.updateState = function(m) {
499 if (this.type != m[1] || this.tag != m[2])
502 this.pageStart = parseInt(m[3]) || this.itemCount - 1;
508 Tag.prototype.show = function() {
509 Pager.prototype.show.call(this);
511 var ctype = {ref: '@', tag: '#'}[this.type];
513 $$('[name=section]').each(function(v) {
514 v.update(' about ' + ctype + this.tag);
519 // Pager for browsing subscription feeds
522 this.username = loginStatus.username;
523 this.baseFrag = '/feed';
524 this.pageStart = parseInt(m[1]);
526 new Ajax.Request(baseURL + '/feed', {
529 username: loginStatus.username
531 onSuccess: function(r) {
532 var response = r.responseText.evalJSON();
534 var maxid = response.length - 1;
535 response.each(function(v, i) {
537 mangleRecord(v, tagRecordTemplate)
539 this.addItems(response);
541 this.pageStart = response.length - 1;
542 this.itemCount = response.length;
546 onFailure: function(r) {
551 Feed.prototype = new Pager();
552 Feed.prototype.constructor = Feed;
554 Feed.prototype.updateState = function(m) {
555 this.pageStart = parseInt(m[1]) || this.itemCount - 1;
561 Feed.prototype.show = function() {
562 Pager.prototype.show.call(this);
563 $$('[name=section]').each(function(v) {
564 v.update(' ' + loginStatus.username + "'s spycam");
569 function postPopup(initial) {
570 if (loginStatus.loggedIn || initial) {
571 var post = $('post');
572 if (post.visible()) {
577 $('post.content').value = initial;
578 } else if (!$('post.content').value && currentPager.username && currentPager.username != loginStatus.username) {
579 $('post.content').value = '@' + currentPager.username + ': ';
581 $('post.content').focus();
587 var username = $('signup.username').value;
588 var password = $('signup.password').value;
590 new Ajax.Request(baseURL + '/create', {
595 onSuccess: function(r) {
599 loginStatus.login(username, password);
601 onFailure: function(r) {
602 alert("Failed to create user");
607 function signup_cancel() {
612 function subscribe() {
613 new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
616 username: loginStatus.username
618 onSuccess: function(r) {
619 var response = r.responseText.evalJSON();
620 if (response.status == 'success') {
621 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
622 $$('[name=user.subscribelink]').each(Element.hide);
623 $$('[name=user.unsubscribelink]').each(Element.show);
625 alert('Failed to subscribe. This is probably for the best');
628 onFailure: function(r) {
629 alert('Failed to subscribe. This is probably for the best');
634 function unsubscribe() {
635 new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
638 username: loginStatus.username
640 onSuccess: function(r) {
641 var response = r.responseText.evalJSON();
642 if (response.status == 'success') {
643 alert("You come to your senses.");
644 $$('[name=user.subscribelink]').each(Element.show);
645 $$('[name=user.unsubscribelink]').each(Element.hide);
647 alert('You are unable to tear yourself away (because something failed on the server)');
650 onFailure: function(r) {
651 alert('You are unable to tear yourself away (because something failed on the server)');
656 var resizePostContentTimeout = null;
657 function resizePostContent() {
658 if (resizePostContentTimeout)
659 clearTimeout(resizePostContentTimeout);
660 resizePostContentTimeout = setTimeout(function() {
661 var c = $('post.content');
662 var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
663 var m = c.value.match(/\r?\n/g);
669 c.style.height = (lines * 17) + "pt";
671 resizePostContentTimeout = null;
675 var tickerTimer = null;
676 var tickerHead, tickerTail;
678 function tickerFader(a, b, p) {
682 a.style.lineHeight = (100 * p) + '%';
684 b.style.opacity = p2;
685 b.style.lineHeight = (100 * p2) + '%';
692 Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
693 tickerHead = tickerHead.nextSibling;
694 tickerTail = tickerTail.nextSibling;
695 if (tickerHead == null) {
697 loadLatest.delay(10);
701 function startTicker() {
703 for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
707 // Show the first five
708 tickerHead = $('latest-posts').firstChild;
709 for (var i = 0; i < 10 && tickerHead; i++) {
711 tickerHead = tickerHead.nextSibling;
713 tickerTail = $('latest-posts').firstChild;
714 tickerTimer = setInterval(ticker, 5000);
717 function stopTicker() {
719 clearInterval(tickerTimer);
723 function loadLatest() {
724 new Ajax.Request(baseURL + '/latest.json', {
726 onSuccess: function(r) {
727 var j = r.responseText.evalJSON();
729 $('latest-tags').update();
730 j.tags.each(function(v) {
731 var a = new Element('a', {href: baseURL + '/#/tag/' + v});
733 a.onclick = "return qlink()";
735 $('latest-tags').insert(a);
736 $('latest-tags').appendChild(document.createTextNode(' '));
739 $('latest-posts').update();
740 j.records.each(function(v) {
741 v.data = v.data.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
742 v.date = (new Date(v.timestamp * 1000)).toString();
743 var html = latestRecordsTemplate.evaluate(v);
744 $('latest-posts').insert(html);
751 function qlink(loc) {
754 } else if (event && event.target) {
755 location.href = event.target.href;
760 lastHash = location.hash;
769 Welcome.prototype.show = function() {
770 $$('[name=section]').each(function(v) { v.update('Welcome') });
774 Welcome.prototype.hide = function() {
779 function ExternalURLPost(m) {
780 this.title = decodeURIComponent(m[1]).replace(']','').replace('[','');
781 this.url = decodeURIComponent(m[2]);
784 ExternalURLPost.prototype.show = function() {
785 $('post.content').value = '[' + this.title + '](' + this.url + ')';
790 ['search', /^\?post\/([^/]+)\/(.+)/, ExternalURLPost],
791 ['hash', /^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/, Tag],
792 ['hash', /^#\/feed(?:\/p(\d+))?$/, Feed],
793 ['hash', /^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/, User]
796 function urlSwitch() {
800 for (var i = 0; i < urlmap.length; i++) {
801 if (m = location[urlmap[i][0]].match(urlmap[i][1])) {
802 pageconstructor = urlmap[i][2];
806 if (i == urlmap.length)
807 pageconstructor = Welcome;
809 if (currentPager && currentPager instanceof pageconstructor) {
810 // updateState returns true if the state has been successfully updated.
811 // Otherwise, we continue and create a new instance.
812 if (currentPager.updateState(m))
816 if (currentPager && currentPager.hide)
819 currentPager = new pageconstructor(m);
820 if (currentPager.show)
825 function hashCheck() {
826 if (location.hash != lastHash) {
827 lastHash = location.hash;
834 loginStatus = new LoginStatus();
836 lastHash = location.hash;
839 setInterval(hashCheck, 250);
841 document.body.observe('keyup', function(event) {
842 if (event.shiftKey && event.keyCode == 32) {
847 $('post.content').addEventListener('keyup', function(event) {
848 event.stopPropagation();