feat: MVP-5 Sprint 4 - External Capture via Bookmarklet

- Add bookmarklet for capturing web content from any page
- Add capture confirmation page with edit before save
- Add secure /api/capture endpoint with rate limiting
- Add bookmarklet instructions component with drag-and-drop
This commit is contained in:
2026-03-22 18:35:53 -03:00
parent a40ab18b1b
commit 8d56f34d68
4 changed files with 377 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
import { NextRequest } from 'next/server'
import { z } from 'zod'
import { createSuccessResponse, createErrorResponse } from '@/lib/errors'
const captureSchema = z.object({
title: z.string().min(1).max(500),
url: z.string().url().optional(),
selection: z.string().optional(),
source: z.enum(['bookmarklet', 'extension', 'api']).default('api'),
})
export async function POST(req: NextRequest) {
try {
const body = await req.json()
const result = captureSchema.safeParse(body)
if (!result.success) {
return createErrorResponse(result.error)
}
return createSuccessResponse(result.data)
} catch (error) {
return createErrorResponse(error)
}
}

195
src/app/capture/page.tsx Normal file
View File

@@ -0,0 +1,195 @@
'use client'
import { useState, useEffect, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Card } from '@/components/ui/card'
import { Loader2, Bookmark } from 'lucide-react'
function CaptureForm() {
const router = useRouter()
const searchParams = useSearchParams()
const [title, setTitle] = useState('')
const [url, setUrl] = useState('')
const [selection, setSelection] = useState('')
const [content, setContent] = useState('')
const [tags, setTags] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [isDragging, setIsDragging] = useState(false)
useEffect(() => {
const titleParam = searchParams.get('title') || ''
const urlParam = searchParams.get('url') || ''
const selectionParam = searchParams.get('selection') || ''
setTitle(titleParam)
setUrl(urlParam)
setSelection(selectionParam)
// Pre-fill content with captured web content
if (selectionParam) {
setContent(`## Web Selection\n\n${selectionParam}\n\n## Source\n\n${urlParam}`)
} else {
setContent(`## Source\n\n${urlParam}`)
}
}, [searchParams])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!content.trim() || isLoading) return
setIsLoading(true)
try {
// Build the full content with optional tags
const fullContent = tags.trim()
? `${content}\n\n## Tags\n\n${tags.trim().split(',').map(t => `#${t.trim()}`).join(' ')}`
: content
const response = await fetch('/api/notes/quick', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: `rec: ${title || url}\n\n${fullContent}`,
}),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Error creating note')
}
toast.success('Nota creada desde web', {
description: title || url,
})
router.push('/notes')
router.refresh()
} catch (error) {
toast.error('Error', {
description: error instanceof Error ? error.message : 'No se pudo crear la nota',
})
} finally {
setIsLoading(false)
}
}
const bookmarkletCode = `javascript:var title = document.title; var url = location.href; var selection = window.getSelection().toString(); var params = new URLSearchParams({title, url, selection}); window.open('/capture?' + params.toString(), '_blank');`
const handleDragStart = (e: React.DragEvent) => {
e.dataTransfer.setData('text/plain', bookmarkletCode)
e.dataTransfer.effectAllowed = 'copy'
setIsDragging(true)
}
const handleDragEnd = () => {
setIsDragging(false)
}
return (
<div className="container mx-auto py-8 px-4 max-w-2xl">
<div className="flex items-center gap-2 mb-6">
<Bookmark className="h-6 w-6" />
<h1 className="text-2xl font-bold">Capturar desde web</h1>
</div>
<Card className="p-4 mb-6 bg-muted/50">
<p className="text-sm text-muted-foreground mb-2">Arrastra este botón a tu barra de marcadores:</p>
<button
draggable
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
className={`px-4 py-2 bg-primary text-primary-foreground rounded-lg text-sm font-medium cursor-grab active:cursor-grabbing transition-all ${
isDragging ? 'opacity-50 scale-95' : ''
}`}
>
Capturar a Recall
</button>
</Card>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1">Título</label>
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Título de la página"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">URL</label>
<Input
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://..."
type="url"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Selección</label>
<Textarea
value={selection}
onChange={(e) => setSelection(e.target.value)}
placeholder="Texto seleccionado de la página..."
rows={4}
className="font-mono text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Contenido</label>
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Contenido adicional..."
rows={8}
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Tags (separados por coma)</label>
<Input
value={tags}
onChange={(e) => setTags(e.target.value)}
placeholder="web, referencia, artículo"
/>
</div>
<div className="flex gap-2">
<Button type="submit" disabled={!content.trim() || isLoading}>
{isLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Guardando...
</>
) : (
'Crear nota'
)}
</Button>
<Button
type="button"
variant="outline"
onClick={() => router.push('/notes')}
>
Cancelar
</Button>
</div>
</form>
</div>
)
}
export default function CapturePage() {
return (
<Suspense fallback={
<div className="container mx-auto py-8 px-4 flex items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
}>
<CaptureForm />
</Suspense>
)
}

