utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. calculateIndexData(prevData, nextData, nItems = 1) {
  185. let base, increment;
  186. // If we drop the card to an empty column
  187. if (!prevData && !nextData) {
  188. base = 0;
  189. increment = 1;
  190. // If we drop the card in the first position
  191. } else if (!prevData) {
  192. base = nextData.sort - 1;
  193. increment = -1;
  194. // If we drop the card in the last position
  195. } else if (!nextData) {
  196. base = prevData.sort + 1;
  197. increment = 1;
  198. }
  199. // In the general case take the average of the previous and next element
  200. // sort indexes.
  201. else {
  202. const prevSortIndex = prevData.sort;
  203. const nextSortIndex = nextData.sort;
  204. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  205. base = prevSortIndex + increment;
  206. }
  207. // XXX Return a generator that yield values instead of a base with a
  208. // increment number.
  209. return {
  210. base,
  211. increment,
  212. };
  213. },
  214. // Determine the new sort index
  215. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  216. let base, increment;
  217. // If we drop the card to an empty column
  218. if (!prevCardDomElement && !nextCardDomElement) {
  219. base = 0;
  220. increment = 1;
  221. // If we drop the card in the first position
  222. } else if (!prevCardDomElement) {
  223. base = Blaze.getData(nextCardDomElement).sort - 1;
  224. increment = -1;
  225. // If we drop the card in the last position
  226. } else if (!nextCardDomElement) {
  227. base = Blaze.getData(prevCardDomElement).sort + 1;
  228. increment = 1;
  229. }
  230. // In the general case take the average of the previous and next element
  231. // sort indexes.
  232. else {
  233. const prevSortIndex = Blaze.getData(prevCardDomElement).sort;
  234. const nextSortIndex = Blaze.getData(nextCardDomElement).sort;
  235. increment = (nextSortIndex - prevSortIndex) / (nCards + 1);
  236. base = prevSortIndex + increment;
  237. }
  238. // XXX Return a generator that yield values instead of a base with a
  239. // increment number.
  240. return {
  241. base,
  242. increment,
  243. };
  244. },
  245. // Detect touch device
  246. isTouchDevice() {
  247. const isTouchable = (() => {
  248. const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  249. const mq = function(query) {
  250. return window.matchMedia(query).matches;
  251. };
  252. if (
  253. 'ontouchstart' in window ||
  254. (window.DocumentTouch && document instanceof window.DocumentTouch)
  255. ) {
  256. return true;
  257. }
  258. // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  259. // https://git.io/vznFH
  260. const query = [
  261. '(',
  262. prefixes.join('touch-enabled),('),
  263. 'heartz',
  264. ')',
  265. ].join('');
  266. return mq(query);
  267. })();
  268. Utils.isTouchDevice = () => isTouchable;
  269. return isTouchable;
  270. },
  271. calculateTouchDistance(touchA, touchB) {
  272. return Math.sqrt(
  273. Math.pow(touchA.screenX - touchB.screenX, 2) +
  274. Math.pow(touchA.screenY - touchB.screenY, 2),
  275. );
  276. },
  277. enableClickOnTouch(selector) {
  278. let touchStart = null;
  279. let lastTouch = null;
  280. $(document).on('touchstart', selector, function(e) {
  281. touchStart = e.originalEvent.touches[0];
  282. });
  283. $(document).on('touchmove', selector, function(e) {
  284. const touches = e.originalEvent.touches;
  285. lastTouch = touches[touches.length - 1];
  286. });
  287. $(document).on('touchend', selector, function(e) {
  288. if (
  289. touchStart &&
  290. lastTouch &&
  291. Utils.calculateTouchDistance(touchStart, lastTouch) <= 20
  292. ) {
  293. e.preventDefault();
  294. const clickEvent = document.createEvent('MouseEvents');
  295. clickEvent.initEvent('click', true, true);
  296. e.target.dispatchEvent(clickEvent);
  297. }
  298. });
  299. },
  300. manageCustomUI() {
  301. Meteor.call('getCustomUI', (err, data) => {
  302. if (err && err.error[0] === 'var-not-exist') {
  303. Session.set('customUI', false); // siteId || address server not defined
  304. }
  305. if (!err) {
  306. Utils.setCustomUI(data);
  307. }
  308. });
  309. },
  310. setCustomUI(data) {
  311. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  312. if (currentBoard) {
  313. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  314. } else {
  315. DocHead.setTitle(`${data.productName}`);
  316. }
  317. },
  318. setMatomo(data) {
  319. window._paq = window._paq || [];
  320. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  321. if (data.withUserName) {
  322. window._paq.push(['setUserId', Meteor.user().username]);
  323. }
  324. window._paq.push(['trackPageView']);
  325. window._paq.push(['enableLinkTracking']);
  326. (function() {
  327. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  328. window._paq.push(['setSiteId', data.siteId]);
  329. const script = document.createElement('script');
  330. Object.assign(script, {
  331. id: 'scriptMatomo',
  332. type: 'text/javascript',
  333. async: 'true',
  334. defer: 'true',
  335. src: `${data.address}piwik.js`,
  336. });
  337. const s = document.getElementsByTagName('script')[0];
  338. s.parentNode.insertBefore(script, s);
  339. })();
  340. Session.set('matomo', true);
  341. },
  342. manageMatomo() {
  343. const matomo = Session.get('matomo');
  344. if (matomo === undefined) {
  345. Meteor.call('getMatomoConf', (err, data) => {
  346. if (err && err.error[0] === 'var-not-exist') {
  347. Session.set('matomo', false); // siteId || address server not defined
  348. }
  349. if (!err) {
  350. Utils.setMatomo(data);
  351. }
  352. });
  353. } else if (matomo) {
  354. window._paq.push(['trackPageView']);
  355. }
  356. },
  357. getTriggerActionDesc(event, tempInstance) {
  358. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  359. const triggerEls = jqueryEl.find('.trigger-content').children();
  360. let finalString = '';
  361. for (let i = 0; i < triggerEls.length; i++) {
  362. const element = tempInstance.$(triggerEls[i]);
  363. if (element.hasClass('trigger-text')) {
  364. finalString += element.text().toLowerCase();
  365. } else if (element.hasClass('user-details')) {
  366. let username = element.find('input').val();
  367. if (username === undefined || username === '') {
  368. username = '*';
  369. }
  370. finalString += `${element
  371. .find('.trigger-text')
  372. .text()
  373. .toLowerCase()} ${username}`;
  374. } else if (element.find('select').length > 0) {
  375. finalString += element
  376. .find('select option:selected')
  377. .text()
  378. .toLowerCase();
  379. } else if (element.find('input').length > 0) {
  380. let inputvalue = element.find('input').val();
  381. if (inputvalue === undefined || inputvalue === '') {
  382. inputvalue = '*';
  383. }
  384. finalString += inputvalue;
  385. }
  386. // Add space
  387. if (i !== length - 1) {
  388. finalString += ' ';
  389. }
  390. }
  391. return finalString;
  392. },
  393. };
  394. // A simple tracker dependency that we invalidate every time the window is
  395. // resized. This is used to reactively re-calculate the popup position in case
  396. // of a window resize. This is the equivalent of a "Signal" in some other
  397. // programming environments (eg, elm).
  398. $(window).on('resize', () => Utils.windowResizeDep.changed());