utils.js 14 KB

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