utils.js 14 KB

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