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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. // Send a message to the corresponding tool
  147. function messageForTool(message) {
  148. var name = message.tool,
  149. tool = Tools.list[name];
  150. if (tool) {
  151. Tools.applyHooks(Tools.messageHooks, message);
  152. tool.draw(message, false);
  153. } else {
  154. ///We received a message destinated to a tool that we don't have
  155. //So we add it to the pending messages
  156. if (!Tools.pendingMessages[name]) Tools.pendingMessages[name] = [message];
  157. else Tools.pendingMessages[name].push(message);
  158. }
  159. }
  160. // Apply the function to all arguments by batches
  161. function batchCall(fn, args) {
  162. var BATCH_SIZE = 512;
  163. if (args.length > 0) {
  164. var batch = args.slice(0, BATCH_SIZE);
  165. var rest = args.slice(BATCH_SIZE);
  166. for (var i = 0; i < batch.length; i++) fn(batch[i]);
  167. requestAnimationFrame(batchCall.bind(null, fn, rest));
  168. }
  169. }
  170. // Call messageForTool recursively on the message and its children
  171. function handleMessage(message) {
  172. //Check if the message is in the expected format
  173. if (message.tool) messageForTool(message);
  174. if (message._children) batchCall(handleMessage, message._children);
  175. if (!message.tool && !message._children) {
  176. console.error("Received a badly formatted message (no tool). ", message);
  177. }
  178. }
  179. //Receive draw instructions from the server
  180. Tools.socket.on("broadcast", handleMessage);
  181. Tools.unreadMessagesCount = 0;
  182. Tools.newUnreadMessage = function () {
  183. document.title = "(" + (++Tools.unreadMessagesCount) + ") WBO";
  184. };
  185. window.addEventListener("focus", function () {
  186. Tools.unreadMessagesCount = 0;
  187. document.title = "WBO";
  188. });
  189. //List of hook functions that will be applied to messages before sending or drawing them
  190. Tools.messageHooks = [
  191. function resizeCanvas(m) {
  192. //Enlarge the canvas is something is drawn near its border
  193. if (m.x && m.y) {
  194. var svg = Tools.svg, x = m.x, y = m.y;
  195. if (x > svg.width.baseVal.value - 1000) {
  196. svg.width.baseVal.value = x + 2000;
  197. }
  198. if (y > svg.height.baseVal.value - 500) {
  199. svg.height.baseVal.value = y + 2000;
  200. }
  201. }
  202. },
  203. function updateUnreadCount(m) {
  204. if (document.hidden && ["child", "update"].indexOf(m.type) === -1) {
  205. Tools.newUnreadMessage();
  206. }
  207. }
  208. ];
  209. //List of hook functions that will be applied to tools before adding them
  210. Tools.toolHooks = [
  211. function checkToolAttributes(tool) {
  212. if (typeof (tool.name) !== "string") throw "A tool must have a name";
  213. if (typeof (tool.listeners) !== "object") {
  214. tool.listeners = {};
  215. }
  216. if (typeof (tool.onstart) !== "function") {
  217. tool.onstart = function () { };
  218. }
  219. if (typeof (tool.onquit) !== "function") {
  220. tool.onquit = function () { };
  221. }
  222. },
  223. function compileListeners(tool) {
  224. //compile listeners into compiledListeners
  225. var listeners = tool.listeners;
  226. //A tool may provide precompiled listeners
  227. var compiled = tool.compiledListeners || {};
  228. tool.compiledListeners = compiled;
  229. function compile(listener) { //closure
  230. return (function listen(evt) {
  231. var x = evt.pageX,
  232. y = evt.pageY;
  233. return listener(x, y, evt, false);
  234. });
  235. }
  236. function compileTouch(listener) { //closure
  237. return (function touchListen(evt) {
  238. //Currently, we don't handle multitouch
  239. if (evt.changedTouches.length === 1) {
  240. //evt.preventDefault();
  241. var touch = evt.changedTouches[0];
  242. var x = touch.pageX,
  243. y = touch.pageY;
  244. return listener(x, y, evt, true);
  245. }
  246. return true;
  247. });
  248. }
  249. if (listeners.press) {
  250. compiled["mousedown"] = compile(listeners.press);
  251. compiled["touchstart"] = compileTouch(listeners.press);
  252. }
  253. if (listeners.move) {
  254. compiled["mousemove"] = compile(listeners.move);
  255. compiled["touchmove"] = compileTouch(listeners.move);
  256. }
  257. if (listeners.release) {
  258. var release = compile(listeners.release),
  259. releaseTouch = compileTouch(listeners.release);
  260. compiled["mouseup"] = release;
  261. compiled["mouseleave"] = release;
  262. compiled["touchleave"] = releaseTouch;
  263. compiled["touchend"] = releaseTouch;
  264. compiled["touchcancel"] = releaseTouch;
  265. }
  266. }
  267. ];
  268. Tools.applyHooks = function (hooks, object) {
  269. //Apply every hooks on the object
  270. hooks.forEach(function (hook) {
  271. hook(object);
  272. });
  273. };
  274. // Utility functions
  275. Tools.generateUID = function (prefix, suffix) {
  276. var uid = Date.now().toString(36); //Create the uids in chronological order
  277. uid += (Math.round(Math.random() * 36)).toString(36); //Add a random character at the end
  278. if (prefix) uid = prefix + uid;
  279. if (suffix) uid = uid + suffix;
  280. return uid;
  281. };
  282. Tools.createSVGElement = function (name) {
  283. return document.createElementNS(Tools.svg.namespaceURI, name);
  284. };
  285. Tools.positionElement = function (elem, x, y) {
  286. elem.style.top = y + "px";
  287. elem.style.left = x + "px";
  288. };
  289. Tools.getColor = (function color() {
  290. var chooser = document.getElementById("chooseColor");
  291. return function () { return chooser.value; };
  292. })();
  293. Tools.getSize = (function size() {
  294. var chooser = document.getElementById("chooseSize");
  295. function update() {
  296. if (chooser.value < 1 || chooser.value > 50) {
  297. chooser.value = 3;
  298. }
  299. }
  300. update();
  301. chooser.onchange = update;
  302. return function () { return chooser.value; };
  303. })();
  304. Tools.i18n = (function i18n() {
  305. var lng = (navigator.language || navigator.browserLanguage).split('-')[0];
  306. var translations = {};
  307. var state = "pending";
  308. var xhr = new XMLHttpRequest;
  309. xhr.open("GET", "/translations/" + lng + ".json");
  310. xhr.send(null);
  311. xhr.onload = function () {
  312. state = xhr.status === 200 ? "loaded" : "error";
  313. if (state !== "loaded") return;
  314. translations = JSON.parse(xhr.responseText);
  315. Tools.i18n.translateDOM();
  316. }
  317. return {
  318. "t": function translate(s) {
  319. return translations[s] || s;
  320. },
  321. "translateDOM": function translateDOM() {
  322. if (state !== "loaded") return false;
  323. var els = document.querySelectorAll("[data-translation=waiting]");
  324. for (var i = 0; i < els.length; i++) {
  325. var el = els[i];
  326. el.setAttribute("data-translation", "done");
  327. el.innerHTML = Tools.i18n.t(el.innerHTML);
  328. }
  329. return true;
  330. }
  331. };
  332. })();
  333. //Scale the canvas on load
  334. Tools.svg.width.baseVal.value = document.body.clientWidth;
  335. Tools.svg.height.baseVal.value = document.body.clientHeight;
  336. (function menu() {
  337. var menu = document.getElementById("menu");
  338. tog = document.getElementById("toggleMenu");
  339. tog.onclick = function (e) {
  340. menu.classList.toggle("closed");
  341. };
  342. })();
  343. /*********** Polyfills ***********/
  344. if (!window.performance || !window.performance.now) {
  345. window.performance = {
  346. "now": Date.now
  347. }
  348. }
  349. if (!Math.hypot) {
  350. Math.hypot = function (x, y) {
  351. //The true Math.hypot accepts any number of parameters
  352. return Math.sqrt(x * x + y * y);
  353. }
  354. }
  355. /**
  356. What does a "tool" object look like?
  357. newtool = {
  358. "name" : "SuperTool",
  359. "listeners" : {
  360. "press" : function(x,y,evt){...},
  361. "move" : function(x,y,evt){...},
  362. "release" : function(x,y,evt){...},
  363. },
  364. "draw" : function(data, isLocal){
  365. //Print the data on Tools.svg
  366. },
  367. "onstart" : function(oldTool){...},
  368. "onquit" : function(newTool){...},
  369. "stylesheet" : "style.css",
  370. }
  371. */