π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
refactor(ui): move export and guide description state into hooks
Luis Ortiz9b0964d757f8
diff --git a/packages/ui/src/fullview/ExportPreviewModal.tsx b/packages/ui/src/fullview/ExportPreviewModal.tsxindex 5a7c263..e2688ba 100644--- a/packages/ui/src/fullview/ExportPreviewModal.tsx+++ b/packages/ui/src/fullview/ExportPreviewModal.tsx@@ -1,6 +1,4 @@import { i18n } from '@mimik/core/env';-import { downloadBlob, downloadText, safeFilename } from '@mimik/core/export/download';-import { exportGuideAsHTML } from '@mimik/core/export/html-export';import {DEFAULT_EXPORT_OPTIONS,type ExportOptions,@@ -10,21 +8,20 @@ import {saveExportOptions,VIDEO_RESOLUTIONS,} from '@mimik/core/export/options';-import { exportGuideAsPDF } from '@mimik/core/export/pdf-export';-import { paginatePreview, withPreviewStyles } from '@mimik/core/export/preview';-import type { VideoChapter } from '@mimik/core/export/video-export';-import { canExportVideo, STEP_SECONDS } from '@mimik/core/export/video-support';+import { paginatePreview } from '@mimik/core/export/preview';+import { STEP_SECONDS } from '@mimik/core/export/video-support';import type { Guide, Screenshot, Step } from '@mimik/core/guides/types';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 { lazy, Suspense, useEffect, useState } from 'react';-import type { VideoMime } from './VideoStepPlayer';+import { type ExportFormat, useGuideExport } from './use-guide-export';+import { useVideoPreview } from './use-video-preview';const VideoStepPlayer = lazy(() => import('./VideoStepPlayer'));-const VIDEO_AUTOPLAY_STEP_LIMIT = 25;+const _VIDEO_AUTOPLAY_STEP_LIMIT = 25;const IMAGE_SCALES: ImageScale[] = ['small', 'medium', 'large'];interface ExportPreviewModalProps {@@ -35,100 +32,18 @@ interface ExportPreviewModalProps {screenshots: Map<string, Screenshot>;}-type ExportFormat = 'docx' | 'gif' | 'html' | 'markdown' | 'pdf' | 'video';type PreviewMode = 'document' | 'video';export default function ExportPreviewModal({ open, onOpenChange, guide, steps, screenshots }: ExportPreviewModalProps) {const [options, setOptions] = useState<ExportOptions>(DEFAULT_EXPORT_OPTIONS);- const [preview, setPreview] = useState('');- const [rendering, setRendering] = useState(false);- const [exporting, setExporting] = useState<ExportFormat | null>(null);- const [videoSupported, setVideoSupported] = useState(false);const [mode, setMode] = useState<PreviewMode>('document');- const [videoUrl, setVideoUrl] = useState<string | null>(null);- const [videoType, setVideoType] = useState<VideoMime>('video/mp4');- const [videoChapters, setVideoChapters] = useState<VideoChapter[]>([]);- const [downloadProgress, setDownloadProgress] = useState(0);- const downloadAbort = useRef<AbortController | null>(null);- const [videoError, setVideoError] = useState<string | null>(null);- const [videoProgress, setVideoProgress] = useState(0);- const [videoRequested, setVideoRequested] = useState(false);useEffect(() => {if (open) loadExportOptions().then(setOptions);}, [open]);- useEffect(() => {- let active = true;- canExportVideo().then((supported) => {- if (active) setVideoSupported(supported);- });- return () => {- active = false;- };- }, []);-- const videoPending = steps.length > VIDEO_AUTOPLAY_STEP_LIMIT && !videoRequested;- const { cover, stepDescriptions, resolution } = options;-- useEffect(() => {- if (!open) setVideoRequested(false);- }, [open]);-- useEffect(() => {- if (!open || mode !== 'document') return;- let cancelled = false;- setRendering(true);- const timer = setTimeout(async () => {- const html = await exportGuideAsHTML(guide, steps, screenshots, options);- if (cancelled) return;- setPreview(withPreviewStyles(html));- setRendering(false);- }, 200);- return () => {- cancelled = true;- clearTimeout(timer);- };- }, [open, mode, guide, steps, screenshots, options]);-- useEffect(() => {- if (!open || mode !== 'video' || videoPending) return;- const controller = new AbortController();- let url: string | null = null;- setVideoError(null);- setVideoProgress(0);- const timer = setTimeout(async () => {- try {- const { exportGuideAsVideo } = await import('@/core/export/video-export');- const { blob, chapters } = await exportGuideAsVideo(- guide,- steps,- screenshots,- { cover, stepDescriptions, resolution },- {- signal: controller.signal,- onProgress: (encoded, frames) => {- if (!controller.signal.aborted) setVideoProgress(frames > 0 ? encoded / frames : 0);- },- },- );- if (controller.signal.aborted) return;- url = URL.createObjectURL(blob);- setVideoType(blob.type === 'video/webm' ? 'video/webm' : 'video/mp4');- setVideoChapters(chapters);- setVideoUrl(url);- } catch (error) {- if (controller.signal.aborted || (error instanceof DOMException && error.name === 'AbortError')) return;- setVideoError(error instanceof Error ? error.message : String(error));- }- }, 200);- return () => {- controller.abort();- clearTimeout(timer);- if (url) URL.revokeObjectURL(url);- setVideoUrl(null);- };- }, [open, mode, guide, steps, screenshots, cover, stepDescriptions, resolution, videoPending]);+ const doc = useGuideExport({ active: open && mode === 'document', guide, steps, screenshots, options });+ const video = useVideoPreview({ active: open && mode === 'video', guide, steps, screenshots, options });const update = (patch: Partial<ExportOptions>) => {const next = { ...options, ...patch };@@ -136,50 +51,6 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, svoid saveExportOptions(next);};- async function handleExport(format: ExportFormat) {- setExporting(format);- try {- if (format === 'html') {- const html = await exportGuideAsHTML(guide, steps, screenshots, options);- downloadText(html, safeFilename(guide.title, 'html'), 'text/html');- } else if (format === 'pdf') {- downloadBlob(await exportGuideAsPDF(guide, steps, screenshots, options), safeFilename(guide.title, 'pdf'));- } else if (format === 'docx') {- const { exportGuideAsDOCX } = await import('@/core/export/docx-export');- downloadBlob(await exportGuideAsDOCX(guide, steps, screenshots, options), safeFilename(guide.title, 'docx'));- } else if (format === 'gif') {- const controller = new AbortController();- downloadAbort.current = controller;- setDownloadProgress(0);- const { exportGuideAsGif } = await import('@/core/export/gif-export');- const { blob, extension } = await exportGuideAsGif(guide, steps, screenshots, options, {- signal: controller.signal,- onProgress: (encoded, frames) => setDownloadProgress(frames > 0 ? encoded / frames : 0),- });- downloadBlob(blob, safeFilename(guide.title, extension));- } else if (format === 'video') {- const controller = new AbortController();- downloadAbort.current = controller;- setDownloadProgress(0);- const { exportGuideAsVideo } = await import('@/core/export/video-export');- const { blob, extension } = await exportGuideAsVideo(guide, steps, screenshots, options, {- signal: controller.signal,- onProgress: (encoded, frames) => setDownloadProgress(frames > 0 ? encoded / frames : 0),- });- downloadBlob(blob, safeFilename(guide.title, extension));- } else {- const { exportGuideAsMarkdown } = await import('@/core/export/markdown-export');- const md = await exportGuideAsMarkdown(guide, steps, screenshots);- downloadText(md, safeFilename(guide.title, 'md'), 'text/markdown');- }- } catch (error) {- if (!(error instanceof DOMException && error.name === 'AbortError')) throw error;- } finally {- downloadAbort.current = null;- setExporting(null);- }- }-const toggles: Array<{ key: keyof ExportOptions; label: string; hint: string }> = [{ key: 'cover', label: i18n.t('exportPreview.cover'), hint: i18n.t('exportPreview.coverHint') },{ key: 'screenshots', label: i18n.t('exportPreview.screenshots'), hint: i18n.t('exportPreview.screenshotsHint') },@@ -202,7 +73,7 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s{ key: 'html', icon: FileCode, label: i18n.t('exportMenu.html') },{ key: 'markdown', icon: FileText, label: i18n.t('exportMenu.markdown') },{ key: 'gif', icon: FileImage, label: i18n.t('exportMenu.gif') },- ...(videoSupported ? [{ key: 'video' as const, icon: Video, label: i18n.t('exportMenu.video') }] : []),+ ...(video.supported ? [{ key: 'video' as const, icon: Video, label: i18n.t('exportMenu.video') }] : []),];return (@@ -261,7 +132,7 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s</div></div>- {videoSupported && (+ {video.supported && (<div className="pt-3 border-t border-border"><div className="text-[12px] font-semibold text-foreground mb-2">{i18n.t('exportPreview.resolution')}@@ -307,19 +178,19 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s<div className="pt-3 border-t border-border space-y-1.5">{formats.map(({ key, icon: Icon, label }) => {- const cancellable = exporting === key && (key === 'video' || key === 'gif');+ const cancellable = doc.running === key && (key === 'video' || key === 'gif');return (<Buttonkey={key}size="sm"variant="ghost"- disabled={exporting !== null && !cancellable}- onClick={() => (cancellable ? downloadAbort.current?.abort() : handleExport(key))}+ disabled={doc.running !== null && !cancellable}+ onClick={() => (cancellable ? doc.cancel() : doc.run(key))}className="w-full justify-start gap-2 border border-border hover:border-accent">- {exporting === key ? <Loader2 size={14} className="animate-spin" /> : <Icon size={14} />}+ {doc.running === key ? <Loader2 size={14} className="animate-spin" /> : <Icon size={14} />}{cancellable- ? i18n.t('exportMenu.cancelProgress', [String(Math.round(downloadProgress * 100))])+ ? i18n.t('exportMenu.cancelProgress', [String(Math.round(doc.progress * 100))]): i18n.t('exportPreview.download', [label])}</Button>);@@ -328,7 +199,7 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s</div><div className="flex-1 flex flex-col overflow-hidden">- {videoSupported && (+ {video.supported && (<div className="shrink-0 flex items-center gap-1.5 px-3 py-2 border-b border-border">{modes.map(({ key, icon: Icon, label }) => (<button@@ -352,7 +223,7 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s<div className="flex-1 bg-[#3F3F46] relative overflow-hidden">{mode === 'document' ? (<>- {rendering && (+ {doc.rendering && (<div className="absolute top-3 right-3 z-10 flex items-center gap-1.5 text-[10px] text-muted-foreground bg-card border border-border rounded-full px-2.5 py-1"><Loader2 size={11} className="animate-spin" />{i18n.t('exportPreview.rendering')}@@ -360,7 +231,7 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s)}<iframetitle={i18n.t('exportPreview.title')}- srcDoc={preview}+ srcDoc={doc.html}onLoad={(event) => {const doc = event.currentTarget.contentDocument;if (doc) paginatePreview(doc);@@ -370,7 +241,7 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s</>) : (<div className="absolute inset-0 flex items-center justify-center">- {videoPending ? (+ {video.deferred ? (<div className="max-w-[340px] flex flex-col items-center gap-2 rounded-xl border border-border bg-card px-5 py-4 text-center"><Video size={20} className="text-accent" /><div className="text-[12px] font-semibold text-foreground">@@ -382,20 +253,20 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s<div className="text-[11px] text-muted-foreground leading-snug">{i18n.t('exportPreview.videoReadyHint')}</div>- <Button size="sm" className="mt-1" onClick={() => setVideoRequested(true)}>+ <Button size="sm" className="mt-1" onClick={video.request}>{i18n.t('exportPreview.videoGenerate')}</Button></div>- ) : videoError ? (+ ) : video.error ? (<div className="max-w-[320px] rounded-xl border border-border bg-card px-4 py-3 text-center"><div className="text-[12px] font-semibold text-foreground">{i18n.t('exportPreview.videoFailed')}</div>- <div className="mt-1 text-[11px] text-muted-foreground leading-snug">{videoError}</div>+ <div className="mt-1 text-[11px] text-muted-foreground leading-snug">{video.error}</div></div>- ) : videoUrl ? (+ ) : video.url ? (<Suspense fallback={null}>- <VideoStepPlayer key={videoUrl} src={videoUrl} type={videoType} chapters={videoChapters} />+ <VideoStepPlayer key={video.url} src={video.url} type={video.mime} chapters={video.chapters} /></Suspense>) : (<div className="flex flex-col items-center gap-2 bg-card border border-border rounded-xl px-4 py-3">@@ -403,11 +274,11 @@ export default function ExportPreviewModal({ open, onOpenChange, guide, steps, s<div className="h-1.5 w-40 overflow-hidden rounded-full bg-border"><divclassName="h-full rounded-full bg-accent transition-[width] duration-150"- style={{ width: `${Math.round(videoProgress * 100)}%` }}+ style={{ width: `${Math.round(video.progress * 100)}%` }}/></div><div className="text-[10px] font-semibold tabular-nums text-foreground">- {Math.round(videoProgress * 100)}%+ {Math.round(video.progress * 100)}%</div></div>)}diff --git a/packages/ui/src/fullview/GuideContent.tsx b/packages/ui/src/fullview/GuideContent.tsxindex a82e817..fb759f0 100644--- a/packages/ui/src/fullview/GuideContent.tsx+++ b/packages/ui/src/fullview/GuideContent.tsx@@ -21,7 +21,6 @@ import { formatDate } from '@mimik/ui/lib/utils';import AnnotationEditor from '@mimik/ui/shared/AnnotationEditor';import { useAskAi } from '@mimik/ui/shared/AskAi';import FaviconImg from '@mimik/ui/shared/FaviconImg';-import { guideDescriptionErrorMessage } from '@mimik/ui/shared/guide-description-error';import Toast from '@mimik/ui/shared/Toast';import { useFullview } from '@mimik/ui/stores/fullview';import { History, Loader2, Play, Sparkles } from 'lucide-react';@@ -29,6 +28,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { TypeAnimation } from 'react-type-animation';import GuideStepList from './components/GuideStepList';import VersionHistoryPanel from './components/VersionHistoryPanel';+import { useGuideDescription } from './use-guide-description';interface GuideContentProps {guideId: string;@@ -94,10 +94,10 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Guconst [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 applyDescription = useCallback((next: string) => {+ setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description: next } } : prev));+ }, []);+ const desc = useGuideDescription(guideId, applyDescription);const titleRef = useRef('');const appliedInitialRef = useRef(false);const editingDescriptionRef = useRef(false);@@ -106,7 +106,7 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Guconst result = await getGuide(guideId);if (result) {setData(result);- if (!editingDescriptionRef.current) setDescription(result.guide.description ?? '');+ if (!editingDescriptionRef.current) desc.set(result.guide.description ?? '');const newTitle = result.guide.title;const prev = titleRef.current;if (@@ -136,7 +136,7 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Gu}, [data, guideId, setGuideExportData]);useEffect(() => {- localStorage.get(['aiApiKey']).then((s) => setHasApiKey(Boolean(s.aiApiKey)));+ localStorage.get(['aiApiKey']).then((s) => desc.setHasApiKey(Boolean(s.aiApiKey)));}, []);const handleTitleBlur = useCallback(async () => {@@ -147,43 +147,14 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Gu}, [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));+ if (data && desc.text !== (data.guide.description ?? '')) {+ await updateGuideDescription(guideId, desc.text);+ setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description: desc.text } } : 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],- );+ }, [data, guideId, desc.text]);- const askAi = useAskAi(description, commitGuideDescription, hasApiKey);-- const handleGenerateDescription = useCallback(async () => {- setGenerating(true);- setDescriptionError(null);- try {- const result = await send('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 askAi = useAskAi(desc.text, desc.commit, desc.hasApiKey);const handleDescriptionChange = useCallback(async (stepId: string, description: string) => {await updateStepDescription(stepId, description, 'manual');@@ -299,7 +270,7 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Guconst animatingTitle = preview ? null : typingTitle;const untitledPending =!preview && !typingTitle && title === i18n.t('fullview_untitledGuide') && viewSteps.length > 0;- const metaGenerating = (untitledPending || animatingTitle !== null) && !description;+ const metaGenerating = (untitledPending || animatingTitle !== null) && !desc.text;return (<div className="flex flex-col min-h-[calc(100vh-64px)]">@@ -389,10 +360,10 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Guel.style.height = `${el.scrollHeight}px`;}}}- value={description}+ value={desc.text}rows={2}onChange={(e) => {- setDescription(e.target.value);+ desc.set(e.target.value);const el = e.target;el.style.height = '0';el.style.height = `${el.scrollHeight}px`;@@ -405,11 +376,11 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Guplaceholder={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 &&+ {desc.hasApiKey && <span className="shrink-0 mt-0.5">{askAi.trigger}</span>}+ {desc.hasApiKey &&(() => {- const busy = generating || metaGenerating;- const label = description+ const busy = desc.generating || metaGenerating;+ const label = desc.text? i18n.t('editor.regenerateDescription'): i18n.t('editor.generateDescription');return (@@ -419,7 +390,7 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Gutype="button"onClick={() => {if (busy) return;- void handleGenerateDescription();+ void desc.generate();}}aria-disabled={busy}aria-label={label}@@ -436,11 +407,11 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: Gu</Tooltip>);})()}- <Toast message={descriptionError} onDismiss={() => setDescriptionError(null)} />+ <Toast message={desc.error} onDismiss={desc.clearError} /></div>) : (- description && (- <p className="max-w-[720px] text-[15px] leading-relaxed text-muted-foreground">{description}</p>+ desc.text && (+ <p className="max-w-[720px] text-[15px] leading-relaxed text-muted-foreground">{desc.text}</p>))}</div>@@ -484,7 +455,7 @@ export default function GuideContent({ guideId, initialStepId, initialTool }: GuonOpenEditor={handleOpenEditor}onReorder={(newSteps) => setData((prev) => (prev ? { ...prev, steps: newSteps } : prev))}readOnly={!editing || preview !== null}- hasApiKey={hasApiKey}+ hasApiKey={desc.hasApiKey}onChanged={loadGuide}onInsertRecording={(targetGuideId, insertAtIndex, tabId) => {panel.open();diff --git a/packages/ui/src/fullview/use-guide-description.ts b/packages/ui/src/fullview/use-guide-description.tsnew file mode 100644index 0000000..e27d690--- /dev/null+++ b/packages/ui/src/fullview/use-guide-description.ts@@ -0,0 +1,63 @@+import { updateGuideDescription } from '@mimik/core/guides/service';+import { send } from '@mimik/ui/env';+import { guideDescriptionErrorMessage } from '@mimik/ui/shared/guide-description-error';+import { useCallback, useState } from 'react';++export interface GuideDescription {+ text: string;+ set: (next: string) => void;+ generating: boolean;+ error: string | null;+ hasApiKey: boolean;+ setHasApiKey: (has: boolean) => void;+ clearError: () => void;+ commit: (next: string) => void;+ generate: () => Promise<void>;+}++export function useGuideDescription(guideId: string, onWritten: (next: string) => void): GuideDescription {+ const [text, setText] = useState('');+ const [generating, setGenerating] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [hasApiKey, setHasApiKey] = useState(false);++ const commit = useCallback(+ (next: string) => {+ setText(next);+ void updateGuideDescription(guideId, next);+ onWritten(next);+ },+ [guideId, onWritten],+ );++ const generate = useCallback(async () => {+ setGenerating(true);+ setError(null);+ try {+ const result = await send('generateGuideDescription', { guideId });+ if (result.error) {+ setError(guideDescriptionErrorMessage(result.error));+ return;+ }+ if (!result.description) return;+ setText(result.description);+ onWritten(result.description);+ } catch {+ setError(guideDescriptionErrorMessage('generation-failed'));+ } finally {+ setGenerating(false);+ }+ }, [guideId, onWritten]);++ return {+ text,+ set: setText,+ generating,+ error,+ clearError: () => setError(null),+ hasApiKey,+ setHasApiKey,+ commit,+ generate,+ };+}diff --git a/packages/ui/src/fullview/use-guide-export.ts b/packages/ui/src/fullview/use-guide-export.tsnew file mode 100644index 0000000..54eb79f--- /dev/null+++ b/packages/ui/src/fullview/use-guide-export.ts@@ -0,0 +1,89 @@+import { downloadBlob, downloadText, safeFilename } from '@mimik/core/export/download';+import { exportGuideAsHTML } from '@mimik/core/export/html-export';+import type { ExportOptions } from '@mimik/core/export/options';+import { exportGuideAsPDF } from '@mimik/core/export/pdf-export';+import { withPreviewStyles } from '@mimik/core/export/preview';+import type { Guide, Screenshot, Step } from '@mimik/core/guides/types';+import { useEffect, useRef, useState } from 'react';++export type ExportFormat = 'docx' | 'gif' | 'html' | 'markdown' | 'pdf' | 'video';++export interface GuideExport {+ html: string;+ rendering: boolean;+ running: ExportFormat | null;+ progress: number;+ run: (format: ExportFormat) => Promise<void>;+ cancel: () => void;+}++interface Params {+ active: boolean;+ guide: Guide;+ steps: Step[];+ screenshots: Map<string, Screenshot>;+ options: ExportOptions;+}++export function useGuideExport({ active, guide, steps, screenshots, options }: Params): GuideExport {+ const [html, setHtml] = useState('');+ const [rendering, setRendering] = useState(false);+ const [running, setRunning] = useState<ExportFormat | null>(null);+ const [progress, setProgress] = useState(0);+ const abort = useRef<AbortController | null>(null);++ useEffect(() => {+ if (!active) return;+ let cancelled = false;+ setRendering(true);+ const timer = setTimeout(async () => {+ const built = await exportGuideAsHTML(guide, steps, screenshots, options);+ if (cancelled) return;+ setHtml(withPreviewStyles(built));+ setRendering(false);+ }, 200);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [active, guide, steps, screenshots, options]);++ const run = async (format: ExportFormat) => {+ setRunning(format);+ try {+ if (format === 'html') {+ const built = await exportGuideAsHTML(guide, steps, screenshots, options);+ downloadText(built, safeFilename(guide.title, 'html'), 'text/html');+ } else if (format === 'pdf') {+ downloadBlob(await exportGuideAsPDF(guide, steps, screenshots, options), safeFilename(guide.title, 'pdf'));+ } else if (format === 'docx') {+ const { exportGuideAsDOCX } = await import('@mimik/core/export/docx-export');+ downloadBlob(await exportGuideAsDOCX(guide, steps, screenshots, options), safeFilename(guide.title, 'docx'));+ } else if (format === 'markdown') {+ const { exportGuideAsMarkdown } = await import('@mimik/core/export/markdown-export');+ const md = await exportGuideAsMarkdown(guide, steps, screenshots);+ downloadText(md, safeFilename(guide.title, 'md'), 'text/markdown');+ } else {+ const controller = new AbortController();+ abort.current = controller;+ setProgress(0);+ const encode =+ format === 'gif'+ ? (await import('@mimik/core/export/gif-export')).exportGuideAsGif+ : (await import('@mimik/core/export/video-export')).exportGuideAsVideo;+ const built = await encode(guide, steps, screenshots, options, {+ signal: controller.signal,+ onProgress: (encoded, frames) => setProgress(frames > 0 ? encoded / frames : 0),+ });+ downloadBlob(built.blob, safeFilename(guide.title, built.extension));+ }+ } catch (error) {+ if (!(error instanceof DOMException && error.name === 'AbortError')) throw error;+ } finally {+ abort.current = null;+ setRunning(null);+ }+ };++ return { html, rendering, running, progress, run, cancel: () => abort.current?.abort() };+}diff --git a/packages/ui/src/fullview/use-video-preview.ts b/packages/ui/src/fullview/use-video-preview.tsnew file mode 100644index 0000000..821c4ec--- /dev/null+++ b/packages/ui/src/fullview/use-video-preview.ts@@ -0,0 +1,96 @@+import type { ExportOptions } from '@mimik/core/export/options';+import type { VideoChapter } from '@mimik/core/export/video-export';+import { canExportVideo } from '@mimik/core/export/video-support';+import type { Guide, Screenshot, Step } from '@mimik/core/guides/types';+import { useEffect, useState } from 'react';++import type { VideoMime } from './VideoStepPlayer';++const AUTOPLAY_STEP_LIMIT = 25;++export interface VideoPreview {+ supported: boolean;+ url: string | null;+ mime: VideoMime;+ chapters: VideoChapter[];+ progress: number;+ error: string | null;+ deferred: boolean;+ request: () => void;+}++interface Params {+ active: boolean;+ guide: Guide;+ steps: Step[];+ screenshots: Map<string, Screenshot>;+ options: ExportOptions;+}++export function useVideoPreview({ active, guide, steps, screenshots, options }: Params): VideoPreview {+ const [supported, setSupported] = useState(false);+ const [url, setUrl] = useState<string | null>(null);+ const [mime, setMime] = useState<VideoMime>('video/mp4');+ const [chapters, setChapters] = useState<VideoChapter[]>([]);+ const [progress, setProgress] = useState(0);+ const [error, setError] = useState<string | null>(null);+ const [requested, setRequested] = useState(false);++ const { cover, stepDescriptions, resolution } = options;+ const deferred = steps.length > AUTOPLAY_STEP_LIMIT && !requested;++ useEffect(() => {+ let alive = true;+ canExportVideo().then((can) => {+ if (alive) setSupported(can);+ });+ return () => {+ alive = false;+ };+ }, []);++ useEffect(() => {+ if (!active) setRequested(false);+ }, [active]);++ useEffect(() => {+ if (!active || deferred) return;+ const controller = new AbortController();+ let made: string | null = null;+ setError(null);+ setProgress(0);+ const timer = setTimeout(async () => {+ try {+ const { exportGuideAsVideo } = await import('@mimik/core/export/video-export');+ const built = await exportGuideAsVideo(+ guide,+ steps,+ screenshots,+ { cover, stepDescriptions, resolution },+ {+ signal: controller.signal,+ onProgress: (encoded, frames) => {+ if (!controller.signal.aborted) setProgress(frames > 0 ? encoded / frames : 0);+ },+ },+ );+ if (controller.signal.aborted) return;+ made = URL.createObjectURL(built.blob);+ setMime(built.blob.type === 'video/webm' ? 'video/webm' : 'video/mp4');+ setChapters(built.chapters);+ setUrl(made);+ } catch (err) {+ if (controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError')) return;+ setError(err instanceof Error ? err.message : String(err));+ }+ }, 200);+ return () => {+ controller.abort();+ clearTimeout(timer);+ if (made) URL.revokeObjectURL(made);+ setUrl(null);+ };+ }, [active, deferred, guide, steps, screenshots, cover, stepDescriptions, resolution]);++ return { supported, url, mime, chapters, progress, error, deferred, request: () => setRequested(true) };+}