utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import { Cookies } from 'meteor/ostrio:cookies';
  2. const cookies = new Cookies();
  3. Utils = {
  4. setBoardView(view) {
  5. currentUser = Meteor.user();
  6. if (currentUser) {
  7. Meteor.user().setBoardView(view);
  8. } else if (view === 'board-view-lists') {
  9. cookies.set('boardView', 'board-view-lists'); //true
  10. } else if (view === 'board-view-swimlanes') {
  11. cookies.set('boardView', 'board-view-swimlanes'); //true
  12. } else if (view === 'board-view-cal') {
  13. cookies.set('boardView', 'board-view-cal'); //true
  14. }
  15. },
  16. unsetBoardView() {
  17. cookies.remove('boardView');
  18. cookies.remove('collapseSwimlane');
  19. },
  20. boardView() {
  21. currentUser = Meteor.user();
  22. if (currentUser) {
  23. return (currentUser.profile || {}).boardView;
  24. } else {
  25. if (cookies.get('boardView') === 'board-view-lists') {
  26. return 'board-view-lists';
  27. } else if (
  28. cookies.get('boardView') === 'board-view-swimlanes'
  29. ) {
  30. return 'board-view-swimlanes';
  31. } else if (cookies.get('boardView') === 'board-view-cal') {
  32. return 'board-view-cal';
  33. } else {
  34. return false;
  35. }
  36. }
  37. },
  38. // XXX We should remove these two methods
  39. goBoardId(_id) {
  40. const board = Boards.findOne(_id);
  41. return (
  42. board
  43. && FlowRouter.go('board', {
  44. id: board._id,
  45. slug: board.slug,
  46. })
  47. );
  48. },
  49. goCardId(_id) {
  50. const card = Cards.findOne(_id);
  51. const board = Boards.findOne(card.boardId);
  52. return (
  53. board
  54. && FlowRouter.go('card', {
  55. cardId: card._id,
  56. boardId: board._id,
  57. slug: board.slug,
  58. })
  59. );
  60. },
  61. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  62. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  63. processUploadedAttachment(card, fileObj, callback) {
  64. const next = attachment => {
  65. if (typeof callback === 'function') {
  66. callback(attachment);
  67. }
  68. };
  69. if (!card) {
  70. return next();
  71. }
  72. const file = new FS.File(fileObj);
  73. if (card.isLinkedCard()) {
  74. file.boardId = Cards.findOne(card.linkedId).boardId;
  75. file.cardId = card.linkedId;
  76. } else {
  77. file.boardId = card.boardId;
  78. file.swimlaneId = card.swimlaneId;
  79. file.listId = card.listId;
  80. file.cardId = card._id;
  81. }
  82. file.userId = Meteor.userId();
  83. if (file.original) {
  84. file.original.name = fileObj.name;
  85. }
  86. return next(Attachments.insert(file));
  87. },
  88. shrinkImage(options) {
  89. // shrink image to certain size
  90. const dataurl = options.dataurl,
  91. callback = options.callback,
  92. toBlob = options.toBlob;
  93. let canvas = document.createElement('canvas'),
  94. image = document.createElement('img');
  95. const maxSize = options.maxSize || 1024;
  96. const ratio = options.ratio || 1.0;
  97. const next = function(result) {
  98. image = null;
  99. canvas = null;
  100. if (typeof callback === 'function') {
  101. callback(result);
  102. }
  103. };
  104. image.onload = function() {
  105. let width = this.width,
  106. height = this.height;
  107. let changed = false;
  108. if (width > height) {
  109. if (width > maxSize) {
  110. height *= maxSize / width;
  111. width = maxSize;
  112. changed = true;
  113. }
  114. } else if (height > maxSize) {
  115. width *= maxSize / height;
  116. height = maxSize;
  117. changed = true;
  118. }
  119. canvas.width = width;
  120. canvas.height = height;
  121. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  122. if (changed === true) {
  123. const type = 'image/jpeg';
  124. if (toBlob) {
  125. canvas.toBlob(next, type, ratio);
  126. } else {
  127. next(canvas.toDataURL(type, ratio));
  128. }
  129. } else {
  130. next(changed);
  131. }
  132. };
  133. image.onerror = function() {
  134. next(false);
  135. };
  136. image.src = dataurl;
  137. },
  138. capitalize(string) {
  139. return string.charAt(0).toUpperCase() + string.slice(1);
  140. },
  141. windowResizeDep: new Tracker.Dependency(),
  142. // in fact, what we really care is screen size
  143. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  144. // in a small window (even on desktop), Wekan run in compact mode.
  145. // we can easily debug with a small window of desktop browser. :-)
  146. isMiniScreen() {
  147. this.windowResizeDep.depend();
  148. return $(window).width() <= 800;
  149. },
  150. calculateIndexData(prevData, nextData, nItems = 1) {
  151. let base, increment;
  152. // If we drop the card to an empty column
  153. if (!prevData && !nextData) {
  154. base = 0;
  155. increment = 1;
  156. // If we drop the card in the first position
  157. } else if (!prevData) {
  158. base = nextData.sort - 1;
  159. increment = -1;
  160. // If we drop the card in the last position
  161. } else if (!nextData) {
  162. base = prevData.sort + 1;
  163. increment = 1;
  164. }
  165. // In the general case take the average of the previous and next element
  166. // sort indexes.
  167. else {
  168. const prevSortIndex = prevData.sort;
  169. const nextSortIndex = nextData.sort;
  170. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  171. base = prevSortIndex + increment;
  172. }
  173. // XXX Return a generator that yield values instead of a base with a
  174. // increment number.
  175. return {
  176. base,
  177. increment,
  178. };
  179. },
  180. // Determine the new sort index
  181. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  182. let base, increment;
  183. // If we drop the card to an empty column
  184. if (!prevCardDomElement && !nextCardDomElement) {
  185. base = 0;
  186. increment = 1;
  187. // If we drop the card in the first position
  188. } else if (!prevCardDomElement) {
  189. base = Blaze.getData(nextCardDomElement).sort - 1;
  190. increment = -1;
  191. // If we drop the card in the last position
  192. } else if (!nextCardDomElement) {
  193. base = Blaze.getData(prevCardDomElement).sort + 1;
  194. increment = 1;
  195. }
  196. // In the general case take the average of the previous and next element
  197. // sort indexes.
  198. else {
  199. const prevSortIndex = Blaze.getData(prevCardDomElement).sort;
  200. const nextSortIndex = Blaze.getData(nextCardDomElement).sort;
  201. increment = (nextSortIndex - prevSortIndex) / (nCards + 1);
  202. base = prevSortIndex + increment;
  203. }
  204. // XXX Return a generator that yield values instead of a base with a
  205. // increment number.
  206. return {
  207. base,
  208. increment,
  209. };
  210. },
  211. // Detect touch device
  212. isTouchDevice() {
  213. const isTouchable = (() => {
  214. const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  215. const mq = function(query) {
  216. return window.matchMedia(query).matches;
  217. };
  218. if (
  219. 'ontouchstart' in window
  220. || (window.DocumentTouch && document instanceof window.DocumentTouch)
  221. ) {
  222. return true;
  223. }
  224. // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  225. // https://git.io/vznFH
  226. const query = [
  227. '(',
  228. prefixes.join('touch-enabled),('),
  229. 'heartz',
  230. ')',
  231. ].join('');
  232. return mq(query);
  233. })();
  234. Utils.isTouchDevice = () => isTouchable;
  235. return isTouchable;
  236. },
  237. calculateTouchDistance(touchA, touchB) {
  238. return Math.sqrt(
  239. Math.pow(touchA.screenX - touchB.screenX, 2)
  240. + Math.pow(touchA.screenY - touchB.screenY, 2),
  241. );
  242. },
  243. enableClickOnTouch(selector) {
  244. let touchStart = null;
  245. let lastTouch = null;
  246. $(document).on('touchstart', selector, function(e) {
  247. touchStart = e.originalEvent.touches[0];
  248. });
  249. $(document).on('touchmove', selector, function(e) {
  250. const touches = e.originalEvent.touches;
  251. lastTouch = touches[touches.length - 1];
  252. });
  253. $(document).on('touchend', selector, function(e) {
  254. if (
  255. touchStart
  256. && lastTouch
  257. && Utils.calculateTouchDistance(touchStart, lastTouch) <= 20
  258. ) {
  259. e.preventDefault();
  260. const clickEvent = document.createEvent('MouseEvents');
  261. clickEvent.initEvent('click', true, true);
  262. e.target.dispatchEvent(clickEvent);
  263. }
  264. });
  265. },
  266. manageCustomUI() {
  267. Meteor.call('getCustomUI', (err, data) => {
  268. if (err && err.error[0] === 'var-not-exist') {
  269. Session.set('customUI', false); // siteId || address server not defined
  270. }
  271. if (!err) {
  272. Utils.setCustomUI(data);
  273. }
  274. });
  275. },
  276. setCustomUI(data) {
  277. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  278. if (currentBoard) {
  279. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  280. } else {
  281. DocHead.setTitle(`${data.productName}`);
  282. }
  283. },
  284. setMatomo(data) {
  285. window._paq = window._paq || [];
  286. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  287. if (data.withUserName) {
  288. window._paq.push(['setUserId', Meteor.user().username]);
  289. }
  290. window._paq.push(['trackPageView']);
  291. window._paq.push(['enableLinkTracking']);
  292. (function() {
  293. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  294. window._paq.push(['setSiteId', data.siteId]);
  295. const script = document.createElement('script');
  296. Object.assign(script, {
  297. id: 'scriptMatomo',
  298. type: 'text/javascript',
  299. async: 'true',
  300. defer: 'true',
  301. src: `${data.address}piwik.js`,
  302. });
  303. const s = document.getElementsByTagName('script')[0];
  304. s.parentNode.insertBefore(script, s);
  305. })();
  306. Session.set('matomo', true);
  307. },
  308. manageMatomo() {
  309. const matomo = Session.get('matomo');
  310. if (matomo === undefined) {
  311. Meteor.call('getMatomoConf', (err, data) => {
  312. if (err && err.error[0] === 'var-not-exist') {
  313. Session.set('matomo', false); // siteId || address server not defined
  314. }
  315. if (!err) {
  316. Utils.setMatomo(data);
  317. }
  318. });
  319. } else if (matomo) {
  320. window._paq.push(['trackPageView']);
  321. }
  322. },
  323. getTriggerActionDesc(event, tempInstance) {
  324. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  325. const triggerEls = jqueryEl.find('.trigger-content').children();
  326. let finalString = '';
  327. for (let i = 0; i < triggerEls.length; i++) {
  328. const element = tempInstance.$(triggerEls[i]);
  329. if (element.hasClass('trigger-text')) {
  330. finalString += element.text().toLowerCase();
  331. } else if (element.hasClass('user-details')) {
  332. let username = element.find('input').val();
  333. if (username === undefined || username === '') {
  334. username = '*';
  335. }
  336. finalString += `${element
  337. .find('.trigger-text')
  338. .text()
  339. .toLowerCase()} ${username}`;
  340. } else if (element.find('select').length > 0) {
  341. finalString += element
  342. .find('select option:selected')
  343. .text()
  344. .toLowerCase();
  345. } else if (element.find('input').length > 0) {
  346. let inputvalue = element.find('input').val();
  347. if (inputvalue === undefined || inputvalue === '') {
  348. inputvalue = '*';
  349. }
  350. finalString += inputvalue;
  351. }
  352. // Add space
  353. if (i !== length - 1) {
  354. finalString += ' ';
  355. }
  356. }
  357. return finalString;
  358. },
  359. };
  360. // A simple tracker dependency that we invalidate every time the window is
  361. // resized. This is used to reactively re-calculate the popup position in case
  362. // of a window resize. This is the equivalent of a "Signal" in some other
  363. // programming environments (eg, elm).
  364. $(window).on('resize', () => Utils.windowResizeDep.changed());