utils.js 18 KB

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