utils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. myCardsSortToggle() {
  54. if (this.myCardsSort() === 'board') {
  55. this.setMyCardsSort('dueAt');
  56. } else {
  57. this.setMyCardsSort('board');
  58. }
  59. },
  60. setMyCardsSort(sort) {
  61. window.localStorage.setItem('myCardsSort', sort);
  62. location.reload();
  63. },
  64. archivedBoardIds() {
  65. const archivedBoards = [];
  66. Boards.find({ archived: false }).forEach(board => {
  67. archivedBoards.push(board._id);
  68. });
  69. return archivedBoards;
  70. },
  71. dueCardsView() {
  72. let view = window.localStorage.getItem('dueCardsView');
  73. if (!view || !['user', 'all'].includes(view)) {
  74. window.localStorage.setItem('dueCardsView', 'user');
  75. location.reload();
  76. view = 'user';
  77. }
  78. return view;
  79. },
  80. dueBoardsSelector() {
  81. const user = Meteor.user();
  82. const selector = {
  83. archived: false,
  84. };
  85. // if user is not an admin allow her to see cards only from boards where
  86. // she is a member
  87. if (!user.isAdmin()) {
  88. selector.$or = [
  89. { permission: 'public' },
  90. { members: { $elemMatch: { userId: user._id, isActive: true } } },
  91. ];
  92. }
  93. return selector;
  94. },
  95. dueCardsSelector() {
  96. const user = Meteor.user();
  97. const selector = {
  98. archived: false,
  99. };
  100. // if user is not an admin allow her to see cards only from boards where
  101. // she is a member
  102. if (!user.isAdmin()) {
  103. selector.$or = [
  104. { permission: 'public' },
  105. { members: { $elemMatch: { userId: user._id, isActive: true } } },
  106. ];
  107. }
  108. return selector;
  109. },
  110. // XXX We should remove these two methods
  111. goBoardId(_id) {
  112. const board = Boards.findOne(_id);
  113. return (
  114. board &&
  115. FlowRouter.go('board', {
  116. id: board._id,
  117. slug: board.slug,
  118. })
  119. );
  120. },
  121. goCardId(_id) {
  122. const card = Cards.findOne(_id);
  123. const board = Boards.findOne(card.boardId);
  124. return (
  125. board &&
  126. FlowRouter.go('card', {
  127. cardId: card._id,
  128. boardId: board._id,
  129. slug: board.slug,
  130. })
  131. );
  132. },
  133. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  134. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  135. processUploadedAttachment(card, fileObj, callback) {
  136. const next = attachment => {
  137. if (typeof callback === 'function') {
  138. callback(attachment);
  139. }
  140. };
  141. if (!card) {
  142. return next();
  143. }
  144. const file = new FS.File(fileObj);
  145. if (card.isLinkedCard()) {
  146. file.boardId = Cards.findOne(card.linkedId).boardId;
  147. file.cardId = card.linkedId;
  148. } else {
  149. file.boardId = card.boardId;
  150. file.swimlaneId = card.swimlaneId;
  151. file.listId = card.listId;
  152. file.cardId = card._id;
  153. }
  154. file.userId = Meteor.userId();
  155. if (file.original) {
  156. file.original.name = fileObj.name;
  157. }
  158. return next(Attachments.insert(file));
  159. },
  160. shrinkImage(options) {
  161. // shrink image to certain size
  162. const dataurl = options.dataurl,
  163. callback = options.callback,
  164. toBlob = options.toBlob;
  165. let canvas = document.createElement('canvas'),
  166. image = document.createElement('img');
  167. const maxSize = options.maxSize || 1024;
  168. const ratio = options.ratio || 1.0;
  169. const next = function(result) {
  170. image = null;
  171. canvas = null;
  172. if (typeof callback === 'function') {
  173. callback(result);
  174. }
  175. };
  176. image.onload = function() {
  177. let width = this.width,
  178. height = this.height;
  179. let changed = false;
  180. if (width > height) {
  181. if (width > maxSize) {
  182. height *= maxSize / width;
  183. width = maxSize;
  184. changed = true;
  185. }
  186. } else if (height > maxSize) {
  187. width *= maxSize / height;
  188. height = maxSize;
  189. changed = true;
  190. }
  191. canvas.width = width;
  192. canvas.height = height;
  193. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  194. if (changed === true) {
  195. const type = 'image/jpeg';
  196. if (toBlob) {
  197. canvas.toBlob(next, type, ratio);
  198. } else {
  199. next(canvas.toDataURL(type, ratio));
  200. }
  201. } else {
  202. next(changed);
  203. }
  204. };
  205. image.onerror = function() {
  206. next(false);
  207. };
  208. image.src = dataurl;
  209. },
  210. capitalize(string) {
  211. return string.charAt(0).toUpperCase() + string.slice(1);
  212. },
  213. windowResizeDep: new Tracker.Dependency(),
  214. // in fact, what we really care is screen size
  215. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  216. // in a small window (even on desktop), Wekan run in compact mode.
  217. // we can easily debug with a small window of desktop browser. :-)
  218. isMiniScreen() {
  219. // OLD WINDOW WIDTH DETECTION:
  220. this.windowResizeDep.depend();
  221. return $(window).width() <= 800;
  222. // NEW TOUCH DEVICE DETECTION:
  223. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  224. /*
  225. var hasTouchScreen = false;
  226. if ("maxTouchPoints" in navigator) {
  227. hasTouchScreen = navigator.maxTouchPoints > 0;
  228. } else if ("msMaxTouchPoints" in navigator) {
  229. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  230. } else {
  231. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  232. if (mQ && mQ.media === "(pointer:coarse)") {
  233. hasTouchScreen = !!mQ.matches;
  234. } else if ('orientation' in window) {
  235. hasTouchScreen = true; // deprecated, but good fallback
  236. } else {
  237. // Only as a last resort, fall back to user agent sniffing
  238. var UA = navigator.userAgent;
  239. hasTouchScreen = (
  240. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  241. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  242. );
  243. }
  244. }
  245. */
  246. //if (hasTouchScreen)
  247. // document.getElementById("exampleButton").style.padding="1em";
  248. //return false;
  249. },
  250. // returns if desktop drag handles are enabled
  251. isShowDesktopDragHandles() {
  252. const currentUser = Meteor.user();
  253. if (currentUser) {
  254. return (currentUser.profile || {}).showDesktopDragHandles;
  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());