utils.js 14 KB

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