Google Reader Unread Count at Head

By shintok Last update May 19, 2008 — Installed 1,093 times. Daily Installs: 1, 2, 0, 1, 2, 1, 0, 3, 0, 0, 1, 1, 2, 2, 1, 2, 1, 0, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 1, 1, 0, 2
// ==UserScript==
// @name          Google Reader Unread Count at Head
// @namespace     http://shinto.dyndns.org/greasemonkey
// @description   Brings the unread count to the head of feed title
// @include       https://www.google.com/reader/*
// @include       http://www.google.com/reader/*
// ==/UserScript==

(function() {

  var timerID = null;
  var isThrottling = false;
  var wantUpdate = false;

  function countAtHead() {
    GM_log("countAtHead called");

    if(isThrottling){
      wantUpdate = true;
      return;
    }
    isThrottling=true;
    GM_log("not throttled");

    modifySubTree();

    throttleTimer = setInterval(releaseThrottling, 3000);
  }

  function modifySubTree() {
    var nameText = document.evaluate(
      '//span[starts-with(@class,"name-text")][starts-with(../*[1]/@class,"name-text")]',
      document,
      null,
      XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
      null);

    if ( nameText.snapshotLength > 0 ) {
      GM_log("swapping count location");
      for (var i = 0; i < nameText.snapshotLength; i++) {
        var p = nameText.snapshotItem(i).parentNode;
        var x = p.removeChild(p.firstChild);
        p.appendChild(x);
      }
    }
  }


  function releaseThrottling() {
    clearInterval(throttleTimer);
    isThrottling = false;
    GM_log("throttling released");

    if(wantUpdate){
      GM_log("update wanted while throttling");
      wantUpdate=false;
      countAtHead();
    }
  }


  function initialRun() {
    GM_log("init");
    clearInterval(timerID);
    countAtHead();
    GM_log("clear timer");

    document.getElementById("sub-tree")
      .addEventListener('DOMNodeInserted', countAtHead, false);
    GM_log("event listener added");
  }


  timerID = setInterval(initialRun, 3000);


}) ();