utils.js 12 KB

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