utils.js 12 KB

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