utils.js 10 KB

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