utils.js 15 KB

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