utils.js 24 KB

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