utils.js 17 KB

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