utils.js 17 KB

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