(function($, block) { // Entity formatters for use by tweet list var entity_formatters = { 'urls': function(e) { return '' + e.display_url + ''; }, 'user_mentions': function(e) { return '@'+e.screen_name+''; }, 'hashtags': function(e) { return '#' +e.text+''; }, 'default': function(e) { return '{ENTITY}'; } }; // processes entities for the given message and entity object var process_entities = function(message, entities) { // short-circuit failure mode if(typeof entities === 'undefined') { return message; } // build list of entities sorted on starting index var es = []; $.each(entities, function(t, ts) { $.each(ts, function(_, e) { e['type'] = t; es.push(e); }); }); es.sort(function(a,b) { return a['indices'][0] - b['indices'][0]; }); // process entities one-by-one in order of appearance var marker = 0; var result = ""; for(var i in es) { var e = es[i]; var start = e['indices'][0]; var stop = e['indices'][1]; //copy string content result += message.substring(marker, start); //process entity (through formatter or no-op function) var formatter = entity_formatters[e.type] || function(e) { return message.substring(start,stop) }; result += formatter(e); // update marker location marker = stop; } // append tail of message result += message.substring(marker, message.length); return result; } block.fn.tweets = function(config) { var options = $.extend({ memory: 20 }, config); // create the necessary HTML in the block container this.$element.append('
    '); // store list for later var $list = this.$element.find('ol'); // register default handler for handling tweet data this.actions(function(e, tweet){ tweets = window.sessionStorage.getItem('tweets'); tweets = JSON.parse(tweets); tweets.push(tweet); var localMemory = 100; if(tweets.length >= localMemory) { tweets.shift(); } window.sessionStorage.setItem('tweets', JSON.stringify(tweets)); var $item = $('
  1. '); var $tweet = $('
    '); var $content = $('
    '); var $header = $('
    '); // Build a tag image and header: var $account = $(''); $account.attr("href", "http://twitter.com/" + tweet.user.screen_name); var $avatar = $("").addClass("avatar"); $avatar.attr("src", tweet.user.profile_image_url); $account.append($avatar); $account.append($('' + tweet.user.name + '')); $account.append($(' ')); $account.append($('@' + tweet.user.screen_name + '')); $header.append($account); // Build timestamp: var $time = $(''); $time.append($('' + tweet.created_at + '')); $header.append($time); $content.append($header); // Build contents: var text = process_entities(tweet.text, tweet.entities); var $text = $('

    ' + text + '

    '); $content.append($text); // Build outer structure of containing divs: $tweet.append($content); $item.append($tweet); // place new tweet in front of list $list.prepend($item); // remove stale tweets if ($list.children().length > options.memory) { $list.children().last().remove(); } }); return this.$element; }; })(jQuery, block);