utils.js 11 KB

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