Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

board.js 18KB

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