utils.js 15 KB

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