workflow.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. var GRID_PUBLIC_ID
  2. ,KNOWN_VERSION = 0
  3. ,GRID
  4. ,SELECTED = []
  5. ,CURRENTINPUT = null;
  6. function doGet(url, callback) {
  7. var xhr = new XMLHttpRequest();
  8. xhr.onreadystatechange = function(e) {
  9. if (xhr.readyState === 4) {
  10. var resp = null;
  11. if (xhr.status === 200) {
  12. resp = xhr.response;
  13. try {
  14. resp = JSON.parse(/** @type {string} */ (resp));
  15. } catch (e) {
  16. resp = null;
  17. }
  18. }
  19. callback(xhr.status, resp);
  20. }
  21. };
  22. xhr.open('GET', url, true);
  23. xhr.send(null);
  24. }
  25. function initPolling() {
  26. doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
  27. if (resp) {
  28. GRID = new Grid(resp);
  29. if (resp["grid"]) {
  30. KNOWN_VERSION = Math.max(GRID.update(resp["grid"]) || 0, KNOWN_VERSION);
  31. uiCreateGrid();
  32. }
  33. } // TODO else cannot init party
  34. });
  35. }
  36. function pollNow() {
  37. // TODO avoid duplicate call / abort planned poll
  38. doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
  39. if (resp && resp["grid"]) {
  40. var newVersion = Math.max(GRID.update(resp["grid"]) || 0, KNOWN_VERSION);
  41. if (newVersion !== KNOWN_VERSION) {
  42. onGridUpdated();
  43. KNOWN_VERSION = newVersion;
  44. }
  45. }
  46. // TODO plan next poll
  47. });
  48. }
  49. function keyPressHandler(cell, key) {
  50. doGet("/api/put?grid=" +GRID_PUBLIC_ID +"&key=" +key +"&x=" +cell.x +"&y=" +cell.y, function(status, resp) {
  51. if (status === 403) {
  52. // TODO wrong
  53. } else if (status === 204) {
  54. // TODO good
  55. pollNow();
  56. }
  57. });
  58. }
  59. function unselect() {
  60. SELECTED.forEach(function (cell) {
  61. cell.dom.classList.remove(R.klass.cell.selected);
  62. });
  63. if (CURRENTINPUT) {
  64. CURRENTINPUT.dom.classList.remove(R.klass.cell.currentInput);
  65. CURRENTINPUT = null;
  66. }
  67. SELECTED = [];
  68. }
  69. function select(x, y) {
  70. var cell = UI_CELLS[x +y *GRID.width];
  71. SELECTED.push(cell);
  72. cell.dom.classList.add(R.klass.cell.selected);
  73. }
  74. document.addEventListener('DOMContentLoaded', function() {
  75. GRID_PUBLIC_ID = (document.location.hash.substr(1));
  76. if (GRID_PUBLIC_ID == "") {
  77. document.location.href = "/";
  78. return;
  79. }
  80. document.addEventListener('click', gridClickDelegate);
  81. document.addEventListener('keypress', function(e) {
  82. if (CURRENTINPUT) {
  83. var key = e.key.charAt(0).toUpperCase();
  84. if (key.match(/[A-Z]/)) {
  85. keyPressHandler(CURRENTINPUT, key);
  86. }
  87. }
  88. });
  89. initPolling();
  90. });