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: consume the shared components through the ui port

Luis Ortizf6a41f619ccf
diff --git a/apps/desktop/src/renderer/core-env.ts b/apps/desktop/src/renderer/core-env.ts
index a089f83..fec01db 100644
--- a/apps/desktop/src/renderer/core-env.ts
+++ b/apps/desktop/src/renderer/core-env.ts
@@ -1,8 +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 en from '@mimik/locales/en.yml';
configureCore({
- t: (key) => key,
+ t: (key, substitutions) => translate(en as Messages, key, substitutions),
assetUrl: (path) => new URL(path, document.baseURI).href,
storage: {
get: async <K extends SettingsKey>(keys: readonly K[]) => {
diff --git a/package.json b/package.json
index 8bad912..fcbe2a0 100644
--- a/package.json
+++ b/package.json
@@ -33,6 +33,7 @@
"@ai-sdk/anthropic": "^3.0.64",
"@ai-sdk/openai": "^3.0.49",
"@fontsource/poppins": "^5.2.7",
+ "@mimik/ui": "workspace:*",
"@tailwindcss/vite": "^4.2.2",
"@vidstack/react": "^1.15.6",
"@webext-core/messaging": "^2.3.0",
diff --git a/src/capture/events/handlers.ts b/src/capture/events/handlers.ts
index 5e283ae..5c4c2a2 100644
--- a/src/capture/events/handlers.ts
+++ b/src/capture/events/handlers.ts
@@ -1,3 +1,4 @@
+import { logger } from '@mimik/ui/lib/logger';
import PQueue from 'p-queue';
import { extensionCaptureSink } from '@/capture/sink';
import { extractDOMContext } from '@/core/capture/dom/context';
@@ -16,7 +17,6 @@ import type { CaptureSink } from '@/core/capture/sink';
import { DEFAULT_TARGET_COLOR } from '@/core/screenshot/types';
import { localStorage } from '@/lib/browser-api';
import { HoverRing } from '@/lib/hover-ring';
-import { logger } from '@/lib/logger';
import { InputSession } from './input-session';
const DEDUP_MS = 300;
diff --git a/src/capture/events/input-session.ts b/src/capture/events/input-session.ts
index 6c44297..a5909ac 100644
--- a/src/capture/events/input-session.ts
+++ b/src/capture/events/input-session.ts
@@ -1,9 +1,9 @@
+import { logger } from '@mimik/ui/lib/logger';
import { i18n } from '#imports';
import { extractDOMContext } from '@/core/capture/dom/context';
import { extractElementMeta, type FrozenRect, freezeRect } from '@/core/capture/dom/element-meta';
import { getFieldLabel, getFieldValue, isRedactedField, isSensitiveField } from '@/core/capture/dom/element-utils';
import type { CaptureSink } from '@/core/capture/sink';
-import { logger } from '@/lib/logger';
export class InputSession {
stepId: string | null = null;
diff --git a/src/capture/session.ts b/src/capture/session.ts
index e9b677b..ba92879 100644
--- a/src/capture/session.ts
+++ b/src/capture/session.ts
@@ -1,5 +1,5 @@
+import { logger } from '@mimik/ui/lib/logger';
import { CaptureState } from '@/core/capture/machine';
-import { logger } from '@/lib/logger';
import { sendMessage } from '@/lib/messaging';
import { type CaptureHandle, startCapture } from './events/handlers';
diff --git a/src/capture/start-insert-recording.ts b/src/capture/start-insert-recording.ts
index 8f09e95..fdeaeab 100644
--- a/src/capture/start-insert-recording.ts
+++ b/src/capture/start-insert-recording.ts
@@ -1,5 +1,5 @@
+import { logger } from '@mimik/ui/lib/logger';
import { focusWindow, getTab, requestHostPermissions, updateTab } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import { sendMessage } from '@/lib/messaging';
import { isRecordableUrl } from './recordable-tabs';
diff --git a/src/entrypoints/background/actor.ts b/src/entrypoints/background/actor.ts
index a7f3001..2cefaf2 100644
--- a/src/entrypoints/background/actor.ts
+++ b/src/entrypoints/background/actor.ts
@@ -1,7 +1,7 @@
+import { logger } from '@mimik/ui/lib/logger';
import { createActor } from 'xstate';
import { type CaptureSnapshot, type CaptureStateValue, captureMachine } from '@/core/capture/machine';
import { sessionStorage } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import type { PanelStateUpdate } from '@/lib/port';
import type { ActorRef } from './types';
diff --git a/src/entrypoints/background/ai-description.ts b/src/entrypoints/background/ai-description.ts
index e6f6aa0..542d2d9 100644
--- a/src/entrypoints/background/ai-description.ts
+++ b/src/entrypoints/background/ai-description.ts
@@ -1,10 +1,10 @@
+import { logger } from '@mimik/ui/lib/logger';
import { getAIDescription } from '@/core/capture/ai/description';
import { describeAiFailure } from '@/core/capture/ai/errors';
import { resolveAiKey } from '@/core/capture/ai/keys';
import { AI_PROVIDERS } from '@/core/capture/ai/models';
import type { DOMContext } from '@/core/capture/dom/context';
import { localStorage } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import { broadcastAiToPanel } from '@/lib/port';
export async function generateAiDescription(domContext: DOMContext): Promise<string | undefined> {
diff --git a/src/entrypoints/background/describe-unnarrated.ts b/src/entrypoints/background/describe-unnarrated.ts
index b04b62e..7492a5b 100644
--- a/src/entrypoints/background/describe-unnarrated.ts
+++ b/src/entrypoints/background/describe-unnarrated.ts
@@ -1,5 +1,5 @@
+import { logger } from '@mimik/ui/lib/logger';
import { applyAiDescription, clearStepAiPending } from '@/core/guides/service';
-import { logger } from '@/lib/logger';
import { generateAiDescription } from './ai-description';
import { takeDeferredDescription, takeDeferredDescriptions } from './deferred-descriptions';
import { queueDescription } from './description-queue';
diff --git a/src/entrypoints/background/description-queue.ts b/src/entrypoints/background/description-queue.ts
index 5ccd374..cb99ab9 100644
--- a/src/entrypoints/background/description-queue.ts
+++ b/src/entrypoints/background/description-queue.ts
@@ -1,5 +1,5 @@
+import { logger } from '@mimik/ui/lib/logger';
import PQueue from 'p-queue';
-import { logger } from '@/lib/logger';
const DRAIN_TIMEOUT_MS = 20000;
const TASK_TIMEOUT_MS = 45000;
diff --git a/src/entrypoints/background/guide-meta.ts b/src/entrypoints/background/guide-meta.ts
index f86dd34..f310125 100644
--- a/src/entrypoints/background/guide-meta.ts
+++ b/src/entrypoints/background/guide-meta.ts
@@ -1,3 +1,4 @@
+import { logger } from '@mimik/ui/lib/logger';
import { i18n } from '#imports';
import { resolveAiKey } from '@/core/capture/ai/keys';
import { generateGuideMeta } from '@/core/capture/ai/meta';
@@ -11,7 +12,6 @@ import {
updateGuideTitle,
} from '@/core/guides/service';
import { localStorage } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import type { GenerateGuideDescriptionResponse, GuideDescriptionError } from '@/lib/messaging';
import { drainDescriptions } from './description-queue';
import { whenNarrationSettled } from './voice';
diff --git a/src/entrypoints/background/index.ts b/src/entrypoints/background/index.ts
index 1e2b241..5b1b1cb 100644
--- a/src/entrypoints/background/index.ts
+++ b/src/entrypoints/background/index.ts
@@ -1,4 +1,6 @@
import '@/lib/core-env';
+import '@/lib/ui-env';
+import { logger } from '@mimik/ui/lib/logger';
import { browser, defineBackground } from '#imports';
import { rewriteSelection } from '@/core/capture/ai/rewrite';
import { validateApiKey } from '@/core/capture/ai/validate';
@@ -21,7 +23,6 @@ import {
toggleSidebar,
updateTab,
} from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import { onMessage } from '@/lib/messaging';
import { broadcastStateToPanel, setupPortListener } from '@/lib/port';
import { recordUpdate } from '@/lib/update-notice';
diff --git a/src/entrypoints/background/navigation.ts b/src/entrypoints/background/navigation.ts
index 82b9558..d9fe196 100644
--- a/src/entrypoints/background/navigation.ts
+++ b/src/entrypoints/background/navigation.ts
@@ -1,3 +1,4 @@
+import { logger } from '@mimik/ui/lib/logger';
import { CaptureState } from '@/core/capture/machine';
import {
getTab,
@@ -7,7 +8,6 @@ import {
onTabUpdated,
sendMessageToTab,
} from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import { TabMessage } from '@/lib/tab-messages';
import { getActor, waitUntilReady } from './actor';
import { injectContentScript, isInjectableTab } from './tab-manager';
diff --git a/src/entrypoints/background/step-pipeline.ts b/src/entrypoints/background/step-pipeline.ts
index c1b109f..46e851d 100644
--- a/src/entrypoints/background/step-pipeline.ts
+++ b/src/entrypoints/background/step-pipeline.ts
@@ -1,3 +1,4 @@
+import { logger } from '@mimik/ui/lib/logger';
import { AI_KEY_SETTINGS, resolveAiKey } from '@/core/capture/ai/keys';
import type { DOMContext } from '@/core/capture/dom/context';
import { CaptureState } from '@/core/capture/machine';
@@ -13,7 +14,6 @@ import {
import type { ElementMeta, Screenshot, Step } from '@/core/guides/types';
import { DEFAULT_TARGET_COLOR } from '@/core/screenshot/types';
import { captureVisibleTab, localStorage } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import type { CaptureStepData, CaptureStepResponse } from '@/lib/messaging';
import { getActor } from './actor';
import { generateAiDescription } from './ai-description';
diff --git a/src/entrypoints/background/tab-manager.ts b/src/entrypoints/background/tab-manager.ts
index 56d8c2d..15bedb4 100644
--- a/src/entrypoints/background/tab-manager.ts
+++ b/src/entrypoints/background/tab-manager.ts
@@ -1,5 +1,5 @@
+import { logger } from '@mimik/ui/lib/logger';
import { executeScript, queryTabs, sendMessageToTab } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import { TabMessage } from '@/lib/tab-messages';
export function isInjectableTab(tab: { url?: string; pendingUrl?: string }): boolean {
diff --git a/src/entrypoints/background/voice.ts b/src/entrypoints/background/voice.ts
index 867d7ee..6102428 100644
--- a/src/entrypoints/background/voice.ts
+++ b/src/entrypoints/background/voice.ts
@@ -1,9 +1,9 @@
+import { logger } from '@mimik/ui/lib/logger';
import { CaptureState } from '@/core/capture/machine';
import { hasVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';
import { narrationUpdates } from '@/core/capture/voice/narration-updates';
import { applyNarrationToSteps, findExistingStepIds, getStepsForGuide } from '@/core/guides/service';
import { localStorage, onMessage as onRuntimeMessage } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import {
closeVoiceHost,
closeVoiceHostIfIdle,
diff --git a/src/entrypoints/content.ts b/src/entrypoints/content.ts
index f4e5515..9231757 100644
--- a/src/entrypoints/content.ts
+++ b/src/entrypoints/content.ts
@@ -1,4 +1,6 @@
import '@/lib/core-env';
+import '@/lib/ui-env';
+import { logger } from '@mimik/ui/lib/logger';
import { defineContentScript } from 'wxt/utils/define-content-script';
import { browser } from '#imports';
import { BlurManager } from '@/blur/manager';
@@ -6,7 +8,6 @@ import { CaptureSession } from '@/capture/session';
import { updateUrl } from '@/core/capture/spa-nav';
import { showStartNotification } from '@/core/capture/start-notification';
import { GuideMeController } from '@/guideme/content';
-import { logger } from '@/lib/logger';
import { TabMessage } from '@/lib/tab-messages';
const CLEANUP_EVENT = `mimik_cleanup_${browser.runtime.id}`;
diff --git a/src/entrypoints/fullview/index.tsx b/src/entrypoints/fullview/index.tsx
index fc5b628..e0ea46a 100644
--- a/src/entrypoints/fullview/index.tsx
+++ b/src/entrypoints/fullview/index.tsx
@@ -1,6 +1,7 @@
import '@/lib/core-env';
+import '@/lib/ui-env';
import ReactDOM from 'react-dom/client';
import FullViewApp from '@/ui/fullview/App';
-import '@/ui/global.css';
+import '@mimik/ui/global.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<FullViewApp />);
diff --git a/src/entrypoints/mic-permission/index.tsx b/src/entrypoints/mic-permission/index.tsx
index b075e8a..4b58062 100644
--- a/src/entrypoints/mic-permission/index.tsx
+++ b/src/entrypoints/mic-permission/index.tsx
@@ -1,6 +1,7 @@
import '@/lib/core-env';
+import '@/lib/ui-env';
import ReactDOM from 'react-dom/client';
import MicPermissionApp from '@/ui/mic-permission/App';
-import '@/ui/global.css';
+import '@mimik/ui/global.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<MicPermissionApp />);
diff --git a/src/entrypoints/offscreen/index.ts b/src/entrypoints/offscreen/index.ts
index 8780301..3219edc 100644
--- a/src/entrypoints/offscreen/index.ts
+++ b/src/entrypoints/offscreen/index.ts
@@ -1,4 +1,5 @@
import '@/lib/core-env';
+import '@/lib/ui-env';
import { startVoiceHost } from '@/lib/voice-host';
startVoiceHost();
diff --git a/src/entrypoints/onboarding/index.tsx b/src/entrypoints/onboarding/index.tsx
index 32da7fb..38677da 100644
--- a/src/entrypoints/onboarding/index.tsx
+++ b/src/entrypoints/onboarding/index.tsx
@@ -1,6 +1,7 @@
import '@/lib/core-env';
+import '@/lib/ui-env';
import ReactDOM from 'react-dom/client';
import OnboardingApp from '@/ui/onboarding/App';
-import '@/ui/global.css';
+import '@mimik/ui/global.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<OnboardingApp />);
diff --git a/src/entrypoints/options/index.tsx b/src/entrypoints/options/index.tsx
index 5607079..58d9474 100644
--- a/src/entrypoints/options/index.tsx
+++ b/src/entrypoints/options/index.tsx
@@ -1,4 +1,5 @@
import '@/lib/core-env';
+import '@/lib/ui-env';
import ReactDOM from 'react-dom/client';
import App from '@/ui/options/App';
import '@/ui/options/index.css';
diff --git a/src/entrypoints/sidepanel/index.tsx b/src/entrypoints/sidepanel/index.tsx
index 5b8afd0..e6a186a 100644
--- a/src/entrypoints/sidepanel/index.tsx
+++ b/src/entrypoints/sidepanel/index.tsx
@@ -1,8 +1,9 @@
import '@/lib/core-env';
+import '@/lib/ui-env';
import ReactDOM from 'react-dom/client';
import { startSidepanelVoiceHost } from '@/lib/sidepanel-voice-host';
import App from '@/ui/sidepanel/App';
-import '@/ui/global.css';
+import '@mimik/ui/global.css';
startSidepanelVoiceHost();
diff --git a/src/guideme/content.ts b/src/guideme/content.ts
index 8b8f0dc..213bc81 100644
--- a/src/guideme/content.ts
+++ b/src/guideme/content.ts
@@ -1,10 +1,10 @@
+import { logger } from '@mimik/ui/lib/logger';
import { browser } from '#imports';
import { findElement } from '@/core/guideme/finder';
import { GuideMeOverlay } from '@/core/guideme/overlay';
import type { GuideMeSession } from '@/core/guideme/session';
import { BLOCKED_KEY, MANUAL_KEY, SESSION_KEY, STEP_KEY } from '@/core/guideme/session';
import type { Step } from '@/core/guides/types';
-import { logger } from '@/lib/logger';
import { sendMessage } from '@/lib/messaging';
const MAX_RETRIES = 5;
diff --git a/src/lib/__tests__/utils.test.ts b/src/lib/__tests__/utils.test.ts
index 20cab43..1a6643b 100644
--- a/src/lib/__tests__/utils.test.ts
+++ b/src/lib/__tests__/utils.test.ts
@@ -1,5 +1,5 @@
+import { extractDomain, getDomainInitial, getMostCommonDomain } from '@mimik/ui/lib/utils';
import { describe, expect, it } from 'vitest';
-import { extractDomain, getDomainInitial, getMostCommonDomain } from '../utils';
describe('extractDomain', () => {
it('extracts hostname from a full URL', () => {
diff --git a/src/lib/logger.ts b/src/lib/logger.ts
deleted file mode 100644
index 7b23487..0000000
--- a/src/lib/logger.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { logger } from '@/core/logger';
diff --git a/src/lib/offscreen.ts b/src/lib/offscreen.ts
index 4d7c9b1..f92007f 100644
--- a/src/lib/offscreen.ts
+++ b/src/lib/offscreen.ts
@@ -1,5 +1,5 @@
+import { logger } from '@mimik/ui/lib/logger';
import { createTab, getExtensionURL, onMessage, sendMessage } from './browser-api';
-import { logger } from './logger';
import { localVoiceHost } from './voice-local';
import {
isVoiceMessageFor,
diff --git a/src/lib/port.ts b/src/lib/port.ts
index e6886ae..40caa88 100644
--- a/src/lib/port.ts
+++ b/src/lib/port.ts
@@ -1,7 +1,7 @@
+import { logger } from '@mimik/ui/lib/logger';
import { browser } from '#imports';
import type { AiFailureReason } from '@/core/capture/ai/errors';
import type { CaptureStateValue } from '@/core/capture/machine';
-import { logger } from '@/lib/logger';
import type { VoiceErrorReason } from '@/lib/voice-messages';
const PORT_NAME = 'mimik-panel';
diff --git a/src/lib/sidepanel-voice-host.ts b/src/lib/sidepanel-voice-host.ts
index dcda4dc..5c27975 100644
--- a/src/lib/sidepanel-voice-host.ts
+++ b/src/lib/sidepanel-voice-host.ts
@@ -1,4 +1,4 @@
-import { logger } from './logger';
+import { logger } from '@mimik/ui/lib/logger';
import { setLocalVoiceHost } from './voice-local';
export function startSidepanelVoiceHost(): void {
diff --git a/src/lib/ui-env.ts b/src/lib/ui-env.ts
new file mode 100644
index 0000000..31cb097
--- /dev/null
+++ b/src/lib/ui-env.ts
@@ -0,0 +1,32 @@
+import { configureUi } from '@mimik/ui/env';
+import { getRecordableTabs } from '@/capture/recordable-tabs';
+import { startInsertRecording } from '@/capture/start-insert-recording';
+import {
+ createTab,
+ focusWindow,
+ getActiveTab,
+ getTab,
+ openSidebar,
+ queryTabs,
+ requestHostPermissions,
+ updateTab,
+} from '@/lib/browser-api';
+import { sendMessage } from '@/lib/messaging';
+
+configureUi({
+ tabs: {
+ active: () => getActiveTab() as never,
+ get: (tabId) => getTab(tabId) as never,
+ query: (query) => queryTabs(query as never) as never,
+ create: (url) => createTab({ url }) as never,
+ update: (tabId, props) => updateTab(tabId, props as never) as never,
+ focusWindow: (windowId) => focusWindow(windowId) as never,
+ recordable: () => getRecordableTabs() as never,
+ startInsertRecording: (guideId, index, tabId) => startInsertRecording(guideId, index, tabId) as never,
+ },
+ panel: {
+ open: () => openSidebar(),
+ requestHostPermissions: () => requestHostPermissions(),
+ },
+ send: (name, payload) => sendMessage(name as never, payload as never) as never,
+});
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
deleted file mode 100644
index 9c4e0fc..0000000
--- a/src/lib/utils.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-export { extractDomain, getMostCommonDomain } from '@/core/guides/domain';
-
-import { type ClassValue, clsx } from 'clsx';
-import dayjs from 'dayjs';
-import relativeTime from 'dayjs/plugin/relativeTime';
-import 'dayjs/locale/es';
-import 'dayjs/locale/pt-br';
-import 'dayjs/locale/fr';
-import 'dayjs/locale/de';
-import 'dayjs/locale/zh-cn';
-import { twMerge } from 'tailwind-merge';
-import { i18n } from '#imports';
-
-dayjs.extend(relativeTime);
-
-const DAYJS_LOCALE_MAP: Record<string, string> = {
- es: 'es',
- 'pt-BR': 'pt-br',
- pt: 'pt-br',
- fr: 'fr',
- de: 'de',
- 'zh-CN': 'zh-cn',
- zh: 'zh-cn',
-};
-
-function getDayjsLocale(): string | undefined {
- try {
- const locale = i18n.t('meta.locale');
- if (locale && DAYJS_LOCALE_MAP[locale]) return DAYJS_LOCALE_MAP[locale];
- const key = locale?.split(/[-_]/)[0]?.toLowerCase();
- if (key && DAYJS_LOCALE_MAP[key]) return DAYJS_LOCALE_MAP[key];
- } catch {}
- return undefined;
-}
-
-export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs));
-}
-
-export function formatDate(ts: number): string {
- const locale = getDayjsLocale();
- const d = locale ? dayjs(ts).locale(locale) : dayjs(ts);
- return d.format('MMM D, YYYY');
-}
-
-export function formatDateShort(ts: number): string {
- const locale = getDayjsLocale();
- const d = locale ? dayjs(ts).locale(locale) : dayjs(ts);
- return d.format('MMM D');
-}
-
-export function formatDateTime(ts: number): string {
- const locale = getDayjsLocale();
- const d = locale ? dayjs(ts).locale(locale) : dayjs(ts);
- return d.format('MMM D, YYYY β€” h:mm A');
-}
-
-export function formatRelativeTime(ts: number): string {
- const locale = getDayjsLocale();
- return locale ? dayjs(ts).locale(locale).fromNow() : dayjs(ts).fromNow();
-}
-
-export function getFaviconUrl(url: string, size = 64): string {
- try {
- const full = /^https?:\/\//i.test(url) ? url : `https://${url}`;
- return `https://t1.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${encodeURIComponent(full)}&size=${size}&drop_404_icon=true`;
- } catch {
- return '';
- }
-}
-
-const INITIAL_GRADIENTS = [
- ['#6366F1', '#818CF8'],
- ['#8B5CF6', '#A78BFA'],
- ['#EC4899', '#F472B6'],
- ['#14B8A6', '#2DD4BF'],
- ['#F59E0B', '#FBBF24'],
- ['#3B82F6', '#60A5FA'],
-] as const;
-
-export function getDomainInitial(domain: string): { letter: string; gradient: readonly [string, string] } {
- const letter = domain.charAt(0).toUpperCase();
- let hash = 0;
- for (let i = 0; i < domain.length; i++) {
- hash = (hash * 31 + domain.charCodeAt(i)) | 0;
- }
- const gradient = INITIAL_GRADIENTS[Math.abs(hash) % INITIAL_GRADIENTS.length];
- return { letter, gradient };
-}
diff --git a/src/lib/voice-host.ts b/src/lib/voice-host.ts
index 1b17bd3..69c7082 100644
--- a/src/lib/voice-host.ts
+++ b/src/lib/voice-host.ts
@@ -1,7 +1,7 @@
+import { logger } from '@mimik/ui/lib/logger';
import { partialRecording } from '@/core/capture/voice/partial-recording';
import type { NarrationResult } from '@/core/capture/voice/types';
import { getExtensionURL, onMessage, sendMessage } from './browser-api';
-import { logger } from './logger';
import { MicRecorder, type MicRecording } from './mic-recorder';
import {
isVoiceMessageFor,
diff --git a/src/lib/voice-narration.ts b/src/lib/voice-narration.ts
index c8babf3..ef4416c 100644
--- a/src/lib/voice-narration.ts
+++ b/src/lib/voice-narration.ts
@@ -1,3 +1,4 @@
+import { logger } from '@mimik/ui/lib/logger';
import { resolveVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';
import { detectSpeechByEnergy } from '@/core/capture/voice/energy-gate';
import { runNarrationPipeline } from '@/core/capture/voice/pipeline';
@@ -5,7 +6,6 @@ import { buildStepWindows } from '@/core/capture/voice/step-windows';
import { createTranscriber, type VoiceProvider } from '@/core/capture/voice/transcribe';
import type { NarrationResult } from '@/core/capture/voice/types';
import { localStorage } from './browser-api';
-import { logger } from './logger';
import type { VoiceStepMark } from './voice-messages';
export interface TranscriptionSettings {
diff --git a/src/stores/fullview.ts b/src/stores/fullview.ts
deleted file mode 100644
index 76c35d0..0000000
--- a/src/stores/fullview.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { create } from 'zustand';
-import { useShallow } from 'zustand/react/shallow';
-import type { Guide, Screenshot, Step } from '@/core/guides/types';
-
-interface GuideExportData {
- guideId: string;
- guide: Guide;
- steps: Step[];
- screenshots: Map<string, Screenshot>;
-}
-
-interface FullviewStore {
- guides: Guide[];
- setGuides: (guides: Guide[]) => void;
- updateGuide: (id: string, patch: Partial<Guide>) => void;
- thumbnails: Map<string, Screenshot>;
- setThumbnails: (thumbnails: Map<string, Screenshot>) => void;
- libraryLoading: boolean;
- setLibraryLoading: (loading: boolean) => void;
- counts: { all: number; starred: number; trash: number };
- setCounts: (counts: { all: number; starred: number; trash: number }) => void;
-
- searchOpen: boolean;
- setSearchOpen: (open: boolean) => void;
- toggleSearch: () => void;
-
- guideTitle: string;
- setGuideTitle: (title: string) => void;
- guideStepCount: number;
- setGuideStepCount: (count: number) => void;
- guideExportData: GuideExportData | null;
- setGuideExportData: (data: GuideExportData | null) => void;
- scrollToStepId: string | null;
- scrollToStep: (stepId: string) => void;
- activeStepId: string | null;
- setActiveStepId: (id: string | null) => void;
-
- editing: boolean;
- setEditing: (editing: boolean) => void;
- historyOpen: boolean;
- setHistoryOpen: (open: boolean) => void;
- historyRefreshKey: number;
- bumpHistoryRefresh: () => void;
-}
-
-function flushFocusedField() {
- const el = document.activeElement;
- if (el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement) el.blur();
-}
-
-export const useFullviewStore = create<FullviewStore>((set) => ({
- guides: [],
- setGuides: (guides) => set({ guides }),
- updateGuide: (id, patch) => set((s) => ({ guides: s.guides.map((g) => (g.id === id ? { ...g, ...patch } : g)) })),
- thumbnails: new Map(),
- setThumbnails: (thumbnails) => set({ thumbnails }),
- libraryLoading: true,
- setLibraryLoading: (libraryLoading) => set({ libraryLoading }),
- counts: { all: 0, starred: 0, trash: 0 },
- setCounts: (counts) => set({ counts }),
-
- searchOpen: false,
- setSearchOpen: (searchOpen) => set({ searchOpen }),
- toggleSearch: () => set((s) => ({ searchOpen: !s.searchOpen })),
-
- guideTitle: '',
- setGuideTitle: (guideTitle) => set({ guideTitle }),
- guideStepCount: 0,
- setGuideStepCount: (guideStepCount) => set({ guideStepCount }),
- guideExportData: null,
- setGuideExportData: (guideExportData) =>
- set((s) =>
- s.guideExportData?.guideId === guideExportData?.guideId
- ? { guideExportData }
- : { guideExportData, editing: false, historyOpen: false, historyRefreshKey: 0 },
- ),
- scrollToStepId: null,
- scrollToStep: (stepId) => {
- set({ scrollToStepId: stepId });
- setTimeout(() => set({ scrollToStepId: null }), 100);
- },
- activeStepId: null,
- setActiveStepId: (activeStepId) => set({ activeStepId }),
-
- editing: false,
- setEditing: (editing) => {
- if (!editing) flushFocusedField();
- set({ editing });
- },
- historyOpen: false,
- setHistoryOpen: (historyOpen) => {
- if (historyOpen) flushFocusedField();
- set({ historyOpen });
- },
- historyRefreshKey: 0,
- bumpHistoryRefresh: () => set((s) => ({ historyRefreshKey: s.historyRefreshKey + 1 })),
-}));
-
-export function useFullview<T>(selector: (s: FullviewStore) => T): T {
- return useFullviewStore(useShallow(selector));
-}
diff --git a/src/ui/components/ui/badge.tsx b/src/ui/components/ui/badge.tsx
deleted file mode 100644
index 4aa8e43..0000000
--- a/src/ui/components/ui/badge.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { cva, type VariantProps } from 'class-variance-authority';
-import { Slot } from 'radix-ui';
-import type * as React from 'react';
-
-import { cn } from '@/lib/utils';
-
-const badgeVariants = cva(
- 'inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3',
- {
- variants: {
- variant: {
- default: 'bg-primary text-primary-foreground [a&]:hover:bg-primary/90',
- secondary: 'bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90',
- destructive:
- 'bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90',
- outline: 'border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
- ghost: '[a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
- link: 'text-primary underline-offset-4 [a&]:hover:underline',
- },
- },
- defaultVariants: {
- variant: 'default',
- },
- },
-);
-
-function Badge({
- className,
- variant = 'default',
- asChild = false,
- ...props
-}: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
- const Comp = asChild ? Slot.Root : 'span';
-
- return (
- <Comp data-slot="badge" data-variant={variant} className={cn(badgeVariants({ variant }), className)} {...props} />
- );
-}
-
-export { Badge, badgeVariants };
diff --git a/src/ui/components/ui/button.tsx b/src/ui/components/ui/button.tsx
deleted file mode 100644
index efa52ec..0000000
--- a/src/ui/components/ui/button.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { cva, type VariantProps } from 'class-variance-authority';
-import { Slot } from 'radix-ui';
-import type * as React from 'react';
-
-import { cn } from '@/lib/utils';
-
-const buttonVariants = cva(
- "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
- {
- variants: {
- variant: {
- default: 'bg-primary text-primary-foreground hover:bg-primary/90',
- destructive:
- 'bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40',
- outline:
- 'border border-border bg-background shadow-xs hover:bg-secondary dark:border-input dark:bg-input/30 dark:hover:bg-input/50',
- secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
- ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
- link: 'text-primary underline-offset-4 hover:underline',
- },
- size: {
- default: 'h-9 px-4 py-2 has-[>svg]:px-3',
- xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
- sm: 'h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5',
- lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',
- icon: 'size-9',
- 'icon-xs': "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
- 'icon-sm': 'size-8',
- 'icon-lg': 'size-10',
- },
- },
- defaultVariants: {
- variant: 'default',
- size: 'default',
- },
- },
-);
-
-function Button({
- className,
- variant = 'default',
- size = 'default',
- asChild = false,
- ...props
-}: React.ComponentProps<'button'> &
- VariantProps<typeof buttonVariants> & {
- asChild?: boolean;
- }) {
- const Comp = asChild ? Slot.Root : 'button';
-
- return (
- <Comp
- data-slot="button"
- data-variant={variant}
- data-size={size}
- className={cn(buttonVariants({ variant, size, className }))}
- {...props}
- />
- );
-}
-
-export { Button, buttonVariants };
diff --git a/src/ui/components/ui/dialog.tsx b/src/ui/components/ui/dialog.tsx
deleted file mode 100644
index 0ee2922..0000000
--- a/src/ui/components/ui/dialog.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { XIcon } from 'lucide-react';
-import { Dialog as DialogPrimitive } from 'radix-ui';
-import type * as React from 'react';
-
-import { cn } from '@/lib/utils';
-
-function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
- return <DialogPrimitive.Root data-slot="dialog" {...props} />;
-}
-
-function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
- return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
-}
-
-function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
- return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
-}
-
-function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
- return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
-}
-
-function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
- return (
- <DialogPrimitive.Overlay
- data-slot="dialog-overlay"
- className={cn(
- 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',
- className,
- )}
- {...props}
- />
- );
-}
-
-function DialogContent({
- className,
- children,
- showCloseButton = true,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Content> & {
- showCloseButton?: boolean;
-}) {
- return (
- <DialogPortal data-slot="dialog-portal">
- <DialogOverlay />
- <DialogPrimitive.Content
- data-slot="dialog-content"
- className={cn(
- 'fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border border-border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg',
- className,
- )}
- {...props}
- >
- {children}
- {showCloseButton && (
- <DialogPrimitive.Close
- data-slot="dialog-close"
- className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
- >
- <XIcon />
- <span className="sr-only">Close</span>
- </DialogPrimitive.Close>
- )}
- </DialogPrimitive.Content>
- </DialogPortal>
- );
-}
-
-function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
- return (
- <div
- data-slot="dialog-header"
- className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
- {...props}
- />
- );
-}
-
-function DialogFooter({ className, ...props }: React.ComponentProps<'div'>) {
- return (
- <div
- data-slot="dialog-footer"
- className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
- {...props}
- />
- );
-}
-
-function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
- return (
- <DialogPrimitive.Title
- data-slot="dialog-title"
- className={cn('text-lg leading-none font-semibold', className)}
- {...props}
- />
- );
-}
-
-function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
- return (
- <DialogPrimitive.Description
- data-slot="dialog-description"
- className={cn('text-sm text-muted-foreground', className)}
- {...props}
- />
- );
-}
-
-export {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogOverlay,
- DialogPortal,
- DialogTitle,
- DialogTrigger,
-};
diff --git a/src/ui/components/ui/dropdown-menu.tsx b/src/ui/components/ui/dropdown-menu.tsx
deleted file mode 100644
index 13c0780..0000000
--- a/src/ui/components/ui/dropdown-menu.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import { ChevronRight } from 'lucide-react';
-import { DropdownMenu as DropdownMenuPrimitive } from 'radix-ui';
-import type * as React from 'react';
-
-import { cn } from '@/lib/utils';
-
-function DropdownMenu({ modal = false, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
- return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" modal={modal} {...props} />;
-}
-
-function DropdownMenuTrigger({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
- return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
-}
-
-function DropdownMenuPortal({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
- return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
-}
-
-function DropdownMenuContent({
- className,
- sideOffset = 4,
- ...props
-}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
- return (
- <DropdownMenuPortal>
- <DropdownMenuPrimitive.Content
- data-slot="dropdown-menu-content"
- sideOffset={sideOffset}
- className={cn(
- 'z-50 min-w-40 overflow-hidden rounded-lg border border-border bg-card p-1 text-foreground shadow-lg data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
- className,
- )}
- {...props}
- />
- </DropdownMenuPortal>
- );
-}
-
-function DropdownMenuItem({
- className,
- variant = 'default',
- ...props
-}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & { variant?: 'default' | 'destructive' }) {
- return (
- <DropdownMenuPrimitive.Item
- data-slot="dropdown-menu-item"
- data-variant={variant}
- className={cn(
- "flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",
- 'text-foreground data-[highlighted]:bg-secondary data-[highlighted]:text-accent',
- 'data-[variant=destructive]:text-destructive data-[variant=destructive]:data-[highlighted]:bg-destructive/10 data-[variant=destructive]:data-[highlighted]:text-destructive',
- className,
- )}
- {...props}
- />
- );
-}
-
-function DropdownMenuSeparator({ className, ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
- return (
- <DropdownMenuPrimitive.Separator
- data-slot="dropdown-menu-separator"
- className={cn('-mx-1 my-1 h-px bg-border', className)}
- {...props}
- />
- );
-}
-
-function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
- return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
-}
-
-function DropdownMenuSubTrigger({
- className,
- children,
- ...props
-}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger>) {
- return (
- <DropdownMenuPrimitive.SubTrigger
- data-slot="dropdown-menu-sub-trigger"
- className={cn(
- "flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-secondary data-[state=open]:bg-secondary [&_svg:not([class*='size-'])]:size-4",
- className,
- )}
- {...props}
- >
- {children}
- <ChevronRight className="ml-auto size-4" />
- </DropdownMenuPrimitive.SubTrigger>
- );
-}
-
-function DropdownMenuSubContent({
- className,
- ...props
-}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
- return (
- <DropdownMenuPrimitive.SubContent
- data-slot="dropdown-menu-sub-content"
- className={cn(
- 'z-50 min-w-[8rem] overflow-hidden rounded-md border border-border bg-card p-1 text-foreground shadow-md',
- className,
- )}
- {...props}
- />
- );
-}
-
-export {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuPortal,
- DropdownMenuSeparator,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
- DropdownMenuTrigger,
-};
diff --git a/src/ui/components/ui/input.tsx b/src/ui/components/ui/input.tsx
deleted file mode 100644
index f92d954..0000000
--- a/src/ui/components/ui/input.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import type * as React from 'react';
-
-import { cn } from '@/lib/utils';
-
-function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
- return (
- <input
- type={type}
- data-slot="input"
- className={cn(
- 'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30',
- 'focus-visible:border-ring focus-visible:ring-0',
- 'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
- className,
- )}
- {...props}
- />
- );
-}
-
-export { Input };
diff --git a/src/ui/components/ui/popover.tsx b/src/ui/components/ui/popover.tsx
deleted file mode 100644
index 89527c8..0000000
--- a/src/ui/components/ui/popover.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { Popover as PopoverPrimitive } from 'radix-ui';
-import type * as React from 'react';
-
-import { cn } from '@/lib/utils';
-
-function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {
- return <PopoverPrimitive.Root data-slot="popover" {...props} />;
-}
-
-function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
- return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
-}
-
-function PopoverContent({
- className,
- align = 'center',
- sideOffset = 4,
- ...props
-}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
- return (
- <PopoverPrimitive.Portal>
- <PopoverPrimitive.Content
- data-slot="popover-content"
- align={align}
- sideOffset={sideOffset}
- className={cn(
- 'z-50 w-64 rounded-lg border border-border bg-card p-3 text-foreground shadow-lg outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
- className,
- )}
- {...props}
- />
- </PopoverPrimitive.Portal>
- );
-}
-
-function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
- return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
-}
-
-export { Popover, PopoverAnchor, PopoverContent, PopoverTrigger };
diff --git a/src/ui/components/ui/select.tsx b/src/ui/components/ui/select.tsx
deleted file mode 100644
index 4dfeb65..0000000
--- a/src/ui/components/ui/select.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { Check, ChevronDown } from 'lucide-react';
-import { Select as SelectPrimitive } from 'radix-ui';
-import type * as React from 'react';
-
-import { cn } from '@/lib/utils';
-
-function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
- return <SelectPrimitive.Root data-slot="select" {...props} />;
-}
-
-function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
- return <SelectPrimitive.Value data-slot="select-value" {...props} />;
-}
-
-function SelectTrigger({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Trigger>) {
- return (
- <SelectPrimitive.Trigger
- data-slot="select-trigger"
- className={cn(
- 'flex w-full items-center justify-between gap-2 rounded-lg border border-border bg-card px-3 py-2 text-[13px] font-medium text-foreground outline-none focus:border-ring focus:ring-2 focus:ring-ring/10 disabled:opacity-50 [&>span]:truncate',
- className,
- )}
- {...props}
- >
- {children}
- <SelectPrimitive.Icon asChild>
- <ChevronDown size={13} className="shrink-0 opacity-60" />
- </SelectPrimitive.Icon>
- </SelectPrimitive.Trigger>
- );
-}
-
-function SelectContent({
- className,
- children,
- position = 'popper',
- ...props
-}: React.ComponentProps<typeof SelectPrimitive.Content>) {
- return (
- <SelectPrimitive.Portal>
- <SelectPrimitive.Content
- data-slot="select-content"
- position={position}
- className={cn(
- 'relative z-50 max-h-72 min-w-[8rem] overflow-hidden rounded-lg border border-border bg-card text-foreground shadow-lg data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',
- className,
- )}
- {...props}
- >
- <SelectPrimitive.Viewport className="p-1">{children}</SelectPrimitive.Viewport>
- </SelectPrimitive.Content>
- </SelectPrimitive.Portal>
- );
-}
-
-function SelectItem({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Item>) {
- return (
- <SelectPrimitive.Item
- data-slot="select-item"
- className={cn(
- 'relative flex cursor-pointer select-none items-center gap-2 rounded-md py-1.5 pl-2 pr-7 text-[13px] outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[highlighted]:bg-secondary',
- className,
- )}
- {...props}
- >
- <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
- <span className="absolute right-2 flex items-center">
- <SelectPrimitive.ItemIndicator>
- <Check size={13} className="text-accent" />
- </SelectPrimitive.ItemIndicator>
- </span>
- </SelectPrimitive.Item>
- );
-}
-
-export { Select, SelectContent, SelectItem, SelectTrigger, SelectValue };
diff --git a/src/ui/components/ui/tooltip.tsx b/src/ui/components/ui/tooltip.tsx
deleted file mode 100644
index 0515420..0000000
--- a/src/ui/components/ui/tooltip.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { Tooltip as TooltipPrimitive } from 'radix-ui';
-import type * as React from 'react';
-
-import { cn } from '@/lib/utils';
-
-function TooltipProvider({ delayDuration = 350, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
- return <TooltipPrimitive.Provider data-slot="tooltip-provider" delayDuration={delayDuration} {...props} />;
-}
-
-function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
- return <TooltipPrimitive.Root data-slot="tooltip" {...props} />;
-}
-
-function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
- return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
-}
-
-function TooltipContent({
- className,
- sideOffset = 6,
- collisionPadding = 8,
- children,
- ...props
-}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
- return (
- <TooltipPrimitive.Portal>
- <TooltipPrimitive.Content
- data-slot="tooltip-content"
- sideOffset={sideOffset}
- collisionPadding={collisionPadding}
- className={cn(
- 'z-[60] max-w-56 rounded-md bg-primary px-2 py-1 text-[11px] font-semibold text-balance text-primary-foreground shadow-lg data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0',
- className,
- )}
- {...props}
- >
- {children}
- <TooltipPrimitive.Arrow className="fill-primary" width={9} height={4} />
- </TooltipPrimitive.Content>
- </TooltipPrimitive.Portal>
- );
-}
-
-export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };
diff --git a/src/ui/fullview/App.tsx b/src/ui/fullview/App.tsx
index 1753066..3b2dd04 100644
--- a/src/ui/fullview/App.tsx
+++ b/src/ui/fullview/App.tsx
@@ -1,11 +1,11 @@
+import { TooltipProvider } from '@mimik/ui/components/ui/tooltip';
+import GuideContent from '@mimik/ui/fullview/GuideContent';
+import LibraryContent from '@mimik/ui/fullview/LibraryContent';
+import { useRoute } from '@mimik/ui/fullview/router';
+import { useFullview } from '@mimik/ui/stores/fullview';
import { useEffect } from 'react';
-import { useFullview } from '@/stores/fullview';
-import { TooltipProvider } from '@/ui/components/ui/tooltip';
import UpdateNotice from '@/ui/shared/UpdateNotice';
import VoiceNotice from './components/VoiceNotice';
-import GuideContent from './GuideContent';
-import LibraryContent from './LibraryContent';
-import { useRoute } from './router';
import SearchModal from './SearchModal';
import TopNav from './TopNav';
diff --git a/src/ui/fullview/ExportPreviewModal.tsx b/src/ui/fullview/ExportPreviewModal.tsx
index 79e6d91..016ec4f 100644
--- a/src/ui/fullview/ExportPreviewModal.tsx
+++ b/src/ui/fullview/ExportPreviewModal.tsx
@@ -1,3 +1,5 @@
+import { Button } from '@mimik/ui/components/ui/button';
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@mimik/ui/components/ui/dialog';
import { FileCode, FileDown, FileImage, FileText, Loader2, Video } from 'lucide-react';
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
@@ -17,8 +19,6 @@ import { paginatePreview, withPreviewStyles } from '@/core/export/preview';
import type { VideoChapter } from '@/core/export/video-export';
import { canExportVideo, STEP_SECONDS } from '@/core/export/video-support';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
-import { Button } from '@/ui/components/ui/button';
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog';
const VideoStepPlayer = lazy(() => import('@/ui/fullview/VideoStepPlayer'));
diff --git a/src/ui/fullview/GuideContent.tsx b/src/ui/fullview/GuideContent.tsx
deleted file mode 100644
index 0c37b2d..0000000
--- a/src/ui/fullview/GuideContent.tsx
+++ /dev/null
@@ -1,514 +0,0 @@
-import { History, Loader2, Play, Sparkles } from 'lucide-react';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { TypeAnimation } from 'react-type-animation';
-import { i18n } from '#imports';
-import { startInsertRecording } from '@/capture/start-insert-recording';
-import { actionSteps } from '@/core/guides/blocks';
-import {
- deleteStep,
- getGuide,
- getScreenshotsForSteps,
- onGuidesChanged,
- updateGuideDescription,
- updateGuideTitle,
- updateStepDescription,
-} from '@/core/guides/service';
-import type { SnapshotLike } from '@/core/guides/snapshot-diff';
-import type { Guide, Screenshot, Snapshot, Step } from '@/core/guides/types';
-import type { ScreenshotEdits } from '@/core/screenshot/types';
-import { localStorage, openSidebar } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
-import { sendMessage } from '@/lib/messaging';
-import { formatDate, getMostCommonDomain } from '@/lib/utils';
-import { useFullview } from '@/stores/fullview';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import AnnotationEditor from '@/ui/shared/AnnotationEditor';
-import { useAskAi } from '@/ui/shared/AskAi';
-import FaviconImg from '@/ui/shared/FaviconImg';
-import { guideDescriptionErrorMessage } from '@/ui/shared/guide-description-error';
-import Toast from '@/ui/shared/Toast';
-import GuideStepList from './components/GuideStepList';
-import VersionHistoryPanel from './components/VersionHistoryPanel';
-
-interface GuideContentProps {
- guideId: string;
- initialStepId?: string;
- initialTool?: 'annotate' | 'redact' | 'crop' | 'target';
-}
-
-interface GuideData {
- guide: Guide;
- steps: Step[];
- screenshots: Map<string, Screenshot>;
-}
-
-interface PreviewData {
- snapshotId: string;
- steps: Step[];
- screenshots: Map<string, Screenshot>;
-}
-
-async function buildPreview(snapshot: Snapshot): Promise<PreviewData> {
- const rows = new Map(snapshot.screenshots.map((row) => [row.id, row]));
- const steps = [...snapshot.steps].sort((a, b) => a.index - b.index);
- const wanted = steps.map((s) => s.screenshotId).filter((id): id is string => !!id && rows.has(id));
- const live = await getScreenshotsForSteps(wanted);
- const blobs = new Map([...live.values()].map((row) => [row.id, row.blob]));
- const screenshots = new Map<string, Screenshot>();
- for (const step of steps) {
- const row = step.screenshotId ? rows.get(step.screenshotId) : undefined;
- const blob = row ? blobs.get(row.id) : undefined;
- if (row && blob) screenshots.set(step.id, { ...row, blob });
- }
- return { snapshotId: snapshot.id, steps, screenshots };
-}
-
-export default function GuideContent({ guideId, initialStepId, initialTool }: GuideContentProps) {
- const {
- setGuideTitle,
- setGuideStepCount,
- setGuideExportData,
- scrollToStep,
- editing,
- setEditing,
- historyOpen,
- setHistoryOpen,
- historyRefreshKey,
- } = useFullview((s) => ({
- setGuideTitle: s.setGuideTitle,
- setGuideStepCount: s.setGuideStepCount,
- setGuideExportData: s.setGuideExportData,
- scrollToStep: s.scrollToStep,
- editing: s.editing,
- setEditing: s.setEditing,
- historyOpen: s.historyOpen,
- setHistoryOpen: s.setHistoryOpen,
- historyRefreshKey: s.historyRefreshKey,
- }));
-
- const [data, setData] = useState<GuideData | null>(null);
- const [loading, setLoading] = useState(true);
- const [title, setTitle] = useState('');
- const [typingTitle, setTypingTitle] = useState<string | null>(null);
- const [editingStepId, setEditingStepId] = useState<string | null>(null);
- const [editingTool, setEditingTool] = useState<'annotate' | 'redact' | 'crop' | 'target'>('annotate');
- const [preview, setPreview] = useState<Snapshot | null>(null);
- const [previewData, setPreviewData] = useState<PreviewData | null>(null);
- const [description, setDescription] = useState('');
- const [generating, setGenerating] = useState(false);
- const [hasApiKey, setHasApiKey] = useState(false);
- const [descriptionError, setDescriptionError] = useState<string | null>(null);
- const titleRef = useRef('');
- const appliedInitialRef = useRef(false);
- const editingDescriptionRef = useRef(false);
-
- const loadGuide = useCallback(async () => {
- const result = await getGuide(guideId);
- if (result) {
- setData(result);
- if (!editingDescriptionRef.current) setDescription(result.guide.description ?? '');
- const newTitle = result.guide.title;
- const prev = titleRef.current;
- if (
- prev === i18n.t('fullview_untitledGuide') &&
- newTitle !== i18n.t('fullview_untitledGuide') &&
- result.steps.length > 0
- ) {
- setTypingTitle(newTitle);
- } else {
- titleRef.current = newTitle;
- setTitle(newTitle);
- }
- document.title = `${newTitle} β€” ${i18n.t('app_name')}`;
- setGuideTitle(newTitle);
- setGuideStepCount(actionSteps(result.steps).length);
- }
- setLoading(false);
- }, [guideId, setGuideTitle, setGuideStepCount]);
-
- useEffect(() => {
- loadGuide();
- return onGuidesChanged(() => loadGuide());
- }, [loadGuide]);
-
- useEffect(() => {
- if (data) setGuideExportData({ guideId, ...data });
- }, [data, guideId, setGuideExportData]);
-
- useEffect(() => {
- localStorage.get(['aiApiKey']).then((s) => setHasApiKey(Boolean(s.aiApiKey)));
- }, []);
-
- const handleTitleBlur = useCallback(async () => {
- if (!data || title === data.guide.title) return;
- await updateGuideTitle(guideId, title);
- setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, title } } : prev));
- document.title = `${title} β€” ${i18n.t('app_name')}`;
- }, [data, guideId, title]);
-
- const handleGuideDescriptionBlur = useCallback(async () => {
- if (data && description !== (data.guide.description ?? '')) {
- await updateGuideDescription(guideId, description);
- setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description } } : prev));
- }
- editingDescriptionRef.current = false;
- }, [data, guideId, description]);
-
- const commitGuideDescription = useCallback(
- (next: string) => {
- setDescription(next);
- void updateGuideDescription(guideId, next);
- setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description: next } } : prev));
- },
- [guideId],
- );
-
- const askAi = useAskAi(description, commitGuideDescription, hasApiKey);
-
- const handleGenerateDescription = useCallback(async () => {
- setGenerating(true);
- setDescriptionError(null);
- try {
- const result = await sendMessage('generateGuideDescription', { guideId });
- if (result.error) {
- setDescriptionError(guideDescriptionErrorMessage(result.error));
- return;
- }
- const generated = result.description;
- if (!generated) return;
- setDescription(generated);
- setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description: generated } } : prev));
- } catch {
- setDescriptionError(guideDescriptionErrorMessage('generation-failed'));
- } finally {
- setGenerating(false);
- }
- }, [guideId]);
-
- const handleDescriptionChange = useCallback(async (stepId: string, description: string) => {
- await updateStepDescription(stepId, description, 'manual');
- setData((prev) => {
- if (!prev) return prev;
- return { ...prev, steps: prev.steps.map((s) => (s.id === stepId ? { ...s, description } : s)) };
- });
- }, []);
-
- const handleDeleteStep = useCallback(
- async (stepId: string) => {
- await deleteStep(guideId, stepId);
- await loadGuide();
- },
- [guideId, loadGuide],
- );
-
- const handleOpenEditor = useCallback(
- async (stepId: string, tool: 'annotate' | 'redact' | 'crop' | 'target') => {
- await loadGuide();
- setEditingStepId(stepId);
- setEditingTool(tool);
- },
- [loadGuide],
- );
-
- const handleEditorDone = useCallback(
- (edits: ScreenshotEdits) => {
- if (!editingStepId || !data) return;
- const screenshot = data.screenshots.get(editingStepId);
- if (!screenshot) return;
- setData((prev) => {
- if (!prev) return prev;
- const newScreenshots = new Map(prev.screenshots);
- newScreenshots.set(editingStepId, { ...screenshot, edits });
- return { ...prev, screenshots: newScreenshots };
- });
- setEditingStepId(null);
- },
- [editingStepId, data],
- );
-
- useEffect(() => {
- if (!preview) {
- setPreviewData(null);
- return;
- }
- let cancelled = false;
- buildPreview(preview)
- .then((built) => {
- if (!cancelled) setPreviewData(built);
- })
- .catch((err) => logger.error(' Version preview failed', err));
- return () => {
- cancelled = true;
- };
- }, [preview]);
-
- useEffect(() => {
- if (editing || !historyOpen) setPreview(null);
- }, [editing, historyOpen]);
-
- useEffect(() => {
- if (appliedInitialRef.current || !data || !initialStepId) return;
- if (!data.screenshots.has(initialStepId)) return;
- appliedInitialRef.current = true;
- scrollToStep(initialStepId);
- if (initialTool) {
- setEditingStepId(initialStepId);
- setEditingTool(initialTool);
- }
- }, [data, initialStepId, initialTool, scrollToStep]);
-
- const live = useMemo<SnapshotLike>(
- () => ({
- title: data?.guide.title ?? '',
- stepIds: data?.guide.stepIds ?? [],
- steps: data?.steps ?? [],
- screenshots: data ? [...data.screenshots.values()] : [],
- }),
- [data],
- );
-
- if (loading)
- return (
- <div>
- <div className="h-10 w-2/3 rounded-lg bg-border/50 animate-pulse" />
- <div className="h-4 w-48 rounded bg-border/30 animate-pulse mt-3 mb-8" />
- <div className="space-y-6">
- {[0, 1, 2].map((i) => (
- <div key={i} className="rounded-xl border border-border/50 p-4">
- <div
- className="aspect-video rounded-lg bg-[#f2f4fa] animate-pulse mb-3"
- style={{ animationDelay: `${i * 150}ms` }}
- />
- <div
- className="h-4 w-3/4 rounded bg-border/40 animate-pulse"
- style={{ animationDelay: `${i * 150 + 50}ms` }}
- />
- </div>
- ))}
- </div>
- </div>
- );
- if (!data) return <p className="text-sm py-12 text-center text-purple">{i18n.t('fullview_guideNotFound')}</p>;
-
- const previewView = preview && previewData?.snapshotId === preview.id ? previewData : null;
- const viewSteps = previewView ? previewView.steps : data.steps;
- const viewScreenshots = previewView ? previewView.screenshots : data.screenshots;
- const actionCount = actionSteps(viewSteps).length;
- const domain = getMostCommonDomain(viewSteps);
- const editingScreenshot = editingStepId ? data.screenshots.get(editingStepId) : undefined;
- const animatingTitle = preview ? null : typingTitle;
- const untitledPending =
- !preview && !typingTitle && title === i18n.t('fullview_untitledGuide') && viewSteps.length > 0;
- const metaGenerating = (untitledPending || animatingTitle !== null) && !description;
-
- return (
- <div className="flex flex-col min-h-[calc(100vh-64px)]">
- {editingStepId && editingScreenshot && (
- <AnnotationEditor
- screenshot={editingScreenshot}
- tool={editingTool}
- onDone={handleEditorDone}
- onCancel={() => setEditingStepId(null)}
- />
- )}
-
- <div className={historyOpen ? 'flex items-start gap-6' : ''}>
- <div className={historyOpen ? 'flex-1 min-w-0' : ''}>
- {preview && (
- <div className="flex items-center gap-2 rounded-lg bg-secondary border border-border px-4 py-3 mb-4">
- <History size={15} className="text-accent shrink-0" />
- <span className="text-[12px] text-foreground">{i18n.t('history.readOnlyBanner')}</span>
- </div>
- )}
-
- <div className={untitledPending ? 'min-h-[88px]' : ''}>
- {untitledPending ? (
- <div className="text-[32px] font-extrabold leading-tight animate-gradient-text bg-[length:300%_100%] bg-clip-text text-transparent bg-gradient-to-r from-muted-foreground via-violet to-muted-foreground max-w-[480px]">
- {i18n.t('fullview_writingTitle')}
- </div>
- ) : animatingTitle ? (
- <div className="relative text-[32px] font-extrabold leading-tight">
- <div className="invisible" aria-hidden="true">
- {animatingTitle}
- </div>
- <div className="absolute inset-0 text-foreground">
- <TypeAnimation
- sequence={[
- animatingTitle,
- () => {
- titleRef.current = animatingTitle;
- setTitle(animatingTitle);
- setTypingTitle(null);
- },
- ]}
- speed={70}
- cursor={false}
- />
- <span className="inline-block w-[3px] h-[30px] bg-violet ml-0.5 align-text-bottom animate-blink" />
- </div>
- </div>
- ) : editing && !preview ? (
- <textarea
- ref={(el) => {
- if (el) {
- el.style.height = '0';
- el.style.height = `${el.scrollHeight}px`;
- }
- }}
- value={title}
- rows={1}
- onChange={(e) => {
- setTitle(e.target.value);
- setGuideTitle(e.target.value);
- const el = e.target;
- el.style.height = '0';
- el.style.height = `${el.scrollHeight}px`;
- }}
- onBlur={handleTitleBlur}
- className="text-[32px] font-extrabold bg-transparent border-b-2 border-transparent hover:border-border focus:outline-none focus:border-accent w-full p-0 text-foreground resize-none leading-tight overflow-hidden"
- />
- ) : (
- <h1 className="text-[32px] font-extrabold leading-tight text-foreground whitespace-pre-wrap break-words">
- {preview ? preview.title : title}
- </h1>
- )}
- </div>
-
- {!preview && (
- <div className="mt-3">
- {metaGenerating ? (
- <div className="max-w-[720px] text-[15px] leading-relaxed animate-gradient-text bg-[length:300%_100%] bg-clip-text text-transparent bg-gradient-to-r from-muted-foreground via-violet to-muted-foreground">
- {i18n.t('fullview_writingDescription')}
- </div>
- ) : editing ? (
- <div className="flex items-start gap-2 max-w-[720px]">
- <textarea
- ref={(el) => {
- if (el) {
- el.style.height = '0';
- el.style.height = `${el.scrollHeight}px`;
- }
- }}
- value={description}
- rows={2}
- onChange={(e) => {
- setDescription(e.target.value);
- const el = e.target;
- el.style.height = '0';
- el.style.height = `${el.scrollHeight}px`;
- }}
- onFocus={() => {
- editingDescriptionRef.current = true;
- }}
- onSelect={askAi.onSelect}
- onBlur={handleGuideDescriptionBlur}
- placeholder={i18n.t('editor.descriptionPlaceholder')}
- className="flex-1 resize-none overflow-hidden bg-transparent p-0 text-[15px] leading-relaxed text-muted-foreground placeholder:text-muted-foreground/60 border-b-2 border-transparent hover:border-border focus:outline-none focus:border-accent"
- />
- {hasApiKey && <span className="shrink-0 mt-0.5">{askAi.trigger}</span>}
- {hasApiKey &&
- (() => {
- const busy = generating || metaGenerating;
- const label = description
- ? i18n.t('editor.regenerateDescription')
- : i18n.t('editor.generateDescription');
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- type="button"
- onClick={() => {
- if (busy) return;
- void handleGenerateDescription();
- }}
- aria-disabled={busy}
- aria-label={label}
- className="shrink-0 mt-0.5 p-1 rounded-md text-muted-foreground hover:text-accent hover:bg-secondary transition-colors aria-disabled:cursor-not-allowed aria-disabled:hover:text-muted-foreground aria-disabled:hover:bg-transparent"
- >
- {busy ? (
- <Loader2 size={15} className="animate-spin text-accent" />
- ) : (
- <Sparkles size={15} />
- )}
- </button>
- </TooltipTrigger>
- <TooltipContent>{label}</TooltipContent>
- </Tooltip>
- );
- })()}
- <Toast message={descriptionError} onDismiss={() => setDescriptionError(null)} />
- </div>
- ) : (
- description && (
- <p className="max-w-[720px] text-[15px] leading-relaxed text-muted-foreground">{description}</p>
- )
- )}
- </div>
- )}
-
- <div className="flex items-center gap-1.5 mt-2 mb-4 flex-wrap">
- <span className="inline-flex items-center text-[11px] font-medium text-muted-foreground bg-card border border-border px-2.5 py-0.5 rounded-full">
- {formatDate(data.guide.createdAt)}
- </span>
- <span className="inline-flex items-center text-[11px] font-medium text-muted-foreground bg-card border border-border px-2.5 py-0.5 rounded-full">
- {actionCount !== 1
- ? i18n.t('fullview_stepCountPlural', [String(actionCount)])
- : i18n.t('fullview_stepCount', [String(actionCount)])}
- </span>
- {domain && (
- <span className="inline-flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground bg-card border border-border pl-1.5 pr-2.5 py-0.5 rounded-full">
- <FaviconImg domain={domain} size={14} className="rounded-full" />
- {domain}
- </span>
- )}
- {!editing && !preview && viewSteps.length > 0 && (
- <button
- onClick={() => {
- openSidebar();
- void sendMessage('startGuideMe', { guideId });
- }}
- disabled={!viewSteps.some((s) => s.elementMeta)}
- className="inline-flex items-center gap-1.5 text-[11px] font-semibold text-primary-foreground bg-primary hover:bg-primary/90 px-3 py-0.5 rounded-full transition-colors disabled:opacity-30 disabled:cursor-not-allowed ml-auto"
- >
- <Play size={11} />
- {i18n.t('fullview_guideMe')}
- </button>
- )}
- </div>
-
- <GuideStepList
- guideId={guideId}
- steps={viewSteps}
- screenshots={viewScreenshots}
- onDescriptionChange={handleDescriptionChange}
- onDelete={handleDeleteStep}
- onOpenEditor={handleOpenEditor}
- onReorder={(newSteps) => setData((prev) => (prev ? { ...prev, steps: newSteps } : prev))}
- readOnly={!editing || preview !== null}
- hasApiKey={hasApiKey}
- onChanged={loadGuide}
- onInsertRecording={(targetGuideId, insertAtIndex, tabId) => {
- openSidebar();
- void startInsertRecording(targetGuideId, insertAtIndex, tabId);
- }}
- />
- </div>
-
- {historyOpen && (
- <VersionHistoryPanel
- guideId={guideId}
- selectedId={preview?.id ?? null}
- refreshKey={historyRefreshKey}
- live={live}
- onSelect={(snapshot) => {
- setPreview(snapshot);
- if (snapshot) setEditing(false);
- }}
- onRestored={loadGuide}
- onClose={() => setHistoryOpen(false)}
- />
- )}
- </div>
- </div>
- );
-}
diff --git a/src/ui/fullview/LibraryContent.tsx b/src/ui/fullview/LibraryContent.tsx
deleted file mode 100644
index 2106e98..0000000
--- a/src/ui/fullview/LibraryContent.tsx
+++ /dev/null
@@ -1,387 +0,0 @@
-import { ArrowDownWideNarrow, ChevronDown, ChevronLeft, ChevronRight, LayoutGrid, LayoutList } from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import {
- type GuideChangeEvent,
- getFirstScreenshot,
- getGuides,
- getStarredGuides,
- getTrashedGuides,
- onGuidesChanged,
- permanentlyDeleteGuide,
- restoreGuide,
- softDeleteGuide,
- toggleStar,
-} from '@/core/guides/service';
-import type { Guide, Screenshot } from '@/core/guides/types';
-import { useFullview } from '@/stores/fullview';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import ConfirmDeleteModal from './components/ConfirmDeleteModal';
-import GuideGridView from './components/GuideGridView';
-import GuideListView from './components/GuideListView';
-
-interface LibraryContentProps {
- category: 'all' | 'starred' | 'trash';
-}
-
-const emptyConfig: Record<string, { titleKey: string; subKey: string }> = {
- all: { titleKey: 'library_noGuidesTitle', subKey: 'library_noGuidesSub' },
- starred: { titleKey: 'library_noStarredTitle', subKey: 'library_noStarredSub' },
- trash: { titleKey: 'library_trashEmptyTitle', subKey: 'library_trashEmptySub' },
-};
-
-function EmptyMascot({ category }: { category: string }) {
- if (category === 'starred') return <StarredMascot />;
- if (category === 'trash') return <TrashMascot />;
- return <NoGuidesMascot />;
-}
-
-function NoGuidesMascot() {
- return (
- <svg viewBox="0 0 200 200" className="w-24 h-24 animate-[float_3s_ease-in-out_infinite]">
- <style>{`
- @keyframes float{0%,100%{transform:translateY(0)}50%{transform:translateY(-6px)}}
- @keyframes sparkle{0%,100%{opacity:.3;transform:scale(.8)}50%{opacity:1;transform:scale(1.1)}}
- `}</style>
- <circle cx="45" cy="80" r="3" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite' }} />
- <circle cx="160" cy="70" r="2.5" fill="#818CF8" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.3s' }} />
- <circle cx="50" cy="140" r="2" fill="#A5B4FC" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.6s' }} />
- <circle
- cx="155"
- cy="145"
- r="2.5"
- fill="#818CF8"
- style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.9s' }}
- />
- <circle cx="100" cy="110" r="50" fill="#C7D2FE" />
- <rect x="58" y="110" width="84" height="40" rx="5" fill="#1E1B4B" />
- <path d="M58 110 L58 98 Q58 82 100 82 Q142 82 142 98 L142 110Z" fill="#3730A3" />
- <path d="M58 110 L58 98 Q58 82 100 82 Q142 82 142 98 L142 110Z" fill="#4F46E5" />
- <rect x="58" y="109" width="84" height="2" fill="#C7D2FE" />
- <path d="M82 126 Q88 118 94 126" stroke="#C7D2FE" strokeWidth="3" fill="none" strokeLinecap="round" />
- <path d="M106 126 Q112 118 118 126" stroke="#C7D2FE" strokeWidth="3" fill="none" strokeLinecap="round" />
- <path d="M90 138 Q100 146 110 138" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
- </svg>
- );
-}
-
-function StarredMascot() {
- return (
- <svg viewBox="0 0 200 200" className="w-24 h-24">
- <style>{`
- @keyframes twinkle{0%,100%{opacity:.4;transform:scale(.9)}50%{opacity:1;transform:scale(1.15)}}
- `}</style>
- <circle cx="100" cy="115" r="50" fill="#C7D2FE" />
- <rect x="58" y="115" width="84" height="40" rx="5" fill="#1E1B4B" />
- <path d="M58 115 L58 103 Q58 87 100 87 Q142 87 142 103 L142 115Z" fill="#3730A3" />
- <path d="M58 115 L58 103 Q58 87 100 87 Q142 87 142 103 L142 115Z" fill="#4F46E5" />
- <rect x="58" y="114" width="84" height="2" fill="#C7D2FE" />
- <path d="M82 131 Q88 124 94 131" stroke="#C7D2FE" strokeWidth="3" fill="none" strokeLinecap="round" />
- <path d="M106 131 Q112 124 118 131" stroke="#C7D2FE" strokeWidth="3" fill="none" strokeLinecap="round" />
- <path d="M92 143 Q100 150 108 143" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
- <g style={{ animation: 'twinkle 1.5s ease-in-out infinite' }}>
- <polygon
- points="155,70 159,80 170,81 162,88 164,99 155,93 146,99 148,88 140,81 151,80"
- fill="#FBBF24"
- stroke="#F59E0B"
- strokeWidth="1"
- />
- </g>
- <line x1="142" y1="120" x2="153" y2="90" stroke="#C7D2FE" strokeWidth="3" strokeLinecap="round" />
- </svg>
- );
-}
-
-function TrashMascot() {
- return (
- <svg viewBox="0 0 200 200" className="w-24 h-24">
- <style>{`
- @keyframes sweep{0%,100%{transform:rotate(-10deg)}50%{transform:rotate(10deg)}}
- @keyframes sparkle{0%,100%{opacity:.3;transform:scale(.8)}50%{opacity:1;transform:scale(1.1)}}
- `}</style>
- <circle cx="100" cy="115" r="50" fill="#C7D2FE" />
- <rect x="58" y="115" width="84" height="40" rx="5" fill="#1E1B4B" />
- <path d="M58 115 L58 103 Q58 87 100 87 Q142 87 142 103 L142 115Z" fill="#3730A3" />
- <path d="M58 115 L58 103 Q58 87 100 87 Q142 87 142 103 L142 115Z" fill="#4F46E5" />
- <rect x="58" y="114" width="84" height="2" fill="#C7D2FE" />
- <path d="M82 131 Q88 124 94 131" stroke="#C7D2FE" strokeWidth="3" fill="none" strokeLinecap="round" />
- <path d="M106 131 Q112 124 118 131" stroke="#C7D2FE" strokeWidth="3" fill="none" strokeLinecap="round" />
- <path d="M92 143 Q100 150 108 143" stroke="#C7D2FE" strokeWidth="2.5" fill="none" strokeLinecap="round" />
- <g style={{ transformOrigin: '155px 130px', animation: 'sweep 1.5s ease-in-out infinite' }}>
- <line x1="155" y1="75" x2="155" y2="140" stroke="#A5B4FC" strokeWidth="3" strokeLinecap="round" />
- <path d="M147 140 Q155 135 163 140 L160 155 Q155 158 150 155Z" fill="#818CF8" />
- </g>
- <circle cx="165" cy="155" r="2" fill="#818CF8" style={{ animation: 'sparkle 1s ease-in-out infinite' }} />
- <circle cx="148" cy="160" r="1.5" fill="#818CF8" style={{ animation: 'sparkle 1s ease-in-out infinite 0.3s' }} />
- </svg>
- );
-}
-
-type SortKey = 'recent' | 'oldest' | 'alpha' | 'steps';
-const sortLabelKeys: Record<SortKey, string> = {
- recent: 'sort_recentFirst',
- oldest: 'sort_oldestFirst',
- alpha: 'sort_alphaAZ',
- steps: 'sort_mostSteps',
-};
-
-const PAGE_SIZE = 9;
-
-function sortGuides(guides: Guide[], sort: SortKey): Guide[] {
- const sorted = [...guides];
- switch (sort) {
- case 'recent':
- return sorted.sort((a, b) => b.updatedAt - a.updatedAt);
- case 'oldest':
- return sorted.sort((a, b) => a.updatedAt - b.updatedAt);
- case 'alpha':
- return sorted.sort((a, b) => a.title.localeCompare(b.title));
- case 'steps':
- return sorted.sort((a, b) => b.stepIds.length - a.stepIds.length);
- }
-}
-
-export default function LibraryContent({ category }: LibraryContentProps) {
- const {
- setGuides,
- updateGuide,
- setThumbnails,
- libraryLoading: loading,
- setLibraryLoading: setLoading,
- setCounts,
- } = useFullview((s) => ({
- setGuides: s.setGuides,
- updateGuide: s.updateGuide,
- setThumbnails: s.setThumbnails,
- libraryLoading: s.libraryLoading,
- setLibraryLoading: s.setLibraryLoading,
- setCounts: s.setCounts,
- }));
-
- const [display, setDisplay] = useState<'list' | 'grid'>(
- () => (localStorage.getItem('mimik-display') as 'list' | 'grid') || 'grid',
- );
- const [sort, setSort] = useState<SortKey>('recent');
- const [sortOpen, setSortOpen] = useState(false);
- const [page, setPage] = useState(0);
- const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
- const sortRef = useRef<HTMLDivElement>(null);
-
- const allGuidesRef = useRef<Guide[]>([]);
-
- useEffect(() => {
- const handler = (e: MouseEvent) => {
- if (sortRef.current && !sortRef.current.contains(e.target as Node)) setSortOpen(false);
- };
- document.addEventListener('mousedown', handler);
- return () => document.removeEventListener('mousedown', handler);
- }, []);
-
- const refreshCounts = useCallback(async () => {
- const [all, starred, trashed] = await Promise.all([getGuides(), getStarredGuides(), getTrashedGuides()]);
- setCounts({ all: all.length, starred: starred.length, trash: trashed.length });
- }, [setCounts]);
-
- const loadGuides = useCallback(async () => {
- setLoading(true);
- const [all, starred, trashed] = await Promise.all([getGuides(), getStarredGuides(), getTrashedGuides()]);
- setCounts({ all: all.length, starred: starred.length, trash: trashed.length });
-
- const current = category === 'starred' ? starred : category === 'trash' ? trashed : all;
- allGuidesRef.current = current;
-
- const sorted = sortGuides(current, sort);
- const paged = sorted.slice(0, PAGE_SIZE);
- setGuides(paged);
- setPage(0);
-
- const thumbMap = new Map<string, Screenshot>();
- for (const guide of current.slice(0, 20)) {
- const screenshot = await getFirstScreenshot(guide.id);
- if (screenshot) thumbMap.set(guide.id, screenshot);
- }
- setThumbnails(thumbMap);
- setLoading(false);
- }, [category, sort, setCounts, setGuides, setThumbnails, setLoading]);
-
- useEffect(() => {
- loadGuides();
- }, [loadGuides]);
-
- useEffect(
- () =>
- onGuidesChanged((event: GuideChangeEvent) => {
- if (event.type === 'starred') {
- updateGuide(event.id, { starred: event.starred });
- refreshCounts();
- } else {
- loadGuides();
- }
- }),
- [refreshCounts, loadGuides, updateGuide],
- );
-
- const totalPages = Math.ceil(allGuidesRef.current.length / PAGE_SIZE);
-
- const applyPage = useCallback(
- async (newPage: number) => {
- const sorted = sortGuides(allGuidesRef.current, sort);
- const start = newPage * PAGE_SIZE;
- const paged = sorted.slice(start, start + PAGE_SIZE);
- setGuides(paged);
- setPage(newPage);
-
- const thumbMap = new Map<string, Screenshot>();
- for (const guide of paged) {
- const screenshot = await getFirstScreenshot(guide.id);
- if (screenshot) thumbMap.set(guide.id, screenshot);
- }
- setThumbnails(thumbMap);
- },
- [sort, setGuides, setThumbnails],
- );
-
- const handleSort = (key: SortKey) => {
- setSort(key);
- setSortOpen(false);
- const sorted = sortGuides(allGuidesRef.current, key);
- setGuides(sorted.slice(0, PAGE_SIZE));
- setPage(0);
- };
-
- const toggleDisplay = () => {
- const next = display === 'list' ? 'grid' : 'list';
- setDisplay(next);
- localStorage.setItem('mimik-display', next);
- };
-
- const handleStar = async (e: React.MouseEvent, id: string) => {
- e.stopPropagation();
- const guide = allGuidesRef.current.find((g) => g.id === id);
- if (guide) updateGuide(id, { starred: !guide.starred });
- await toggleStar(id);
- await refreshCounts();
- };
- const handleTrash = async (e: React.MouseEvent, id: string) => {
- e.stopPropagation();
- await softDeleteGuide(id);
- await loadGuides();
- };
- const handleRestore = async (e: React.MouseEvent, id: string) => {
- e.stopPropagation();
- await restoreGuide(id);
- await loadGuides();
- };
- const handlePermanentDelete = (e: React.MouseEvent, id: string) => {
- e.stopPropagation();
- setDeleteTarget(id);
- };
- const confirmPermanentDelete = async () => {
- if (!deleteTarget) return;
- setDeleteTarget(null);
- await permanentlyDeleteGuide(deleteTarget);
- await loadGuides();
- };
-
- const showPagination = !loading && allGuidesRef.current.length > PAGE_SIZE;
-
- return (
- <div>
- <div className="flex items-center justify-end gap-2 mb-4">
- <div ref={sortRef} className="relative">
- <button
- onClick={() => setSortOpen(!sortOpen)}
- className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground px-3 py-1.5 rounded-lg border border-border bg-card hover:border-violet hover:text-purple transition-colors"
- >
- <ArrowDownWideNarrow size={13} />
- {i18n.t(sortLabelKeys[sort] as any)}
- <ChevronDown size={10} className="ml-0.5" />
- </button>
- {sortOpen && (
- <div className="absolute right-0 top-full mt-1 bg-card border border-border rounded-lg shadow-lg py-1 z-10 min-w-[140px]">
- {(Object.keys(sortLabelKeys) as SortKey[]).map((key) => (
- <button
- key={key}
- onClick={() => handleSort(key)}
- className={`w-full text-left text-xs font-medium px-3 py-2 transition-colors ${
- sort === key
- ? 'text-foreground bg-secondary'
- : 'text-muted-foreground hover:bg-secondary/50 hover:text-foreground'
- }`}
- >
- {i18n.t(sortLabelKeys[key] as any)}
- </button>
- ))}
- </div>
- )}
- </div>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={toggleDisplay}
- className="flex items-center justify-center w-8 h-8 rounded-lg border border-border bg-card text-muted-foreground hover:border-violet hover:text-purple transition-colors"
- >
- {display === 'list' ? <LayoutGrid size={15} /> : <LayoutList size={15} />}
- </button>
- </TooltipTrigger>
- <TooltipContent align="end">
- {display === 'list' ? i18n.t('sort_gridView') : i18n.t('sort_listView')}
- </TooltipContent>
- </Tooltip>
- </div>
-
- {loading ? (
- <p className="text-sm py-12 text-center text-purple">{i18n.t('common_loading')}</p>
- ) : allGuidesRef.current.length === 0 ? (
- <div className="text-center py-20 flex flex-col items-center">
- <EmptyMascot category={category} />
- <p className="text-lg font-medium text-foreground mt-4">{i18n.t(emptyConfig[category].titleKey as any)}</p>
- <p className="text-sm text-muted-foreground mt-1">{i18n.t(emptyConfig[category].subKey as any)}</p>
- </div>
- ) : display === 'list' ? (
- <GuideListView
- category={category}
- onStar={handleStar}
- onTrash={handleTrash}
- onRestore={handleRestore}
- onPermanentDelete={handlePermanentDelete}
- />
- ) : (
- <GuideGridView
- category={category}
- onStar={handleStar}
- onTrash={handleTrash}
- onRestore={handleRestore}
- onPermanentDelete={handlePermanentDelete}
- />
- )}
-
- {showPagination && (
- <div className="flex items-center justify-center gap-3 mt-6">
- <button
- onClick={() => applyPage(page - 1)}
- disabled={page === 0}
- className="flex items-center justify-center w-8 h-8 rounded-lg border border-border bg-card text-muted-foreground hover:border-violet hover:text-purple transition-colors disabled:opacity-30 disabled:pointer-events-none"
- >
- <ChevronLeft size={15} />
- </button>
- <span className="text-xs font-medium text-muted-foreground">
- {i18n.t('fullview_pageOf', [String(page + 1), String(totalPages)])}
- </span>
- <button
- onClick={() => applyPage(page + 1)}
- disabled={page >= totalPages - 1}
- className="flex items-center justify-center w-8 h-8 rounded-lg border border-border bg-card text-muted-foreground hover:border-violet hover:text-purple transition-colors disabled:opacity-30 disabled:pointer-events-none"
- >
- <ChevronRight size={15} />
- </button>
- </div>
- )}
- <ConfirmDeleteModal
- open={deleteTarget !== null}
- onClose={() => setDeleteTarget(null)}
- onConfirm={confirmPermanentDelete}
- />
- </div>
- );
-}
diff --git a/src/ui/fullview/SearchModal.tsx b/src/ui/fullview/SearchModal.tsx
index d41743b..bbd9047 100644
--- a/src/ui/fullview/SearchModal.tsx
+++ b/src/ui/fullview/SearchModal.tsx
@@ -1,15 +1,14 @@
+import { Dialog, DialogPortal } from '@mimik/ui/components/ui/dialog';
+import { Input } from '@mimik/ui/components/ui/input';
+import { navigate } from '@mimik/ui/fullview/router';
+import { useFullview } from '@mimik/ui/stores/fullview';
import { Search, X } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
import { getGuideDomain, getGuides } from '@/core/guides/service';
import type { Guide } from '@/core/guides/types';
-
-import { useFullview } from '@/stores/fullview';
-import { Dialog, DialogPortal } from '@/ui/components/ui/dialog';
-import { Input } from '@/ui/components/ui/input';
import KeyboardHints from './components/KeyboardHints';
import SearchResults from './components/SearchResults';
-import { navigate } from './router';
interface GuideResult {
guide: Guide;
diff --git a/src/ui/fullview/TopNav.tsx b/src/ui/fullview/TopNav.tsx
index 3025f31..445f4f5 100644
--- a/src/ui/fullview/TopNav.tsx
+++ b/src/ui/fullview/TopNav.tsx
@@ -1,14 +1,14 @@
+import { Button } from '@mimik/ui/components/ui/button';
+import type { Route } from '@mimik/ui/fullview/router';
+import { navigate } from '@mimik/ui/fullview/router';
+import { logger } from '@mimik/ui/lib/logger';
+import MascotIcon from '@mimik/ui/shared/MascotIcon';
+import { useFullview } from '@mimik/ui/stores/fullview';
import { Check, ChevronRight, Download, FileText, History, Pencil, Search, Star, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { i18n } from '#imports';
import { createSnapshot } from '@/core/guides/service';
-import { logger } from '@/lib/logger';
-import { useFullview } from '@/stores/fullview';
-import { Button } from '@/ui/components/ui/button';
-import MascotIcon from '@/ui/shared/MascotIcon';
import ExportPreviewModal from './ExportPreviewModal';
-import type { Route } from './router';
-import { navigate } from './router';
interface TopNavProps {
route: Route;
diff --git a/src/ui/fullview/components/ConfirmDeleteModal.tsx b/src/ui/fullview/components/ConfirmDeleteModal.tsx
deleted file mode 100644
index 7144127..0000000
--- a/src/ui/fullview/components/ConfirmDeleteModal.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { Trash2 } from 'lucide-react';
-import { i18n } from '#imports';
-import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/ui/components/ui/dialog';
-
-interface ConfirmDeleteModalProps {
- open: boolean;
- onClose: () => void;
- onConfirm: () => void;
-}
-
-export default function ConfirmDeleteModal({ open, onClose, onConfirm }: ConfirmDeleteModalProps) {
- return (
- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
- <DialogContent showCloseButton={false} className="max-w-[320px] p-7 text-center border-none">
- <div className="flex justify-center">
- <div className="w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center">
- <Trash2 size={22} className="text-destructive" />
- </div>
- </div>
- <DialogTitle className="text-center text-base">{i18n.t('confirmDelete_title')}</DialogTitle>
- <DialogDescription className="text-center">{i18n.t('confirmDelete_message')}</DialogDescription>
- <div className="flex flex-col gap-2 mt-2">
- <button
- onClick={onConfirm}
- className="w-full py-2.5 rounded-lg bg-destructive text-white text-sm font-semibold hover:bg-destructive/90 transition-colors"
- >
- {i18n.t('confirmDelete_confirm')}
- </button>
- <button
- onClick={onClose}
- className="w-full py-2.5 rounded-lg bg-secondary text-foreground text-sm font-semibold hover:bg-lavender transition-colors"
- >
- {i18n.t('common_cancel')}
- </button>
- </div>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/src/ui/fullview/components/GuideGridView.tsx b/src/ui/fullview/components/GuideGridView.tsx
deleted file mode 100644
index 4dac63c..0000000
--- a/src/ui/fullview/components/GuideGridView.tsx
+++ /dev/null
@@ -1,188 +0,0 @@
-import { MoreVertical, RotateCcw, Star, StarOff, Trash2 } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import { formatDate } from '@/lib/utils';
-import { useFullview } from '@/stores/fullview';
-import ScreenshotView from '@/ui/shared/ScreenshotView';
-import { navigate } from '../router';
-
-interface GuideGridViewProps {
- category: 'all' | 'starred' | 'trash';
- onStar: (e: React.MouseEvent, id: string) => void;
- onTrash: (e: React.MouseEvent, id: string) => void;
- onRestore: (e: React.MouseEvent, id: string) => void;
- onPermanentDelete: (e: React.MouseEvent, id: string) => void;
-}
-
-function MimikEyes() {
- return (
- <div className="w-full h-full flex items-center justify-center bg-primary">
- <svg width="120" height="50" viewBox="0 0 120 50" fill="none">
- <path d="M15 30 Q27 14 39 30" stroke="#C7D2FE" strokeWidth="5" strokeLinecap="round" fill="none" />
- <path d="M81 30 Q93 14 105 30" stroke="#C7D2FE" strokeWidth="5" strokeLinecap="round" fill="none" />
- <path d="M39 44 Q60 54 81 44" stroke="#C7D2FE" strokeWidth="3.5" strokeLinecap="round" fill="none" />
- </svg>
- </div>
- );
-}
-
-function CardMenu({
- guideId,
- starred,
- category,
- onStar,
- onTrash,
- onRestore,
- onPermanentDelete,
-}: {
- guideId: string;
- starred: boolean;
- category: string;
- onStar: (e: React.MouseEvent, id: string) => void;
- onTrash: (e: React.MouseEvent, id: string) => void;
- onRestore: (e: React.MouseEvent, id: string) => void;
- onPermanentDelete: (e: React.MouseEvent, id: string) => void;
-}) {
- const [open, setOpen] = useState(false);
- const ref = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (!open) return;
- const handler = (e: MouseEvent) => {
- if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
- };
- document.addEventListener('mousedown', handler);
- return () => document.removeEventListener('mousedown', handler);
- }, [open]);
-
- const items: {
- icon: React.ReactNode;
- label: string;
- onClick: (e: React.MouseEvent) => void;
- destructive?: boolean;
- }[] = [];
-
- if (category === 'trash') {
- items.push({
- icon: <RotateCcw size={13} />,
- label: i18n.t('common_restore'),
- onClick: (e) => {
- onRestore(e, guideId);
- setOpen(false);
- },
- });
- items.push({
- icon: <Trash2 size={13} />,
- label: i18n.t('library_deletePermanently'),
- onClick: (e) => {
- onPermanentDelete(e, guideId);
- setOpen(false);
- },
- destructive: true,
- });
- } else {
- items.push({
- icon: starred ? <StarOff size={13} /> : <Star size={13} />,
- label: starred ? i18n.t('common_unstar') : i18n.t('common_star'),
- onClick: (e) => {
- onStar(e, guideId);
- setOpen(false);
- },
- });
- items.push({
- icon: <Trash2 size={13} />,
- label: i18n.t('library_moveToTrash'),
- onClick: (e) => {
- onTrash(e, guideId);
- setOpen(false);
- },
- destructive: true,
- });
- }
-
- return (
- <div ref={ref} className="relative">
- <button
- onClick={(e) => {
- e.stopPropagation();
- setOpen(!open);
- }}
- className="flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors"
- >
- <MoreVertical size={14} />
- </button>
- {open && (
- <div
- className="absolute left-full ml-1 top-0 bg-card border border-border rounded-lg shadow-lg py-1 z-20 min-w-[160px]"
- onClick={(e) => e.stopPropagation()}
- >
- {items.map((item) => (
- <button
- key={item.label}
- onClick={item.onClick}
- className={`flex items-center gap-2 w-full text-left text-xs font-medium px-3 py-2 transition-colors ${
- item.destructive ? 'text-destructive hover:bg-destructive/10' : 'text-foreground hover:bg-secondary'
- }`}
- >
- {item.icon}
- {item.label}
- </button>
- ))}
- </div>
- )}
- </div>
- );
-}
-
-export default function GuideGridView({ category, onStar, onTrash, onRestore, onPermanentDelete }: GuideGridViewProps) {
- const { guides, thumbnails } = useFullview((s) => ({
- guides: s.guides,
- thumbnails: s.thumbnails,
- }));
-
- return (
- <div className="grid grid-cols-2 lg:grid-cols-3 gap-4">
- {guides.map((guide) => {
- const thumb = thumbnails.get(guide.id);
- return (
- <div
- key={guide.id}
- onClick={() => navigate({ page: 'guide', guideId: guide.id })}
- className="group rounded-xl bg-card cursor-pointer hover:shadow-md transition-shadow border border-border relative"
- >
- <div className="h-36 overflow-hidden rounded-t-xl">
- {thumb ? (
- <ScreenshotView screenshot={thumb} alt={guide.title} className="!rounded-none !border-0" readOnly />
- ) : (
- <MimikEyes />
- )}
- </div>
- <div className="p-3 flex items-start justify-between">
- <div className="min-w-0 flex-1">
- <p className="text-sm font-medium truncate text-foreground">{guide.title}</p>
- {guide.description && (
- <p className="text-xs mt-0.5 text-muted-foreground line-clamp-2">{guide.description}</p>
- )}
- <p className="text-xs mt-0.5 text-muted-foreground">
- {guide.stepIds.length !== 1
- ? i18n.t('fullview_stepCountPlural', [String(guide.stepIds.length)])
- : i18n.t('fullview_stepCount', [String(guide.stepIds.length)])}{' '}
- &middot; {formatDate(guide.updatedAt)}
- </p>
- </div>
- <CardMenu
- guideId={guide.id}
- starred={guide.starred}
- category={category}
- onStar={onStar}
- onTrash={onTrash}
- onRestore={onRestore}
- onPermanentDelete={onPermanentDelete}
- />
- </div>
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/src/ui/fullview/components/GuideListView.tsx b/src/ui/fullview/components/GuideListView.tsx
deleted file mode 100644
index 61571b5..0000000
--- a/src/ui/fullview/components/GuideListView.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import { RotateCcw, Star, Trash2 } from 'lucide-react';
-import { i18n } from '#imports';
-import { formatDate } from '@/lib/utils';
-import { useFullview } from '@/stores/fullview';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import { navigate } from '../router';
-
-interface GuideListViewProps {
- category: 'all' | 'starred' | 'trash';
- onStar: (e: React.MouseEvent, id: string) => void;
- onTrash: (e: React.MouseEvent, id: string) => void;
- onRestore: (e: React.MouseEvent, id: string) => void;
- onPermanentDelete: (e: React.MouseEvent, id: string) => void;
-}
-
-export default function GuideListView({ category, onStar, onTrash, onRestore, onPermanentDelete }: GuideListViewProps) {
- const { guides } = useFullview((s) => ({ guides: s.guides }));
-
- return (
- <div className="rounded-xl overflow-hidden bg-card border border-border">
- {guides.map((guide, idx) => (
- <div
- key={guide.id}
- onClick={() => navigate({ page: 'guide', guideId: guide.id })}
- className="flex items-center px-5 py-3.5 cursor-pointer transition-colors group hover:bg-secondary"
- style={{ borderBottom: idx < guides.length - 1 ? '1px solid var(--color-border)' : undefined }}
- >
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate text-foreground">{guide.title}</p>
- {guide.description && (
- <p className="text-xs mt-0.5 text-muted-foreground line-clamp-1">{guide.description}</p>
- )}
- <p className="text-xs mt-0.5 text-muted-foreground">
- {guide.stepIds.length !== 1
- ? i18n.t('fullview_stepCountPlural', [String(guide.stepIds.length)])
- : i18n.t('fullview_stepCount', [String(guide.stepIds.length)])}{' '}
- &middot; {formatDate(guide.updatedAt)}
- </p>
- </div>
- <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity motion-reduce:transition-none">
- {category !== 'trash' ? (
- <>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={(e) => onStar(e, guide.id)}
- className="p-1.5 rounded-lg transition-colors text-purple hover:text-accent"
- >
- <Star size={14} fill={guide.starred ? 'currentColor' : 'none'} />
- </button>
- </TooltipTrigger>
- <TooltipContent>{guide.starred ? i18n.t('common_unstar') : i18n.t('common_star')}</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={(e) => onTrash(e, guide.id)}
- className="p-1.5 rounded-lg transition-colors text-purple hover:text-destructive"
- >
- <Trash2 size={14} />
- </button>
- </TooltipTrigger>
- <TooltipContent align="end">{i18n.t('library_moveToTrash')}</TooltipContent>
- </Tooltip>
- </>
- ) : (
- <>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={(e) => onRestore(e, guide.id)}
- className="p-1.5 rounded-lg transition-colors text-purple hover:text-success"
- >
- <RotateCcw size={14} />
- </button>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('common_restore')}</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={(e) => onPermanentDelete(e, guide.id)}
- className="p-1.5 rounded-lg transition-colors text-purple hover:text-destructive"
- >
- <Trash2 size={14} />
- </button>
- </TooltipTrigger>
- <TooltipContent align="end">{i18n.t('library_deletePermanently')}</TooltipContent>
- </Tooltip>
- </>
- )}
- </div>
- </div>
- ))}
- </div>
- );
-}
diff --git a/src/ui/fullview/components/GuideStepList.tsx b/src/ui/fullview/components/GuideStepList.tsx
deleted file mode 100644
index 4afa0cb..0000000
--- a/src/ui/fullview/components/GuideStepList.tsx
+++ /dev/null
@@ -1,275 +0,0 @@
-import { Trash2 } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import { isBlock, stepNumbers } from '@/core/guides/blocks';
-import { createSnapshot, deleteSteps, insertBlock, reorderSteps } from '@/core/guides/service';
-import type { BlockType, Screenshot, Step } from '@/core/guides/types';
-import { dominantRatio } from '@/core/screenshot/geometry';
-import { logger } from '@/lib/logger';
-import { useFullview } from '@/stores/fullview';
-import { Button } from '@/ui/components/ui/button';
-import BlockCard from '@/ui/shared/BlockCard';
-import CaptureTabDialog from '@/ui/shared/CaptureTabDialog';
-import ConfirmDialog from '@/ui/shared/ConfirmDialog';
-import EmptyGuideState from '@/ui/shared/EmptyGuideState';
-import InsertBlockMenu from '@/ui/shared/InsertBlockMenu';
-import StepCard from '@/ui/sidepanel/StepCard';
-
-interface GuideStepListProps {
- guideId: string;
- steps: Step[];
- screenshots: Map<string, Screenshot>;
- onDescriptionChange: (stepId: string, description: string) => void;
- onDelete: (stepId: string) => void;
- onOpenEditor: (stepId: string, tool: 'annotate' | 'redact' | 'crop' | 'target') => void;
- onReorder: (newSteps: Step[]) => void;
- readOnly?: boolean;
- onChanged?: () => void;
- hasApiKey?: boolean;
- onInsertRecording?: (guideId: string, insertAtIndex: number, tabId: number) => void;
-}
-
-export default function GuideStepList({
- guideId,
- steps,
- screenshots,
- onDescriptionChange,
- onDelete,
- onOpenEditor,
- onReorder,
- readOnly,
- onChanged,
- hasApiKey,
- onInsertRecording,
-}: GuideStepListProps) {
- const { scrollToStepId, setActiveStepId, bumpHistoryRefresh } = useFullview((s) => ({
- scrollToStepId: s.scrollToStepId,
- setActiveStepId: s.setActiveStepId,
- bumpHistoryRefresh: s.bumpHistoryRefresh,
- }));
-
- const [recordAtIndex, setRecordAtIndex] = useState<number | null>(null);
- const [dragIndex, setDragIndex] = useState<number | null>(null);
- const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
- const [selected, setSelected] = useState<Set<string>>(new Set());
- const [confirmBulkDelete, setConfirmBulkDelete] = useState(false);
- const anchorIndex = useRef<number | null>(null);
- const stepRefs = useRef<Map<string, HTMLDivElement>>(new Map());
- const frameRatio = dominantRatio(screenshots);
- const numbers = stepNumbers(steps);
-
- useEffect(() => {
- if (scrollToStepId) {
- stepRefs.current.get(scrollToStepId)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
- }
- }, [scrollToStepId]);
-
- useEffect(() => {
- if (steps.length === 0) return;
- const observer = new IntersectionObserver(
- (entries) => {
- for (const entry of entries) {
- if (entry.isIntersecting) {
- setActiveStepId(entry.target.getAttribute('data-step-id'));
- }
- }
- },
- { threshold: 0.5 },
- );
- for (const el of stepRefs.current.values()) observer.observe(el);
- return () => observer.disconnect();
- }, [steps, setActiveStepId]);
-
- useEffect(() => {
- if (readOnly) {
- setSelected(new Set());
- anchorIndex.current = null;
- }
- }, [readOnly]);
-
- const handleDragEnd = () => {
- if (dragIndex !== null && dragOverIndex !== null && dragIndex !== dragOverIndex) {
- const newSteps = [...steps];
- const [moved] = newSteps.splice(dragIndex, 1);
- newSteps.splice(dragOverIndex, 0, moved);
- reorderSteps(
- guideId,
- newSteps.map((s) => s.id),
- );
- onReorder(newSteps);
- }
- setDragIndex(null);
- setDragOverIndex(null);
- };
-
- const handleInsertBlock = async (atIndex: number, blockType: BlockType) => {
- await insertBlock(guideId, atIndex, blockType, '');
- onChanged?.();
- };
-
- const toggleSelected = (index: number, extend: boolean) => {
- const from = extend && anchorIndex.current !== null ? anchorIndex.current : index;
- anchorIndex.current = index;
- setSelected((prev) => {
- const next = new Set(prev);
- const adding = !prev.has(steps[index].id);
- for (let i = Math.min(from, index); i <= Math.max(from, index); i++) {
- if (adding) next.add(steps[i].id);
- else next.delete(steps[i].id);
- }
- return next;
- });
- };
-
- const handleBulkDelete = async () => {
- setConfirmBulkDelete(false);
- const ids = steps.filter((step) => selected.has(step.id)).map((step) => step.id);
- try {
- if (await createSnapshot(guideId)) bumpHistoryRefresh();
- } catch (err) {
- logger.error(' Snapshot before bulk delete failed', err);
- }
- await deleteSteps(guideId, ids);
- setSelected(new Set());
- anchorIndex.current = null;
- onChanged?.();
- };
-
- const dragHandlers = (idx: number) =>
- readOnly
- ? undefined
- : {
- onDragStart: (e: React.DragEvent) => {
- setDragIndex(idx);
- e.dataTransfer.effectAllowed = 'move';
- },
- onDragOver: (e: React.DragEvent) => {
- e.preventDefault();
- setDragOverIndex(idx);
- },
- onDragEnd: handleDragEnd,
- };
-
- const captureDialog = (
- <CaptureTabDialog
- open={recordAtIndex !== null}
- onCancel={() => setRecordAtIndex(null)}
- onStart={(tabId) => {
- const atIndex = recordAtIndex;
- setRecordAtIndex(null);
- if (atIndex !== null) onInsertRecording?.(guideId, atIndex, tabId);
- }}
- />
- );
-
- if (steps.length === 0) {
- return (
- <div className="flex flex-col">
- <EmptyGuideState />
- {!readOnly && (
- <InsertBlockMenu
- onInsert={(blockType) => handleInsertBlock(0, blockType)}
- onRecord={onInsertRecording && (() => setRecordAtIndex(0))}
- />
- )}
- {captureDialog}
- </div>
- );
- }
-
- return (
- <div className="space-y-6">
- {!readOnly && (
- <InsertBlockMenu
- onInsert={(blockType) => handleInsertBlock(0, blockType)}
- onRecord={onInsertRecording && (() => setRecordAtIndex(0))}
- />
- )}
- {steps.map((step, idx) => (
- <div
- key={step.id}
- ref={(el) => {
- if (el) stepRefs.current.set(step.id, el);
- else stepRefs.current.delete(step.id);
- }}
- data-step-id={step.id}
- >
- {dragOverIndex === idx && dragIndex !== null && dragIndex !== idx && (
- <div className="h-1 bg-accent rounded-full mx-4 mb-2" />
- )}
- <div className="flex items-start gap-2">
- {!readOnly && (
- <input
- type="checkbox"
- checked={selected.has(step.id)}
- onChange={() => {}}
- onClick={(e) => toggleSelected(idx, e.shiftKey)}
- aria-label={i18n.t('editor.selectStep')}
- className="mt-3 shrink-0 w-4 h-4 accent-accent"
- />
- )}
- <div className="flex-1 min-w-0">
- {isBlock(step) ? (
- <BlockCard
- step={step}
- onDescriptionChange={onDescriptionChange}
- onDelete={onDelete}
- onChanged={onChanged}
- readOnly={readOnly}
- dragHandleProps={dragHandlers(idx)}
- />
- ) : (
- <StepCard
- step={step}
- number={numbers.get(step.id) ?? 0}
- screenshot={screenshots.get(step.id)}
- placeholderRatio={frameRatio}
- frameRatio={frameRatio}
- onDescriptionChange={onDescriptionChange}
- onDelete={onDelete}
- onOpenEditor={onOpenEditor}
- readOnly={readOnly}
- hasApiKey={hasApiKey}
- onChanged={onChanged}
- dragHandleProps={dragHandlers(idx)}
- />
- )}
- </div>
- </div>
- {!readOnly && (
- <InsertBlockMenu
- onInsert={(blockType) => handleInsertBlock(idx + 1, blockType)}
- onRecord={onInsertRecording && (() => setRecordAtIndex(idx + 1))}
- />
- )}
- </div>
- ))}
- {captureDialog}
- {selected.size > 0 && (
- <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-40 flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-lg">
- <span className="text-[12px] font-medium text-foreground">
- {i18n.t('editor.selectedCount', [String(selected.size)])}
- </span>
- <Button variant="ghost" size="sm" onClick={() => setSelected(new Set())}>
- {i18n.t('common.cancel')}
- </Button>
- <Button variant="destructive" size="sm" onClick={() => setConfirmBulkDelete(true)}>
- <Trash2 size={13} />
- {i18n.t('common.delete')}
- </Button>
- </div>
- )}
- <ConfirmDialog
- open={confirmBulkDelete}
- heading={
- selected.size === 1
- ? i18n.t('editor.deleteSelectedStep', ['1'])
- : i18n.t('editor.deleteSelectedSteps', [String(selected.size)])
- }
- destructive
- onConfirm={handleBulkDelete}
- onCancel={() => setConfirmBulkDelete(false)}
- />
- </div>
- );
-}
diff --git a/src/ui/fullview/components/KeyboardHints.tsx b/src/ui/fullview/components/KeyboardHints.tsx
index 70b516b..7a2ee5d 100644
--- a/src/ui/fullview/components/KeyboardHints.tsx
+++ b/src/ui/fullview/components/KeyboardHints.tsx
@@ -1,4 +1,4 @@
-import { i18n } from '#imports';
+import { i18n } from '@mimik/core/env';
const hints = [
{ key: '↑↓', labelKey: 'keyboard_navigate' as const },
diff --git a/src/ui/fullview/components/SearchResults.tsx b/src/ui/fullview/components/SearchResults.tsx
index c87cc16..13b5534 100644
--- a/src/ui/fullview/components/SearchResults.tsx
+++ b/src/ui/fullview/components/SearchResults.tsx
@@ -1,7 +1,7 @@
-import { i18n } from '#imports';
-import type { Guide } from '@/core/guides/types';
-import { formatDateShort } from '@/lib/utils';
-import FaviconImg from '@/ui/shared/FaviconImg';
+import { i18n } from '@mimik/core/env';
+import type { Guide } from '@mimik/core/guides/types';
+import { formatDateShort } from '@mimik/ui/lib/utils';
+import FaviconImg from '@mimik/ui/shared/FaviconImg';
interface GuideResult {
guide: Guide;
diff --git a/src/ui/fullview/components/VersionHistoryPanel.tsx b/src/ui/fullview/components/VersionHistoryPanel.tsx
deleted file mode 100644
index 666542f..0000000
--- a/src/ui/fullview/components/VersionHistoryPanel.tsx
+++ /dev/null
@@ -1,368 +0,0 @@
-import { ChevronRight, MoreVertical, RotateCcw, X } from 'lucide-react';
-import { useEffect, useMemo, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import { getSnapshots, renameSnapshot, revertToSnapshot } from '@/core/guides/service';
-import { diffSnapshots, type SnapshotDiff, type SnapshotLike } from '@/core/guides/snapshot-diff';
-import { groupSnapshots } from '@/core/guides/snapshot-groups';
-import type { Snapshot } from '@/core/guides/types';
-import { formatDateTime } from '@/lib/utils';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from '@/ui/components/ui/dropdown-menu';
-
-function isQuotaError(e: unknown): boolean {
- return e instanceof Error && (e.name === 'QuotaExceededError' || e.name === 'DexieError2QuotaExceededError');
-}
-
-function changeSummary(diff: SnapshotDiff): string {
- const parts: string[] = [];
- if (diff.titleChanged) parts.push(i18n.t('history.changeTitle'));
- if (diff.added === 1) parts.push(i18n.t('history.changeStepAdded', [String(diff.added)]));
- else if (diff.added > 1) parts.push(i18n.t('history.changeStepsAdded', [String(diff.added)]));
- if (diff.removed === 1) parts.push(i18n.t('history.changeStepRemoved', [String(diff.removed)]));
- else if (diff.removed > 1) parts.push(i18n.t('history.changeStepsRemoved', [String(diff.removed)]));
- if (diff.edited === 1) parts.push(i18n.t('history.changeStepEdited', [String(diff.edited)]));
- else if (diff.edited > 1) parts.push(i18n.t('history.changeStepsEdited', [String(diff.edited)]));
- if (diff.urls === 1) parts.push(i18n.t('history.changeLink', [String(diff.urls)]));
- else if (diff.urls > 1) parts.push(i18n.t('history.changeLinks', [String(diff.urls)]));
- if (diff.replaced === 1) parts.push(i18n.t('history.changeImageReplaced', [String(diff.replaced)]));
- else if (diff.replaced > 1) parts.push(i18n.t('history.changeImagesReplaced', [String(diff.replaced)]));
- if (diff.cropped === 1) parts.push(i18n.t('history.changeImageCropped', [String(diff.cropped)]));
- else if (diff.cropped > 1) parts.push(i18n.t('history.changeImagesCropped', [String(diff.cropped)]));
- if (diff.annotated === 1) parts.push(i18n.t('history.changeImageAnnotated', [String(diff.annotated)]));
- else if (diff.annotated > 1) parts.push(i18n.t('history.changeImagesAnnotated', [String(diff.annotated)]));
- if (diff.blurred === 1) parts.push(i18n.t('history.changeImageBlurred', [String(diff.blurred)]));
- else if (diff.blurred > 1) parts.push(i18n.t('history.changeImagesBlurred', [String(diff.blurred)]));
- if (diff.altEdited) parts.push(i18n.t('history.changeAltText'));
- if (diff.reordered) parts.push(i18n.t('history.changeStepReordered'));
- return parts.join(' Β· ');
-}
-
-function filterPill(active: boolean): string {
- return `px-2 py-0.5 rounded-full text-[10px] font-semibold border ${
- active
- ? 'bg-secondary border-border text-foreground'
- : 'border-transparent text-muted-foreground hover:text-foreground'
- }`;
-}
-
-interface VersionHistoryPanelProps {
- guideId: string;
- selectedId: string | null;
- refreshKey: number;
- live: SnapshotLike;
- onSelect: (snapshot: Snapshot | null) => void;
- onRestored: () => void;
- onClose: () => void;
-}
-
-export default function VersionHistoryPanel({
- guideId,
- selectedId,
- refreshKey,
- live,
- onSelect,
- onRestored,
- onClose,
-}: VersionHistoryPanelProps) {
- const [snapshots, setSnapshots] = useState<Snapshot[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [restoring, setRestoring] = useState(false);
- const [expanded, setExpanded] = useState<Set<string>>(new Set());
- const [namedOnly, setNamedOnly] = useState(false);
- const [renamingId, setRenamingId] = useState<string | null>(null);
- const [draft, setDraft] = useState('');
- const refreshRef = useRef(refreshKey);
- const renamingRef = useRef<string | null>(null);
- const inputRef = useRef<HTMLInputElement>(null);
-
- useEffect(() => {
- const silent = refreshRef.current !== refreshKey;
- refreshRef.current = refreshKey;
- let cancelled = false;
- if (!silent) {
- setLoading(true);
- setError(null);
- renamingRef.current = null;
- setRenamingId(null);
- }
- getSnapshots(guideId)
- .then((list) => {
- if (!cancelled) setSnapshots(list);
- })
- .catch(() => {
- if (!cancelled) setError(i18n.t('history.loadError'));
- })
- .finally(() => {
- if (!cancelled) setLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, [guideId, refreshKey]);
-
- useEffect(() => {
- if (renamingId) inputRef.current?.focus();
- }, [renamingId]);
-
- const diffs = useMemo(() => {
- const map = new Map<string, SnapshotDiff>();
- snapshots.forEach((snapshot, i) => {
- const older = snapshots[i + 1];
- if (older) map.set(snapshot.id, diffSnapshots(older, snapshot));
- });
- return map;
- }, [snapshots]);
-
- const currentSummary = useMemo(
- () => (snapshots.length > 0 ? changeSummary(diffSnapshots(snapshots[0], live)) : ''),
- [snapshots, live],
- );
-
- const named = useMemo(() => snapshots.filter((s) => s.name), [snapshots]);
-
- const handleRestore = async (snapshot: Snapshot) => {
- if (restoring) return;
- setRestoring(true);
- setError(null);
- try {
- const undo = await revertToSnapshot(snapshot.id);
- if (!undo) {
- setError(i18n.t('history.restoreError'));
- return;
- }
- setSnapshots(await getSnapshots(guideId));
- setExpanded(new Set());
- renamingRef.current = null;
- setRenamingId(null);
- onSelect(null);
- onRestored();
- } catch (e) {
- setError(i18n.t(isQuotaError(e) ? 'history.storageFull' : 'history.restoreError'));
- } finally {
- setRestoring(false);
- }
- };
-
- const startRename = (snapshot: Snapshot) => {
- renamingRef.current = snapshot.id;
- setRenamingId(snapshot.id);
- setDraft(snapshot.name ?? '');
- };
-
- const cancelRename = () => {
- renamingRef.current = null;
- setRenamingId(null);
- };
-
- const commitRename = async (snapshot: Snapshot) => {
- if (renamingRef.current !== snapshot.id) return;
- renamingRef.current = null;
- setRenamingId(null);
- const trimmed = draft.trim();
- const name = trimmed === '' ? undefined : trimmed;
- if (name === snapshot.name) return;
- try {
- await renameSnapshot(snapshot.id, trimmed);
- setSnapshots((prev) => prev.map((s) => (s.id === snapshot.id ? { ...s, name } : s)));
- } catch {
- setError(i18n.t('history.renameError'));
- }
- };
-
- const toggle = (key: string) => {
- setExpanded((prev) => {
- const next = new Set(prev);
- if (next.has(key)) next.delete(key);
- else next.add(key);
- return next;
- });
- };
-
- const entry = (snapshot: Snapshot) => {
- const active = selectedId === snapshot.id;
- const diff = diffs.get(snapshot.id);
- const summary = diff ? changeSummary(diff) : '';
- return (
- <div key={snapshot.id} className="relative pl-5 py-2.5">
- <span
- className={`absolute left-0 top-4 w-2 h-2 rounded-full border-2 ${
- active ? 'bg-accent border-accent' : 'bg-card border-border'
- }`}
- />
- <div className="flex items-start gap-1">
- <div className="flex-1 min-w-0">
- {renamingId === snapshot.id ? (
- <input
- ref={inputRef}
- value={draft}
- placeholder={i18n.t('history.namePlaceholder')}
- aria-label={i18n.t('history.namePlaceholder')}
- onChange={(e) => setDraft(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- void commitRename(snapshot);
- } else if (e.key === 'Escape') {
- e.preventDefault();
- cancelRename();
- }
- }}
- onBlur={() => void commitRename(snapshot)}
- className="w-full text-[12px] font-semibold text-foreground bg-card border border-accent rounded px-1.5 py-0.5 focus:outline-none"
- />
- ) : (
- <button
- type="button"
- aria-pressed={active}
- onClick={() => onSelect(active ? null : snapshot)}
- className={`block w-full text-left text-[12px] ${
- active ? 'font-semibold text-foreground' : 'text-muted-foreground hover:text-foreground'
- }`}
- >
- <span className="block truncate">{snapshot.name || formatDateTime(snapshot.createdAt)}</span>
- {snapshot.name && (
- <span className="block text-[10px] font-normal text-muted-foreground mt-0.5">
- {formatDateTime(snapshot.createdAt)}
- </span>
- )}
- </button>
- )}
- {summary && <p className="text-[10px] text-muted-foreground mt-0.5">{summary}</p>}
- {active && (
- <button
- type="button"
- disabled={restoring}
- onClick={() => void handleRestore(snapshot)}
- className="inline-flex items-center gap-1.5 mt-2 text-[11px] font-semibold text-accent disabled:opacity-50"
- >
- <RotateCcw size={11} />
- {i18n.t('history.restore')}
- </button>
- )}
- </div>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- aria-label={i18n.t('history.nameVersion')}
- className="shrink-0 p-0.5 text-muted-foreground hover:text-foreground"
- >
- <MoreVertical size={13} />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" onCloseAutoFocus={(e) => e.preventDefault()}>
- <DropdownMenuItem onSelect={() => startRename(snapshot)}>
- {i18n.t('history.nameVersion')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- );
- };
-
- return (
- <aside className="w-72 shrink-0 border-l border-border pl-4 flex flex-col gap-1">
- <div className="flex items-center gap-2 h-10">
- <button
- type="button"
- onClick={onClose}
- aria-label={i18n.t('common.close')}
- className="p-1 text-muted-foreground hover:text-foreground"
- >
- <X size={14} />
- </button>
- <span className="text-[13px] font-semibold text-foreground">{i18n.t('history.title')}</span>
- </div>
-
- {error && (
- <p role="alert" className="text-[11px] text-destructive py-2">
- {error}
- </p>
- )}
-
- {loading ? (
- <p className="text-[11px] text-muted-foreground py-2">{i18n.t('common.loading')}</p>
- ) : snapshots.length === 0 ? (
- <p className="text-[11px] text-muted-foreground py-2">{i18n.t('history.empty')}</p>
- ) : (
- <>
- <div className="flex items-center gap-1 pb-1">
- <button
- type="button"
- aria-pressed={!namedOnly}
- onClick={() => setNamedOnly(false)}
- className={filterPill(!namedOnly)}
- >
- {i18n.t('history.allVersions')}
- </button>
- <button
- type="button"
- aria-pressed={namedOnly}
- onClick={() => setNamedOnly(true)}
- className={filterPill(namedOnly)}
- >
- {i18n.t('history.namedOnly')}
- </button>
- </div>
- <div className="relative border-l border-dashed border-border ml-1 pl-2 flex-1 min-h-0 overflow-y-auto">
- <div className="pl-5 py-2.5 relative">
- <span
- className={`absolute left-0 top-4 w-2 h-2 rounded-full border-2 ${
- selectedId === null ? 'bg-accent border-accent' : 'bg-card border-border'
- }`}
- />
- <button
- type="button"
- aria-pressed={selectedId === null}
- onClick={() => onSelect(null)}
- className={`block w-full text-left text-[12px] ${
- selectedId === null ? 'font-semibold text-foreground' : 'text-muted-foreground hover:text-foreground'
- }`}
- >
- {i18n.t('history.current')}
- </button>
- {currentSummary && <p className="text-[11px] text-muted-foreground mt-0.5">{currentSummary}</p>}
- </div>
- {namedOnly ? (
- named.length === 0 ? (
- <p className="text-[11px] text-muted-foreground py-2 pl-5">{i18n.t('history.emptyNamed')}</p>
- ) : (
- named.map(entry)
- )
- ) : (
- groupSnapshots(snapshots).map((row) =>
- row.kind === 'entry' ? (
- entry(row.snapshot)
- ) : (
- <div key={row.snapshots[0].id}>
- <button
- type="button"
- aria-expanded={expanded.has(row.snapshots[0].id)}
- onClick={() => toggle(row.snapshots[0].id)}
- className="flex items-center gap-1 py-2 text-[11px] text-muted-foreground hover:text-foreground"
- >
- <ChevronRight
- size={11}
- className={
- expanded.has(row.snapshots[0].id) ? 'rotate-90 transition-transform' : 'transition-transform'
- }
- />
- {i18n.t('history.unchangedVersions', [String(row.snapshots.length)])}
- </button>
- {expanded.has(row.snapshots[0].id) && row.snapshots.map(entry)}
- </div>
- ),
- )
- )}
- </div>
- </>
- )}
- </aside>
- );
-}
diff --git a/src/ui/fullview/components/VoiceNotice.tsx b/src/ui/fullview/components/VoiceNotice.tsx
index 1760df2..1b92e40 100644
--- a/src/ui/fullview/components/VoiceNotice.tsx
+++ b/src/ui/fullview/components/VoiceNotice.tsx
@@ -1,9 +1,9 @@
+import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui/components/ui/tooltip';
import { Check, Loader2, TriangleAlert, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
import { getVoiceStatus } from '@/lib/offscreen';
import { observeVoiceFromBackground, type PanelVoiceUpdate } from '@/lib/port';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
import { voiceNotice } from '../voice-notice';
const IDLE: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'idle' };
diff --git a/src/ui/fullview/components/__tests__/version-history-panel.test.tsx b/src/ui/fullview/components/__tests__/version-history-panel.test.tsx
deleted file mode 100644
index 3a0e369..0000000
--- a/src/ui/fullview/components/__tests__/version-history-panel.test.tsx
+++ /dev/null
@@ -1,238 +0,0 @@
-// @vitest-environment jsdom
-import { render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { SnapshotLike } from '@/core/guides/snapshot-diff';
-import type { Screenshot, Snapshot, Step } from '@/core/guides/types';
-import type { Annotation, ScreenshotEdits } from '@/core/screenshot/types';
-
-const getSnapshots = vi.fn();
-
-vi.mock('@/core/guides/service', () => ({
- getSnapshots: (...args: unknown[]) => getSnapshots(...args),
- renameSnapshot: vi.fn(),
- revertToSnapshot: vi.fn(),
-}));
-
-import VersionHistoryPanel from '../VersionHistoryPanel';
-
-const box: Annotation = { id: 'a1', type: 'box', x: 0, y: 0, w: 10, h: 10, color: '#000000' };
-const otherBox: Annotation = { id: 'a1', type: 'box', x: 4, y: 4, w: 10, h: 10, color: '#000000' };
-const redact: Annotation = { id: 'r1', type: 'redact', x: 0, y: 0, w: 5, h: 5, style: 'blur' };
-const otherRedact: Annotation = { id: 'r1', type: 'redact', x: 0, y: 0, w: 5, h: 5, style: 'solid' };
-const viewportA = { x: 0, y: 0, width: 100, height: 50 };
-const viewportB = { x: 5, y: 0, width: 90, height: 50 };
-
-function step(id: string, description: string, screenshotId?: string, url = 'https://a.test'): Step {
- return {
- id,
- guideId: 'g1',
- index: 0,
- description,
- action: 'click',
- url,
- timestamp: 1,
- ...(screenshotId ? { screenshotId } : {}),
- };
-}
-
-function shot(id: string, stepId: string, edits?: ScreenshotEdits): Omit<Screenshot, 'blob'> {
- return { id, stepId, mimeType: 'image/png', width: 10, height: 10, ...(edits ? { edits } : {}) };
-}
-
-function older(overrides: Partial<Snapshot>): Snapshot {
- return {
- id: 'n1',
- guideId: 'g1',
- createdAt: 1_700_000_000_000,
- contentHash: 'h1',
- title: 'Guide',
- stepIds: [],
- steps: [],
- screenshots: [],
- ...overrides,
- };
-}
-
-function setup(snapshot: Snapshot, live: SnapshotLike) {
- getSnapshots.mockResolvedValue([snapshot]);
- return render(
- <VersionHistoryPanel
- guideId="g1"
- selectedId={null}
- refreshKey={0}
- live={live}
- onSelect={vi.fn()}
- onRestored={vi.fn()}
- onClose={vi.fn()}
- />,
- );
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe('VersionHistoryPanel change summary', () => {
- it('lists every cause once, in order, for a version that changed one of each', async () => {
- const snapshot = older({
- title: 'Before',
- stepIds: ['s1', 's3', 's4', 's5', 's6', 's7', 's8', 's9'],
- steps: [
- step('s1', 'Gone'),
- step('s3', 'Old three'),
- step('s4', 'Same', undefined, 'https://a.test/one'),
- step('s5', 'Same', 'sc5a'),
- step('s6', 'Same', 'sc6'),
- step('s7', 'Same', 'sc7'),
- step('s8', 'Same', 'sc8'),
- step('s9', 'Same', 'sc9'),
- ],
- screenshots: [
- shot('sc5a', 's5'),
- shot('sc6', 's6', { viewport: viewportA }),
- shot('sc7', 's7', { annotations: [box] }),
- shot('sc8', 's8', { annotations: [redact] }),
- shot('sc9', 's9', { alt: 'before' }),
- ],
- });
- const live: SnapshotLike = {
- title: 'After',
- stepIds: ['s2', 's4', 's3', 's5', 's6', 's7', 's8', 's9'],
- steps: [
- step('s2', 'New'),
- step('s4', 'Same', undefined, 'https://a.test/two'),
- step('s3', 'New three'),
- step('s5', 'Same', 'sc5b'),
- step('s6', 'Same', 'sc6'),
- step('s7', 'Same', 'sc7'),
- step('s8', 'Same', 'sc8'),
- step('s9', 'Same', 'sc9'),
- ],
- screenshots: [
- shot('sc5b', 's5'),
- shot('sc6', 's6', { viewport: viewportB }),
- shot('sc7', 's7', { annotations: [otherBox] }),
- shot('sc8', 's8', { annotations: [otherRedact] }),
- shot('sc9', 's9', { alt: 'after' }),
- ],
- };
-
- setup(snapshot, live);
-
- const expected = [
- 'history.changeTitle',
- 'history.changeStepAdded[1]',
- 'history.changeStepRemoved[1]',
- 'history.changeStepEdited[1]',
- 'history.changeLink[1]',
- 'history.changeImageReplaced[1]',
- 'history.changeImageCropped[1]',
- 'history.changeImageAnnotated[1]',
- 'history.changeImageBlurred[1]',
- 'history.changeAltText',
- 'history.changeStepReordered',
- ].join(' Β· ');
-
- await waitFor(() => {
- expect(screen.getByText(expected)).toBeTruthy();
- });
- });
-
- it('uses the plural key for every counted cause above one', async () => {
- const ids = ['e1', 'e2', 'u1', 'u2', 'rp1', 'rp2', 'cr1', 'cr2', 'an1', 'an2', 'bl1', 'bl2'];
- const snapshot = older({
- title: 'Before',
- stepIds: ['x1', 'x2', ...ids],
- steps: [
- step('x1', 'Gone one'),
- step('x2', 'Gone two'),
- step('e1', 'Old e1'),
- step('e2', 'Old e2'),
- step('u1', 'Same', undefined, 'https://a.test/one'),
- step('u2', 'Same', undefined, 'https://a.test/two'),
- step('rp1', 'Same', 'rp1a'),
- step('rp2', 'Same', 'rp2a'),
- step('cr1', 'Same', 'cr1s'),
- step('cr2', 'Same', 'cr2s'),
- step('an1', 'Same', 'an1s'),
- step('an2', 'Same', 'an2s'),
- step('bl1', 'Same', 'bl1s'),
- step('bl2', 'Same', 'bl2s'),
- ],
- screenshots: [
- shot('rp1a', 'rp1'),
- shot('rp2a', 'rp2'),
- shot('cr1s', 'cr1', { viewport: viewportA, alt: 'before' }),
- shot('cr2s', 'cr2', { viewport: viewportA }),
- shot('an1s', 'an1', { annotations: [box] }),
- shot('an2s', 'an2', { annotations: [box] }),
- shot('bl1s', 'bl1', { annotations: [redact] }),
- shot('bl2s', 'bl2', { annotations: [redact] }),
- ],
- });
- const live: SnapshotLike = {
- title: 'After',
- stepIds: ['y1', 'y2', 'e2', 'e1', ...ids.slice(2)],
- steps: [
- step('y1', 'New one'),
- step('y2', 'New two'),
- step('e2', 'New e2'),
- step('e1', 'New e1'),
- step('u1', 'Same', undefined, 'https://b.test/one'),
- step('u2', 'Same', undefined, 'https://b.test/two'),
- step('rp1', 'Same', 'rp1b'),
- step('rp2', 'Same', 'rp2b'),
- step('cr1', 'Same', 'cr1s'),
- step('cr2', 'Same', 'cr2s'),
- step('an1', 'Same', 'an1s'),
- step('an2', 'Same', 'an2s'),
- step('bl1', 'Same', 'bl1s'),
- step('bl2', 'Same', 'bl2s'),
- ],
- screenshots: [
- shot('rp1b', 'rp1'),
- shot('rp2b', 'rp2'),
- shot('cr1s', 'cr1', { viewport: viewportB, alt: 'after' }),
- shot('cr2s', 'cr2', { viewport: viewportB }),
- shot('an1s', 'an1', { annotations: [otherBox] }),
- shot('an2s', 'an2', { annotations: [otherBox] }),
- shot('bl1s', 'bl1', { annotations: [otherRedact] }),
- shot('bl2s', 'bl2', { annotations: [otherRedact] }),
- ],
- };
-
- setup(snapshot, live);
-
- const expected = [
- 'history.changeTitle',
- 'history.changeStepsAdded[2]',
- 'history.changeStepsRemoved[2]',
- 'history.changeStepsEdited[2]',
- 'history.changeLinks[2]',
- 'history.changeImagesReplaced[2]',
- 'history.changeImagesCropped[2]',
- 'history.changeImagesAnnotated[2]',
- 'history.changeImagesBlurred[2]',
- 'history.changeAltText',
- 'history.changeStepReordered',
- ].join(' Β· ');
-
- await waitFor(() => {
- expect(screen.getByText(expected)).toBeTruthy();
- });
- });
-
- it('renders no summary when nothing changed', async () => {
- const steps = [step('s1', 'One', 'sc1')];
- const screenshots = [shot('sc1', 's1', { annotations: [box, redact], alt: 'same' })];
- const snapshot = older({ stepIds: ['s1'], steps, screenshots });
- const live: SnapshotLike = { title: 'Guide', stepIds: ['s1'], steps, screenshots };
-
- setup(snapshot, live);
-
- await waitFor(() => {
- expect(screen.getByText('history.current')).toBeTruthy();
- });
- expect(screen.queryByText(/history\.change/)).toBeNull();
- });
-});
diff --git a/src/ui/fullview/router.ts b/src/ui/fullview/router.ts
deleted file mode 100644
index 43eb525..0000000
--- a/src/ui/fullview/router.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useEffect, useState } from 'react';
-
-export type Route =
- | { page: 'library'; category: 'all' | 'starred' | 'trash' }
- | {
- page: 'guide';
- guideId: string;
- stepId?: string;
- tool?: 'annotate' | 'redact' | 'crop' | 'target';
- };
-
-function parseHash(hash: string): Route {
- const h = hash.replace(/^#\/?/, '');
- if (h.startsWith('guide/')) {
- const guideId = h.slice(6);
- if (guideId) return { page: 'guide', guideId };
- }
- if (h === 'library/starred') return { page: 'library', category: 'starred' };
- if (h === 'library/trash') return { page: 'library', category: 'trash' };
- return { page: 'library', category: 'all' };
-}
-
-export function navigate(route: Route) {
- if (route.page === 'guide') {
- window.location.hash = `#guide/${route.guideId}`;
- } else if (route.category === 'all') {
- window.location.hash = '#library';
- } else {
- window.location.hash = `#library/${route.category}`;
- }
-}
-
-export function useRoute(): Route {
- const [route, setRoute] = useState<Route>(() => {
- const params = new URLSearchParams(window.location.search);
- const guideId = params.get('guideId');
- if (guideId) {
- const stepId = params.get('stepId') ?? undefined;
- const toolParam = params.get('tool');
- const tool =
- toolParam === 'annotate' || toolParam === 'redact' || toolParam === 'crop' || toolParam === 'target'
- ? toolParam
- : undefined;
- window.history.replaceState(null, '', `${window.location.pathname}#guide/${guideId}`);
- return { page: 'guide', guideId, stepId, tool };
- }
- return parseHash(window.location.hash);
- });
-
- useEffect(() => {
- const handler = () => setRoute(parseHash(window.location.hash));
- window.addEventListener('hashchange', handler);
- return () => window.removeEventListener('hashchange', handler);
- }, []);
-
- return route;
-}
diff --git a/src/ui/global.css b/src/ui/global.css
deleted file mode 100644
index da58704..0000000
--- a/src/ui/global.css
+++ /dev/null
@@ -1,79 +0,0 @@
-@import "@fontsource/poppins/400.css";
-@import "@fontsource/poppins/500.css";
-@import "@fontsource/poppins/600.css";
-@import "@fontsource/poppins/700.css";
-@import "@fontsource/poppins/800.css";
-@import "tailwindcss";
-
-@custom-variant dark (&:is(.dark *));
-
-@theme inline {
- --color-background: #fafafc;
- --color-foreground: #1E1B4B;
- --color-card: #fff;
- --color-card-foreground: #1E1B4B;
- --color-popover: #fff;
- --color-popover-foreground: #1E1B4B;
- --color-primary: #1E1B4B;
- --color-primary-foreground: #C7D2FE;
- --color-secondary: #EEF2FF;
- --color-secondary-foreground: #1E1B4B;
- --color-muted: #EEF2FF;
- --color-muted-foreground: #6B7280;
- --color-accent: #4F46E5;
- --color-accent-foreground: #EEF2FF;
- --color-destructive: #DC2626;
- --color-destructive-foreground: #fff;
- --color-border: #C7D2FE;
- --color-input: #C7D2FE;
- --color-ring: #4F46E5;
- --radius: 0.5rem;
-
- --color-violet: #818CF8;
- --color-violet-light: #A78BFA;
- --color-violet-dark: #3730A3;
- --color-violet-mid: #3730A3;
- --color-lavender: #C7D2FE;
- --color-purple: #4F46E5;
- --color-deep: #1E1B4B;
- --color-success: #059669;
-}
-
-body {
- font-family: "Poppins", sans-serif;
-}
-
-button:not(:disabled):not([aria-disabled="true"]),
-[role="button"]:not([aria-disabled="true"]),
-label:has(> input[type="checkbox"]),
-input[type="checkbox"]:not(:disabled) {
- cursor: pointer;
-}
-
-@keyframes gradient-text {
- 0% { background-position: 100% 50%; }
- 100% { background-position: -100% 50%; }
-}
-
-@utility animate-gradient-text {
- animation: gradient-text 3s ease infinite;
-}
-
-@keyframes twinkle {
- 0%, 100% { opacity: 0.3; transform: scale(0.8); }
- 50% { opacity: 1; transform: scale(1.1); }
-}
-
-@keyframes cam-flash {
- 0%, 88%, 100% { opacity: 0; }
- 92% { opacity: 0.7; }
-}
-
-@keyframes blink {
- 0%, 100% { opacity: 1; }
- 50% { opacity: 0; }
-}
-
-@utility animate-blink {
- animation: blink 0.7s step-end infinite;
-}
diff --git a/src/ui/onboarding/App.tsx b/src/ui/onboarding/App.tsx
index 49e9124..e4f67f7 100644
--- a/src/ui/onboarding/App.tsx
+++ b/src/ui/onboarding/App.tsx
@@ -1,3 +1,5 @@
+import { Input } from '@mimik/ui/components/ui/input';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@mimik/ui/components/ui/select';
import { Globe, Mic, MousePointerClick, Shield } from 'lucide-react';
import { useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
@@ -15,8 +17,6 @@ import {
import { AI_LANGUAGES, type AILanguageCode } from '@/core/capture/ai/prompts';
import type { VoiceProvider } from '@/core/capture/voice/transcribe';
import { localStorage, openSidebar, requestHostPermissions } from '@/lib/browser-api';
-import { Input } from '@/ui/components/ui/input';
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/ui/components/ui/select';
import { KeyStatusNote, KeyWarningNote, ModelList, SecretInput, useKeyCheck } from '@/ui/shared/key-check';
import MicrophonePicker from '@/ui/shared/MicrophonePicker';
diff --git a/src/ui/options/index.css b/src/ui/options/index.css
index 88a2057..f03ac8b 100644
--- a/src/ui/options/index.css
+++ b/src/ui/options/index.css
@@ -1,4 +1,4 @@
-@import "../global.css";
+@import "../../../packages/ui/src/global.css";
html, body, #root {
margin: 0;
diff --git a/src/ui/shared/AnnotationEditor.tsx b/src/ui/shared/AnnotationEditor.tsx
deleted file mode 100644
index dd7707c..0000000
--- a/src/ui/shared/AnnotationEditor.tsx
+++ /dev/null
@@ -1,1245 +0,0 @@
-import {
- ArrowUpRight,
- ChevronDown,
- Circle as CircleIcon,
- CopyPlus,
- Crop,
- EyeOff,
- Minus,
- MousePointer2,
- MousePointerClick,
- MoveVertical,
- Redo2,
- RotateCcw,
- Square,
- SquareDashed,
- Trash2,
- Type,
- Undo2,
-} from 'lucide-react';
-import type { ComponentType, ReactNode } from 'react';
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import { updateScreenshotEdits } from '@/core/guides/service';
-import type { Screenshot, ScreenshotBounds } from '@/core/guides/types';
-import { shadeOf } from '@/core/screenshot/color';
-import { drawAnnotation, drawRoundedRect, TARGET_RADIUS, TARGET_STROKE } from '@/core/screenshot/draw';
-import {
- annotationBounds,
- cropTo,
- type Handle,
- hitTest,
- moveAnnotation,
- resizeAnnotation,
- resolveTarget,
-} from '@/core/screenshot/geometry';
-import type {
- Annotation,
- ArrowEnd,
- FontFamily,
- LineWidth,
- ScreenshotEdits,
- TargetBorder,
-} from '@/core/screenshot/types';
-import {
- ARROW_ENDS,
- DEFAULT_FONT_SIZE,
- DEFAULT_LINE_HEIGHT,
- DEFAULT_TARGET_COLOR,
- FONT_FAMILIES,
- FONT_FAMILY_ORDER,
- LINE_WIDTH_ORDER,
- LINE_WIDTHS,
- MAX_FONT_SIZE,
- MAX_LINE_HEIGHT,
- MIN_FONT_SIZE,
- MIN_LINE_HEIGHT,
-} from '@/core/screenshot/types';
-import { localStorage } from '@/lib/browser-api';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from '@/ui/components/ui/dropdown-menu';
-import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover';
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import ColorPicker, { swatchStyle } from './ColorPicker';
-
-type EditorMode = 'crop' | 'annotate' | 'redact';
-type EditorTool = 'select' | 'crop' | 'box' | 'ellipse' | 'arrow' | 'line' | 'text' | 'redact';
-
-interface AnnotationEditorProps {
- screenshot: Screenshot;
- tool: 'annotate' | 'redact' | 'crop' | 'target';
- onDone: (edits: ScreenshotEdits) => void;
- onCancel: () => void;
-}
-
-interface TextEditorState {
- x: number;
- y: number;
- left: number;
- top: number;
-}
-
-type DragState =
- | { mode: 'move'; id: string; lastX: number; lastY: number }
- | { mode: 'resize'; id: string; handle: Handle; lastX: number; lastY: number }
- | { mode: 'crop'; start: { x: number; y: number }; rect: ScreenshotBounds }
- | { mode: 'cropResize'; handle: Handle; rect: ScreenshotBounds; lastX: number; lastY: number }
- | { mode: 'cropMove'; rect: ScreenshotBounds; lastX: number; lastY: number }
- | { mode: 'draw'; start: { x: number; y: number }; shape: Annotation };
-
-const COLORS = ['#4F46E5', '#DC2626', '#059669', '#F59E0B', '#1E1B4B'];
-const SELECTION_COLOR = '#4F46E5';
-const BRACKET_ARM = 26;
-const BRACKET_THICKNESS = 4;
-const MIN_SHAPE_SIZE = 6;
-const MIN_CROP_SIZE = 20;
-const HANDLE_DISPLAY_SIZE = 10;
-const HANDLE_HIT_PX = 10;
-const HISTORY_LIMIT = 49;
-
-function clampNumber(raw: string | number, min: number, max: number): number {
- const n = Number(raw);
- if (!Number.isFinite(n)) return min;
- return Math.min(max, Math.max(min, n));
-}
-
-interface StepperProps {
- label: string;
- value: number;
- min: number;
- max: number;
- step: number;
- decimals?: number;
- width: string;
- prefix?: ReactNode;
- suffix?: ReactNode;
- onChange: (value: number) => void;
-}
-
-function Stepper({ label, value, min, max, step, decimals = 0, width, prefix, suffix, onChange }: StepperProps) {
- const round = (n: number) => Number(n.toFixed(decimals));
- return (
- <Tip label={label}>
- <div className="flex items-center gap-0.5 rounded-md bg-primary-foreground/10 h-6 px-1">
- {prefix}
- <button
- type="button"
- aria-label="-"
- onClick={() => onChange(round(clampNumber(value - step, min, max)))}
- className="w-4 h-5 rounded text-primary-foreground/70 hover:bg-primary-foreground/15 text-[13px] leading-none"
- >
- &minus;
- </button>
- <input
- value={value}
- inputMode="decimal"
- aria-label={label}
- onChange={(e) => onChange(round(clampNumber(e.target.value, min, max)))}
- className={`${width} bg-transparent text-center text-[11px] tabular-nums text-primary-foreground outline-none`}
- />
- <button
- type="button"
- aria-label="+"
- onClick={() => onChange(round(clampNumber(value + step, min, max)))}
- className="w-4 h-5 rounded text-primary-foreground/70 hover:bg-primary-foreground/15 text-[13px] leading-none"
- >
- +
- </button>
- {suffix}
- </div>
- </Tip>
- );
-}
-
-const TOOLBAR_TRIGGER =
- 'flex items-center gap-1 h-6 rounded-md bg-primary-foreground/10 px-1.5 text-primary-foreground hover:bg-primary-foreground/20';
-
-function Tip({ label, children }: { label: string; children: ReactNode }) {
- return (
- <Tooltip>
- <TooltipTrigger asChild>{children}</TooltipTrigger>
- <TooltipContent>{label}</TooltipContent>
- </Tooltip>
- );
-}
-
-interface ColorPopoverProps {
- label: string;
- value: string;
- allowNone?: boolean;
- onChange: (color: string) => void;
- children: ReactNode;
-}
-
-function ColorPopover({ label, value, allowNone, onChange, children }: ColorPopoverProps) {
- return (
- <Popover>
- <Tooltip>
- <TooltipTrigger asChild>
- <PopoverTrigger asChild>{children}</PopoverTrigger>
- </TooltipTrigger>
- <TooltipContent>{label}</TooltipContent>
- </Tooltip>
- <PopoverContent align="center" className="w-56 p-2.5">
- <ColorPicker value={value} allowNone={allowNone} onChange={onChange} />
- </PopoverContent>
- </Popover>
- );
-}
-
-function MenuPopover({ label, children, items }: { label: string; children: ReactNode; items: ReactNode }) {
- return (
- <DropdownMenu>
- <Tooltip>
- <TooltipTrigger asChild>
- <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
- </TooltipTrigger>
- <TooltipContent>{label}</TooltipContent>
- </Tooltip>
- <DropdownMenuContent align="center">{items}</DropdownMenuContent>
- </DropdownMenu>
- );
-}
-
-const ARROW_END_MARKS: Record<ArrowEnd, ReactNode> = {
- none: null,
- bar: <line x1="25" y1="2" x2="25" y2="10" />,
- arrow: <polyline points="19,2 25,6 19,10" fill="none" />,
- 'arrow-solid': <polygon points="26,6 18,2 18,10" stroke="none" />,
- circle: <circle cx="22" cy="6" r="3.5" fill="none" />,
- 'circle-solid': <circle cx="22" cy="6" r="3.5" stroke="none" />,
- square: <rect x="18.5" y="2.5" width="7" height="7" fill="none" />,
- 'square-solid': <rect x="18.5" y="2.5" width="7" height="7" stroke="none" />,
-};
-
-function ArrowEndGlyph({ end }: { end: ArrowEnd }) {
- return (
- <svg
- width="30"
- height="12"
- viewBox="0 0 30 12"
- stroke="currentColor"
- strokeWidth="1.6"
- fill="currentColor"
- aria-hidden="true"
- >
- <line x1="3" y1="6" x2={end === 'none' ? 27 : 19} y2="6" />
- {ARROW_END_MARKS[end]}
- </svg>
- );
-}
-
-const TARGET_DASH = [8, 5];
-const TARGET_MARCH = [26, 10];
-const DASH_PERIOD = 13;
-const MARCH_PERIOD = 36;
-const TARGET_MARCH_CYCLES = 4;
-const PULSE_PERIOD_MS = 5200;
-
-const TARGET_SWEEP: [number, number, number][] = [
- [0, 0.35, 0.9],
- [0.2, 1, 0.75],
- [0.4, 0.45, 1],
- [0.6, 1, 0.6],
- [0.8, 0.4, 1],
- [1, 0.35, 0.9],
-];
-
-const SELECTION_GAP = 6;
-const DRAFT_ID = 'draft';
-const TARGET_ID = 'click-target';
-
-const TOOLS: { id: EditorTool; icon: ComponentType<{ size?: number }>; labelKey: string }[] = [
- { id: 'select', icon: MousePointer2, labelKey: 'annotationEditor.toolSelect' },
- { id: 'crop', icon: Crop, labelKey: 'annotationEditor.toolCrop' },
- { id: 'box', icon: Square, labelKey: 'annotationEditor.toolBox' },
- { id: 'ellipse', icon: CircleIcon, labelKey: 'annotationEditor.toolEllipse' },
- { id: 'arrow', icon: ArrowUpRight, labelKey: 'annotationEditor.toolArrow' },
- { id: 'line', icon: Minus, labelKey: 'annotationEditor.toolLine' },
- { id: 'text', icon: Type, labelKey: 'annotationEditor.toolText' },
- { id: 'redact', icon: EyeOff, labelKey: 'annotationEditor.toolRedact' },
-];
-
-function modeForTool(tool: EditorTool): EditorMode {
- if (tool === 'crop') return 'crop';
- if (tool === 'redact') return 'redact';
- return 'annotate';
-}
-
-function cursorFor(mode: EditorMode, tool: EditorTool, hovering: boolean, grabbing: boolean): string {
- if (grabbing) return 'grabbing';
- if (mode !== 'annotate') return 'crosshair';
- if (hovering) return 'grab';
- if (tool === 'select') return 'default';
- if (tool === 'text') return 'text';
- return 'crosshair';
-}
-
-function handleCorners(b: ScreenshotBounds): [Handle, number, number][] {
- return [
- ['nw', b.x, b.y],
- ['ne', b.x + b.width, b.y],
- ['sw', b.x, b.y + b.height],
- ['se', b.x + b.width, b.y + b.height],
- ];
-}
-
-function selectionBounds(a: Annotation, scale: number): ScreenshotBounds {
- const inset = SELECTION_GAP * scale;
- const b = annotationBounds(a);
- return { x: b.x - inset, y: b.y - inset, width: b.width + inset * 2, height: b.height + inset * 2 };
-}
-
-function hitHandle(b: ScreenshotBounds, x: number, y: number, radius: number): Handle | null {
- for (const [handle, hx, hy] of handleCorners(b)) {
- if (Math.abs(x - hx) <= radius && Math.abs(y - hy) <= radius) return handle;
- }
- return null;
-}
-
-export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }: AnnotationEditorProps) {
- const [activeTool, setActiveTool] = useState<EditorTool>(
- tool === 'crop' ? 'crop' : tool === 'redact' ? 'redact' : 'box',
- );
- const [annotations, setAnnotations] = useState<Annotation[]>(() => {
- const existing = screenshot.edits?.annotations ?? [];
- const t = resolveTarget(screenshot);
- if (!t) return existing;
- return [
- ...existing,
- { id: TARGET_ID, type: 'target', x: t.x, y: t.y, w: t.width, h: t.height, color: t.color, border: t.border },
- ];
- });
- const [viewport, setViewport] = useState<ScreenshotBounds | undefined>(screenshot.edits?.viewport);
- const [selectedId, setSelectedId] = useState<string | null>(tool === 'target' ? TARGET_ID : null);
- const [color, setColor] = useState<string>(COLORS[0]);
- const [draft, setDraft] = useState<Annotation | null>(null);
- const [cropDraft, setCropDraft] = useState<ScreenshotBounds | null>(null);
- const [textEditor, setTextEditor] = useState<TextEditorState | null>(null);
- const [textValue, setTextValue] = useState('');
- const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
- const [saving, setSaving] = useState(false);
- const [hovering, setHovering] = useState(false);
- const [anchor, setAnchor] = useState<{ x: number; y: number } | null>(null);
- const [pulse, setPulse] = useState(0);
- const [defaultTargetColor, setDefaultTargetColor] = useState(DEFAULT_TARGET_COLOR);
- const [grabbing, setGrabbing] = useState(false);
-
- const [fill] = useState('transparent');
- const [lineWidth] = useState<LineWidth>('ms');
- const [radius] = useState(0);
- const [arrowEnd] = useState<ArrowEnd>('arrow-solid');
- const [fontFamily, setFontFamily] = useState<FontFamily>('sans-serif');
- const [bold, setBold] = useState(false);
- const [italic, setItalic] = useState(false);
- const [fontSize, setFontSize] = useState(DEFAULT_FONT_SIZE);
- const [lineHeight, setLineHeight] = useState(DEFAULT_LINE_HEIGHT);
- const [past, setPast] = useState<Annotation[][]>([]);
- const [future, setFuture] = useState<Annotation[][]>([]);
-
- const annotationsRef = useRef(annotations);
- annotationsRef.current = annotations;
-
- const pushHistory = useCallback(() => {
- setPast((p) => [...p.slice(-HISTORY_LIMIT), annotationsRef.current]);
- setFuture([]);
- }, []);
-
- const undo = () => {
- if (!past.length) return;
- setFuture((f) => [annotationsRef.current, ...f]);
- setAnnotations(past[past.length - 1]);
- setPast((p) => p.slice(0, -1));
- };
-
- const redo = () => {
- if (!future.length) return;
- setPast((p) => [...p, annotationsRef.current]);
- setAnnotations(future[0]);
- setFuture((f) => f.slice(1));
- };
-
- const mode = modeForTool(activeTool);
- const selected = annotations.find((a) => a.id === selectedId);
- const selectedTarget = selected?.type === 'target' ? selected : null;
- const hasTarget = annotations.some((a) => a.id === TARGET_ID);
-
- const addTarget = () => {
- pushHistory();
- const w = Math.min(screenshot.width * 0.25, 260);
- const h = Math.min(screenshot.height * 0.1, 90);
- setAnnotations((prev) => [
- ...prev,
- {
- id: TARGET_ID,
- type: 'target',
- x: (screenshot.width - w) / 2,
- y: (screenshot.height - h) / 2,
- w,
- h,
- color: defaultTargetColor,
- border: 'dashed',
- },
- ]);
- setActiveTool('select');
- setSelectedId(TARGET_ID);
- };
-
- const patchSelected = (patch: Record<string, unknown>) => {
- if (!selectedId || selectedId === TARGET_ID) return;
- pushHistory();
- setAnnotations((prev) => prev.map((a) => (a.id === selectedId ? ({ ...a, ...patch } as Annotation) : a)));
- };
-
- const updateTarget = (patch: { color?: string; border?: TargetBorder }) => {
- setAnnotations((prev) => prev.map((a) => (a.id === TARGET_ID && a.type === 'target' ? { ...a, ...patch } : a)));
- };
-
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const textInputRef = useRef<HTMLInputElement>(null);
- const dragRef = useRef<DragState | null>(null);
-
- const getScale = useCallback((): number => {
- const canvas = canvasRef.current;
- if (!canvas) return 1;
- const rect = canvas.getBoundingClientRect();
- return rect.width ? canvas.width / rect.width : 1;
- }, []);
-
- const toImageSpace = useCallback((e: { clientX: number; clientY: number }): { x: number; y: number } => {
- const canvas = canvasRef.current;
- if (!canvas) return { x: 0, y: 0 };
- const rect = canvas.getBoundingClientRect();
- const scaleX = rect.width ? canvas.width / rect.width : 1;
- const scaleY = rect.height ? canvas.height / rect.height : 1;
- return { x: (e.clientX - rect.left) * scaleX, y: (e.clientY - rect.top) * scaleY };
- }, []);
-
- useEffect(() => {
- let cancelled = false;
- let loaded: ImageBitmap | null = null;
- setBitmap(null);
- createImageBitmap(screenshot.blob).then((bmp) => {
- if (cancelled) {
- bmp.close();
- return;
- }
- loaded = bmp;
- setBitmap(bmp);
- });
- return () => {
- cancelled = true;
- loaded?.close();
- };
- }, [screenshot.blob]);
-
- useEffect(() => {
- const handler = (e: KeyboardEvent) => {
- const target = e.target as HTMLElement | null;
- if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return;
- if (e.key === 'Escape') {
- setSelectedId(null);
- } else if ((e.key === 'Delete' || e.key === 'Backspace') && selectedId) {
- e.preventDefault();
- pushHistory();
- setAnnotations((prev) => prev.filter((a) => a.id !== selectedId));
- setSelectedId(null);
- }
- };
- window.addEventListener('keydown', handler);
- return () => window.removeEventListener('keydown', handler);
- }, [selectedId, pushHistory]);
-
- useEffect(() => {
- const sel = annotationsRef.current.find((a) => a.id === selectedId);
- if (!sel) {
- setAnchor(null);
- return;
- }
- const b = annotationBounds(sel);
- setAnchor({ x: b.x + b.width / 2, y: b.y + b.height });
- }, [selectedId]);
-
- useEffect(() => {
- localStorage.get(['targetColor']).then((result) => {
- if (result.targetColor) setDefaultTargetColor(result.targetColor as string);
- });
- }, []);
-
- useEffect(() => {
- if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
- let raf = 0;
- const loop = (elapsed: number) => {
- setPulse((elapsed % PULSE_PERIOD_MS) / PULSE_PERIOD_MS);
- raf = requestAnimationFrame(loop);
- };
- raf = requestAnimationFrame(loop);
- return () => cancelAnimationFrame(raf);
- }, []);
-
- useEffect(() => {
- if (!textEditor) return;
- const id = requestAnimationFrame(() => textInputRef.current?.focus());
- return () => cancelAnimationFrame(id);
- }, [textEditor]);
-
- useLayoutEffect(() => {
- const canvas = canvasRef.current;
- const ctx = canvas?.getContext('2d');
- if (!canvas || !ctx || !bitmap) return;
-
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
-
- for (const a of annotations) {
- if (a.type === 'target') {
- const gradient = ctx.createConicGradient(pulse * Math.PI * 2, a.x + a.w / 2, a.y + a.h / 2);
- for (const [stop, v, s] of TARGET_SWEEP) gradient.addColorStop(stop, shadeOf(a.color, v, s));
- ctx.save();
- ctx.strokeStyle = gradient;
- ctx.lineWidth = TARGET_STROKE + 1;
- ctx.shadowColor = a.color;
- ctx.shadowBlur = 14;
- ctx.setLineDash(a.border === 'dashed' ? TARGET_DASH : TARGET_MARCH);
- ctx.lineDashOffset = -pulse * TARGET_MARCH_CYCLES * (a.border === 'dashed' ? DASH_PERIOD : MARCH_PERIOD);
- drawRoundedRect(ctx, a.x, a.y, a.w, a.h, TARGET_RADIUS);
- ctx.stroke();
- ctx.restore();
- continue;
- }
- drawAnnotation(ctx, a, 0, 0);
- }
- if (draft) {
- ctx.save();
- ctx.globalAlpha = 0.7;
- drawAnnotation(ctx, draft, 0, 0);
- ctx.restore();
- }
-
- const scale = getScale();
-
- if (mode === 'crop') {
- const frame = cropDraft ?? viewport ?? { x: 0, y: 0, width: canvas.width, height: canvas.height };
- ctx.save();
- ctx.fillStyle = 'rgba(30, 27, 75, 0.55)';
- ctx.beginPath();
- ctx.rect(0, 0, canvas.width, canvas.height);
- ctx.rect(frame.x, frame.y, frame.width, frame.height);
- ctx.fill('evenodd');
- ctx.strokeStyle = '#FFFFFF';
- ctx.lineWidth = 1 * scale;
- ctx.strokeRect(frame.x, frame.y, frame.width, frame.height);
-
- const arm = Math.min(BRACKET_ARM * scale, frame.width / 3, frame.height / 3);
- const thick = BRACKET_THICKNESS * scale;
- ctx.fillStyle = SELECTION_COLOR;
- ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
- ctx.shadowBlur = 4 * scale;
- for (const [handle, hx, hy] of handleCorners(frame)) {
- const left = handle === 'nw' || handle === 'sw';
- const top = handle === 'nw' || handle === 'ne';
- const x = left ? hx : hx - arm;
- const y = top ? hy : hy - arm;
- ctx.fillRect(x, top ? hy : hy - thick, arm, thick);
- ctx.fillRect(left ? hx : hx - thick, y, thick, arm);
- }
- ctx.restore();
- }
-
- const sel = annotations.find((a) => a.id === selectedId);
- if (sel) {
- const b = selectionBounds(sel, scale);
- ctx.save();
- ctx.strokeStyle = SELECTION_COLOR;
- ctx.lineWidth = 1.5 * scale;
- ctx.strokeRect(b.x, b.y, b.width, b.height);
- const handleSize = HANDLE_DISPLAY_SIZE * scale;
- ctx.fillStyle = SELECTION_COLOR;
- for (const [, hx, hy] of handleCorners(b)) {
- ctx.fillRect(hx - handleSize / 2, hy - handleSize / 2, handleSize, handleSize);
- }
- ctx.restore();
- }
- }, [annotations, draft, cropDraft, selectedId, bitmap, getScale, mode, viewport, pulse]);
-
- const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
- e.currentTarget.setPointerCapture(e.pointerId);
- const p = toImageSpace(e);
-
- if (mode === 'crop') {
- const scale = getScale();
- const frame = viewport ?? { x: 0, y: 0, width: screenshot.width, height: screenshot.height };
- const handle = hitHandle(frame, p.x, p.y, HANDLE_HIT_PX * scale);
- if (handle) {
- dragRef.current = { mode: 'cropResize', handle, rect: frame, lastX: p.x, lastY: p.y };
- setCropDraft(frame);
- return;
- }
- if (p.x > frame.x && p.x < frame.x + frame.width && p.y > frame.y && p.y < frame.y + frame.height) {
- dragRef.current = { mode: 'cropMove', rect: frame, lastX: p.x, lastY: p.y };
- setCropDraft(frame);
- return;
- }
- const rect: ScreenshotBounds = { x: p.x, y: p.y, width: 0, height: 0 };
- dragRef.current = { mode: 'crop', start: p, rect };
- setCropDraft(rect);
- return;
- }
-
- if (mode === 'redact') {
- const shape: Annotation = { id: DRAFT_ID, type: 'redact', x: p.x, y: p.y, w: 0, h: 0, style: 'blur' };
- dragRef.current = { mode: 'draw', start: p, shape };
- setDraft(shape);
- return;
- }
-
- const current = annotations.find((a) => a.id === selectedId);
- if (current) {
- const scale = getScale();
- const handle = hitHandle(selectionBounds(current, scale), p.x, p.y, HANDLE_HIT_PX * scale);
- if (handle) {
- pushHistory();
- dragRef.current = { mode: 'resize', id: current.id, handle, lastX: p.x, lastY: p.y };
- return;
- }
- }
-
- const hit = hitTest(annotations, p.x, p.y);
- if (hit) {
- pushHistory();
- setSelectedId(hit.id);
- dragRef.current = { mode: 'move', id: hit.id, lastX: p.x, lastY: p.y };
- setGrabbing(true);
- return;
- }
- setSelectedId(null);
-
- if (activeTool === 'select') return;
-
- if (activeTool === 'text') {
- e.preventDefault();
- const rect = canvasRef.current?.getBoundingClientRect();
- setTextEditor({
- x: p.x,
- y: p.y + fontSize,
- left: rect ? e.clientX - rect.left : 0,
- top: rect ? e.clientY - rect.top : 0,
- });
- setTextValue('');
- return;
- }
-
- let shape: Annotation;
- if (activeTool === 'ellipse') {
- shape = { id: DRAFT_ID, type: 'ellipse', x: p.x, y: p.y, w: 0, h: 0, color, fill, lineWidth };
- } else if (activeTool === 'arrow' || activeTool === 'line') {
- shape = {
- id: DRAFT_ID,
- type: 'arrow',
- x1: p.x,
- y1: p.y,
- x2: p.x,
- y2: p.y,
- color,
- lineWidth,
- end: activeTool === 'line' ? 'none' : arrowEnd,
- };
- } else {
- shape = { id: DRAFT_ID, type: 'box', x: p.x, y: p.y, w: 0, h: 0, color, fill, lineWidth, radius };
- }
- dragRef.current = { mode: 'draw', start: p, shape };
- setDraft(shape);
- };
-
- const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
- const drag = dragRef.current;
- if (!drag) {
- if (mode === 'annotate') {
- const p = toImageSpace(e);
- setHovering(Boolean(hitTest(annotations, p.x, p.y)));
- }
- return;
- }
- const p = toImageSpace(e);
-
- if (drag.mode === 'move' || drag.mode === 'resize') {
- const dx = p.x - drag.lastX;
- const dy = p.y - drag.lastY;
- drag.lastX = p.x;
- drag.lastY = p.y;
- const next = annotationsRef.current.map((a) => {
- if (a.id !== drag.id) return a;
- return drag.mode === 'move' ? moveAnnotation(a, dx, dy) : resizeAnnotation(a, drag.handle, dx, dy);
- });
- setAnnotations(next);
- const moved = next.find((a) => a.id === drag.id);
- if (moved) {
- const b = annotationBounds(moved);
- setAnchor({ x: b.x + b.width / 2, y: b.y + b.height });
- }
- return;
- }
-
- if (drag.mode === 'cropResize') {
- const dx = p.x - drag.lastX;
- const dy = p.y - drag.lastY;
- drag.lastX = p.x;
- drag.lastY = p.y;
- const left = drag.handle === 'nw' || drag.handle === 'sw';
- const top = drag.handle === 'nw' || drag.handle === 'ne';
- const r = drag.rect;
- const next: ScreenshotBounds = {
- x: left ? r.x + dx : r.x,
- y: top ? r.y + dy : r.y,
- width: Math.max(MIN_CROP_SIZE, left ? r.width - dx : r.width + dx),
- height: Math.max(MIN_CROP_SIZE, top ? r.height - dy : r.height + dy),
- };
- drag.rect = cropTo(next, { width: screenshot.width, height: screenshot.height });
- setCropDraft(drag.rect);
- return;
- }
-
- if (drag.mode === 'cropMove') {
- const dx = p.x - drag.lastX;
- const dy = p.y - drag.lastY;
- drag.lastX = p.x;
- drag.lastY = p.y;
- drag.rect = cropTo(
- { ...drag.rect, x: drag.rect.x + dx, y: drag.rect.y + dy },
- { width: screenshot.width, height: screenshot.height },
- );
- setCropDraft(drag.rect);
- return;
- }
-
- if (drag.mode === 'crop') {
- const rect: ScreenshotBounds = {
- x: Math.min(drag.start.x, p.x),
- y: Math.min(drag.start.y, p.y),
- width: Math.abs(p.x - drag.start.x),
- height: Math.abs(p.y - drag.start.y),
- };
- drag.rect = rect;
- setCropDraft(rect);
- return;
- }
-
- const shape = drag.shape;
- let next: Annotation = shape;
- if (shape.type === 'box' || shape.type === 'ellipse' || shape.type === 'redact') {
- next = {
- ...shape,
- x: Math.min(drag.start.x, p.x),
- y: Math.min(drag.start.y, p.y),
- w: Math.abs(p.x - drag.start.x),
- h: Math.abs(p.y - drag.start.y),
- };
- } else if (shape.type === 'arrow') {
- next = { ...shape, x2: p.x, y2: p.y };
- } else if (shape.type === 'freehand') {
- next = { ...shape, points: [...shape.points, p.x, p.y] };
- }
- drag.shape = next;
- setDraft(next);
- };
-
- const handlePointerUp = () => {
- setGrabbing(false);
- const settled = annotations.find((a) => a.id === selectedId);
- if (settled) {
- const b = annotationBounds(settled);
- setAnchor({ x: b.x + b.width / 2, y: b.y + b.height });
- }
- const drag = dragRef.current;
- dragRef.current = null;
- if (!drag) return;
-
- if (drag.mode === 'crop' || drag.mode === 'cropResize' || drag.mode === 'cropMove') {
- setCropDraft(null);
- const rect = drag.rect;
- if (rect.width < MIN_CROP_SIZE || rect.height < MIN_CROP_SIZE) return;
- setViewport(cropTo(rect, { width: screenshot.width, height: screenshot.height }));
- return;
- }
-
- if (drag.mode === 'draw') {
- setDraft(null);
- const shape = drag.shape;
- if (shape.type === 'freehand') {
- if (shape.points.length < 4) return;
- } else if (shape.type === 'box' || shape.type === 'ellipse' || shape.type === 'redact') {
- if (shape.w < MIN_SHAPE_SIZE || shape.h < MIN_SHAPE_SIZE) return;
- } else if (shape.type === 'arrow') {
- if (Math.hypot(shape.x2 - shape.x1, shape.y2 - shape.y1) < MIN_SHAPE_SIZE) return;
- }
- pushHistory();
- const id = crypto.randomUUID();
- setAnnotations((prev) => [...prev, { ...shape, id }]);
- setActiveTool('select');
- setSelectedId(id);
- }
- };
-
- const handlePointerCancel = () => {
- dragRef.current = null;
- setDraft(null);
- setCropDraft(null);
- };
-
- const setProp = (key: string, value: unknown) => {
- patchSelected({ [key]: value });
- };
-
- const setTextProp = (patch: {
- fontFamily?: FontFamily;
- bold?: boolean;
- italic?: boolean;
- size?: number;
- lineHeight?: number;
- }) => {
- if (patch.fontFamily) setFontFamily(patch.fontFamily);
- if (patch.bold !== undefined) setBold(patch.bold);
- if (patch.italic !== undefined) setItalic(patch.italic);
- if (patch.size !== undefined) setFontSize(patch.size);
- if (patch.lineHeight !== undefined) setLineHeight(patch.lineHeight);
- if (!selected || selected.type !== 'text') return;
- const next = {
- fontFamily: patch.fontFamily ?? selected.fontFamily ?? 'sans-serif',
- bold: patch.bold ?? selected.bold ?? false,
- italic: patch.italic ?? selected.italic ?? false,
- size: patch.size ?? selected.size,
- lineHeight: patch.lineHeight ?? selected.lineHeight ?? DEFAULT_LINE_HEIGHT,
- };
- patchSelected({ ...next, ...measureText(selected.text, next.size, next.fontFamily, next.bold, next.italic) });
- };
-
- const handleColorSelect = (c: string) => {
- setColor(c);
- if (!annotations.some((a) => a.id === selectedId && a.type !== 'redact')) return;
- pushHistory();
- setAnnotations((prev) => prev.map((a) => (a.id === selectedId && a.type !== 'redact' ? { ...a, color: c } : a)));
- };
-
- const measureText = (value: string, px: number, family: FontFamily, isBold: boolean, isItalic: boolean) => {
- const ctx = canvasRef.current?.getContext('2d');
- if (!ctx) return { w: value.length * px * 0.6, h: px * 1.4 };
- ctx.save();
- ctx.font = `${isItalic ? 'italic ' : ''}${isBold ? 700 : 500} ${px}px ${FONT_FAMILIES[family]}`;
- const w = ctx.measureText(value).width;
- ctx.restore();
- return { w, h: px * 1.4 };
- };
-
- const commitText = () => {
- if (textEditor && textValue.trim()) {
- const id = crypto.randomUUID();
- pushHistory();
- setActiveTool('select');
- setSelectedId(id);
- setAnnotations((prev) => [
- ...prev,
- {
- id,
- type: 'text',
- x: textEditor.x,
- y: textEditor.y,
- text: textValue.trim(),
- color,
- size: fontSize,
- ...measureText(textValue.trim(), fontSize, fontFamily, bold, italic),
- fontFamily,
- bold,
- italic,
- lineHeight,
- },
- ]);
- }
- setTextEditor(null);
- setTextValue('');
- };
-
- const handleDone = async () => {
- setSaving(true);
- const targetAnnotation = annotations.find((a) => a.id === TARGET_ID);
- const nextTarget =
- targetAnnotation && targetAnnotation.type === 'target'
- ? {
- x: targetAnnotation.x,
- y: targetAnnotation.y,
- width: targetAnnotation.w,
- height: targetAnnotation.h,
- border: targetAnnotation.border,
- color: targetAnnotation.color,
- }
- : null;
- const nextEdits: ScreenshotEdits = {
- ...screenshot.edits,
- annotations: annotations.filter((a) => a.id !== TARGET_ID),
- target: nextTarget,
- };
- if (viewport) nextEdits.viewport = viewport;
- await updateScreenshotEdits(screenshot.id, nextEdits);
- onDone(nextEdits);
- };
-
- return (
- <TooltipProvider>
- <div className="fixed inset-0 z-50 bg-black/80 flex flex-col">
- <div className="shrink-0 bg-card border-b border-border px-3 h-[50px] flex items-center gap-3">
- <div className="flex-1 flex items-center gap-1">
- <Tip label={i18n.t('annotationEditor.undo')}>
- <button
- type="button"
- onClick={undo}
- disabled={past.length === 0}
- className="flex items-center justify-center w-8 h-8 rounded-lg text-foreground/75 hover:bg-secondary hover:text-foreground disabled:opacity-25"
- >
- <Undo2 size={15} />
- </button>
- </Tip>
- <Tip label={i18n.t('annotationEditor.redo')}>
- <button
- type="button"
- onClick={redo}
- disabled={future.length === 0}
- className="flex items-center justify-center w-8 h-8 rounded-lg text-foreground/75 hover:bg-secondary hover:text-foreground disabled:opacity-25"
- >
- <Redo2 size={15} />
- </button>
- </Tip>
- </div>
-
- <div className="flex items-center gap-0.5 rounded-xl bg-secondary p-1">
- {TOOLS.map(({ id, icon: Icon, labelKey }) => (
- <Tip key={id} label={i18n.t(labelKey)}>
- <button
- type="button"
- onClick={() => {
- setActiveTool(id);
- setSelectedId(null);
- }}
- aria-pressed={activeTool === id}
- className={`flex items-center justify-center w-9 h-8 rounded-lg transition-colors ${
- activeTool === id
- ? 'bg-primary text-primary-foreground'
- : 'text-foreground/75 hover:bg-card hover:text-foreground'
- }`}
- >
- <Icon size={16} />
- </button>
- </Tip>
- ))}
- {!hasTarget && (
- <>
- <span className="w-px h-5 bg-border mx-1.5" />
- <Tip label={i18n.t('annotationEditor.addTarget')}>
- <button
- type="button"
- onClick={addTarget}
- className="flex items-center justify-center w-9 h-8 rounded-lg text-foreground/75 hover:bg-card hover:text-foreground"
- >
- <MousePointerClick size={16} />
- </button>
- </Tip>
- </>
- )}
- </div>
-
- <div className="flex-1 flex items-center justify-end gap-1.5">
- {mode === 'crop' && viewport && (
- <button
- type="button"
- onClick={() => {
- setViewport(undefined);
- setCropDraft(null);
- }}
- className="flex items-center gap-1.5 px-2.5 h-8 rounded-lg text-[12px] font-semibold text-foreground/75 hover:bg-secondary"
- >
- <RotateCcw size={13} />
- {i18n.t('annotationEditor.resetCrop')}
- </button>
- )}
- <button
- type="button"
- onClick={onCancel}
- className="px-3 h-8 text-[12px] font-semibold text-foreground/75 rounded-lg hover:bg-secondary"
- >
- {i18n.t('common.cancel')}
- </button>
- <button
- type="button"
- onClick={handleDone}
- disabled={saving}
- className="px-4 h-8 text-[12px] font-bold text-primary-foreground bg-primary rounded-lg hover:bg-primary/90 disabled:opacity-50"
- >
- {i18n.t('annotationEditor.done')}
- </button>
- </div>
- </div>
- <div className="flex-1 flex overflow-hidden">
- <div className="flex-1 flex items-center justify-center overflow-auto p-6">
- <div className="relative inline-block">
- <canvas
- ref={canvasRef}
- width={screenshot.width}
- height={screenshot.height}
- className="block max-w-full max-h-[calc(100vh-98px)] rounded-lg shadow-2xl touch-none"
- style={{ cursor: cursorFor(mode, activeTool, hovering, grabbing) }}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerCancel={handlePointerCancel}
- />
- {textEditor && (
- <input
- ref={textInputRef}
- value={textValue}
- onChange={(e) => setTextValue(e.target.value)}
- onBlur={commitText}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- commitText();
- } else if (e.key === 'Escape') {
- e.preventDefault();
- setTextEditor(null);
- setTextValue('');
- }
- }}
- placeholder={i18n.t('annotationEditor.textPlaceholder')}
- className="absolute z-10 rounded-[2px] border-2 border-accent bg-transparent px-1 outline-none leading-tight"
- style={{
- left: textEditor.left,
- top: textEditor.top - fontSize / getScale(),
- color,
- fontFamily: FONT_FAMILIES[fontFamily],
- fontSize: `${fontSize / getScale()}px`,
- fontWeight: bold ? 700 : 500,
- fontStyle: italic ? 'italic' : 'normal',
- lineHeight,
- width: `${Math.max(i18n.t('annotationEditor.textPlaceholder').length + 1, textValue.length + 4)}ch`,
- }}
- />
- )}
- {selected && anchor && (
- <div
- className="absolute z-20 -translate-x-1/2 flex flex-col items-center gap-1.5"
- style={{
- left: `${((anchor?.x ?? 0) / screenshot.width) * 100}%`,
- top: `${((anchor?.y ?? 0) / screenshot.height) * 100}%`,
- }}
- >
- <div className="mt-2 flex items-center gap-1 rounded-xl bg-primary px-2 py-1.5 shadow-xl">
- {selected.type !== 'redact' && (
- <ColorPopover
- label={i18n.t('annotationEditor.lineColor')}
- value={selected.color}
- onChange={handleColorSelect}
- >
- <button
- type="button"
- className="w-6 h-6 rounded-full border-2 border-primary-foreground/25"
- style={{ backgroundColor: selected.color }}
- />
- </ColorPopover>
- )}
- {selectedTarget ? (
- <Tip label={i18n.t('annotationEditor.targetBorder')}>
- <button
- type="button"
- onClick={() =>
- updateTarget({ border: selectedTarget.border === 'dashed' ? 'solid' : 'dashed' })
- }
- className="w-6 h-6 flex items-center justify-center rounded-md text-primary-foreground hover:bg-primary-foreground/15"
- >
- {selectedTarget.border === 'dashed' ? <SquareDashed size={14} /> : <Square size={14} />}
- </button>
- </Tip>
- ) : (
- <Tip label={i18n.t('annotationEditor.duplicate')}>
- <button
- type="button"
- onClick={() => {
- pushHistory();
- const copy = { ...moveAnnotation(selected, 24, 24), id: crypto.randomUUID() };
- setAnnotations((prev) => [...prev, copy]);
- setSelectedId(copy.id);
- }}
- className="w-6 h-6 flex items-center justify-center rounded-md text-primary-foreground hover:bg-primary-foreground/15"
- >
- <CopyPlus size={14} />
- </button>
- </Tip>
- )}
- {(selected.type === 'box' || selected.type === 'ellipse') && (
- <ColorPopover
- label={i18n.t('annotationEditor.fillColor')}
- allowNone
- value={selected.fill ?? 'transparent'}
- onChange={(c) => setProp('fill', c)}
- >
- <button
- type="button"
- className="w-6 h-6 flex items-center justify-center rounded-md hover:bg-primary-foreground/15"
- >
- <span
- className="w-4 h-4 rounded-[3px] border border-primary-foreground/35"
- style={swatchStyle(selected.fill)}
- />
- </button>
- </ColorPopover>
- )}
- {selected.type !== 'text' && selected.type !== 'redact' && selected.type !== 'target' && (
- <MenuPopover
- label={i18n.t('annotationEditor.lineWidth')}
- items={LINE_WIDTH_ORDER.map((w) => (
- <DropdownMenuItem key={w} onSelect={() => setProp('lineWidth', w)}>
- <span
- className={`w-16 rounded-full ${LINE_WIDTHS[w] ? 'bg-foreground' : 'bg-foreground/20'}`}
- style={{ height: LINE_WIDTHS[w] || 2 }}
- />
- </DropdownMenuItem>
- ))}
- >
- <button type="button" className={TOOLBAR_TRIGGER}>
- <span
- className={`w-7 rounded-full ${
- LINE_WIDTHS[selected.lineWidth ?? 'ms']
- ? 'bg-primary-foreground'
- : 'bg-primary-foreground/25'
- }`}
- style={{ height: LINE_WIDTHS[selected.lineWidth ?? 'ms'] || 2 }}
- />
- <ChevronDown size={10} className="opacity-60" />
- </button>
- </MenuPopover>
- )}
- {selected.type === 'box' && (
- <Stepper
- label={i18n.t('annotationEditor.cornerRadius')}
- value={Math.round(selected.radius ?? 0)}
- min={0}
- max={60}
- step={4}
- width="w-6"
- onChange={(v) => setProp('radius', v)}
- />
- )}
- {selected.type === 'arrow' && (
- <MenuPopover
- label={i18n.t('annotationEditor.arrowEnd')}
- items={ARROW_ENDS.map((end) => (
- <DropdownMenuItem key={end} onSelect={() => setProp('end', end)}>
- <ArrowEndGlyph end={end} />
- </DropdownMenuItem>
- ))}
- >
- <button type="button" className={TOOLBAR_TRIGGER}>
- <ArrowEndGlyph end={selected.end ?? 'arrow-solid'} />
- <ChevronDown size={10} className="opacity-60" />
- </button>
- </MenuPopover>
- )}
- {selected.type === 'text' && (
- <>
- <DropdownMenu>
- <Tooltip>
- <TooltipTrigger asChild>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- aria-label={i18n.t('annotationEditor.font')}
- className="flex items-center gap-1.5 h-6 rounded-md bg-primary-foreground/10 px-2 text-[11px] text-primary-foreground hover:bg-primary-foreground/20"
- style={{ fontFamily: FONT_FAMILIES[selected.fontFamily ?? 'sans-serif'] }}
- >
- <span className="text-[13px] leading-none">Ag</span>
- <ChevronDown size={10} className="opacity-60" />
- </button>
- </DropdownMenuTrigger>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('annotationEditor.font')}</TooltipContent>
- </Tooltip>
- <DropdownMenuContent align="start" className="min-w-[150px]">
- {FONT_FAMILY_ORDER.map((f) => (
- <DropdownMenuItem
- key={f}
- onSelect={() => setTextProp({ fontFamily: f })}
- style={{ fontFamily: FONT_FAMILIES[f] }}
- >
- <span className="text-[15px]">Ag</span>
- <span className="text-[12px] text-muted-foreground">{f}</span>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <div className="flex items-center gap-0.5 rounded-md bg-primary-foreground/10 p-0.5">
- <Tip label={i18n.t('annotationEditor.bold')}>
- <button
- type="button"
- onClick={() => setTextProp({ bold: !selected.bold })}
- className={`w-5 h-5 rounded text-[12px] font-extrabold ${selected.bold ? 'bg-accent text-primary-foreground' : 'text-primary-foreground hover:bg-primary-foreground/15'}`}
- >
- B
- </button>
- </Tip>
- <Tip label={i18n.t('annotationEditor.italic')}>
- <button
- type="button"
- onClick={() => setTextProp({ italic: !selected.italic })}
- className={`w-5 h-5 rounded text-[12px] italic font-serif ${selected.italic ? 'bg-accent text-primary-foreground' : 'text-primary-foreground hover:bg-primary-foreground/15'}`}
- >
- I
- </button>
- </Tip>
- </div>
- <Stepper
- label={i18n.t('annotationEditor.fontSize')}
- prefix={<span className="text-[9px] text-primary-foreground/60">A</span>}
- suffix={<span className="text-[13px] text-primary-foreground/60">A</span>}
- value={Math.round(selected.size)}
- min={MIN_FONT_SIZE}
- max={MAX_FONT_SIZE}
- step={2}
- width="w-7"
- onChange={(v) => setTextProp({ size: v })}
- />
- <Stepper
- label={i18n.t('annotationEditor.lineHeight')}
- prefix={<MoveVertical size={11} className="text-primary-foreground/60" />}
- value={selected.lineHeight ?? DEFAULT_LINE_HEIGHT}
- min={MIN_LINE_HEIGHT}
- max={MAX_LINE_HEIGHT}
- step={0.1}
- decimals={1}
- width="w-7"
- onChange={(v) => setTextProp({ lineHeight: v })}
- />
- </>
- )}
- <Tip label={i18n.t('common.delete')}>
- <button
- type="button"
- onClick={() => {
- pushHistory();
- setAnnotations((prev) => prev.filter((a) => a.id !== selected.id));
- setSelectedId(null);
- }}
- className="w-6 h-6 flex items-center justify-center rounded-md text-primary-foreground hover:bg-destructive/25"
- >
- <Trash2 size={14} />
- </button>
- </Tip>
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- </div>
- </TooltipProvider>
- );
-}
diff --git a/src/ui/shared/AskAi.tsx b/src/ui/shared/AskAi.tsx
deleted file mode 100644
index e6b227c..0000000
--- a/src/ui/shared/AskAi.tsx
+++ /dev/null
@@ -1,250 +0,0 @@
-import { Loader2, Sparkles, Wand2 } from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
-import { createPortal } from 'react-dom';
-import { i18n } from '#imports';
-import { REWRITE_PRESETS, type RewritePreset } from '@/core/capture/ai/prompts';
-import { sendMessage } from '@/lib/messaging';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import { rewriteErrorMessage } from '@/ui/shared/rewrite-error';
-import Toast from '@/ui/shared/Toast';
-
-const PRESET_LABEL_KEYS = {
- shorter: 'editor.rewriteShorter',
- detail: 'editor.rewriteDetail',
- grammar: 'editor.rewriteGrammar',
- formal: 'editor.rewriteFormal',
- casual: 'editor.rewriteCasual',
-} as const satisfies Record<RewritePreset, string>;
-
-const PRESET_ORDER = Object.keys(PRESET_LABEL_KEYS) as RewritePreset[];
-
-const PANEL_WIDTH = 320;
-const PANEL_GAP = 6;
-const VIEWPORT_MARGIN = 8;
-
-interface Span {
- start: number;
- end: number;
- lead: string;
- core: string;
- trail: string;
-}
-
-function readSpan(value: string, start: number, end: number): Span | null {
- const raw = value.slice(start, end);
- const core = raw.trim();
- if (!core) return null;
- const lead = raw.slice(0, raw.indexOf(core[0]));
- return { start, end, lead, core, trail: raw.slice(lead.length + core.length) };
-}
-
-export function useAskAi(value: string, onReplace: (next: string) => void, enabled = true) {
- const [span, setSpan] = useState<Span | null>(null);
- const [active, setActive] = useState<Span | null>(null);
- const [anchor, setAnchor] = useState<{ top: number; left: number } | null>(null);
- const [instruction, setInstruction] = useState('');
- const [busy, setBusy] = useState(false);
- const [result, setResult] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const triggerRef = useRef<HTMLButtonElement>(null);
- const panelRef = useRef<HTMLDivElement>(null);
- const inputRef = useRef<HTMLInputElement>(null);
-
- const reset = useCallback(() => {
- setActive(null);
- setInstruction('');
- setResult(null);
- }, []);
-
- const place = useCallback(() => {
- const rect = triggerRef.current?.getBoundingClientRect();
- if (!rect) return;
- const maxLeft = window.innerWidth - PANEL_WIDTH - VIEWPORT_MARGIN;
- setAnchor({
- top: rect.bottom + PANEL_GAP,
- left: Math.min(Math.max(VIEWPORT_MARGIN, rect.left), Math.max(VIEWPORT_MARGIN, maxLeft)),
- });
- }, []);
-
- useEffect(() => {
- if (!active) return;
- place();
- const reposition = () => place();
- window.addEventListener('scroll', reposition, true);
- window.addEventListener('resize', reposition);
- return () => {
- window.removeEventListener('scroll', reposition, true);
- window.removeEventListener('resize', reposition);
- };
- }, [active, place]);
-
- useEffect(() => {
- if (!active) return;
- const onPointerDown = (e: MouseEvent) => {
- const target = e.target as Node;
- if (panelRef.current?.contains(target) || triggerRef.current?.contains(target)) return;
- reset();
- };
- const onKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape') reset();
- };
- document.addEventListener('mousedown', onPointerDown);
- document.addEventListener('keydown', onKeyDown);
- return () => {
- document.removeEventListener('mousedown', onPointerDown);
- document.removeEventListener('keydown', onKeyDown);
- };
- }, [active, reset]);
-
- useEffect(() => {
- if (active && result === null) inputRef.current?.focus();
- }, [active, result]);
-
- const onSelect = useCallback((e: React.SyntheticEvent<HTMLTextAreaElement>) => {
- const el = e.currentTarget;
- setSpan(readSpan(el.value, el.selectionStart, el.selectionEnd));
- }, []);
-
- const open = useCallback(() => {
- if (!value.trim()) return;
- const target = span ?? readSpan(value, 0, value.length);
- if (!target) return;
- setResult(null);
- setInstruction('');
- setActive(target);
- }, [span, value]);
-
- const run = useCallback(
- async (target: Span, prompt: string) => {
- if (!prompt.trim() || busy) return;
- setBusy(true);
- setError(null);
- try {
- const response = await sendMessage('rewriteSelection', { text: target.core, instruction: prompt });
- if (response.error) {
- setError(rewriteErrorMessage(response.error));
- return;
- }
- if (response.text) setResult(response.text);
- } catch {
- setError(rewriteErrorMessage('generation-failed'));
- } finally {
- setBusy(false);
- }
- },
- [busy],
- );
-
- const replace = useCallback(() => {
- if (!active || !result) return;
- if (value.slice(active.start, active.end) !== active.lead + active.core + active.trail) {
- setError(i18n.t('editor.rewriteErrorStale'));
- reset();
- return;
- }
- onReplace(value.slice(0, active.start) + active.lead + result + active.trail + value.slice(active.end));
- setSpan(null);
- reset();
- }, [active, result, value, onReplace, reset]);
-
- const panel =
- active && anchor
- ? createPortal(
- <div
- ref={panelRef}
- style={{ top: anchor.top, left: anchor.left, width: PANEL_WIDTH }}
- className="fixed z-[2147483000] rounded-lg border border-border bg-card shadow-lg overflow-hidden"
- >
- <p className="px-2.5 pt-2 pb-1.5 text-[11px] leading-snug text-muted-foreground border-b border-border line-clamp-2">
- {active.core}
- </p>
- {result === null ? (
- <>
- <div className="flex items-center gap-1.5 px-2 py-1.5 border-b border-border">
- <Sparkles size={12} className="shrink-0 text-accent" />
- <input
- ref={inputRef}
- value={instruction}
- disabled={busy}
- onChange={(e) => setInstruction(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- void run(active, instruction);
- }
- }}
- placeholder={i18n.t('editor.rewritePlaceholder')}
- className="flex-1 min-w-0 bg-transparent p-0 text-[12px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none disabled:opacity-50"
- />
- {busy ? (
- <Loader2 size={12} className="shrink-0 animate-spin text-accent" />
- ) : (
- <span className="shrink-0 text-[10px] text-muted-foreground">{i18n.t('editor.rewriteEnter')}</span>
- )}
- </div>
- <div className="py-1">
- {PRESET_ORDER.map((preset) => (
- <button
- key={preset}
- type="button"
- disabled={busy}
- onClick={() => void run(active, REWRITE_PRESETS[preset])}
- className="w-full px-2.5 py-1.5 text-left text-[12px] text-foreground hover:bg-secondary disabled:opacity-50"
- >
- {i18n.t(PRESET_LABEL_KEYS[preset])}
- </button>
- ))}
- </div>
- </>
- ) : (
- <>
- <p className="px-2.5 py-2 text-[12px] leading-snug text-foreground whitespace-pre-wrap border-b border-border">
- {result}
- </p>
- <div className="flex items-center gap-1 px-2 py-1.5">
- <button
- type="button"
- onClick={replace}
- className="rounded-md bg-accent px-2 py-1 text-[11px] font-medium text-primary-foreground hover:bg-deep"
- >
- {i18n.t('editor.rewriteReplace')}
- </button>
- <button
- type="button"
- onClick={reset}
- className="rounded-md px-2 py-1 text-[11px] font-medium text-muted-foreground hover:bg-secondary"
- >
- {i18n.t('editor.rewriteDiscard')}
- </button>
- </div>
- </>
- )}
- </div>,
- document.body,
- )
- : null;
-
- const trigger = !enabled ? null : (
- <>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- ref={triggerRef}
- type="button"
- onClick={open}
- aria-disabled={!value.trim()}
- aria-label={i18n.t('editor.rewriteAskAi')}
- className={`p-1 rounded-md transition-colors aria-disabled:opacity-40 aria-disabled:cursor-not-allowed ${active ? 'text-accent' : 'text-border hover:text-accent'}`}
- >
- <Wand2 size={14} />
- </button>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('editor.rewriteAskAi')}</TooltipContent>
- </Tooltip>
- {panel}
- <Toast message={error} onDismiss={() => setError(null)} />
- </>
- );
-
- return { onSelect, trigger };
-}
diff --git a/src/ui/shared/BlockCard.tsx b/src/ui/shared/BlockCard.tsx
deleted file mode 100644
index 131439a..0000000
--- a/src/ui/shared/BlockCard.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-import { Trash2 } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { i18n } from '#imports';
-import { CALLOUT_VARIANTS, calloutAccent, DEFAULT_CALLOUT_COLOR, tint, variantLabel } from '@/core/guides/blocks';
-import { updateCallout } from '@/core/guides/service';
-import type { CalloutVariant, Step } from '@/core/guides/types';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import ConfirmDialog from '@/ui/shared/ConfirmDialog';
-import { DragGrip, type DragHandleProps, useCardDrag } from '@/ui/shared/card-drag';
-
-interface BlockCardProps {
- step: Step;
- onDescriptionChange?: (stepId: string, description: string) => void;
- onDelete?: (stepId: string) => void;
- onChanged?: () => void;
- dragHandleProps?: DragHandleProps;
- readOnly?: boolean;
-}
-
-export default function BlockCard({
- step,
- onDescriptionChange,
- onDelete,
- onChanged,
- dragHandleProps,
- readOnly,
-}: BlockCardProps) {
- const [description, setDescription] = useState(step.description);
- const [confirmDelete, setConfirmDelete] = useState(false);
-
- useEffect(() => {
- setDescription(step.description);
- }, [step.description]);
-
- const cardDrag = useCardDrag(dragHandleProps);
- const isHeading = step.blockType === 'heading';
- const accent = calloutAccent(step);
- const variant = step.calloutVariant ?? 'info';
-
- const pickVariant = async (next: CalloutVariant) => {
- await updateCallout(step.id, next, next === 'custom' ? (step.calloutColor ?? DEFAULT_CALLOUT_COLOR) : undefined);
- onChanged?.();
- };
-
- const pickColor = async (color: string) => {
- await updateCallout(step.id, 'custom', color);
- onChanged?.();
- };
-
- const textClass = isHeading
- ? 'text-[15px] font-bold leading-tight text-foreground'
- : 'text-[13px] font-medium leading-snug text-foreground';
-
- return (
- <div
- {...cardDrag}
- onDragOver={(e) => {
- e.preventDefault();
- dragHandleProps?.onDragOver(e);
- }}
- onDragEnd={dragHandleProps?.onDragEnd}
- className="mb-3"
- >
- <div
- className={isHeading ? 'border-b border-foreground pb-1.5' : 'rounded-lg px-3 py-2.5 border-l-[3px]'}
- style={isHeading ? undefined : { borderLeftColor: accent, background: tint(accent) }}
- >
- {readOnly ? (
- <p className={`${textClass} whitespace-pre-wrap`}>{step.description}</p>
- ) : (
- <textarea
- className={`${textClass} w-full resize-none outline-none border-0 bg-transparent p-0`}
- value={description}
- rows={1}
- ref={(el) => {
- if (el) {
- el.style.height = '0';
- el.style.height = `${el.scrollHeight}px`;
- }
- }}
- onChange={(e) => {
- setDescription(e.target.value);
- e.target.style.height = '0';
- e.target.style.height = `${e.target.scrollHeight}px`;
- }}
- onBlur={() => {
- if (description !== step.description) onDescriptionChange?.(step.id, description);
- }}
- placeholder={isHeading ? i18n.t('blocks.headingPlaceholder') : i18n.t('blocks.calloutPlaceholder')}
- />
- )}
- </div>
- {!readOnly && (
- <div className="flex items-center gap-1 mt-1">
- {dragHandleProps && <DragGrip />}
- {!isHeading &&
- CALLOUT_VARIANTS.map((option) => (
- <Tooltip key={option}>
- <TooltipTrigger asChild>
- <button
- type="button"
- onClick={() => pickVariant(option)}
- aria-label={variantLabel(option)}
- aria-pressed={variant === option}
- className={`w-3.5 h-3.5 rounded-full border ${variant === option ? 'border-foreground' : 'border-border'}`}
- style={{
- background:
- option === 'custom' && variant !== 'custom'
- ? 'linear-gradient(135deg,#DC2626,#4F46E5,#059669)'
- : calloutAccent({ ...step, calloutVariant: option }),
- }}
- />
- </TooltipTrigger>
- <TooltipContent>{variantLabel(option)}</TooltipContent>
- </Tooltip>
- ))}
- {!isHeading && variant === 'custom' && (
- <Tooltip>
- <TooltipTrigger asChild>
- <input
- type="color"
- value={accent}
- onChange={(e) => pickColor(e.target.value)}
- aria-label={variantLabel('custom')}
- className="w-5 h-4 bg-transparent border-0 p-0 cursor-pointer"
- />
- </TooltipTrigger>
- <TooltipContent>{variantLabel('custom')}</TooltipContent>
- </Tooltip>
- )}
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- type="button"
- onClick={() => setConfirmDelete(true)}
- aria-label={isHeading ? i18n.t('blocks.deleteHeading') : i18n.t('blocks.deleteCallout')}
- className="ml-auto p-1 rounded-md transition-colors text-border hover:text-destructive"
- >
- <Trash2 size={13} />
- </button>
- </TooltipTrigger>
- <TooltipContent>
- {isHeading ? i18n.t('blocks.deleteHeading') : i18n.t('blocks.deleteCallout')}
- </TooltipContent>
- </Tooltip>
- </div>
- )}
- <ConfirmDialog
- open={confirmDelete}
- heading={isHeading ? i18n.t('blocks.deleteHeading') : i18n.t('blocks.deleteCallout')}
- destructive
- onConfirm={() => {
- setConfirmDelete(false);
- onDelete?.(step.id);
- }}
- onCancel={() => setConfirmDelete(false)}
- />
- </div>
- );
-}
diff --git a/src/ui/shared/CaptureTabDialog.tsx b/src/ui/shared/CaptureTabDialog.tsx
deleted file mode 100644
index 100fe65..0000000
--- a/src/ui/shared/CaptureTabDialog.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { Globe } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { i18n } from '#imports';
-import { getRecordableTabs, type RecordableTab } from '@/capture/recordable-tabs';
-import { Button } from '@/ui/components/ui/button';
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/ui/components/ui/dialog';
-
-interface CaptureTabDialogProps {
- open: boolean;
- onCancel: () => void;
- onStart: (tabId: number) => void;
-}
-
-export default function CaptureTabDialog({ open, onCancel, onStart }: CaptureTabDialogProps) {
- const [tabs, setTabs] = useState<RecordableTab[]>([]);
- const [selected, setSelected] = useState<number | null>(null);
-
- useEffect(() => {
- if (!open) return;
- setSelected(null);
- getRecordableTabs().then(setTabs);
- }, [open]);
-
- return (
- <Dialog open={open} onOpenChange={(next) => !next && onCancel()}>
- <DialogContent className="sm:max-w-[400px]">
- <DialogHeader>
- <DialogTitle>{i18n.t('capture.moreStepsTitle')}</DialogTitle>
- <DialogDescription>{i18n.t('capture.moreStepsBody')}</DialogDescription>
- </DialogHeader>
- <div className="max-h-[240px] overflow-y-auto flex flex-col gap-1.5">
- {tabs.length === 0 ? (
- <p className="text-[13px] text-muted-foreground py-2">{i18n.t('capture.noRecordableTabs')}</p>
- ) : (
- tabs.map((tab) => (
- <button
- key={tab.id}
- type="button"
- onClick={() => setSelected(tab.id)}
- aria-pressed={selected === tab.id}
- className={`flex items-center gap-2 rounded-lg border px-2.5 py-2 text-left transition-colors ${
- selected === tab.id ? 'border-accent bg-secondary' : 'border-border hover:bg-secondary'
- }`}
- >
- {tab.favIconUrl ? (
- <img src={tab.favIconUrl} alt="" width={16} height={16} className="shrink-0 rounded" />
- ) : (
- <Globe size={16} className="shrink-0 text-muted-foreground" />
- )}
- <span className="text-[13px] text-foreground truncate">{tab.title}</span>
- </button>
- ))
- )}
- </div>
- <DialogFooter>
- <Button variant="outline" size="sm" onClick={onCancel}>
- {i18n.t('common.cancel')}
- </Button>
- <Button size="sm" disabled={selected === null} onClick={() => selected !== null && onStart(selected)}>
- {i18n.t('capture.startCapture')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/src/ui/shared/ColorPicker.tsx b/src/ui/shared/ColorPicker.tsx
deleted file mode 100644
index 150afff..0000000
--- a/src/ui/shared/ColorPicker.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { useRef, useState } from 'react';
-import { hexToHsv, hsvToHex, normalizeHex } from '@/core/screenshot/color';
-import { SHAPE_COLORS } from '@/core/screenshot/types';
-import { Input } from '@/ui/components/ui/input';
-
-export const NO_FILL_SWATCH = 'linear-gradient(45deg, #FFFFFF 44%, #EF4444 44%, #EF4444 56%, #FFFFFF 56%)';
-
-export function swatchStyle(color: string | undefined) {
- return !color || color === 'transparent' ? { backgroundImage: NO_FILL_SWATCH } : { backgroundColor: color };
-}
-
-interface ColorPickerProps {
- value: string;
- allowNone?: boolean;
- presets?: readonly string[];
- onChange: (color: string) => void;
-}
-
-export default function ColorPicker({ value, allowNone, presets = SHAPE_COLORS, onChange }: ColorPickerProps) {
- const [draft, setDraft] = useState(value);
- const areaRef = useRef<HTMLDivElement>(null);
- const hueRef = useRef<HTMLDivElement>(null);
-
- const hsv = hexToHsv(normalizeHex(value) ?? '#000000');
- const hueHex = hsvToHex({ h: hsv.h, s: 1, v: 1 });
-
- const track = (
- ref: React.RefObject<HTMLDivElement | null>,
- e: React.PointerEvent,
- read: (fx: number, fy: number) => void,
- ) => {
- const el = ref.current;
- if (!el) return;
- el.setPointerCapture(e.pointerId);
- const apply = (clientX: number, clientY: number) => {
- const r = el.getBoundingClientRect();
- read(
- Math.max(0, Math.min(1, (clientX - r.left) / r.width)),
- Math.max(0, Math.min(1, (clientY - r.top) / r.height)),
- );
- };
- apply(e.clientX, e.clientY);
- const move = (ev: PointerEvent) => apply(ev.clientX, ev.clientY);
- const up = () => {
- el.removeEventListener('pointermove', move);
- el.removeEventListener('pointerup', up);
- };
- el.addEventListener('pointermove', move);
- el.addEventListener('pointerup', up);
- };
-
- const commit = (next: string) => {
- setDraft(next);
- onChange(next);
- };
-
- return (
- <div className="flex flex-col gap-2.5">
- <div
- ref={areaRef}
- onPointerDown={(e) => track(areaRef, e, (fx, fy) => commit(hsvToHex({ h: hsv.h, s: fx, v: 1 - fy })))}
- className="relative h-32 w-full rounded-lg cursor-crosshair touch-none"
- style={{
- backgroundImage: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #FFF, ${hueHex})`,
- }}
- >
- <span
- className="absolute w-3.5 h-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow"
- style={{ left: `${hsv.s * 100}%`, top: `${(1 - hsv.v) * 100}%`, backgroundColor: value }}
- />
- </div>
-
- <div
- ref={hueRef}
- onPointerDown={(e) => track(hueRef, e, (fx) => commit(hsvToHex({ h: fx * 360, s: hsv.s || 1, v: hsv.v || 1 })))}
- className="relative h-3.5 w-full rounded-full cursor-ew-resize touch-none"
- style={{
- backgroundImage:
- 'linear-gradient(to right, #F00 0%, #FF0 17%, #0F0 33%, #0FF 50%, #00F 67%, #F0F 83%, #F00 100%)',
- }}
- >
- <span
- className="absolute top-1/2 w-3.5 h-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow"
- style={{ left: `${(hsv.h / 360) * 100}%`, backgroundColor: hueHex }}
- />
- </div>
-
- <div className="flex flex-wrap gap-1.5">
- {(allowNone ? presets : presets.filter((c) => c !== 'transparent')).map((c) => (
- <button
- key={c}
- type="button"
- aria-label={c}
- onClick={() => commit(c)}
- className={`w-[18px] h-[18px] rounded-full border border-border transition-transform ${
- value === c ? 'ring-2 ring-accent ring-offset-1' : 'hover:scale-110'
- }`}
- style={swatchStyle(c)}
- />
- ))}
- </div>
-
- <Input
- value={draft}
- onChange={(e) => {
- setDraft(e.target.value);
- const norm = normalizeHex(e.target.value);
- if (norm) onChange(norm);
- }}
- onBlur={() => setDraft(value)}
- spellCheck={false}
- className="h-7 w-full text-[11px] uppercase"
- />
- </div>
- );
-}
diff --git a/src/ui/shared/ConfirmDialog.tsx b/src/ui/shared/ConfirmDialog.tsx
deleted file mode 100644
index 6460278..0000000
--- a/src/ui/shared/ConfirmDialog.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { i18n } from '#imports';
-import { Button } from '@/ui/components/ui/button';
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/ui/components/ui/dialog';
-
-interface ConfirmDialogProps {
- open: boolean;
- heading: string;
- description?: string;
- confirmLabel?: string;
- destructive?: boolean;
- onConfirm: () => void;
- onCancel: () => void;
-}
-
-export default function ConfirmDialog({
- open,
- heading,
- description,
- confirmLabel,
- destructive = false,
- onConfirm,
- onCancel,
-}: ConfirmDialogProps) {
- return (
- <Dialog open={open} onOpenChange={(next) => !next && onCancel()}>
- <DialogContent className="sm:max-w-[360px]">
- <DialogHeader>
- <DialogTitle>{heading}</DialogTitle>
- {description && <DialogDescription>{description}</DialogDescription>}
- </DialogHeader>
- <DialogFooter>
- <Button variant="outline" size="sm" onClick={onCancel}>
- {i18n.t('common.cancel')}
- </Button>
- <Button variant={destructive ? 'destructive' : 'default'} size="sm" onClick={onConfirm}>
- {confirmLabel ?? i18n.t('common.delete')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/src/ui/shared/EmptyGuideState.tsx b/src/ui/shared/EmptyGuideState.tsx
deleted file mode 100644
index 7bed19f..0000000
--- a/src/ui/shared/EmptyGuideState.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { i18n } from '#imports';
-
-export default function EmptyGuideState() {
- return (
- <div className="flex flex-col items-center justify-center flex-1 min-h-[300px]">
- <div className="relative">
- <svg width="72" height="54" viewBox="20 50 160 120" className="block">
- <rect x="30" y="95" width="140" height="68" rx="5" className="fill-primary" />
- <path d="M30 95 L30 80 Q30 60, 100 60 Q170 60, 170 80 L170 95 Z" className="fill-violet-mid" />
- <rect x="30" y="93" width="140" height="3" className="fill-lavender" />
- <line x1="66" y1="120" x2="86" y2="120" className="stroke-lavender" strokeWidth="4" strokeLinecap="round" />
- <line x1="114" y1="120" x2="134" y2="120" className="stroke-lavender" strokeWidth="4" strokeLinecap="round" />
- <path
- d="M88 140 Q100 145 112 140"
- className="stroke-lavender"
- strokeWidth="3"
- fill="none"
- strokeLinecap="round"
- />
- </svg>
- <div className="absolute -top-2 -right-3 flex gap-0.5 text-muted-foreground/40">
- <span className="text-sm animate-pulse">z</span>
- <span className="text-xs animate-pulse [animation-delay:400ms]">z</span>
- <span className="text-[10px] animate-pulse [animation-delay:800ms]">z</span>
- </div>
- </div>
- <p className="text-sm font-medium text-foreground mt-5">{i18n.t('emptyGuide.title')}</p>
- <p className="text-xs text-muted-foreground mt-1">{i18n.t('emptyGuide.subtitle')}</p>
- </div>
- );
-}
diff --git a/src/ui/shared/FaviconImg.tsx b/src/ui/shared/FaviconImg.tsx
deleted file mode 100644
index 1f1a11e..0000000
--- a/src/ui/shared/FaviconImg.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useState } from 'react';
-import { getDomainInitial, getFaviconUrl } from '@/lib/utils';
-
-interface FaviconImgProps {
- domain: string;
- size?: number;
- className?: string;
-}
-
-export default function FaviconImg({ domain, size = 20, className = '' }: FaviconImgProps) {
- const [failed, setFailed] = useState(false);
- const src = domain ? getFaviconUrl(domain, size > 32 ? 64 : 32) : '';
-
- if (!domain || failed) {
- const { letter, gradient } = getDomainInitial(domain || '?');
- const fontSize = Math.max(Math.round(size * 0.55), 6);
- return (
- <span
- className={className}
- style={{
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'center',
- width: size,
- height: size,
- borderRadius: '50%',
- background: `linear-gradient(135deg, ${gradient[0]}, ${gradient[1]})`,
- color: '#fff',
- fontSize,
- fontWeight: 600,
- lineHeight: 1,
- flexShrink: 0,
- }}
- >
- {letter}
- </span>
- );
- }
-
- return (
- <img
- src={src}
- alt=""
- className={className}
- style={{ width: size, height: size, flexShrink: 0 }}
- onError={() => setFailed(true)}
- />
- );
-}
diff --git a/src/ui/shared/ImagePlaceholder.tsx b/src/ui/shared/ImagePlaceholder.tsx
deleted file mode 100644
index 82de863..0000000
--- a/src/ui/shared/ImagePlaceholder.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { ImageUp } from 'lucide-react';
-import { useState } from 'react';
-import { i18n } from '#imports';
-import MascotIcon from '@/ui/shared/MascotIcon';
-import ReplaceImageDialog from '@/ui/shared/ReplaceImageDialog';
-
-interface ImagePlaceholderProps {
- label: string;
- ratio?: number;
- className?: string;
- onUpload?: (file: File) => void | Promise<void>;
-}
-
-const DEFAULT_RATIO = 16 / 10;
-
-export default function ImagePlaceholder({
- label,
- ratio = DEFAULT_RATIO,
- className = '',
- onUpload,
-}: ImagePlaceholderProps) {
- const [uploadOpen, setUploadOpen] = useState(false);
-
- return (
- <div
- className={`flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border bg-secondary/60 text-muted-foreground ${className}`}
- style={{ aspectRatio: ratio }}
- >
- <MascotIcon size={64} pose="lookaway" tone="muted" />
- <span className="text-[12px] font-semibold text-muted-foreground">{label}</span>
- {onUpload && (
- <>
- <button
- type="button"
- onClick={() => setUploadOpen(true)}
- className="flex items-center gap-1.5 h-7 px-2.5 rounded-md border border-border bg-card/90 text-[11px] font-semibold text-foreground transition-colors hover:bg-secondary hover:text-accent"
- >
- <ImageUp size={13} />
- {i18n.t('screenshotView.addImage')}
- </button>
- <ReplaceImageDialog
- open={uploadOpen}
- onSelect={(file) => {
- setUploadOpen(false);
- void onUpload(file);
- }}
- onCancel={() => setUploadOpen(false)}
- />
- </>
- )}
- </div>
- );
-}
diff --git a/src/ui/shared/InsertBlockMenu.tsx b/src/ui/shared/InsertBlockMenu.tsx
deleted file mode 100644
index e525be3..0000000
--- a/src/ui/shared/InsertBlockMenu.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { Circle, Heading, Plus, StickyNote } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import type { BlockType } from '@/core/guides/types';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-
-interface InsertBlockMenuProps {
- onInsert: (blockType: BlockType) => void;
- onRecord?: () => void;
-}
-
-export default function InsertBlockMenu({ onInsert, onRecord }: InsertBlockMenuProps) {
- const [open, setOpen] = useState(false);
- const rowRef = useRef<HTMLDivElement>(null);
- const triggerRef = useRef<HTMLButtonElement>(null);
-
- useEffect(() => {
- if (!open) return;
- const handlePointerDown = (e: MouseEvent) => {
- if (rowRef.current && !rowRef.current.contains(e.target as Node)) setOpen(false);
- };
- document.addEventListener('mousedown', handlePointerDown);
- return () => document.removeEventListener('mousedown', handlePointerDown);
- }, [open]);
-
- const choices = [
- { type: 'heading' as const, icon: Heading, label: i18n.t('blocks.heading') },
- { type: 'callout' as const, icon: StickyNote, label: i18n.t('blocks.callout') },
- ];
-
- return (
- <div
- ref={rowRef}
- onKeyDown={(e) => {
- if (e.key !== 'Escape' || !open) return;
- setOpen(false);
- triggerRef.current?.focus();
- }}
- className="group relative flex items-center justify-center gap-1 h-6 my-1"
- >
- <span aria-hidden="true" className="absolute inset-x-0 top-1/2 border-t border-dashed border-border" />
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- type="button"
- ref={triggerRef}
- onClick={() => setOpen((prev) => !prev)}
- aria-label={i18n.t('blocks.add')}
- aria-expanded={open}
- className={`relative flex items-center justify-center w-5 h-5 rounded-full border border-border bg-card transition-colors hover:text-accent hover:border-accent ${open ? 'text-accent border-accent' : 'text-purple'}`}
- >
- <Plus size={13} />
- </button>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('blocks.add')}</TooltipContent>
- </Tooltip>
- {open &&
- choices.map((choice) => (
- <button
- key={choice.type}
- type="button"
- onClick={() => {
- setOpen(false);
- onInsert(choice.type);
- }}
- className="relative flex items-center gap-1 rounded-full border border-border bg-card px-2 py-0.5 text-[11px] font-medium text-purple hover:text-accent hover:bg-secondary"
- >
- <choice.icon size={13} />
- {choice.label}
- </button>
- ))}
- {open && onRecord && (
- <button
- type="button"
- onClick={() => {
- setOpen(false);
- onRecord();
- }}
- className="relative flex items-center gap-1 rounded-full border border-border bg-card px-2 py-0.5 text-[11px] font-medium text-purple hover:text-accent hover:bg-secondary"
- >
- <Circle size={13} />
- {i18n.t('capture.recordSteps')}
- </button>
- )}
- </div>
- );
-}
diff --git a/src/ui/shared/MascotIcon.tsx b/src/ui/shared/MascotIcon.tsx
deleted file mode 100644
index 556179a..0000000
--- a/src/ui/shared/MascotIcon.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-interface MascotIconProps {
- size?: number;
- pose?: 'happy' | 'lookaway';
- tone?: 'brand' | 'muted';
-}
-
-export default function MascotIcon({ size = 22, pose = 'happy', tone = 'brand' }: MascotIconProps) {
- const muted = tone === 'muted';
- const body = muted ? 'fill-current opacity-55' : 'fill-primary';
- const crown = muted ? 'fill-current opacity-80' : 'fill-violet-mid';
- const seam = muted ? 'fill-current opacity-25' : 'fill-lavender';
- const feature = muted ? 'fill-card stroke-card' : 'fill-lavender stroke-lavender';
-
- return (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- viewBox="20 50 160 120"
- width={size}
- height={Math.round((size * 120) / 160)}
- className="block shrink-0"
- aria-hidden="true"
- >
- <defs>
- <clipPath id="mascot-crown-split">
- <path d="M30 95 L170 60 L170 95 Z" />
- </clipPath>
- </defs>
- <rect x="30" y="95" width="140" height="68" rx="5" className={body} />
- <path d="M30 95 L30 80 Q30 60, 100 60 Q170 60, 170 80 L170 95 Z" className={crown} />
- {!muted && (
- <path
- d="M30 95 L30 80 Q30 60, 100 60 Q170 60, 170 80 L170 95 Z"
- className="fill-accent"
- clipPath="url(#mascot-crown-split)"
- />
- )}
- <rect x="30" y="93" width="140" height="3" className={seam} />
-
- {pose === 'lookaway' ? (
- <>
- <circle cx="80" cy="124" r="5" className={feature} strokeWidth="0" />
- <circle cx="128" cy="124" r="5" className={feature} strokeWidth="0" />
- <path d="M86 141 Q100 136 116 141" className={feature} strokeWidth="3.5" fill="none" strokeLinecap="round" />
- </>
- ) : (
- <>
- <path d="M68 122 Q76 112 84 122" className={feature} strokeWidth="5" fill="none" strokeLinecap="round" />
- <path d="M116 122 Q124 112 132 122" className={feature} strokeWidth="5" fill="none" strokeLinecap="round" />
- <path d="M84 138 Q100 148 116 138" className={feature} strokeWidth="3.5" fill="none" strokeLinecap="round" />
- </>
- )}
- </svg>
- );
-}
diff --git a/src/ui/shared/MicrophonePicker.tsx b/src/ui/shared/MicrophonePicker.tsx
index af6f0a9..eef00b8 100644
--- a/src/ui/shared/MicrophonePicker.tsx
+++ b/src/ui/shared/MicrophonePicker.tsx
@@ -1,10 +1,10 @@
+import { i18n } from '@mimik/core/env';
+import { Button } from '@mimik/ui/components/ui/button';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@mimik/ui/components/ui/select';
import { Check, ChevronRight, Mic, MicOff, Square, TriangleAlert } from 'lucide-react';
import { useCallback, useEffect, useId, useRef, useState } from 'react';
-import { i18n } from '#imports';
import { getActiveTab } from '@/lib/browser-api';
import { openMicPermissionPage } from '@/lib/offscreen';
-import { Button } from '@/ui/components/ui/button';
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/ui/components/ui/select';
import {
isMicrophoneMissing,
type MicrophoneDevice,
diff --git a/src/ui/shared/ReplaceImageDialog.tsx b/src/ui/shared/ReplaceImageDialog.tsx
deleted file mode 100644
index 199de06..0000000
--- a/src/ui/shared/ReplaceImageDialog.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { ImageUp } from 'lucide-react';
-import { useRef, useState } from 'react';
-import { i18n } from '#imports';
-import { Button } from '@/ui/components/ui/button';
-import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog';
-
-interface ReplaceImageDialogProps {
- open: boolean;
- onSelect: (file: File) => void;
- onCancel: () => void;
-}
-
-export default function ReplaceImageDialog({ open, onSelect, onCancel }: ReplaceImageDialogProps) {
- const inputRef = useRef<HTMLInputElement>(null);
- const [dragging, setDragging] = useState(false);
-
- const take = (file: File | undefined) => {
- if (file?.type.startsWith('image/')) onSelect(file);
- };
-
- return (
- <Dialog open={open} onOpenChange={(next) => !next && onCancel()}>
- <DialogContent className="sm:max-w-[420px]">
- <DialogHeader>
- <DialogTitle>{i18n.t('screenshotView.replaceImage')}</DialogTitle>
- <DialogDescription>{i18n.t('screenshotView.replaceHint')}</DialogDescription>
- </DialogHeader>
- <button
- type="button"
- onClick={() => inputRef.current?.click()}
- onDragOver={(e) => {
- e.preventDefault();
- setDragging(true);
- }}
- onDragLeave={() => setDragging(false)}
- onDrop={(e) => {
- e.preventDefault();
- setDragging(false);
- take(e.dataTransfer.files?.[0]);
- }}
- className={`w-full flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed py-10 transition-colors ${
- dragging ? 'border-accent bg-secondary' : 'border-border hover:border-accent hover:bg-secondary/50'
- }`}
- >
- <ImageUp size={26} className="text-accent" />
- <span className="text-[13px] font-semibold text-foreground">{i18n.t('screenshotView.replaceDrop')}</span>
- <span className="text-[11px] text-muted-foreground">{i18n.t('screenshotView.replaceFormats')}</span>
- </button>
- <div className="flex justify-end">
- <Button variant="outline" size="sm" onClick={onCancel}>
- {i18n.t('common.cancel')}
- </Button>
- </div>
- <input
- ref={inputRef}
- type="file"
- accept="image/*"
- className="hidden"
- onChange={(e) => {
- const file = e.target.files?.[0];
- e.target.value = '';
- take(file);
- }}
- />
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/src/ui/shared/ScreenshotView.tsx b/src/ui/shared/ScreenshotView.tsx
deleted file mode 100644
index a999490..0000000
--- a/src/ui/shared/ScreenshotView.tsx
+++ /dev/null
@@ -1,495 +0,0 @@
-import { Download, ImageUp, Pencil, Trash2, ZoomIn, ZoomOut } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import { deleteScreenshot, replaceScreenshot, updateScreenshotEdits } from '@/core/guides/service';
-import type { Screenshot, ScreenshotBounds } from '@/core/guides/types';
-import { panBy, resolveViewport, zoomBy } from '@/core/screenshot/geometry';
-import { imageDimensions, renderScreenshot } from '@/core/screenshot/render';
-import type { ScreenshotEdits } from '@/core/screenshot/types';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
- DropdownMenuTrigger,
-} from '@/ui/components/ui/dropdown-menu';
-import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import ConfirmDialog from '@/ui/shared/ConfirmDialog';
-import ImagePlaceholder from '@/ui/shared/ImagePlaceholder';
-import ReplaceImageDialog from '@/ui/shared/ReplaceImageDialog';
-
-interface ScreenshotViewProps {
- screenshot: Screenshot;
- className?: string;
- alt?: string;
- animate?: boolean;
- crop?: boolean;
- frameRatio?: number;
- readOnly?: boolean;
- onOpenEditor?: (tool: 'annotate' | 'redact' | 'crop' | 'target') => void;
- onChanged?: () => void;
-}
-
-interface DragState {
- pointerId: number;
- startX: number;
- startY: number;
- startViewport: ScreenshotBounds;
- moved: boolean;
-}
-
-const SAVE_DEBOUNCE_MS = 400;
-const SAVED_MESSAGE_MS = 1500;
-const ZOOM_IN_FACTOR = 1.25;
-const ZOOM_OUT_FACTOR = 0.8;
-const VIEWPORT_EPSILON = 0.5;
-const FRAME_EASING = 'cubic-bezier(0.22, 1, 0.36, 1)';
-const FRAME_TRANSITION = `width 0.4s ${FRAME_EASING}, height 0.4s ${FRAME_EASING}, left 0.4s ${FRAME_EASING}, top 0.4s ${FRAME_EASING}`;
-const FRAME_RATIO_EPSILON = 0.01;
-
-function withFullViewport(screenshot: Screenshot): Screenshot {
- return {
- ...screenshot,
- edits: { ...screenshot.edits, viewport: { x: 0, y: 0, width: screenshot.width, height: screenshot.height } },
- };
-}
-
-export default function ScreenshotView({
- screenshot,
- className = '',
- alt = '',
- animate = false,
- crop = false,
- frameRatio,
- readOnly = false,
- onOpenEditor,
- onChanged,
-}: ScreenshotViewProps) {
- const [fullUrl, setFullUrl] = useState<string | null>(null);
- const [showViewport, setShowViewport] = useState(false);
- const [editsOverride, setEditsOverride] = useState<ScreenshotEdits | undefined>(undefined);
- const [screenshotOverride, setScreenshotOverride] = useState<Screenshot | null>(null);
- const [deleted, setDeleted] = useState(false);
- const [saved, setSaved] = useState(false);
- const [altDraft, setAltDraft] = useState('');
- const [confirmDelete, setConfirmDelete] = useState(false);
- const [replaceOpen, setReplaceOpen] = useState(false);
- const processedKeyRef = useRef<string | null>(null);
- const urlRef = useRef<string | null>(null);
- const propScreenshotRef = useRef(screenshot);
- const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const savedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const dragRef = useRef<DragState | null>(null);
-
- const baseScreenshot = screenshotOverride ?? screenshot;
- const effectiveEdits = editsOverride ?? screenshot.edits;
- const effectiveScreenshot: Screenshot = { ...baseScreenshot, edits: effectiveEdits };
-
- useEffect(() => {
- if (propScreenshotRef.current !== screenshot) {
- propScreenshotRef.current = screenshot;
- setEditsOverride(undefined);
- setScreenshotOverride(null);
- setDeleted(false);
- }
- }, [screenshot]);
-
- useEffect(() => {
- setAltDraft(effectiveEdits?.alt ?? '');
- }, [effectiveEdits?.alt]);
-
- const annotationsForRender = effectiveEdits?.annotations;
- const targetForRender = effectiveEdits?.target;
-
- useEffect(() => {
- if (!baseScreenshot.blob) return;
- const cacheKey = `${baseScreenshot.id}:${baseScreenshot.blob.size}:${JSON.stringify(annotationsForRender ?? null)}:${JSON.stringify(targetForRender ?? null)}`;
- if (processedKeyRef.current === cacheKey) return;
-
- let cancelled = false;
- const current: Screenshot = {
- ...baseScreenshot,
- edits: { annotations: annotationsForRender, target: targetForRender },
- };
-
- (async () => {
- const blob = await renderScreenshot(withFullViewport(current));
- const newUrl = URL.createObjectURL(blob);
-
- if (cancelled) {
- URL.revokeObjectURL(newUrl);
- return;
- }
-
- processedKeyRef.current = cacheKey;
- if (urlRef.current) URL.revokeObjectURL(urlRef.current);
- urlRef.current = newUrl;
- setShowViewport(false);
- setFullUrl(newUrl);
- })();
-
- return () => {
- cancelled = true;
- };
- }, [baseScreenshot, annotationsForRender, targetForRender]);
-
- useEffect(() => {
- if (!fullUrl || showViewport) return;
- if (!animate) {
- setShowViewport(true);
- return;
- }
- let id = requestAnimationFrame(() => {
- id = requestAnimationFrame(() => {
- setShowViewport(true);
- });
- });
- return () => cancelAnimationFrame(id);
- }, [fullUrl, showViewport, animate]);
-
- useEffect(() => {
- return () => {
- if (urlRef.current) URL.revokeObjectURL(urlRef.current);
- };
- }, []);
-
- useEffect(() => {
- return () => {
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
- if (savedTimerRef.current) clearTimeout(savedTimerRef.current);
- };
- }, []);
-
- const scheduleSave = (edits: ScreenshotEdits) => {
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
- saveTimerRef.current = setTimeout(() => {
- updateScreenshotEdits(baseScreenshot.id, edits).then(() => {
- setSaved(true);
- if (savedTimerRef.current) clearTimeout(savedTimerRef.current);
- savedTimerRef.current = setTimeout(() => setSaved(false), SAVED_MESSAGE_MS);
- });
- }, SAVE_DEBOUNCE_MS);
- };
-
- const handleZoom = (factor: number) => {
- const viewport = resolveViewport(effectiveScreenshot);
- const nextViewport = zoomBy(viewport, factor, baseScreenshot);
- const nextEdits: ScreenshotEdits = { ...effectiveEdits, viewport: nextViewport };
- setEditsOverride(nextEdits);
- scheduleSave(nextEdits);
- };
-
- const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
- if (readOnly || !crop) return;
- const viewport = resolveViewport(effectiveScreenshot);
- const zoomed =
- viewport.width < baseScreenshot.width - VIEWPORT_EPSILON ||
- viewport.height < baseScreenshot.height - VIEWPORT_EPSILON;
- if (!zoomed) return;
- e.currentTarget.setPointerCapture(e.pointerId);
- dragRef.current = {
- pointerId: e.pointerId,
- startX: e.clientX,
- startY: e.clientY,
- startViewport: viewport,
- moved: false,
- };
- };
-
- const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
- const drag = dragRef.current;
- if (!drag || drag.pointerId !== e.pointerId) return;
- const el = e.currentTarget;
- if (el.clientWidth === 0) return;
- drag.moved = true;
- const scale = drag.startViewport.width / el.clientWidth;
- const dx = (e.clientX - drag.startX) * scale;
- const dy = (e.clientY - drag.startY) * scale;
- const nextViewport = panBy(drag.startViewport, -dx, -dy, baseScreenshot);
- setEditsOverride({ ...effectiveEdits, viewport: nextViewport });
- };
-
- const handlePointerEnd = (e: React.PointerEvent<HTMLDivElement>) => {
- const drag = dragRef.current;
- if (!drag || drag.pointerId !== e.pointerId) return;
- dragRef.current = null;
- if (drag.moved) scheduleSave(effectiveEdits ?? {});
- };
-
- const handleAltChange = (value: string) => {
- setAltDraft(value);
- const nextEdits: ScreenshotEdits = { ...effectiveEdits, alt: value };
- setEditsOverride(nextEdits);
- scheduleSave(nextEdits);
- };
-
- const handleReplaceFile = async (file: File) => {
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
- setReplaceOpen(false);
-
- const { width, height } = await imageDimensions(file);
-
- const nextEdits: ScreenshotEdits = { ...effectiveEdits, target: null };
- delete nextEdits.viewport;
- delete nextEdits.alt;
-
- const newId = await replaceScreenshot(screenshot.stepId, file, { width, height }, nextEdits);
-
- setScreenshotOverride({
- ...baseScreenshot,
- id: newId,
- blob: file,
- mimeType: file.type,
- width,
- height,
- });
- setEditsOverride(nextEdits);
- setDeleted(false);
- onChanged?.();
- };
-
- const handleDownload = async (which: 'edited' | 'original') => {
- const blob = which === 'original' ? baseScreenshot.blob : await renderScreenshot(effectiveScreenshot);
- const ext = which === 'original' ? (baseScreenshot.mimeType.split('/')[1] ?? 'png') : 'webp';
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `mimik-screenshot-${screenshot.id}-${which}.${ext}`;
- a.click();
- URL.revokeObjectURL(url);
- };
-
- const handleDeleteImage = async () => {
- if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
- setConfirmDelete(false);
- await deleteScreenshot(screenshot.stepId);
- setDeleted(true);
- onChanged?.();
- };
-
- const ownRatio =
- baseScreenshot.width && baseScreenshot.height ? baseScreenshot.width / baseScreenshot.height : 16 / 9;
- const ratio = frameRatio ?? ownRatio;
-
- if (deleted) {
- return (
- <ImagePlaceholder
- label={i18n.t('screenshotView.imageDeleted')}
- ratio={ratio}
- className={className}
- onUpload={readOnly ? undefined : handleReplaceFile}
- />
- );
- }
-
- if (!fullUrl) {
- return (
- <div className={`rounded-lg bg-secondary p-4 flex flex-col gap-2.5 ${className}`} style={{ aspectRatio: ratio }}>
- <div className="h-7 rounded-md bg-border/60 animate-pulse" />
- <div className="flex-1 flex gap-3">
- <div className="w-[30%] flex flex-col gap-2">
- <div className="h-5 rounded bg-border/50 animate-pulse [animation-delay:100ms]" />
- <div className="h-4 rounded bg-border/40 animate-pulse [animation-delay:200ms]" />
- <div className="h-4 rounded bg-border/40 animate-pulse [animation-delay:300ms]" />
- <div className="h-4 rounded bg-border/40 animate-pulse [animation-delay:400ms]" />
- </div>
- <div className="flex-1 flex flex-col gap-2">
- <div className="h-6 w-3/5 rounded bg-border/40 animate-pulse [animation-delay:150ms]" />
- <div className="h-3 w-4/5 rounded bg-border/30 animate-pulse [animation-delay:250ms]" />
- <div className="h-3 w-[70%] rounded bg-border/30 animate-pulse [animation-delay:350ms]" />
- <div className="h-3 w-3/4 rounded bg-border/30 animate-pulse [animation-delay:450ms]" />
- </div>
- </div>
- </div>
- );
- }
-
- const currentViewport = resolveViewport(effectiveScreenshot);
- const isZoomed =
- currentViewport.width < baseScreenshot.width - VIEWPORT_EPSILON ||
- currentViewport.height < baseScreenshot.height - VIEWPORT_EPSILON;
- const showZoomControls = !readOnly && crop;
- const showTopControls = !readOnly;
- const altText = effectiveEdits?.alt || alt;
-
- const fullFrame: ScreenshotBounds = { x: 0, y: 0, width: baseScreenshot.width, height: baseScreenshot.height };
- const displayedViewport = crop && showViewport ? currentViewport : fullFrame;
- const imgStyle: React.CSSProperties = {
- width: `${(baseScreenshot.width / displayedViewport.width) * 100}%`,
- height: `${(baseScreenshot.height / displayedViewport.height) * 100}%`,
- left: `${(-displayedViewport.x / displayedViewport.width) * 100}%`,
- top: `${(-displayedViewport.y / displayedViewport.height) * 100}%`,
- transition: animate ? FRAME_TRANSITION : undefined,
- };
-
- const vpRatio = displayedViewport.width / displayedViewport.height;
- const letterbox =
- frameRatio !== undefined && Math.abs(vpRatio - frameRatio) > FRAME_RATIO_EPSILON ? frameRatio : undefined;
- const frameFit: React.CSSProperties | undefined =
- letterbox === undefined ? undefined : vpRatio >= letterbox ? { width: '100%' } : { height: '100%' };
-
- const frame = (
- <div
- data-screenshot-frame=""
- className={letterbox === undefined ? 'relative overflow-hidden w-full' : 'relative overflow-hidden'}
- style={{ aspectRatio: `${displayedViewport.width} / ${displayedViewport.height}`, ...frameFit }}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerEnd}
- onPointerCancel={handlePointerEnd}
- >
- <img
- src={fullUrl}
- alt={altText}
- draggable={false}
- className={`absolute block max-w-none ${showZoomControls && isZoomed ? 'cursor-grab active:cursor-grabbing' : ''}`}
- style={imgStyle}
- />
- </div>
- );
-
- return (
- <div className={`relative overflow-hidden rounded-lg border border-border ${className}`}>
- {letterbox === undefined ? (
- frame
- ) : (
- <div className="w-full flex items-center justify-center bg-secondary" style={{ aspectRatio: letterbox }}>
- {frame}
- </div>
- )}
- {showTopControls && (
- <div className="absolute top-2 right-2 z-10 flex items-center gap-1">
- <Popover>
- <Tooltip>
- <TooltipTrigger asChild>
- <PopoverTrigger asChild>
- <button
- type="button"
- onClick={(e) => e.stopPropagation()}
- className="flex items-center justify-center h-7 px-2 rounded-md border border-border bg-card/90 text-foreground backdrop-blur-sm text-[10px] font-semibold tracking-wide transition-colors hover:bg-secondary hover:text-accent"
- >
- {i18n.t('screenshotView.altButton')}
- </button>
- </PopoverTrigger>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('screenshotView.altLabel')}</TooltipContent>
- </Tooltip>
- <PopoverContent align="end" onClick={(e) => e.stopPropagation()}>
- <p className="text-xs font-semibold text-foreground mb-2">{i18n.t('screenshotView.altLabel')}</p>
- <textarea
- value={altDraft}
- onChange={(e) => handleAltChange(e.target.value)}
- placeholder={i18n.t('screenshotView.altPlaceholder')}
- rows={3}
- className="w-full text-sm rounded-md border border-border bg-card px-2 py-1.5 text-foreground outline-none focus-visible:border-accent resize-none"
- />
- </PopoverContent>
- </Popover>
- <DropdownMenu>
- <Tooltip>
- <TooltipTrigger asChild>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- onClick={(e) => e.stopPropagation()}
- aria-label={i18n.t('screenshotView.editMenu')}
- className="flex items-center justify-center w-7 h-7 rounded-md border border-border bg-card/90 text-foreground backdrop-blur-sm transition-colors hover:bg-secondary hover:text-accent"
- >
- <Pencil size={14} />
- </button>
- </DropdownMenuTrigger>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('screenshotView.editMenu')}</TooltipContent>
- </Tooltip>
- <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
- <DropdownMenuItem onSelect={() => onOpenEditor?.('annotate')}>
- <Pencil size={14} />
- {i18n.t('screenshotView.edit')}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem onSelect={() => setReplaceOpen(true)}>
- <ImageUp size={14} />
- {i18n.t('screenshotView.replaceImage')}
- </DropdownMenuItem>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <Download size={14} />
- {i18n.t('screenshotView.download')}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- <DropdownMenuItem onSelect={() => handleDownload('edited')}>
- {i18n.t('screenshotView.downloadEdited')}
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => handleDownload('original')}>
- {i18n.t('screenshotView.downloadOriginal')}
- </DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSeparator />
- <DropdownMenuItem variant="destructive" onSelect={() => setConfirmDelete(true)}>
- <Trash2 size={14} />
- {i18n.t('screenshotView.deleteImage')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- <ReplaceImageDialog open={replaceOpen} onSelect={handleReplaceFile} onCancel={() => setReplaceOpen(false)} />
- <ConfirmDialog
- open={confirmDelete}
- heading={i18n.t('screenshotView.deleteImage')}
- description={i18n.t('screenshotView.deleteConfirm')}
- destructive
- onConfirm={handleDeleteImage}
- onCancel={() => setConfirmDelete(false)}
- />
- </div>
- )}
- {!readOnly && saved && (
- <span className="absolute bottom-2 left-1/2 -translate-x-1/2 z-10 flex items-center px-2.5 h-7 rounded-md text-[10px] font-semibold bg-primary text-primary-foreground shadow-sm">
- {i18n.t('screenshotView.saved')}
- </span>
- )}
- <div className="absolute bottom-2 right-2 z-10 flex items-center gap-1">
- {showZoomControls && (
- <>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleZoom(ZOOM_IN_FACTOR);
- }}
- aria-label={i18n.t('screenshotView.zoomIn')}
- className="flex items-center justify-center w-7 h-7 rounded-md border border-border bg-card/90 text-foreground backdrop-blur-sm transition-colors hover:bg-secondary hover:text-accent"
- >
- <ZoomIn size={14} />
- </button>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('screenshotView.zoomIn')}</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleZoom(ZOOM_OUT_FACTOR);
- }}
- aria-label={i18n.t('screenshotView.zoomOut')}
- className="flex items-center justify-center w-7 h-7 rounded-md border border-border bg-card/90 text-foreground backdrop-blur-sm transition-colors hover:bg-secondary hover:text-accent"
- >
- <ZoomOut size={14} />
- </button>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('screenshotView.zoomOut')}</TooltipContent>
- </Tooltip>
- </>
- )}
- </div>
- </div>
- );
-}
diff --git a/src/ui/shared/SettingsView.tsx b/src/ui/shared/SettingsView.tsx
index cf8c9bb..8f88b2a 100644
--- a/src/ui/shared/SettingsView.tsx
+++ b/src/ui/shared/SettingsView.tsx
@@ -1,3 +1,26 @@
+import { PRESET_LABELS, type PresetKey } from '@mimik/core/blur/regexes';
+import { type AIApiKeys, keyFor, migrateApiKeys, withKeyFor } from '@mimik/core/capture/ai/keys';
+import {
+ AI_PROVIDERS,
+ type AIProviderKey,
+ CUSTOM_MODEL_VALUE,
+ DEFAULT_AI_PROVIDER,
+ isCustomBaseUrl,
+ isCustomModel,
+ providerOrDefault,
+} from '@mimik/core/capture/ai/models';
+import { AI_LANGUAGES, type AILanguageCode } from '@mimik/core/capture/ai/prompts';
+import { resolveVoiceApiKey } from '@mimik/core/capture/voice/api-key';
+import type { VoiceProvider } from '@mimik/core/capture/voice/transcribe';
+import { i18n } from '@mimik/core/env';
+import { type BrandLogo, defaultFooterLine, makeBrandLogo } from '@mimik/core/export/branding';
+import { DEFAULT_TARGET_COLOR, TARGET_COLORS } from '@mimik/core/screenshot/types';
+import { Button } from '@mimik/ui/components/ui/button';
+import { Input } from '@mimik/ui/components/ui/input';
+import { Popover, PopoverContent, PopoverTrigger } from '@mimik/ui/components/ui/popover';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@mimik/ui/components/ui/select';
+import { logger } from '@mimik/ui/lib/logger';
+import ColorPicker from '@mimik/ui/shared/ColorPicker';
import {
ArrowLeft,
Bug,
@@ -16,30 +39,7 @@ import {
TriangleAlert,
} from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import { PRESET_LABELS, type PresetKey } from '@/core/blur/regexes';
-import { type AIApiKeys, keyFor, migrateApiKeys, withKeyFor } from '@/core/capture/ai/keys';
-import {
- AI_PROVIDERS,
- type AIProviderKey,
- CUSTOM_MODEL_VALUE,
- DEFAULT_AI_PROVIDER,
- isCustomBaseUrl,
- isCustomModel,
- providerOrDefault,
-} from '@/core/capture/ai/models';
-import { AI_LANGUAGES, type AILanguageCode } from '@/core/capture/ai/prompts';
-import { resolveVoiceApiKey } from '@/core/capture/voice/api-key';
-import type { VoiceProvider } from '@/core/capture/voice/transcribe';
-import { type BrandLogo, defaultFooterLine, makeBrandLogo } from '@/core/export/branding';
-import { DEFAULT_TARGET_COLOR, TARGET_COLORS } from '@/core/screenshot/types';
import { localStorage } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
-import { Button } from '@/ui/components/ui/button';
-import { Input } from '@/ui/components/ui/input';
-import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover';
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/ui/components/ui/select';
-import ColorPicker from '@/ui/shared/ColorPicker';
import { KeyStatusNote, KeyWarningNote, ModelList, SecretInput, useKeyCheck } from '@/ui/shared/key-check';
import MicrophonePicker from '@/ui/shared/MicrophonePicker';
import { changedSettings, type SettingsSnapshot } from '@/ui/shared/settings-autosave';
diff --git a/src/ui/shared/StepSourceBadge.tsx b/src/ui/shared/StepSourceBadge.tsx
deleted file mode 100644
index 00edf4a..0000000
--- a/src/ui/shared/StepSourceBadge.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { i18n } from '#imports';
-import type { DescriptionSource } from '@/core/guides/types';
-
-const STYLES: Record<DescriptionSource, string> = {
- ai: 'bg-secondary text-accent',
- narration: 'bg-success/10 text-success',
- heuristic: 'bg-primary text-primary-foreground',
- manual: 'border border-border text-muted-foreground',
-};
-
-const LABELS: Record<DescriptionSource, string> = {
- ai: 'stepSource.ai',
- narration: 'stepSource.voice',
- heuristic: 'stepSource.basic',
- manual: 'stepSource.edited',
-};
-
-export default function StepSourceBadge({ source }: { source: DescriptionSource | undefined }) {
- if (!source) return null;
-
- return (
- <span
- className={`inline-block leading-none text-[9px] font-bold uppercase tracking-wide rounded px-1 py-[2px] shrink-0 ${STYLES[source]}`}
- title={i18n.t('stepSource.hint')}
- >
- {i18n.t(LABELS[source])}
- </span>
- );
-}
diff --git a/src/ui/shared/Toast.tsx b/src/ui/shared/Toast.tsx
deleted file mode 100644
index 20b1242..0000000
--- a/src/ui/shared/Toast.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { AlertCircle } from 'lucide-react';
-import { useEffect } from 'react';
-
-interface ToastProps {
- message: string | null;
- onDismiss: () => void;
- duration?: number;
-}
-
-export default function Toast({ message, onDismiss, duration = 5000 }: ToastProps) {
- useEffect(() => {
- if (!message) return;
- const timer = setTimeout(onDismiss, duration);
- return () => clearTimeout(timer);
- }, [message, duration, onDismiss]);
-
- if (!message) return null;
-
- return (
- <output
- className="fixed bottom-4 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 max-w-[90%] px-4 py-2.5 rounded-lg shadow-lg bg-primary text-primary-foreground text-[13px] font-medium"
- aria-live="polite"
- >
- <AlertCircle size={14} className="shrink-0" />
- {message}
- </output>
- );
-}
diff --git a/src/ui/shared/UpdateNotice.tsx b/src/ui/shared/UpdateNotice.tsx
index 28abd4a..8c37216 100644
--- a/src/ui/shared/UpdateNotice.tsx
+++ b/src/ui/shared/UpdateNotice.tsx
@@ -1,6 +1,6 @@
+import { i18n } from '@mimik/core/env';
import { Sparkles, X } from 'lucide-react';
import { useEffect, useState } from 'react';
-import { i18n } from '#imports';
import { dismissUpdateNotice, readUpdateNotice } from '@/lib/update-notice';
const RELEASES_URL = 'https://github.com/westpoint-io/mimik/releases';
diff --git a/src/ui/shared/__tests__/guide-description-error.test.ts b/src/ui/shared/__tests__/guide-description-error.test.ts
deleted file mode 100644
index aaa0e7b..0000000
--- a/src/ui/shared/__tests__/guide-description-error.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import type { GuideDescriptionError } from '@/lib/messaging';
-import { guideDescriptionErrorMessage } from '../guide-description-error';
-
-const CASES: [GuideDescriptionError, string][] = [
- ['no-api-key', 'editor.descriptionErrorNoApiKey'],
- ['no-steps', 'editor.descriptionErrorNoSteps'],
- ['generation-failed', 'editor.descriptionErrorFailed'],
- ['save-failed', 'editor.descriptionErrorSaveFailed'],
-];
-
-describe('guideDescriptionErrorMessage', () => {
- it.each(CASES)('maps %s to its locale key', (error, key) => {
- expect(guideDescriptionErrorMessage(error)).toBe(key);
- });
-
- it('gives every error code a distinct message', () => {
- const messages = CASES.map(([error]) => guideDescriptionErrorMessage(error));
- expect(new Set(messages).size).toBe(CASES.length);
- });
-});
diff --git a/src/ui/shared/__tests__/step-source-badge.test.tsx b/src/ui/shared/__tests__/step-source-badge.test.tsx
deleted file mode 100644
index 1fdbcf7..0000000
--- a/src/ui/shared/__tests__/step-source-badge.test.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-// @vitest-environment jsdom
-import '@testing-library/jest-dom/vitest';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-import type { DescriptionSource } from '@/core/guides/types';
-import StepSourceBadge from '@/ui/shared/StepSourceBadge';
-
-const SOURCES: DescriptionSource[] = ['ai', 'narration', 'heuristic', 'manual'];
-const LOCALES = ['en', 'de', 'es', 'fr', 'pt-BR', 'zh-CN'];
-
-describe('StepSourceBadge', () => {
- it('says nothing for a step recorded before the field existed', () => {
- const { container } = render(<StepSourceBadge source={undefined} />);
- expect(container).toBeEmptyDOMElement();
- });
-
- it.each(SOURCES)('renders a label for %s', (source) => {
- render(<StepSourceBadge source={source} />);
- expect(screen.getByText(/.+/)).toBeInTheDocument();
- });
-
- it('distinguishes a rule-based description from an AI one', () => {
- const { container: ai } = render(<StepSourceBadge source="ai" />);
- const { container: basic } = render(<StepSourceBadge source="heuristic" />);
- expect(ai.textContent).not.toBe(basic.textContent);
- expect(ai.firstElementChild?.className).not.toBe(basic.firstElementChild?.className);
- });
-
- it('carries a label for every source, in every locale', () => {
- for (const locale of LOCALES) {
- const text = readFileSync(join(process.cwd(), 'src/locales', `${locale}.yml`), 'utf8');
- for (const key of ['ai', 'voice', 'basic', 'edited', 'hint']) {
- expect(text, `${locale} is missing stepSource.${key}`).toContain(` ${key}:`);
- }
- }
- });
-});
diff --git a/src/ui/shared/card-drag.tsx b/src/ui/shared/card-drag.tsx
deleted file mode 100644
index 3ff05fa..0000000
--- a/src/ui/shared/card-drag.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { GripVertical } from 'lucide-react';
-import { useRef } from 'react';
-
-export interface DragHandleProps {
- onDragStart: (e: React.DragEvent) => void;
- onDragOver: (e: React.DragEvent) => void;
- onDragEnd: () => void;
-}
-
-export function useCardDrag(dragHandleProps?: DragHandleProps) {
- const pressedHandle = useRef(false);
- return {
- draggable: !!dragHandleProps,
- onPointerDownCapture: (e: React.PointerEvent) => {
- pressedHandle.current = !!(e.target as Element).closest('[data-drag-handle]');
- },
- onDragStart: (e: React.DragEvent) => {
- if (!pressedHandle.current) {
- e.preventDefault();
- return;
- }
- dragHandleProps?.onDragStart(e);
- },
- };
-}
-
-export function DragGrip() {
- return (
- <span
- data-drag-handle=""
- aria-hidden="true"
- className="shrink-0 p-1 -m-1 cursor-grab text-border hover:text-muted-foreground"
- >
- <GripVertical size={14} />
- </span>
- );
-}
diff --git a/src/ui/shared/guide-description-error.ts b/src/ui/shared/guide-description-error.ts
deleted file mode 100644
index 56afafa..0000000
--- a/src/ui/shared/guide-description-error.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { i18n } from '#imports';
-import type { GuideDescriptionError } from '@/lib/messaging';
-
-const DESCRIPTION_ERROR_KEYS = {
- 'no-api-key': 'editor.descriptionErrorNoApiKey',
- 'no-steps': 'editor.descriptionErrorNoSteps',
- 'generation-failed': 'editor.descriptionErrorFailed',
- 'save-failed': 'editor.descriptionErrorSaveFailed',
-} as const satisfies Record<GuideDescriptionError, string>;
-
-export function guideDescriptionErrorMessage(error: GuideDescriptionError): string {
- return i18n.t(DESCRIPTION_ERROR_KEYS[error]);
-}
diff --git a/src/ui/shared/key-check.tsx b/src/ui/shared/key-check.tsx
index 7b17c3d..6e5da20 100644
--- a/src/ui/shared/key-check.tsx
+++ b/src/ui/shared/key-check.tsx
@@ -1,8 +1,8 @@
+import { i18n } from '@mimik/core/env';
+import { Input } from '@mimik/ui/components/ui/input';
import { Check, Eye, EyeOff, TriangleAlert } from 'lucide-react';
import { useCallback, useRef, useState } from 'react';
-import { i18n } from '#imports';
import { sendMessage } from '@/lib/messaging';
-import { Input } from '@/ui/components/ui/input';
export type KeyStatus = 'checking' | 'valid' | 'rejected' | 'unreachable' | 'model-required' | 'model-invalid' | null;
diff --git a/src/ui/shared/rewrite-error.ts b/src/ui/shared/rewrite-error.ts
deleted file mode 100644
index 188e6f3..0000000
--- a/src/ui/shared/rewrite-error.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { i18n } from '#imports';
-import type { RewriteError } from '@/lib/messaging';
-
-const REWRITE_ERROR_KEYS = {
- 'no-api-key': 'editor.rewriteErrorNoApiKey',
- 'generation-failed': 'editor.rewriteErrorFailed',
-} as const satisfies Record<RewriteError, string>;
-
-export function rewriteErrorMessage(error: RewriteError): string {
- return i18n.t(REWRITE_ERROR_KEYS[error]);
-}
diff --git a/src/ui/sidepanel/App.tsx b/src/ui/sidepanel/App.tsx
index dc295fa..8a4c5bb 100644
--- a/src/ui/sidepanel/App.tsx
+++ b/src/ui/sidepanel/App.tsx
@@ -1,3 +1,7 @@
+import { Button } from '@mimik/ui/components/ui/button';
+import { Input } from '@mimik/ui/components/ui/input';
+import { TooltipProvider } from '@mimik/ui/components/ui/tooltip';
+import { logger } from '@mimik/ui/lib/logger';
import { Globe, Search, Settings, Video } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
@@ -14,13 +18,9 @@ import {
requestHostPermissions,
updateTab,
} from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import { sendMessage } from '@/lib/messaging';
import { getVoiceStatus } from '@/lib/offscreen';
import { connectToBackground, type PanelAiUpdate, type PanelVoiceUpdate } from '@/lib/port';
-import { Button } from '@/ui/components/ui/button';
-import { Input } from '@/ui/components/ui/input';
-import { TooltipProvider } from '@/ui/components/ui/tooltip';
import SettingsView from '@/ui/shared/SettingsView';
import UpdateNotice from '@/ui/shared/UpdateNotice';
import GuideEditor from './GuideEditor';
diff --git a/src/ui/sidepanel/ExportMenu.tsx b/src/ui/sidepanel/ExportMenu.tsx
index abf4b3c..b25e559 100644
--- a/src/ui/sidepanel/ExportMenu.tsx
+++ b/src/ui/sidepanel/ExportMenu.tsx
@@ -1,3 +1,4 @@
+import { Button } from '@mimik/ui/components/ui/button';
import { Download, FileCode, FileDown, FileImage, FileText, Loader2, Video } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
@@ -8,7 +9,6 @@ import { exportGuideAsPDF } from '@/core/export/pdf-export';
import { canExportVideo } from '@/core/export/video-support';
import { getGuide } from '@/core/guides/service';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
-import { Button } from '@/ui/components/ui/button';
interface ExportMenuProps {
guideId: string;
diff --git a/src/ui/sidepanel/GuideEditor.tsx b/src/ui/sidepanel/GuideEditor.tsx
index 53d2036..621a74a 100644
--- a/src/ui/sidepanel/GuideEditor.tsx
+++ b/src/ui/sidepanel/GuideEditor.tsx
@@ -1,3 +1,9 @@
+import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui/components/ui/tooltip';
+import { getMostCommonDomain } from '@mimik/ui/lib/utils';
+import BlockCard from '@mimik/ui/shared/BlockCard';
+import EmptyGuideState from '@mimik/ui/shared/EmptyGuideState';
+import FaviconImg from '@mimik/ui/shared/FaviconImg';
+import StepCard from '@mimik/ui/sidepanel/StepCard';
import { ArrowLeft, Maximize2, Play } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { i18n } from '#imports';
@@ -7,12 +13,6 @@ import type { Guide, Screenshot, Step } from '@/core/guides/types';
import { dominantRatio } from '@/core/screenshot/geometry';
import { createTab, focusWindow, getExtensionURL, queryTabs, updateTab } from '@/lib/browser-api';
import { sendMessage } from '@/lib/messaging';
-import { getMostCommonDomain } from '@/lib/utils';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import BlockCard from '@/ui/shared/BlockCard';
-import EmptyGuideState from '@/ui/shared/EmptyGuideState';
-import FaviconImg from '@/ui/shared/FaviconImg';
-import StepCard from './StepCard';
interface GuideEditorProps {
guideId: string;
diff --git a/src/ui/sidepanel/GuideMeView.tsx b/src/ui/sidepanel/GuideMeView.tsx
index d73e6b7..8e5825d 100644
--- a/src/ui/sidepanel/GuideMeView.tsx
+++ b/src/ui/sidepanel/GuideMeView.tsx
@@ -1,3 +1,6 @@
+import { extractDomain } from '@mimik/ui/lib/utils';
+import FaviconImg from '@mimik/ui/shared/FaviconImg';
+import ScreenshotView from '@mimik/ui/shared/ScreenshotView';
import { ArrowLeft, Check, ChevronLeft, ChevronRight, TriangleAlert } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { browser, i18n } from '#imports';
@@ -8,9 +11,6 @@ import { actionSteps } from '@/core/guides/blocks';
import { getGuide } from '@/core/guides/service';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
import { sendMessage } from '@/lib/messaging';
-import { extractDomain } from '@/lib/utils';
-import FaviconImg from '@/ui/shared/FaviconImg';
-import ScreenshotView from '@/ui/shared/ScreenshotView';
interface GuideMeViewProps {
guideId: string;
diff --git a/src/ui/sidepanel/LibraryView.tsx b/src/ui/sidepanel/LibraryView.tsx
index 6166a25..bce4795 100644
--- a/src/ui/sidepanel/LibraryView.tsx
+++ b/src/ui/sidepanel/LibraryView.tsx
@@ -1,3 +1,6 @@
+import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui/components/ui/tooltip';
+import { formatRelativeTime } from '@mimik/ui/lib/utils';
+import FaviconImg from '@mimik/ui/shared/FaviconImg';
import { Star, Trash2 } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { i18n } from '#imports';
@@ -10,9 +13,6 @@ import {
toggleStar,
} from '@/core/guides/service';
import type { Guide } from '@/core/guides/types';
-import { formatRelativeTime } from '@/lib/utils';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import FaviconImg from '@/ui/shared/FaviconImg';
interface LibraryViewProps {
onOpen: (guideId: string) => void;
diff --git a/src/ui/sidepanel/MicToggle.tsx b/src/ui/sidepanel/MicToggle.tsx
index b990c47..e8a5258 100644
--- a/src/ui/sidepanel/MicToggle.tsx
+++ b/src/ui/sidepanel/MicToggle.tsx
@@ -1,12 +1,12 @@
+import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui/components/ui/tooltip';
+import { logger } from '@mimik/ui/lib/logger';
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 { getActiveTab, localStorage } from '@/lib/browser-api';
-import { logger } from '@/lib/logger';
import { sendMessage } from '@/lib/messaging';
import { abortVoiceCapture, openMicPermissionPage } from '@/lib/offscreen';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
interface MicToggleProps {
enabled: boolean;
diff --git a/src/ui/sidepanel/RecordingView.tsx b/src/ui/sidepanel/RecordingView.tsx
index 659cd55..ad1e853 100644
--- a/src/ui/sidepanel/RecordingView.tsx
+++ b/src/ui/sidepanel/RecordingView.tsx
@@ -1,3 +1,8 @@
+import { Button } from '@mimik/ui/components/ui/button';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui/components/ui/tooltip';
+import { extractDomain } from '@mimik/ui/lib/utils';
+import ScreenshotView from '@mimik/ui/shared/ScreenshotView';
+import StepSourceBadge from '@mimik/ui/shared/StepSourceBadge';
import { Check, EyeOff, Loader2, X } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { browser, i18n } from '#imports';
@@ -6,11 +11,6 @@ import type { Screenshot, Step } from '@/core/guides/types';
import { getActiveTab, localStorage } from '@/lib/browser-api';
import { sendMessage } from '@/lib/messaging';
import type { PanelAiUpdate, PanelVoiceUpdate } from '@/lib/port';
-import { extractDomain } from '@/lib/utils';
-import { Button } from '@/ui/components/ui/button';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import ScreenshotView from '@/ui/shared/ScreenshotView';
-import StepSourceBadge from '@/ui/shared/StepSourceBadge';
import AiStatus from './AiStatus';
import MicToggle from './MicToggle';
import VoiceStatus from './VoiceStatus';
diff --git a/src/ui/sidepanel/StepCard.tsx b/src/ui/sidepanel/StepCard.tsx
deleted file mode 100644
index 18d3dd9..0000000
--- a/src/ui/sidepanel/StepCard.tsx
+++ /dev/null
@@ -1,196 +0,0 @@
-import { Check, Copy, Loader2, Trash2 } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import { i18n } from '#imports';
-import { replaceScreenshot } from '@/core/guides/service';
-import type { Screenshot, Step } from '@/core/guides/types';
-import { imageDimensions, renderScreenshot } from '@/core/screenshot/render';
-import { logger } from '@/lib/logger';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
-import { useAskAi } from '@/ui/shared/AskAi';
-import ConfirmDialog from '@/ui/shared/ConfirmDialog';
-import { DragGrip, type DragHandleProps, useCardDrag } from '@/ui/shared/card-drag';
-import ImagePlaceholder from '@/ui/shared/ImagePlaceholder';
-import ScreenshotView from '@/ui/shared/ScreenshotView';
-import StepSourceBadge from '@/ui/shared/StepSourceBadge';
-
-interface StepCardProps {
- step: Step;
- number: number;
- screenshot: Screenshot | undefined;
- onDescriptionChange?: (stepId: string, description: string) => void;
- onDelete?: (stepId: string) => void;
- dragHandleProps?: DragHandleProps;
- onOpenEditor?: (stepId: string, tool: 'annotate' | 'redact' | 'crop' | 'target') => void;
- onCopy?: (stepId: string) => void;
- placeholderRatio?: number;
- frameRatio?: number;
- readOnly?: boolean;
- onChanged?: () => void;
- hasApiKey?: boolean;
-}
-
-export default function StepCard({
- step,
- number,
- screenshot,
- onDescriptionChange,
- onDelete,
- dragHandleProps,
- onOpenEditor,
- placeholderRatio,
- frameRatio,
- readOnly,
- onChanged,
- hasApiKey,
-}: StepCardProps) {
- const [description, setDescription] = useState(step.description);
- const [dragOver, setDragOver] = useState(false);
- const [copied, setCopied] = useState(false);
- const [confirmDelete, setConfirmDelete] = useState(false);
- const cardDrag = useCardDrag(dragHandleProps);
-
- useEffect(() => {
- setDescription(step.description);
- }, [step.description]);
-
- const handleDescriptionBlur = () => {
- if (description !== step.description) onDescriptionChange?.(step.id, description);
- };
-
- const askAi = useAskAi(
- description,
- (next) => {
- setDescription(next);
- onDescriptionChange?.(step.id, next);
- },
- !readOnly && !step.aiPending && Boolean(hasApiKey),
- );
-
- const handleDelete = () => {
- setConfirmDelete(false);
- onDelete?.(step.id);
- };
-
- const handleCopy = async () => {
- if (!screenshot) return;
- try {
- const rendered = await renderScreenshot(screenshot, { format: 'image/png' });
- await navigator.clipboard.write([new ClipboardItem({ 'image/png': rendered })]);
- setCopied(true);
- setTimeout(() => setCopied(false), 1500);
- } catch (err) {
- logger.error(' Copy to clipboard failed', err);
- }
- };
-
- const handleUpload = async (file: File) => {
- await replaceScreenshot(step.id, file, await imageDimensions(file));
- onChanged?.();
- };
-
- const handleDragOver = (e: React.DragEvent) => {
- e.preventDefault();
- setDragOver(true);
- dragHandleProps?.onDragOver(e);
- };
-
- return (
- <div
- {...cardDrag}
- onDragOver={handleDragOver}
- onDragLeave={() => setDragOver(false)}
- onDragEnd={() => {
- setDragOver(false);
- dragHandleProps?.onDragEnd();
- }}
- className={`rounded-xl mb-3 overflow-hidden transition-shadow border border-border bg-card ${dragOver ? 'ring-2 ring-accent' : ''}`}
- >
- {screenshot ? (
- <ScreenshotView
- screenshot={screenshot}
- alt={`Step ${number} screenshot`}
- className="!rounded-none !border-0"
- crop
- frameRatio={frameRatio}
- readOnly={readOnly}
- onOpenEditor={!readOnly && onOpenEditor ? (tool) => onOpenEditor(step.id, tool) : undefined}
- onChanged={onChanged}
- />
- ) : (
- <ImagePlaceholder
- label={i18n.t('editor.noScreenshot')}
- ratio={placeholderRatio}
- className="w-full !rounded-none border-x-0 border-t-0"
- onUpload={readOnly ? undefined : handleUpload}
- />
- )}
-
- <div className="px-3 pt-2 pb-2">
- <div className="flex items-center gap-2">
- {dragHandleProps && <DragGrip />}
- <span className="flex items-center justify-center w-[22px] h-[22px] rounded-full text-[11px] font-bold shrink-0 bg-primary text-primary-foreground">
- {number}
- </span>
- {step.aiPending ? (
- <span className="flex items-center gap-1.5 text-[13px] font-medium leading-snug flex-1 text-muted-foreground">
- <Loader2 size={13} className="animate-spin" />
- {i18n.t('editor.writingStepDescription')}
- </span>
- ) : readOnly ? (
- <p className="text-[13px] font-medium leading-snug flex-1 text-foreground whitespace-pre-wrap">
- {step.description}
- </p>
- ) : (
- <textarea
- className="w-full text-[13px] font-medium resize-none outline-none border-0 bg-transparent p-0 leading-snug flex-1 text-foreground"
- value={description}
- rows={1}
- onChange={(e) => setDescription(e.target.value)}
- onSelect={askAi.onSelect}
- onBlur={handleDescriptionBlur}
- />
- )}
- </div>
- <div className="flex items-center justify-between gap-2 mt-1">
- {step.aiPending ? <span /> : <StepSourceBadge source={step.descriptionSource} />}
- <div className="flex items-center gap-0.5">
- {askAi.trigger}
- {screenshot && (
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={handleCopy}
- className={`p-1 rounded-md transition-colors ${copied ? 'text-success' : 'text-border hover:text-success'}`}
- >
- {copied ? <Check size={13} /> : <Copy size={13} />}
- </button>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('editor.copyScreenshot')}</TooltipContent>
- </Tooltip>
- )}
- {!readOnly && (
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={() => setConfirmDelete(true)}
- className="p-1 rounded-md transition-colors text-border hover:text-destructive"
- >
- <Trash2 size={13} />
- </button>
- </TooltipTrigger>
- <TooltipContent>{i18n.t('recording.deleteStep')}</TooltipContent>
- </Tooltip>
- )}
- </div>
- </div>
- </div>
- <ConfirmDialog
- open={confirmDelete}
- heading={i18n.t('editor.deleteThisStep')}
- destructive
- onConfirm={handleDelete}
- onCancel={() => setConfirmDelete(false)}
- />
- </div>
- );
-}
diff --git a/src/ui/sidepanel/VoiceToast.tsx b/src/ui/sidepanel/VoiceToast.tsx
index 12a5bee..18ac7ee 100644
--- a/src/ui/sidepanel/VoiceToast.tsx
+++ b/src/ui/sidepanel/VoiceToast.tsx
@@ -1,8 +1,8 @@
+import { Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui/components/ui/tooltip';
import { Check, Loader2, TriangleAlert, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { i18n } from '#imports';
import type { PanelVoiceUpdate } from '@/lib/port';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
import { narratedKey, voiceErrorKey } from './voice-status';
const CONFIRM_MS = 7000;
diff --git a/src/ui/sidepanel/__tests__/step-card-drag.test.tsx b/src/ui/sidepanel/__tests__/step-card-drag.test.tsx
index 39ecc12..e9772ce 100644
--- a/src/ui/sidepanel/__tests__/step-card-drag.test.tsx
+++ b/src/ui/sidepanel/__tests__/step-card-drag.test.tsx
@@ -1,13 +1,14 @@
// @vitest-environment jsdom
+
+import { TooltipProvider } from '@mimik/ui/components/ui/tooltip';
import { fireEvent, render } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { Step } from '@/core/guides/types';
-import { TooltipProvider } from '@/ui/components/ui/tooltip';
vi.mock('@/core/guides/service', () => ({ replaceScreenshot: vi.fn() }));
vi.mock('@/core/screenshot/render', () => ({ imageDimensions: vi.fn(), renderScreenshot: vi.fn() }));
-import StepCard from '../StepCard';
+import StepCard from '@mimik/ui/sidepanel/StepCard';
const step: Step = {
id: 's1',
diff --git a/src/ui/sidepanel/__tests__/step-card-upload.test.tsx b/src/ui/sidepanel/__tests__/step-card-upload.test.tsx
index 8776061..3cae082 100644
--- a/src/ui/sidepanel/__tests__/step-card-upload.test.tsx
+++ b/src/ui/sidepanel/__tests__/step-card-upload.test.tsx
@@ -1,13 +1,14 @@
// @vitest-environment jsdom
+
+import { TooltipProvider } from '@mimik/ui/components/ui/tooltip';
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { Step } from '@/core/guides/types';
-import { TooltipProvider } from '@/ui/components/ui/tooltip';
vi.mock('@/core/guides/service', () => ({ replaceScreenshot: vi.fn() }));
vi.mock('@/core/screenshot/render', () => ({ imageDimensions: vi.fn(), renderScreenshot: vi.fn() }));
-import StepCard from '../StepCard';
+import StepCard from '@mimik/ui/sidepanel/StepCard';
const step: Step = {
id: 's1',
diff --git a/tsconfig.json b/tsconfig.json
index dac3c2d..4ab7953 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -6,8 +6,10 @@
"allowImportingTsExtensions": true,
"paths": {
"@/core/*": ["./packages/core/src/*"],
- "@/*": ["./src/*"]
+ "@/*": ["./src/*"],
+ "@mimik/ui/*": ["./packages/ui/src/*"],
+ "@mimik/core/*": ["./packages/core/src/*"]
}
},
- "include": ["src/**/*", "packages/core/src/**/*", "wxt.config.ts", ".wxt/wxt.d.ts"]
+ "include": ["src/**/*", "packages/core/src/**/*", "packages/ui/src/**/*", "wxt.config.ts", ".wxt/wxt.d.ts"]
}
diff --git a/wxt.config.ts b/wxt.config.ts
index 3c86866..a878345 100644
--- a/wxt.config.ts
+++ b/wxt.config.ts
@@ -21,6 +21,8 @@ export default defineConfig({
],
},
alias: {
+ '@mimik/core': 'packages/core/src',
+ '@mimik/ui': 'packages/ui/src',
'@/core': 'packages/core/src',
'@': 'src',
},