utils.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
  3. Utils = {
  4. setBackgroundImage(url) {
  5. const currentBoard = Utils.getCurrentBoard();
  6. if (currentBoard.backgroundImageURL !== undefined) {
  7. $(".board-wrapper").css({"background":"url(" + currentBoard.backgroundImageURL + ")","background-size":"cover"});
  8. $(".swimlane,.swimlane .list,.swimlane .list .list-body,.swimlane .list:first-child .list-body").css({"background-color":"transparent"});
  9. $(".minicard").css({"opacity": "0.9"});
  10. } else if (currentBoard["background-color"]) {
  11. currentBoard.setColor(currentBoard["background-color"]);
  12. }
  13. },
  14. /** returns the current board id
  15. * <li> returns the current board id or the board id of the popup card if set
  16. */
  17. getCurrentBoardId() {
  18. let popupCardBoardId = Session.get('popupCardBoardId');
  19. let currentBoard = Session.get('currentBoard');
  20. let ret = currentBoard;
  21. if (popupCardBoardId) {
  22. ret = popupCardBoardId;
  23. }
  24. return ret;
  25. },
  26. getCurrentCardId(ignorePopupCard) {
  27. let ret = Session.get('currentCard');
  28. if (!ret && !ignorePopupCard) {
  29. ret = Utils.getPopupCardId();
  30. }
  31. return ret;
  32. },
  33. getPopupCardId() {
  34. const ret = Session.get('popupCardId');
  35. return ret;
  36. },
  37. getCurrentListId() {
  38. const ret = Session.get('currentList');
  39. return ret;
  40. },
  41. /** returns the current board
  42. * <li> returns the current board or the board of the popup card if set
  43. */
  44. getCurrentBoard() {
  45. const boardId = Utils.getCurrentBoardId();
  46. const ret = ReactiveCache.getBoard(boardId);
  47. return ret;
  48. },
  49. getCurrentCard(ignorePopupCard) {
  50. const cardId = Utils.getCurrentCardId(ignorePopupCard);
  51. const ret = ReactiveCache.getCard(cardId);
  52. return ret;
  53. },
  54. getCurrentList() {
  55. const listId = this.getCurrentListId();
  56. let ret = null;
  57. if (listId) {
  58. ret = ReactiveCache.getList(listId);
  59. }
  60. return ret;
  61. },
  62. getPopupCard() {
  63. const cardId = Utils.getPopupCardId();
  64. const ret = ReactiveCache.getCard(cardId);
  65. return ret;
  66. },
  67. canModifyCard() {
  68. const currentUser = ReactiveCache.getCurrentUser();
  69. const ret = (
  70. currentUser &&
  71. currentUser.isBoardMember() &&
  72. !currentUser.isCommentOnly() &&
  73. !currentUser.isWorker()
  74. );
  75. return ret;
  76. },
  77. canModifyBoard() {
  78. const currentUser = ReactiveCache.getCurrentUser();
  79. const ret = (
  80. currentUser &&
  81. currentUser.isBoardMember() &&
  82. !currentUser.isCommentOnly()
  83. );
  84. return ret;
  85. },
  86. reload() {
  87. // we move all window.location.reload calls into this function
  88. // so we can disable it when running tests.
  89. // This is because we are not allowed to override location.reload but
  90. // we can override Utils.reload to prevent reload during tests.
  91. window.location.reload();
  92. },
  93. setBoardView(view) {
  94. currentUser = ReactiveCache.getCurrentUser();
  95. if (currentUser) {
  96. ReactiveCache.getCurrentUser().setBoardView(view);
  97. } else if (view === 'board-view-swimlanes') {
  98. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  99. Utils.reload();
  100. } else if (view === 'board-view-lists') {
  101. window.localStorage.setItem('boardView', 'board-view-lists'); //true
  102. Utils.reload();
  103. } else if (view === 'board-view-cal') {
  104. window.localStorage.setItem('boardView', 'board-view-cal'); //true
  105. Utils.reload();
  106. } else {
  107. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  108. Utils.reload();
  109. }
  110. },
  111. unsetBoardView() {
  112. window.localStorage.removeItem('boardView');
  113. window.localStorage.removeItem('collapseSwimlane');
  114. },
  115. boardView() {
  116. currentUser = ReactiveCache.getCurrentUser();
  117. if (currentUser) {
  118. return (currentUser.profile || {}).boardView;
  119. } else if (
  120. window.localStorage.getItem('boardView') === 'board-view-swimlanes'
  121. ) {
  122. return 'board-view-swimlanes';
  123. } else if (
  124. window.localStorage.getItem('boardView') === 'board-view-lists'
  125. ) {
  126. return 'board-view-lists';
  127. } else if (window.localStorage.getItem('boardView') === 'board-view-cal') {
  128. return 'board-view-cal';
  129. } else {
  130. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  131. Utils.reload();
  132. return 'board-view-swimlanes';
  133. }
  134. },
  135. myCardsSort() {
  136. let sort = window.localStorage.getItem('myCardsSort');
  137. if (!sort || !['board', 'dueAt'].includes(sort)) {
  138. sort = 'board';
  139. }
  140. return sort;
  141. },
  142. myCardsSortToggle() {
  143. if (this.myCardsSort() === 'board') {
  144. this.setMyCardsSort('dueAt');
  145. } else {
  146. this.setMyCardsSort('board');
  147. }
  148. },
  149. setMyCardsSort(sort) {
  150. window.localStorage.setItem('myCardsSort', sort);
  151. Utils.reload();
  152. },
  153. archivedBoardIds() {
  154. const ret = ReactiveCache.getBoards({ archived: false }).map(board => board._id);
  155. return ret;
  156. },
  157. dueCardsView() {
  158. let view = window.localStorage.getItem('dueCardsView');
  159. if (!view || !['me', 'all'].includes(view)) {
  160. view = 'me';
  161. }
  162. return view;
  163. },
  164. setDueCardsView(view) {
  165. window.localStorage.setItem('dueCardsView', view);
  166. Utils.reload();
  167. },
  168. myCardsView() {
  169. let view = window.localStorage.getItem('myCardsView');
  170. if (!view || !['boards', 'table'].includes(view)) {
  171. view = 'boards';
  172. }
  173. return view;
  174. },
  175. setMyCardsView(view) {
  176. window.localStorage.setItem('myCardsView', view);
  177. Utils.reload();
  178. },
  179. // XXX We should remove these two methods
  180. goBoardId(_id) {
  181. const board = ReactiveCache.getBoard(_id);
  182. return (
  183. board &&
  184. FlowRouter.go('board', {
  185. id: board._id,
  186. slug: board.slug,
  187. })
  188. );
  189. },
  190. goCardId(_id) {
  191. const card = ReactiveCache.getCard(_id);
  192. const board = ReactiveCache.getBoard(card.boardId);
  193. return (
  194. board &&
  195. FlowRouter.go('card', {
  196. cardId: card._id,
  197. boardId: board._id,
  198. slug: board.slug,
  199. })
  200. );
  201. },
  202. getCommonAttachmentMetaFrom(card) {
  203. const meta = {};
  204. if (card.isLinkedCard()) {
  205. meta.boardId = ReactiveCache.getCard(card.linkedId).boardId;
  206. meta.cardId = card.linkedId;
  207. } else {
  208. meta.boardId = card.boardId;
  209. meta.swimlaneId = card.swimlaneId;
  210. meta.listId = card.listId;
  211. meta.cardId = card._id;
  212. }
  213. return meta;
  214. },
  215. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  216. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  217. shrinkImage(options) {
  218. // shrink image to certain size
  219. const dataurl = options.dataurl,
  220. callback = options.callback,
  221. toBlob = options.toBlob;
  222. let canvas = document.createElement('canvas'),
  223. image = document.createElement('img');
  224. const maxSize = options.maxSize || 1024;
  225. const ratio = options.ratio || 1.0;
  226. const next = function (result) {
  227. image = null;
  228. canvas = null;
  229. if (typeof callback === 'function') {
  230. callback(result);
  231. }
  232. };
  233. image.onload = function () {
  234. let width = this.width,
  235. height = this.height;
  236. let changed = false;
  237. if (width > height) {
  238. if (width > maxSize) {
  239. height *= maxSize / width;
  240. width = maxSize;
  241. changed = true;
  242. }
  243. } else if (height > maxSize) {
  244. width *= maxSize / height;
  245. height = maxSize;
  246. changed = true;
  247. }
  248. canvas.width = width;
  249. canvas.height = height;
  250. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  251. if (changed === true) {
  252. const type = 'image/jpeg';
  253. if (toBlob) {
  254. canvas.toBlob(next, type, ratio);
  255. } else {
  256. next(canvas.toDataURL(type, ratio));
  257. }
  258. } else {
  259. next(changed);
  260. }
  261. };
  262. image.onerror = function () {
  263. next(false);
  264. };
  265. image.src = dataurl;
  266. },
  267. capitalize(string) {
  268. return string.charAt(0).toUpperCase() + string.slice(1);
  269. },
  270. windowResizeDep: new Tracker.Dependency(),
  271. // in fact, what we really care is screen size
  272. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  273. // in a small window (even on desktop), Wekan run in compact mode.
  274. // we can easily debug with a small window of desktop browser. :-)
  275. isMiniScreen() {
  276. // OLD WINDOW WIDTH DETECTION:
  277. this.windowResizeDep.depend();
  278. return $(window).width() <= 800;
  279. },
  280. isTouchScreen() {
  281. // NEW TOUCH DEVICE DETECTION:
  282. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  283. var hasTouchScreen = false;
  284. if ("maxTouchPoints" in navigator) {
  285. hasTouchScreen = navigator.maxTouchPoints > 0;
  286. } else if ("msMaxTouchPoints" in navigator) {
  287. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  288. } else {
  289. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  290. if (mQ && mQ.media === "(pointer:coarse)") {
  291. hasTouchScreen = !!mQ.matches;
  292. } else if ('orientation' in window) {
  293. hasTouchScreen = true; // deprecated, but good fallback
  294. } else {
  295. // Only as a last resort, fall back to user agent sniffing
  296. var UA = navigator.userAgent;
  297. hasTouchScreen = (
  298. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  299. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  300. );
  301. }
  302. }
  303. return hasTouchScreen;
  304. },
  305. // returns if desktop drag handles are enabled
  306. isShowDesktopDragHandles() {
  307. //const currentUser = ReactiveCache.getCurrentUser();
  308. //if (currentUser) {
  309. // return (currentUser.profile || {}).showDesktopDragHandles;
  310. //} else if (window.localStorage.getItem('showDesktopDragHandles')) {
  311. if (window.localStorage.getItem('showDesktopDragHandles')) {
  312. return true;
  313. } else {
  314. return false;
  315. }
  316. },
  317. // returns if mini screen or desktop drag handles
  318. isTouchScreenOrShowDesktopDragHandles() {
  319. //return this.isTouchScreen() || this.isShowDesktopDragHandles();
  320. return this.isShowDesktopDragHandles();
  321. },
  322. calculateIndexData(prevData, nextData, nItems = 1) {
  323. let base, increment;
  324. // If we drop the card to an empty column
  325. if (!prevData && !nextData) {
  326. base = 0;
  327. increment = 1;
  328. // If we drop the card in the first position
  329. } else if (!prevData) {
  330. const nextSortIndex = nextData.sort;
  331. const ceil = Math.ceil(nextSortIndex - 1);
  332. if (ceil < nextSortIndex) {
  333. increment = nextSortIndex - ceil;
  334. base = nextSortIndex - increment;
  335. } else {
  336. base = nextData.sort - 1;
  337. increment = -1;
  338. }
  339. // If we drop the card in the last position
  340. } else if (!nextData) {
  341. const prevSortIndex = prevData.sort;
  342. const floor = Math.floor(prevSortIndex + 1);
  343. if (floor > prevSortIndex) {
  344. increment = prevSortIndex - floor;
  345. base = prevSortIndex - increment;
  346. } else {
  347. base = prevData.sort + 1;
  348. increment = 1;
  349. }
  350. }
  351. // In the general case take the average of the previous and next element
  352. // sort indexes.
  353. else {
  354. const prevSortIndex = prevData.sort;
  355. const nextSortIndex = nextData.sort;
  356. if (nItems == 1 ) {
  357. if (prevSortIndex < 0 ) {
  358. const ceil = Math.ceil(nextSortIndex - 1);
  359. if (ceil < nextSortIndex && ceil > prevSortIndex) {
  360. increment = ceil - prevSortIndex;
  361. }
  362. } else {
  363. const floor = Math.floor(nextSortIndex - 1);
  364. if (floor < nextSortIndex && floor > prevSortIndex) {
  365. increment = floor - prevSortIndex;
  366. }
  367. }
  368. }
  369. if (!increment) {
  370. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  371. }
  372. if (!base) {
  373. base = prevSortIndex + increment;
  374. }
  375. }
  376. // XXX Return a generator that yield values instead of a base with a
  377. // increment number.
  378. return {
  379. base,
  380. increment,
  381. };
  382. },
  383. // Determine the new sort index
  384. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  385. let prevData = null;
  386. let nextData = null;
  387. if (prevCardDomElement) {
  388. prevData = Blaze.getData(prevCardDomElement)
  389. }
  390. if (nextCardDomElement) {
  391. nextData = Blaze.getData(nextCardDomElement);
  392. }
  393. const ret = Utils.calculateIndexData(prevData, nextData, nCards);
  394. return ret;
  395. },
  396. manageCustomUI() {
  397. Meteor.call('getCustomUI', (err, data) => {
  398. if (err && err.error[0] === 'var-not-exist') {
  399. Session.set('customUI', false); // siteId || address server not defined
  400. }
  401. if (!err) {
  402. Utils.setCustomUI(data);
  403. }
  404. });
  405. },
  406. setCustomUI(data) {
  407. const currentBoard = Utils.getCurrentBoard();
  408. if (currentBoard) {
  409. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  410. } else {
  411. DocHead.setTitle(`${data.productName}`);
  412. }
  413. },
  414. setMatomo(data) {
  415. window._paq = window._paq || [];
  416. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  417. if (data.withUserName) {
  418. window._paq.push(['setUserId', ReactiveCache.getCurrentUser().username]);
  419. }
  420. window._paq.push(['trackPageView']);
  421. window._paq.push(['enableLinkTracking']);
  422. (function () {
  423. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  424. window._paq.push(['setSiteId', data.siteId]);
  425. const script = document.createElement('script');
  426. Object.assign(script, {
  427. id: 'scriptMatomo',
  428. type: 'text/javascript',
  429. async: 'true',
  430. defer: 'true',
  431. src: `${data.address}piwik.js`,
  432. });
  433. const s = document.getElementsByTagName('script')[0];
  434. s.parentNode.insertBefore(script, s);
  435. })();
  436. Session.set('matomo', true);
  437. },
  438. manageMatomo() {
  439. const matomo = Session.get('matomo');
  440. if (matomo === undefined) {
  441. Meteor.call('getMatomoConf', (err, data) => {
  442. if (err && err.error[0] === 'var-not-exist') {
  443. Session.set('matomo', false); // siteId || address server not defined
  444. }
  445. if (!err) {
  446. Utils.setMatomo(data);
  447. }
  448. });
  449. } else if (matomo) {
  450. window._paq.push(['trackPageView']);
  451. }
  452. },
  453. getTriggerActionDesc(event, tempInstance) {
  454. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  455. const triggerEls = jqueryEl.find('.trigger-content').children();
  456. let finalString = '';
  457. for (let i = 0; i < triggerEls.length; i++) {
  458. const element = tempInstance.$(triggerEls[i]);
  459. if (element.hasClass('trigger-text')) {
  460. finalString += element.text().toLowerCase();
  461. } else if (element.hasClass('user-details')) {
  462. let username = element.find('input').val();
  463. if (username === undefined || username === '') {
  464. username = '*';
  465. }
  466. finalString += `${element
  467. .find('.trigger-text')
  468. .text()
  469. .toLowerCase()} ${username}`;
  470. } else if (element.find('select').length > 0) {
  471. finalString += element
  472. .find('select option:selected')
  473. .text()
  474. .toLowerCase();
  475. } else if (element.find('input').length > 0) {
  476. let inputvalue = element.find('input').val();
  477. if (inputvalue === undefined || inputvalue === '') {
  478. inputvalue = '*';
  479. }
  480. finalString += inputvalue;
  481. }
  482. // Add space
  483. if (i !== length - 1) {
  484. finalString += ' ';
  485. }
  486. }
  487. return finalString;
  488. },
  489. fallbackCopyTextToClipboard(text) {
  490. var textArea = document.createElement("textarea");
  491. textArea.value = text;
  492. // Avoid scrolling to bottom
  493. textArea.style.top = "0";
  494. textArea.style.left = "0";
  495. textArea.style.position = "fixed";
  496. document.body.appendChild(textArea);
  497. textArea.focus();
  498. textArea.select();
  499. try {
  500. document.execCommand('copy');
  501. return Promise.resolve(true);
  502. } catch (e) {
  503. return Promise.reject(false);
  504. } finally {
  505. document.body.removeChild(textArea);
  506. }
  507. },
  508. /** copy the text to the clipboard
  509. * @see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript/30810322#30810322
  510. * @param string copy this text to the clipboard
  511. * @return Promise
  512. */
  513. copyTextToClipboard(text) {
  514. let ret;
  515. if (navigator.clipboard) {
  516. ret = navigator.clipboard.writeText(text).then(function () {
  517. }, function (err) {
  518. console.error('Async: Could not copy text: ', err);
  519. });
  520. } else {
  521. ret = Utils.fallbackCopyTextToClipboard(text);
  522. }
  523. return ret;
  524. },
  525. /** show the "copied!" message
  526. * @param promise the promise of Utils.copyTextToClipboard
  527. * @param $tooltip jQuery tooltip element
  528. */
  529. showCopied(promise, $tooltip) {
  530. if (promise) {
  531. promise.then(() => {
  532. $tooltip.show(100);
  533. setTimeout(() => $tooltip.hide(100), 1000);
  534. }, (err) => {
  535. console.error("error: ", err);
  536. });
  537. }
  538. },
  539. };
  540. // A simple tracker dependency that we invalidate every time the window is
  541. // resized. This is used to reactively re-calculate the popup position in case
  542. // of a window resize. This is the equivalent of a "Signal" in some other
  543. // programming environments (eg, elm).
  544. $(window).on('resize', () => Utils.windowResizeDep.changed());