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: share narration slicing, the mic button rule, the narration notice, one rect type and one desktop locale list

Luis Ortiza64721b389e6
diff --git a/apps/desktop/src/renderer/__tests__/app-locale.test.ts b/apps/desktop/src/main/__tests__/app-locale.test.ts
similarity index 92%
rename from apps/desktop/src/renderer/__tests__/app-locale.test.ts
rename to apps/desktop/src/main/__tests__/app-locale.test.ts
index cb493a7..496173a 100644
--- a/apps/desktop/src/renderer/__tests__/app-locale.test.ts
+++ b/apps/desktop/src/main/__tests__/app-locale.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { appLocale } from '../lib/app-locale';
+import { appLocale } from '../app-locale';
describe('appLocale', () => {
it('takes the language picked in settings', () => {
diff --git a/apps/desktop/src/renderer/lib/app-locale.ts b/apps/desktop/src/main/app-locale.ts
similarity index 100%
rename from apps/desktop/src/renderer/lib/app-locale.ts
rename to apps/desktop/src/main/app-locale.ts
diff --git a/apps/desktop/src/main/app-messages.ts b/apps/desktop/src/main/app-messages.ts
new file mode 100644
index 0000000..805867d
--- /dev/null
+++ b/apps/desktop/src/main/app-messages.ts
@@ -0,0 +1,19 @@
+import type { Messages } from '@mimik/core/i18n/translate';
+import de from '@mimik/locales/de.yml';
+import en from '@mimik/locales/en.yml';
+import es from '@mimik/locales/es.yml';
+import fr from '@mimik/locales/fr.yml';
+import ptBR from '@mimik/locales/pt-BR.yml';
+import ru from '@mimik/locales/ru.yml';
+import zhCN from '@mimik/locales/zh-CN.yml';
+import type { AppLocale } from './app-locale';
+
+export const APP_MESSAGES: Record<AppLocale, Messages> = {
+ en: en as Messages,
+ de: de as Messages,
+ es: es as Messages,
+ fr: fr as Messages,
+ 'pt-BR': ptBR as Messages,
+ 'zh-CN': zhCN as Messages,
+ ru: ru as Messages,
+};
diff --git a/apps/desktop/src/main/capture/region.ts b/apps/desktop/src/main/capture/region.ts
index e565548..aef8d0b 100644
--- a/apps/desktop/src/main/capture/region.ts
+++ b/apps/desktop/src/main/capture/region.ts
@@ -1,21 +1,15 @@
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import type { Rect } from '@mimik/core/rect';
import { app, screen } from 'electron';
-export interface Region {
- x: number;
- y: number;
- width: number;
- height: number;
-}
-
const MIN_REGION = { width: 60, height: 30 };
function file(): string {
return join(app.getPath('userData'), 'capture-region.json');
}
-export function defaultRegion(): Region {
+export function defaultRegion(): Rect {
const { workArea } = screen.getPrimaryDisplay();
const width = Math.round(workArea.width * 0.6);
const height = Math.round(workArea.height * 0.6);
@@ -27,7 +21,7 @@ export function defaultRegion(): Region {
};
}
-export function clampToDisplays(region: Region): Region {
+export function clampToDisplays(region: Rect): Rect {
const { workArea } = screen.getDisplayMatching(region);
const width = Math.min(Math.max(region.width, MIN_REGION.width), workArea.width);
const height = Math.min(Math.max(region.height, MIN_REGION.height), workArea.height);
@@ -39,18 +33,18 @@ export function clampToDisplays(region: Region): Region {
};
}
-export function loadRegion(): Region {
+export function loadRegion(): Rect {
try {
- const stored = JSON.parse(readFileSync(file(), 'utf8')) as Partial<Region>;
+ const stored = JSON.parse(readFileSync(file(), 'utf8')) as Partial<Rect>;
const complete = (['x', 'y', 'width', 'height'] as const).every((k) => Number.isFinite(stored[k]));
if (!complete) return defaultRegion();
- return clampToDisplays(stored as Region);
+ return clampToDisplays(stored as Rect);
} catch {
return defaultRegion();
}
}
-export function saveRegion(region: Region): Region {
+export function saveRegion(region: Rect): Rect {
const clamped = clampToDisplays(region);
try {
writeFileSync(file(), JSON.stringify(clamped));
diff --git a/apps/desktop/src/main/capture/screenshot.ts b/apps/desktop/src/main/capture/screenshot.ts
index 84cbb4d..4cd9a12 100644
--- a/apps/desktop/src/main/capture/screenshot.ts
+++ b/apps/desktop/src/main/capture/screenshot.ts
@@ -1,3 +1,4 @@
+import type { Rect } from '@mimik/core/rect';
import { screen } from 'electron';
import { Monitor } from 'node-screenshots';
@@ -13,13 +14,6 @@ export interface Capture {
displayId: number;
}
-export interface Rect {
- x: number;
- y: number;
- width: number;
- height: number;
-}
-
function monitorAt(x: number, y: number): Monitor {
const found = Monitor.fromPoint(Math.round(x), Math.round(y));
if (found) return found;
diff --git a/apps/desktop/src/main/capture/settings.ts b/apps/desktop/src/main/capture/settings.ts
index c429c01..eba06aa 100644
--- a/apps/desktop/src/main/capture/settings.ts
+++ b/apps/desktop/src/main/capture/settings.ts
@@ -1,14 +1,12 @@
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { snapZoom } from '@mimik/core/screenshot/record';
import { app } from 'electron';
export type CaptureMode = 'window' | 'screen' | 'area';
const CAPTURE_MODES: CaptureMode[] = ['window', 'screen', 'area'];
const MAX_SCREENSHOT_DELAY_MS = 2000;
-const MIN_ZOOM = 1;
-const MAX_ZOOM = 5;
-const ZOOM_STEP = 0.25;
export const MIN_TYPING_DEBOUNCE_MS = 200;
export const MAX_TYPING_DEBOUNCE_MS = 5000;
@@ -69,10 +67,6 @@ function file(): string {
return join(app.getPath('userData'), 'capture-settings.json');
}
-function snapZoom(zoom: number): number {
- return Math.min(Math.max(Math.round(zoom / ZOOM_STEP) * ZOOM_STEP, MIN_ZOOM), MAX_ZOOM);
-}
-
type LegacySettings = Partial<Record<'captureOutsideClicks' | 'captureKeys' | 'captureTyping', unknown>>;
export function normaliseSettings(input: Partial<CaptureSettings> & LegacySettings): CaptureSettings {
diff --git a/apps/desktop/src/main/i18n.ts b/apps/desktop/src/main/i18n.ts
index 699b73d..c75138e 100644
--- a/apps/desktop/src/main/i18n.ts
+++ b/apps/desktop/src/main/i18n.ts
@@ -1,41 +1,15 @@
-import de from '@mimik/locales/de.yml';
-import en from '@mimik/locales/en.yml';
-import es from '@mimik/locales/es.yml';
-import fr from '@mimik/locales/fr.yml';
-import ptBR from '@mimik/locales/pt-BR.yml';
-import ru from '@mimik/locales/ru.yml';
-import zhCN from '@mimik/locales/zh-CN.yml';
+import { translate } from '@mimik/core/i18n/translate';
+import { type AppLocale, appLocale } from './app-locale';
+import { APP_MESSAGES } from './app-messages';
-type Messages = { [key: string]: string | Messages };
-
-const LOCALES: Record<string, Messages> = {
- en: en as Messages,
- de: de as Messages,
- es: es as Messages,
- fr: fr as Messages,
- 'pt-BR': ptBR as Messages,
- 'zh-CN': zhCN as Messages,
- ru: ru as Messages,
-};
-const active = { locale: 'en' };
-
-function lookup(messages: Messages, key: string): string | undefined {
- const found = key
- .split('.')
- .reduce<string | Messages | undefined>(
- (node, part) => (typeof node === 'object' ? node[part] : undefined),
- messages,
- );
- return typeof found === 'string' ? found : undefined;
-}
+const active: { locale: AppLocale } = { locale: 'en' };
export const mainI18n = {
setLocale(code: string): void {
- const language = code.split('-')[0];
- active.locale = LOCALES[code] ? code : (Object.keys(LOCALES).find((l) => l.split('-')[0] === language) ?? 'en');
+ active.locale = appLocale(null, code);
},
t(key: string, substitutions: string[] = []): string {
- const text = lookup(LOCALES[active.locale], key) ?? lookup(LOCALES.en, key) ?? key;
- return substitutions.reduce((out, value, i) => out.replaceAll(`$${i + 1}`, value), text);
+ const text = translate(APP_MESSAGES[active.locale], key, substitutions);
+ return text === key ? translate(APP_MESSAGES.en, key, substitutions) : text;
},
};
diff --git a/apps/desktop/src/renderer/core-env.ts b/apps/desktop/src/renderer/core-env.ts
index 8b2018c..f08f909 100644
--- a/apps/desktop/src/renderer/core-env.ts
+++ b/apps/desktop/src/renderer/core-env.ts
@@ -1,26 +1,10 @@
import { configureCore } from '@mimik/core/env';
import type { Settings, SettingsKey } from '@mimik/core/guides/types';
-import { type Messages, translate } from '@mimik/core/i18n/translate';
-import de from '@mimik/locales/de.yml';
-import en from '@mimik/locales/en.yml';
-import es from '@mimik/locales/es.yml';
-import fr from '@mimik/locales/fr.yml';
-import ptBR from '@mimik/locales/pt-BR.yml';
-import ru from '@mimik/locales/ru.yml';
-import zhCN from '@mimik/locales/zh-CN.yml';
-import { type AppLocale, appLocale } from './lib/app-locale';
+import { translate } from '@mimik/core/i18n/translate';
+import { appLocale } from '../main/app-locale';
+import { APP_MESSAGES as MESSAGES } from '../main/app-messages';
import { mainFetch } from './lib/main-fetch';
-const MESSAGES: Record<AppLocale, Messages> = {
- en: en as Messages,
- de: de as Messages,
- es: es as Messages,
- fr: fr as Messages,
- 'pt-BR': ptBR as Messages,
- 'zh-CN': zhCN as Messages,
- ru: ru as Messages,
-};
-
const locale = appLocale(window.localStorage.getItem('appLanguage')?.replace(/^"|"$/g, ''), navigator.language);
window.mimik?.locale(locale);
diff --git a/apps/desktop/src/renderer/narration.ts b/apps/desktop/src/renderer/narration.ts
index b3df548..a070b3a 100644
--- a/apps/desktop/src/renderer/narration.ts
+++ b/apps/desktop/src/renderer/narration.ts
@@ -4,7 +4,7 @@ import { describeStepNow, describeUnnarratedSteps } from '@mimik/core/capture/vo
import { MicRecorder } from '@mimik/core/capture/voice/mic-recorder';
import { narrateRecording, type VoiceRecording } from '@mimik/core/capture/voice/narrate-recording';
import { NARRATION_SETTLE_MS } from '@mimik/core/capture/voice/narration-settle-ms';
-import { partialRecording } from '@mimik/core/capture/voice/partial-recording';
+import { NarrationSlicer } from '@mimik/core/capture/voice/narration-slicer';
import { readTranscriptionSettings } from '@mimik/core/capture/voice/read-transcription-settings';
import { readVoiceSettings } from '@mimik/core/capture/voice/read-voice-settings';
import { startFailureReason } from '@mimik/core/capture/voice/start-failure-reason';
@@ -20,7 +20,7 @@ export class DesktopNarration {
private live: Promise<MicRecorder | null> | null = null;
private mic: MicRecorder | null = null;
private guideId: string | null = null;
- private flushedUpTo = 0;
+ private slicer = new NarrationSlicer();
private narrated = 0;
private lost = false;
private current: VoiceUpdate = { phase: 'idle' };
@@ -46,14 +46,11 @@ export class DesktopNarration {
deferDescription(guideId, mark.stepId, describe ?? (() => this.undescribed(mark.stepId)));
const mic = this.mic;
this.track(async () => {
- const full = mic && usableRecording(mic.snapshot());
- const closesAt = full ? (mark.timestamp - full.audioEpochMs) / 1000 : 0;
- const slice = full && closesAt > this.flushedUpTo ? partialRecording(full, this.flushedUpTo, closesAt) : null;
+ const slice = this.slicer.forStep(mic && usableRecording(mic.snapshot()), mark.timestamp);
if (!slice) {
describeStepNow(guideId, mark.stepId);
return;
}
- this.flushedUpTo = closesAt;
const narrated = await this.transcribe(guideId, slice, [mark]);
if (!narrated.includes(mark.stepId)) describeStepNow(guideId, mark.stepId);
});
@@ -62,10 +59,10 @@ export class DesktopNarration {
stop(): void {
const opening = this.live;
const guideId = this.guideId;
- const from = this.flushedUpTo;
+ const slicer = this.slicer;
this.live = null;
this.mic = null;
- this.flushedUpTo = 0;
+ this.slicer = new NarrationSlicer();
window.mimik.capture.narration(null);
if (!opening || !guideId) return;
if (this.current.phase === 'recording') this.report({ phase: 'transcribing' });
@@ -75,7 +72,7 @@ export class DesktopNarration {
const audio = mic && usableRecording(mic.stop());
window.mimik.capture.narration(null);
await Promise.all(inflight);
- const tail = audio && from > 0 ? partialRecording(audio, from, audio.durationSeconds) : audio;
+ const tail = audio && slicer.tail(audio);
const steps = await getStepsForGuide(guideId);
if (tail && steps.length > 0) {
await this.transcribe(
@@ -89,12 +86,12 @@ export class DesktopNarration {
});
}
- abort(): void {
+ turnOff(): void {
const opening = this.live;
const guideId = this.guideId;
this.live = null;
this.mic = null;
- this.flushedUpTo = 0;
+ this.slicer = new NarrationSlicer();
window.mimik.capture.narration(null);
void opening?.then((mic) => {
mic?.release();
diff --git a/apps/desktop/src/renderer/overlay/controls.ts b/apps/desktop/src/renderer/overlay/controls.ts
index 2396866..c0a9bab 100644
--- a/apps/desktop/src/renderer/overlay/controls.ts
+++ b/apps/desktop/src/renderer/overlay/controls.ts
@@ -1,6 +1,7 @@
import { aiFailureNotice } from '@mimik/core/capture/ai/errors';
import { CaptureState } from '@mimik/core/capture/machine';
import { splitAtShortcut } from '@mimik/core/capture/split-at-shortcut';
+import { micToggleState } from '@mimik/core/capture/voice/mic-toggle-state';
import { readVoiceSettings } from '@mimik/core/capture/voice/read-voice-settings';
import { voiceErrorKey } from '@mimik/core/capture/voice/voice-error-key';
import { i18n } from '@mimik/core/env';
@@ -226,13 +227,11 @@ export function controls(): void {
}
badge.hidden = paused || collapsed;
- const micLocked = (!micKeyed && !micOn) || paused;
+ const { locked: micLocked, labelKey: micLabelKey } = micToggleState(micOn, micKeyed, paused);
const micState = `${micOn ? 'on' : micLocked ? 'locked' : 'off'}${paused ? ':paused' : ''}`;
if (micState !== shownMic) {
shownMic = micState;
- const micLabel = i18n.t(
- paused ? 'voice.pausedWithCapture' : micLocked ? 'voice.needsApiKey' : micOn ? 'voice.turnOff' : 'voice.turnOn',
- );
+ const micLabel = i18n.t(micLabelKey);
mic.className = micLocked ? 'locked' : micOn ? 'on' : 'off';
mic.title = micLabel;
mic.setAttribute('aria-label', micLabel);
diff --git a/apps/desktop/src/renderer/overlay/editor.ts b/apps/desktop/src/renderer/overlay/editor.ts
index ddaa29d..ac9f010 100644
--- a/apps/desktop/src/renderer/overlay/editor.ts
+++ b/apps/desktop/src/renderer/overlay/editor.ts
@@ -1,7 +1,7 @@
import { i18n } from '@mimik/core/env';
+import type { Rect } from '@mimik/core/rect';
import { icon } from '../icons';
import { el } from './el';
-import type { Region } from './types';
const MIN = { width: 60, height: 30 };
@@ -9,7 +9,7 @@ const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as const;
type Handle = (typeof HANDLES)[number];
-function normalise(a: { x: number; y: number }, b: { x: number; y: number }): Region {
+function normalise(a: { x: number; y: number }, b: { x: number; y: number }): Rect {
return {
x: Math.min(a.x, b.x),
y: Math.min(a.y, b.y),
@@ -52,7 +52,7 @@ export function editor(origin: { x: number; y: number }): void {
);
document.body.append(region, bar);
- let rect: Region | null = null;
+ let rect: Rect | null = null;
function paint(): void {
if (!rect) {
@@ -73,7 +73,7 @@ export function editor(origin: { x: number; y: number }): void {
size.textContent = `${Math.round(rect.width)} Γ— ${Math.round(rect.height)}`;
}
- function commit(next: Region): void {
+ function commit(next: Rect): void {
rect = next;
paint();
window.mimikOverlay.setRegion(next);
diff --git a/packages/core/src/capture/voice/__tests__/narration-slicer.test.ts b/packages/core/src/capture/voice/__tests__/narration-slicer.test.ts
new file mode 100644
index 0000000..53e7c7a
--- /dev/null
+++ b/packages/core/src/capture/voice/__tests__/narration-slicer.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import type { VoiceRecording } from '../narrate-recording';
+import { NarrationSlicer } from '../narration-slicer';
+
+const RATE = 16_000;
+
+function recording(seconds: number): VoiceRecording {
+ return { pcm: new Int16Array(seconds * RATE), sampleRate: RATE, audioEpochMs: 1_000, durationSeconds: seconds };
+}
+
+describe('NarrationSlicer', () => {
+ it('cuts each step its own stretch of audio, from the end of the last one', () => {
+ const slicer = new NarrationSlicer();
+
+ expect(slicer.forStep(recording(10), 1_000 + 4_000)?.durationSeconds).toBe(4);
+ expect(slicer.forStep(recording(10), 1_000 + 9_000)?.durationSeconds).toBe(5);
+ });
+
+ it('gives a step nothing when no audio has arrived since the last cut', () => {
+ const slicer = new NarrationSlicer();
+ slicer.forStep(recording(10), 1_000 + 6_000);
+
+ expect(slicer.forStep(recording(10), 1_000 + 6_000)).toBeNull();
+ expect(slicer.forStep(null, 1_000 + 8_000)).toBeNull();
+ });
+
+ it('leaves the tail after the last cut for Stop, or the whole recording when nothing was cut', () => {
+ const slicer = new NarrationSlicer();
+ expect(slicer.tail(recording(10))?.durationSeconds).toBe(10);
+
+ slicer.forStep(recording(10), 1_000 + 7_000);
+ expect(slicer.tail(recording(10))?.durationSeconds).toBe(3);
+
+ slicer.reset();
+ expect(slicer.tail(recording(10))?.durationSeconds).toBe(10);
+ });
+});
diff --git a/packages/core/src/capture/voice/mic-toggle-state.ts b/packages/core/src/capture/voice/mic-toggle-state.ts
new file mode 100644
index 0000000..70ac83c
--- /dev/null
+++ b/packages/core/src/capture/voice/mic-toggle-state.ts
@@ -0,0 +1,16 @@
+export interface MicToggleState {
+ locked: boolean;
+ labelKey: string;
+}
+
+export function micToggleState(enabled: boolean, keyed: boolean, paused: boolean): MicToggleState {
+ const locked = (!keyed && !enabled) || paused;
+ const labelKey = paused
+ ? 'voice.pausedWithCapture'
+ : locked
+ ? 'voice.needsApiKey'
+ : enabled
+ ? 'voice.turnOff'
+ : 'voice.turnOn';
+ return { locked, labelKey };
+}
diff --git a/packages/core/src/capture/voice/narration-slicer.ts b/packages/core/src/capture/voice/narration-slicer.ts
new file mode 100644
index 0000000..572037d
--- /dev/null
+++ b/packages/core/src/capture/voice/narration-slicer.ts
@@ -0,0 +1,22 @@
+import type { VoiceRecording } from './narrate-recording';
+import { partialRecording } from './partial-recording';
+
+export class NarrationSlicer {
+ private flushedUpTo = 0;
+
+ reset(): void {
+ this.flushedUpTo = 0;
+ }
+
+ forStep(full: VoiceRecording | null, timestamp: number): VoiceRecording | null {
+ if (!full) return null;
+ const closesAt = (timestamp - full.audioEpochMs) / 1000;
+ const slice = closesAt > this.flushedUpTo ? partialRecording(full, this.flushedUpTo, closesAt) : null;
+ if (slice) this.flushedUpTo = closesAt;
+ return slice;
+ }
+
+ tail(audio: VoiceRecording): VoiceRecording | null {
+ return this.flushedUpTo > 0 ? partialRecording(audio, this.flushedUpTo, audio.durationSeconds) : audio;
+ }
+}
diff --git a/packages/core/src/export/video-export.ts b/packages/core/src/export/video-export.ts
index 83f3f5f..05471fd 100644
--- a/packages/core/src/export/video-export.ts
+++ b/packages/core/src/export/video-export.ts
@@ -26,6 +26,7 @@ import { COVER_SEGMENT, stepNarration } from '@/core/export/voiceover/script';
import { actionSteps, calloutAccent, isBlock } from '@/core/guides/blocks';
import type { BlockType, Guide, Screenshot, Step } from '@/core/guides/types';
import { logger } from '@/core/logger';
+import type { Rect } from '@/core/rect';
import type { Ctx } from '@/core/screenshot/draw';
import { drawRoundedRect, TARGET_RADIUS, TARGET_STROKE } from '@/core/screenshot/draw';
import { clamp, resolveFrameViewport, resolveTarget } from '@/core/screenshot/geometry';
@@ -172,13 +173,6 @@ export function easeInOut(t: number): number {
return x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2;
}
-export interface Rect {
- x: number;
- y: number;
- width: number;
- height: number;
-}
-
interface Size {
width: number;
height: number;
diff --git a/apps/desktop/src/renderer/overlay/types.ts b/packages/core/src/rect.ts
similarity index 70%
rename from apps/desktop/src/renderer/overlay/types.ts
rename to packages/core/src/rect.ts
index d48e4ce..9086a22 100644
--- a/apps/desktop/src/renderer/overlay/types.ts
+++ b/packages/core/src/rect.ts
@@ -1,4 +1,4 @@
-export interface Region {
+export interface Rect {
x: number;
y: number;
width: number;
diff --git a/packages/ui/src/voice/components/VoiceNotice.tsx b/packages/ui/src/voice/components/VoiceNotice.tsx
index bafccf7..0c15428 100644
--- a/packages/ui/src/voice/components/VoiceNotice.tsx
+++ b/packages/ui/src/voice/components/VoiceNotice.tsx
@@ -21,9 +21,10 @@ interface VoiceNoticeProps {
update: VoiceUpdate;
seenLive: boolean;
onOpenSettings: () => void;
+ placement?: 'corner' | 'bottom';
}
-export function VoiceNotice({ update, seenLive, onOpenSettings }: VoiceNoticeProps) {
+export function VoiceNotice({ update, seenLive, onOpenSettings, placement = 'corner' }: VoiceNoticeProps) {
const [dismissed, setDismissed] = useState<string | null>(null);
const notice = voiceNotice(update, seenLive);
const signature = notice?.signature;
@@ -39,7 +40,14 @@ export function VoiceNotice({ update, seenLive, onOpenSettings }: VoiceNoticePro
const Icon = shown ? TONE_ICONS[shown.tone] : null;
return (
- <div role="status" className="fixed bottom-5 right-5 z-50 w-[min(23rem,calc(100vw-2.5rem))] pointer-events-none">
+ <div
+ role="status"
+ className={`fixed z-50 pointer-events-none ${
+ placement === 'bottom'
+ ? 'bottom-3 left-1/2 -translate-x-1/2 w-[calc(100%-1.5rem)] max-w-sm'
+ : 'bottom-5 right-5 w-[min(23rem,calc(100vw-2.5rem))]'
+ }`}
+ >
{shown && Icon && (
<div className="pointer-events-auto rounded-xl border border-border bg-card shadow-lg px-3.5 py-3 flex items-start gap-2.5">
<Icon size={15} className={`shrink-0 mt-0.5 ${TONE_CLASSES[shown.tone]}`} />
diff --git a/src/lib/voice/create-voice-host.ts b/src/lib/voice/create-voice-host.ts
index b77b718..a67e824 100644
--- a/src/lib/voice/create-voice-host.ts
+++ b/src/lib/voice/create-voice-host.ts
@@ -1,7 +1,7 @@
import { logger } from '@mimik/core/logger';
import { MicRecorder } from '@/core/capture/voice/mic-recorder';
import { EMPTY_NARRATION, narrateRecording, type VoiceRecording } from '@/core/capture/voice/narrate-recording';
-import { partialRecording } from '@/core/capture/voice/partial-recording';
+import { NarrationSlicer } from '@/core/capture/voice/narration-slicer';
import type { TranscriptionSettings } from '@/core/capture/voice/read-transcription-settings';
import { startFailureReason } from '@/core/capture/voice/start-failure-reason';
import type { NarrationResult } from '@/core/capture/voice/types';
@@ -44,7 +44,7 @@ function emit(event: VoiceEvent): void {
export function createVoiceHost(): VoiceHost {
let pending = 0;
let retained: VoiceRecording | null = null;
- let flushedUpToSeconds = 0;
+ const slicer = new NarrationSlicer();
const recorder = new MicRecorder(getExtensionURL('/pcm-processor.js'), {
onEpoch: (audioEpochMs) =>
@@ -108,7 +108,7 @@ export function createVoiceHost(): VoiceHost {
return { started: false, reason: 'already-recording', error: 'Microphone capture is already running' };
}
try {
- flushedUpToSeconds = 0;
+ slicer.reset();
const stream = await recorder.start(request.deviceId);
logger.info('voice: microphone capture started', stream);
return { started: true, ...stream };
@@ -140,14 +140,9 @@ export function createVoiceHost(): VoiceHost {
return { ok: false, reason: 'missing-api-key', error: 'No transcription API key is configured' };
}
- const full = usableRecording(recorder.snapshot());
- if (!full) return { ok: true, flushed: false };
-
- const closesAt = (request.step.timestamp - full.audioEpochMs) / 1000;
- const slice = partialRecording(full, flushedUpToSeconds, closesAt);
+ const slice = slicer.forStep(usableRecording(recorder.snapshot()), request.step.timestamp);
if (!slice) return { ok: true, flushed: false };
- flushedUpToSeconds = closesAt;
pending += 1;
try {
const result = await narrateRecording(slice, [request.step], request.settings);
@@ -180,7 +175,7 @@ export function createVoiceHost(): VoiceHost {
return { ok: false, reason: 'missing-api-key', error: 'No transcription API key is configured' };
}
- const tail = flushedUpToSeconds > 0 ? partialRecording(audio, flushedUpToSeconds, audio.durationSeconds) : audio;
+ const tail = slicer.tail(audio);
if (!tail) {
deliver(request.guideId, EMPTY_NARRATION, true);
return { ok: true, audioEpochMs, durationSeconds };
diff --git a/src/ui/sidepanel/App.tsx b/src/ui/sidepanel/App.tsx
index 523bce6..af88604 100644
--- a/src/ui/sidepanel/App.tsx
+++ b/src/ui/sidepanel/App.tsx
@@ -1,6 +1,6 @@
import { isLive } from '@mimik/core/capture/is-live';
import { logger } from '@mimik/core/logger';
-import { Button, Input, TooltipProvider } from '@mimik/ui';
+import { Button, Input, TooltipProvider, VoiceNotice } from '@mimik/ui';
import { Globe, Search, Settings, Video } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
@@ -27,7 +27,6 @@ import { GuideMeView } from './GuideMeView';
import { LibraryView } from './LibraryView';
import { MascotIcon } from './MascotIcon';
import { RecordingView } from './RecordingView';
-import { VoiceToast } from './VoiceToast';
type View =
| { name: 'library' }
@@ -39,7 +38,6 @@ type View =
export function App() {
const [isAlive, setIsAlive] = useState(false);
- const [_isRecording, setIsRecording] = useState(false);
const [view, setView] = useState<View>({ name: 'library' });
const [search, setSearch] = useState('');
const [activeUrl, setActiveUrl] = useState<string>();
@@ -69,14 +67,11 @@ export function App() {
setPaused(isPaused);
setPauseReason(isPaused ? (update.pauseReason ?? null) : null);
if (live) {
- setIsRecording(update.state === CaptureState.RECORDING);
setAiFailure(null);
const guideId = update.currentGuideId;
if (guideId) {
setView((prev) => (prev.name === 'recording' ? prev : { name: 'recording', guideId }));
}
- } else {
- setIsRecording(false);
}
},
onVoiceUpdate: (update) => {
@@ -137,7 +132,6 @@ export function App() {
try {
const res = await sendMessage('startRecording', { url });
if (res.guideId) {
- setIsRecording(true);
setView({ name: 'recording', guideId: res.guideId });
}
} catch (err) {
@@ -149,7 +143,6 @@ export function App() {
try {
const res = await sendMessage('stopRecording', undefined);
if (res.success) {
- setIsRecording(false);
setView(res.inserted && res.guideId ? { name: 'editor', guideId: res.guideId } : { name: 'library' });
if (res.guideId) {
const url = getExtensionURL(`/fullview.html?guideId=${res.guideId}`);
@@ -170,7 +163,6 @@ export function App() {
const handleDiscardRecording = useCallback(async () => {
try {
await sendMessage('discardRecording', undefined);
- setIsRecording(false);
setView({ name: 'library' });
} catch (err) {
logger.error(' DISCARD_RECORDING error', err);
@@ -234,7 +226,6 @@ export function App() {
return (
<div className="min-h-screen bg-card flex flex-col">
- {/* Header */}
<div className="px-6 pt-6 pb-7 border-b border-border">
<div className="flex items-center justify-between mb-5">
<span className="text-[17px] font-bold tracking-tight text-foreground">{i18n.t('app.name')}</span>
@@ -280,7 +271,6 @@ export function App() {
)}
</div>
- {/* Body */}
<div className="flex-1 px-5 pt-5">
<UpdateNotice className="mb-4" />
@@ -313,7 +303,12 @@ export function App() {
<TooltipProvider>
{renderView()}
{import.meta.env.BROWSER !== 'firefox' && view.name !== 'recording' && (
- <VoiceToast update={voice} confirmable={voiceStarted} onOpenSettings={() => setView({ name: 'settings' })} />
+ <VoiceNotice
+ update={voice}
+ seenLive={voiceStarted}
+ onOpenSettings={() => setView({ name: 'settings' })}
+ placement="bottom"
+ />
)}
</TooltipProvider>
);
diff --git a/src/ui/sidepanel/MicToggle.tsx b/src/ui/sidepanel/MicToggle.tsx
index 13821ca..843a210 100644
--- a/src/ui/sidepanel/MicToggle.tsx
+++ b/src/ui/sidepanel/MicToggle.tsx
@@ -4,6 +4,7 @@ import { Mic, MicOff } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
import { hasVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';
+import { micToggleState } from '@/core/capture/voice/mic-toggle-state';
import { getActiveTab } from '@/lib/browser-api/get-active-tab';
import { localStorage } from '@/lib/browser-api/local-storage';
import { sendMessage } from '@/lib/messaging';
@@ -40,7 +41,7 @@ export function MicToggle({ enabled, live, paused = false, onChange }: MicToggle
};
}, []);
- const locked = (!keyed && !enabled) || paused;
+ const { locked, labelKey } = micToggleState(enabled, keyed, paused);
const toggle = useCallback(async () => {
if (locked) return;
@@ -71,11 +72,7 @@ export function MicToggle({ enabled, live, paused = false, onChange }: MicToggle
}, [enabled, live, locked, onChange]);
const Icon = enabled ? Mic : MicOff;
- const label = paused
- ? i18n.t('voice.pausedWithCapture')
- : locked
- ? i18n.t('voice.needsApiKey')
- : i18n.t(enabled ? 'voice.turnOff' : 'voice.turnOn');
+ const label = i18n.t(labelKey);
return (
<Tooltip>
diff --git a/src/ui/sidepanel/RecordingView.tsx b/src/ui/sidepanel/RecordingView.tsx
index c4f435e..b4adfc3 100644
--- a/src/ui/sidepanel/RecordingView.tsx
+++ b/src/ui/sidepanel/RecordingView.tsx
@@ -128,7 +128,6 @@ export function RecordingView({
return (
<div className="flex flex-col h-screen bg-card relative">
- {/* Floating recording pill */}
<div className="absolute top-3 left-1/2 -translate-x-1/2 z-10 flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/90 backdrop-blur-sm border border-border shadow-sm">
<span className={`w-2 h-2 rounded-full ${paused ? 'bg-accent' : 'bg-destructive animate-pulse'}`} />
<span className="text-xs font-semibold text-foreground">
@@ -140,7 +139,6 @@ export function RecordingView({
</span>
</div>
- {/* Feed */}
<div className="flex-1 overflow-y-auto pt-12">
{steps.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full gap-3">
@@ -211,7 +209,6 @@ export function RecordingView({
<div ref={bottomRef} />
</div>
- {/* Bottom bar */}
<div className="shrink-0 border-t border-border">
<AiStatus update={aiFailure} />
{import.meta.env.BROWSER !== 'firefox' && <VoiceStatus update={voice} enabled={voiceEnabled} paused={paused} />}
diff --git a/src/ui/sidepanel/VoiceToast.tsx b/src/ui/sidepanel/VoiceToast.tsx
deleted file mode 100644
index 35edd37..0000000
--- a/src/ui/sidepanel/VoiceToast.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui';
-import { Check, Loader2, TriangleAlert, X } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { i18n } from '#imports';
-import { narratedKey } from '@/core/capture/voice/narrated-key';
-import { voiceErrorKey } from '@/core/capture/voice/voice-error-key';
-import { voiceSignature } from '@/core/capture/voice/voice-signature';
-import type { PanelVoiceUpdate } from '@/lib/port/types';
-
-const CONFIRM_MS = 7000;
-
-interface VoiceToastProps {
- update: PanelVoiceUpdate;
- confirmable: boolean;
- onOpenSettings: () => void;
-}
-
-export function VoiceToast({ update, confirmable, onOpenSettings }: VoiceToastProps) {
- const [dismissed, setDismissed] = useState<string | null>(null);
- const signature = voiceSignature(update);
- const confirming = update.phase === 'idle' && update.narrated !== undefined && confirmable;
-
- useEffect(() => {
- if (!confirming) return;
- const timer = setTimeout(() => setDismissed(signature), CONFIRM_MS);
- return () => clearTimeout(timer);
- }, [confirming, signature]);
-
- const visible = update.phase === 'transcribing' || update.phase === 'error' || confirming;
- if (!visible || dismissed === signature) return null;
-
- const narrated = update.narrated ?? 0;
-
- return (
- <div
- role="status"
- className="fixed bottom-3 left-1/2 -translate-x-1/2 z-50 w-[calc(100%-1.5rem)] max-w-sm rounded-xl border border-border bg-card shadow-lg px-3 py-2.5 flex items-start gap-2.5"
- >
- {update.phase === 'transcribing' && (
- <Loader2 size={14} className="shrink-0 mt-0.5 text-accent animate-spin motion-reduce:animate-none" />
- )}
- {update.phase === 'error' && <TriangleAlert size={14} className="shrink-0 mt-0.5 text-destructive" />}
- {confirming && <Check size={14} className="shrink-0 mt-0.5 text-success" />}
-
- <div className="flex-1 min-w-0">
- {update.phase === 'transcribing' && (
- <>
- <p className="text-[11px] font-semibold text-foreground">{i18n.t('voice.transcribing')}</p>
- <p className="text-[10px] text-muted-foreground leading-relaxed">{i18n.t('voice.transcribingHint')}</p>
- </>
- )}
-
- {update.phase === 'error' && (
- <>
- <p className="text-[11px] font-semibold text-foreground leading-relaxed">
- {i18n.t(voiceErrorKey(update.reason))}
- </p>
- <p className="text-[10px] text-muted-foreground leading-relaxed">{i18n.t('voice.guideSafe')}</p>
- {update.reason === 'missing-api-key' && (
- <button onClick={onOpenSettings} className="mt-1.5 text-[10px] font-semibold text-accent hover:underline">
- {i18n.t('voice.openSettings')}
- </button>
- )}
- </>
- )}
-
- {confirming && (
- <p className="text-[11px] font-semibold text-foreground">
- {narrated === 0 ? i18n.t('voice.narratedNone') : i18n.t(narratedKey(narrated), [String(narrated)])}
- </p>
- )}
- </div>
-
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={() => setDismissed(signature)}
- className="shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground transition-colors"
- >
- <X size={13} />
- </button>
- </TooltipTrigger>
- <TooltipContent align="end">{i18n.t('common.close')}</TooltipContent>
- </Tooltip>
- </div>
- );
-}