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

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