utils.js 17 KB

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