import { useState, useEffect, useCallback, useRef } from 'react'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, } from '@/components/ui/dialog'; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; import { Label } from '@/components/ui/label'; import { Skeleton } from '@/components/ui/skeleton'; import { Badge } from '@/components/ui/badge'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'; import { useToast } from '@/hooks/useToast'; import { useFS } from '@/hooks/useFS'; import { useFSPaths } from '@/hooks/useFSPaths'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNostrPublish } from '@/hooks/useNostrPublish'; import { useUploadFile } from '@/hooks/useUploadFile'; import { useAppEvent } from '@/hooks/useAppEvent'; import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings'; import { useQueryClient } from '@tanstack/react-query'; import { DotAI } from '@/lib/DotAI'; import { buildAppEvent } from '@/lib/appEvent'; import { Loader2, Save, Plus, X, ExternalLink, Pencil, ChevronDown, CircleHelp, } from 'lucide-react'; import type { NostrEvent } from '@nostrify/nostrify'; interface AppDialogProps { projectId: string; open: boolean; onOpenChange: (open: boolean) => void; } interface AppFormData { name: string; about: string; picture: string; banner: string; website: string; dTag: string; tTags: string[]; supportedKinds: string[]; webHandlers: Array<{ url: string; type: string }>; } /** Parse a kind 31990 event into form data */ function eventToFormData(event: NostrEvent): AppFormData { let metadata: Record = {}; try { if (event.content) { metadata = JSON.parse(event.content); } } catch { // Invalid JSON content, use empty metadata } const dTag = event.tags.find(([t]) => t === 'd')?.[1] ?? ''; const supportedKinds = event.tags .filter(([t]) => t === 'k') .map(([, v]) => v) .filter(Boolean); const webHandlers = event.tags .filter(([t]) => t === 'web') .map(([, url, type]) => ({ url: url ?? '', type: type ?? '' })); const tTags = event.tags .filter(([t]) => t === 't') .map(([, v]) => v) .filter(Boolean); return { name: metadata.name ?? '', about: metadata.about ?? '', picture: metadata.picture ?? '', banner: metadata.banner ?? '', website: metadata.website ?? '', dTag, tTags, supportedKinds, webHandlers, }; } /** Convert a slug like "my-cool-app" to title case like "My Cool App" */ function toTitleCase(slug: string): string { return slug .replace(/[-_]+/g, ' ') .replace(/\b\w/g, (c) => c.toUpperCase()) .trim(); } /** Create empty form data for a new app */ function emptyFormData(projectId: string): AppFormData { return { name: toTitleCase(projectId), about: '', picture: '', banner: '', website: '', dTag: projectId, tTags: [], supportedKinds: [], webHandlers: [], }; } /** Read a file from VFS as a UTF-8 string, returning null if it doesn't exist. */ async function readVfsText(fs: { readFile(path: string, options: { encoding: string }): Promise }, path: string): Promise { try { return await fs.readFile(path, { encoding: 'utf8' }); } catch { return null; } } /** Extract OG/meta tag content from HTML text. */ function parseMetaContent(html: string, property: string): string | null { const re = new RegExp(`]+(?:property|name)=["']${property}["'][^>]+content=["']([^"']+)["']`, 'i'); const alt = new RegExp(`]+content=["']([^"']+)["'][^>]+(?:property|name)=["']${property}["']`, 'i'); return (re.exec(html) ?? alt.exec(html))?.[1] ?? null; } /** Scrape autofill candidates from the project's built output and source files. */ async function scrapeProjectMeta( fs: { readFile(path: string, options: { encoding: string }): Promise }, cwd: string, ): Promise> { const result: Partial<{ name: string; about: string; picture: string; banner: string }> = {}; // 1. Try dist/index.html for OG tags const html = await readVfsText(fs, `${cwd}/dist/index.html`); if (html) { const ogTitle = parseMetaContent(html, 'og:title'); const ogDesc = parseMetaContent(html, 'og:description') ?? parseMetaContent(html, 'description'); const ogImage = parseMetaContent(html, 'og:image'); const ogBanner = parseMetaContent(html, 'og:image:banner') ?? parseMetaContent(html, 'twitter:image'); if (ogTitle) result.name = ogTitle; if (ogDesc) result.about = ogDesc; if (ogImage) result.picture = ogImage; if (ogBanner) result.banner = ogBanner; } // 2. Try web manifest for name, description, and icons const manifestPaths = [ `${cwd}/public/manifest.webmanifest`, `${cwd}/public/manifest.json`, `${cwd}/dist/manifest.webmanifest`, `${cwd}/dist/manifest.json`, ]; for (const path of manifestPaths) { const text = await readVfsText(fs, path); if (!text) continue; try { const manifest = JSON.parse(text); if (!result.name && (manifest.name || manifest.short_name)) { result.name = manifest.name ?? manifest.short_name; } if (!result.about && manifest.description) { result.about = manifest.description; } if (!result.picture && Array.isArray(manifest.icons) && manifest.icons.length > 0) { // Prefer the largest icon const sorted = [...manifest.icons].sort((a, b) => { const sizeA = parseInt(a.sizes?.split('x')[0] ?? '0'); const sizeB = parseInt(b.sizes?.split('x')[0] ?? '0'); return sizeB - sizeA; }); const iconSrc = sorted[0]?.src; if (iconSrc) { // If it's an absolute URL use it directly, otherwise it's a relative VFS path result.picture = iconSrc.startsWith('http') ? iconSrc : iconSrc; } } break; } catch { // Invalid JSON, try next } } return result; } export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) { const { fs } = useFS(); const { projectsPath } = useFSPaths(); const { user } = useCurrentUser(); const { toast } = useToast(); const queryClient = useQueryClient(); const { mutateAsync: publishEvent } = useNostrPublish(); const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile(); const cwd = `${projectsPath}/${projectId}`; const { event, isLoading, aTag, hasApp, refetch } = useAppEvent({ cwd }); const { settings: deploySettings, isLoading: isDeployLoading } = useProjectDeploySettings(projectId); const [formData, setFormData] = useState(emptyFormData(projectId)); const [isSaving, setIsSaving] = useState(false); const [submitted, setSubmitted] = useState(false); const [confirmDelete, setConfirmDelete] = useState(false); const [newTag, setNewTag] = useState(''); const [newKind, setNewKind] = useState(''); const [newHandlerUrl, setNewHandlerUrl] = useState(''); const [newHandlerType, setNewHandlerType] = useState(''); const [advancedOpen, setAdvancedOpen] = useState(false); const fileInputRef = useRef(null); const bannerFileInputRef = useRef(null); // Get the deployed URL from project deploy settings const deployedUrl = (() => { if (!deploySettings?.currentProvider || !deploySettings?.providers) return null; const config = deploySettings.providers[deploySettings.currentProvider]; return config?.url ?? null; })(); // Populate form when event loads useEffect(() => { if (event) { setFormData(eventToFormData(event)); } else if (!isLoading && !hasApp) { setFormData(emptyFormData(projectId)); } }, [event, isLoading, hasApp, projectId]); // Auto-fill website from deployment URL when creating a new app (not editing existing) useEffect(() => { if (!hasApp && !isDeployLoading && deployedUrl && !formData.website) { setFormData(prev => ({ ...prev, website: deployedUrl })); } }, [hasApp, isDeployLoading, deployedUrl, formData.website]); // Auto-fill form from OG tags / web manifest when opening for the first time useEffect(() => { if (!open || hasApp || isLoading) return; scrapeProjectMeta(fs, cwd).then(meta => { setFormData(prev => ({ ...prev, name: prev.name && prev.name !== toTitleCase(projectId) ? prev.name : (meta.name ?? prev.name), about: prev.about || meta.about || '', picture: prev.picture || meta.picture || '', banner: prev.banner || meta.banner || '', })); }).catch(() => {/* silently ignore */}); }, [open, hasApp, isLoading]); // eslint-disable-line react-hooks/exhaustive-deps const updateField = useCallback((key: K, value: AppFormData[K]) => { setFormData(prev => ({ ...prev, [key]: value })); }, []); const addTag = useCallback(() => { const tag = newTag.trim().toLowerCase(); if (tag && !formData.tTags.includes(tag)) { updateField('tTags', [...formData.tTags, tag]); setNewTag(''); } }, [newTag, formData.tTags, updateField]); const removeTag = useCallback((tag: string) => { updateField('tTags', formData.tTags.filter(t => t !== tag)); }, [formData.tTags, updateField]); const addKind = useCallback(() => { const kind = newKind.trim(); if (kind && !formData.supportedKinds.includes(kind)) { updateField('supportedKinds', [...formData.supportedKinds, kind]); setNewKind(''); } }, [newKind, formData.supportedKinds, updateField]); const removeKind = useCallback((kind: string) => { updateField('supportedKinds', formData.supportedKinds.filter(k => k !== kind)); }, [formData.supportedKinds, updateField]); const addHandler = useCallback(() => { const url = newHandlerUrl.trim(); if (url) { updateField('webHandlers', [...formData.webHandlers, { url, type: newHandlerType.trim() }]); setNewHandlerUrl(''); setNewHandlerType(''); } }, [newHandlerUrl, newHandlerType, formData.webHandlers, updateField]); const removeHandler = useCallback((index: number) => { updateField('webHandlers', formData.webHandlers.filter((_, i) => i !== index)); }, [formData.webHandlers, updateField]); const handleBannerUpload = useCallback(async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; try { const tags = await uploadFile(file); const url = tags[0]?.[1]; if (url) { updateField('banner', url); toast({ title: 'Banner uploaded', description: 'Your app banner has been uploaded.' }); } } catch (error) { toast({ title: 'Upload failed', description: error instanceof Error ? error.message : 'Failed to upload banner.', variant: 'destructive', }); } finally { if (bannerFileInputRef.current) { bannerFileInputRef.current.value = ''; } } }, [uploadFile, updateField, toast]); const handleIconUpload = useCallback(async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; try { const tags = await uploadFile(file); const url = tags[0]?.[1]; if (url) { updateField('picture', url); toast({ title: 'Icon uploaded', description: 'Your app icon has been uploaded.' }); } } catch (error) { toast({ title: 'Upload failed', description: error instanceof Error ? error.message : 'Failed to upload icon.', variant: 'destructive', }); } finally { // Reset input so re-selecting the same file triggers onChange if (fileInputRef.current) { fileInputRef.current.value = ''; } } }, [uploadFile, updateField, toast]); const handleSave = async () => { if (!user) { toast({ title: 'Not logged in', description: 'You must be logged in with Nostr to publish an app.', variant: 'destructive', }); return; } setSubmitted(true); if (!formData.name.trim() || !formData.about.trim() || !formData.website.trim() || !formData.picture.trim() || !formData.banner.trim()) { return; } if (!formData.dTag.trim()) { toast({ title: 'Identifier required', description: 'Please enter a unique identifier (d-tag) for your app.', variant: 'destructive', }); return; } setIsSaving(true); try { // Build event content and tags const { content, tags } = await buildAppEvent( { name: formData.name, about: formData.about, picture: formData.picture, banner: formData.banner, website: formData.website, dTag: formData.dTag, tTags: formData.tTags, supportedKinds: formData.supportedKinds, webHandlers: formData.webHandlers, }, { fs, cwd, pubkey: user.pubkey }, ); // Publish the event const published = await publishEvent({ kind: 31990, content, tags, }); // Store the "a" coordinate in .git/shakespeare/app.json const aValue = `31990:${published.pubkey}:${formData.dTag.trim()}`; const dotAI = new DotAI(fs, cwd); await dotAI.writeAppConfig({ a: aValue }); // Invalidate queries await queryClient.invalidateQueries({ queryKey: ['app-event'] }); await refetch(); toast({ title: hasApp ? 'App updated' : 'App published', description: `"${formData.name}" has been ${hasApp ? 'updated' : 'published'} to Nostr.`, }); onOpenChange(false); } catch (error) { console.error('Failed to publish app:', error); toast({ title: 'Failed to publish', description: error instanceof Error ? error.message : 'An unexpected error occurred', variant: 'destructive', }); } finally { setIsSaving(false); } }; const handleDelete = async () => { if (!event) return; setIsSaving(true); try { // Publish NIP-09 deletion event await publishEvent({ kind: 5, content: 'Deleted app', tags: [['e', event.id], ['a', `31990:${event.pubkey}:${formData.dTag}`]], }); // Remove the local app config const dotAI = new DotAI(fs, cwd); await dotAI.writeAppConfig({ a: '' }); await queryClient.invalidateQueries({ queryKey: ['app-event'] }); toast({ title: 'App deleted', description: `"${formData.name}" has been deleted.` }); onOpenChange(false); } catch (error) { toast({ title: 'Failed to delete', description: error instanceof Error ? error.message : 'An unexpected error occurred', variant: 'destructive', }); } finally { setIsSaving(false); setConfirmDelete(false); } }; if (!user) { return ( App

You must be logged in with Nostr to manage your app.

); } return ( {hasApp ? 'Edit App' : 'Publish App'} {hasApp ? 'Update your app\'s listing on Nostr.' : 'Publish your project as a Nostr app.'} {isLoading ? (
) : (
{/* App Preview Card — banner + overlapping icon */}
{/* Hidden file inputs */} {/* Banner */}
!isSaving && !isUploading && bannerFileInputRef.current?.click()} > {!formData.banner && (
)} {!formData.banner && (
)}
{isUploading ? : } {formData.banner ? 'Change banner' : 'Add banner'}
{formData.banner && (
)}
{/* Icon + Name/Description */}
{/* Icon overlapping banner */}
!isSaving && !isUploading && fileInputRef.current?.click()}> {formData.picture ? null : }
{/* Name & Description */}
updateField('name', e.target.value)} placeholder="App Name" disabled={isSaving} className={submitted && !formData.name.trim() ? 'border-destructive focus-visible:ring-destructive' : ''} />