Team object now carries a copy of its initial state.
[mkws-moved-to-github.git] / src / mkws-team.js
index d209e43..bae55cf 100644 (file)
@@ -1,3 +1,4 @@
+"use strict";
 // Factory function for team objects. As much as possible, this uses
 // only member variables (prefixed "m_") and inner functions with
 // private scope.
@@ -8,47 +9,86 @@
 // limitCategory(), delimitTarget(), delimitQuery(), showPage(),
 // pagerPrev(), pagerNext().
 //
-function team($, teamName) {
+// Before the team can be used for searching and related operations,
+// its pz2 object must be created by calling team.makePz2().
+//
+mkws.makeTeam = function($, teamName) {
   var that = {};
+
+  // Member variables are separated into two categories
+
+  // 1. Persistent state (to be coded in URL fragment)
+  var m_state = {
+    query: null,                // initially undefined
+    sort: null,                 // will be set below
+    size: null,                 // will be set below
+    page: 1,
+    recid: '',
+    filters: filterSet(that)
+  }
+
+  // 2. Internal state (not to be coded)
   var m_teamName = teamName;
+  var m_paz; // will be initialised below
   var m_submitted = false;
-  var m_query; // initially undefined
-  var m_sortOrder; // will be set below
-  var m_perpage; // will be set below
-  var m_filterSet = filterSet(that);
   var m_totalRecordCount = 0;
-  var m_currentPage = 1;
-  var m_currentRecordId = '';
   var m_currentRecordData = null;
   var m_logTime = {
     // Timestamps for logging
     "start": $.now(),
     "last": $.now()
   };
-  var m_paz; // will be initialised below
   var m_templateText = {}; // widgets can register templates to be compiled
   var m_template = {}; // compiled templates, from any source
-  var m_config = mkws.objectInheritingFrom(mkws.config);
   var m_widgets = {}; // Maps widget-type to array of widget objects
   var m_gotRecords = false;
+  
+  var config = mkws.objectInheritingFrom(mkws.config);
+  that.config = config;
 
   that.toString = function() { return '[Team ' + teamName + ']'; };
 
   // Accessor methods for individual widgets: readers
   that.name = function() { return m_teamName; };
   that.submitted = function() { return m_submitted; };
-  that.sortOrder = function() { return m_sortOrder; };
-  that.perpage = function() { return m_perpage; };
+  that.sortOrder = function() { return m_state.sort; };
+  that.perpage = function() { return m_state.size; };
+  that.query = function() { return m_state.query; };
   that.totalRecordCount = function() { return m_totalRecordCount; };
-  that.currentPage = function() { return m_currentPage; };
-  that.currentRecordId = function() { return m_currentRecordId; };
+  that.currentPage = function() { return m_state.page; };
+  that.currentRecordId = function() { return m_state.recid; };
   that.currentRecordData = function() { return m_currentRecordData; };
-  that.filters = function() { return m_filterSet; };
-  that.config = function() { return m_config; };
+  that.filters = function() { return m_state.filters; };
+  that.gotRecords = function() { return m_gotRecords; };
 
   // Accessor methods for individual widgets: writers
-  that.set_sortOrder = function(val) { m_sortOrder = val };
-  that.set_perpage = function(val) { m_perpage = val };
+  that.set_sortOrder = function(val) { m_state.sort = val };
+  that.set_perpage = function(val) { m_state.size = val };
+
+  m_state.sort = config.sort_default;
+  m_state.size = config.perpage_default;
+  var m_default = $.extend(true, {}, m_state);
+
+  that.urlFragment = function () {
+    var s;
+
+    for (var key in m_state) {
+      if (m_state.hasOwnProperty(key) &&
+          m_state[key] != m_default[key]) {
+        if (!s) {
+          var s = 'mkws';
+          if (m_teamName !== 'AUTO') s += m_teamName;
+          s += '=';
+        } else {
+          s += "@";
+        }
+
+        s += key + '=' + m_state[key];
+      }
+    }
+
+    return s;
+  }
 
 
   // The following PubSub code is modified from the jQuery manual:
@@ -58,63 +98,48 @@ function team($, teamName) {
   //    team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
   //    team.queue("eventName").publish(arg1, arg2, ...);
   //
-  var queues = {};
+  var m_queues = {};
   function queue(id) {
-    if (!queues[id]) {
+    if (!m_queues[id]) {
       var callbacks = $.Callbacks();
-      queues[id] = {
+      m_queues[id] = {
         publish: callbacks.fire,
         subscribe: callbacks.add,
         unsubscribe: callbacks.remove
       };
     }
-    return queues[id];
+    return m_queues[id];
   };
   that.queue = queue;
 
 
-  function log(s) {
+  function _log(fn, s) {
     var now = $.now();
     var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
                      ((now - m_logTime.last)/1000).toFixed(3) + ") ");
     m_logTime.last = now;
-    mkws.log(m_teamName + ": " + timestamp + s);
+    fn.call(mkws.log, m_teamName + ": " + timestamp + s);
     that.queue("log").publish(m_teamName, timestamp, s);
   }
-  that.log = log;
-
 
-  log("making new widget team");
+  that.trace = function(x) { _log(mkws.trace, x) };
+  that.debug = function(x) { _log(mkws.debug, x) };
+  that.info = function(x) { _log(mkws.info, x) };
+  that.warn = function(x) { _log(mkws.warn, x) };
+  that.error = function(x) { _log(mkws.error, x) };
+  that.fatal = function(x) { _log(mkws.fatal, x) };
 
-  m_sortOrder = m_config.sort_default;
-  m_perpage = m_config.perpage_default;
-
-  // create a parameters array and pass it to the pz2's constructor
-  // then register the form submit event with the pz2.search function
-  // autoInit is set to true on default
-  m_paz = new pz2({ "windowid": teamName,
-                    "pazpar2path": m_config.pazpar2_url,
-                    "usesessions" : m_config.use_service_proxy ? false : true,
-                    "oninit": onInit,
-                    "onbytarget": onBytarget,
-                    "onstat": onStat,
-                    "onterm": (m_config.facets.length ? onTerm : undefined),
-                    "onshow": onShow,
-                    "onrecord": onRecord,
-                    "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
-                    "termlist": m_config.facets.join(',')
-                  });
-  log("created main pz2 object");
+  that.info("making new widget team");
 
   // pz2.js event handlers:
   function onInit() {
-    log("init");
+    that.info("init");
     m_paz.stat();
     m_paz.bytarget();
   }
 
   function onBytarget(data) {
-    log("bytarget");
+    that.info("bytarget");
     queue("targets").publish(data);
   }
 
@@ -126,28 +151,29 @@ function team($, teamName) {
       queue("firstrecords").publish(hitcount);
     }
     if (parseInt(data.activeclients[0], 10) === 0) {
-      log("complete");
+      that.info("complete");
       queue("complete").publish(hitcount);
     }
   }
 
   function onTerm(data) {
-    log("term");
-    queue("termlists").publish(data);
+    that.info("term");
+    queue("facets").publish(data);
   }
 
   function onShow(data, teamName) {
-    log("show");
+    that.info("show");
     m_totalRecordCount = data.merged;
-    log("found " + m_totalRecordCount + " records");
+    that.info("found " + m_totalRecordCount + " records");
     queue("pager").publish(data);
     queue("records").publish(data);
   }
 
   function onRecord(data, args, teamName) {
-    log("record");
+    that.info("record");
     // FIXME: record is async!!
     clearTimeout(m_paz.recordTimer);
+    queue("record").publish(data);
     var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
     if (detRecordDiv.length) {
       // in case on_show was faster to redraw element
@@ -160,94 +186,135 @@ function team($, teamName) {
   }
 
 
+  // create a parameters array and pass it to the pz2's constructor
+  // then register the form submit event with the pz2.search function
+  // autoInit is set to true on default
+  that.makePz2 = function() {
+    that.debug("m_queues=" + $.toJSON(m_queues));
+    var params = {
+      "windowid": teamName,
+      "pazpar2path": mkws.pazpar2_url(),
+      "usesessions" : config.use_service_proxy ? false : true,
+      "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
+      "termlist": config.facets.join(',')
+    };
+
+    params.oninit = onInit;
+    if (m_queues.targets) {
+      params.onbytarget = onBytarget;
+      that.info("setting bytarget callback");
+    }
+    if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
+      params.onstat = onStat;
+      that.info("setting stat callback");
+    }
+    if (m_queues.facets && config.facets.length) {
+      params.onterm = onTerm;
+      that.info("setting term callback");
+    }
+    if (m_queues.records) {
+      that.info("setting show callback");
+      params.onshow = onShow;
+      // Record callback is subscribed from records callback
+      that.info("setting record callback");
+      params.onrecord = onRecord;
+    }
+
+    m_paz = new pz2(params);
+    that.info("created main pz2 object");
+  }
+
+
   // Used by the Records widget and onRecord()
   function recordElementId(s) {
-    return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
+    return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
   }
   that.recordElementId = recordElementId;
 
   // Used by onRecord(), showDetails() and renderDetails()
   function recordDetailsId(s) {
-    return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
+    return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
   }
 
 
   that.targetFiltered = function(id) {
-    return m_filterSet.targetFiltered(id);
+    return m_state.filters.targetFiltered(id);
   };
 
 
   that.limitTarget = function(id, name) {
-    log("limitTarget(id=" + id + ", name=" + name + ")");
-    m_filterSet.add(targetFilter(id, name));
-    if (m_query) triggerSearch();
+    that.info("limitTarget(id=" + id + ", name=" + name + ")");
+    m_state.filters.add(targetFilter(id, name));
+    if (m_state.query) triggerSearch();
     return false;
   };
 
 
   that.limitQuery = function(field, value) {
-    log("limitQuery(field=" + field + ", value=" + value + ")");
-    m_filterSet.add(fieldFilter(field, value));
-    if (m_query) triggerSearch();
+    that.info("limitQuery(field=" + field + ", value=" + value + ")");
+    m_state.filters.add(fieldFilter(field, value));
+    if (m_state.query) triggerSearch();
     return false;
   };
 
 
   that.limitCategory = function(id) {
-    log("limitCategory(id=" + id + ")");
+    that.info("limitCategory(id=" + id + ")");
     // Only one category filter at a time
-    m_filterSet.removeMatching(function(f) { return f.type === 'category' });
-    if (id !== '') m_filterSet.add(categoryFilter(id));
-    if (m_query) triggerSearch();
+    m_state.filters.removeMatching(function(f) { return f.type === 'category' });
+    if (id !== '') m_state.filters.add(categoryFilter(id));
+    if (m_state.query) triggerSearch();
     return false;
   };
 
 
   that.delimitTarget = function(id) {
-    log("delimitTarget(id=" + id + ")");
-    m_filterSet.removeMatching(function(f) { return f.type === 'target' });
-    if (m_query) triggerSearch();
+    that.info("delimitTarget(id=" + id + ")");
+    m_state.filters.removeMatching(function(f) { return f.type === 'target' });
+    if (m_state.query) triggerSearch();
     return false;
   };
 
 
   that.delimitQuery = function(field, value) {
-    log("delimitQuery(field=" + field + ", value=" + value + ")");
-    m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
+    that.info("delimitQuery(field=" + field + ", value=" + value + ")");
+    m_state.filters.removeMatching(function(f) { return f.type == 'field' &&
                                              field == f.field && value == f.value });
-    if (m_query) triggerSearch();
+    if (m_state.query) triggerSearch();
     return false;
   };
 
 
   that.showPage = function(pageNum) {
-    m_currentPage = pageNum;
-    m_paz.showPage(m_currentPage - 1);
+    m_state.page = pageNum;
+    m_paz.showPage(m_state.page - 1);
   };
 
 
   that.pagerNext = function() {
-    if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
+    if (m_totalRecordCount - m_state.size * m_state.page > 0) {
       m_paz.showNext();
-      m_currentPage++;
+      m_state.page++;
     }
   };
 
 
   that.pagerPrev = function() {
     if (m_paz.showPrev() != false)
-      m_currentPage--;
+      m_state.page--;
   };
 
 
   that.reShow = function() {
     resetPage();
-    m_paz.show(0, m_perpage, m_sortOrder);
+    m_paz.show(0, m_state.size, m_state.sort);
+    // ### not really the right place for this but it will do for now.
+    that.warn("fragment: " + that.urlFragment());
   };
 
 
   function resetPage() {
-    m_currentPage = 1;
+    m_state.page = 1;
     m_totalRecordCount = 0;
     m_gotRecords = false;
   }
@@ -255,14 +322,14 @@ function team($, teamName) {
 
 
   function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
-    log("newSearch: " + query);
+    that.info("newSearch: " + query);
 
-    if (m_config.use_service_proxy && !mkws.authenticated) {
+    if (config.use_service_proxy && !mkws.authenticated) {
       alert("searching before authentication");
       return;
     }
 
-    m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
+    m_state.filters.removeMatching(function(f) { return f.type !== 'category' });
     triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
     switchView('records'); // In case it's configured to start off as hidden
     m_submitted = true;
@@ -272,17 +339,16 @@ function team($, teamName) {
 
   function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
     resetPage();
-    queue("navi").publish();
 
     // Continue to use previous query/sort-order unless new ones are specified
-    if (query) m_query = query;
-    if (sortOrder) m_sortOrder = sortOrder;
-    if (perpage) m_perpage = perpage;
-    if (targets) m_filterSet.add(targetFilter(targets, targets));
-
-    var pp2filter = m_filterSet.pp2filter();
-    var pp2limit = m_filterSet.pp2limit(limit);
-    var pp2catLimit = m_filterSet.pp2catLimit();
+    if (query) m_state.query = query;
+    if (sortOrder) m_state.sort = sortOrder;
+    if (perpage) m_state.size = perpage;
+    if (targets) m_state.filters.add(targetFilter(targets, targets));
+
+    var pp2filter = m_state.filters.pp2filter();
+    var pp2limit = m_state.filters.pp2limit(limit);
+    var pp2catLimit = m_state.filters.pp2catLimit();
     if (pp2catLimit) {
       pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
     }
@@ -292,23 +358,33 @@ function team($, teamName) {
     if (maxrecs) params.maxrecs = maxrecs;
     if (torusquery) {
       if (!mkws.config.use_service_proxy)
-        alert("can't narrow search by torusquery when Service Proxy is not in use");
+        alert("can't narrow search by torusquery when not authenticated");
       params.torusquery = torusquery;
     }
 
-    log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
+    that.info("triggerSearch(" + m_state.query + "): filters = " + m_state.filters.toJSON() + ", " +
         "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
 
-    m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
+    m_paz.search(m_state.query, m_state.size, m_state.sort, pp2filter, undefined, params);
+    queue("searchtriggered").publish();
+
+    // ### not really the right place for this but it will do for now.
+    that.warn("fragment: " + that.urlFragment());
   }
 
+  // fetch record details to be retrieved from the record queue
+  that.fetchDetails = function(recId) {
+    that.info("fetchDetails() requesting record '" + recId + "'");
+    m_paz.record(recId);
+  };
+
 
   // switching view between targets and records
   function switchView(view) {
-    var targets = widgetNode('Targets');
-    var results = widgetNode('Results') || widgetNode('Records');
-    var blanket = widgetNode('Blanket');
-    var motd    = widgetNode('MOTD');
+    var targets = widgetNode('targets');
+    var results = widgetNode('results') || widgetNode('records');
+    var blanket = widgetNode('blanket');
+    var motd    = widgetNode('motd');
 
     switch(view) {
     case 'targets':
@@ -332,20 +408,20 @@ function team($, teamName) {
 
   // detailed record drawing
   that.showDetails = function(recId) {
-    var oldRecordId = m_currentRecordId;
-    m_currentRecordId = recId;
+    var oldRecordId = m_state.recid;
+    m_state.recid = recId;
 
     // remove current detailed view if any
     findnode('#' + recordDetailsId(oldRecordId)).remove();
 
     // if the same clicked, just hide
     if (recId == oldRecordId) {
-      m_currentRecordId = '';
+      m_state.recid = '';
       m_currentRecordData = null;
       return;
     }
     // request the record
-    log("showDetails() requesting record '" + recId + "'");
+    that.info("showDetails() requesting record '" + recId + "'");
     m_paz.record(recId);
   };
 
@@ -355,14 +431,14 @@ function team($, teamName) {
     teamName = teamName || m_teamName;
 
     if (teamName === 'AUTO') {
-      selector = (selector + '.mkwsTeam_' + teamName + ',' +
-                  selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
+      selector = (selector + '.mkws-team-' + teamName + ',' +
+                  selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
     } else {
-      selector = selector + '.mkwsTeam_' + teamName;
+      selector = selector + '.mkws-team-' + teamName;
     }
 
     var node = $(selector);
-    //log('findnode(' + selector + ') found ' + node.length + ' nodes');
+    //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
     return node;
   }
 
@@ -373,37 +449,46 @@ function team($, teamName) {
   }
 
   function renderDetails(data, marker) {
-    var template = loadTemplate("Record");
+    var template = loadTemplate("details");
     var details = template(data);
-    return '<div class="mkwsDetails mkwsTeam_' + m_teamName + '" ' +
+    return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
       'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
   }
   that.renderDetails = renderDetails;
 
 
   that.registerTemplate = function(name, text) {
+    if(mkws._old2new.hasOwnProperty(name)) {
+      that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
+      name = mkws._old2new[name];
+    }
     m_templateText[name] = text;
   };
 
 
-  function loadTemplate(name) {
+  function loadTemplate(name, fallbackString) {
+    if(mkws._old2new.hasOwnProperty(name)) {
+       that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
+       name = mkws._old2new[name];
+    }
+
     var template = m_template[name];
     if (template === undefined && Handlebars.compile) {
       var source;
-      var node = $(".mkwsTemplate_" + name + " .mkwsTeam_" + that.name());
+      var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
       if (node && node.length < 1) {
-        node = $(".mkwsTemplate_" + name);
+        node = $(".mkws-template-" + name);
       }
       if (node) source = node.html();
       if (!source) source = m_templateText[name];
       if (source) {
         template = Handlebars.compile(source);
-        log("compiled template '" + name + "'");
+        that.info("compiled template '" + name + "'");
       }
     }
     //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
     if (template === undefined && Handlebars.templates) {
-      template = Handlebars.templates[name];
+      template = Handlebars.templates["mkws-template-" + name];
     }
     if (template === undefined && mkws.defaultTemplates) {
       template = mkws.defaultTemplates[name];
@@ -413,9 +498,10 @@ function team($, teamName) {
       return template;
     }
     else {
-      alert("Missing MKWS template for " + name);
+      that.info("No MKWS template for " + name);
+      return null;
     }  
-    }
+  }
   that.loadTemplate = loadTemplate;
 
 
@@ -449,8 +535,7 @@ function team($, teamName) {
       }
     }
     return undefined;
-  }
-
+  };
 
   return that;
 };