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 πŸ“–

11.6 KB
Raw Blame
import { isLive } from '@mimik/core/capture/is-live';
import { logger } from '@mimik/core/logger';
import { Button, Input, TooltipProvider, UpdateNotice, VoiceNotice } from '@mimik/ui';
import { Globe, Search, Settings, Video } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
import { isRecordableUrl } from '@/capture/recordable-tabs';
import { CaptureState, type PauseReason } from '@/core/capture/machine';
import type { GuideMeSession } from '@/core/guideme/session';
import { SESSION_KEY } from '@/core/guideme/session';
import { createTab } from '@/lib/browser-api/create-tab';
import { focusWindow } from '@/lib/browser-api/focus-window';
import { getActiveTab } from '@/lib/browser-api/get-active-tab';
import { getExtensionURL } from '@/lib/browser-api/get-extension-url';
import { queryTabs } from '@/lib/browser-api/query-tabs';
import { requestHostPermissions } from '@/lib/browser-api/request-host-permissions';
import { updateTab } from '@/lib/browser-api/update-tab';
import { sendMessage } from '@/lib/messaging';
import { getVoiceStatus } from '@/lib/offscreen/get-voice-status';
import { connectToBackground } from '@/lib/port/connect-to-background';
import type { PanelAiUpdate, PanelVoiceUpdate } from '@/lib/port/types';
import { useLetterNotice } from '@/ui/shared/hooks/use-letter-notice';
import { useUpdateNotice } from '@/ui/shared/hooks/use-update-notice';
import { LetterDialog } from '@/ui/shared/LetterDialog';
import { SettingsView } from '@/ui/shared/SettingsView';
import { GuideEditor } from './GuideEditor';
import { GuideMeCompletion } from './GuideMeCompletion';
import { GuideMeView } from './GuideMeView';
import { LibraryView } from './LibraryView';
import { MascotIcon } from './MascotIcon';
import { RecordingView } from './RecordingView';

type View =
  | { name: 'library' }
  | { name: 'editor'; guideId: string }
  | { name: 'recording'; guideId: string }
  | { name: 'settings' }
  | { name: 'guideme'; guideId: string }
  | { name: 'guideme-done'; guideId: string };

