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(editor): replace destructive blur canvas with re-editable annotation editor

Luis Ortiz5c73b2411e4d
diff --git a/src/ui/fullview/App.tsx b/src/ui/fullview/App.tsx
index 787cfca..31dc4e5 100644
--- a/src/ui/fullview/App.tsx
+++ b/src/ui/fullview/App.tsx
@@ -35,7 +35,7 @@ export default function FullViewApp() {
{route.page === 'guide' && (
<main className="flex-1 py-10 px-6">
<div className="max-w-[720px] mx-auto">
- <GuideContent guideId={route.guideId} />
+ <GuideContent guideId={route.guideId} initialStepId={route.stepId} initialTool={route.tool} />
</div>
</main>
)}
diff --git a/src/ui/fullview/GuideContent.tsx b/src/ui/fullview/GuideContent.tsx
index f0b9072..842b41c 100644
--- a/src/ui/fullview/GuideContent.tsx
+++ b/src/ui/fullview/GuideContent.tsx
@@ -2,25 +2,21 @@ import { Play } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { TypeAnimation } from 'react-type-animation';
import { i18n } from '#imports';
-import {
- deleteStep,
- getGuide,
- onGuidesChanged,
- updateGuideTitle,
- updateScreenshotBlob,
- updateStepDescription,
-} from '@/core/guides/service';
+import { deleteStep, getGuide, onGuidesChanged, updateGuideTitle, updateStepDescription } from '@/core/guides/service';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
+import type { ScreenshotEdits } from '@/core/screenshot/types';
import { openSidebar } from '@/lib/browser-api';
import { sendMessage } from '@/lib/messaging';
import { formatDate, getMostCommonDomain } from '@/lib/utils';
import { useFullview } from '@/stores/fullview';
+import AnnotationEditor from '@/ui/shared/AnnotationEditor';
import FaviconImg from '@/ui/shared/FaviconImg';
-import BlurCanvas from '@/ui/sidepanel/BlurCanvas';
import GuideStepList from './components/GuideStepList';
interface GuideContentProps {
guideId: string;
+ initialStepId?: string;
+ initialTool?: 'annotate' | 'redact' | 'crop';
}
interface GuideData {
@@ -29,19 +25,22 @@ interface GuideData {
screenshots: Map<string, Screenshot>;
}
-export default function GuideContent({ guideId }: GuideContentProps) {
- const { setGuideTitle, setGuideStepCount, setGuideExportData } = useFullview((s) => ({
+export default function GuideContent({ guideId, initialStepId, initialTool }: GuideContentProps) {
+ const { setGuideTitle, setGuideStepCount, setGuideExportData, scrollToStep } = useFullview((s) => ({
setGuideTitle: s.setGuideTitle,
setGuideStepCount: s.setGuideStepCount,
setGuideExportData: s.setGuideExportData,
+ scrollToStep: s.scrollToStep,
}));
const [data, setData] = useState<GuideData | null>(null);
const [loading, setLoading] = useState(true);
const [title, setTitle] = useState('');
const [typingTitle, setTypingTitle] = useState<string | null>(null);
- const [blurringStepId, setBlurringStepId] = useState<string | null>(null);
+ const [editingStepId, setEditingStepId] = useState<string | null>(null);
+ const [editingTool, setEditingTool] = useState<'annotate' | 'redact' | 'crop'>('annotate');
const titleRef = useRef('');
+ const appliedInitialRef = useRef(false);
const loadGuide = useCallback(async () => {
const result = await getGuide(guideId);
@@ -95,23 +94,38 @@ export default function GuideContent({ guideId }: GuideContentProps) {
[guideId, loadGuide],
);
- const handleBlurSave = useCallback(
- async (blob: Blob) => {
- if (!blurringStepId || !data) return;
- const screenshot = data.screenshots.get(blurringStepId);
+ const handleOpenEditor = useCallback((stepId: string, tool: 'annotate' | 'redact' | 'crop') => {
+ setEditingStepId(stepId);
+ setEditingTool(tool);
+ }, []);
+
+ const handleEditorDone = useCallback(
+ (edits: ScreenshotEdits) => {
+ if (!editingStepId || !data) return;
+ const screenshot = data.screenshots.get(editingStepId);
if (!screenshot) return;
- await updateScreenshotBlob(screenshot.id, blob);
setData((prev) => {
if (!prev) return prev;
const newScreenshots = new Map(prev.screenshots);
- newScreenshots.set(blurringStepId, { ...screenshot, blob });
+ newScreenshots.set(editingStepId, { ...screenshot, edits });
return { ...prev, screenshots: newScreenshots };
});
- setBlurringStepId(null);
+ setEditingStepId(null);
},
- [blurringStepId, data],
+ [editingStepId, data],
);
+ 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]);
+
if (loading)
return (
<div>
@@ -136,12 +150,17 @@ export default function GuideContent({ guideId }: GuideContentProps) {
if (!data) return <p className="text-sm py-12 text-center text-purple">{i18n.t('fullview_guideNotFound')}</p>;
const domain = getMostCommonDomain(data.steps);
- const blurScreenshot = blurringStepId ? data.screenshots.get(blurringStepId) : undefined;
+ const editingScreenshot = editingStepId ? data.screenshots.get(editingStepId) : undefined;
return (
<div className="flex flex-col min-h-[calc(100vh-64px)]">
- {blurringStepId && blurScreenshot && (
- <BlurCanvas screenshot={blurScreenshot} onSave={handleBlurSave} onCancel={() => setBlurringStepId(null)} />
+ {editingStepId && editingScreenshot && (
+ <AnnotationEditor
+ screenshot={editingScreenshot}
+ tool={editingTool}
+ onDone={handleEditorDone}
+ onCancel={() => setEditingStepId(null)}
+ />
)}
<div
@@ -233,7 +252,7 @@ export default function GuideContent({ guideId }: GuideContentProps) {
screenshots={data.screenshots}
onDescriptionChange={handleDescriptionChange}
onDelete={handleDeleteStep}
- onBlur={(stepId) => setBlurringStepId(stepId)}
+ onOpenEditor={handleOpenEditor}
onReorder={(newSteps) => setData((prev) => (prev ? { ...prev, steps: newSteps } : prev))}
/>
</div>
diff --git a/src/ui/fullview/components/GuideStepList.tsx b/src/ui/fullview/components/GuideStepList.tsx
index 523efdc..931ecc2 100644
--- a/src/ui/fullview/components/GuideStepList.tsx
+++ b/src/ui/fullview/components/GuideStepList.tsx
@@ -11,7 +11,7 @@ interface GuideStepListProps {
screenshots: Map<string, Screenshot>;
onDescriptionChange: (stepId: string, description: string) => void;
onDelete: (stepId: string) => void;
- onBlur: (stepId: string) => void;
+ onOpenEditor: (stepId: string, tool: 'annotate' | 'redact' | 'crop') => void;
onReorder: (newSteps: Step[]) => void;
}
@@ -21,7 +21,7 @@ export default function GuideStepList({
screenshots,
onDescriptionChange,
onDelete,
- onBlur,
+ onOpenEditor,
onReorder,
}: GuideStepListProps) {
const { scrollToStepId, setActiveStepId } = useFullview((s) => ({
@@ -93,7 +93,7 @@ export default function GuideStepList({
screenshot={screenshots.get(step.id)}
onDescriptionChange={onDescriptionChange}
onDelete={onDelete}
- onBlur={onBlur}
+ onOpenEditor={onOpenEditor}
dragHandleProps={{
onDragStart: (e: React.DragEvent) => {
setDragIndex(idx);
diff --git a/src/ui/fullview/router.ts b/src/ui/fullview/router.ts
index 832e8e2..83b5d6c 100644
--- a/src/ui/fullview/router.ts
+++ b/src/ui/fullview/router.ts
@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react';
-export type Route = { page: 'library'; category: 'all' | 'starred' | 'trash' } | { page: 'guide'; guideId: string };
+export type Route =
+ | { page: 'library'; category: 'all' | 'starred' | 'trash' }
+ | { page: 'guide'; guideId: string; stepId?: string; tool?: 'annotate' | 'redact' | 'crop' };
function parseHash(hash: string): Route {
const h = hash.replace(/^#\/?/, '');
@@ -28,8 +30,11 @@ export function useRoute(): 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 : undefined;
window.history.replaceState(null, '', `${window.location.pathname}#guide/${guideId}`);
- return { page: 'guide', guideId };
+ return { page: 'guide', guideId, stepId, tool };
}
return parseHash(window.location.hash);
});
diff --git a/src/ui/shared/AnnotationEditor.tsx b/src/ui/shared/AnnotationEditor.tsx
new file mode 100644
index 0000000..1682e7e
--- /dev/null
+++ b/src/ui/shared/AnnotationEditor.tsx
@@ -0,0 +1,526 @@
+import { ArrowUpRight, Check, Crop, EyeOff, MousePointer2, PenTool, Square, Type, X } from 'lucide-react';
+import type { ComponentType } 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 {
+ annotationBounds,
+ cropTo,
+ type Handle,
+ hitTest,
+ moveAnnotation,
+ resizeAnnotation,
+} from '@/core/screenshot/geometry';
+import type { Annotation, ScreenshotEdits } from '@/core/screenshot/types';
+
+type EditorTool = 'select' | 'box' | 'arrow' | 'text' | 'freehand' | 'redact' | 'crop';
+
+interface AnnotationEditorProps {
+ screenshot: Screenshot;
+ tool: 'annotate' | 'redact' | 'crop';
+ 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: 'draw'; start: { x: number; y: number }; shape: Annotation };
+
+const COLORS = ['#4F46E5', '#DC2626', '#059669', '#F59E0B', '#1E1B4B'];
+const DEFAULT_TEXT_SIZE = 28;
+const MIN_SHAPE_SIZE = 6;
+const MIN_CROP_SIZE = 20;
+const HANDLE_DISPLAY_SIZE = 10;
+const HANDLE_HIT_PX = 10;
+const DRAFT_ID = 'draft';
+
+const TOOLS: { id: EditorTool; icon: ComponentType<{ size?: number }>; labelKey: string }[] = [
+ { id: 'select', icon: MousePointer2, labelKey: 'annotationEditor.toolSelect' },
+ { id: 'box', icon: Square, labelKey: 'annotationEditor.toolBox' },
+ { id: 'arrow', icon: ArrowUpRight, labelKey: 'annotationEditor.toolArrow' },
+ { id: 'text', icon: Type, labelKey: 'annotationEditor.toolText' },
+ { id: 'freehand', icon: PenTool, labelKey: 'annotationEditor.toolFreehand' },
+ { id: 'redact', icon: EyeOff, labelKey: 'annotationEditor.toolRedact' },
+ { id: 'crop', icon: Crop, labelKey: 'annotationEditor.toolCrop' },
+];
+
+function initialToolFor(tool: 'annotate' | 'redact' | 'crop'): EditorTool {
+ if (tool === 'redact') return 'redact';
+ if (tool === 'crop') return 'crop';
+ return 'box';
+}
+
+function cursorFor(tool: EditorTool): string {
+ 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 isResizable(a: Annotation): boolean {
+ return a.type === 'box' || a.type === 'redact';
+}
+
+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;
+}
+
+function drawShape(ctx: CanvasRenderingContext2D, a: Annotation, alpha: number) {
+ ctx.save();
+ ctx.globalAlpha = alpha;
+ switch (a.type) {
+ case 'box':
+ ctx.strokeStyle = a.color;
+ ctx.lineWidth = 3;
+ ctx.strokeRect(a.x, a.y, a.w, a.h);
+ break;
+ case 'arrow': {
+ const head = 14;
+ const angle = Math.atan2(a.y2 - a.y1, a.x2 - a.x1);
+ ctx.strokeStyle = a.color;
+ ctx.fillStyle = a.color;
+ ctx.lineWidth = 3;
+ ctx.beginPath();
+ ctx.moveTo(a.x1, a.y1);
+ ctx.lineTo(a.x2, a.y2);
+ ctx.stroke();
+ ctx.beginPath();
+ ctx.moveTo(a.x2, a.y2);
+ ctx.lineTo(a.x2 - head * Math.cos(angle - Math.PI / 6), a.y2 - head * Math.sin(angle - Math.PI / 6));
+ ctx.lineTo(a.x2 - head * Math.cos(angle + Math.PI / 6), a.y2 - head * Math.sin(angle + Math.PI / 6));
+ ctx.closePath();
+ ctx.fill();
+ break;
+ }
+ case 'text':
+ ctx.fillStyle = a.color;
+ ctx.font = `600 ${a.size}px Poppins, sans-serif`;
+ ctx.fillText(a.text, a.x, a.y);
+ break;
+ case 'freehand':
+ ctx.strokeStyle = a.color;
+ ctx.lineWidth = 4;
+ ctx.lineJoin = 'round';
+ ctx.lineCap = 'round';
+ ctx.beginPath();
+ ctx.moveTo(a.points[0], a.points[1]);
+ for (let i = 2; i < a.points.length; i += 2) ctx.lineTo(a.points[i], a.points[i + 1]);
+ ctx.stroke();
+ break;
+ case 'redact':
+ if (a.style === 'solid') {
+ ctx.fillStyle = '#1E1B4B';
+ ctx.fillRect(a.x, a.y, a.w, a.h);
+ } else {
+ ctx.filter = 'blur(12px)';
+ ctx.drawImage(ctx.canvas, a.x, a.y, a.w, a.h, a.x, a.y, a.w, a.h);
+ }
+ break;
+ }
+ ctx.restore();
+}
+
+export default function AnnotationEditor({ screenshot, tool, onDone, onCancel }: AnnotationEditorProps) {
+ const [activeTool, setActiveTool] = useState<EditorTool>(initialToolFor(tool));
+ const [annotations, setAnnotations] = useState<Annotation[]>(screenshot.edits?.annotations ?? []);
+ const [viewport, setViewport] = useState<ScreenshotBounds | undefined>(screenshot.edits?.viewport);
+ const [selectedId, setSelectedId] = useState<string | null>(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 canvasRef = useRef<HTMLCanvasElement>(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();
+ setAnnotations((prev) => prev.filter((a) => a.id !== selectedId));
+ setSelectedId(null);
+ }
+ };
+ window.addEventListener('keydown', handler);
+ return () => window.removeEventListener('keydown', handler);
+ }, [selectedId]);
+
+ 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) drawShape(ctx, a, 1);
+ if (draft) drawShape(ctx, draft, 0.7);
+
+ const scale = getScale();
+
+ if (cropDraft) {
+ ctx.save();
+ ctx.strokeStyle = '#4F46E5';
+ ctx.lineWidth = 2 * scale;
+ ctx.setLineDash([6 * scale, 4 * scale]);
+ ctx.strokeRect(cropDraft.x, cropDraft.y, cropDraft.width, cropDraft.height);
+ ctx.restore();
+ }
+
+ const selected = annotations.find((a) => a.id === selectedId);
+ if (selected) {
+ const b = annotationBounds(selected);
+ ctx.save();
+ ctx.strokeStyle = '#4F46E5';
+ ctx.lineWidth = 2 * scale;
+ ctx.setLineDash([6 * scale, 4 * scale]);
+ ctx.strokeRect(b.x, b.y, b.width, b.height);
+ ctx.setLineDash([]);
+ if (isResizable(selected)) {
+ const handleSize = HANDLE_DISPLAY_SIZE * scale;
+ ctx.fillStyle = '#4F46E5';
+ 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]);
+
+ const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ const p = toImageSpace(e);
+
+ if (activeTool === 'select') {
+ const selected = annotations.find((a) => a.id === selectedId);
+ if (selected && isResizable(selected)) {
+ const b = annotationBounds(selected);
+ const handle = hitHandle(b, p.x, p.y, HANDLE_HIT_PX * getScale());
+ if (handle) {
+ dragRef.current = { mode: 'resize', id: selected.id, handle, lastX: p.x, lastY: p.y };
+ return;
+ }
+ }
+ const hit = hitTest(annotations, p.x, p.y);
+ if (hit) {
+ setSelectedId(hit.id);
+ dragRef.current = { mode: 'move', id: hit.id, lastX: p.x, lastY: p.y };
+ } else {
+ setSelectedId(null);
+ }
+ return;
+ }
+
+ if (activeTool === 'crop') {
+ const rect: ScreenshotBounds = { x: p.x, y: p.y, width: 0, height: 0 };
+ dragRef.current = { mode: 'crop', start: p, rect };
+ setCropDraft(rect);
+ return;
+ }
+
+ if (activeTool === 'text') {
+ const rect = canvasRef.current?.getBoundingClientRect();
+ setTextEditor({
+ x: p.x,
+ y: p.y + DEFAULT_TEXT_SIZE,
+ left: rect ? e.clientX - rect.left : 0,
+ top: rect ? e.clientY - rect.top : 0,
+ });
+ setTextValue('');
+ return;
+ }
+
+ let shape: Annotation;
+ if (activeTool === 'box') {
+ shape = { id: DRAFT_ID, type: 'box', x: p.x, y: p.y, w: 0, h: 0, color };
+ } else if (activeTool === 'arrow') {
+ shape = { id: DRAFT_ID, type: 'arrow', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color };
+ } else if (activeTool === 'freehand') {
+ shape = { id: DRAFT_ID, type: 'freehand', points: [p.x, p.y], color };
+ } else {
+ shape = { 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);
+ };
+
+ const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
+ const drag = dragRef.current;
+ if (!drag) return;
+ const p = toImageSpace(e);
+
+ if (drag.mode === 'move') {
+ const dx = p.x - drag.lastX;
+ const dy = p.y - drag.lastY;
+ drag.lastX = p.x;
+ drag.lastY = p.y;
+ setAnnotations((prev) => prev.map((a) => (a.id === drag.id ? moveAnnotation(a, dx, dy) : a)));
+ return;
+ }
+
+ if (drag.mode === 'resize') {
+ const dx = p.x - drag.lastX;
+ const dy = p.y - drag.lastY;
+ drag.lastX = p.x;
+ drag.lastY = p.y;
+ setAnnotations((prev) => prev.map((a) => (a.id === drag.id ? resizeAnnotation(a, drag.handle, dx, dy) : a)));
+ 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 === '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 = () => {
+ const drag = dragRef.current;
+ dragRef.current = null;
+ if (!drag) return;
+
+ if (drag.mode === 'crop') {
+ 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 }));
+ setActiveTool('select');
+ 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 === '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;
+ }
+ setAnnotations((prev) => [...prev, { ...shape, id: crypto.randomUUID() }]);
+ }
+ };
+
+ const handlePointerCancel = () => {
+ dragRef.current = null;
+ setDraft(null);
+ setCropDraft(null);
+ };
+
+ const handleColorSelect = (c: string) => {
+ setColor(c);
+ setAnnotations((prev) => prev.map((a) => (a.id === selectedId && a.type !== 'redact' ? { ...a, color: c } : a)));
+ };
+
+ const commitText = () => {
+ if (textEditor && textValue.trim()) {
+ setAnnotations((prev) => [
+ ...prev,
+ {
+ id: crypto.randomUUID(),
+ type: 'text',
+ x: textEditor.x,
+ y: textEditor.y,
+ text: textValue.trim(),
+ color,
+ size: DEFAULT_TEXT_SIZE,
+ },
+ ]);
+ }
+ setTextEditor(null);
+ setTextValue('');
+ };
+
+ const handleDone = async () => {
+ setSaving(true);
+ const nextEdits: ScreenshotEdits = { ...screenshot.edits, annotations };
+ if (viewport) nextEdits.viewport = viewport;
+ await updateScreenshotEdits(screenshot.id, nextEdits);
+ onDone(nextEdits);
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 bg-black/80 flex flex-col">
+ <div className="px-4 py-2.5 bg-primary flex items-center justify-between shrink-0">
+ <span className="text-xs font-medium text-primary-foreground">{i18n.t('annotationEditor.title')}</span>
+ <div className="flex items-center gap-1.5">
+ <button
+ type="button"
+ onClick={onCancel}
+ className="flex items-center gap-1 px-3 py-1.5 text-[11px] font-semibold text-primary-foreground rounded-lg border border-primary-foreground/10 bg-primary-foreground/[0.06] hover:bg-destructive/15 hover:text-destructive transition-colors"
+ >
+ <X size={12} />
+ {i18n.t('common.cancel')}
+ </button>
+ <button
+ type="button"
+ onClick={handleDone}
+ disabled={saving}
+ className="flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-primary bg-primary-foreground rounded-lg hover:bg-primary-foreground/90 transition-colors disabled:opacity-50"
+ >
+ <Check size={12} />
+ {i18n.t('annotationEditor.done')}
+ </button>
+ </div>
+ </div>
+ <div className="flex-1 flex overflow-hidden">
+ <div className="w-14 shrink-0 bg-card border-r border-border flex flex-col items-center gap-1.5 py-3 overflow-y-auto">
+ {TOOLS.map(({ id, icon: Icon, labelKey }) => (
+ <button
+ key={id}
+ type="button"
+ onClick={() => setActiveTool(id)}
+ title={i18n.t(labelKey)}
+ className={`flex items-center justify-center w-9 h-9 rounded-md transition-colors ${
+ activeTool === id
+ ? 'bg-accent text-primary-foreground'
+ : 'text-foreground hover:bg-secondary hover:text-accent'
+ }`}
+ >
+ <Icon size={16} />
+ </button>
+ ))}
+ <div className="w-8 h-px bg-border my-1.5" />
+ <fieldset
+ className="flex flex-col items-center gap-1.5 border-0 p-0 m-0"
+ aria-label={i18n.t('annotationEditor.colorLabel')}
+ >
+ {COLORS.map((c) => (
+ <button
+ key={c}
+ type="button"
+ onClick={() => handleColorSelect(c)}
+ title={c}
+ className={`w-6 h-6 rounded-full border-2 transition-colors ${color === c ? 'border-accent' : 'border-transparent'}`}
+ style={{ backgroundColor: c }}
+ />
+ ))}
+ </fieldset>
+ </div>
+ <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-140px)] rounded-lg shadow-2xl touch-none"
+ style={{ cursor: cursorFor(activeTool) }}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerCancel={handlePointerCancel}
+ />
+ {textEditor && (
+ <input
+ ref={(el) => el?.focus()}
+ 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-md border border-accent bg-card px-2 py-1 text-sm text-foreground outline-none"
+ style={{ left: textEditor.left, top: textEditor.top }}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/sidepanel/BlurCanvas.tsx b/src/ui/sidepanel/BlurCanvas.tsx
deleted file mode 100644
index 65f806e..0000000
--- a/src/ui/sidepanel/BlurCanvas.tsx
+++ /dev/null
@@ -1,243 +0,0 @@
-import { Check, EyeOff, Undo, X } from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
-import { i18n } from '#imports';
-import type { Screenshot } from '@/core/guides/types';
-
-interface BlurCanvasProps {
- screenshot: Screenshot;
- onSave: (blurredBlob: Blob) => void;
- onCancel: () => void;
-}
-
-interface Rect {
- x: number;
- y: number;
- w: number;
- h: number;
-}
-
-export default function BlurCanvas({ screenshot, onSave, onCancel }: BlurCanvasProps) {
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const [isDrawing, setIsDrawing] = useState(false);
- const [startPos, setStartPos] = useState({ x: 0, y: 0 });
- const [_currentPos, setCurrentPos] = useState({ x: 0, y: 0 });
- const [blurRects, setBlurRects] = useState<Rect[]>([]);
- const imgRef = useRef<HTMLImageElement | null>(null);
- const originalImageDataRef = useRef<ImageData | null>(null);
-
- useEffect(() => {
- const canvas = canvasRef.current;
- if (!canvas) return;
- const ctx = canvas.getContext('2d');
- if (!ctx) return;
-
- const url = URL.createObjectURL(screenshot.blob);
- const img = new Image();
- img.onload = () => {
- canvas.width = screenshot.width;
- canvas.height = screenshot.height;
- ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
- originalImageDataRef.current = ctx.getImageData(0, 0, canvas.width, canvas.height);
- imgRef.current = img;
- URL.revokeObjectURL(url);
- };
- img.src = url;
- }, [screenshot]);
-
- const applyBoxBlur = useCallback((ctx: CanvasRenderingContext2D, rect: Rect) => {
- const { x, y, w, h } = rect;
- if (w <= 0 || h <= 0) return;
-
- const canvasW = ctx.canvas.width;
- const canvasH = ctx.canvas.height;
-
- const x0 = Math.max(0, Math.round(x));
- const y0 = Math.max(0, Math.round(y));
- const x1 = Math.min(canvasW, Math.round(x + w));
- const y1 = Math.min(canvasH, Math.round(y + h));
- if (x1 <= x0 || y1 <= y0) return;
-
- const imageData = ctx.getImageData(x0, y0, x1 - x0, y1 - y0);
- const data = imageData.data;
- const rw = x1 - x0;
- const rh = y1 - y0;
- const radius = 10;
-
- const blurred = new Uint8ClampedArray(data.length);
- for (let py = 0; py < rh; py++) {
- for (let px = 0; px < rw; px++) {
- let r = 0,
- g = 0,
- b = 0,
- count = 0;
- for (let dy = -radius; dy <= radius; dy++) {
- for (let dx = -radius; dx <= radius; dx++) {
- const nx = px + dx;
- const ny = py + dy;
- if (nx >= 0 && nx < rw && ny >= 0 && ny < rh) {
- const idx = (ny * rw + nx) * 4;
- r += data[idx];
- g += data[idx + 1];
- b += data[idx + 2];
- count++;
- }
- }
- }
- const outIdx = (py * rw + px) * 4;
- blurred[outIdx] = r / count;
- blurred[outIdx + 1] = g / count;
- blurred[outIdx + 2] = b / count;
- blurred[outIdx + 3] = data[outIdx + 3];
- }
- }
- const blurredData = new ImageData(blurred, rw, rh);
- ctx.putImageData(blurredData, x0, y0);
- }, []);
-
- const redrawCanvas = useCallback(
- (rects: Rect[], previewRect?: Rect) => {
- const canvas = canvasRef.current;
- if (!canvas || !imgRef.current || !originalImageDataRef.current) return;
- const ctx = canvas.getContext('2d');
- if (!ctx) return;
-
- ctx.putImageData(originalImageDataRef.current, 0, 0);
-
- for (const rect of rects) {
- applyBoxBlur(ctx, rect);
- }
-
- if (previewRect && previewRect.w !== 0 && previewRect.h !== 0) {
- ctx.save();
- ctx.strokeStyle = 'rgba(79, 70, 229, 0.8)';
- ctx.lineWidth = 2;
- ctx.setLineDash([4, 4]);
- ctx.strokeRect(previewRect.x, previewRect.y, previewRect.w, previewRect.h);
- ctx.restore();
- }
- },
- [applyBoxBlur],
- );
-
- const getCanvasPos = (e: React.MouseEvent<HTMLCanvasElement>): { x: number; y: number } => {
- const canvas = canvasRef.current!;
- const rect = canvas.getBoundingClientRect();
- const scaleX = canvas.width / rect.width;
- const scaleY = canvas.height / rect.height;
- return {
- x: (e.clientX - rect.left) * scaleX,
- y: (e.clientY - rect.top) * scaleY,
- };
- };
-
- const onMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
- const pos = getCanvasPos(e);
- setIsDrawing(true);
- setStartPos(pos);
- setCurrentPos(pos);
- };
-
- const onMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
- if (!isDrawing) return;
- const pos = getCanvasPos(e);
- setCurrentPos(pos);
- const previewRect = {
- x: Math.min(startPos.x, pos.x),
- y: Math.min(startPos.y, pos.y),
- w: Math.abs(pos.x - startPos.x),
- h: Math.abs(pos.y - startPos.y),
- };
- redrawCanvas(blurRects, previewRect);
- };
-
- const onMouseUp = (e: React.MouseEvent<HTMLCanvasElement>) => {
- if (!isDrawing) return;
- setIsDrawing(false);
- const pos = getCanvasPos(e);
- const rect: Rect = {
- x: Math.min(startPos.x, pos.x),
- y: Math.min(startPos.y, pos.y),
- w: Math.abs(pos.x - startPos.x),
- h: Math.abs(pos.y - startPos.y),
- };
- if (rect.w > 2 && rect.h > 2) {
- const newRects = [...blurRects, rect];
- setBlurRects(newRects);
- redrawCanvas(newRects);
- }
- };
-
- const handleUndo = () => {
- const newRects = blurRects.slice(0, -1);
- setBlurRects(newRects);
- redrawCanvas(newRects);
- };
-
- const handleSave = () => {
- const canvas = canvasRef.current;
- if (!canvas) return;
- canvas.toBlob(
- (blob) => {
- if (blob) onSave(blob);
- },
- 'image/jpeg',
- 0.85,
- );
- };
-
- return (
- <div className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4">
- <div className="bg-card rounded-xl overflow-hidden flex flex-col max-w-full max-h-full shadow-2xl">
- <div className="px-4 py-2.5 bg-primary flex items-center justify-between">
- <div className="flex items-center gap-2.5">
- <span className="w-7 h-7 rounded-full bg-primary-foreground/10 flex items-center justify-center">
- <EyeOff size={14} className="text-primary-foreground" />
- </span>
- <span className="text-xs font-medium text-primary-foreground">{i18n.t('blurCanvas.drawInstructions')}</span>
- {blurRects.length > 0 && (
- <span className="text-[10px] font-semibold text-primary-foreground bg-primary-foreground/10 px-2 py-0.5 rounded-full">
- {blurRects.length !== 1
- ? i18n.t('blurCanvas.regionCountPlural', [String(blurRects.length)])
- : i18n.t('blurCanvas.regionCount', [String(blurRects.length)])}
- </span>
- )}
- </div>
- <div className="flex items-center gap-1.5">
- <button
- onClick={handleUndo}
- disabled={blurRects.length === 0}
- className="flex items-center gap-1 px-3 py-1.5 text-[11px] font-semibold text-primary-foreground rounded-lg border border-primary-foreground/10 bg-primary-foreground/[0.06] hover:bg-primary-foreground/15 disabled:opacity-30 transition-colors"
- >
- <Undo size={12} />
- {i18n.t('common.undo')}
- </button>
- <button
- onClick={onCancel}
- className="flex items-center gap-1 px-3 py-1.5 text-[11px] font-semibold text-primary-foreground rounded-lg border border-primary-foreground/10 bg-primary-foreground/[0.06] hover:bg-destructive/15 hover:text-destructive transition-colors"
- >
- <X size={12} />
- {i18n.t('common.cancel')}
- </button>
- <button
- onClick={handleSave}
- className="flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-primary bg-primary-foreground rounded-lg hover:bg-primary-foreground/90 transition-colors"
- >
- <Check size={12} />
- {i18n.t('common.save')}
- </button>
- </div>
- </div>
- <div className="overflow-auto">
- <canvas
- ref={canvasRef}
- onMouseDown={onMouseDown}
- onMouseMove={onMouseMove}
- onMouseUp={onMouseUp}
- className="block max-w-full cursor-crosshair"
- style={{ maxHeight: 'calc(100vh - 160px)' }}
- />
- </div>
- </div>
- </div>
- );
-}
diff --git a/src/ui/sidepanel/GuideEditor.tsx b/src/ui/sidepanel/GuideEditor.tsx
index b84eb7e..512f3a7 100644
--- a/src/ui/sidepanel/GuideEditor.tsx
+++ b/src/ui/sidepanel/GuideEditor.tsx
@@ -1,14 +1,7 @@
import { ArrowLeft, Layers, Maximize2, Play } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { i18n } from '#imports';
-import {
- deleteStep,
- getGuide,
- reorderSteps,
- updateGuideTitle,
- updateScreenshotBlob,
- updateStepDescription,
-} from '@/core/guides/service';
+import { deleteStep, getGuide, reorderSteps, updateGuideTitle, updateStepDescription } from '@/core/guides/service';
import type { Guide, Screenshot, Step } from '@/core/guides/types';
import { createTab, focusWindow, getExtensionURL, queryTabs, updateTab } from '@/lib/browser-api';
import { sendMessage } from '@/lib/messaging';
@@ -16,7 +9,6 @@ import { getMostCommonDomain } from '@/lib/utils';
import { Input } from '@/ui/components/ui/input';
import EmptyGuideState from '@/ui/shared/EmptyGuideState';
import FaviconImg from '@/ui/shared/FaviconImg';
-import BlurCanvas from './BlurCanvas';
import ExportMenu from './ExportMenu';
import StepCard from './StepCard';
@@ -39,7 +31,6 @@ export default function GuideEditor({ guideId, onBack, onGuideMe }: GuideEditorP
const [title, setTitle] = useState('');
const [dragIndex, setDragIndex] = useState<number | null>(null);
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
- const [blurringStepId, setBlurringStepId] = useState<string | null>(null);
const loadGuide = useCallback(async () => {
const result = await getGuide(guideId);
@@ -87,21 +78,22 @@ export default function GuideEditor({ guideId, onBack, onGuideMe }: GuideEditorP
[guideId, loadGuide],
);
- const handleBlurSave = useCallback(
- async (blob: Blob) => {
- if (!blurringStepId || !data) return;
- const blurScreenshot = data.screenshots.get(blurringStepId);
- if (!blurScreenshot) return;
- await updateScreenshotBlob(blurScreenshot.id, blob);
- setData((prev) => {
- if (!prev) return prev;
- const newScreenshots = new Map(prev.screenshots);
- newScreenshots.set(blurringStepId, { ...blurScreenshot, blob });
- return { ...prev, screenshots: newScreenshots };
+ const openInFullView = useCallback(
+ (targetGuideId: string, stepId?: string, tool?: 'annotate' | 'redact' | 'crop') => {
+ const params = new URLSearchParams({ guideId: targetGuideId });
+ if (stepId) params.set('stepId', stepId);
+ if (tool) params.set('tool', tool);
+ const url = getExtensionURL(`/fullview.html?${params.toString()}`);
+ queryTabs({ url: getExtensionURL('/fullview.html') }).then((tabs) => {
+ if (tabs.length > 0 && tabs[0].id) {
+ updateTab(tabs[0].id, { active: true, url });
+ if (tabs[0].windowId) focusWindow(tabs[0].windowId);
+ } else {
+ createTab({ url });
+ }
});
- setBlurringStepId(null);
},
- [blurringStepId, data],
+ [],
);
if (loading) return <p className="text-sm text-purple p-4">{i18n.t('common.loading')}</p>;
@@ -118,13 +110,8 @@ export default function GuideEditor({ guideId, onBack, onGuideMe }: GuideEditorP
);
}
- const blurScreenshot = blurringStepId ? data.screenshots.get(blurringStepId) : undefined;
-
return (
<div className="min-h-screen bg-card flex flex-col">
- {blurringStepId && blurScreenshot && (
- <BlurCanvas screenshot={blurScreenshot} onSave={handleBlurSave} onCancel={() => setBlurringStepId(null)} />
- )}
<div className="px-4 pt-3 pb-2">
<div className="flex items-center gap-2">
<button
@@ -141,17 +128,7 @@ export default function GuideEditor({ guideId, onBack, onGuideMe }: GuideEditorP
className="text-lg font-bold bg-transparent border-0 border-b border-transparent hover:border-border focus-visible:ring-0 focus-visible:border-accent shadow-none p-0 h-auto text-foreground"
/>
<button
- onClick={() => {
- const url = getExtensionURL(`/fullview.html?guideId=${guideId}`);
- queryTabs({ url: getExtensionURL('/fullview.html') }).then((tabs) => {
- if (tabs.length > 0 && tabs[0].id) {
- updateTab(tabs[0].id, { active: true, url: getExtensionURL(`/fullview.html?guideId=${guideId}`) });
- if (tabs[0].windowId) focusWindow(tabs[0].windowId);
- } else {
- createTab({ url });
- }
- });
- }}
+ onClick={() => openInFullView(guideId)}
className="shrink-0 p-1.5 rounded-md transition-colors text-purple hover:text-accent hover:bg-secondary"
title={i18n.t('library.openInFullView')}
>
@@ -208,7 +185,7 @@ export default function GuideEditor({ guideId, onBack, onGuideMe }: GuideEditorP
screenshot={data.screenshots.get(step.id)}
onDescriptionChange={handleDescriptionChange}
onDelete={handleDeleteStep}
- onBlur={(stepId) => setBlurringStepId(stepId)}
+ onOpenEditor={(stepId, tool) => openInFullView(guideId, stepId, tool)}
dragHandleProps={{
onDragStart: (e: React.DragEvent) => {
setDragIndex(idx);
diff --git a/src/ui/sidepanel/StepCard.tsx b/src/ui/sidepanel/StepCard.tsx
index a343fac..a7169f4 100644
--- a/src/ui/sidepanel/StepCard.tsx
+++ b/src/ui/sidepanel/StepCard.tsx
@@ -1,4 +1,4 @@
-import { Check, Copy, EyeOff, Trash2 } from 'lucide-react';
+import { Check, Copy, Trash2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import { i18n } from '#imports';
import type { Screenshot, Step } from '@/core/guides/types';
@@ -17,7 +17,7 @@ interface StepCardProps {
onDescriptionChange: (stepId: string, description: string) => void;
onDelete: (stepId: string) => void;
dragHandleProps?: DragHandleProps;
- onBlur?: (stepId: string) => void;
+ onOpenEditor?: (stepId: string, tool: 'annotate' | 'redact' | 'crop') => void;
onCopy?: (stepId: string) => void;
}
@@ -27,7 +27,7 @@ export default function StepCard({
onDescriptionChange,
onDelete,
dragHandleProps,
- onBlur,
+ onOpenEditor,
}: StepCardProps) {
const [description, setDescription] = useState(step.description);
const [dragOver, setDragOver] = useState(false);
@@ -81,6 +81,7 @@ export default function StepCard({
alt={`Step ${step.index + 1} screenshot`}
className="!rounded-none !border-0"
crop
+ onOpenEditor={onOpenEditor ? (tool) => onOpenEditor(step.id, tool) : undefined}
/>
) : (
<div className="w-full h-32 flex items-center justify-center text-sm bg-secondary text-purple">
@@ -104,22 +105,13 @@ export default function StepCard({
<div className="flex items-center justify-end mt-1">
<div className="flex items-center gap-0.5">
{screenshot && (
- <>
- <button
- onClick={() => onBlur?.(step.id)}
- className="p-1 rounded-md transition-colors text-border hover:text-accent"
- title={i18n.t('editor.blurSensitiveArea')}
- >
- <EyeOff size={13} />
- </button>
- <button
- onClick={handleCopy}
- className={`p-1 rounded-md transition-colors ${copied ? 'text-success' : 'text-border hover:text-success'}`}
- title={i18n.t('editor.copyScreenshot')}
- >
- {copied ? <Check size={13} /> : <Copy size={13} />}
- </button>
- </>
+ <button
+ onClick={handleCopy}
+ className={`p-1 rounded-md transition-colors ${copied ? 'text-success' : 'text-border hover:text-success'}`}
+ title={i18n.t('editor.copyScreenshot')}
+ >
+ {copied ? <Check size={13} /> : <Copy size={13} />}
+ </button>
)}
<button
onClick={handleDelete}