utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. Utils = {
  2. setBoardView(view) {
  3. currentUser = Meteor.user();
  4. if (currentUser) {
  5. Meteor.user().setBoardView(view);
  6. } else if (view === 'board-view-swimlanes') {
  7. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  8. location.reload();
  9. } else if (view === 'board-view-lists') {
  10. window.localStorage.setItem('boardView', 'board-view-lists'); //true
  11. location.reload();
  12. } else if (view === 'board-view-cal') {
  13. window.localStorage.setItem('boardView', 'board-view-cal'); //true
  14. location.reload();
  15. } else {
  16. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  17. location.reload();
  18. }
  19. },
  20. unsetBoardView() {
  21. window.localStorage.removeItem('boardView');
  22. window.localStorage.removeItem('collapseSwimlane');
  23. },
  24. boardView() {
  25. currentUser = Meteor.user();
  26. if (currentUser) {
  27. return (currentUser.profile || {}).boardView;
  28. } else if (
  29. window.localStorage.getItem('boardView') === 'board-view-swimlanes'
  30. ) {
  31. return 'board-view-swimlanes';
  32. } else if (
  33. window.localStorage.getItem('boardView') === 'board-view-lists'
  34. ) {
  35. return 'board-view-lists';
  36. } else if (window.localStorage.getItem('boardView') === 'board-view-cal') {
  37. return 'board-view-cal';
  38. } else {
  39. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  40. location.reload();
  41. return 'board-view-swimlanes';
  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. // OLD WINDOW WIDTH DETECTION:
  154. this.windowResizeDep.depend();
  155. return $(window).width() <= 800;
  156. // NEW TOUCH DEVICE DETECTION:
  157. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  158. /*
  159. var hasTouchScreen = false;
  160. if ("maxTouchPoints" in navigator) {
  161. hasTouchScreen = navigator.maxTouchPoints > 0;
  162. } else if ("msMaxTouchPoints" in navigator) {
  163. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  164. } else {
  165. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  166. if (mQ && mQ.media === "(pointer:coarse)") {
  167. hasTouchScreen = !!mQ.matches;
  168. } else if ('orientation' in window) {
  169. hasTouchScreen = true; // deprecated, but good fallback
  170. } else {
  171. // Only as a last resort, fall back to user agent sniffing
  172. var UA = navigator.userAgent;
  173. hasTouchScreen = (
  174. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  175. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  176. );
  177. }
  178. }
  179. */
  180. //if (hasTouchScreen)
  181. // document.getElementById("exampleButton").style.padding="1em";
  182. //return false;
  183. },
  184. // returns if desktop drag handles are enabled
  185. isShowDesktopDragHandles() {
  186. const currentUser = Meteor.user();
  187. if (currentUser) {
  188. return (currentUser.profile || {}).showDesktopDragHandles;
  189. } else {
  190. return false;
  191. }
  192. },
  193. // returns if mini screen or desktop drag handles
  194. isMiniScreenOrShowDesktopDragHandles() {
  195. return this.isMiniScreen() || this.isShowDesktopDragHandles();
  196. },
  197. calculateIndexData(prevData, nextData, nItems = 1) {
  198. let base, increment;
  199. // If we drop the card to an empty column
  200. if (!prevData && !nextData) {
  201. base = 0;
  202. increment = 1;
  203. // If we drop the card in the first position
  204. } else if (!prevData) {
  205. base = nextData.sort - 1;
  206. increment = -1;
  207. // If we drop the card in the last position
  208. } else if (!nextData) {
  209. base = prevData.sort + 1;
  210. increment = 1;
  211. }
  212. // In the general case take the average of the previous and next element
  213. // sort indexes.
  214. else {
  215. const prevSortIndex = prevData.sort;
  216. const nextSortIndex = nextData.sort;
  217. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  218. base = prevSortIndex + increment;
  219. }
  220. // XXX Return a generator that yield values instead of a base with a
  221. // increment number.
  222. return {
  223. base,
  224. increment,
  225. };
  226. },
  227. // Determine the new sort index
  228. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  229. let base, increment;
  230. // If we drop the card to an empty column
  231. if (!prevCardDomElement && !nextCardDomElement) {
  232. base = 0;
  233. increment = 1;
  234. // If we drop the card in the first position
  235. } else if (!prevCardDomElement) {
  236. base = Blaze.getData(nextCardDomElement).sort - 1;
  237. increment = -1;
  238. // If we drop the card in the last position
  239. } else if (!nextCardDomElement) {
  240. base = Blaze.getData(prevCardDomElement).sort + 1;
  241. increment = 1;
  242. }
  243. // In the general case take the average of the previous and next element
  244. // sort indexes.
  245. else {
  246. const prevSortIndex = Blaze.getData(prevCardDomElement).sort;
  247. const nextSortIndex = Blaze.getData(nextCardDomElement).sort;
  248. increment = (nextSortIndex - prevSortIndex) / (nCards + 1);
  249. base = prevSortIndex + increment;
  250. }
  251. // XXX Return a generator that yield values instead of a base with a
  252. // increment number.
  253. return {
  254. base,
  255. increment,
  256. };
  257. },
  258. // Detect touch device
  259. isTouchDevice() {
  260. const isTouchable = (() => {
  261. const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  262. const mq = function(query) {
  263. return window.matchMedia(query).matches;
  264. };
  265. if (
  266. 'ontouchstart' in window ||
  267. (window.DocumentTouch && document instanceof window.DocumentTouch)
  268. ) {
  269. return true;
  270. }
  271. // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  272. // https://git.io/vznFH
  273. const query = [
  274. '(',
  275. prefixes.join('touch-enabled),('),
  276. 'heartz',
  277. ')',
  278. ].join('');
  279. return mq(query);
  280. })();
  281. Utils.isTouchDevice = () => isTouchable;
  282. return isTouchable;
  283. },
  284. calculateTouchDistance(touchA, touchB) {
  285. return Math.sqrt(
  286. Math.pow(touchA.screenX - touchB.screenX, 2) +
  287. Math.pow(touchA.screenY - touchB.screenY, 2),
  288. );
  289. },
  290. enableClickOnTouch(selector) {
  291. let touchStart = null;
  292. let lastTouch = null;
  293. $(document).on('touchstart', selector, function(e) {
  294. touchStart = e.originalEvent.touches[0];
  295. });
  296. $(document).on('touchmove', selector, function(e) {
  297. const touches = e.originalEvent.touches;
  298. lastTouch = touches[touches.length - 1];
  299. });
  300. $(document).on('touchend', selector, function(e) {
  301. if (
  302. touchStart &&
  303. lastTouch &&
  304. Utils.calculateTouchDistance(touchStart, lastTouch) <= 20
  305. ) {
  306. e.preventDefault();
  307. const clickEvent = document.createEvent('MouseEvents');
  308. clickEvent.initEvent('click', true, true);
  309. e.target.dispatchEvent(clickEvent);
  310. }
  311. });
  312. },
  313. manageCustomUI() {
  314. Meteor.call('getCustomUI', (err, data) => {
  315. if (err && err.error[0] === 'var-not-exist') {
  316. Session.set('customUI', false); // siteId || address server not defined
  317. }
  318. if (!err) {
  319. Utils.setCustomUI(data);
  320. }
  321. });
  322. },
  323. setCustomUI(data) {
  324. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  325. if (currentBoard) {
  326. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  327. } else {
  328. DocHead.setTitle(`${data.productName}`);
  329. }
  330. },
  331. setMatomo(data) {
  332. window._paq = window._paq || [];
  333. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  334. if (data.withUserName) {
  335. window._paq.push(['setUserId', Meteor.user().username]);
  336. }
  337. window._paq.push(['trackPageView']);
  338. window._paq.push(['enableLinkTracking']);
  339. (function() {
  340. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  341. window._paq.push(['setSiteId', data.siteId]);
  342. const script = document.createElement('script');
  343. Object.assign(script, {
  344. id: 'scriptMatomo',
  345. type: 'text/javascript',
  346. async: 'true',
  347. defer: 'true',
  348. src: `${data.address}piwik.js`,
  349. });
  350. const s = document.getElementsByTagName('script')[0];
  351. s.parentNode.insertBefore(script, s);
  352. })();
  353. Session.set('matomo', true);
  354. },
  355. manageMatomo() {
  356. const matomo = Session.get('matomo');
  357. if (matomo === undefined) {
  358. Meteor.call('getMatomoConf', (err, data) => {
  359. if (err && err.error[0] === 'var-not-exist') {
  360. Session.set('matomo', false); // siteId || address server not defined
  361. }
  362. if (!err) {
  363. Utils.setMatomo(data);
  364. }
  365. });
  366. } else if (matomo) {
  367. window._paq.push(['trackPageView']);
  368. }
  369. },
  370. getTriggerActionDesc(event, tempInstance) {
  371. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  372. const triggerEls = jqueryEl.find('.trigger-content').children();
  373. let finalString = '';
  374. for (let i = 0; i < triggerEls.length; i++) {
  375. const element = tempInstance.$(triggerEls[i]);
  376. if (element.hasClass('trigger-text')) {
  377. finalString += element.text().toLowerCase();
  378. } else if (element.hasClass('user-details')) {
  379. let username = element.find('input').val();
  380. if (username === undefined || username === '') {
  381. username = '*';
  382. }
  383. finalString += `${element
  384. .find('.trigger-text')
  385. .text()
  386. .toLowerCase()} ${username}`;
  387. } else if (element.find('select').length > 0) {
  388. finalString += element
  389. .find('select option:selected')
  390. .text()
  391. .toLowerCase();
  392. } else if (element.find('input').length > 0) {
  393. let inputvalue = element.find('input').val();
  394. if (inputvalue === undefined || inputvalue === '') {
  395. inputvalue = '*';
  396. }
  397. finalString += inputvalue;
  398. }
  399. // Add space
  400. if (i !== length - 1) {
  401. finalString += ' ';
  402. }
  403. }
  404. return finalString;
  405. },
  406. };
  407. // A simple tracker dependency that we invalidate every time the window is
  408. // resized. This is used to reactively re-calculate the popup position in case
  409. // of a window resize. This is the equivalent of a "Signal" in some other
  410. // programming environments (eg, elm).
  411. $(window).on('resize', () => Utils.windowResizeDep.changed());