2
0

utils.js 14 KB

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