utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 if (window.localStorage.getItem('showDesktopDragHandles')) {
  233. return true;
  234. } else {
  235. return false;
  236. }
  237. },
  238. // returns if mini screen or desktop drag handles
  239. isMiniScreenOrShowDesktopDragHandles() {
  240. return this.isMiniScreen() || this.isShowDesktopDragHandles();
  241. },
  242. calculateIndexData(prevData, nextData, nItems = 1) {
  243. let base, increment;
  244. // If we drop the card to an empty column
  245. if (!prevData && !nextData) {
  246. base = 0;
  247. increment = 1;
  248. // If we drop the card in the first position
  249. } else if (!prevData) {
  250. base = nextData.sort - 1;
  251. increment = -1;
  252. // If we drop the card in the last position
  253. } else if (!nextData) {
  254. base = prevData.sort + 1;
  255. increment = 1;
  256. }
  257. // In the general case take the average of the previous and next element
  258. // sort indexes.
  259. else {
  260. const prevSortIndex = prevData.sort;
  261. const nextSortIndex = nextData.sort;
  262. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  263. base = prevSortIndex + increment;
  264. }
  265. // XXX Return a generator that yield values instead of a base with a
  266. // increment number.
  267. return {
  268. base,
  269. increment,
  270. };
  271. },
  272. // Determine the new sort index
  273. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  274. let base, increment;
  275. // If we drop the card to an empty column
  276. if (!prevCardDomElement && !nextCardDomElement) {
  277. base = 0;
  278. increment = 1;
  279. // If we drop the card in the first position
  280. } else if (!prevCardDomElement) {
  281. base = Blaze.getData(nextCardDomElement).sort - 1;
  282. increment = -1;
  283. // If we drop the card in the last position
  284. } else if (!nextCardDomElement) {
  285. base = Blaze.getData(prevCardDomElement).sort + 1;
  286. increment = 1;
  287. }
  288. // In the general case take the average of the previous and next element
  289. // sort indexes.
  290. else {
  291. const prevSortIndex = Blaze.getData(prevCardDomElement).sort;
  292. const nextSortIndex = Blaze.getData(nextCardDomElement).sort;
  293. increment = (nextSortIndex - prevSortIndex) / (nCards + 1);
  294. base = prevSortIndex + increment;
  295. }
  296. // XXX Return a generator that yield values instead of a base with a
  297. // increment number.
  298. return {
  299. base,
  300. increment,
  301. };
  302. },
  303. // Detect touch device
  304. isTouchDevice() {
  305. const isTouchable = (() => {
  306. const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  307. const mq = function(query) {
  308. return window.matchMedia(query).matches;
  309. };
  310. if (
  311. 'ontouchstart' in window ||
  312. (window.DocumentTouch && document instanceof window.DocumentTouch)
  313. ) {
  314. return true;
  315. }
  316. // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  317. // https://git.io/vznFH
  318. const query = [
  319. '(',
  320. prefixes.join('touch-enabled),('),
  321. 'heartz',
  322. ')',
  323. ].join('');
  324. return mq(query);
  325. })();
  326. Utils.isTouchDevice = () => isTouchable;
  327. return isTouchable;
  328. },
  329. calculateTouchDistance(touchA, touchB) {
  330. return Math.sqrt(
  331. Math.pow(touchA.screenX - touchB.screenX, 2) +
  332. Math.pow(touchA.screenY - touchB.screenY, 2),
  333. );
  334. },
  335. enableClickOnTouch(selector) {
  336. let touchStart = null;
  337. let lastTouch = null;
  338. $(document).on('touchstart', selector, function(e) {
  339. touchStart = e.originalEvent.touches[0];
  340. });
  341. $(document).on('touchmove', selector, function(e) {
  342. const touches = e.originalEvent.touches;
  343. lastTouch = touches[touches.length - 1];
  344. });
  345. $(document).on('touchend', selector, function(e) {
  346. if (
  347. touchStart &&
  348. lastTouch &&
  349. Utils.calculateTouchDistance(touchStart, lastTouch) <= 20
  350. ) {
  351. e.preventDefault();
  352. const clickEvent = document.createEvent('MouseEvents');
  353. clickEvent.initEvent('click', true, true);
  354. e.target.dispatchEvent(clickEvent);
  355. }
  356. });
  357. },
  358. manageCustomUI() {
  359. Meteor.call('getCustomUI', (err, data) => {
  360. if (err && err.error[0] === 'var-not-exist') {
  361. Session.set('customUI', false); // siteId || address server not defined
  362. }
  363. if (!err) {
  364. Utils.setCustomUI(data);
  365. }
  366. });
  367. },
  368. setCustomUI(data) {
  369. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  370. if (currentBoard) {
  371. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  372. } else {
  373. DocHead.setTitle(`${data.productName}`);
  374. }
  375. },
  376. setMatomo(data) {
  377. window._paq = window._paq || [];
  378. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  379. if (data.withUserName) {
  380. window._paq.push(['setUserId', Meteor.user().username]);
  381. }
  382. window._paq.push(['trackPageView']);
  383. window._paq.push(['enableLinkTracking']);
  384. (function() {
  385. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  386. window._paq.push(['setSiteId', data.siteId]);
  387. const script = document.createElement('script');
  388. Object.assign(script, {
  389. id: 'scriptMatomo',
  390. type: 'text/javascript',
  391. async: 'true',
  392. defer: 'true',
  393. src: `${data.address}piwik.js`,
  394. });
  395. const s = document.getElementsByTagName('script')[0];
  396. s.parentNode.insertBefore(script, s);
  397. })();
  398. Session.set('matomo', true);
  399. },
  400. manageMatomo() {
  401. const matomo = Session.get('matomo');
  402. if (matomo === undefined) {
  403. Meteor.call('getMatomoConf', (err, data) => {
  404. if (err && err.error[0] === 'var-not-exist') {
  405. Session.set('matomo', false); // siteId || address server not defined
  406. }
  407. if (!err) {
  408. Utils.setMatomo(data);
  409. }
  410. });
  411. } else if (matomo) {
  412. window._paq.push(['trackPageView']);
  413. }
  414. },
  415. getTriggerActionDesc(event, tempInstance) {
  416. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  417. const triggerEls = jqueryEl.find('.trigger-content').children();
  418. let finalString = '';
  419. for (let i = 0; i < triggerEls.length; i++) {
  420. const element = tempInstance.$(triggerEls[i]);
  421. if (element.hasClass('trigger-text')) {
  422. finalString += element.text().toLowerCase();
  423. } else if (element.hasClass('user-details')) {
  424. let username = element.find('input').val();
  425. if (username === undefined || username === '') {
  426. username = '*';
  427. }
  428. finalString += `${element
  429. .find('.trigger-text')
  430. .text()
  431. .toLowerCase()} ${username}`;
  432. } else if (element.find('select').length > 0) {
  433. finalString += element
  434. .find('select option:selected')
  435. .text()
  436. .toLowerCase();
  437. } else if (element.find('input').length > 0) {
  438. let inputvalue = element.find('input').val();
  439. if (inputvalue === undefined || inputvalue === '') {
  440. inputvalue = '*';
  441. }
  442. finalString += inputvalue;
  443. }
  444. // Add space
  445. if (i !== length - 1) {
  446. finalString += ' ';
  447. }
  448. }
  449. return finalString;
  450. },
  451. };
  452. // A simple tracker dependency that we invalidate every time the window is
  453. // resized. This is used to reactively re-calculate the popup position in case
  454. // of a window resize. This is the equivalent of a "Signal" in some other
  455. // programming environments (eg, elm).
  456. $(window).on('resize', () => Utils.windowResizeDep.changed());