utils.js 15 KB

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