utils.js 18 KB

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