Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

refactor: extract CaptureSession class for content script lifecycle

Luis Ortiza44ea8549258
diff --git a/src/core/capture/session.ts b/src/core/capture/session.ts
new file mode 100644
index 0000000..ab6f4a5
--- /dev/null
+++ b/src/core/capture/session.ts
@@ -0,0 +1,51 @@
+import { logger } from '@/lib/logger';
+import { startCapture } from './events';
+import { startRrwebRecording } from './rrweb-recorder';
+
+export class CaptureSession {
+ private stopEvents: (() => void) | null = null;
+ private stopReplay: (() => void) | null = null;
+ private activeGuideId: string | null = null;
+ private disabled = false;
+
+ get isActive(): boolean {
+ return this.activeGuideId !== null;
+ }
+
+ get isDisabled(): boolean {
+ return this.disabled;
+ }
+
+ get guideId(): string | null {
+ return this.activeGuideId;
+ }
+
+ start(guideId: string): void {
+ if (this.disabled) return;
+ if (this.isActive) {
+ this.stop();
+ }
+
+ logger.info('Capture started β†’ guideId:', guideId);
+ this.activeGuideId = guideId;
+ this.stopEvents = startCapture(guideId);
+ this.stopReplay = startRrwebRecording(guideId);
+ }
+
+ stop(): void {
+ if (!this.isActive) return;
+
+ logger.info('Capture stopped β†’ guideId:', this.activeGuideId);
+ this.stopEvents?.();
+ this.stopReplay?.();
+ this.stopEvents = null;
+ this.stopReplay = null;
+ this.activeGuideId = null;
+ }
+
+ dispose(): void {
+ this.stop();
+ this.disabled = true;
+ logger.debug('Capture session disposed');
+ }
+}
diff --git a/src/entrypoints/background/index.ts b/src/entrypoints/background/index.ts
index d424ebc..5958236 100644
--- a/src/entrypoints/background/index.ts
+++ b/src/entrypoints/background/index.ts
@@ -27,9 +27,7 @@ export default defineBackground(() => {
waitUntilReady().then(() => {
try {
port.postMessage(getStateUpdate());
- } catch {
- /* disconnected */
- }
+ } catch {}
});
});
diff --git a/src/entrypoints/background/navigation.ts b/src/entrypoints/background/navigation.ts
index d4eff39..1b6d536 100644
--- a/src/entrypoints/background/navigation.ts
+++ b/src/entrypoints/background/navigation.ts
@@ -49,8 +49,7 @@ export function registerNavigationListeners() {
if (isInjectableTab(tab)) {
await injectContentScript(activeInfo.tabId);
}
- } catch {
- }
+ } catch {}
}
});
@@ -67,8 +66,7 @@ export function registerNavigationListeners() {
logger.debug("Tab loaded β†’ injecting content script on tab", tabId);
try {
await injectContentScript(tabId);
- } catch {
- }
+ } catch {}
}
});
}
diff --git a/src/entrypoints/background/tab-manager.ts b/src/entrypoints/background/tab-manager.ts
index 460fdc8..26a206a 100644
--- a/src/entrypoints/background/tab-manager.ts
+++ b/src/entrypoints/background/tab-manager.ts
@@ -21,8 +21,7 @@ export async function injectContentScript(tabId: number): Promise<void> {
} catch {
try {
await executeScript(tabId, ['/content-scripts/content.js']);
- } catch {
- }
+ } catch {}
}
}
diff --git a/src/entrypoints/content.ts b/src/entrypoints/content.ts
index 9bdeaf1..7a3205c 100644
--- a/src/entrypoints/content.ts
+++ b/src/entrypoints/content.ts
@@ -4,100 +4,84 @@ import { defineContentScript } from 'wxt/utils/define-content-script';
import { sendMessage } from '@/lib/messaging';
import { TabMessage } from '@/lib/tab-messages';
import { CaptureState } from '@/core/capture/machine';
-import { startCapture } from '@/core/capture/events';
-import { startRrwebRecording } from '@/core/capture/rrweb-recorder';
+import { CaptureSession } from '@/core/capture/session';
import { updateUrl } from '@/core/capture/spa-nav';
-const CLEANUP_EVENT = `mimik_remove_content_script_${browser.runtime.id}`;
+const CLEANUP_EVENT = `mimik_cleanup_${browser.runtime.id}`;
-export default defineContentScript({
- matches: ['<all_urls>'],
- allFrames: true,
- matchAboutBlank: true,
- runAt: 'document_idle',
-
- main() {
- document.dispatchEvent(new CustomEvent(CLEANUP_EVENT));
-
- let stopCapture: (() => void) | null = null;
- let stopRrweb: (() => void) | null = null;
- let destroyed = false;
+function createTabMessageHandler(session: CaptureSession) {
+ return function handleTabMessage(
+ msg: Record<string, unknown>,
+ _sender: unknown,
+ sendResponse: (r: unknown) => void,
+ ) {
+ if (session.isDisabled) return false;
- function beginCapture(guideId: string) {
- if (destroyed) return;
- logger.info('Begin capture β†’ guideId:', guideId);
- stopCapture?.();
- stopRrweb?.();
- stopCapture = startCapture(guideId);
- stopRrweb = startRrwebRecording(guideId);
- }
-
- function endCapture() {
- if (stopCapture) logger.info('End capture');
- stopCapture?.();
- stopRrweb?.();
- stopCapture = null;
- stopRrweb = null;
- }
-
- function cleanup() {
- destroyed = true;
- endCapture();
- browser.runtime.onMessage.removeListener(messageHandler);
- document.removeEventListener(CLEANUP_EVENT, cleanup);
- }
-
- document.addEventListener(CLEANUP_EVENT, cleanup);
- window.addEventListener('beforeunload', () => endCapture());
-
- function messageHandler(
- msg: Record<string, unknown>,
- _sender: unknown,
- sendResponse: (r: unknown) => void,
- ) {
- if (destroyed) return false;
-
- if (msg.type === TabMessage.PING) {
+ switch (msg.type) {
+ case TabMessage.PING:
sendResponse({ alive: true });
return true;
- }
- if (msg.type === TabMessage.GET_ROUTE) {
- sendResponse({ alive: true, capturing: !!stopCapture });
+ case TabMessage.GET_ROUTE:
+ sendResponse({ alive: true, capturing: session.isActive });
return true;
- }
- if (msg.type === TabMessage.START_CAPTURE && msg.guideId) {
- beginCapture(msg.guideId as string);
- sendResponse({ started: true });
+ case TabMessage.START_CAPTURE:
+ if (msg.guideId) {
+ session.start(msg.guideId as string);
+ sendResponse({ started: true });
+ }
return true;
- }
- if (msg.type === TabMessage.STOP_CAPTURE) {
- endCapture();
+ case TabMessage.STOP_CAPTURE:
+ session.stop();
sendResponse({ stopped: true });
return true;
- }
- if (msg.type === TabMessage.URL_CHANGED && msg.url) {
- updateUrl(msg.url as string);
- sendResponse({ updated: true });
+ case TabMessage.URL_CHANGED:
+ if (msg.url) {
+ updateUrl(msg.url as string);
+ sendResponse({ updated: true });
+ }
return true;
- }
- return false;
+ default:
+ return false;
}
+ };
+}
+
+function syncWithBackground(session: CaptureSession) {
+ sendMessage('getState', undefined)
+ .then(res => {
+ if (session.isDisabled) return;
+ if (res.state === CaptureState.RECORDING && res.currentGuideId) {
+ session.start(res.currentGuideId);
+ }
+ })
+ .catch(() => {});
+}
+
+export default defineContentScript({
+ matches: ['<all_urls>'],
+ allFrames: true,
+ matchAboutBlank: true,
+ runAt: 'document_idle',
- browser.runtime.onMessage.addListener(messageHandler);
+ main() {
+ document.dispatchEvent(new CustomEvent(CLEANUP_EVENT));
- sendMessage('getState', undefined)
- .then(res => {
- if (destroyed) return;
- if (res.state === CaptureState.RECORDING && res.currentGuideId) {
- beginCapture(res.currentGuideId);
- }
- })
- .catch(() => {});
+ const session = new CaptureSession();
+ const handleTabMessage = createTabMessageHandler(session);
+
+ document.addEventListener(CLEANUP_EVENT, () => {
+ session.dispose();
+ browser.runtime.onMessage.removeListener(handleTabMessage);
+ });
+
+ window.addEventListener('beforeunload', () => session.stop());
+ browser.runtime.onMessage.addListener(handleTabMessage);
+ syncWithBackground(session);
logger.info('Content script loaded β†’', window.location.href);
},