Commit 0ed0f5cb authored by Yuanle Song's avatar Yuanle Song
Browse files

make it work offline, add sw.js

- bugfix: click expand/shrink stack/trail button should not follow href link.
- update UI a little. updated text for times button.
- add flags to enable unit test. disable test by default.
parent 7e5d7fac
Loading
Loading
Loading
Loading
+58 −5
Original line number Diff line number Diff line
@@ -143,7 +143,10 @@
	<div id="stack-content"></div>
      </div>
      <div id="keyboard">
	<p>Keyboard <a title="reset RPN calculator" id="reset" href="#">Reset All</a></p>
	<p>Keyboard
	  <a title="reset RPN calculator" id="reset" href="#">Reset All</a>
	  <a title="refresh page" id="refresh-page" href="#">Refresh Page</a>
	</p>
	<div class="keyboard">
	  <table>
	    <tr>
@@ -156,13 +159,13 @@
	      <td data-bt-name="num7">7</td>
	      <td data-bt-name="num8">8</td>
	      <td data-bt-name="num9">9</td>
	      <td title="delete pending digit or number in stack (q)" data-bt-name="backspace">←</td>
	      <td title="delete pending digit or last number in stack (q)" data-bt-name="backspace">←</td>
	    </tr>
	    <tr>
	      <td data-bt-name="num4">4</td>
	      <td data-bt-name="num5">5</td>
	      <td data-bt-name="num6">6</td>
	      <td title="times" data-bt-name="times">*</td>
	      <td title="times (*)" data-bt-name="times">×</td>
	    </tr>
	    <tr>
	      <td data-bt-name="num1">1</td>
