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

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