utils.js 17 KB

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