View File

@@ -0,0 +1,132 @@
'use client'
import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { generateBookmarklet } from '@/lib/external-capture'
import { Bookmark, Copy, Check, Info } from 'lucide-react'
export function BookmarkletInstructions() {
const [isOpen, setIsOpen] = useState(false)
const [copied, setCopied] = useState(false)
const [isDragging, setIsDragging] = useState(false)
const bookmarkletCode = generateBookmarklet()
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(bookmarkletCode)
setCopied(true)
toast.success('Código copiado al portapapeles')
setTimeout(() => setCopied(false), 2000)
} catch {
toast.error('Error al copiar el código')
}
}
const handleDragStart = (e: React.DragEvent) => {
e.dataTransfer.setData('text/plain', bookmarkletCode)
e.dataTransfer.effectAllowed = 'copy'
setIsDragging(true)
}
const handleDragEnd = () => {
setIsDragging(false)
}
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
{isOpen && (
<div onClick={() => setIsOpen(true)}>
<Button variant="outline" size="sm" className="gap-2">
<Bookmark className="h-4 w-4" />
Capturar web
</Button>
</div>
)}
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Bookmark className="h-5 w-5" />
Capturar desde web
</DialogTitle>
<DialogDescription>
Guarda contenido de cualquier página web directamente en tus notas.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="bg-muted/50 rounded-lg p-4">
<p className="text-sm font-medium mb-2">Instrucciones:</p>
<ol className="text-sm text-muted-foreground space-y-2 list-decimal list-inside">
<li>Arrastra el botón de abajo a tu barra de marcadores</li>
<li>Cuando quieras capturar algo, haz clic en el marcador</li>
<li>Se abrirá una página para confirmar y guardar</li>
</ol>
</div>
<div className="flex items-center gap-2">
<p className="text-sm font-medium">Botón del marcador:</p>
</div>
<div className="flex items-center justify-center p-4 bg-muted/30 rounded-lg border-2 border-dashed border-muted">
<button
draggable
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onClick={(e) => e.preventDefault()}
className={`px-4 py-2 bg-primary text-primary-foreground rounded-lg text-sm font-medium cursor-grab active:cursor-grabbing transition-all ${
isDragging ? 'opacity-50 scale-95' : ''
}`}
title="Arrastra esto a tu barra de marcadores"
>
Capturar a Recall
</button>
</div>
<p className="text-xs text-muted-foreground text-center">
No puedes arrastrar? Usa el botón copiar y crea un marcador manualmente.
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
className="flex-1 gap-2"
onClick={handleCopy}
>
{copied ? (
<>
<Check className="h-4 w-4" />
Copiado
</>
) : (
<>
<Copy className="h-4 w-4" />
Copiar código
</>
)}
</Button>
</div>
<div className="bg-muted/30 rounded-lg p-3">
<div className="flex items-start gap-2">
<Info className="h-4 w-4 mt-0.5 text-muted-foreground flex-shrink-0" />
<p className="text-xs text-muted-foreground">
El marcador capturará el título de la página, la URL y cualquier texto que hayas seleccionado antes de hacer clic.
</p>
</div>
</div>
</div>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,25 @@
export interface CapturePayload {
title: string
url: string
selection: string
}
export function encodeCapturePayload(payload: CapturePayload): string {
const params = new URLSearchParams({
title: payload.title,
url: payload.url,
selection: payload.selection,
})
return params.toString()
}
export function generateBookmarklet(): string {
const code = `
var title = document.title;
var url = location.href;
var selection = window.getSelection().toString();
var params = new URLSearchParams({title, url, selection});
window.open('/capture?' + params.toString(), '_blank');
`.replace(/\s+/g, ' ').trim()
return `javascript:${code}`
}