utils.js 10 KB

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