Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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