utils.js 17 KB

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