Merge branch 'master' of ssh://git.indexdata.com/home/git/private/mkjsf.git into...
[mkjsf-moved-to-github.git] / src / META-INF / resources / pz2utils / listeners.js
diff --git a/src/META-INF/resources/pz2utils/listeners.js b/src/META-INF/resources/pz2utils/listeners.js
new file mode 100644 (file)
index 0000000..3bbfa2b
--- /dev/null
@@ -0,0 +1,229 @@
+var renderTargetsReqVar;\r
+var renderOnRecordTargetsReqVar;\r
+\r
+// Renders UI elements listed in 'renderWhileActiveclients', optionally doing\r
+// another update round-trip to Pazpar2 when done.\r
+function renderTargets(doRefresh) {\r
+  // console.log('rendering ' + renderWhileActiveclients);\r
+  var sourcecomp = document.getElementById("pz2watch:activeclientsField");\r
+  jsf.ajax.request(sourcecomp, null, {\r
+    render : renderWhileActiveclients\r
+  });\r
+  if (doRefresh) {\r
+    // console.log('Will do another ajax request after a timeout in order to\r
+    // render: pz2watch:activeclientsField');\r
+    renderTargetsReqVar = setTimeout(function() {\r
+      // console.log('Making request for pz2watch:activeclientsField');\r
+      jsf.ajax.request(sourcecomp, null, {\r
+        render : "pz2watch:activeclientsField"\r
+      });\r
+    }, 500);\r
+  } else {\r
+    // console.log("No further updates from server requested");\r
+  }\r
+}\r
+\r
+// Renders UI elements listed in 'renderWhileActiveclientsRecord', optionally\r
+// doing\r
+// another record request when done.\r
+function renderOnRecordTargets(doRefresh) {\r
+  // console.log('rendering ' + renderWhileActiveclientsRecord);\r
+  var sourcecomp = document.getElementById("pz2watch:activeclientsFieldRecord");\r
+  jsf.ajax.request(sourcecomp, null, {\r
+    render : renderWhileActiveclientsRecord\r
+  });\r
+  if (doRefresh) {\r
+    // console.log('Will do another ajax request after a timeout in order to\r
+    // render: pz2watch:activeclientsFieldRecord');\r
+    renderOnRecordTargetsReqVar = setTimeout(function() {\r
+      // console.log('Making request for pz2watch:activeclientsFieldRecord');\r
+      jsf.ajax.request(sourcecomp, null, {\r
+        render : "pz2watch:activeclientsFieldRecord"\r
+      });\r
+    }, 1000);\r
+  } else {\r
+    // console.log("No further updates from server requested");\r
+  }\r
+}\r
+\r
+// Listens for browser initiated changes to 'window.location.hash' and sends \r
+// the hash key changes to the back-end, to have the back-end pull up a previous \r
+// Pazpar2 state.\r
+// \r
+// See also: The field in pz2watch.xhtml, the StateListener function below,\r
+// the method Pz2Bean.handleQueryStateChanges(), and the classes \r
+// Pazpar2State and StateManager for a complete picture of browser history \r
+// handling.\r
+function windowlocationhashListener() {\r
+  if (trackHistory) {\r
+    \r
+    var stateKey = document.getElementById("pz2watch:windowlocationhash");\r
+    // console.log("browser hash update response detected.");\r
+    // console.log("pz2watch:windowlocationhash: [" + stateKey.value + "]");\r
+    // console.log("window.location.hash: [" + window.location.hash + "]");\r
+    if (window.location.hash != stateKey.value) {  \r
+      if (window.location.hash) {\r
+        //console.log("updating pz2watch:windowlocationhash with new window.location.hash [" + window.location.hash + "]");\r
+        stateKey.value = window.location.hash;\r
+        //console.log("firing pz2watch:windowlocationhash onChange");\r
+        stateKey.onchange();\r
+      } else if (stateKey.value) {\r
+        //console.log("updating window.location.hash with pz2watch:windowlocationhash  [" + stateKey.value + "]");\r
+        window.location.hash = stateKey.value;\r
+        //console.log("firing pz2watch:windowlocationhash onChange");\r
+        stateKey.onchange();\r
+      } \r
+    } else {\r
+      //console.log("State hash already has the value of the new browser hash - not updating state hash");\r
+    }\r
+  }\r
+}\r
+\r
+// Listens for ViewExpiredException message. Reloads the current page, stripped\r
+// of\r
+// it's jsessionid and hash content\r
+function viewExpirationListener(data) {\r
+  if (data.status === "success" && data.responseXML) {\r
+    var errorElements = data.responseXML.getElementsByTagName("error-name");\r
+    if (errorElements.length > 0) {\r
+      var errorname = errorElements.item(0).textContent\r
+          || errorElements.item(0).text;\r
+      if (errorname === "class javax.faces.application.ViewExpiredException") {\r
+        var newloc = window.location.protocol + "//" + window.location.host\r
+            + window.location.pathname.replace(/;jsessionid.*/, '');\r
+        alert('Sorry, this session has expired. A new one will be loaded.');\r
+        window.location.replace(newloc);\r
+      }\r
+    }\r
+  }\r
+\r
+}\r
+\r
+function errorListener(data) {\r
+  // alert(data.toSource());\r
+  if (data.source.name === "pz2watch:activeclientsField") {\r
+    alert("This occurred when polling: ["\r
+        + data.description\r
+        + "]. The page could be in an inconsistent state after this. We apologize for the inconvenience.");\r
+  } else {\r
+    var pattern = /viewId.*could not be restored./;\r
+    if (pattern.test(data.description)) {\r
+      // ignore - caught by view expiration listener\r
+    } else {\r
+      alert("An error ["\r
+          + data.errorName + ": " +data.description\r
+          + "] was triggered by ["\r
+          + data.source.name\r
+          + "]. The page could be in an inconsistent state after this. We apologize for the inconvenience.");\r
+    }\r
+  }\r
+}\r
+\r
+// Composite listener, invoking all field update listeners\r
+function fieldUpdateListener(data) {\r
+  if (data.status === "success") {\r
+    var updates = data.responseXML.getElementsByTagName("update");\r
+    for ( var i = 0, max = updates.length; i < max; i++) {\r
+      var lsnri = fieldListeners.getListener(updates[i].getAttribute("id"));\r
+      if (lsnri) {\r
+        lsnri.invoke(updates[i]);\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+var Pz2listeners = function() {\r
+  var lsnrs = {};\r
+  this.addListener = function(key, lsnr) {\r
+    lsnrs[key] = lsnr;\r
+  };\r
+  this.getListener = function(key) {\r
+    return lsnrs[key];\r
+  };\r
+};\r
+\r
+var fieldListeners = new Pz2listeners();\r
+\r
+// Listens for back-end initiated changes to the state key and updates\r
+// window.location.hash with changes, to record them in browsing history\r
+var StateListener = function() {\r
+  this.invoke = function(field) {\r
+    var stateKeyDoc = StringtoXML(field.textContent || field.text);\r
+    var stateKeyValue = stateKeyDoc.childNodes[0].getAttribute("value");\r
+    // console.log('Received state key update from the back-end: ' + stateKeyValue);\r
+    if (stateKeyValue !== window.location.hash) {\r
+      window.location.hash = stateKeyValue;\r
+      // console.log("Browsers hash (window.location.hash) updated with [" + stateKeyValue + "]");\r
+    } else {\r
+      // console.log("Browsers hash (window.location.hash) already has the value [" + stateKeyValue + "]");\r
+    }\r
+  };\r
+};\r
+\r
+// Listens for updates to general 'activeclients' field, then invokes\r
+// renderTargets\r
+var ActiveclientsListener = function() {\r
+  this.invoke = function(field) {\r
+    var updateDoc = StringtoXML(field.textContent || field.text);\r
+    var activeClientsValue = (updateDoc.childNodes[0].textContent || updateDoc.childNodes[0].text);\r
+    // console.log('Activeclients response detected: ' + activeClientsValue);\r
+    clearTimeout(renderTargetsReqVar);\r
+    if (activeClientsValue > '0') {\r
+      renderTargets(true);\r
+    } else {\r
+      renderTargets(false);\r
+    }\r
+  };\r
+};\r
+\r
+// Listens for updates to record 'activeclients' field, then invokes\r
+// renderOnRecordTargets\r
+var ActiveclientsRecordListener = function() {\r
+  this.invoke = function(field) {\r
+    var updateDoc = StringtoXML(field.textContent || field.text);\r
+    var activeClientsRecordValue = (updateDoc.childNodes[0].textContent || updateDoc.childNodes[0].text);\r
+    // console.log('Activeclients response for record detected: ' + activeClientsRecordValue);\r
+    clearTimeout(renderOnRecordTargetsReqVar);\r
+    if (activeClientsRecordValue > '0') {\r
+      renderOnRecordTargets(true);\r
+    } else {\r
+      // console.log('Active clients is 0, final rendering');\r
+      renderOnRecordTargets(false);\r
+    }\r
+  };\r
+};\r
+\r
+// Inserts field update listeners, state listeners, view expired listener\r
+// into Ajax response handling\r
+jsf.ajax.addOnEvent(fieldUpdateListener);\r
+jsf.ajax.addOnEvent(viewExpirationListener);\r
+jsf.ajax.addOnError(errorListener);\r
+\r
+function StringtoXML(text) {\r
+  var doc;\r
+  if (window.ActiveXObject) {\r
+    doc = new ActiveXObject('Microsoft.XMLDOM');\r
+    doc.async = false;\r
+    doc.loadXML(text);\r
+  } else {\r
+    var parser = new DOMParser();\r
+    doc = parser.parseFromString(text, 'text/xml');\r
+  }\r
+  return doc;\r
+}\r
+\r
+// Sets up field update listeners\r
+var setUpListeners = function() {\r
+  // console.log("Starts tracking activeclientsField, for 'show' and 'record'");\r
+  fieldListeners.addListener("pz2watch:activeclientsField",\r
+      new ActiveclientsListener());\r
+  fieldListeners.addListener("pz2watch:activeclientsFieldRecord",\r
+      new ActiveclientsRecordListener());\r
+  if (trackHistory) {\r
+    // console.log("Starts tracking windowlocationhash field");\r
+    fieldListeners.addListener("pz2watch:windowlocationhash",\r
+        new StateListener());\r
+    // console.log("Setting listener for browser onhashchange");\r
+    window.onload = window.onhashchange = windowlocationhashListener;\r
+  }\r
+};
\ No newline at end of file