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

feat(fullview): duplicate a guide from the library or the guide page

davbioa2b68086319f
diff --git a/src/ui/fullview/LibraryContent.tsx b/src/ui/fullview/LibraryContent.tsx
index fa4e20c..de55c44 100644
--- a/src/ui/fullview/LibraryContent.tsx
+++ b/src/ui/fullview/LibraryContent.tsx
@@ -10,6 +10,7 @@ import {
import { useCallback, useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
import {
+ duplicateGuide,
type GuideChangeEvent,
getFirstScreenshot,
getGuides,
@@ -23,6 +24,7 @@ import {
} from '@/core/guides/service';
import type { Guide, Screenshot } from '@/core/guides/types';
import { BUNDLE_EXTENSION } from '@/core/transfer/schema';
+import { logger } from '@/lib/logger';
import { useFullview } from '@/stores/fullview';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';
import ConfirmDeleteModal from './components/ConfirmDeleteModal';
@@ -178,6 +180,7 @@ export default function LibraryContent({ category }: LibraryContentProps) {
const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
const [importFile, setImportFile] = useState<File | null>(null);
const [dragging, setDragging] = useState(false);
+ const [duplicateFailed, setDuplicateFailed] = useState(false);
const sortRef = useRef<HTMLDivElement>(null);
const fileRef = useRef<HTMLInputElement>(null);
const dragDepth = useRef(0);
@@ -282,6 +285,19 @@ export default function LibraryContent({ category }: LibraryContentProps) {
await softDeleteGuide(id);
await loadGuides();
};
+ const handleDuplicate = async (e: React.MouseEvent, id: string) => {
+ e.stopPropagation();
+ setDuplicateFailed(false);
+ try {
+ if (!(await duplicateGuide(id))) throw new Error('guide not found');
+ } catch (err) {
+ logger.error(' Duplicate guide failed', err);
+ setDuplicateFailed(true);
+ return;
+ }
+ await loadGuides();
+ await refreshCounts();
+ };
const handleRestore = async (e: React.MouseEvent, id: string) => {
e.stopPropagation();
await restoreGuide(id);
@@ -401,6 +417,12 @@ export default function LibraryContent({ category }: LibraryContentProps) {
</Tooltip>
</div>
+ {duplicateFailed && (
+ <p role="alert" className="text-xs mb-3 text-center text-destructive">
+ {i18n.t('library_duplicateFailed')}
+ </p>
+ )}
+
{loading ? (
<p className="text-sm py-12 text-center text-purple">{i18n.t('common_loading')}</p>
) : allGuidesRef.current.length === 0 ? (
@@ -416,6 +438,7 @@ export default function LibraryContent({ category }: LibraryContentProps) {
onTrash={handleTrash}
onRestore={handleRestore}
onPermanentDelete={handlePermanentDelete}
+ onDuplicate={handleDuplicate}
/>
) : (
<GuideGridView
@@ -424,6 +447,7 @@ export default function LibraryContent({ category }: LibraryContentProps) {
onTrash={handleTrash}
onRestore={handleRestore}
onPermanentDelete={handlePermanentDelete}
+ onDuplicate={handleDuplicate}
/>
)}
diff --git a/src/ui/fullview/TopNav.tsx b/src/ui/fullview/TopNav.tsx
index 4b0c48f..f663a2f 100644
--- a/src/ui/fullview/TopNav.tsx
+++ b/src/ui/fullview/TopNav.tsx
@@ -1,6 +1,7 @@
import {
Check,
ChevronRight,
+ Copy,
Download,
FileText,
History,
@@ -10,9 +11,9 @@ import {
Star,
Trash2,
} from 'lucide-react';
-import { useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
-import { createSnapshot } from '@/core/guides/service';
+import { createSnapshot, duplicateGuide } from '@/core/guides/service';
import { logger } from '@/lib/logger';
import { useFullview } from '@/stores/fullview';
import { Button } from '@/ui/components/ui/button';
@@ -25,6 +26,10 @@ interface TopNavProps {
route: Route;
}
+// Long enough to swallow the tail of a fast multi-click, short enough that deliberately forking a
+// copy again is never blocked for a noticeable moment.
+const DUPLICATE_SETTLE_MS = 700;
+
const navItems = [
{ key: 'all' as const, labelKey: 'fullview_allGuides' as const, icon: FileText },
{ key: 'starred' as const, labelKey: 'fullview_starred' as const, icon: Star },
@@ -64,6 +69,32 @@ export default function TopNav({ route }: TopNavProps) {
hasTranscript: s.hasTranscript,
}));
const [exportOpen, setExportOpen] = useState(false);
+ const [duplicating, setDuplicating] = useState(false);
+ const settleTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => () => clearTimeout(settleTimer.current ?? undefined), []);
+
+ // Straight into the copy: the reason to duplicate a guide is to trim it down into a shorter one,
+ // and that work happens in the copy, not the original.
+ const handleDuplicate = async (guideId: string) => {
+ if (duplicating) return;
+ setDuplicating(true);
+ try {
+ const copyId = await duplicateGuide(guideId);
+ if (copyId) {
+ navigate({ page: 'guide', guideId: copyId });
+ // Hold the button disabled across the navigation. Copying takes a few milliseconds, so an
+ // in-flight guard alone is no guard at all: the button keeps its place while the page under
+ // it becomes the copy, and a second click of a fast double-click lands on the copy and forks
+ // *it*, chaining "Copy of Copy of…" for as long as the user keeps clicking.
+ settleTimer.current = setTimeout(() => setDuplicating(false), DUPLICATE_SETTLE_MS);
+ return;
+ }
+ } catch (err) {
+ logger.error(' Duplicate guide failed', err);
+ }
+ setDuplicating(false);
+ };
const toggleEditing = (guideId: string) => {
if (editing) {
@@ -169,10 +200,22 @@ export default function TopNav({ route }: TopNavProps) {
</Button>
)}
{!editing && (
- <Button size="sm" onClick={() => setExportOpen(true)} className="h-8 rounded-lg">
- <Download size={14} />
- {i18n.t('common.export')}
- </Button>
+ <>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={duplicating}
+ onClick={() => handleDuplicate(exportData.guideId)}
+ className={NAV_CONTROL}
+ >
+ <Copy size={14} />
+ {i18n.t('library.duplicate')}
+ </Button>
+ <Button size="sm" onClick={() => setExportOpen(true)} className="h-8 rounded-lg">
+ <Download size={14} />
+ {i18n.t('common.export')}
+ </Button>
+ </>
)}
<ExportPreviewModal
open={exportOpen}
diff --git a/src/ui/fullview/__tests__/topnav-duplicate.test.tsx b/src/ui/fullview/__tests__/topnav-duplicate.test.tsx
new file mode 100644
index 0000000..a642e02
--- /dev/null
+++ b/src/ui/fullview/__tests__/topnav-duplicate.test.tsx
@@ -0,0 +1,120 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen } from '@testing-library/react';
+import { act } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const duplicateGuide = vi.fn();
+const navigate = vi.fn();
+
+vi.mock('@/core/guides/service', () => ({
+ createSnapshot: vi.fn().mockResolvedValue(null),
+ duplicateGuide: (...args: unknown[]) => duplicateGuide(...args),
+}));
+
+vi.mock('../router', () => ({
+ navigate: (...args: unknown[]) => navigate(...args),
+}));
+
+vi.mock('../ExportPreviewModal', () => ({ default: () => null }));
+
+const storeState = {
+ counts: { all: 1, starred: 0, trash: 0 },
+ guideTitle: 'LONG ORIGINAL',
+ guideStepCount: 12,
+ guideExportData: { guideId: 'g1', guide: {}, steps: [], screenshots: new Map() },
+ setSearchOpen: vi.fn(),
+ editing: false,
+ setEditing: vi.fn(),
+ historyOpen: false,
+ setHistoryOpen: vi.fn(),
+ bumpHistoryRefresh: vi.fn(),
+ transcriptOpen: false,
+ setTranscriptOpen: vi.fn(),
+ hasTranscript: false,
+};
+
+vi.mock('@/stores/fullview', () => ({
+ useFullview: (selector: (s: typeof storeState) => unknown) => selector(storeState),
+}));
+
+import TopNav from '../TopNav';
+
+const route = { page: 'guide', guideId: 'g1' } as const;
+
+function duplicateButton(): HTMLButtonElement {
+ const btn = screen.getAllByRole('button').find((b) => /duplicat|duplicar|ε‰―ζœ¬|dupliz/i.test(b.textContent ?? ''));
+ if (!btn) throw new Error('Duplicate button not rendered');
+ return btn as HTMLButtonElement;
+}
+
+/** Lets the awaited duplicateGuide() resolve and React flush its state update. */
+async function settleMicrotasks() {
+ await act(async () => {
+ await Promise.resolve();
+ });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ duplicateGuide.mockReset().mockResolvedValue('copy-1');
+ navigate.mockReset();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('TopNav duplicate', () => {
+ it('navigates into the copy it just made', async () => {
+ render(<TopNav route={route} />);
+
+ fireEvent.click(duplicateButton());
+ await settleMicrotasks();
+
+ expect(duplicateGuide).toHaveBeenCalledWith('g1');
+ expect(navigate).toHaveBeenCalledWith({ page: 'guide', guideId: 'copy-1' });
+ });
+
+ it('makes one copy from a fast multi-click, not a chain of copies of copies', async () => {
+ render(<TopNav route={route} />);
+
+ // The first click navigates to the copy in a couple of milliseconds. Without a guard that
+ // outlives the navigation, the later clicks land on the copy's own Duplicate button and fork
+ // it again, so a triple-click leaves "Copy of Copy of Copy of ..." behind.
+ fireEvent.click(duplicateButton());
+ await settleMicrotasks();
+ fireEvent.click(duplicateButton());
+ fireEvent.click(duplicateButton());
+ await settleMicrotasks();
+
+ expect(duplicateGuide).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the button disabled across the navigation, then releases it', async () => {
+ render(<TopNav route={route} />);
+
+ fireEvent.click(duplicateButton());
+ await settleMicrotasks();
+ expect(duplicateButton().disabled).toBe(true);
+
+ await act(async () => {
+ vi.advanceTimersByTime(700);
+ });
+ expect(duplicateButton().disabled).toBe(false);
+
+ fireEvent.click(duplicateButton());
+ await settleMicrotasks();
+ expect(duplicateGuide).toHaveBeenCalledTimes(2);
+ });
+
+ it('re-enables immediately when the copy could not be made', async () => {
+ duplicateGuide.mockRejectedValue(new Error('boom'));
+ render(<TopNav route={route} />);
+
+ fireEvent.click(duplicateButton());
+ await settleMicrotasks();
+
+ expect(navigate).not.toHaveBeenCalled();
+ expect(duplicateButton().disabled).toBe(false);
+ });
+});
diff --git a/src/ui/fullview/components/GuideGridView.tsx b/src/ui/fullview/components/GuideGridView.tsx
index 4dac63c..1eec9d4 100644
--- a/src/ui/fullview/components/GuideGridView.tsx
+++ b/src/ui/fullview/components/GuideGridView.tsx
@@ -1,4 +1,4 @@
-import { MoreVertical, RotateCcw, Star, StarOff, Trash2 } from 'lucide-react';
+import { Copy, MoreVertical, RotateCcw, Star, StarOff, Trash2 } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { i18n } from '#imports';
import { formatDate } from '@/lib/utils';
@@ -12,6 +12,7 @@ interface GuideGridViewProps {
onTrash: (e: React.MouseEvent, id: string) => void;
onRestore: (e: React.MouseEvent, id: string) => void;
onPermanentDelete: (e: React.MouseEvent, id: string) => void;
+ onDuplicate: (e: React.MouseEvent, id: string) => void;
}
function MimikEyes() {
@@ -34,6 +35,7 @@ function CardMenu({
onTrash,
onRestore,
onPermanentDelete,
+ onDuplicate,
}: {
guideId: string;
starred: boolean;
@@ -42,6 +44,7 @@ function CardMenu({
onTrash: (e: React.MouseEvent, id: string) => void;
onRestore: (e: React.MouseEvent, id: string) => void;
onPermanentDelete: (e: React.MouseEvent, id: string) => void;
+ onDuplicate: (e: React.MouseEvent, id: string) => void;
}) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
@@ -89,6 +92,14 @@ function CardMenu({
setOpen(false);
},
});
+ items.push({
+ icon: <Copy size={13} />,
+ label: i18n.t('library_duplicate'),
+ onClick: (e) => {
+ onDuplicate(e, guideId);
+ setOpen(false);
+ },
+ });
items.push({
icon: <Trash2 size={13} />,
label: i18n.t('library_moveToTrash'),
@@ -134,7 +145,14 @@ function CardMenu({
);
}
-export default function GuideGridView({ category, onStar, onTrash, onRestore, onPermanentDelete }: GuideGridViewProps) {
+export default function GuideGridView({
+ category,
+ onStar,
+ onTrash,
+ onRestore,
+ onPermanentDelete,
+ onDuplicate,
+}: GuideGridViewProps) {
const { guides, thumbnails } = useFullview((s) => ({
guides: s.guides,
thumbnails: s.thumbnails,
@@ -178,6 +196,7 @@ export default function GuideGridView({ category, onStar, onTrash, onRestore, on
onTrash={onTrash}
onRestore={onRestore}
onPermanentDelete={onPermanentDelete}
+ onDuplicate={onDuplicate}
/>
</div>
</div>
diff --git a/src/ui/fullview/components/GuideListView.tsx b/src/ui/fullview/components/GuideListView.tsx
index 61571b5..a84ddac 100644
--- a/src/ui/fullview/components/GuideListView.tsx
+++ b/src/ui/fullview/components/GuideListView.tsx
@@ -1,4 +1,4 @@
-import { RotateCcw, Star, Trash2 } from 'lucide-react';
+import { Copy, RotateCcw, Star, Trash2 } from 'lucide-react';
import { i18n } from '#imports';
import { formatDate } from '@/lib/utils';
import { useFullview } from '@/stores/fullview';
@@ -11,9 +11,17 @@ interface GuideListViewProps {
onTrash: (e: React.MouseEvent, id: string) => void;
onRestore: (e: React.MouseEvent, id: string) => void;
onPermanentDelete: (e: React.MouseEvent, id: string) => void;
+ onDuplicate: (e: React.MouseEvent, id: string) => void;
}
-export default function GuideListView({ category, onStar, onTrash, onRestore, onPermanentDelete }: GuideListViewProps) {
+export default function GuideListView({
+ category,
+ onStar,
+ onTrash,
+ onRestore,
+ onPermanentDelete,
+ onDuplicate,
+}: GuideListViewProps) {
const { guides } = useFullview((s) => ({ guides: s.guides }));
return (
@@ -51,6 +59,17 @@ export default function GuideListView({ category, onStar, onTrash, onRestore, on
</TooltipTrigger>
<TooltipContent>{guide.starred ? i18n.t('common_unstar') : i18n.t('common_star')}</TooltipContent>
</Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ onClick={(e) => onDuplicate(e, guide.id)}
+ className="p-1.5 rounded-lg transition-colors text-purple hover:text-accent"
+ >
+ <Copy size={14} />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{i18n.t('library_duplicate')}</TooltipContent>
+ </Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<button