utils.js 14 KB

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