utils.js 17 KB

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