gitea源码

stopwatch.ts 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import {createTippy} from '../modules/tippy.ts';
  2. import {GET} from '../modules/fetch.ts';
  3. import {hideElem, queryElems, showElem} from '../utils/dom.ts';
  4. import {logoutFromWorker} from '../modules/worker.ts';
  5. const {appSubUrl, notificationSettings, enableTimeTracking, assetVersionEncoded} = window.config;
  6. export function initStopwatch() {
  7. if (!enableTimeTracking) {
  8. return;
  9. }
  10. const stopwatchEls = document.querySelectorAll('.active-stopwatch');
  11. const stopwatchPopup = document.querySelector('.active-stopwatch-popup');
  12. if (!stopwatchEls.length || !stopwatchPopup) {
  13. return;
  14. }
  15. // global stop watch (in the head_navbar), it should always work in any case either the EventSource or the PeriodicPoller is used.
  16. const seconds = stopwatchEls[0]?.getAttribute('data-seconds');
  17. if (seconds) {
  18. updateStopwatchTime(parseInt(seconds));
  19. }
  20. for (const stopwatchEl of stopwatchEls) {
  21. stopwatchEl.removeAttribute('href'); // intended for noscript mode only
  22. createTippy(stopwatchEl, {
  23. content: stopwatchPopup.cloneNode(true) as Element,
  24. placement: 'bottom-end',
  25. trigger: 'click',
  26. maxWidth: 'none',
  27. interactive: true,
  28. hideOnClick: true,
  29. theme: 'default',
  30. });
  31. }
  32. let usingPeriodicPoller = false;
  33. const startPeriodicPoller = (timeout: number) => {
  34. if (timeout <= 0 || !Number.isFinite(timeout)) return;
  35. usingPeriodicPoller = true;
  36. setTimeout(() => updateStopwatchWithCallback(startPeriodicPoller, timeout), timeout);
  37. };
  38. // if the browser supports EventSource and SharedWorker, use it instead of the periodic poller
  39. if (notificationSettings.EventSourceUpdateTime > 0 && window.EventSource && window.SharedWorker) {
  40. // Try to connect to the event source via the shared worker first
  41. const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js?v=${assetVersionEncoded}`, 'notification-worker');
  42. worker.addEventListener('error', (event) => {
  43. console.error('worker error', event);
  44. });
  45. worker.port.addEventListener('messageerror', () => {
  46. console.error('unable to deserialize message');
  47. });
  48. worker.port.postMessage({
  49. type: 'start',
  50. url: `${window.location.origin}${appSubUrl}/user/events`,
  51. });
  52. worker.port.addEventListener('message', (event) => {
  53. if (!event.data || !event.data.type) {
  54. console.error('unknown worker message event', event);
  55. return;
  56. }
  57. if (event.data.type === 'stopwatches') {
  58. updateStopwatchData(JSON.parse(event.data.data));
  59. } else if (event.data.type === 'no-event-source') {
  60. // browser doesn't support EventSource, falling back to periodic poller
  61. if (!usingPeriodicPoller) startPeriodicPoller(notificationSettings.MinTimeout);
  62. } else if (event.data.type === 'error') {
  63. console.error('worker port event error', event.data);
  64. } else if (event.data.type === 'logout') {
  65. if (event.data.data !== 'here') {
  66. return;
  67. }
  68. worker.port.postMessage({
  69. type: 'close',
  70. });
  71. worker.port.close();
  72. logoutFromWorker();
  73. } else if (event.data.type === 'close') {
  74. worker.port.postMessage({
  75. type: 'close',
  76. });
  77. worker.port.close();
  78. }
  79. });
  80. worker.port.addEventListener('error', (e) => {
  81. console.error('worker port error', e);
  82. });
  83. worker.port.start();
  84. window.addEventListener('beforeunload', () => {
  85. worker.port.postMessage({
  86. type: 'close',
  87. });
  88. worker.port.close();
  89. });
  90. return;
  91. }
  92. startPeriodicPoller(notificationSettings.MinTimeout);
  93. }
  94. async function updateStopwatchWithCallback(callback: (timeout: number) => void, timeout: number) {
  95. const isSet = await updateStopwatch();
  96. if (!isSet) {
  97. timeout = notificationSettings.MinTimeout;
  98. } else if (timeout < notificationSettings.MaxTimeout) {
  99. timeout += notificationSettings.TimeoutStep;
  100. }
  101. callback(timeout);
  102. }
  103. async function updateStopwatch() {
  104. const response = await GET(`${appSubUrl}/user/stopwatches`);
  105. if (!response.ok) {
  106. console.error('Failed to fetch stopwatch data');
  107. return false;
  108. }
  109. const data = await response.json();
  110. return updateStopwatchData(data);
  111. }
  112. function updateStopwatchData(data: any) {
  113. const watch = data[0];
  114. const btnEls = document.querySelectorAll('.active-stopwatch');
  115. if (!watch) {
  116. hideElem(btnEls);
  117. } else {
  118. const {repo_owner_name, repo_name, issue_index, seconds} = watch;
  119. const issueUrl = `${appSubUrl}/${repo_owner_name}/${repo_name}/issues/${issue_index}`;
  120. document.querySelector('.stopwatch-link')?.setAttribute('href', issueUrl);
  121. document.querySelector('.stopwatch-commit')?.setAttribute('action', `${issueUrl}/times/stopwatch/stop`);
  122. document.querySelector('.stopwatch-cancel')?.setAttribute('action', `${issueUrl}/times/stopwatch/cancel`);
  123. const stopwatchIssue = document.querySelector('.stopwatch-issue');
  124. if (stopwatchIssue) stopwatchIssue.textContent = `${repo_owner_name}/${repo_name}#${issue_index}`;
  125. updateStopwatchTime(seconds);
  126. showElem(btnEls);
  127. }
  128. return Boolean(data.length);
  129. }
  130. // TODO: This flickers on page load, we could avoid this by making a custom element to render time periods.
  131. function updateStopwatchTime(seconds: number) {
  132. const hours = seconds / 3600 || 0;
  133. const minutes = seconds / 60 || 0;
  134. const timeText = hours >= 1 ? `${Math.round(hours)}h` : `${Math.round(minutes)}m`;
  135. queryElems(document, '.header-stopwatch-dot', (el) => el.textContent = timeText);
  136. }