Add support for markdown-style headlines (lines beginning with #)
[blerg.git] / www / js / blerg.js
index 7bb5fe2..d227a7a 100644 (file)
@@ -1,10 +1,17 @@
+/* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
+ * BSD-style license.  Please see the COPYING file for details.
+ */
+
 // Config
 var baseURL = '';
 var recordTemplate = new Template(
-    '<div class="record">#{data}<div class="info">Posted #{date}</div></div>'
+    '<div class="record">#{data}<div class="info">Posted #{date}. <a href="/\##{author}/#{record}">[permalink]</a></div></div>'
 );
 var tagRecordTemplate = new Template(
-    '<div class="record">#{data}<div class="info">Posted by <a href="\##{author}">@#{author}</a> on #{date}</div></div>'
+    '<div class="record">#{data}<div class="info">Posted by <a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> on #{date}</div></div>'
+);
+var latestRecordsTemplate = new Template(
+    '<div class="record"><a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> #{data}</div>'
 );
 
 // Page elements
@@ -35,7 +42,7 @@ LoginStatus.prototype.login = function(username, password) {
     new Ajax.Request(baseURL + '/login', {
         parameters: {
             username: username,
-            password: password,
+            password: password
         },
         onSuccess: function(r) {
             var j = r.responseText.evalJSON();
@@ -60,21 +67,22 @@ LoginStatus.prototype.login = function(username, password) {
 LoginStatus.prototype.logout = function() {
     new Ajax.Request(baseURL + '/logout', {
         parameters: {
-            username: this.username,
+            username: this.username
         },
         onSuccess: function(r) {
             this.loggedIn = false;
             document.cookie = "auth=; expires=1-Jan-1970 00:00:00 GMT";
             this.update();
-        }.bind(this),
+        }.bind(this)
     });
     document.cookie = "username=; expires=1-Jan-1970 00:00:00 GMT";
 }
 
 LoginStatus.prototype.update = function() {
     if (this.loggedIn) {
-        $('userlink').href = '#' + this.username;
+        $('userlink').href = '/#' + this.username;
         $('userlink').update('@' + this.username);
+        $('reflink').href = '/#/ref/' + this.username;
         $('login').hide();
         $('logout').show();
     } else {
@@ -87,7 +95,7 @@ LoginStatus.prototype.update = function() {
 LoginStatus.prototype.post = function(msg) {
     if (!this.loggedIn) {
         alert("You are not logged in!");
-        exit(0);
+        return;
     }
 
     new Ajax.Request(baseURL + '/put', {
@@ -100,12 +108,10 @@ LoginStatus.prototype.post = function(msg) {
             if (j && j.status == 'success') {
                 $('post.content').value = '';
                 if (location.hash != '#' + this.username) {
-                    location.hash = this.username;
-                    hashSwitch();
+                    qlink(this.username);
                 } else {
                     currentPager.itemCount++;
-                    currentPager.pageStart = null;
-                    currentPager.loadItems();
+                    currentPager.reload();
                 }
             } else {
                 alert('Post failed!');
@@ -130,15 +136,13 @@ Pager.prototype.initPager = function() {
 
 Pager.prototype.olderPage = function() {
     if (this.pageStart >= this.itemsPerPage) {
-        this.pageStart -= this.itemsPerPage;
-        this.displayItems();
+        qlink(this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage));
     }
 }
 
 Pager.prototype.newerPage = function() {
     if (this.pageStart + this.itemsPerPage < this.itemCount) {
-        this.pageStart += this.itemsPerPage;
-        this.displayItems();
+        qlink(this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage));
     }
 }
 
@@ -163,15 +167,46 @@ Pager.prototype.displayItems = function() {
         items.insert("There doesn't seem to be anything here!");
     }
 
-    if (this.pageStart < this.itemCount - 1)
+    if (this.pageStart < this.itemCount - 1) {
+        $('newer_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage);
         $('newer_link').show();
-    else
+    } else {
         $('newer_link').hide();
+    }
 
-    if (this.pageStart >= 10)
+    if (this.pageStart >= 10) {
+        $('older_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage);
         $('older_link').show();
-    else
+    } else {
         $('older_link').hide();
+    }
+
+    document.body.scrollTo();
+}
+
+Pager.prototype.reload = function() {
+    this.pageStart = null;
+    this.loadItems(null, null, Pager.prototype.showPageAt.bind(this, this.itemCount - 1));
+}
+
+Pager.prototype.showPageAt = function(r) {
+    var end = (r - 9 > 0 ? r - 9 : 0);
+    if (this.itemCache[r] && this.itemCache[end]) {
+        this.pageStart = r;
+        this.displayItems();
+    } else {
+        this.loadItems((r >= 49 ? r - 49 : 0), r, Pager.prototype.showPageAt.bind(this, r));
+    }
+}
+
+Pager.prototype.showRecord = function(r) {
+    if (this.itemCache[r]) {
+        $('older_link').hide();
+        $('newer_link').hide();
+        items.update(this.itemCache[r].html);
+    } else {
+        this.loadItems(r, r, Pager.prototype.showRecord.bind(this, r));
+    }
 }
 
 
@@ -179,6 +214,29 @@ Pager.prototype.displayItems = function() {
 function User(username) {
     this.initPager();
     this.username = username;
+    this.baseFrag = username;
+
+    $$('[name=user.subscribelink]').each(Element.hide);
+    $$('[name=user.unsubscribelink]').each(Element.hide);
+
+    if (loginStatus.loggedIn) {
+        new Ajax.Request(baseURL + '/feedinfo/' + username, {
+            method: 'post',
+            parameters: {
+                username: loginStatus.username
+            },
+            onSuccess: function(r) {
+                var json = r.responseText.evalJSON();
+                if (json.subscribed) {
+                    $$('[name=user.subscribelink]').each(Element.hide);
+                    $$('[name=user.unsubscribelink]').each(Element.show);
+                } else {
+                    $$('[name=user.subscribelink]').each(Element.show);
+                    $$('[name=user.unsubscribelink]').each(Element.hide);
+                }
+            }
+        });
+    }
 
     new Ajax.Request(baseURL + '/info/' + username, {
         method: 'get',
@@ -186,9 +244,10 @@ function User(username) {
             var j = r.responseText.evalJSON();
             if (j) {
                 this.itemCount = parseInt(j.record_count);
-                this.displayItems();
+                if (!this.pageStart)
+                    this.showPageAt(this.itemCount - 1);
             }
-        }.bind(this),
+        }.bind(this)
     });
 }
 User.prototype = new Pager();
@@ -198,12 +257,15 @@ User.prototype.show = function() {
     $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
     $('welcome').hide();
     items.show();
-    $('reflink').href = '#ref/' + this.username;
     $('rss').show();
     $('rsslink').href = '/rss/' + this.username;
+    $$('[name=user.reflink]').each(function(e) {
+        e.href = '/#/ref/' + this.username;
+    }.bind(this));
+    $('usercontrols').show();
 }
 
-User.prototype.loadItems = function(from, to) {
+User.prototype.loadItems = function(from, to, continuation) {
     var url;
     if (from != undefined && to != undefined) {
         url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
@@ -219,13 +281,14 @@ User.prototype.loadItems = function(from, to) {
             if (records && records.length > 0) {
                 records.each(function(v) {
                     v.id = v.record;
+                    v.author = this.username;
                     mangleRecord(v, recordTemplate);
-                });
+                }.bind(this));
                 this.addItems(records);
                 if (!this.pageStart)
                     this.pageStart = records[0].recInt;
             }
-            this.displayItems();
+            continuation();
         }.bind(this),
         onFailure: function(r) {
             this.displayItems();
@@ -239,22 +302,92 @@ User.prototype.loadItems = function(from, to) {
 function mangleRecord(record, template) {
     record.recInt = parseInt(record.record);
 
-    // Sanitize HTML input
-    record.data = record.data.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt');
+    var lines = record.data.split(/\r?\n/);
+    if (lines[lines.length - 1] == '')
+        lines.pop();
+
+    var out = ['<p>'];
+    var endpush = null;
+    var listMode = false;
+    lines.each(function(l) {
+        if (l == '') {
+            if (out[out.length - 1] == '<br>') {
+                out[out.length - 1] = '<p>';
+            }
+            if (out[out.length - 1] == '</li>') {
+                out.push('</ul>');
+                out.push('<p>');
+                listMode = false;
+            }
+            return;
+        }
+
+        // Put quoted material into a special paragraph
+        if (l[0] == '>') {
+            var pi = out.lastIndexOf('<p>');
+            if (pi != -1) {
+                out[pi] = '<p class="quote">';
+                l = l.replace(/^>\s*/, '');
+            }
+        }
+
+        // Sanitize HTML input
+        l = l.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
 
-    // Turn HTTP URLs into links
-    record.data = record.data.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/(\S*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
+        // Turn HTTP URLs into links
+        l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
 
-    // Turn markdown links into links
-    record.data = record.data.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)]*?)?)\)/, '$1<a href="$3">$2</a>');
+        // Turn markdown links into links
+        l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
 
-    // Turn refs and tags into links
-    record.data = record.data.replace(/(\s|^)#(\w+)/g, '$1<a href="#tag/$2">#$2</a>');
-    record.data = record.data.replace(/(\s|^)@(\w+)/g, '$1<a href="#$2">@$2</a>');
+        // Turn *foo* into italics and **foo** into bold
+        l = l.replace(/([^\w\\]|^)\*\*(\w[^*]*)\*\*(\W|$)/g, '$1<b>$2</b>$3');
+        l = l.replace(/([^\w\\]|^)\*(\w[^*]*)\*(\W|$)/g, '$1<i>$2</i>$3');
 
-    // Turn newlines into linebreaks and paragraphs
-    record.data = record.data.replace(/\r?\n\r?\n/g, "<p>").replace(/\r?\n/g, "<br>");
+        // Remove backslashes from escaped metachars
+        l = l.replace(/\\([*\[\]])/g, '$1');
 
+        // Turn refs and tags into links
+        l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
+        l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
+
+        // Create lists when lines begin with *
+        if (l[0] == '*') {
+            if (!listMode) {
+                var pi = out.lastIndexOf('<p>');
+                out[pi] = '<ul>';
+                listMode = true;
+            }
+            l = l.replace(/^\*\s*/, '');
+            out.push('<li>');
+            endpush = '</li>';
+        }
+
+        // Create headers when lines begin with = or #
+        if (l[0] == '=' || l[0] == '#') {
+            var m = l.match(/^([=#]+)/);
+            var depth = m[1].length;
+            if (depth <= 5) {
+                l = l.replace(/^[=#]+\s*/, '').replace(/\s*[=#]+$/, '');
+                out.push('<h' + depth + '>');
+                endpush = '</h' + depth + '>';
+            }
+        }
+
+        out.push(l);
+        if (endpush) {
+            out.push(endpush);
+            endpush = null;
+        } else {
+            out.push('<br>');
+        }
+    });
+    while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
+        out.pop();
+    if (listMode)
+        out.push('</ul>');
+
+    record.data = out.join('');
     record.date = (new Date(record.timestamp * 1000)).toString();
     record.html = template.evaluate(record);
 }
@@ -275,9 +408,11 @@ function Tag(type, tag) {
     case 'tag':
         //url += '%23';
         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
+        this.baseFrag = '/tag/' + tag;
         break;
     case 'ref':
         url += '%40';
+        this.baseFrag = '/ref/' + tag;
         break;
     default:
         alert('Invalid tag type: ' + type);
@@ -297,6 +432,7 @@ function Tag(type, tag) {
                 });
                 this.addItems(j);
                 this.pageStart = j.length - 1;
+                this.itemCount = j.length;
             }
             this.displayItems();
         }.bind(this),
@@ -321,8 +457,57 @@ Tag.prototype.show = function() {
     $('newer_link').hide();
     $('rss').hide();
     items.show();
+    $('usercontrols').hide();
+}
+
+
+// Pager for browsing subscription feeds
+function Feed() {
+    this.initPager();
+    this.username = loginStatus.username;
+    this.baseFrag = '/feed';
+
+    new Ajax.Request(baseURL + '/feed', {
+        method: 'post',
+        parameters: {
+            username: loginStatus.username
+        },
+        onSuccess: function(r) {
+            var response = r.responseText.evalJSON();
+            if (response) {
+                var maxid = response.length - 1;
+                response.each(function(v, i) {
+                    v.id = maxid - i;
+                    mangleRecord(v, tagRecordTemplate)
+                });
+                this.addItems(response);
+                this.pageStart = response.length - 1;
+                this.itemCount = response.length;
+            }
+            this.displayItems();
+        }.bind(this),
+        onFailure: function(r) {
+            this.displayItems();
+        }.bind(this)
+    });
+}
+Feed.prototype = new Pager();
+Feed.prototype.constructor = Feed;
+
+Feed.prototype.show = function() {
+    $$('[name=section]').each(function(v) {
+        v.update(' ' + loginStatus.username + "'s spycam");
+    }.bind(this));
+    $('welcome').hide();
+    $('post').hide();
+    $('older_link').hide();
+    $('newer_link').hide();
+    $('rss').hide();
+    items.show();
+    $('usercontrols').hide();
 }
 
+
 function postPopup() {
     if (loginStatus.loggedIn) {
         var post = $('post');
@@ -345,12 +530,11 @@ function signup() {
     new Ajax.Request(baseURL + '/create', {
         parameters: {
             username: username,
-            password: password,
+            password: password
         },
         onSuccess: function(r) {
             $('signup').hide();
-            location.hash = username;
-            hashSwitch();
+            qlink(username);
 
             loginStatus.login(username, password);
         },
@@ -365,14 +549,48 @@ function signup_cancel() {
     hashSwitch();
 }
 
-function newer_page() {
-    if (currentPager)
-        currentPager.newerPage();
+function subscribe() {
+    new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
+        method: 'post',
+        parameters: {
+            username: loginStatus.username
+        },
+        onSuccess: function(r) {
+            var response = r.responseText.evalJSON();
+            if (response.status == 'success') {
+                alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
+                $$('[name=user.subscribelink]').each(Element.hide);
+                $$('[name=user.unsubscribelink]').each(Element.show);
+            } else {
+                alert('Failed to subscribe. This is probably for the best');
+            }
+        },
+        onFailure: function(r) {
+            alert('Failed to subscribe. This is probably for the best');
+        }
+    });
 }
 
-function older_page() {
-    if (currentPager)
-        currentPager.olderPage();
+function unsubscribe() {
+    new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
+        method: 'post',
+        parameters: {
+            username: loginStatus.username
+        },
+        onSuccess: function(r) {
+            var response = r.responseText.evalJSON();
+            if (response.status == 'success') {
+                alert("You come to your senses.");
+                $$('[name=user.subscribelink]').each(Element.show);
+                $$('[name=user.unsubscribelink]').each(Element.hide);
+            } else {
+                alert('You are unable to tear yourself away (because something failed on the server)');
+            }
+        },
+        onFailure: function(r) {
+            alert('You are unable to tear yourself away (because something failed on the server)');
+        }
+    });
 }
 
 var resizePostContentTimeout = null;
@@ -394,31 +612,136 @@ function resizePostContent() {
     }, 150);
 }
 
+var tickerTimer = null;
+var tickerHead, tickerTail;
+
+function tickerFader(a, b, p) {
+    var p2 = 1 - p;
+
+    a.style.opacity = p;
+    a.style.lineHeight = (100 * p) + '%';
+
+    b.style.opacity = p2;
+    b.style.lineHeight = (100 * p2) + '%';
+    if (p == 1.0)
+        b.hide();
+}
+
+function ticker() {
+    tickerHead.show();
+    Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
+    tickerHead = tickerHead.nextSibling;
+    tickerTail = tickerTail.nextSibling;
+    if (tickerHead == null) {
+        stopTicker();
+        loadLatest.delay(10);
+    }
+}
+
+function startTicker() {
+    stopTicker();
+    for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
+        elem.hide();
+    }
+
+    // Show the first five
+    tickerHead = $('latest-posts').firstChild;
+    for (var i = 0; i < 10 && tickerHead; i++) {
+        tickerHead.show();
+        tickerHead = tickerHead.nextSibling;
+    }
+    tickerTail = $('latest-posts').firstChild;
+    tickerTimer = setInterval(ticker, 5000);
+}
+
+function stopTicker() {
+    if (tickerTimer)
+        clearInterval(tickerTimer);
+    tickerTimer = null;
+}
+
+function loadLatest() {
+    new Ajax.Request(baseURL + '/latest.json', {
+        onSuccess: function(r) {
+            var j = r.responseText.evalJSON();
+
+            $('latest-tags').update();
+            j.tags.each(function(v) {
+                var a = new Element('a', {href: '/#/tag/' + v});
+                a.insert('#' + v);
+                a.onclick = "return qlink()";
+                a.className = 'ref';
+                $('latest-tags').insert(a);
+                $('latest-tags').appendChild(document.createTextNode(' '));
+            });
+
+            $('latest-posts').update();
+            j.records.each(function(v) {
+                v.data = v.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+                v.date = (new Date(v.timestamp * 1000)).toString();
+                var html = latestRecordsTemplate.evaluate(v);
+                $('latest-posts').insert(html);
+            });
+            startTicker();
+        }
+    });
+}
+
+function qlink(loc) {
+    if (loc) {
+        location.hash = loc;
+    } else if (event && event.target) {
+        location.href = event.target.href;
+    } else {
+        // Bogus qlink
+        return;
+    }
+    hashSwitch();
+    return false;
+}
+
 function hashSwitch() {
-    var m = location.hash.match(/^#((ref|tag)\/)?(\w+)(:(\d+))?/);
-    if (m) {
-        if (m[1]) {
-            currentPager = new Tag(m[2], m[3]);
+    var m;
+    stopTicker();
+    if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
+        $('post').show();
+        $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
+    } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)(?:\/p(\d+))?$/)) {
+        if (!currentPager || !(currentPager instanceof Tag) || currentPager.type != m[1] || currentPager.tag != m[2])
+            currentPager = new Tag(m[1], m[2]);
+        currentPager.show();
+
+        if (m[3]) {
+            var r = parseInt(m[3]);
+            currentPager.showPageAt(r);
+        }
+    } else if (m = location.hash.match(/^#\/feed(?:\/p(\d+))?$/)) {
+        if (loginStatus.loggedIn) {
+            if (!currentPager || !(currentPager instanceof Feed) || currentPager.username != loginStatus.username)
+                currentPager = new Feed();
             currentPager.show();
+            if (m[3]) {
+                var r = parseInt(m[3]);
+                currentPager.showPageAt(r);
+            }
         } else {
-            if (!currentPager || currentPager.username != m[3])
-                currentPager = new User(m[3]);
-            currentPager.show();
-            loginStatus.update();
-
-            if (m[5]) {
-                var r = parseInt(m[5]);
-                currentPager.showRecord = r;
-                if (currentPager.recordCache[r]) {
-                    currentPager.displayItems();
-                } else {
-                    currentPager.loadItems((r >= 49 ? r - 49 : 0), r);
-                }
+            location.href = baseURL;
+        }
+    } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
+        if (!currentPager || !(currentPager instanceof User) || currentPager.username != m[1])
+            currentPager = new User(m[1]);
+        currentPager.show();
+        loginStatus.update();
+
+        if (m[3]) {
+            var r = parseInt(m[3]);
+            if (m[2] == 'p') {
+                currentPager.showPageAt(r);
             } else {
-                currentPager.pageStart = currentPager.itemCount - 1;
-                currentPager.loadItems();
+                currentPager.showRecord(r);
             }
         }
+        // Do nothing otherwise, the User constructor takes care of it
     } else {
         $$('[name=section]').each(function(v) { v.update('Welcome') });
         $('signup').hide();
@@ -428,6 +751,8 @@ function hashSwitch() {
         $('older_link').hide();
         $('welcome').show();
         $('rss').hide();
+        $('usercontrols').hide();
+        loadLatest();
     }
 }
 
@@ -449,9 +774,12 @@ function init() {
     setInterval(hashCheck, 250);
 
     document.body.observe('keyup', function(event) {
-        if (event.shiftKey && event.keyCode == '32') {
+        if (event.shiftKey && event.keyCode == 32) {
             postPopup();
             event.stop();
         }
     });
+    $('post.content').addEventListener('keyup', function(event) {
+        event.stopPropagation();
+    }, true);
 }