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(blur): put detection behind a BlurDetector interface

Luis Ortiz5de4db0ddc8c
diff --git a/packages/core/src/blur/__tests__/regexes.test.ts b/packages/core/src/blur/__tests__/regexes.test.ts
index 79f6cc6..9d26fbd 100644
--- a/packages/core/src/blur/__tests__/regexes.test.ts
+++ b/packages/core/src/blur/__tests__/regexes.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { findMatches, PRESET_LABELS, PRESET_REGEXES, type PresetKey } from '../regexes';
+import { activePatterns, findMatches, PRESET_LABELS, PRESET_REGEXES, type PresetKey } from '../regexes';
describe('PRESET_LABELS', () => {
it('has a label for every preset key', () => {
@@ -362,3 +362,21 @@ describe('PRESET_REGEXES', () => {
}
});
});
+
+describe('activePatterns', () => {
+ it('maps only the categories that are switched on', () => {
+ expect(activePatterns(['email', 'ssn'])).toHaveLength(2);
+ expect(activePatterns([])).toHaveLength(0);
+ });
+
+ it('hands out fresh regexes so a stale lastIndex cannot drop a match', () => {
+ const [first] = activePatterns(['email']);
+ first.exec('contact me at [email protected] please');
+ expect(first.lastIndex).toBeGreaterThan(0);
+
+ const [second] = activePatterns(['email']);
+ expect(second).not.toBe(first);
+ expect(second.lastIndex).toBe(0);
+ expect(findMatches('[email protected]', activePatterns(['email']))).toHaveLength(1);
+ });
+});
diff --git a/packages/core/src/blur/detector.ts b/packages/core/src/blur/detector.ts
new file mode 100644
index 0000000..4b16ac0
--- /dev/null
+++ b/packages/core/src/blur/detector.ts
@@ -0,0 +1,9 @@
+import type { PresetKey } from './regexes';
+
+export interface BlurDetector {
+ start(presets: PresetKey[]): void;
+ updatePresets(presets: PresetKey[]): void;
+ unblurAll(): void;
+ detach(): void;
+ stop(): void;
+}
diff --git a/packages/core/src/blur/regexes.ts b/packages/core/src/blur/regexes.ts
index fb4e7fc..cd8d115 100644
--- a/packages/core/src/blur/regexes.ts
+++ b/packages/core/src/blur/regexes.ts
@@ -19,6 +19,24 @@ export const PRESET_LABELS: Record<PresetKey, string> = {
macAddress: 'MAC Address',
};
+export const DEFAULT_PRESETS: Record<PresetKey, boolean> = {
+ email: true,
+ phone: true,
+ ssn: false,
+ creditCard: false,
+ ipAddress: false,
+ macAddress: false,
+};
+
+export function activePatterns(presets: PresetKey[]): RegExp[] {
+ const patterns: RegExp[] = [];
+ for (const key of presets) {
+ const regex = PRESET_REGEXES[key];
+ if (regex) patterns.push(new RegExp(regex.source, regex.flags));
+ }
+ return patterns;
+}
+
export interface MatchRange {
start: number;
end: number;
diff --git a/packages/core/src/blur/scanner.ts b/packages/core/src/blur/scanner.ts
index 4395faa..d9e38c6 100644
--- a/packages/core/src/blur/scanner.ts
+++ b/packages/core/src/blur/scanner.ts
@@ -1,4 +1,5 @@
-import { findMatches, type MatchRange, PRESET_REGEXES, type PresetKey } from './regexes';
+import type { BlurDetector } from './detector';
+import { activePatterns, findMatches, type MatchRange, type PresetKey } from './regexes';
import { injectBlurStyles } from './styles';
const BLUR_CLASS = 'mimik-blur';
@@ -7,7 +8,7 @@ const PEEK_CLASS = 'mimik-blur-peek';
const INPUT_BLUR = 'blur(10px)';
const EXCLUDED_TAGS = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'IFRAME', 'TEXTAREA', 'INPUT', 'SELECT', 'OPTION']);
-export class BlurScanner {
+export class BlurScanner implements BlurDetector {
private observer: MutationObserver | null = null;
private debounceTimer: ReturnType<typeof setTimeout> | null = null;
private onInput: (() => void) | null = null;
@@ -39,17 +40,8 @@ export class BlurScanner {
if (this.debounceTimer) clearTimeout(this.debounceTimer);
}
- private getActivePatterns(): RegExp[] {
- const patterns: RegExp[] = [];
- for (const key of this.activePresets) {
- const regex = PRESET_REGEXES[key];
- if (regex) patterns.push(new RegExp(regex.source, regex.flags));
- }
- return patterns;
- }
-
private scan() {
- const patterns = this.getActivePatterns();
+ const patterns = activePatterns(this.activePresets);
if (patterns.length === 0) return;
this.blurTextNodes(document.body, patterns);
this.blurInputFields(patterns);
diff --git a/src/blur/__tests__/detector.test.ts b/src/blur/__tests__/detector.test.ts
new file mode 100644
index 0000000..98b0d1b
--- /dev/null
+++ b/src/blur/__tests__/detector.test.ts
@@ -0,0 +1,93 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { BlurDetector } from '@/core/blur/detector';
+import type { PresetKey } from '@/core/blur/regexes';
+import { BlurManager } from '../manager';
+
+const stored: { blurPresets?: Record<PresetKey, boolean> } = {};
+
+vi.mock('#imports', () => ({
+ browser: {
+ storage: {
+ local: {
+ get: vi.fn(async () => stored),
+ set: vi.fn(async (items: Record<string, unknown>) => Object.assign(stored, items)),
+ },
+ },
+ },
+}));
+
+vi.mock('@/lib/messaging', () => ({ sendMessage: vi.fn(async () => undefined) }));
+
+vi.mock('@/core/blur/panel', () => ({
+ BlurPanel: class {
+ mount() {}
+ unmount() {}
+ },
+}));
+
+function recordingDetector() {
+ const calls: string[] = [];
+ const presets: PresetKey[][] = [];
+ const detector: BlurDetector = {
+ start: (p) => {
+ calls.push('start');
+ presets.push(p);
+ },
+ updatePresets: (p) => {
+ calls.push('updatePresets');
+ presets.push(p);
+ },
+ unblurAll: () => calls.push('unblurAll'),
+ detach: () => calls.push('detach'),
+ stop: () => calls.push('stop'),
+ };
+ return { detector, calls, presets };
+}
+
+beforeEach(() => {
+ document.body.innerHTML = '';
+ for (const key of Object.keys(stored)) delete (stored as Record<string, unknown>)[key];
+});
+
+describe('BlurManager against a detector that is not the DOM scanner', () => {
+ it('starts it with the categories that are switched on', async () => {
+ const { detector, calls, presets } = recordingDetector();
+
+ await new BlurManager(detector).start();
+
+ expect(calls).toEqual(['start']);
+ expect(presets[0]).toEqual(['email', 'phone']);
+ });
+
+ it('routes a category change through the interface', async () => {
+ const { detector, calls, presets } = recordingDetector();
+ await new BlurManager(detector).start();
+
+ document.dispatchEvent(
+ new CustomEvent('mimik-blur:update-presets', { detail: { presets: ['ssn', 'creditCard'] } }),
+ );
+
+ expect(calls).toContain('updatePresets');
+ expect(presets.at(-1)).toEqual(['ssn', 'creditCard']);
+ });
+
+ it('routes a reset through the interface', async () => {
+ const { detector, calls } = recordingDetector();
+ await new BlurManager(detector).start();
+
+ document.dispatchEvent(new CustomEvent('mimik-blur:reset'));
+
+ expect(calls).toContain('unblurAll');
+ });
+
+ it('tears the detector down on stop', async () => {
+ const { detector, calls } = recordingDetector();
+ const manager = new BlurManager(detector);
+ await manager.start();
+
+ manager.stop();
+
+ expect(calls).toContain('stop');
+ });
+});
diff --git a/src/blur/manager.ts b/src/blur/manager.ts
index 86a2ce1..33ce6e2 100644
--- a/src/blur/manager.ts
+++ b/src/blur/manager.ts
@@ -1,28 +1,21 @@
import { browser } from '#imports';
+import type { BlurDetector } from '@/core/blur/detector';
import { BlurPanel } from '@/core/blur/panel';
-import type { PresetKey } from '@/core/blur/regexes';
+import { DEFAULT_PRESETS, type PresetKey } from '@/core/blur/regexes';
import { BlurScanner } from '@/core/blur/scanner';
import { injectBlurStyles, removeBlurStyles } from '@/core/blur/styles';
import { sendMessage } from '@/lib/messaging';
import { ElementPicker } from './element-picker';
-const DEFAULT_PRESETS: Record<PresetKey, boolean> = {
- email: true,
- phone: true,
- ssn: false,
- creditCard: false,
- ipAddress: false,
- macAddress: false,
-};
-
const EVENTS = ['mimik-blur:update-presets', 'mimik-blur:start-picker', 'mimik-blur:reset', 'mimik-blur:done'] as const;
export class BlurManager {
- private scanner = new BlurScanner();
private picker = new ElementPicker();
private panel: BlurPanel | null = null;
private active = false;
+ constructor(private detector: BlurDetector = new BlurScanner()) {}
+
async start() {
if (this.active) return;
this.active = true;
@@ -31,7 +24,7 @@ export class BlurManager {
const presets = await this.loadPresets();
const activeKeys = (Object.entries(presets) as [PresetKey, boolean][]).filter(([, on]) => on).map(([k]) => k);
- this.scanner.start(activeKeys);
+ this.detector.start(activeKeys);
this.panel = new BlurPanel(presets);
this.panel.mount();
@@ -41,7 +34,7 @@ export class BlurManager {
stop() {
if (!this.active) return;
this.teardown();
- this.scanner.stop();
+ this.detector.stop();
removeBlurStyles();
}
@@ -49,7 +42,7 @@ export class BlurManager {
this.active = false;
this.panel?.unmount();
this.panel = null;
- this.scanner.detach();
+ this.detector.detach();
this.picker.stop();
for (const event of EVENTS) document.removeEventListener(event, this.handleEvent);
}
@@ -58,7 +51,7 @@ export class BlurManager {
switch (e.type) {
case 'mimik-blur:update-presets': {
const activeKeys = (e as CustomEvent<{ presets: PresetKey[] }>).detail.presets;
- this.scanner.updatePresets(activeKeys);
+ this.detector.updatePresets(activeKeys);
this.savePresets(activeKeys);
break;
}
@@ -66,7 +59,7 @@ export class BlurManager {
this.picker.start(() => this.picker.stop());
break;
case 'mimik-blur:reset':
- this.scanner.unblurAll();
+ this.detector.unblurAll();
break;
case 'mimik-blur:done':
this.teardown();