You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

board.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /**
  2. * WHITEBOPHIR
  3. *********************************************************
  4. * @licstart The following is the entire license notice for the
  5. * JavaScript code in this page.
  6. *
  7. * Copyright (C) 2013 Ophir LOJKINE
  8. *
  9. *
  10. * The JavaScript code in this page is free software: you can
  11. * redistribute it and/or modify it under the terms of the GNU
  12. * General Public License (GNU GPL) as published by the Free Software
  13. * Foundation, either version 3 of the License, or (at your option)
  14. * any later version. The code is distributed WITHOUT ANY WARRANTY;
  15. * without even the implied warranty of MERCHANTABILITY or FITNESS
  16. * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
  17. *
  18. * As additional permission under GNU GPL version 3 section 7, you
  19. * may distribute non-source (e.g., minimized or compacted) forms of
  20. * that code without the copy of the GNU GPL normally required by
  21. * section 4, provided you include this license notice and a URL
  22. * through which recipients can access the Corresponding Source.
  23. *
  24. * @licend
  25. */
  26. var Tools = {};
  27. Tools.board = document.getElementById("board");
  28. Tools.svg = document.getElementById("canvas");
  29. Tools.socket = io.connect('', {
  30. "reconnection delay": 1, //Make the xhr connections as fast as possible
  31. });
  32. Tools.curTool = null;
  33. Tools.boardName = (function () {
  34. var path = window.location.pathname.split("/");
  35. return path[path.length - 1];
  36. })();
  37. //Get the board as soon as the page is loaded
  38. Tools.socket.emit("getboard", Tools.boardName);
  39. Tools.HTML = {
  40. template: new Minitpl("#tools > .tool"),
  41. addTool: function (toolName, toolIcon) {
  42. var callback = function () {
  43. Tools.change(toolName);
  44. };
  45. return this.template.add(function (elem) {
  46. elem.addEventListener("click", callback);
  47. elem.id = "toolID-" + toolName;
  48. elem.getElementsByClassName("tool-name")[0].textContent = toolName;
  49. elem.getElementsByClassName("tool-icon")[0].textContent = toolIcon;
  50. Tools.i18n.translateDOM();
  51. });
  52. },
  53. changeTool: function (oldToolName, newToolName) {
  54. var oldTool = document.getElementById("toolID-" + oldToolName);
  55. var newTool = document.getElementById("toolID-" + newToolName);
  56. if (oldTool) oldTool.classList.remove("curTool");
  57. if (newTool) newTool.classList.add("curTool");
  58. },
  59. addStylesheet: function (href) {
  60. //Adds a css stylesheet to the html or svg document
  61. var link = document.createElement("link");
  62. link.href = href;
  63. link.rel = "stylesheet";
  64. link.type = "text/css";
  65. document.head.appendChild(link);
  66. }
  67. };
  68. Tools.list = {}; // An array of all known tools. {"toolName" : {toolObject}}
  69. Tools.add = function (newTool) {
  70. if (newTool.name in Tools.list) {
  71. console.log("Tools.add: The tool '" + newTool.name + "' is already" +
  72. "in the list. Updating it...");
  73. }
  74. //Format the new tool correctly
  75. Tools.applyHooks(Tools.toolHooks, newTool);
  76. //Add the tool to the list
  77. Tools.list[newTool.name] = newTool;
  78. if (newTool.stylesheet) {
  79. Tools.HTML.addStylesheet(newTool.stylesheet);
  80. }
  81. //Add the tool to the GUI
  82. Tools.HTML.addTool(newTool.name, newTool.icon);
  83. //There may be pending messages for the tool
  84. var pending = Tools.pendingMessages[newTool.name];
  85. if (pending) {
  86. console.log("Drawing pending messages for '%s'.", newTool.name);
  87. var msg;
  88. while (msg = pending.shift()) {
  89. //Transmit the message to the tool (precising that it comes from the network)
  90. newTool.draw(msg, false);
  91. }
  92. }
  93. };
  94. Tools.change = function (toolName) {
  95. if (!(toolName in Tools.list)) {
  96. throw "Trying to select a tool that has never been added!";
  97. }
  98. var newtool = Tools.list[toolName];
  99. //Update the GUI
  100. var curToolName = (Tools.curTool) ? Tools.curTool.name : "";
  101. try {
  102. Tools.HTML.changeTool(curToolName, toolName);
  103. } catch (e) {
  104. console.error("Unable to update the GUI with the new tool. " + e);
  105. }
  106. Tools.svg.style.cursor = newtool.mouseCursor || "auto";
  107. //There is not necessarily already a curTool
  108. if (Tools.curTool !== null) {
  109. //It's useless to do anything if the new tool is already selected
  110. if (newtool === Tools.curTool) return;
  111. //Remove the old event listeners
  112. for (var event in Tools.curTool.compiledListeners) {
  113. var listener = Tools.curTool.compiledListeners[event];
  114. Tools.board.removeEventListener(event, listener);
  115. }
  116. //Call the callbacks of the old tool
  117. Tools.curTool.onquit(newtool);
  118. }
  119. //Add the new event listeners
  120. for (var event in newtool.compiledListeners) {
  121. var listener = newtool.compiledListeners[event];
  122. Tools.board.addEventListener(event, listener, { 'passive': false });
  123. }
  124. //Call the start callback of the new tool
  125. newtool.onstart(Tools.curTool);
  126. Tools.curTool = newtool;
  127. };
  128. Tools.send = function (data, toolName) {
  129. toolName = toolName || Tools.curTool.name;
  130. var d = data;
  131. d.tool = toolName;
  132. Tools.applyHooks(Tools.messageHooks, d);
  133. var message = {
  134. "board": Tools.boardName,
  135. "data": d
  136. }
  137. Tools.socket.emit('broadcast', message);
  138. };
  139. Tools.drawAndSend = function (data) {
  140. Tools.curTool.draw(data, true);
  141. Tools.send(data);
  142. };
  143. //Object containing the messages that have been received before the corresponding tool
  144. //is loaded. keys : the name of the tool, values : array of messages for this tool
  145. Tools.pendingMessages = {};
  146. //Receive draw instructions from the server
  147. Tools.socket.on("broadcast", function (message) {
  148. function messageForTool(message) {
  149. var name = message.tool,
  150. tool = Tools.list[name];
  151. if (tool) {
  152. Tools.applyHooks(Tools.messageHooks, message);
  153. tool.draw(message, false);
  154. } else {
  155. ///We received a message destinated to a tool that we don't have
  156. //So we add it to the pending messages
  157. if (!Tools.pendingMessages[name]) Tools.pendingMessages[name] = [message];
  158. else Tools.pendingMessages[name].push(message);
  159. }
  160. }
  161. //Check if the message is in the expected format
  162. if (message.tool) {
  163. messageForTool(message);
  164. }
  165. if (message._children) {
  166. for (var i = 0; i < message._children.length; i++) {
  167. //Apply hooks on children too
  168. var msg = message._children[i];
  169. messageForTool(msg);
  170. }
  171. }
  172. if (!message.tool && !message._children) {
  173. console.error("Received a badly formatted message (no tool). ", message);
  174. }
  175. });
  176. Tools.unreadMessagesCount = 0;
  177. Tools.newUnreadMessage = function () {
  178. document.title = "(" + (++Tools.unreadMessagesCount) + ") WBO";
  179. };
  180. window.addEventListener("focus", function () {
  181. Tools.unreadMessagesCount = 0;
  182. document.title = "WBO";
  183. });
  184. //List of hook functions that will be applied to messages before sending or drawing them
  185. Tools.messageHooks = [
  186. function resizeCanvas(m) {
  187. //Enlarge the canvas is something is drawn near its border
  188. if (m.x && m.y) {
  189. var svg = Tools.svg, x = m.x, y = m.y;
  190. if (x > svg.width.baseVal.value - 1000) {
  191. svg.width.baseVal.value = x + 2000;
  192. }
  193. if (y > svg.height.baseVal.value - 500) {
  194. svg.height.baseVal.value = y + 2000;
  195. }
  196. }
  197. },
  198. function updateUnreadCount(m) {
  199. if (document.hidden && ["child", "update"].indexOf(m.type) === -1) {
  200. Tools.newUnreadMessage();
  201. }
  202. }
  203. ];
  204. //List of hook functions that will be applied to tools before adding them
  205. Tools.toolHooks = [
  206. function checkToolAttributes(tool) {
  207. if (typeof (tool.name) !== "string") throw "A tool must have a name";
  208. if (typeof (tool.listeners) !== "object") {
  209. tool.listeners = {};
  210. }
  211. if (typeof (tool.onstart) !== "function") {
  212. tool.onstart = function () { };
  213. }
  214. if (typeof (tool.onquit) !== "function") {
  215. tool.onquit = function () { };
  216. }
  217. },
  218. function compileListeners(tool) {
  219. //compile listeners into compiledListeners
  220. var listeners = tool.listeners;
  221. //A tool may provide precompiled listeners
  222. var compiled = tool.compiledListeners || {};
  223. tool.compiledListeners = compiled;
  224. function compile(listener) { //closure
  225. return (function listen(evt) {
  226. var x = evt.pageX,
  227. y = evt.pageY;
  228. return listener(x, y, evt, false);
  229. });
  230. }
  231. function compileTouch(listener) { //closure
  232. return (function touchListen(evt) {
  233. //Currently, we don't handle multitouch
  234. if (evt.changedTouches.length === 1) {
  235. //evt.preventDefault();
  236. var touch = evt.changedTouches[0];
  237. var x = touch.pageX,
  238. y = touch.pageY;
  239. return listener(x, y, evt, true);
  240. }
  241. return true;
  242. });
  243. }
  244. if (listeners.press) {
  245. compiled["mousedown"] = compile(listeners.press);
  246. compiled["touchstart"] = compileTouch(listeners.press);
  247. }
  248. if (listeners.move) {
  249. compiled["mousemove"] = compile(listeners.move);
  250. compiled["touchmove"] = compileTouch(listeners.move);
  251. }
  252. if (listeners.release) {
  253. var release = compile(listeners.release),
  254. releaseTouch = compileTouch(listeners.release);
  255. compiled["mouseup"] = release;
  256. compiled["mouseleave"] = release;
  257. compiled["touchleave"] = releaseTouch;
  258. compiled["touchend"] = releaseTouch;
  259. compiled["touchcancel"] = releaseTouch;
  260. }
  261. }
  262. ];
  263. Tools.applyHooks = function (hooks, object) {
  264. //Apply every hooks on the object
  265. hooks.forEach(function (hook) {
  266. hook(object);
  267. });
  268. };
  269. // Utility functions
  270. Tools.generateUID = function (prefix, suffix) {
  271. var uid = Date.now().toString(36); //Create the uids in chronological order
  272. uid += (Math.round(Math.random() * 36)).toString(36); //Add a random character at the end
  273. if (prefix) uid = prefix + uid;
  274. if (suffix) uid = uid + suffix;
  275. return uid;
  276. };
  277. Tools.createSVGElement = function (name) {
  278. return document.createElementNS(Tools.svg.namespaceURI, name);
  279. };
  280. Tools.positionElement = function (elem, x, y) {
  281. elem.style.top = y + "px";
  282. elem.style.left = x + "px";
  283. };
  284. Tools.getColor = (function color() {
  285. var chooser = document.getElementById("chooseColor");
  286. return function () { return chooser.value; };
  287. })();
  288. Tools.getSize = (function size() {
  289. var chooser = document.getElementById("chooseSize");
  290. function update() {
  291. if (chooser.value < 1 || chooser.value > 50) {
  292. chooser.value = 3;
  293. }
  294. }
  295. update();
  296. chooser.onchange = update;
  297. return function () { return chooser.value; };
  298. })();
  299. Tools.i18n = (function i18n() {
  300. var lng = (navigator.language || navigator.browserLanguage).split('-')[0];
  301. var translations = {};
  302. var state = "pending";
  303. var xhr = new XMLHttpRequest;
  304. xhr.open("GET", "/translations/" + lng + ".json");
  305. xhr.send(null);
  306. xhr.onload = function () {
  307. state = xhr.status === 200 ? "loaded" : "error";
  308. if (state !== "loaded") return;
  309. translations = JSON.parse(xhr.responseText);
  310. Tools.i18n.translateDOM();
  311. }
  312. return {
  313. "t": function translate(s) {
  314. return translations[s] || s;
  315. },
  316. "translateDOM": function translateDOM() {
  317. if (state !== "loaded") return false;
  318. var els = document.querySelectorAll("[data-translation=waiting]");
  319. for (var i = 0; i < els.length; i++) {
  320. var el = els[i];
  321. el.setAttribute("data-translation", "done");
  322. el.innerHTML = Tools.i18n.t(el.innerHTML);
  323. }
  324. return true;
  325. }
  326. };
  327. })();
  328. //Scale the canvas on load
  329. Tools.svg.width.baseVal.value = document.body.clientWidth;
  330. Tools.svg.height.baseVal.value = document.body.clientHeight;
  331. (function menu() {
  332. var menu = document.getElementById("menu");
  333. tog = document.getElementById("toggleMenu");
  334. tog.onclick = function (e) {
  335. menu.classList.toggle("closed");
  336. };
  337. })();
  338. /*********** Polyfills ***********/
  339. if (!window.performance || !window.performance.now) {
  340. window.performance = {
  341. "now": Date.now
  342. }
  343. }
  344. if (!Math.hypot) {
  345. Math.hypot = function (x, y) {
  346. //The true Math.hypot accepts any number of parameters
  347. return Math.sqrt(x * x + y * y);
  348. }
  349. }
  350. /**
  351. What does a "tool" object look like?
  352. newtool = {
  353. "name" : "SuperTool",
  354. "listeners" : {
  355. "press" : function(x,y,evt){...},
  356. "move" : function(x,y,evt){...},
  357. "release" : function(x,y,evt){...},
  358. },
  359. "draw" : function(data, isLocal){
  360. //Print the data on Tools.svg
  361. },
  362. "onstart" : function(oldTool){...},
  363. "onquit" : function(newTool){...},
  364. "stylesheet" : "style.css",
  365. }
  366. */