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

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