utils.js 16 KB

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