svg.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. if (!String.prototype.encodeHTML) {
  2. String.prototype.encodeHTML = function () {
  3. return this.replace(/&/g, '&')
  4. .replace(/</g, '&lt;')
  5. .replace(/>/g, '&gt;')
  6. .replace(/"/g, '&quot;')
  7. .replace(/'/g, '&apos;');
  8. };
  9. }
  10. var transition = {pid: '', port: '8080' };
  11. // BERT Protocol
  12. var players = ["Gabrielo","Mustafa","Alina","Me"];
  13. function statsRow(start_name,i,games) {
  14. var start_score = 200;
  15. var name = template_engine(
  16. '<tspan xmlns="http://www.w3.org/2000/svg" x="{this.x}" y="{this.y}">{this.body}</tspan>',{
  17. x: start_name,
  18. y: 180+25*i,
  19. body: games[i].value[0][0] + " — " + games[i].value[0][1]});
  20. var element1 = svg(name);
  21. document.getElementById('Stat-Right').appendChild(element1);
  22. }
  23. function handle_web_socket(body) {
  24. // console.log(dec(body).value[0][0].value);
  25. switch (dec(body).value[0][0].value) {
  26. case 'stats_event':
  27. document.getElementById('Player-Statistics').style.display = '';
  28. var games = dec(body).value[0][2];
  29. var reveals = dec(body).value[0][3];
  30. var protocol = dec(body).value[0][4];
  31. removeChilds(document.getElementById('Stat-Left'));
  32. removeChilds(document.getElementById('Stat-Right'));
  33. for (var i=0;i<games.length;i++) { statsRow(24, i,games); }
  34. for (var i=0;i<protocol.length;i++) { statsRow(340,i,protocol); }
  35. // for (var i=0;i<reveals.length;i++) { statsRow(340,i,reveals); }
  36. break;
  37. }
  38. switch (dec(body).value[0][2].value) {
  39. case 'okey_game_info':
  40. var a = dec(body).value[0][3][0].value[0][1];
  41. // console.log("Players: " + a.length);
  42. for (var i=0;i<a.length;i++) {
  43. var c = a[i].value[0][3].value;
  44. var v = a[i].value[0][4].value;
  45. setPlayerName(players[i],c + " " + v);
  46. // console.log("Player: " + c + " " + v);
  47. }
  48. break;
  49. case 'okey_game_started':
  50. var a = dec(body).value[0][3][0].value[0][1];
  51. // console.log("Cards: " + a.length);
  52. for (var i=1;i<=a.length;i++) {
  53. var c = a[i-1].value[0][1];
  54. var v = a[i-1].value[0][2];
  55. // console.log("Card: " + c + " " + v);
  56. place_card(i,rand(1,2),c,v);
  57. }
  58. break;
  59. case 'okey_game_player_state': /// these two messages should be combined
  60. var a = dec(body).value[0][3][3].value[0][1];
  61. // console.log("Cards: " + a.length);
  62. for (var i=1;i<=a.length;i++) {
  63. var c = a[i-1].value[0][1];
  64. var v = a[i-1].value[0][2];
  65. // console.log("Card: " + c + " " + v);
  66. place_card(i,1,c,v);
  67. }
  68. break;
  69. case 'okey_tile_discarded':
  70. console.log(String(dec(body)));
  71. var player = dec(body).value[0][3][0].value[0][1];
  72. var tile = dec(body).value[0][3][1].value[0][1];
  73. if (player.value == document.user) {
  74. console.log("Discard: " + player.value);
  75. var p = findCardOnTable(tile.value[0][1],tile.value[0][2]);
  76. empty_card(p.x,p.y);
  77. }
  78. break;
  79. case 'okey_tile_taken':
  80. console.log(String(dec(body)));
  81. var player = dec(body).value[0][3][0].value[0][1];
  82. var taken = dec(body).value[0][3][2].value[0][1];
  83. if (taken.value != 'null' && player.value == document.user) {
  84. console.log("Taken: " + player.value);
  85. var c = taken.value[0][1];
  86. var v = taken.value[0][2];
  87. var pos = findPlace();
  88. // console.log(pos);
  89. place_card(pos.x,pos.y,c,v);
  90. }
  91. break;
  92. default: console.log(String(dec(body)));
  93. }
  94. }
  95. // SVG DOM and Template Engine
  96. function template_engine(html, data) {
  97. var re = /{([^}]+)?}/g, code = 'var r=[];', cursor = 0;
  98. var add = function(line,js) {
  99. js? (code += 'r.push(' + line + ');') :
  100. (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");' : '');
  101. return add; }
  102. while(match = re.exec(html)) {
  103. add(html.slice(cursor, match.index))(match[1],true);
  104. cursor = match.index + match[0].length; }
  105. add(html.substr(cursor, html.length - cursor));
  106. code += 'return r.join("");';
  107. return new Function(code.replace(/[\r\t\n]/g, '')).apply(data); }
  108. function reload(file, name) { var slot = document.getElementById(name);
  109. slot.parentNode.replaceChild(svg(localStorage.getItem(file)),slot);}
  110. function reload_cont(cont,name,element) { if (null != cont) (cont)(); else reload(name,element); }
  111. function loadFile(name,cont,element) {
  112. if (localStorage.getItem(name) == null) {
  113. var client = new XMLHttpRequest();
  114. client.open('GET', name, true);
  115. client.onload = function() {
  116. localStorage.setItem(name,client.responseText);
  117. reload_cont(cont,name,element); }
  118. client.send(); }
  119. else reload_cont(cont,name,element); }
  120. function svg(html) {
  121. return new DOMParser().parseFromString(html, "text/xml").firstChild;
  122. }
  123. function svgBulk() {
  124. var res = [];
  125. var node = new DOMParser().parseFromString(html, "text/xml").firstChild;
  126. for (var i=0;i<node.childnode.length;i++) { var child = childNodes.item(i);
  127. if (child.tagName != undefined) res.push(child); } }
  128. // The Card
  129. //var color = ['#CE290F','#3B5998','#48AF5E','#FFEC00'];
  130. var color = ['#DE3F26','#606060','#48AF5E','#FFC800'];
  131. var slotName = slotNameDef;
  132. function slotNameDef(x,y) { return "Slot-"+y+","+x; }
  133. function card(line,pos,col,v) {
  134. return template_engine(
  135. localStorage.getItem("templates/Card.svg"),
  136. { name: slotName(pos,line),
  137. suit: color[col-1],
  138. value: v,
  139. y: (line-1)*69,
  140. x: (pos-1)*42 }); }
  141. // Game Scene
  142. function setPlayerName(e, playerName) {
  143. var dx = (document.getElementById(e).attributes['fill'].value == "#FFFFFF") ? 65 : 20;
  144. document.getElementById(e).setAttribute("y",27);
  145. document.getElementById(e).setAttribute("x",dx);
  146. document.getElementById(e).textContent = playerName;
  147. // console.log("Bounding Box: " + document.getElementById(e).getBBox().width);
  148. document.getElementById(e+"-Pad").setAttribute('width',
  149. document.getElementById(e).getBBox().width + 45); }
  150. function place_card(x,y,c,v) {
  151. var slot = document.getElementById(slotName(x,y));
  152. slot.parentNode.replaceChild(svg(card(y,x,c,v)),slot); }
  153. function empty_card(x,y) { var slot = document.getElementById(slotName(x,y));
  154. var html = '<g xmlns="http://www.w3.org/2000/svg" id="'+slotName(x,y)+'"/>';
  155. slot.parentNode.replaceChild(svg(html),slot); }
  156. function rand(lo,hi) { return Math.floor((Math.random()*hi)+lo); }
  157. function loadScene() {
  158. reload("Kakaranet-Scene.svg", "Refined");
  159. for (var i=1;i<16;i++) { empty_card(i,2); empty_card(i,1); }
  160. //drawSampleCards();
  161. }
  162. function findPlace() {
  163. for (var y=1;y<3;y++) for (var x=1;x<15;x++) {
  164. var e = document.getElementById(slotName(x,y));
  165. if (e.childElementCount == 0) {
  166. var pos = e.attributes['id'].value.split("-")[1].split(",");
  167. console.log("Free");
  168. console.log(pos[0]);
  169. console.log(pos[1]);
  170. return { y: pos[0], x: pos[1] }; } } }
  171. function findCardOnTable(c,v) {
  172. console.log("Find Card " + c + " " + v);
  173. for (var y=1;y<3;y++) for (var x=1;x<15;x++) {
  174. var e = document.getElementById(slotName(x,y));
  175. if (e.childElementCount > 0) {
  176. var value = e.lastChild.textContent;
  177. var col = color.indexOf(e.lastChild.attributes['fill'].value) + 1;
  178. console.log(col + " " + value);
  179. if (c == col && v == value) return { 'x': x, 'y': y }; } }
  180. console.log("Card Not Found");
  181. return ""; }
  182. function loadAppend(file, animation, name) {
  183. loadFile(file, function() {
  184. var slot = document.getElementById(name);
  185. var r = template_engine(localStorage.getItem(file),{'name': animation});
  186. document.getElementById(name).appendChild(svg(r)); }); }
  187. function loadAnimationForButton(a, b) { return loadAppend('templates/ButtonAnimation.svg', a, b); }
  188. // TODO: Rollout Monadic Chain here
  189. loadFile('templates/Card.svg', function() {
  190. loadFile('Kakaranet-Scene.svg', function() {
  191. loadScene();
  192. var a = [{button: "Create", pathes: ["CreateShow", "CreateHide"]},
  193. {button: "Play", pathes: ["PlayShow", "PlayHide"]}];
  194. for (var y=0;y<a.length;y++) for (var x=0;x<a[y].pathes.length;x++)
  195. loadAnimationForButton(a[y].pathes[x],a[y].button);
  196. document.getElementById("Right-Menu") .setAttribute('onclick', 'onRightMenu(evt)');
  197. document.getElementById("Play") .setAttribute('onclick', 'onRightMenuDown(evt)');
  198. document.getElementById("Create") .setAttribute('onclick', 'onRightMenuDown(evt)');
  199. document.getElementById("Point-Table").setAttribute('onclick', 'onPlayerInfo(evt)');
  200. document.getElementById("Player-Statistics").setAttribute('onclick', 'onPlayerInfoClose(evt)');
  201. document.getElementById('Page-1').addEventListener("mousewheel", mouseWheelHandler, false);
  202. var clipPath1 = svg('<clipPath id="myClip1"><rect xmlns="http://www.w3.org/2000/svg" id="Clip-Path-Left" x="0" y="0" width="216" height="400"/></clipPath>');
  203. var clipPath2 = svg('<clipPath id="myClip2"><rect xmlns="http://www.w3.org/2000/svg" id="Clip-Path-Right" x="0" y="0" width="216" height="400"/></clipPath>');
  204. document.getElementsByTagName('defs').item(0).appendChild(clipPath1);
  205. document.getElementsByTagName('defs').item(0).appendChild(clipPath2);
  206. document.getElementById("Online-List").setAttribute("clip-path","url(#myClip1)");
  207. document.getElementById("Chat").setAttribute("clip-path","url(#myClip2)");
  208. document.getElementById("Clip-Path-Left").setAttribute("transform", "translate(0,0)");
  209. document.getElementById("Clip-Path-Right").setAttribute("transform", "translate(0,0)");
  210. document.getElementById('Player-Statistics').style.display = 'none';
  211. document.getElementById("Right-Bar").setAttribute("fill","skyblue");
  212. document.getElementById("Right-Bar").onmouseover = barHover;
  213. document.getElementById("Right-Bar").onmouseout = barHoverOut;
  214. document.getElementById("Left-Bar").onmouseover = onlineHover;
  215. document.getElementById("Left-Bar").onmouseout = onlineHoverOut;
  216. document.getElementById('edit').setAttribute("contentEditable","true");
  217. document.getElementById('edit').onkeydown = chatEditor;
  218. onRightMenuDown();
  219. }, "Refined");
  220. });
  221. var removeChilds = function (node) {
  222. var last;
  223. while (last = node.lastChild) node.removeChild(last);
  224. };
  225. function onPlayerInfo(evt) {
  226. ws.send(enc(tuple(atom('client'),
  227. tuple(atom('stats_action'),bin(document.user),atom('game_okey')))));
  228. }
  229. function onPlayerInfoClose(evt) {
  230. document.getElementById('Player-Statistics').style.display = 'none';
  231. }
  232. function onRightMenu(evt) {
  233. localStorage.clear();
  234. ["PlayShow","CreateShow"].map(function (x) {
  235. document.getElementById(x+"-Motion").beginElement(); }); }
  236. function onRightMenuDown(evt) {
  237. ["PlayHide","CreateHide"].map(function (x) {
  238. document.getElementById(x+"-Motion").beginElement(); }); }
  239. // SVG Samples for svg.htm
  240. /*
  241. loadFile('templates/Mustafa-Persona.svg', null, "Mustafa-Persona-Sample");
  242. loadFile('templates/Mustafa-Selection.svg', null, "Mustafa-Selection-Sample");
  243. document.getElementById("MustafaSelection").addEventListener('click', function() {
  244. var style = document.getElementById("Mustafa-Selection-Sample").style;
  245. if (style.display == 'none') style.display = 'block';
  246. else style.display = 'none'; });
  247. */
  248. function slotName1(x,y) { return "1Slot-"+y+","+x; }
  249. function drawSampleCards() {
  250. slotName = slotName1;
  251. for (var i=1;i<15;i++) { place_card(i,rand(1,2),rand(1,4),rand(1,13)); }
  252. slotName = slotNameDef; }
  253. var scrollSensitivity = 0.2;
  254. var scroll_left = 5;
  255. var scroll_right = -10000;
  256. function chatMessage(id, me, string) {
  257. var i=0;
  258. var colors=['#FDFDFD','#DFF1F4'];
  259. var x1 = 7;
  260. var y1 = 0;
  261. var translate_y = parseFloat(document.getElementById("Chat").getBBox().height);
  262. var x2 = 205;
  263. var textElement = chatText(id,me,string);
  264. var dy = translate_y == 0 ? 0 : translate_y + 10;
  265. var html = "<g xmlns='http://www.w3.org/2000/svg' " +
  266. "id='Message-"+id+"' transform='translate(0,"+dy+")'></g>";
  267. var messageElement = svg(html);
  268. messageElement.appendChild(textElement);
  269. document.getElementById("Chat").appendChild(messageElement);
  270. create_multiline(textElement);
  271. var y2 = textElement.getBBox().height + 5;
  272. var box = "<path xmlns='http://www.w3.org/2000/svg' d='M"+x1+","+y1+
  273. " L"+x2+","+y1+
  274. ((me == "Maxim") ?
  275. (" L"+x2+","+parseFloat(y2-7)+
  276. " L"+parseFloat(x2+7)+","+y2+
  277. " L"+x1+","+y2)
  278. :
  279. (" L"+x2+","+y2+
  280. " L"+0+","+y2+
  281. " L"+x1+","+parseFloat(y2-7)))
  282. + " L"+x1+","+y1+"' fill='"+colors[me=="Maxim"?1:0]+"'></path>";
  283. var boxElement = svg(box);
  284. messageElement.insertBefore(boxElement,textElement);
  285. boxElement.setAttribute("mouseover","barHover(evt);");
  286. boxElement.setAttribute("mouseout","barHoverOut(evt);");
  287. textElement.setAttribute("mouseover","barHover(evt);");
  288. textElement.setAttribute("mouseout","barHoverOut(evt);");
  289. messageElement.setAttribute("onmouseover","barHover(evt);");
  290. messageElement.setAttribute("onmouseout","barHoverOut(evt);");
  291. // console.log(messageElement);
  292. }
  293. function chatText(id, me, string) {
  294. var i = 0;
  295. var colors=['#3B5998'];
  296. var html = "<text id='ChatText-"+id+"' width='180' " +
  297. " xmlns='http://www.w3.org/2000/svg' "+
  298. " font-family='Exo 2' font-size='16' font-weight='normal' fill='"+colors[i]+"'>" +
  299. string + "</text>";
  300. // console.log(html);
  301. return svg(html);
  302. }
  303. function mouseWheelHandler(e) {
  304. var leftBar = document.getElementById("Left-Bar");
  305. var rightBar = document.getElementById("Right-Bar");
  306. var leftFill = leftBar.getAttribute("fill");
  307. var rightFill = rightBar.getAttribute("fill");
  308. var leftActive = leftFill == "skyblue";
  309. var rightActive = rightFill == "skyblue";
  310. if (!leftActive && !rightActive) return;
  311. console.log(leftActive);
  312. var evt = e;
  313. var scroll_dy = evt.detail ? evt.detail * scrollSensitivity : evt.wheelDelta * scrollSensitivity;
  314. var ori = leftActive ? scroll_left : scroll_right;
  315. var scroll = parseFloat(scroll_dy) + parseFloat(ori);
  316. var selectedBar = leftActive ? "Online-List" : "Chat";
  317. var selectedClip = leftActive ? "Clip-Path-Left" : "Clip-Path-Right";
  318. var selectedBarShift = leftActive ? 0 : 857;
  319. var limit = parseFloat(document.getElementById(selectedBar).getBBox().height) - 400;
  320. if (scroll > 5) scroll = 5;
  321. if (scroll < -limit) scroll = -limit;
  322. document.getElementById(selectedClip).setAttribute("transform", "translate(0,"+parseFloat(-scroll)+")");
  323. document.getElementById(selectedBar).setAttribute("transform", "translate("+selectedBarShift+","+(parseFloat(95+scroll))+")");
  324. if (leftActive) scroll_left = scroll; else scroll_right = scroll;
  325. return true;
  326. }
  327. var svgNS = "http://www.w3.org/2000/svg";
  328. function create_multiline(target) {
  329. var text_element = target; // evt.target;
  330. var width = 190; //target.getAttribute("width");
  331. var words = text_element.firstChild.data.split('');
  332. // console.log(words);
  333. // var words = [].concat.apply([],lines.map(function(line) { return line.split(' '); }));;
  334. var start_x = 15; //text_element.getAttribute('x');
  335. text_element.firstChild.data = '';
  336. var tspan_element = document.createElementNS(svgNS, "tspan");
  337. tspan_element.setAttribute("x", start_x);
  338. tspan_element.setAttribute("dy", 18);
  339. var text_node = document.createTextNode(words[0]);
  340. tspan_element.appendChild(text_node);
  341. text_element.appendChild(tspan_element);
  342. for(var i=1; i<words.length; i++) {
  343. if (words[i]=="") continue;
  344. var len = tspan_element.firstChild.data.length;
  345. tspan_element.firstChild.data += words[i];
  346. if (tspan_element.getComputedTextLength() > width || words[i]=="\n") {
  347. if (words[i]=='\n') words[i]="";
  348. tspan_element.firstChild.data = tspan_element.firstChild.data.slice(0, len);
  349. var tspan_element = document.createElementNS(svgNS, "tspan");
  350. tspan_element.setAttribute("x", start_x);
  351. tspan_element.setAttribute("dy", 18);
  352. text_node = document.createTextNode(words[i]);
  353. tspan_element.appendChild(text_node);
  354. text_element.appendChild(tspan_element);
  355. }
  356. }
  357. }
  358. function barHover(evt) { document.getElementById("Right-Bar").setAttribute("fill","skyblue"); }
  359. function barHoverOut(evt) { document.getElementById("Right-Bar").setAttribute("fill","lightblue"); }
  360. function onlineHover(evt) { document.getElementById("Left-Bar").setAttribute("fill","skyblue"); }
  361. function onlineHoverOut(evt) { document.getElementById("Left-Bar").setAttribute("fill","lightblue"); }
  362. function onlineHoverColor(evt) {
  363. onlineHover(evt);
  364. var name = evt.target.getAttribute("xmlns:data");
  365. if (null != name) document.getElementById(name).setAttribute("fill","#FFE0A5");
  366. }
  367. function onlineHoverOutColor(evt) {
  368. onlineHoverOut(evt);
  369. var name = evt.target.getAttribute("xmlns:data");
  370. if (null != name) document.getElementById(name).setAttribute("fill","#DBEBED");
  371. }
  372. function chatEditor(evt) {
  373. if (evt.keyCode == 13 && evt.metaKey == false) {
  374. var e = document.getElementById('edit');
  375. if (e.innerText.trim() != ""){
  376. chatMessage("100","Maxim",e.innerText.trim().encodeHTML());
  377. e.innerHTML = '';
  378. }
  379. } else if (evt.keyCode == 13 && evt.metaKey == true) {
  380. document.execCommand('insertText',false, '\n');
  381. }
  382. var scroll = -1000000;
  383. mouseWheelHandler({'detail':scroll,'wheelDelta':scroll});
  384. }
  385. function addOnlineUser(name,full_name,insertMode) {
  386. var listElement = document.getElementById("Online-List");
  387. var y = listElement.getBBox().height;
  388. // console.log(y);
  389. var html = '<g xmlns="http://www.w3.org/2000/svg" height="60" transform="translate(0, '+y+')">' +
  390. '<g xmlns:data="'+name+'"fill="#DBEBED" onmouseover="onlineHoverColor(evt);" onmouseout="onlineHoverOutColor(evt);">' +
  391. ' <rect xmlns:data="'+name+'"fill="#DBEBED" id="'+name+'" x="10" y="0" width="196" height="48" onmouseover="onlineHoverColor(evt);" onmouseout="onlineHoverOutColor(evt);"></rect></g>' +
  392. '<text xmlns:data="'+name+'" onmouseover="onlineHoverColor(evt);" onmouseout="onlineHoverOutColor(evt);" '+
  393. 'font-family="Exo 2" font-size="18" font-weight="normal" line-spacing="18"'+
  394. ' fill="#3B5998">' +
  395. '<tspan xmlns:data="'+name+'" font-weight="bold" fill="green" x="19" y="22">'+full_name+'</tspan>' +
  396. '<tspan xmlns:data="'+name+'" x="19" y="40">Score: 1043 Pos: 13</tspan></text>'+
  397. '<rect onmouseover="onlineHover(evt);" onmouseout="onlineHoverOut(evt);"'+
  398. ' x="10" y="48" width="196" height="8"></rect></g>';
  399. var element = svg(html);
  400. // element.setAttribute("mouseover","onlineHoverColor(evt);");
  401. // element.setAttribute("mouseout","onlineHoverOutColor(evt);");
  402. // console.log(element);
  403. listElement.appendChild(element);
  404. }
  405. chatMessage("1","Maxim2","Joe:\nHello There!".encodeHTML());
  406. chatMessage("2","Maxim2","Alice:\nYou got new Design. Eh?".encodeHTML());
  407. chatMessage("3","Maxim","Maxim So:\nThis was made with pure SVG".encodeHTML());
  408. for (var i=0;i<5;i++) {
  409. addOnlineUser("Maxim1"+i,"Maxim Sokhatsky",'appendChild');
  410. addOnlineUser("Maxim2"+i,"Sinan Ustel",'appendChild');
  411. addOnlineUser("Maxim3"+i,"Ahmet Tez",'appendChild');
  412. addOnlineUser("Maxim4"+i,"Alice Cooper",'appendChild');
  413. }
  414. barHover();
  415. mouseWheelHandler({'detail':-100000,'wheelDelta':-100000});
  416. barHoverOut();
  417. onlineHover();
  418. mouseWheelHandler({'detail':5,'wheelDelta':5});
  419. onlineHoverOut();