@@ -197,11 +200,24 @@
	<div id="trail-content"></div>
      </div>
    </div>
    <script type="text/javascript" src="vendor/localforage.min.js"></script>
    <script type="text/javascript" src="vendor/jquery.min.js"></script>
    <script type="text/javascript" src="fifo.js"></script>
    <script type="text/javascript" src="fsm.js"></script> <!-- fifo.js is required by fsm.js -->
    <script type="text/javascript">
      (function () {
	  const testing = false;
	  const uiTesting = false;

	  // service worker
	  if ('serviceWorker' in navigator) {
	      navigator.serviceWorker
		  .register('sw.js', {scope: './'})
		  .then(function() {
		      console.log("Service Worker Registered");
		  });
	  }

	  /**
	   * show dumb data for UI testing.
	   */
@@ -555,11 +571,15 @@
	  };

	  // page init
	  if (testing) {
	      runTests();
	  }

	  const rpnCalculator = new fsm.RPNCalculator();

	  // showDumbData(rpnCalculator);
	  if (uiTesting) {
	      showDumbData(rpnCalculator);
	  }
	  // init web UI
	  updateUI(rpnCalculator);

@@ -590,6 +610,37 @@
	      updateUI(rpnCalculator);
	      return false;
	  });
	  $('#refresh-page').click(function (evt) {
	      const urlJoin = function (baseUrl, path) {
		  const lastSlash = baseUrl.lastIndexOf("/");
		  return baseUrl.substring(0, lastSlash + 1) + path;
	      };
	      console.assert(urlJoin("http://localhost:8000/calc.html", "fifo.js") ===
			     "http://localhost:8000/fifo.js");
	      console.assert(urlJoin("http://localhost:8000/", "fifo.js") ===
			     "http://localhost:8000/fifo.js");
	      console.assert(urlJoin("http://localhost:8000/abc/t1.html", "fifo.js") ===
			     "http://localhost:8000/abc/fifo.js");
	      console.assert(urlJoin("https://www.example.com/calc.html", "fifo.js") ===
			     "https://www.example.com/fifo.js");
	      console.assert(urlJoin("https://www.example.com/", "fifo.js") ===
			     "https://www.example.com/fifo.js");

	      // set service worker cache to expire, thus fetching latest page on next refresh.
	      const htmlUrl = window.location.href;
	      const fifoJsUrl = urlJoin(htmlUrl, 'fifo.js');
	      const fsmJsUrl = urlJoin(htmlUrl, 'fsm.js');
	      // clear cache in page load order. the basic dependence should
	      // be cleared first before trigger a page reload.
	      localforage.setItem('timestamp:' + fsmJsUrl, new Date(2016,0,1).toJSON()).then(function (_) {
		  localforage.setItem('timestamp:' + fifoJsUrl, new Date(2016,0,1).toJSON()).then(function (_) {
		      localforage.setItem('timestamp:' + htmlUrl, new Date(2016,0,1).toJSON()).then(function (_) {
			  window.location.href = window.location.href;
		      });
		  });
	      });
	      return false;
	  });
	  $('#expand-stack').click(function (evt) {
	      const oldMaxHeight = $('#stack-content').css("max-height");
	      if (oldMaxHeight === "100px") {
@@ -599,6 +650,7 @@
		  $('#stack-content').css("max-height", "100px");
		  $('#expand-stack').text("Expand Stack");
	      }
	      return false;
	  });
	  $('#expand-trail').click(function (evt) {
	      const oldMaxHeight = $('#trail-content').css("max-height");
@@ -609,6 +661,7 @@
		  $('#trail-content').css("max-height", "300px");
		  $('#expand-trail').text("Shrink Trail");
	      }
	      return false;
	  });
	  $(document).keypress(function (evt) {
	      // map evt.key to RPNCalculator keyName.
+11 −8
Original line number Diff line number Diff line
* COMMENT -*- mode: org -*-
#+Date: 2017-01-26
Time-stamp: <2017-01-27>
Time-stamp: <2017-01-28>
#+STARTUP: content
* notes                                                               :entry:
** 2017-01-27 steps to add new operator button.				:doc:
@@ -79,13 +79,6 @@ add "about" button beside "Reset All".
  version and source code location.
- 

** 2017-01-26 make it work offline, add sw.js
- cache calc.html, fifo.js, fsm.js.
  try update cache when cached page is more than 1d old.
- cache vendor/* indefinitely.
  do not check for update.
  I think I can use version to handle this when I do upgrade vendor assets.

** 2017-01-27 deploy on https://rpn.emacsos.com/
- I considered https://www.emacsos.com/rpn-calculator.html, but I don't want
  to mess up with sw.js scope issue.
@@ -101,6 +94,16 @@ should set a max-width on #number-display.
overflow: auto
doesn't work with <td> in firefox.
* done                                                                :entry:
** 2017-01-26 make it work offline, add sw.js
- cache calc.html, fifo.js, fsm.js.
  try update cache when cached page is more than 1d old.
- cache vendor/* indefinitely.
  do not check for update.
  I think I can use version to handle this when I do upgrade vendor assets.
- implementation notes
  - see previous example in phonebookhs project.
    ~/projects/phone-book/phonebook/static/js/sw.js

** 2017-01-27 bug: ** is not supported in firefox.
use Math.pow() instead.

sw.js

0 → 100644
+177 −0
Original line number Diff line number Diff line
importScripts('vendor/localforage.min.js');

var CACHE = 'calc';

/**
 * get path from URL.
 * drop schema, host, query string.
 */
const getUrlPath = function (url) {
    var path = '/' + url.split('/').slice(3).join('/');
    var paramIndex = path.indexOf('?');
    if (paramIndex !== -1) {
	return path.substring(0, paramIndex);
    }
    return path;
};
const cachePathList = ['/', '/calc.html'];
const cacheFileExtList = ['.js', '.css', '.png', '.jpg', '.gif'];
/**
 * return true if this URL should be cached by service worker.
 */
const shouldCache = function (url) {
    const path = getUrlPath(url);
    if (cachePathList.indexOf(path) !== -1) {
    	return true;
    }
    return cacheFileExtList.some(function (ext, index, ar) {
    	return path.endsWith(ext);
    });
};
/**
 * return true if this URL is a vendor asset.
 */
const isVendorAsset = function (url) {
    const path = getUrlPath(url);
    return path.startsWith('/vendor/');
};
/**
 * return true if this URL is static asset. see cacheFileExtList.
 * files ending in those ext are considered to be static asset.
 */
const isStaticAsset = function (url) {
    const path = getUrlPath(url);
    if (path.endsWith('/sw.js')) {
	return false;    // do not cache service worker js file.
    }
    return cacheFileExtList.some(function (ext, index, ar) {
	return path.endsWith(ext);
    });
};

/**
 * cache timestamp key used in indexeddb.
 * each cached url can have a cache timestamp with it.
 */
const cacheTimestampKey = function (url) {
    return "timestamp:" + url;
};

// ===============
//  event handler
// ===============

self.addEventListener('fetch', function(event) {
    /**
     * used as fetch(event.request)'s then function.
     * cache the resp in service worker's req/resp cache, then return the resp.
     *
     * if response is not 2xx, do not cache.
     */
    const cacheRespAndReturn = function (resp) {
	const respClone = resp.clone();
	if (! resp.ok) {
	    return resp;
	}
	caches.open(CACHE).then(function (cache) {
	    cache.put(event.request, respClone);
	    console.log("cached " + event.request.url);
	});
	return resp;
    };

    /**
     * use cache if it exists. Otherwise, fetch and cache it.
     */
    const useServiceWorkerCache = function () {
	return event.respondWith(
	    caches.match(event.request).then(function (resp) {
		if (resp) {
		    return resp;
		} else {
		    return fetch(event.request).then(cacheRespAndReturn);
		}
	    })
	);
    };

    /**
     * use cached Response if it's not expired or when network is down.
     * try renew cache if it's expired.
     */
    const useServiceWorkerCacheIfNotExpired = function () {
	// console.log("use service worker cache if not expired");
	const url = event.request.url;
	const tsKey = cacheTimestampKey(url);
	const expireSeconds = 24 * 3600;
	/**
	 * try update service worker req/resp cache and the ts cache.
	 */
	const tryUpdate = function () {
	    return fetch(event.request).then(function (resp) {
		const respClone = resp.clone();
		if (! resp.ok) {
		    console.log("HTTP ERROR: " + resp.status);
		    return resp;    // just return, don't cache.
		}
		caches.open(CACHE).then(function (cache) {
		    cache.put(event.request, respClone);
		    console.log("cached " + event.request.url);
		    const ts = new Date().toJSON();
		    localforage.setItem(tsKey, ts).then(function () {
			console.log("cache ts updated to " + ts + ", url=" + event.request.url);
		    }).catch(function (err) {
			console.log("cache ts update failed: " + err);
		    });
		});
		return resp;
	    }).catch(function (_err) {
		console.log("fetch failed. try use cached resp.");
		return caches.match(event.request);    // nothing to do if
						       // match failed.
	    });
	};
	return event.respondWith(
	    localforage.getItem(tsKey).then(function (tsString) {
		if (tsString !== null) {
		    const now = new Date();
		    const cacheDate = new Date(tsString);
		    const diffSeconds = (now - cacheDate) / 1000;
		    if (diffSeconds > expireSeconds) {
			console.log("cache expired");
			return tryUpdate();
		    }
		    console.log("cache is valid according to cache ts, url=",
				event.request.url);
		    return caches.match(event.request).then(function (resp) {
			if (resp) {
			    return resp;
			}
			return fetch(event.request);
		    });
		} else {
		    console.log("no ts cache");
		    return tryUpdate();
		}
	    }).catch(function (_err) {
		console.log("no ts cache");
		return tryUpdate();
	    })
	);
    };

    var url = event.request.url;

    if (! shouldCache(url)) {
	console.log("not caching " + url);
	return fetch(event.request).catch(function (err) {
	    console.log(err);
	});
    }
    // console.log("will use sw cache on " + url);
    if (isVendorAsset(url)) {
	return useServiceWorkerCache();
    } else {
	return useServiceWorkerCacheIfNotExpired();
    }
});
+7 −0

File added.

Preview size limit exceeded, changes collapsed.