utils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. myCardsView() {
  129. let view = window.localStorage.getItem('myCardsView');
  130. if (!view || !['boards', 'table'].includes(view)) {
  131. view = 'boards';
  132. }
  133. return view;
  134. },
  135. setMyCardsView(view) {
  136. window.localStorage.setItem('myCardsView', view);
  137. Utils.reload();
  138. },
  139. // XXX We should remove these two methods
  140. goBoardId(_id) {
  141. const board = Boards.findOne(_id);
  142. return (
  143. board &&
  144. FlowRouter.go('board', {
  145. id: board._id,
  146. slug: board.slug,
  147. })
  148. );
  149. },
  150. goCardId(_id) {
  151. const card = Cards.findOne(_id);
  152. const board = Boards.findOne(card.boardId);
  153. return (
  154. board &&
  155. FlowRouter.go('card', {
  156. cardId: card._id,
  157. boardId: board._id,
  158. slug: board.slug,
  159. })
  160. );
  161. },
  162. getCommonAttachmentMetaFrom(card) {
  163. const meta = {};
  164. if (card.isLinkedCard()) {
  165. meta.boardId = Cards.findOne(card.linkedId).boardId;
  166. meta.cardId = card.linkedId;
  167. } else {
  168. meta.boardId = card.boardId;
  169. meta.swimlaneId = card.swimlaneId;
  170. meta.listId = card.listId;
  171. meta.cardId = card._id;
  172. }
  173. return meta;
  174. },
  175. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  176. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  177. shrinkImage(options) {
  178. // shrink image to certain size
  179. const dataurl = options.dataurl,
  180. callback = options.callback,
  181. toBlob = options.toBlob;
  182. let canvas = document.createElement('canvas'),
  183. image = document.createElement('img');
  184. const maxSize = options.maxSize || 1024;
  185. const ratio = options.ratio || 1.0;
  186. const next = function(result) {
  187. image = null;
  188. canvas = null;
  189. if (typeof callback === 'function') {
  190. callback(result);
  191. }
  192. };
  193. image.onload = function() {
  194. let width = this.width,
  195. height = this.height;
  196. let changed = false;
  197. if (width > height) {
  198. if (width > maxSize) {
  199. height *= maxSize / width;
  200. width = maxSize;
  201. changed = true;
  202. }
  203. } else if (height > maxSize) {
  204. width *= maxSize / height;
  205. height = maxSize;
  206. changed = true;
  207. }
  208. canvas.width = width;
  209. canvas.height = height;
  210. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  211. if (changed === true) {
  212. const type = 'image/jpeg';
  213. if (toBlob) {
  214. canvas.toBlob(next, type, ratio);
  215. } else {
  216. next(canvas.toDataURL(type, ratio));
  217. }
  218. } else {
  219. next(changed);
  220. }
  221. };
  222. image.onerror = function() {
  223. next(false);
  224. };
  225. image.src = dataurl;
  226. },
  227. capitalize(string) {
  228. return string.charAt(0).toUpperCase() + string.slice(1);
  229. },
  230. windowResizeDep: new Tracker.Dependency(),
  231. // in fact, what we really care is screen size
  232. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  233. // in a small window (even on desktop), Wekan run in compact mode.
  234. // we can easily debug with a small window of desktop browser. :-)
  235. isMiniScreen() {
  236. // OLD WINDOW WIDTH DETECTION:
  237. this.windowResizeDep.depend();
  238. return $(window).width() <= 800;
  239. // NEW TOUCH DEVICE DETECTION:
  240. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  241. /*
  242. var hasTouchScreen = false;
  243. if ("maxTouchPoints" in navigator) {
  244. hasTouchScreen = navigator.maxTouchPoints > 0;
  245. } else if ("msMaxTouchPoints" in navigator) {
  246. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  247. } else {
  248. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  249. if (mQ && mQ.media === "(pointer:coarse)") {
  250. hasTouchScreen = !!mQ.matches;
  251. } else if ('orientation' in window) {
  252. hasTouchScreen = true; // deprecated, but good fallback
  253. } else {
  254. // Only as a last resort, fall back to user agent sniffing
  255. var UA = navigator.userAgent;
  256. hasTouchScreen = (
  257. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  258. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  259. );
  260. }
  261. }
  262. */
  263. //if (hasTouchScreen)
  264. // document.getElementById("exampleButton").style.padding="1em";
  265. //return false;
  266. },
  267. // returns if desktop drag handles are enabled
  268. isShowDesktopDragHandles() {
  269. const currentUser = Meteor.user();
  270. if (currentUser) {
  271. return (currentUser.profile || {}).showDesktopDragHandles;
  272. } else if (window.localStorage.getItem('showDesktopDragHandles')) {
  273. return true;
  274. } else {
  275. return false;
  276. }
  277. },
  278. // returns if mini screen or desktop drag handles
  279. isMiniScreenOrShowDesktopDragHandles() {
  280. return this.isMiniScreen() || this.isShowDesktopDragHandles();
  281. },
  282. calculateIndexData(prevData, nextData, nItems = 1) {
  283. let base, increment;
  284. // If we drop the card to an empty column
  285. if (!prevData && !nextData) {
  286. base = 0;
  287. increment = 1;
  288. // If we drop the card in the first position
  289. } else if (!prevData) {
  290. base = nextData.sort - 1;
  291. increment = -1;
  292. // If we drop the card in the last position
  293. } else if (!nextData) {
  294. base = prevData.sort + 1;
  295. increment = 1;
  296. }
  297. // In the general case take the average of the previous and next element
  298. // sort indexes.
  299. else {
  300. const prevSortIndex = prevData.sort;
  301. const nextSortIndex = nextData.sort;
  302. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  303. base = prevSortIndex + increment;
  304. }
  305. // XXX Return a generator that yield values instead of a base with a
  306. // increment number.
  307. return {
  308. base,
  309. increment,
  310. };
  311. },
  312. // Determine the new sort index
  313. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  314. let base, increment;
  315. // If we drop the card to an empty column
  316. if (!prevCardDomElement && !nextCardDomElement) {
  317. base = 0;
  318. increment = 1;
  319. // If we drop the card in the first position
  320. } else if (!prevCardDomElement) {
  321. base = Blaze.getData(nextCardDomElement).sort - 1;
  322. increment = -1;
  323. // If we drop the card in the last position
  324. } else if (!nextCardDomElement) {
  325. base = Blaze.getData(prevCardDomElement).sort + 1;
  326. increment = 1;
  327. }
  328. // In the general case take the average of the previous and next element
  329. // sort indexes.
  330. else {
  331. const prevSortIndex = Blaze.getData(prevCardDomElement).sort;
  332. const nextSortIndex = Blaze.getData(nextCardDomElement).sort;
  333. increment = (nextSortIndex - prevSortIndex) / (nCards + 1);
  334. base = prevSortIndex + increment;
  335. }
  336. // XXX Return a generator that yield values instead of a base with a
  337. // increment number.
  338. return {
  339. base,
  340. increment,
  341. };
  342. },
  343. manageCustomUI() {
  344. Meteor.call('getCustomUI', (err, data) => {
  345. if (err && err.error[0] === 'var-not-exist') {
  346. Session.set('customUI', false); // siteId || address server not defined
  347. }
  348. if (!err) {
  349. Utils.setCustomUI(data);
  350. }
  351. });
  352. },
  353. setCustomUI(data) {
  354. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  355. if (currentBoard) {
  356. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  357. } else {
  358. DocHead.setTitle(`${data.productName}`);
  359. }
  360. },
  361. setMatomo(data) {
  362. window._paq = window._paq || [];
  363. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  364. if (data.withUserName) {
  365. window._paq.push(['setUserId', Meteor.user().username]);
  366. }
  367. window._paq.push(['trackPageView']);
  368. window._paq.push(['enableLinkTracking']);
  369. (function() {
  370. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  371. window._paq.push(['setSiteId', data.siteId]);
  372. const script = document.createElement('script');
  373. Object.assign(script, {
  374. id: 'scriptMatomo',
  375. type: 'text/javascript',
  376. async: 'true',
  377. defer: 'true',
  378. src: `${data.address}piwik.js`,
  379. });
  380. const s = document.getElementsByTagName('script')[0];
  381. s.parentNode.insertBefore(script, s);
  382. })();
  383. Session.set('matomo', true);
  384. },
  385. manageMatomo() {
  386. const matomo = Session.get('matomo');
  387. if (matomo === undefined) {
  388. Meteor.call('getMatomoConf', (err, data) => {
  389. if (err && err.error[0] === 'var-not-exist') {
  390. Session.set('matomo', false); // siteId || address server not defined
  391. }
  392. if (!err) {
  393. Utils.setMatomo(data);
  394. }
  395. });
  396. } else if (matomo) {
  397. window._paq.push(['trackPageView']);
  398. }
  399. },
  400. getTriggerActionDesc(event, tempInstance) {
  401. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  402. const triggerEls = jqueryEl.find('.trigger-content').children();
  403. let finalString = '';
  404. for (let i = 0; i < triggerEls.length; i++) {
  405. const element = tempInstance.$(triggerEls[i]);
  406. if (element.hasClass('trigger-text')) {
  407. finalString += element.text().toLowerCase();
  408. } else if (element.hasClass('user-details')) {
  409. let username = element.find('input').val();
  410. if (username === undefined || username === '') {
  411. username = '*';
  412. }
  413. finalString += `${element
  414. .find('.trigger-text')
  415. .text()
  416. .toLowerCase()} ${username}`;
  417. } else if (element.find('select').length > 0) {
  418. finalString += element
  419. .find('select option:selected')
  420. .text()
  421. .toLowerCase();
  422. } else if (element.find('input').length > 0) {
  423. let inputvalue = element.find('input').val();
  424. if (inputvalue === undefined || inputvalue === '') {
  425. inputvalue = '*';
  426. }
  427. finalString += inputvalue;
  428. }
  429. // Add space
  430. if (i !== length - 1) {
  431. finalString += ' ';
  432. }
  433. }
  434. return finalString;
  435. },
  436. fallbackCopyTextToClipboard(text) {
  437. var textArea = document.createElement("textarea");
  438. textArea.value = text;
  439. // Avoid scrolling to bottom
  440. textArea.style.top = "0";
  441. textArea.style.left = "0";
  442. textArea.style.position = "fixed";
  443. document.body.appendChild(textArea);
  444. textArea.focus();
  445. textArea.select();
  446. try {
  447. document.execCommand('copy');
  448. return Promise.resolve(true);
  449. } catch (e) {
  450. return Promise.reject(false);
  451. } finally {
  452. document.body.removeChild(textArea);
  453. }
  454. },
  455. /** copy the text to the clipboard
  456. * @see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript/30810322#30810322
  457. * @param string copy this text to the clipboard
  458. * @return Promise
  459. */
  460. copyTextToClipboard(text) {
  461. let ret;
  462. if (navigator.clipboard) {
  463. ret = navigator.clipboard.writeText(text).then(function() {
  464. }, function(err) {
  465. console.error('Async: Could not copy text: ', err);
  466. });
  467. } else {
  468. ret = Utils.fallbackCopyTextToClipboard(text);
  469. }
  470. return ret;
  471. },
  472. /** show the "copied!" message
  473. * @param promise the promise of Utils.copyTextToClipboard
  474. * @param $tooltip jQuery tooltip element
  475. */
  476. showCopied(promise, $tooltip) {
  477. if (promise) {
  478. promise.then(() => {
  479. $tooltip.show(100);
  480. setTimeout(() => $tooltip.hide(100), 1000);
  481. }, (err) => {
  482. console.error("error: ", err);
  483. });
  484. }
  485. },
  486. };
  487. // A simple tracker dependency that we invalidate every time the window is
  488. // resized. This is used to reactively re-calculate the popup position in case
  489. // of a window resize. This is the equivalent of a "Signal" in some other
  490. // programming environments (eg, elm).
  491. $(window).on('resize', () => Utils.windowResizeDep.changed());