utils.js 17 KB

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