utils.js 12 KB

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