utils.js 10 KB

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