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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. Tools.board.title = Tools.i18n.t(newtool.helpText || "");
  109. //There is not necessarily already a curTool
  110. if (Tools.curTool !== null) {
  111. //It's useless to do anything if the new tool is already selected
  112. if (newtool === Tools.curTool) return;
  113. //Remove the old event listeners
  114. for (var event in Tools.curTool.compiledListeners) {
  115. var listener = Tools.curTool.compiledListeners[event];
  116. Tools.board.removeEventListener(event, listener);
  117. }
  118. //Call the callbacks of the old tool
  119. Tools.curTool.onquit(newtool);
  120. }
  121. //Add the new event listeners
  122. for (var event in newtool.compiledListeners) {
  123. var listener = newtool.compiledListeners[event];
  124. Tools.board.addEventListener(event, listener, { 'passive': false });
  125. }
  126. //Call the start callback of the new tool
  127. newtool.onstart(Tools.curTool);
  128. Tools.curTool = newtool;
  129. };
  130. Tools.send = function (data, toolName) {
  131. toolName = toolName || Tools.curTool.name;
  132. var d = data;
  133. d.tool = toolName;
  134. Tools.applyHooks(Tools.messageHooks, d);
  135. var message = {
  136. "board": Tools.boardName,
  137. "data": d
  138. }
  139. Tools.socket.emit('broadcast', message);
  140. };
  141. Tools.drawAndSend = function (data) {
  142. Tools.curTool.draw(data, true);
  143. Tools.send(data);
  144. };
  145. //Object containing the messages that have been received before the corresponding tool
  146. //is loaded. keys : the name of the tool, values : array of messages for this tool
  147. Tools.pendingMessages = {};
  148. // Send a message to the corresponding tool
  149. function messageForTool(message) {
  150. var name = message.tool,
  151. tool = Tools.list[name];
  152. if (tool) {
  153. Tools.applyHooks(Tools.messageHooks, message);
  154. tool.draw(message, false);
  155. } else {
  156. ///We received a message destinated to a tool that we don't have
  157. //So we add it to the pending messages
  158. if (!Tools.pendingMessages[name]) Tools.pendingMessages[name] = [message];
  159. else Tools.pendingMessages[name].push(message);
  160. }
  161. }
  162. // Apply the function to all arguments by batches
  163. function batchCall(fn, args) {
  164. var BATCH_SIZE = 1024;
  165. if (args.length > 0) {
  166. var batch = args.slice(0, BATCH_SIZE);
  167. var rest = args.slice(BATCH_SIZE);
  168. for (var i = 0; i < batch.length; i++) fn(batch[i]);
  169. requestAnimationFrame(batchCall.bind(null, fn, rest));
  170. }
  171. }
  172. // Call messageForTool recursively on the message and its children
  173. function handleMessage(message) {
  174. //Check if the message is in the expected format
  175. if (message.tool) messageForTool(message);
  176. if (message._children) batchCall(handleMessage, message._children);
  177. if (!message.tool && !message._children) {
  178. console.error("Received a badly formatted message (no tool). ", message);
  179. }
  180. }
  181. //Receive draw instructions from the server
  182. Tools.socket.on("broadcast", handleMessage);
  183. Tools.socket.on("reconnect", function onReconnection() {
  184. Tools.socket.emit('joinboard', Tools.boardName);
  185. });
  186. Tools.unreadMessagesCount = 0;
  187. Tools.newUnreadMessage = function () {
  188. Tools.unreadMessagesCount++;
  189. updateDocumentTitle();
  190. };
  191. window.addEventListener("focus", function () {
  192. Tools.unreadMessagesCount = 0;
  193. updateDocumentTitle();
  194. });
  195. function updateDocumentTitle() {
  196. document.title =
  197. (Tools.unreadMessagesCount ? '(' + Tools.unreadMessagesCount + ') ' : '') +
  198. Tools.boardName +
  199. " | WBO";
  200. }
  201. (function () {
  202. // Scroll and hash handling
  203. var scrollTimeout, lastStateUpdate = Date.now();
  204. window.addEventListener("scroll", function onScroll() {
  205. var x = window.scrollX / Tools.getScale(),
  206. y = window.scrollY / Tools.getScale();
  207. clearTimeout(scrollTimeout);
  208. scrollTimeout = setTimeout(function updateHistory() {
  209. var hash = '#' + (x | 0) + ',' + (y | 0) + ',' + Tools.getScale().toFixed(1);
  210. if (Date.now() - lastStateUpdate > 5000 && hash != window.location.hash) {
  211. window.history.pushState({}, "", hash);
  212. lastStateUpdate = Date.now();
  213. } else {
  214. window.history.replaceState({}, "", hash);
  215. }
  216. }, 100);
  217. });
  218. function setScrollFromHash() {
  219. var coords = window.location.hash.slice(1).split(',');
  220. var x = coords[0] | 0;
  221. var y = coords[1] | 0;
  222. var scale = parseFloat(coords[2]);
  223. resizeCanvas({ x: x, y: y });
  224. Tools.setScale(scale);
  225. window.scrollTo(x * scale, y * scale);
  226. }
  227. window.addEventListener("hashchange", setScrollFromHash, false);
  228. window.addEventListener("popstate", setScrollFromHash, false);
  229. window.addEventListener("DOMContentLoaded", setScrollFromHash, false);
  230. })();
  231. //List of hook functions that will be applied to messages before sending or drawing them
  232. function resizeCanvas(m) {
  233. //Enlarge the canvas whenever something is drawn near its border
  234. var x = m.x | 0, y = m.y | 0
  235. var MAX_BOARD_SIZE = 65536; // Maximum value for any x or y on the board
  236. if (x > Tools.svg.width.baseVal.value - 2000) {
  237. Tools.svg.width.baseVal.value = Math.min(x + 2000, MAX_BOARD_SIZE);
  238. }
  239. if (y > Tools.svg.height.baseVal.value - 2000) {
  240. Tools.svg.height.baseVal.value = Math.min(y + 2000, MAX_BOARD_SIZE);
  241. }
  242. }
  243. function updateUnreadCount(m) {
  244. if (document.hidden && ["child", "update"].indexOf(m.type) === -1) {
  245. Tools.newUnreadMessage();
  246. }
  247. }
  248. Tools.messageHooks = [resizeCanvas, updateUnreadCount];
  249. Tools.scale = 1.0;
  250. var scaleTimeout = null;
  251. Tools.setScale = function setScale(scale) {
  252. if (isNaN(scale)) scale = 1;
  253. scale = Math.max(0.1, Math.min(10, scale));
  254. Tools.svg.style.willChange = 'transform';
  255. Tools.svg.style.transform = 'scale(' + scale + ')';
  256. clearTimeout(scaleTimeout);
  257. scaleTimeout = setTimeout(function () {
  258. Tools.svg.style.willChange = 'auto';
  259. }, 1000);
  260. Tools.scale = scale;
  261. return scale;
  262. }
  263. Tools.getScale = function getScale() {
  264. return Tools.scale;
  265. }
  266. //List of hook functions that will be applied to tools before adding them
  267. Tools.toolHooks = [
  268. function checkToolAttributes(tool) {
  269. if (typeof (tool.name) !== "string") throw "A tool must have a name";
  270. if (typeof (tool.listeners) !== "object") {
  271. tool.listeners = {};
  272. }
  273. if (typeof (tool.onstart) !== "function") {
  274. tool.onstart = function () { };
  275. }
  276. if (typeof (tool.onquit) !== "function") {
  277. tool.onquit = function () { };
  278. }
  279. },
  280. function compileListeners(tool) {
  281. //compile listeners into compiledListeners
  282. var listeners = tool.listeners;
  283. //A tool may provide precompiled listeners
  284. var compiled = tool.compiledListeners || {};
  285. tool.compiledListeners = compiled;
  286. function compile(listener) { //closure
  287. return (function listen(evt) {
  288. var x = evt.pageX / Tools.getScale(),
  289. y = evt.pageY / Tools.getScale();
  290. return listener(x, y, evt, false);
  291. });
  292. }
  293. function compileTouch(listener) { //closure
  294. return (function touchListen(evt) {
  295. //Currently, we don't handle multitouch
  296. if (evt.changedTouches.length === 1) {
  297. //evt.preventDefault();
  298. var touch = evt.changedTouches[0];
  299. var x = touch.pageX / Tools.getScale(),
  300. y = touch.pageY / Tools.getScale();
  301. return listener(x, y, evt, true);
  302. }
  303. return true;
  304. });
  305. }
  306. if (listeners.press) {
  307. compiled["mousedown"] = compile(listeners.press);
  308. compiled["touchstart"] = compileTouch(listeners.press);
  309. }
  310. if (listeners.move) {
  311. compiled["mousemove"] = compile(listeners.move);
  312. compiled["touchmove"] = compileTouch(listeners.move);
  313. }
  314. if (listeners.release) {
  315. var release = compile(listeners.release),
  316. releaseTouch = compileTouch(listeners.release);
  317. compiled["mouseup"] = release;
  318. compiled["mouseleave"] = release;
  319. compiled["touchleave"] = releaseTouch;
  320. compiled["touchend"] = releaseTouch;
  321. compiled["touchcancel"] = releaseTouch;
  322. }
  323. }
  324. ];
  325. Tools.applyHooks = function (hooks, object) {
  326. //Apply every hooks on the object
  327. hooks.forEach(function (hook) {
  328. hook(object);
  329. });
  330. };
  331. // Utility functions
  332. Tools.generateUID = function (prefix, suffix) {
  333. var uid = Date.now().toString(36); //Create the uids in chronological order
  334. uid += (Math.round(Math.random() * 36)).toString(36); //Add a random character at the end
  335. if (prefix) uid = prefix + uid;
  336. if (suffix) uid = uid + suffix;
  337. return uid;
  338. };
  339. Tools.createSVGElement = function (name) {
  340. return document.createElementNS(Tools.svg.namespaceURI, name);
  341. };
  342. Tools.positionElement = function (elem, x, y) {
  343. elem.style.top = y + "px";
  344. elem.style.left = x + "px";
  345. };
  346. Tools.getColor = (function color() {
  347. var chooser = document.getElementById("chooseColor");
  348. // Init with a random color
  349. var clrs = ["#001f3f", "#0074D9", "#7FDBFF", "#39CCCC", "#3D9970",
  350. "#2ECC40", "#01FF70", "#FFDC00", "#FF851B", "#FF4136",
  351. "#85144b", "#F012BE", "#B10DC9", "#111111", "#AAAAAA"];
  352. chooser.value = clrs[Math.random() * clrs.length | 0];
  353. return function () { return chooser.value; };
  354. })();
  355. Tools.getSize = (function size() {
  356. var chooser = document.getElementById("chooseSize");
  357. function update() {
  358. if (chooser.value < 1 || chooser.value > 50) {
  359. chooser.value = 3;
  360. }
  361. }
  362. update();
  363. chooser.onchange = update;
  364. return function () { return chooser.value; };
  365. })();
  366. Tools.getOpacity = (function opacity() {
  367. var chooser = document.getElementById("chooseOpacity");
  368. return function () {
  369. return Math.max(0.1, Math.min(1, chooser.value));
  370. };
  371. })();
  372. Tools.i18n = (function i18n() {
  373. var lng = (navigator.language || navigator.browserLanguage).split('-')[0];
  374. var translations = {};
  375. var state = "pending";
  376. var xhr = new XMLHttpRequest;
  377. xhr.open("GET", "/translations/" + lng + ".json");
  378. xhr.send(null);
  379. xhr.onload = function () {
  380. state = xhr.status === 200 ? "loaded" : "error";
  381. if (state !== "loaded") return;
  382. translations = JSON.parse(xhr.responseText);
  383. Tools.i18n.translateDOM();
  384. }
  385. return {
  386. "t": function translate(s) {
  387. return translations[s] || s;
  388. },
  389. "translateDOM": function translateDOM() {
  390. if (state !== "loaded") return false;
  391. var els = document.querySelectorAll("[data-translation=waiting]");
  392. for (var i = 0; i < els.length; i++) {
  393. var el = els[i];
  394. el.setAttribute("data-translation", "done");
  395. el.innerHTML = Tools.i18n.t(el.innerHTML);
  396. }
  397. return true;
  398. }
  399. };
  400. })();
  401. //Scale the canvas on load
  402. Tools.svg.width.baseVal.value = document.body.clientWidth;
  403. Tools.svg.height.baseVal.value = document.body.clientHeight;
  404. (function menu() {
  405. var menu = document.getElementById("menu");
  406. tog = document.getElementById("toggleMenu");
  407. tog.onclick = function (e) {
  408. menu.classList.toggle("closed");
  409. };
  410. })();
  411. /*********** Polyfills ***********/
  412. if (!window.performance || !window.performance.now) {
  413. window.performance = {
  414. "now": Date.now
  415. }
  416. }
  417. if (!Math.hypot) {
  418. Math.hypot = function (x, y) {
  419. //The true Math.hypot accepts any number of parameters
  420. return Math.sqrt(x * x + y * y);
  421. }
  422. }
  423. /**
  424. What does a "tool" object look like?
  425. newtool = {
  426. "name" : "SuperTool",
  427. "listeners" : {
  428. "press" : function(x,y,evt){...},
  429. "move" : function(x,y,evt){...},
  430. "release" : function(x,y,evt){...},
  431. },
  432. "draw" : function(data, isLocal){
  433. //Print the data on Tools.svg
  434. },
  435. "onstart" : function(oldTool){...},
  436. "onquit" : function(newTool){...},
  437. "stylesheet" : "style.css",
  438. }
  439. */