utils.js 17 KB

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