utils.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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. this.windowResizeDep.depend();
  276. // Show mobile view when:
  277. // 1. Screen width is 800px or less (matches CSS media queries)
  278. // 2. Mobile phones in portrait mode
  279. // 3. iPad in very small screens (≤ 600px)
  280. const isSmallScreen = window.innerWidth <= 800;
  281. const isVerySmallScreen = window.innerWidth <= 600;
  282. const isPortrait = window.innerWidth < window.innerHeight || window.matchMedia("(orientation: portrait)").matches;
  283. const isMobilePhone = /Mobile|Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && !/iPad/i.test(navigator.userAgent);
  284. const isIPhone = /iPhone|iPod/i.test(navigator.userAgent);
  285. const isIPad = /iPad/i.test(navigator.userAgent);
  286. const isUbuntuTouch = /Ubuntu/i.test(navigator.userAgent);
  287. // For iPhone: always show mobile view regardless of orientation
  288. // For other mobile phones: show mobile view in portrait, desktop view in landscape
  289. // For iPad: show mobile view only in very small screens (≤ 600px)
  290. // For Ubuntu Touch: smartphones behave like mobile phones, tablets like iPad
  291. // For desktop: show mobile view when screen width <= 800px
  292. if (isIPhone) {
  293. return true; // iPhone: always mobile view
  294. } else if (isMobilePhone) {
  295. return isPortrait; // Other mobile phones: portrait = mobile, landscape = desktop
  296. } else if (isIPad) {
  297. return isVerySmallScreen; // iPad: only very small screens get mobile view
  298. } else if (isUbuntuTouch) {
  299. // Ubuntu Touch: smartphones (≤ 600px) behave like mobile phones, tablets (> 600px) like iPad
  300. if (isVerySmallScreen) {
  301. return isPortrait; // Ubuntu Touch smartphone: portrait = mobile, landscape = desktop
  302. } else {
  303. return isVerySmallScreen; // Ubuntu Touch tablet: only very small screens get mobile view
  304. }
  305. } else {
  306. return isSmallScreen; // Desktop: based on 800px screen width
  307. }
  308. },
  309. isTouchScreen() {
  310. // NEW TOUCH DEVICE DETECTION:
  311. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  312. var hasTouchScreen = false;
  313. if ("maxTouchPoints" in navigator) {
  314. hasTouchScreen = navigator.maxTouchPoints > 0;
  315. } else if ("msMaxTouchPoints" in navigator) {
  316. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  317. } else {
  318. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  319. if (mQ && mQ.media === "(pointer:coarse)") {
  320. hasTouchScreen = !!mQ.matches;
  321. } else if ('orientation' in window) {
  322. hasTouchScreen = true; // deprecated, but good fallback
  323. } else {
  324. // Only as a last resort, fall back to user agent sniffing
  325. var UA = navigator.userAgent;
  326. hasTouchScreen = (
  327. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  328. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  329. );
  330. }
  331. }
  332. return hasTouchScreen;
  333. },
  334. // returns if desktop drag handles are enabled
  335. isShowDesktopDragHandles() {
  336. if (this.isTouchScreen()) {
  337. return true;
  338. /*
  339. const currentUser = ReactiveCache.getCurrentUser();
  340. if (currentUser) {
  341. return (currentUser.profile || {}).showDesktopDragHandles;
  342. } else if (window.localStorage.getItem('showDesktopDragHandles')) {
  343. //
  344. if (window.localStorage.getItem('showDesktopDragHandles')) {
  345. return true;
  346. } else {
  347. return false;
  348. */
  349. } else {
  350. return false;
  351. }
  352. },
  353. // returns if mini screen or desktop drag handles
  354. isTouchScreenOrShowDesktopDragHandles() {
  355. return this.isTouchScreen();
  356. //return this.isTouchScreen() || this.isShowDesktopDragHandles();
  357. //return this.isShowDesktopDragHandles();
  358. },
  359. calculateIndexData(prevData, nextData, nItems = 1) {
  360. let base, increment;
  361. // If we drop the card to an empty column
  362. if (!prevData && !nextData) {
  363. base = 0;
  364. increment = 1;
  365. // If we drop the card in the first position
  366. } else if (!prevData) {
  367. const nextSortIndex = nextData.sort;
  368. const ceil = Math.ceil(nextSortIndex - 1);
  369. if (ceil < nextSortIndex) {
  370. increment = nextSortIndex - ceil;
  371. base = nextSortIndex - increment;
  372. } else {
  373. base = nextData.sort - 1;
  374. increment = -1;
  375. }
  376. // If we drop the card in the last position
  377. } else if (!nextData) {
  378. const prevSortIndex = prevData.sort;
  379. const floor = Math.floor(prevSortIndex + 1);
  380. if (floor > prevSortIndex) {
  381. increment = prevSortIndex - floor;
  382. base = prevSortIndex - increment;
  383. } else {
  384. base = prevData.sort + 1;
  385. increment = 1;
  386. }
  387. }
  388. // In the general case take the average of the previous and next element
  389. // sort indexes.
  390. else {
  391. const prevSortIndex = prevData.sort;
  392. const nextSortIndex = nextData.sort;
  393. if (nItems == 1 ) {
  394. if (prevSortIndex < 0 ) {
  395. const ceil = Math.ceil(nextSortIndex - 1);
  396. if (ceil < nextSortIndex && ceil > prevSortIndex) {
  397. increment = ceil - prevSortIndex;
  398. }
  399. } else {
  400. const floor = Math.floor(nextSortIndex - 1);
  401. if (floor < nextSortIndex && floor > prevSortIndex) {
  402. increment = floor - prevSortIndex;
  403. }
  404. }
  405. }
  406. if (!increment) {
  407. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  408. }
  409. if (!base) {
  410. base = prevSortIndex + increment;
  411. }
  412. }
  413. // XXX Return a generator that yield values instead of a base with a
  414. // increment number.
  415. return {
  416. base,
  417. increment,
  418. };
  419. },
  420. // Determine the new sort index
  421. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  422. let prevData = null;
  423. let nextData = null;
  424. if (prevCardDomElement) {
  425. prevData = Blaze.getData(prevCardDomElement)
  426. }
  427. if (nextCardDomElement) {
  428. nextData = Blaze.getData(nextCardDomElement);
  429. }
  430. const ret = Utils.calculateIndexData(prevData, nextData, nCards);
  431. return ret;
  432. },
  433. manageCustomUI() {
  434. Meteor.call('getCustomUI', (err, data) => {
  435. if (err && err.error[0] === 'var-not-exist') {
  436. Session.set('customUI', false); // siteId || address server not defined
  437. }
  438. if (!err) {
  439. Utils.setCustomUI(data);
  440. }
  441. });
  442. },
  443. setCustomUI(data) {
  444. const currentBoard = Utils.getCurrentBoard();
  445. if (currentBoard) {
  446. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  447. } else {
  448. DocHead.setTitle(`${data.productName}`);
  449. }
  450. },
  451. setMatomo(data) {
  452. window._paq = window._paq || [];
  453. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  454. if (data.withUserName) {
  455. window._paq.push(['setUserId', ReactiveCache.getCurrentUser().username]);
  456. }
  457. window._paq.push(['trackPageView']);
  458. window._paq.push(['enableLinkTracking']);
  459. (function () {
  460. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  461. window._paq.push(['setSiteId', data.siteId]);
  462. const script = document.createElement('script');
  463. Object.assign(script, {
  464. id: 'scriptMatomo',
  465. type: 'text/javascript',
  466. async: 'true',
  467. defer: 'true',
  468. src: `${data.address}piwik.js`,
  469. });
  470. const s = document.getElementsByTagName('script')[0];
  471. s.parentNode.insertBefore(script, s);
  472. })();
  473. Session.set('matomo', true);
  474. },
  475. manageMatomo() {
  476. const matomo = Session.get('matomo');
  477. if (matomo === undefined) {
  478. Meteor.call('getMatomoConf', (err, data) => {
  479. if (err && err.error[0] === 'var-not-exist') {
  480. Session.set('matomo', false); // siteId || address server not defined
  481. }
  482. if (!err) {
  483. Utils.setMatomo(data);
  484. }
  485. });
  486. } else if (matomo) {
  487. window._paq.push(['trackPageView']);
  488. }
  489. },
  490. getTriggerActionDesc(event, tempInstance) {
  491. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  492. const triggerEls = jqueryEl.find('.trigger-content').children();
  493. let finalString = '';
  494. for (let i = 0; i < triggerEls.length; i++) {
  495. const element = tempInstance.$(triggerEls[i]);
  496. if (element.hasClass('trigger-text')) {
  497. finalString += element.text().toLowerCase();
  498. } else if (element.hasClass('user-details')) {
  499. let username = element.find('input').val();
  500. if (username === undefined || username === '') {
  501. username = '*';
  502. }
  503. finalString += `${element
  504. .find('.trigger-text')
  505. .text()
  506. .toLowerCase()} ${username}`;
  507. } else if (element.find('select').length > 0) {
  508. finalString += element
  509. .find('select option:selected')
  510. .text()
  511. .toLowerCase();
  512. } else if (element.find('input').length > 0) {
  513. let inputvalue = element.find('input').val();
  514. if (inputvalue === undefined || inputvalue === '') {
  515. inputvalue = '*';
  516. }
  517. finalString += inputvalue;
  518. }
  519. // Add space
  520. if (i !== length - 1) {
  521. finalString += ' ';
  522. }
  523. }
  524. return finalString;
  525. },
  526. fallbackCopyTextToClipboard(text) {
  527. var textArea = document.createElement("textarea");
  528. textArea.value = text;
  529. // Avoid scrolling to bottom
  530. textArea.style.top = "0";
  531. textArea.style.left = "0";
  532. textArea.style.position = "fixed";
  533. document.body.appendChild(textArea);
  534. textArea.focus();
  535. textArea.select();
  536. try {
  537. document.execCommand('copy');
  538. return Promise.resolve(true);
  539. } catch (e) {
  540. return Promise.reject(false);
  541. } finally {
  542. document.body.removeChild(textArea);
  543. }
  544. },
  545. /** copy the text to the clipboard
  546. * @see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript/30810322#30810322
  547. * @param string copy this text to the clipboard
  548. * @return Promise
  549. */
  550. copyTextToClipboard(text) {
  551. let ret;
  552. if (navigator.clipboard) {
  553. ret = navigator.clipboard.writeText(text).then(function () {
  554. }, function (err) {
  555. console.error('Async: Could not copy text: ', err);
  556. });
  557. } else {
  558. ret = Utils.fallbackCopyTextToClipboard(text);
  559. }
  560. return ret;
  561. },
  562. /** show the "copied!" message
  563. * @param promise the promise of Utils.copyTextToClipboard
  564. * @param $tooltip jQuery tooltip element
  565. */
  566. showCopied(promise, $tooltip) {
  567. if (promise) {
  568. promise.then(() => {
  569. $tooltip.show(100);
  570. setTimeout(() => $tooltip.hide(100), 1000);
  571. }, (err) => {
  572. console.error("error: ", err);
  573. });
  574. }
  575. },
  576. };
  577. // A simple tracker dependency that we invalidate every time the window is
  578. // resized. This is used to reactively re-calculate the popup position in case
  579. // of a window resize. This is the equivalent of a "Signal" in some other
  580. // programming environments (eg, elm).
  581. $(window).on('resize', () => Utils.windowResizeDep.changed());