utils.js 12 KB

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