utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. Utils = {
  2. /** returns the current board id
  3. * <li> returns the current board id or the board id of the popup card if set
  4. */
  5. getCurrentBoardId() {
  6. let popupCardBoardId = Session.get('popupCardBoardId');
  7. let currentBoard = Session.get('currentBoard');
  8. let ret = currentBoard;
  9. if (popupCardBoardId) {
  10. ret = popupCardBoardId;
  11. }
  12. return ret;
  13. },
  14. getCurrentCardId(ignorePopupCard) {
  15. let ret = Session.get('currentCard');
  16. if (!ret && !ignorePopupCard) {
  17. ret = Utils.getPopupCardId();
  18. }
  19. return ret;
  20. },
  21. getPopupCardId() {
  22. const ret = Session.get('popupCardId');
  23. return ret;
  24. },
  25. /** returns the current board
  26. * <li> returns the current board or the board of the popup card if set
  27. */
  28. getCurrentBoard() {
  29. const boardId = Utils.getCurrentBoardId();
  30. const ret = Boards.findOne(boardId);
  31. return ret;
  32. },
  33. getCurrentCard(ignorePopupCard) {
  34. const cardId = Utils.getCurrentCardId(ignorePopupCard);
  35. const ret = Cards.findOne(cardId);
  36. return ret;
  37. },
  38. getPopupCard() {
  39. const cardId = Utils.getPopupCardId();
  40. const ret = Cards.findOne(cardId);
  41. return ret;
  42. },
  43. reload () {
  44. // we move all window.location.reload calls into this function
  45. // so we can disable it when running tests.
  46. // This is because we are not allowed to override location.reload but
  47. // we can override Utils.reload to prevent reload during tests.
  48. window.location.reload();
  49. },
  50. setBoardView(view) {
  51. currentUser = Meteor.user();
  52. if (currentUser) {
  53. Meteor.user().setBoardView(view);
  54. } else if (view === 'board-view-swimlanes') {
  55. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  56. Utils.reload();
  57. } else if (view === 'board-view-lists') {
  58. window.localStorage.setItem('boardView', 'board-view-lists'); //true
  59. Utils.reload();
  60. } else if (view === 'board-view-cal') {
  61. window.localStorage.setItem('boardView', 'board-view-cal'); //true
  62. Utils.reload();
  63. } else {
  64. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  65. Utils.reload();
  66. }
  67. },
  68. unsetBoardView() {
  69. window.localStorage.removeItem('boardView');
  70. window.localStorage.removeItem('collapseSwimlane');
  71. },
  72. boardView() {
  73. currentUser = Meteor.user();
  74. if (currentUser) {
  75. return (currentUser.profile || {}).boardView;
  76. } else if (
  77. window.localStorage.getItem('boardView') === 'board-view-swimlanes'
  78. ) {
  79. return 'board-view-swimlanes';
  80. } else if (
  81. window.localStorage.getItem('boardView') === 'board-view-lists'
  82. ) {
  83. return 'board-view-lists';
  84. } else if (window.localStorage.getItem('boardView') === 'board-view-cal') {
  85. return 'board-view-cal';
  86. } else {
  87. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  88. Utils.reload();
  89. return 'board-view-swimlanes';
  90. }
  91. },
  92. myCardsSort() {
  93. let sort = window.localStorage.getItem('myCardsSort');
  94. if (!sort || !['board', 'dueAt'].includes(sort)) {
  95. sort = 'board';
  96. }
  97. return sort;
  98. },
  99. myCardsSortToggle() {
  100. if (this.myCardsSort() === 'board') {
  101. this.setMyCardsSort('dueAt');
  102. } else {
  103. this.setMyCardsSort('board');
  104. }
  105. },
  106. setMyCardsSort(sort) {
  107. window.localStorage.setItem('myCardsSort', sort);
  108. Utils.reload();
  109. },
  110. archivedBoardIds() {
  111. const archivedBoards = [];
  112. Boards.find({ archived: false }).forEach(board => {
  113. archivedBoards.push(board._id);
  114. });
  115. return archivedBoards;
  116. },
  117. dueCardsView() {
  118. let view = window.localStorage.getItem('dueCardsView');
  119. if (!view || !['me', 'all'].includes(view)) {
  120. view = 'me';
  121. }
  122. return view;
  123. },
  124. setDueCardsView(view) {
  125. window.localStorage.setItem('dueCardsView', view);
  126. Utils.reload();
  127. },
  128. // XXX We should remove these two methods
  129. goBoardId(_id) {
  130. const board = Boards.findOne(_id);
  131. return (
  132. board &&
  133. FlowRouter.go('board', {
  134. id: board._id,
  135. slug: board.slug,
  136. })
  137. );
  138. },
  139. goCardId(_id) {
  140. const card = Cards.findOne(_id);
  141. const board = Boards.findOne(card.boardId);
  142. return (
  143. board &&
  144. FlowRouter.go('card', {
  145. cardId: card._id,
  146. boardId: board._id,
  147. slug: board.slug,
  148. })
  149. );
  150. },
  151. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  152. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  153. processUploadedAttachment(card, fileObj, callback) {
  154. const next = attachment => {
  155. if (typeof callback === 'function') {
  156. callback(attachment);
  157. }
  158. };
  159. if (!card) {
  160. return next();
  161. }
  162. const file = new FS.File(fileObj);
  163. if (card.isLinkedCard()) {
  164. file.boardId = Cards.findOne(card.linkedId).boardId;
  165. file.cardId = card.linkedId;
  166. } else {
  167. file.boardId = card.boardId;
  168. file.swimlaneId = card.swimlaneId;
  169. file.listId = card.listId;
  170. file.cardId = card._id;
  171. }
  172. file.userId = Meteor.userId();
  173. if (file.original) {
  174. file.original.name = fileObj.name;
  175. }
  176. return next(Attachments.insert(file));
  177. },
  178. shrinkImage(options) {
  179. // shrink image to certain size
  180. const dataurl = options.dataurl,
  181. callback = options.callback,
  182. toBlob = options.toBlob;
  183. let canvas = document.createElement('canvas'),
  184. image = document.createElement('img');
  185. const maxSize = options.maxSize || 1024;
  186. const ratio = options.ratio || 1.0;
  187. const next = function(result) {
  188. image = null;
  189. canvas = null;
  190. if (typeof callback === 'function') {
  191. callback(result);
  192. }
  193. };
  194. image.onload = function() {
  195. let width = this.width,
  196. height = this.height;
  197. let changed = false;
  198. if (width > height) {
  199. if (width > maxSize) {
  200. height *= maxSize / width;
  201. width = maxSize;
  202. changed = true;
  203. }
  204. } else if (height > maxSize) {
  205. width *= maxSize / height;
  206. height = maxSize;
  207. changed = true;
  208. }
  209. canvas.width = width;
  210. canvas.height = height;
  211. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  212. if (changed === true) {
  213. const type = 'image/jpeg';
  214. if (toBlob) {
  215. canvas.toBlob(next, type, ratio);
  216. } else {
  217. next(canvas.toDataURL(type, ratio));
  218. }
  219. } else {
  220. next(changed);
  221. }
  222. };
  223. image.onerror = function() {
  224. next(false);
  225. };
  226. image.src = dataurl;
  227. },
  228. capitalize(string) {
  229. return string.charAt(0).toUpperCase() + string.slice(1);
  230. },
  231. windowResizeDep: new Tracker.Dependency(),
  232. // in fact, what we really care is screen size
  233. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  234. // in a small window (even on desktop), Wekan run in compact mode.
  235. // we can easily debug with a small window of desktop browser. :-)
  236. isMiniScreen() {
  237. // OLD WINDOW WIDTH DETECTION:
  238. this.windowResizeDep.depend();
  239. return $(window).width() <= 800;
  240. // NEW TOUCH DEVICE DETECTION:
  241. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  242. /*
  243. var hasTouchScreen = false;
  244. if ("maxTouchPoints" in navigator) {
  245. hasTouchScreen = navigator.maxTouchPoints > 0;
  246. } else if ("msMaxTouchPoints" in navigator) {
  247. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  248. } else {
  249. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  250. if (mQ && mQ.media === "(pointer:coarse)") {
  251. hasTouchScreen = !!mQ.matches;
  252. } else if ('orientation' in window) {
  253. hasTouchScreen = true; // deprecated, but good fallback
  254. } else {
  255. // Only as a last resort, fall back to user agent sniffing
  256. var UA = navigator.userAgent;
  257. hasTouchScreen = (
  258. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  259. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  260. );
  261. }
  262. }
  263. */
  264. //if (hasTouchScreen)
  265. // document.getElementById("exampleButton").style.padding="1em";
  266. //return false;
  267. },
  268. // returns if desktop drag handles are enabled
  269. isShowDesktopDragHandles() {
  270. const currentUser = Meteor.user();
  271. if (currentUser) {
  272. return (currentUser.profile || {}).showDesktopDragHandles;
  273. } else if (window.localStorage.getItem('showDesktopDragHandles')) {
  274. return true;
  275. } else {
  276. return false;
  277. }
  278. },
  279. // returns if mini screen or desktop drag handles
  280. isMiniScreenOrShowDesktopDragHandles() {
  281. return this.isMiniScreen() || this.isShowDesktopDragHandles();
  282. },
  283. calculateIndexData(prevData, nextData, nItems = 1) {
  284. let base, increment;
  285. // If we drop the card to an empty column
  286. if (!prevData && !nextData) {
  287. base = 0;
  288. increment = 1;
  289. // If we drop the card in the first position
  290. } else if (!prevData) {
  291. base = nextData.sort - 1;
  292. increment = -1;
  293. // If we drop the card in the last position
  294. } else if (!nextData) {
  295. base = prevData.sort + 1;
  296. increment = 1;
  297. }
  298. // In the general case take the average of the previous and next element
  299. // sort indexes.
  300. else {
  301. const prevSortIndex = prevData.sort;
  302. const nextSortIndex = nextData.sort;
  303. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  304. base = prevSortIndex + increment;
  305. }
  306. // XXX Return a generator that yield values instead of a base with a
  307. // increment number.
  308. return {
  309. base,
  310. increment,
  311. };
  312. },
  313. // Determine the new sort index
  314. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  315. let base, increment;
  316. // If we drop the card to an empty column
  317. if (!prevCardDomElement && !nextCardDomElement) {
  318. base = 0;
  319. increment = 1;
  320. // If we drop the card in the first position
  321. } else if (!prevCardDomElement) {
  322. base = Blaze.getData(nextCardDomElement).sort - 1;
  323. increment = -1;
  324. // If we drop the card in the last position
  325. } else if (!nextCardDomElement) {
  326. base = Blaze.getData(prevCardDomElement).sort + 1;
  327. increment = 1;
  328. }
  329. // In the general case take the average of the previous and next element
  330. // sort indexes.
  331. else {
  332. const prevSortIndex = Blaze.getData(prevCardDomElement).sort;
  333. const nextSortIndex = Blaze.getData(nextCardDomElement).sort;
  334. increment = (nextSortIndex - prevSortIndex) / (nCards + 1);
  335. base = prevSortIndex + increment;
  336. }
  337. // XXX Return a generator that yield values instead of a base with a
  338. // increment number.
  339. return {
  340. base,
  341. increment,
  342. };
  343. },
  344. manageCustomUI() {
  345. Meteor.call('getCustomUI', (err, data) => {
  346. if (err && err.error[0] === 'var-not-exist') {
  347. Session.set('customUI', false); // siteId || address server not defined
  348. }
  349. if (!err) {
  350. Utils.setCustomUI(data);
  351. }
  352. });
  353. },
  354. setCustomUI(data) {
  355. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  356. if (currentBoard) {
  357. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  358. } else {
  359. DocHead.setTitle(`${data.productName}`);
  360. }
  361. },
  362. setMatomo(data) {
  363. window._paq = window._paq || [];
  364. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  365. if (data.withUserName) {
  366. window._paq.push(['setUserId', Meteor.user().username]);
  367. }
  368. window._paq.push(['trackPageView']);
  369. window._paq.push(['enableLinkTracking']);
  370. (function() {
  371. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  372. window._paq.push(['setSiteId', data.siteId]);
  373. const script = document.createElement('script');
  374. Object.assign(script, {
  375. id: 'scriptMatomo',
  376. type: 'text/javascript',
  377. async: 'true',
  378. defer: 'true',
  379. src: `${data.address}piwik.js`,
  380. });
  381. const s = document.getElementsByTagName('script')[0];
  382. s.parentNode.insertBefore(script, s);
  383. })();
  384. Session.set('matomo', true);
  385. },
  386. manageMatomo() {
  387. const matomo = Session.get('matomo');
  388. if (matomo === undefined) {
  389. Meteor.call('getMatomoConf', (err, data) => {
  390. if (err && err.error[0] === 'var-not-exist') {
  391. Session.set('matomo', false); // siteId || address server not defined
  392. }
  393. if (!err) {
  394. Utils.setMatomo(data);
  395. }
  396. });
  397. } else if (matomo) {
  398. window._paq.push(['trackPageView']);
  399. }
  400. },
  401. getTriggerActionDesc(event, tempInstance) {
  402. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  403. const triggerEls = jqueryEl.find('.trigger-content').children();
  404. let finalString = '';
  405. for (let i = 0; i < triggerEls.length; i++) {
  406. const element = tempInstance.$(triggerEls[i]);
  407. if (element.hasClass('trigger-text')) {
  408. finalString += element.text().toLowerCase();
  409. } else if (element.hasClass('user-details')) {
  410. let username = element.find('input').val();
  411. if (username === undefined || username === '') {
  412. username = '*';
  413. }
  414. finalString += `${element
  415. .find('.trigger-text')
  416. .text()
  417. .toLowerCase()} ${username}`;
  418. } else if (element.find('select').length > 0) {
  419. finalString += element
  420. .find('select option:selected')
  421. .text()
  422. .toLowerCase();
  423. } else if (element.find('input').length > 0) {
  424. let inputvalue = element.find('input').val();
  425. if (inputvalue === undefined || inputvalue === '') {
  426. inputvalue = '*';
  427. }
  428. finalString += inputvalue;
  429. }
  430. // Add space
  431. if (i !== length - 1) {
  432. finalString += ' ';
  433. }
  434. }
  435. return finalString;
  436. },
  437. };
  438. // A simple tracker dependency that we invalidate every time the window is
  439. // resized. This is used to reactively re-calculate the popup position in case
  440. // of a window resize. This is the equivalent of a "Signal" in some other
  441. // programming environments (eg, elm).
  442. $(window).on('resize', () => Utils.windowResizeDep.changed());