utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. Utils = {
  2. setBoardView(view) {
  3. currentUser = Meteor.user();
  4. if (currentUser) {
  5. Meteor.user().setBoardView(view);
  6. } else if (view === 'board-view-swimlanes') {
  7. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  8. location.reload();
  9. } else if (view === 'board-view-lists') {
  10. window.localStorage.setItem('boardView', 'board-view-lists'); //true
  11. location.reload();
  12. } else if (view === 'board-view-cal') {
  13. window.localStorage.setItem('boardView', 'board-view-cal'); //true
  14. location.reload();
  15. } else {
  16. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  17. location.reload();
  18. }
  19. },
  20. unsetBoardView() {
  21. window.localStorage.removeItem('boardView');
  22. window.localStorage.removeItem('collapseSwimlane');
  23. },
  24. boardView() {
  25. currentUser = Meteor.user();
  26. if (currentUser) {
  27. return (currentUser.profile || {}).boardView;
  28. } else if (
  29. window.localStorage.getItem('boardView') === 'board-view-swimlanes'
  30. ) {
  31. return 'board-view-swimlanes';
  32. } else if (
  33. window.localStorage.getItem('boardView') === 'board-view-lists'
  34. ) {
  35. return 'board-view-lists';
  36. } else if (window.localStorage.getItem('boardView') === 'board-view-cal') {
  37. return 'board-view-cal';
  38. } else {
  39. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  40. location.reload();
  41. return 'board-view-swimlanes';
  42. }
  43. },
  44. // XXX We should remove these two methods
  45. goBoardId(_id) {
  46. const board = Boards.findOne(_id);
  47. return (
  48. board &&
  49. FlowRouter.go('board', {
  50. id: board._id,
  51. slug: board.slug,
  52. })
  53. );
  54. },
  55. goCardId(_id) {
  56. const card = Cards.findOne(_id);
  57. const board = Boards.findOne(card.boardId);
  58. return (
  59. board &&
  60. FlowRouter.go('card', {
  61. cardId: card._id,
  62. boardId: board._id,
  63. slug: board.slug,
  64. })
  65. );
  66. },
  67. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  68. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  69. processUploadedAttachment(card, fileObj, callback) {
  70. const next = attachment => {
  71. if (typeof callback === 'function') {
  72. callback(attachment);
  73. }
  74. };
  75. if (!card) {
  76. return next();
  77. }
  78. const file = new FS.File(fileObj);
  79. if (card.isLinkedCard()) {
  80. file.boardId = Cards.findOne(card.linkedId).boardId;
  81. file.cardId = card.linkedId;
  82. } else {
  83. file.boardId = card.boardId;
  84. file.swimlaneId = card.swimlaneId;
  85. file.listId = card.listId;
  86. file.cardId = card._id;
  87. }
  88. file.userId = Meteor.userId();
  89. if (file.original) {
  90. file.original.name = fileObj.name;
  91. }
  92. return next(Attachments.insert(file));
  93. },
  94. shrinkImage(options) {
  95. // shrink image to certain size
  96. const dataurl = options.dataurl,
  97. callback = options.callback,
  98. toBlob = options.toBlob;
  99. let canvas = document.createElement('canvas'),
  100. image = document.createElement('img');
  101. const maxSize = options.maxSize || 1024;
  102. const ratio = options.ratio || 1.0;
  103. const next = function(result) {
  104. image = null;
  105. canvas = null;
  106. if (typeof callback === 'function') {
  107. callback(result);
  108. }
  109. };
  110. image.onload = function() {
  111. let width = this.width,
  112. height = this.height;
  113. let changed = false;
  114. if (width > height) {
  115. if (width > maxSize) {
  116. height *= maxSize / width;
  117. width = maxSize;
  118. changed = true;
  119. }
  120. } else if (height > maxSize) {
  121. width *= maxSize / height;
  122. height = maxSize;
  123. changed = true;
  124. }
  125. canvas.width = width;
  126. canvas.height = height;
  127. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  128. if (changed === true) {
  129. const type = 'image/jpeg';
  130. if (toBlob) {
  131. canvas.toBlob(next, type, ratio);
  132. } else {
  133. next(canvas.toDataURL(type, ratio));
  134. }
  135. } else {
  136. next(changed);
  137. }
  138. };
  139. image.onerror = function() {
  140. next(false);
  141. };
  142. image.src = dataurl;
  143. },
  144. capitalize(string) {
  145. return string.charAt(0).toUpperCase() + string.slice(1);
  146. },
  147. windowResizeDep: new Tracker.Dependency(),
  148. // in fact, what we really care is screen size
  149. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  150. // in a small window (even on desktop), Wekan run in compact mode.
  151. // we can easily debug with a small window of desktop browser. :-)
  152. isMiniScreen() {
  153. // OLD WINDOW WIDTH DETECTION:
  154. this.windowResizeDep.depend();
  155. return $(window).width() <= 800;
  156. // NEW TOUCH DEVICE DETECTION:
  157. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  158. /*
  159. var hasTouchScreen = false;
  160. if ("maxTouchPoints" in navigator) {
  161. hasTouchScreen = navigator.maxTouchPoints > 0;
  162. } else if ("msMaxTouchPoints" in navigator) {
  163. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  164. } else {
  165. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  166. if (mQ && mQ.media === "(pointer:coarse)") {
  167. hasTouchScreen = !!mQ.matches;
  168. } else if ('orientation' in window) {
  169. hasTouchScreen = true; // deprecated, but good fallback
  170. } else {
  171. // Only as a last resort, fall back to user agent sniffing
  172. var UA = navigator.userAgent;
  173. hasTouchScreen = (
  174. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  175. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  176. );
  177. }
  178. }
  179. */
  180. //if (hasTouchScreen)
  181. // document.getElementById("exampleButton").style.padding="1em";
  182. //return false;
  183. },
  184. // returns if desktop drag handles are enabled
  185. isShowDesktopDragHandles() {
  186. let currentUser = Meteor.user();
  187. if (currentUser) {
  188. return (currentUser.profile || {}).showDesktopDragHandles;
  189. } else if (cookies.has('showDesktopDragHandles')) {
  190. return true;
  191. } else {
  192. return false;
  193. }
  194. },
  195. // returns if mini screen or desktop drag handles
  196. isMiniScreenOrShowDesktopDragHandles() {
  197. return this.isMiniScreen() || this.isShowDesktopDragHandles()
  198. },
  199. calculateIndexData(prevData, nextData, nItems = 1) {
  200. let base, increment;
  201. // If we drop the card to an empty column
  202. if (!prevData && !nextData) {
  203. base = 0;
  204. increment = 1;
  205. // If we drop the card in the first position
  206. } else if (!prevData) {
  207. base = nextData.sort - 1;
  208. increment = -1;
  209. // If we drop the card in the last position
  210. } else if (!nextData) {
  211. base = prevData.sort + 1;
  212. increment = 1;
  213. }
  214. // In the general case take the average of the previous and next element
  215. // sort indexes.
  216. else {
  217. const prevSortIndex = prevData.sort;
  218. const nextSortIndex = nextData.sort;
  219. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  220. base = prevSortIndex + increment;
  221. }
  222. // XXX Return a generator that yield values instead of a base with a
  223. // increment number.
  224. return {
  225. base,
  226. increment,
  227. };
  228. },
  229. // Determine the new sort index
  230. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  231. let base, increment;
  232. // If we drop the card to an empty column
  233. if (!prevCardDomElement && !nextCardDomElement) {
  234. base = 0;
  235. increment = 1;
  236. // If we drop the card in the first position
  237. } else if (!prevCardDomElement) {
  238. base = Blaze.getData(nextCardDomElement).sort - 1;
  239. increment = -1;
  240. // If we drop the card in the last position
  241. } else if (!nextCardDomElement) {
  242. base = Blaze.getData(prevCardDomElement).sort + 1;
  243. increment = 1;
  244. }
  245. // In the general case take the average of the previous and next element
  246. // sort indexes.
  247. else {
  248. const prevSortIndex = Blaze.getData(prevCardDomElement).sort;
  249. const nextSortIndex = Blaze.getData(nextCardDomElement).sort;
  250. increment = (nextSortIndex - prevSortIndex) / (nCards + 1);
  251. base = prevSortIndex + increment;
  252. }
  253. // XXX Return a generator that yield values instead of a base with a
  254. // increment number.
  255. return {
  256. base,
  257. increment,
  258. };
  259. },
  260. // Detect touch device
  261. isTouchDevice() {
  262. const isTouchable = (() => {
  263. const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  264. const mq = function(query) {
  265. return window.matchMedia(query).matches;
  266. };
  267. if (
  268. 'ontouchstart' in window ||
  269. (window.DocumentTouch && document instanceof window.DocumentTouch)
  270. ) {
  271. return true;
  272. }
  273. // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  274. // https://git.io/vznFH
  275. const query = [
  276. '(',
  277. prefixes.join('touch-enabled),('),
  278. 'heartz',
  279. ')',
  280. ].join('');
  281. return mq(query);
  282. })();
  283. Utils.isTouchDevice = () => isTouchable;
  284. return isTouchable;
  285. },
  286. calculateTouchDistance(touchA, touchB) {
  287. return Math.sqrt(
  288. Math.pow(touchA.screenX - touchB.screenX, 2) +
  289. Math.pow(touchA.screenY - touchB.screenY, 2),
  290. );
  291. },
  292. enableClickOnTouch(selector) {
  293. let touchStart = null;
  294. let lastTouch = null;
  295. $(document).on('touchstart', selector, function(e) {
  296. touchStart = e.originalEvent.touches[0];
  297. });
  298. $(document).on('touchmove', selector, function(e) {
  299. const touches = e.originalEvent.touches;
  300. lastTouch = touches[touches.length - 1];
  301. });
  302. $(document).on('touchend', selector, function(e) {
  303. if (
  304. touchStart &&
  305. lastTouch &&
  306. Utils.calculateTouchDistance(touchStart, lastTouch) <= 20
  307. ) {
  308. e.preventDefault();
  309. const clickEvent = document.createEvent('MouseEvents');
  310. clickEvent.initEvent('click', true, true);
  311. e.target.dispatchEvent(clickEvent);
  312. }
  313. });
  314. },
  315. manageCustomUI() {
  316. Meteor.call('getCustomUI', (err, data) => {
  317. if (err && err.error[0] === 'var-not-exist') {
  318. Session.set('customUI', false); // siteId || address server not defined
  319. }
  320. if (!err) {
  321. Utils.setCustomUI(data);
  322. }
  323. });
  324. },
  325. setCustomUI(data) {
  326. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  327. if (currentBoard) {
  328. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  329. } else {
  330. DocHead.setTitle(`${data.productName}`);
  331. }
  332. },
  333. setMatomo(data) {
  334. window._paq = window._paq || [];
  335. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  336. if (data.withUserName) {
  337. window._paq.push(['setUserId', Meteor.user().username]);
  338. }
  339. window._paq.push(['trackPageView']);
  340. window._paq.push(['enableLinkTracking']);
  341. (function() {
  342. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  343. window._paq.push(['setSiteId', data.siteId]);
  344. const script = document.createElement('script');
  345. Object.assign(script, {
  346. id: 'scriptMatomo',
  347. type: 'text/javascript',
  348. async: 'true',
  349. defer: 'true',
  350. src: `${data.address}piwik.js`,
  351. });
  352. const s = document.getElementsByTagName('script')[0];
  353. s.parentNode.insertBefore(script, s);
  354. })();
  355. Session.set('matomo', true);
  356. },
  357. manageMatomo() {
  358. const matomo = Session.get('matomo');
  359. if (matomo === undefined) {
  360. Meteor.call('getMatomoConf', (err, data) => {
  361. if (err && err.error[0] === 'var-not-exist') {
  362. Session.set('matomo', false); // siteId || address server not defined
  363. }
  364. if (!err) {
  365. Utils.setMatomo(data);
  366. }
  367. });
  368. } else if (matomo) {
  369. window._paq.push(['trackPageView']);
  370. }
  371. },
  372. getTriggerActionDesc(event, tempInstance) {
  373. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  374. const triggerEls = jqueryEl.find('.trigger-content').children();
  375. let finalString = '';
  376. for (let i = 0; i < triggerEls.length; i++) {
  377. const element = tempInstance.$(triggerEls[i]);
  378. if (element.hasClass('trigger-text')) {
  379. finalString += element.text().toLowerCase();
  380. } else if (element.hasClass('user-details')) {
  381. let username = element.find('input').val();
  382. if (username === undefined || username === '') {
  383. username = '*';
  384. }
  385. finalString += `${element
  386. .find('.trigger-text')
  387. .text()
  388. .toLowerCase()} ${username}`;
  389. } else if (element.find('select').length > 0) {
  390. finalString += element
  391. .find('select option:selected')
  392. .text()
  393. .toLowerCase();
  394. } else if (element.find('input').length > 0) {
  395. let inputvalue = element.find('input').val();
  396. if (inputvalue === undefined || inputvalue === '') {
  397. inputvalue = '*';
  398. }
  399. finalString += inputvalue;
  400. }
  401. // Add space
  402. if (i !== length - 1) {
  403. finalString += ' ';
  404. }
  405. }
  406. return finalString;
  407. },
  408. };
  409. // A simple tracker dependency that we invalidate every time the window is
  410. // resized. This is used to reactively re-calculate the popup position in case
  411. // of a window resize. This is the equivalent of a "Signal" in some other
  412. // programming environments (eg, elm).
  413. $(window).on('resize', () => Utils.windowResizeDep.changed());