You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stopwatch.js 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import prettyMilliseconds from 'pretty-ms';
  2. import {createTippy} from '../modules/tippy.js';
  3. import {GET} from '../modules/fetch.js';
  4. import {hideElem, showElem} from '../utils/dom.js';
  5. const {appSubUrl, notificationSettings, enableTimeTracking, assetVersionEncoded} = window.config;
  6. export function initStopwatch() {
  7. if (!enableTimeTracking) {
  8. return;
  9. }
  10. const stopwatchEl = document.querySelector('.active-stopwatch-trigger');
  11. const stopwatchPopup = document.querySelector('.active-stopwatch-popup');
  12. if (!stopwatchEl || !stopwatchPopup) {
  13. return;
  14. }
  15. stopwatchEl.removeAttribute('href'); // intended for noscript mode only
  16. createTippy(stopwatchEl, {
  17. content: stopwatchPopup,
  18. placement: 'bottom-end',
  19. trigger: 'click',
  20. maxWidth: 'none',
  21. interactive: true,
  22. hideOnClick: true,
  23. });
  24. // global stop watch (in the head_navbar), it should always work in any case either the EventSource or the PeriodicPoller is used.
  25. const currSeconds = document.querySelector('.stopwatch-time')?.getAttribute('data-seconds');
  26. if (currSeconds) {
  27. updateStopwatchTime(currSeconds);
  28. }
  29. let usingPeriodicPoller = false;
  30. const startPeriodicPoller = (timeout) => {
  31. if (timeout <= 0 || !Number.isFinite(timeout)) return;
  32. usingPeriodicPoller = true;
  33. setTimeout(() => updateStopwatchWithCallback(startPeriodicPoller, timeout), timeout);
  34. };
  35. // if the browser supports EventSource and SharedWorker, use it instead of the periodic poller
  36. if (notificationSettings.EventSourceUpdateTime > 0 && window.EventSource && window.SharedWorker) {
  37. // Try to connect to the event source via the shared worker first
  38. const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js?v=${assetVersionEncoded}`, 'notification-worker');
  39. worker.addEventListener('error', (event) => {
  40. console.error('worker error', event);
  41. });
  42. worker.port.addEventListener('messageerror', () => {
  43. console.error('unable to deserialize message');
  44. });
  45. worker.port.postMessage({
  46. type: 'start',
  47. url: `${window.location.origin}${appSubUrl}/user/events`,
  48. });
  49. worker.port.addEventListener('message', (event) => {
  50. if (!event.data || !event.data.type) {
  51. console.error('unknown worker message event', event);
  52. return;
  53. }
  54. if (event.data.type === 'stopwatches') {
  55. updateStopwatchData(JSON.parse(event.data.data));
  56. } else if (event.data.type === 'no-event-source') {
  57. // browser doesn't support EventSource, falling back to periodic poller
  58. if (!usingPeriodicPoller) startPeriodicPoller(notificationSettings.MinTimeout);
  59. } else if (event.data.type === 'error') {
  60. console.error('worker port event error', event.data);
  61. } else if (event.data.type === 'logout') {
  62. if (event.data.data !== 'here') {
  63. return;
  64. }
  65. worker.port.postMessage({
  66. type: 'close',
  67. });
  68. worker.port.close();
  69. window.location.href = `${appSubUrl}/`;
  70. } else if (event.data.type === 'close') {
  71. worker.port.postMessage({
  72. type: 'close',
  73. });
  74. worker.port.close();
  75. }
  76. });
  77. worker.port.addEventListener('error', (e) => {
  78. console.error('worker port error', e);
  79. });
  80. worker.port.start();
  81. window.addEventListener('beforeunload', () => {
  82. worker.port.postMessage({
  83. type: 'close',
  84. });
  85. worker.port.close();
  86. });
  87. return;
  88. }
  89. startPeriodicPoller(notificationSettings.MinTimeout);
  90. }
  91. async function updateStopwatchWithCallback(callback, timeout) {
  92. const isSet = await updateStopwatch();
  93. if (!isSet) {
  94. timeout = notificationSettings.MinTimeout;
  95. } else if (timeout < notificationSettings.MaxTimeout) {
  96. timeout += notificationSettings.TimeoutStep;
  97. }
  98. callback(timeout);
  99. }
  100. async function updateStopwatch() {
  101. const response = await GET(`${appSubUrl}/user/stopwatches`);
  102. if (!response.ok) {
  103. console.error('Failed to fetch stopwatch data');
  104. return false;
  105. }
  106. const data = await response.json();
  107. return updateStopwatchData(data);
  108. }
  109. function updateStopwatchData(data) {
  110. const watch = data[0];
  111. const btnEl = document.querySelector('.active-stopwatch-trigger');
  112. if (!watch) {
  113. clearStopwatchTimer();
  114. hideElem(btnEl);
  115. } else {
  116. const {repo_owner_name, repo_name, issue_index, seconds} = watch;
  117. const issueUrl = `${appSubUrl}/${repo_owner_name}/${repo_name}/issues/${issue_index}`;
  118. document.querySelector('.stopwatch-link')?.setAttribute('href', issueUrl);
  119. document.querySelector('.stopwatch-commit')?.setAttribute('action', `${issueUrl}/times/stopwatch/toggle`);
  120. document.querySelector('.stopwatch-cancel')?.setAttribute('action', `${issueUrl}/times/stopwatch/cancel`);
  121. const stopwatchIssue = document.querySelector('.stopwatch-issue');
  122. if (stopwatchIssue) stopwatchIssue.textContent = `${repo_owner_name}/${repo_name}#${issue_index}`;
  123. updateStopwatchTime(seconds);
  124. showElem(btnEl);
  125. }
  126. return Boolean(data.length);
  127. }
  128. let updateTimeIntervalId = null; // holds setInterval id when active
  129. function clearStopwatchTimer() {
  130. if (updateTimeIntervalId !== null) {
  131. clearInterval(updateTimeIntervalId);
  132. updateTimeIntervalId = null;
  133. }
  134. }
  135. function updateStopwatchTime(seconds) {
  136. const secs = parseInt(seconds);
  137. if (!Number.isFinite(secs)) return;
  138. clearStopwatchTimer();
  139. const stopwatch = document.querySelector('.stopwatch-time');
  140. // TODO: replace with <relative-time> similar to how system status up time is shown
  141. const start = Date.now();
  142. const updateUi = () => {
  143. const delta = Date.now() - start;
  144. const dur = prettyMilliseconds(secs * 1000 + delta, {compact: true});
  145. if (stopwatch) stopwatch.textContent = dur;
  146. };
  147. updateUi();
  148. updateTimeIntervalId = setInterval(updateUi, 1000);
  149. }