utils.js 17 KB

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