utils.js 17 KB

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