utils.js 16 KB

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