utils.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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 {
  251. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  252. Utils.reload();
  253. }
  254. },
  255. unsetBoardView() {
  256. window.localStorage.removeItem('boardView');
  257. window.localStorage.removeItem('collapseSwimlane');
  258. },
  259. boardView() {
  260. currentUser = ReactiveCache.getCurrentUser();
  261. if (currentUser) {
  262. return (currentUser.profile || {}).boardView;
  263. } else if (
  264. window.localStorage.getItem('boardView') === 'board-view-swimlanes'
  265. ) {
  266. return 'board-view-swimlanes';
  267. } else if (
  268. window.localStorage.getItem('boardView') === 'board-view-lists'
  269. ) {
  270. return 'board-view-lists';
  271. } else if (window.localStorage.getItem('boardView') === 'board-view-cal') {
  272. return 'board-view-cal';
  273. } else {
  274. window.localStorage.setItem('boardView', 'board-view-swimlanes'); //true
  275. Utils.reload();
  276. return 'board-view-swimlanes';
  277. }
  278. },
  279. myCardsSort() {
  280. let sort = window.localStorage.getItem('myCardsSort');
  281. if (!sort || !['board', 'dueAt'].includes(sort)) {
  282. sort = 'board';
  283. }
  284. return sort;
  285. },
  286. myCardsSortToggle() {
  287. if (this.myCardsSort() === 'board') {
  288. this.setMyCardsSort('dueAt');
  289. } else {
  290. this.setMyCardsSort('board');
  291. }
  292. },
  293. setMyCardsSort(sort) {
  294. window.localStorage.setItem('myCardsSort', sort);
  295. Utils.reload();
  296. },
  297. archivedBoardIds() {
  298. const ret = ReactiveCache.getBoards({ archived: false }).map(board => board._id);
  299. return ret;
  300. },
  301. dueCardsView() {
  302. let view = window.localStorage.getItem('dueCardsView');
  303. if (!view || !['me', 'all'].includes(view)) {
  304. view = 'me';
  305. }
  306. return view;
  307. },
  308. setDueCardsView(view) {
  309. window.localStorage.setItem('dueCardsView', view);
  310. Utils.reload();
  311. },
  312. myCardsView() {
  313. let view = window.localStorage.getItem('myCardsView');
  314. if (!view || !['boards', 'table'].includes(view)) {
  315. view = 'boards';
  316. }
  317. return view;
  318. },
  319. setMyCardsView(view) {
  320. window.localStorage.setItem('myCardsView', view);
  321. Utils.reload();
  322. },
  323. // XXX We should remove these two methods
  324. goBoardId(_id) {
  325. const board = ReactiveCache.getBoard(_id);
  326. return (
  327. board &&
  328. FlowRouter.go('board', {
  329. id: board._id,
  330. slug: board.slug,
  331. })
  332. );
  333. },
  334. goCardId(_id) {
  335. const card = ReactiveCache.getCard(_id);
  336. const board = ReactiveCache.getBoard(card.boardId);
  337. return (
  338. board &&
  339. FlowRouter.go('card', {
  340. cardId: card._id,
  341. boardId: board._id,
  342. slug: board.slug,
  343. })
  344. );
  345. },
  346. getCommonAttachmentMetaFrom(card) {
  347. const meta = {};
  348. if (card.isLinkedCard()) {
  349. meta.boardId = ReactiveCache.getCard(card.linkedId).boardId;
  350. meta.cardId = card.linkedId;
  351. } else {
  352. meta.boardId = card.boardId;
  353. meta.swimlaneId = card.swimlaneId;
  354. meta.listId = card.listId;
  355. meta.cardId = card._id;
  356. }
  357. return meta;
  358. },
  359. MAX_IMAGE_PIXEL: Meteor.settings.public.MAX_IMAGE_PIXEL,
  360. COMPRESS_RATIO: Meteor.settings.public.IMAGE_COMPRESS_RATIO,
  361. shrinkImage(options) {
  362. // shrink image to certain size
  363. const dataurl = options.dataurl,
  364. callback = options.callback,
  365. toBlob = options.toBlob;
  366. let canvas = document.createElement('canvas'),
  367. image = document.createElement('img');
  368. const maxSize = options.maxSize || 1024;
  369. const ratio = options.ratio || 1.0;
  370. const next = function (result) {
  371. image = null;
  372. canvas = null;
  373. if (typeof callback === 'function') {
  374. callback(result);
  375. }
  376. };
  377. image.onload = function () {
  378. let width = this.width,
  379. height = this.height;
  380. let changed = false;
  381. if (width > height) {
  382. if (width > maxSize) {
  383. height *= maxSize / width;
  384. width = maxSize;
  385. changed = true;
  386. }
  387. } else if (height > maxSize) {
  388. width *= maxSize / height;
  389. height = maxSize;
  390. changed = true;
  391. }
  392. canvas.width = width;
  393. canvas.height = height;
  394. canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  395. if (changed === true) {
  396. const type = 'image/jpeg';
  397. if (toBlob) {
  398. canvas.toBlob(next, type, ratio);
  399. } else {
  400. next(canvas.toDataURL(type, ratio));
  401. }
  402. } else {
  403. next(changed);
  404. }
  405. };
  406. image.onerror = function () {
  407. next(false);
  408. };
  409. image.src = dataurl;
  410. },
  411. capitalize(string) {
  412. return string.charAt(0).toUpperCase() + string.slice(1);
  413. },
  414. windowResizeDep: new Tracker.Dependency(),
  415. // in fact, what we really care is screen size
  416. // large mobile device like iPad or android Pad has a big screen, it should also behave like a desktop
  417. // in a small window (even on desktop), Wekan run in compact mode.
  418. // we can easily debug with a small window of desktop browser. :-)
  419. isMiniScreen() {
  420. this.windowResizeDep.depend();
  421. // Also depend on mobile mode changes to make this reactive
  422. Session.get('wekan-mobile-mode');
  423. // Show mobile view when:
  424. // 1. Screen width is 800px or less (matches CSS media queries)
  425. // 2. Mobile phones in portrait mode
  426. // 3. iPad in very small screens (≤ 600px)
  427. // 4. All iPhone models by default (including largest models), but respect user preference
  428. const isSmallScreen = window.innerWidth <= 800;
  429. const isVerySmallScreen = window.innerWidth <= 600;
  430. const isPortrait = window.innerWidth < window.innerHeight || window.matchMedia("(orientation: portrait)").matches;
  431. const isMobilePhone = /Mobile|Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && !/iPad/i.test(navigator.userAgent);
  432. const isIPhone = /iPhone|iPod/i.test(navigator.userAgent);
  433. const isIPad = /iPad/i.test(navigator.userAgent);
  434. const isUbuntuTouch = /Ubuntu/i.test(navigator.userAgent);
  435. // Check if user has explicitly set mobile mode preference
  436. const userMobileMode = this.getMobileMode();
  437. // For iPhone: default to mobile view, but respect user's mobile mode toggle preference
  438. // This ensures all iPhone models (including iPhone 15 Pro Max, 14 Pro Max, etc.) start with mobile view
  439. // but users can still switch to desktop mode if they prefer
  440. if (isIPhone) {
  441. // If user has explicitly set a preference, respect it
  442. if (userMobileMode !== null && userMobileMode !== undefined) {
  443. return userMobileMode;
  444. }
  445. // Otherwise, default to mobile view for iPhones
  446. return true;
  447. } else if (isMobilePhone) {
  448. return isPortrait; // Other mobile phones: portrait = mobile, landscape = desktop
  449. } else if (isIPad) {
  450. return isVerySmallScreen; // iPad: only very small screens get mobile view
  451. } else if (isUbuntuTouch) {
  452. // Ubuntu Touch: smartphones (≤ 600px) behave like mobile phones, tablets (> 600px) like iPad
  453. if (isVerySmallScreen) {
  454. return isPortrait; // Ubuntu Touch smartphone: portrait = mobile, landscape = desktop
  455. } else {
  456. return isVerySmallScreen; // Ubuntu Touch tablet: only very small screens get mobile view
  457. }
  458. } else {
  459. return isSmallScreen; // Desktop: based on 800px screen width
  460. }
  461. },
  462. isTouchScreen() {
  463. // NEW TOUCH DEVICE DETECTION:
  464. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
  465. var hasTouchScreen = false;
  466. if ("maxTouchPoints" in navigator) {
  467. hasTouchScreen = navigator.maxTouchPoints > 0;
  468. } else if ("msMaxTouchPoints" in navigator) {
  469. hasTouchScreen = navigator.msMaxTouchPoints > 0;
  470. } else {
  471. var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
  472. if (mQ && mQ.media === "(pointer:coarse)") {
  473. hasTouchScreen = !!mQ.matches;
  474. } else if ('orientation' in window) {
  475. hasTouchScreen = true; // deprecated, but good fallback
  476. } else {
  477. // Only as a last resort, fall back to user agent sniffing
  478. var UA = navigator.userAgent;
  479. hasTouchScreen = (
  480. /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
  481. /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
  482. );
  483. }
  484. }
  485. return hasTouchScreen;
  486. },
  487. // returns if desktop drag handles are enabled
  488. isShowDesktopDragHandles() {
  489. // Always show drag handles on all displays
  490. return true;
  491. },
  492. // returns if mini screen or desktop drag handles
  493. isTouchScreenOrShowDesktopDragHandles() {
  494. // Always enable drag handles for all displays
  495. return true;
  496. },
  497. calculateIndexData(prevData, nextData, nItems = 1) {
  498. let base, increment;
  499. // If we drop the card to an empty column
  500. if (!prevData && !nextData) {
  501. base = 0;
  502. increment = 1;
  503. // If we drop the card in the first position
  504. } else if (!prevData) {
  505. const nextSortIndex = nextData.sort;
  506. const ceil = Math.ceil(nextSortIndex - 1);
  507. if (ceil < nextSortIndex) {
  508. increment = nextSortIndex - ceil;
  509. base = nextSortIndex - increment;
  510. } else {
  511. base = nextData.sort - 1;
  512. increment = -1;
  513. }
  514. // If we drop the card in the last position
  515. } else if (!nextData) {
  516. const prevSortIndex = prevData.sort;
  517. const floor = Math.floor(prevSortIndex + 1);
  518. if (floor > prevSortIndex) {
  519. increment = prevSortIndex - floor;
  520. base = prevSortIndex - increment;
  521. } else {
  522. base = prevData.sort + 1;
  523. increment = 1;
  524. }
  525. }
  526. // In the general case take the average of the previous and next element
  527. // sort indexes.
  528. else {
  529. const prevSortIndex = prevData.sort;
  530. const nextSortIndex = nextData.sort;
  531. if (nItems == 1 ) {
  532. if (prevSortIndex < 0 ) {
  533. const ceil = Math.ceil(nextSortIndex - 1);
  534. if (ceil < nextSortIndex && ceil > prevSortIndex) {
  535. increment = ceil - prevSortIndex;
  536. }
  537. } else {
  538. const floor = Math.floor(nextSortIndex - 1);
  539. if (floor < nextSortIndex && floor > prevSortIndex) {
  540. increment = floor - prevSortIndex;
  541. }
  542. }
  543. }
  544. if (!increment) {
  545. increment = (nextSortIndex - prevSortIndex) / (nItems + 1);
  546. }
  547. if (!base) {
  548. base = prevSortIndex + increment;
  549. }
  550. }
  551. // XXX Return a generator that yield values instead of a base with a
  552. // increment number.
  553. return {
  554. base,
  555. increment,
  556. };
  557. },
  558. // Determine the new sort index
  559. calculateIndex(prevCardDomElement, nextCardDomElement, nCards = 1) {
  560. let prevData = null;
  561. let nextData = null;
  562. if (prevCardDomElement) {
  563. prevData = Blaze.getData(prevCardDomElement)
  564. }
  565. if (nextCardDomElement) {
  566. nextData = Blaze.getData(nextCardDomElement);
  567. }
  568. const ret = Utils.calculateIndexData(prevData, nextData, nCards);
  569. return ret;
  570. },
  571. manageCustomUI() {
  572. Meteor.call('getCustomUI', (err, data) => {
  573. if (err && err.error[0] === 'var-not-exist') {
  574. Session.set('customUI', false); // siteId || address server not defined
  575. }
  576. if (!err) {
  577. Utils.setCustomUI(data);
  578. }
  579. });
  580. },
  581. setCustomUI(data) {
  582. const currentBoard = Utils.getCurrentBoard();
  583. if (currentBoard) {
  584. DocHead.setTitle(`${currentBoard.title} - ${data.productName}`);
  585. } else {
  586. DocHead.setTitle(`${data.productName}`);
  587. }
  588. },
  589. setMatomo(data) {
  590. window._paq = window._paq || [];
  591. window._paq.push(['setDoNotTrack', data.doNotTrack]);
  592. if (data.withUserName) {
  593. window._paq.push(['setUserId', ReactiveCache.getCurrentUser().username]);
  594. }
  595. window._paq.push(['trackPageView']);
  596. window._paq.push(['enableLinkTracking']);
  597. (function () {
  598. window._paq.push(['setTrackerUrl', `${data.address}piwik.php`]);
  599. window._paq.push(['setSiteId', data.siteId]);
  600. const script = document.createElement('script');
  601. Object.assign(script, {
  602. id: 'scriptMatomo',
  603. type: 'text/javascript',
  604. async: 'true',
  605. defer: 'true',
  606. src: `${data.address}piwik.js`,
  607. });
  608. const s = document.getElementsByTagName('script')[0];
  609. s.parentNode.insertBefore(script, s);
  610. })();
  611. Session.set('matomo', true);
  612. },
  613. manageMatomo() {
  614. const matomo = Session.get('matomo');
  615. if (matomo === undefined) {
  616. Meteor.call('getMatomoConf', (err, data) => {
  617. if (err && err.error[0] === 'var-not-exist') {
  618. Session.set('matomo', false); // siteId || address server not defined
  619. }
  620. if (!err) {
  621. Utils.setMatomo(data);
  622. }
  623. });
  624. } else if (matomo) {
  625. window._paq.push(['trackPageView']);
  626. }
  627. },
  628. getTriggerActionDesc(event, tempInstance) {
  629. const jqueryEl = tempInstance.$(event.currentTarget.parentNode);
  630. const triggerEls = jqueryEl.find('.trigger-content').children();
  631. let finalString = '';
  632. for (let i = 0; i < triggerEls.length; i++) {
  633. const element = tempInstance.$(triggerEls[i]);
  634. if (element.hasClass('trigger-text')) {
  635. finalString += element.text().toLowerCase();
  636. } else if (element.hasClass('user-details')) {
  637. let username = element.find('input').val();
  638. if (username === undefined || username === '') {
  639. username = '*';
  640. }
  641. finalString += `${element
  642. .find('.trigger-text')
  643. .text()
  644. .toLowerCase()} ${username}`;
  645. } else if (element.find('select').length > 0) {
  646. finalString += element
  647. .find('select option:selected')
  648. .text()
  649. .toLowerCase();
  650. } else if (element.find('input').length > 0) {
  651. let inputvalue = element.find('input').val();
  652. if (inputvalue === undefined || inputvalue === '') {
  653. inputvalue = '*';
  654. }
  655. finalString += inputvalue;
  656. }
  657. // Add space
  658. if (i !== length - 1) {
  659. finalString += ' ';
  660. }
  661. }
  662. return finalString;
  663. },
  664. fallbackCopyTextToClipboard(text) {
  665. var textArea = document.createElement("textarea");
  666. textArea.value = text;
  667. // Avoid scrolling to bottom
  668. textArea.style.top = "0";
  669. textArea.style.left = "0";
  670. textArea.style.position = "fixed";
  671. document.body.appendChild(textArea);
  672. textArea.focus();
  673. textArea.select();
  674. try {
  675. document.execCommand('copy');
  676. return Promise.resolve(true);
  677. } catch (e) {
  678. return Promise.reject(false);
  679. } finally {
  680. document.body.removeChild(textArea);
  681. }
  682. },
  683. /** copy the text to the clipboard
  684. * @see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript/30810322#30810322
  685. * @param string copy this text to the clipboard
  686. * @return Promise
  687. */
  688. copyTextToClipboard(text) {
  689. let ret;
  690. if (navigator.clipboard) {
  691. ret = navigator.clipboard.writeText(text).then(function () {
  692. }, function (err) {
  693. console.error('Async: Could not copy text: ', err);
  694. });
  695. } else {
  696. ret = Utils.fallbackCopyTextToClipboard(text);
  697. }
  698. return ret;
  699. },
  700. /** show the "copied!" message
  701. * @param promise the promise of Utils.copyTextToClipboard
  702. * @param $tooltip jQuery tooltip element
  703. */
  704. showCopied(promise, $tooltip) {
  705. if (promise) {
  706. promise.then(() => {
  707. $tooltip.show(100);
  708. setTimeout(() => $tooltip.hide(100), 1000);
  709. }, (err) => {
  710. console.error("error: ", err);
  711. });
  712. }
  713. },
  714. };
  715. // A simple tracker dependency that we invalidate every time the window is
  716. // resized. This is used to reactively re-calculate the popup position in case
  717. // of a window resize. This is the equivalent of a "Signal" in some other
  718. // programming environments (eg, elm).
  719. $(window).on('resize', () => Utils.windowResizeDep.changed());