export function App() {
  const [isAlive, setIsAlive] = useState(false);
  const updateNotice = useUpdateNotice();
  const letterNotice = useLetterNotice();
  const [view, setView] = useState<View>({ name: 'library' });
  const [search, setSearch] = useState('');
  const [activeUrl, setActiveUrl] = useState<string>();
  const [voice, setVoice] = useState<PanelVoiceUpdate>({ type: 'VOICE_UPDATE', phase: 'idle' });
  const [aiFailure, setAiFailure] = useState<PanelAiUpdate | null>(null);
  const [voiceStarted, setVoiceStarted] = useState(false);
  const [paused, setPaused] = useState(false);
  const [pauseReason, setPauseReason] = useState<PauseReason | null>(null);

  useEffect(() => {
    const disconnect = connectToBackground({
      onConnect: () => {
        setIsAlive(true);
        if (import.meta.env.BROWSER === 'firefox') return;
        getVoiceStatus()
          .then((status) => {
            if (!status?.transcribing) return;
            setVoiceStarted(true);
            setVoice({ type: 'VOICE_UPDATE', phase: 'transcribing' });
          })
          .catch(() => undefined);
      },
      onDisconnect: () => setIsAlive(false),
      onStateUpdate: (update) => {
        const live = isLive(update.state);
        const isPaused = update.state === CaptureState.PAUSED;
        setPaused(isPaused);
        setPauseReason(isPaused ? (update.pauseReason ?? null) : null);
        if (live) {
          setAiFailure(null);
          const guideId = update.currentGuideId;
          if (guideId) {
            setView((prev) => (prev.name === 'recording' ? prev : { name: 'recording', guideId }));
          }
        }
      },
      onVoiceUpdate: (update) => {
        if (update.phase !== 'idle') setVoiceStarted(true);
        setVoice(update);
      },
      onAiUpdate: setAiFailure,
    });

    return disconnect;
  }, []);

  useEffect(() => {
    browser.storage.local.get([SESSION_KEY]).then((data: Record<string, unknown>) => {
      const session = data[SESSION_KEY] as GuideMeSession | null;
      if (session?.active) {
        setView({ name: 'guideme', guideId: session.guideId });
      }
    });

    const handler = (changes: Record<string, { newValue?: unknown }>) => {
      if (!changes[SESSION_KEY]) return;
      const session = changes[SESSION_KEY].newValue as GuideMeSession | null;
      if (session?.active) {
        setView({ name: 'guideme', guideId: session.guideId });
      }
    };

    browser.storage.local.onChanged.addListener(handler);
    return () => browser.storage.local.onChanged.removeListener(handler);
  }, []);

  useEffect(() => {
    const refresh = () => getActiveTab().then((tab) => setActiveUrl(tab?.url || tab?.pendingUrl || ''));
    refresh();
    browser.tabs.onActivated.addListener(refresh);
    browser.tabs.onUpdated.addListener(refresh);
    return () => {
      browser.tabs.onActivated.removeListener(refresh);
      browser.tabs.onUpdated.removeListener(refresh);
    };
  }, []);

  const handleStartRecording = useCallback(async () => {
    const permissionsPromise = requestHostPermissions();
    const granted = await permissionsPromise;
    if (!granted) {
      logger.warn('Host permissions not granted, cannot start recording');
      return;
    }
    const tab = await getActiveTab();
    const url = tab?.url || tab?.pendingUrl || '';
    if (!isRecordableUrl(url)) {
      logger.warn('Active tab can no longer be recorded');
      return;
    }

    try {
      const res = await sendMessage('startRecording', { url });
      if (res.guideId) {
        setView({ name: 'recording', guideId: res.guideId });
      }
    } catch (err) {
      logger.error(' START_RECORDING error', err);
    }
  }, []);

  const handleStopRecording = useCallback(async () => {
    try {
      const res = await sendMessage('stopRecording', undefined);
      if (res.success) {
        setView(res.inserted && res.guideId ? { name: 'editor', guideId: res.guideId } : { name: 'library' });
        if (res.guideId) {
          const url = getExtensionURL(`/fullview.html?guideId=${res.guideId}`);
          const [tab] = await queryTabs({ url: getExtensionURL('/fullview.html') });
          if (tab?.id) {
            await updateTab(tab.id, { active: true, url });
            if (tab.windowId) await focusWindow(tab.windowId);
          } else {
            await createTab({ url });
          }
        }
      }
    } catch (err) {
      logger.error(' STOP_RECORDING error', err);
    }
  }, []);

  const handleDiscardRecording = useCallback(async () => {
    try {
      await sendMessage('discardRecording', undefined);
      setView({ name: 'library' });
    } catch (err) {
      logger.error(' DISCARD_RECORDING error', err);
    }
  }, []);

  function renderView() {
    if (view.name === 'recording') {
      return (
        <RecordingView
          guideId={view.guideId}
          onStop={handleStopRecording}
          onDiscard={handleDiscardRecording}
          voice={voice}
          aiFailure={aiFailure}
          paused={paused}
          pauseReason={pauseReason}
        />
      );
    }

    if (view.name === 'guideme') {
      return (
        <GuideMeView
          guideId={view.guideId}
          onExit={() => {
            sendMessage('guideMeCancel', undefined).catch(() => {});
            setView({ name: 'library' });
          }}
          onComplete={(id) => setView({ name: 'guideme-done', guideId: id })}
        />
      );
    }

    if (view.name === 'guideme-done') {
      return (
        <GuideMeCompletion
          guideId={view.guideId}
          onDone={() => setView({ name: 'library' })}
          onRunAgain={async (id) => {
            await sendMessage('startGuideMe', { guideId: id });
            setView({ name: 'guideme', guideId: id });
          }}
        />
      );
    }

    if (view.name === 'editor') {
      return (
        <GuideEditor
          guideId={view.guideId}
          onBack={() => setView({ name: 'library' })}
          onGuideMe={(id) => setView({ name: 'guideme', guideId: id })}
        />
      );
    }

    if (view.name === 'settings') {
      return <SettingsView onBack={() => setView({ name: 'library' })} />;
    }

    return (
      <div className="min-h-screen bg-card flex flex-col">
        <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>
            <div className="flex items-center gap-2">
              <span className="flex items-center gap-1.5 text-[10px] font-medium text-muted-foreground">
                <span
                  className={`w-1.5 h-1.5 rounded-full ${isAlive ? 'bg-success' : 'bg-muted-foreground/40'}`}
                  aria-hidden="true"
                />
                {isAlive ? i18n.t('sidepanel.connected') : i18n.t('sidepanel.connecting')}
              </span>
              <button
                onClick={() => setView({ name: 'settings' })}
                className="w-7 h-7 rounded-lg flex items-center justify-center text-muted-foreground hover:text-accent hover:bg-secondary transition-colors"
              >
                <Settings size={15} />
              </button>
            </div>
          </div>

          <div className="text-center mb-5">
            <div className="flex justify-center mb-2">
              <MascotIcon size={44} />
            </div>
            <h3 className="text-base font-medium text-foreground">{i18n.t('sidepanel.heroTitle')}</h3>
            <p className="text-xs mt-1 text-muted-foreground">{i18n.t('sidepanel.heroSubtitle')}</p>
          </div>

          {isRecordableUrl(activeUrl) ? (
            <Button
              onClick={handleStartRecording}
              disabled={!isAlive}
              className="w-full py-3 px-4 h-auto rounded-lg font-semibold text-sm hover:-translate-y-px shadow-sm"
            >
              <Video size={18} />
              {i18n.t('capture.startCapture')}
            </Button>
          ) : (
            <p className="flex items-center justify-center gap-1.5 rounded-lg border border-border py-2.5 text-xs font-medium text-muted-foreground">
              <Globe size={14} className="shrink-0 text-accent" />
              {i18n.t('sidepanel.notRecordable')}
            </p>
          )}
        </div>

        <div className="flex-1 px-5 pt-5">
          <UpdateNotice {...updateNotice} className="mb-4" />
          <LetterDialog {...letterNotice} />

          <div className="relative mb-5">
            <Search size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-purple" />
            <Input
              type="text"
              placeholder={i18n.t('sidepanel.searchPlaceholder')}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-3 rounded-xl border-border bg-card !text-[13px]"
            />
          </div>

          <p className="text-[11px] font-semibold uppercase tracking-wider mb-2.5 text-muted-foreground">
            {i18n.t('sidepanel.recentLabel')}
          </p>

          <LibraryView
            onOpen={(guideId) => setView({ name: 'editor', guideId })}
            isAlive={isAlive}
            searchQuery={search}
          />
        </div>
      </div>
    );
  }

  return (
    <TooltipProvider>
      {renderView()}
      {import.meta.env.BROWSER !== 'firefox' && view.name !== 'recording' && (
        <VoiceNotice
          update={voice}
          seenLive={voiceStarted}
          onOpenSettings={() => setView({ name: 'settings' })}
          placement="bottom"
        />
      )}
    </TooltipProvider>
  );
}