utils.js 9.5 KB

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