utils.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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. /** returns the current board id
  14. * <li> returns the current board id or the board id of the popup card if set
  15. */
  16. getCurrentBoardId() {
  17. let popupCardBoardId = Session.get('popupCardBoardId');
  18. let currentBoard = Session.get('currentBoard');
  19. let ret = currentBoard;
  20. if (popupCardBoardId) {
  21. ret = popupCardBoardId;
  22. }
  23. return ret;
  24. },
  25. getCurrentCardId(ignorePopupCard) {
  26. let ret = Session.get('currentCard');
  27. if (!ret && !ignorePopupCard) {
  28. ret = Utils.getPopupCardId();
  29. }
  30. return ret;
  31. },
  32. getPopupCardId() {
  33. const ret = Session.get('popupCardId');
  34. return ret;
  35. },
  36. getCurrentListId() {
  37. const ret = Session.get('currentList');
  38. return ret;
  39. },
  40. /** returns the current board
  41. * <li> returns the current board or the board of the popup card if set
  42. */
  43. getCurrentBoard() {
  44. const boardId = Utils.getCurrentBoardId();
  45. const ret = ReactiveCache.getBoard(boardId);
  46. return ret;
  47. },
  48. getCurrentCard(ignorePopupCard) {
  49. const cardId = Utils.getCurrentCardId(ignorePopupCard);
  50. const ret = ReactiveCache.getCard(cardId);
  51. return ret;
  52. },
  53. // Zoom and mobile mode utilities
  54. getZoomLevel() {
  55. const user = ReactiveCache.getCurrentUser();
  56. if (user && user.profile && user.profile.zoomLevel !== undefined) {
  57. return user.profile.zoomLevel;
  58. }
  59. // For non-logged-in users, check localStorage
  60. const stored = localStorage.getItem('wekan-zoom-level');
  61. return stored ? parseFloat(stored) : 1.0;
  62. },
  63. setZoomLevel(level) {
  64. const user = ReactiveCache.getCurrentUser();
  65. if (user) {
  66. // Update user profile
  67. user.setZoomLevel(level);
  68. } else {
  69. // Store in localStorage for non-logged-in users
  70. localStorage.setItem('wekan-zoom-level', level.toString());
  71. }
  72. Utils.applyZoomLevel(level);
  73. // Trigger reactive updates for UI components
  74. Session.set('wekan-zoom-level', level);
  75. },
  76. getMobileMode() {
  77. const user = ReactiveCache.getCurrentUser();
  78. if (user && user.profile && user.profile.mobileMode !== undefined) {
  79. return user.profile.mobileMode;
  80. }
  81. // For non-logged-in users, check localStorage
  82. const stored = localStorage.getItem('wekan-mobile-mode');
  83. return stored ? stored === 'true' : false;
  84. },
  85. setMobileMode(enabled) {
  86. const user = ReactiveCache.getCurrentUser();
  87. if (user) {
  88. // Update user profile
  89. user.setMobileMode(enabled);
  90. } else {
  91. // Store in localStorage for non-logged-in users
  92. localStorage.setItem('wekan-mobile-mode', enabled.toString());
  93. }
  94. Utils.applyMobileMode(enabled);
  95. // Trigger reactive updates for UI components
  96. Session.set('wekan-mobile-mode', enabled);
  97. },
  98. applyZoomLevel(level) {
  99. const boardWrapper = document.querySelector('.board-wrapper');
  100. const body = document.body;
  101. const isMobileMode = body.classList.contains('mobile-mode');
  102. if (boardWrapper) {
  103. if (isMobileMode) {
  104. // On mobile mode, only apply zoom to text and icons, not the entire layout
  105. // Remove any existing transform from board-wrapper
  106. boardWrapper.style.transform = '';
  107. boardWrapper.style.transformOrigin = '';
  108. // Apply zoom to text and icon elements instead
  109. const textElements = boardWrapper.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, div, .minicard, .list-header-name, .board-header-btn, .fa, .icon');
  110. textElements.forEach(element => {
  111. element.style.transform = `scale(${level})`;
  112. element.style.transformOrigin = 'center';
  113. });
  114. // Reset board-canvas height
  115. const boardCanvas = document.querySelector('.board-canvas');
  116. if (boardCanvas) {
  117. boardCanvas.style.height = '';
  118. }
  119. } else {
  120. // Desktop mode: apply zoom to entire board-wrapper as before
  121. boardWrapper.style.transform = `scale(${level})`;
  122. boardWrapper.style.transformOrigin = 'top left';
  123. // If zoom is 50% or lower, make board wrapper full width like content
  124. if (level <= 0.5) {
  125. boardWrapper.style.width = '100%';
  126. boardWrapper.style.maxWidth = '100%';
  127. boardWrapper.style.margin = '0';
  128. } else {
  129. // Reset to normal width for higher zoom levels
  130. boardWrapper.style.width = '';
  131. boardWrapper.style.maxWidth = '';
  132. boardWrapper.style.margin = '';
  133. }
  134. // Adjust container height to prevent scroll issues
  135. const boardCanvas = document.querySelector('.board-canvas');
  136. if (boardCanvas) {
  137. boardCanvas.style.height = `${100 / level}%`;
  138. // For high zoom levels (200%+), enable both horizontal and vertical scrolling
  139. if (level >= 2.0) {
  140. boardCanvas.style.overflowX = 'auto';
  141. boardCanvas.style.overflowY = 'auto';
  142. // Ensure the content area can scroll both horizontally and vertically
  143. const content = document.querySelector('#content');
  144. if (content) {
  145. content.style.overflowX = 'auto';
  146. content.style.overflowY = 'auto';
  147. }
  148. } else {
  149. // Reset overflow for normal zoom levels
  150. boardCanvas.style.overflowX = '';
  151. boardCanvas.style.overflowY = '';
  152. const content = document.querySelector('#content');
  153. if (content) {
  154. content.style.overflowX = '';
  155. content.style.overflowY = '';
  156. }
  157. }
  158. }
  159. }
  160. }
  161. },
  162. applyMobileMode(enabled) {
  163. const body = document.body;
  164. if (enabled) {
  165. body.classList.add('mobile-mode');
  166. body.classList.remove('desktop-mode');
  167. } else {
  168. body.classList.add('desktop-mode');
  169. body.classList.remove('mobile-mode');
  170. }
  171. },
  172. initializeUserSettings() {
  173. // Apply saved settings on page load
  174. const zoomLevel = Utils.getZoomLevel();
  175. const mobileMode = Utils.getMobileMode();
  176. Utils.applyZoomLevel(zoomLevel);
  177. Utils.applyMobileMode(mobileMode);
  178. },
  179. getCurrentList() {
  180. const listId = this.getCurrentListId();
  181. let ret = null;
  182. if (listId) {
  183. ret = ReactiveCache.getList(listId);
  184. }
  185. return ret;
  186. },
  187. getPopupCard() {
  188. const cardId = Utils.getPopupCardId();
  189. const ret = ReactiveCache.getCard(cardId);
  190. return ret;
  191. },
  192. canModifyCard() {
  193. const currentUser = ReactiveCache.getCurrentUser();
  194. const ret = (
  195. currentUser &&
  196. currentUser.isBoardMember() &&
  197. !currentUser.isCommentOnly() &&
  198. !currentUser.isWorker()
  199. );
  200. return ret;
  201. },
  202. canMoveCard() {
  203. const currentUser = ReactiveCache.getCurrentUser();
  204. const ret = (
  205. currentUser &&
  206. currentUser.isBoardMember() &&
  207. !currentUser.isCommentOnly()
  208. );
  209. return ret;
  210. },
  211. canModifyBoard() {
  212. const currentUser = ReactiveCache.getCurrentUser();
  213. const ret = (
  214. currentUser &&
  215. currentUser.isBoardMember() &&
  216. !currentUser.isCommentOnly()
  217. );
  218. return ret;
  219. },
  220. reload() {
  221. // we move all window.location.reload calls into this function
  222. // so we can disable it when running tests.
  223. // This is because we are not allowed to override location.reload but
  224. // we can override Utils.reload to prevent reload during tests.
  225. window.location.reload();
  226. },
  227. setBoardView(view) {
  228. const currentUser = ReactiveCache.getCurrentUser();
  229. if (currentUser) {
  230. // Update localStorage first
  231. window.localStorage.setItem('boardView', view);
  232. // Update user profile via Meteor method
  233. Meteor.call('setBoardView', view, (error) => {
  234. if (error) {
  235. console.error('[setBoardView] Update failed:', error);
  236. } else {
  237. // Reload to apply the view change
  238. Utils.reload();
  239. }
  240. });
  241. } else if (view === 'board-view-swimlanes') {
  242. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  243. Utils.reload();
  244. } else if (view === 'board-view-lists') {
  245. window.localStorage.setItem('boardView', 'board-view-lists'); //true
  246. Utils.reload();
  247. } else if (view === 'board-view-cal') {
  248. window.localStorage.setItem('boardView', 'board-view-cal'); //true
  249. Utils.reload();
  250. } else if (view === 'board-view-gantt') {
  251. window.localStorage.setItem('boardView', 'board-view-gantt'); //true
  252. Utils.reload();
  253. } else {
  254. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  255. Utils.reload();
  256. }
  257. },
  258. unsetBoardView() {
  259. window.localStorage.removeItem('boardView');
  260. window.localStorage.removeItem('collapseSwimlane');
  261. },
  262. boardView() {
  263. currentUser = ReactiveCache.getCurrentUser();
  264. if (currentUser) {
  265. return (currentUser.profile || {}).boardView;
  266. } else if (
  267. window.localStorage.getItem('boardView') === 'board-view-swimlanes'
  268. ) {
  269. return 'board-view-swimlanes';
  270. } else if (
  271. window.localStorage.getItem('boardView') === 'board-view-lists'
  272. ) {
  273. return 'board-view-lists';
  274. } else if (window.localStorage.getItem('boardView') === 'board-view-cal') {
  275. return 'board-view-cal';
  276. } else if (window.localStorage.getItem('boardView') === 'board-view-gantt') {
  277. return 'board-view-gantt';
  278. } else {
  279. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  280. Utils.reload();
  281. return 'board-view-swimlanes';
  282. }
  283. },
  284. myCardsSort() {
  285. let sort = window.localStorage.getItem('myCardsSort');
  286. if (!sort || !['board', 'dueAt'].includes(sort)) {
  287. sort = 'board';
  288. }
  289. return sort;
  290. },
  291. myCardsSortToggle() {
  292. if (this.myCardsSort() === 'board') {
  293. this.setMyCardsSort('dueAt');
  294. } else {
  295. this.setMyCardsSort('board');
  296. }
  297. },
  298. setMyCardsSort(sort) {
  299. window.localStorage.setItem('myCardsSort', sort);
  300. Utils.reload();
  301. },
  302. archivedBoardIds() {
  303. const ret = ReactiveCache.getBoards({ archived: false }).map(board => board._id);
  304. return ret;
  305. },
  306. dueCardsView() {
  307. let view = window.localStorage.getItem('dueCardsView');
  308. if (!view || !['me', 'all'].includes(view)) {
  309. view = 'me';
  310. }
  311. return view;
  312. },
  313. setDueCardsView(view) {
  314. window.localStorage.setItem('dueCardsView', view);
  315. Utils.reload();
  316. },
  317. myCardsView() {
  318. let view = window.localStorage.getItem('myCardsView');
  319. if (!view || !['boards', 'table'].includes(view)) {
  320. view = 'boards';
  321. }
  322. return view;
  323. },
  324. setMyCardsView(view) {
  325. window.localStorage.setItem('myCardsView', view);
  326. Utils.reload();
  327. },
  328. // XXX We should remove these two methods
  329. goBoardId(_id) {
  330. const board = ReactiveCache.getBoard(_id);
  331. return (
  332. board &&
  333. FlowRouter.go('board', {
  334. id: board._id,
  335. slug: board.slug,
  336. })
  337. );
  338. },
  339. goCardId(_id) {
  340. const card = ReactiveCache.getCard(_id);
  341. const board = ReactiveCache.getBoard(card.boardId);
  342. return (
  343. board &&
  344. FlowRouter.go('card', {
  345. cardId: card._id,
  346. boardId: board._id,
  347. slug: board.slug,
  348. })
  349. );
  350. },
  351. getCommonAttachmentMetaFrom(card) {
  352. const meta = {};
  353. if (card.isLinkedCard()) {
  354. meta.boardId = ReactiveCache.getCard(card.linkedId).boardId;
  355. meta.cardId = card.linkedId;
  356. } else {
  357. meta.boardId = card.boardId;
  358. meta.swimlaneId = card.swimlaneId;
  359. meta.listId = card.listId;
  360. meta.cardId = card._id;
  361. }
  362. return meta;
  363. },
  364. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  365. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  366. shrinkImage(options) {
  367. // shrink image to certain size
  368. const dataurl = options.dataurl,
  369. callback = options.callback,
  370. toBlob = options.toBlob;
  371. let canvas = document.createElement('canvas'),
  372. image = document.createElement('img');
  373. const maxSize = options.maxSize || 1024;
  374. const ratio = options.ratio || 1.0;
  375. const next = function (result) {
  376. image = null;
  377. canvas = null;
  378. if (typeof callback === 'function') {
  379. callback(result);
  380. }
  381. };
  382. image.onload = function () {
  383. let width = this.width,
  384. height = this.height;
  385. let changed = false;
  386. if (width > height) {
  387. if (width > maxSize) {
  388. height *= maxSize / width;
  389. width = maxSize;
  390. changed = true;
  391. }
  392. } else if (height > maxSize) {
  393. width *= maxSize / height;
  394. height = maxSize;
  395. changed = true;
  396. }
  397. canvas.width = width;
  398. canvas.height = height;
  399. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  400. if (changed === true) {
  401. const type = 'image/jpeg';
  402. if (toBlob) {
  403. canvas.toBlob(next, type, ratio);
  404. } else {
  405. next(canvas.toDataURL(type, ratio));
  406. }
  407. } else {
  408. next(changed);
  409. }
  410. };
  411. image.onerror = function () {
  412. next(false);
  413. };
  414. image.src = dataurl;
  415. },
  416. capitalize(string) {
  417. return string.charAt(0).toUpperCase() + string.slice(1);
  418. },
  419. windowResizeDep: new Tracker.Dependency(),
  420. // in fact, what we really care is screen size
  421. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  422. // in a small window (even on desktop), Wekan run in compact mode.
  423. // we can easily debug with a small window of desktop browser. :-)
  424. isMiniScreen() {
  425. this.windowResizeDep.depend();
  426. // Also depend on mobile mode changes to make this reactive
  427. Session.get('wekan-mobile-mode');
  428. // Show mobile view when:
  429. // 1. Screen width is 800px or less (matches CSS media queries)
  430. // 2. Mobile phones in portrait mode
  431. // 3. iPad in very small screens (≤ 600px)
  432. // 4. All iPhone models by default (including largest models), but respect user preference
  433. const isSmallScreen = window.innerWidth <= 800;
  434. const isVerySmallScreen = window.innerWidth <= 600;
  435. const isPortrait = window.innerWidth < window.innerHeight || window.matchMedia("(orientation: portrait)").matches;
  436. const isMobilePhone = /Mobile|Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && !/iPad/i.test(navigator.userAgent);
  437. const isIPhone = /iPhone|iPod/i.test(navigator.userAgent);
  438. const isIPad = /iPad/i.test(navigator.userAgent);
  439. const isUbuntuTouch = /Ubuntu/i.test(navigator.userAgent);
  440. // Check if user has explicitly set mobile mode preference
  441. const userMobileMode = this.getMobileMode();
  442. // For iPhone: default to mobile view, but respect user's mobile mode toggle preference
  443. // This ensures all iPhone models (including iPhone 15 Pro Max, 14 Pro Max, etc.) start with mobile view
  444. // but users can still switch to desktop mode if they prefer
  445. if (isIPhone) {
  446. // If user has explicitly set a preference, respect it
  447. if (userMobileMode !== null && userMobileMode !== undefined) {
  448. return userMobileMode;
  449. }
  450. // Otherwise, default to mobile view for iPhones
  451. return true;
  452. } else if (isMobilePhone) {
  453. return isPortrait; // Other mobile phones: portrait = mobile, landscape = desktop
  454. } else if (isIPad) {
  455. return isVerySmallScreen; // iPad: only very small screens get mobile view
  456. } else if (isUbuntuTouch) {
  457. // Ubuntu Touch: smartphones (≤ 600px) behave like mobile phones, tablets (> 600px) like iPad
  458. if (isVerySmallScreen) {
  459. return isPortrait; // Ubuntu Touch smartphone: portrait = mobile, landscape = desktop
  460. } else {
  461. return isVerySmallScreen; // Ubuntu Touch tablet: only very small screens get mobile view
  462. }
  463. } else {
  464. return isSmallScreen; // Desktop: based on 800px screen width
  465. }
  466. },
  467. isTouchScreen() {
  468. // NEW TOUCH DEVICE DETECTION:
  469. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  470. var hasTouchScreen = false;
  471. if ("maxTouchPoints" in navigator) {
  472. hasTouchScreen = navigator.maxTouchPoints > 0;
  473. } else if ("msMaxTouchPoints" in navigator) {
  474. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  475. } else {
  476. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  477. if (mQ && mQ.media === "(pointer:coarse)") {
  478. hasTouchScreen = !!mQ.matches;
  479. } else if ('orientation' in window) {
  480. hasTouchScreen = true; // deprecated, but good fallback
  481. } else {
  482. // Only as a last resort, fall back to user agent sniffing
  483. var UA = navigator.userAgent;
  484. hasTouchScreen = (
  485. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  486. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  487. );
  488. }
  489. }
  490. return hasTouchScreen;
  491. },
  492. // returns if desktop drag handles are enabled
  493. isShowDesktopDragHandles() {
  494. // Always show drag handles on all displays
  495. return true;
  496. },
  497. // returns if mini screen or desktop drag handles
  498. isTouchScreenOrShowDesktopDragHandles() {
  499. // Always enable drag handles for all displays
  500. return true;
  501. },
  502. calculateIndexData(prevData, nextData, nItems = 1) {
  503. let base, increment;
  504. // If we drop the card to an empty column
  505. if (!prevData && !nextData) {
  506. base = 0;
  507. increment = 1;
  508. // If we drop the card in the first position
  509. } else if (!prevData) {
  510. const nextSortIndex = nextData.sort;
  511. const ceil = Math.ceil(nextSortIndex - 1);
  512. if (ceil < nextSortIndex) {
  513. increment = nextSortIndex - ceil;
  514. base = nextSortIndex - increment;
  515. } else {
  516. base = nextData.sort - 1;
  517. increment = -1;
  518. }
  519. // If we drop the card in the last position
  520. } else if (!nextData) {
  521. const prevSortIndex = prevData.sort;
  522. const floor = Math.floor(prevSortIndex + 1);
  523. if (floor > prevSortIndex) {
  524. increment = prevSortIndex - floor;
  525. base = prevSortIndex - increment;
  526. } else {
  527. base = prevData.sort + 1;
  528. increment = 1;
  529. }
  530. }
  531. // In the general case take the average of the previous and next element
  532. // sort indexes.
  533. else {
  534. const prevSortIndex = prevData.sort;
  535. const nextSortIndex = nextData.sort;
  536. if (nItems == 1 ) {
  537. if (prevSortIndex < 0 ) {
  538. const ceil = Math.ceil(nextSortIndex - 1);
  539. if (ceil < nextSortIndex && ceil > prevSortIndex) {
  540. increment = ceil - prevSortIndex;
  541. }
  542. } else {
  543. const floor = Math.floor(nextSortIndex - 1);
  544. if (floor < nextSortIndex && floor > prevSortIndex) {
  545. increment = floor - prevSortIndex;
  546. }
  547. }
  548. }
  549. if (!increment) {
  550. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  551. }
  552. if (!base) {
  553. base = prevSortIndex + increment;
  554. }
  555. }
  556. // XXX Return a generator that yield values instead of a base with a
  557. // increment number.
  558. return {
  559. base,
  560. increment,
  561. };
  562. },
  563. // Determine the new sort index
  564. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  565. let prevData = null;
  566. let nextData = null;
  567. if (prevCardDomElement) {
  568. prevData = Blaze.getData(prevCardDomElement)
  569. }
  570. if (nextCardDomElement) {
  571. nextData = Blaze.getData(nextCardDomElement);
  572. }
  573. const ret = Utils.calculateIndexData(prevData, nextData, nCards);
  574. return ret;
  575. },
  576. manageCustomUI() {
  577. Meteor.call('getCustomUI', (err, data) => {
  578. if (err && err.error[0] === 'var-not-exist') {
  579. Session.set('customUI', false); // siteId || address server not defined
  580. }
  581. if (!err) {
  582. Utils.setCustomUI(data);
  583. }
  584. });
  585. },
  586. setCustomUI(data) {
  587. const currentBoard = Utils.getCurrentBoard();
  588. if (currentBoard) {
  589. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  590. } else {
  591. DocHead.setTitle(`${data.productName}`);
  592. }
  593. },
  594. setMatomo(data) {
  595. window._paq = window._paq || [];
  596. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  597. if (data.withUserName) {
  598. window._paq.push(['setUserId', ReactiveCache.getCurrentUser().username]);
  599. }
  600. window._paq.push(['trackPageView']);
  601. window._paq.push(['enableLinkTracking']);
  602. (function () {
  603. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  604. window._paq.push(['setSiteId', data.siteId]);
  605. const script = document.createElement('script');
  606. Object.assign(script, {
  607. id: 'scriptMatomo',
  608. type: 'text/javascript',
  609. async: 'true',
  610. defer: 'true',
  611. src: `${data.address}piwik.js`,
  612. });
  613. const s = document.getElementsByTagName('script')[0];
  614. s.parentNode.insertBefore(script, s);
  615. })();
  616. Session.set('matomo', true);
  617. },
  618. manageMatomo() {
  619. const matomo = Session.get('matomo');
  620. if (matomo === undefined) {
  621. Meteor.call('getMatomoConf', (err, data) => {
  622. if (err && err.error[0] === 'var-not-exist') {
  623. Session.set('matomo', false); // siteId || address server not defined
  624. }
  625. if (!err) {
  626. Utils.setMatomo(data);
  627. }
  628. });
  629. } else if (matomo) {
  630. window._paq.push(['trackPageView']);
  631. }
  632. },
  633. getTriggerActionDesc(event, tempInstance) {
  634. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  635. const triggerEls = jqueryEl.find('.trigger-content').children();
  636. let finalString = '';
  637. for (let i = 0; i < triggerEls.length; i++) {
  638. const element = tempInstance.$(triggerEls[i]);
  639. if (element.hasClass('trigger-text')) {
  640. finalString += element.text().toLowerCase();
  641. } else if (element.hasClass('user-details')) {
  642. let username = element.find('input').val();
  643. if (username === undefined || username === '') {
  644. username = '*';
  645. }
  646. finalString += `${element
  647. .find('.trigger-text')
  648. .text()
  649. .toLowerCase()} ${username}`;
  650. } else if (element.find('select').length > 0) {
  651. finalString += element
  652. .find('select option:selected')
  653. .text()
  654. .toLowerCase();
  655. } else if (element.find('input').length > 0) {
  656. let inputvalue = element.find('input').val();
  657. if (inputvalue === undefined || inputvalue === '') {
  658. inputvalue = '*';
  659. }
  660. finalString += inputvalue;
  661. }
  662. // Add space
  663. if (i !== length - 1) {
  664. finalString += ' ';
  665. }
  666. }
  667. return finalString;
  668. },
  669. fallbackCopyTextToClipboard(text) {
  670. var textArea = document.createElement("textarea");
  671. textArea.value = text;
  672. // Avoid scrolling to bottom
  673. textArea.style.top = "0";
  674. textArea.style.left = "0";
  675. textArea.style.position = "fixed";
  676. document.body.appendChild(textArea);
  677. textArea.focus();
  678. textArea.select();
  679. try {
  680. document.execCommand('copy');
  681. return Promise.resolve(true);
  682. } catch (e) {
  683. return Promise.reject(false);
  684. } finally {
  685. document.body.removeChild(textArea);
  686. }
  687. },
  688. /** copy the text to the clipboard
  689. * @see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript/30810322#30810322
  690. * @param string copy this text to the clipboard
  691. * @return Promise
  692. */
  693. copyTextToClipboard(text) {
  694. let ret;
  695. if (navigator.clipboard) {
  696. ret = navigator.clipboard.writeText(text).then(function () {
  697. }, function (err) {
  698. console.error('Async: Could not copy text: ', err);
  699. });
  700. } else {
  701. ret = Utils.fallbackCopyTextToClipboard(text);
  702. }
  703. return ret;
  704. },
  705. /** show the "copied!" message
  706. * @param promise the promise of Utils.copyTextToClipboard
  707. * @param $tooltip jQuery tooltip element
  708. */
  709. showCopied(promise, $tooltip) {
  710. if (promise) {
  711. promise.then(() => {
  712. $tooltip.show(100);
  713. setTimeout(() => $tooltip.hide(100), 1000);
  714. }, (err) => {
  715. console.error("error: ", err);
  716. });
  717. }
  718. },
  719. };
  720. // A simple tracker dependency that we invalidate every time the window is
  721. // resized. This is used to reactively re-calculate the popup position in case
  722. // of a window resize. This is the equivalent of a "Signal" in some other
  723. // programming environments (eg, elm).
  724. $(window).on('resize', () => Utils.windowResizeDep.changed());