import { useRef, useState, type FormEvent } from 'react' import { ApiError } from '@/api/client' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Button } from '@/components/ui/button' interface SourceFeedsEditorProps { sourceId: string sourceKey: string sourceName: string urls: string[] disabled?: boolean onSave: (urls: string[]) => Promise } const FEED_PATHS: Record = { bloomberg: ['bloomberg-latest', 'bloomberg-economics', 'bloomberg-technology', 'bloomberg-politics', 'bloomberg-technology-ai'], investing_com: ['investing-news'], } function validateUrl(value: string, sourceKey: string): string | null { try { if (value !== value.trim() || value.length > 256) return null const path = /^https:\/\/[^/?#]+(\/[^?#]*)$/.exec(value)?.[1] const url = new URL(value) if (url.protocol !== 'https:' || url.hostname !== 'feed.quanwenrss.com' || url.port || url.username || url.password || value.includes('#') || value.includes('?') || !Object.prototype.hasOwnProperty.call(FEED_PATHS, sourceKey) || !FEED_PATHS[sourceKey].some(name => path === `/feed/${name}.xml` && url.pathname === path)) return null return url.href } catch { return null } } export function SourceFeedsEditor({ sourceId, sourceKey, sourceName, urls, onSave, disabled = false }: SourceFeedsEditorProps) { const [rows, setRows] = useState(() => urls.map((url, id) => ({ id, url }))) const [errors, setErrors] = useState>({}) const [error, setError] = useState('') const [saving, setSaving] = useState(false) const [saved, setSaved] = useState(false) const nextId = useRef(urls.length) const fields = useRef(new Map()) const addButton = useRef(null) function clearMessages() { setErrors({}); setError(''); setSaved(false) } function focusRow(id?: number) { setTimeout(() => { const field = id === undefined ? undefined : fields.current.get(id) if (field) field.focus() else addButton.current?.focus() }, 0) } function add() { const id = nextId.current++ setRows(current => [...current, { id, url: '' }]); clearMessages(); focusRow(id) } function remove(id: number, index: number) { const remaining = rows.filter(row => row.id !== id) setRows(remaining); clearMessages(); focusRow(remaining[Math.min(index, remaining.length - 1)]?.id) } async function save(event: FormEvent) { event.preventDefault() if (saving || disabled) return clearMessages() if (!rows.length) { setError('Ajoutez au moins un flux RSS pour enregistrer.'); return } const invalid: Record = {} const normalized: string[] = [] for (const row of rows) { const url = validateUrl(row.url, sourceKey) if (!row.url.trim()) invalid[row.id] = 'Saisissez une URL de flux RSS.' else if (!url) invalid[row.id] = 'Utilisez une URL RSS HTTPS autorisée pour cette source, sans identifiants, paramètres ni fragment.' else if (normalized.includes(url)) invalid[row.id] = 'Ce flux RSS est déjà présent. Retirez le doublon ou modifiez son URL.' if (url) normalized.push(url) } if (Object.keys(invalid).length) { setErrors(invalid); focusRow(rows.find(row => invalid[row.id])?.id); return } setSaving(true) try { await onSave(normalized); setSaved(true) } catch (error) { if (error instanceof ApiError && error.status === 400 && ['source_feeds_invalid', 'source_feeds_not_supported', 'source_configuration_invalid'].includes(error.message)) { setError('Les flux RSS ont été refusés. Vérifiez les adresses autorisées et les doublons. Votre saisie est conservée.') } else { setError('Impossible d’enregistrer les flux RSS. Votre saisie est conservée. Réessayez.') } } finally { setSaving(false) } } return (

Une URL par ligne. Seuls les flux QuanwenRSS autorisés pour cette source sont acceptés. Les modifications s’appliquent aux prochaines synthèses, sans récupération ni génération immédiate. Un flux accessible ne garantit pas un contenu complet.

{Object.keys(errors).length > 1 &&

Plusieurs flux RSS sont invalides. Corrigez les champs signalés ci-dessous.

} {rows.map((row, index) => (
{ if (element) fields.current.set(row.id, element); else fields.current.delete(row.id) }} className="min-w-0 flex-1 basis-48" disabled={saving || disabled} value={row.url} aria-invalid={!!errors[row.id]} aria-describedby={`feeds-help-${sourceId}${errors[row.id] ? ` feed-error-${sourceId}-${row.id}` : ''}`} onChange={event => { const url = event.target.value; setRows(current => current.map(item => item.id === row.id ? { ...item, url } : item)); clearMessages() }} />
{errors[row.id] && }
))}
{error &&

{error}

} {(saving || saved) &&

{saving ? 'Enregistrement des flux RSS…' : 'Flux RSS enregistrés pour les prochaines synthèses. Aucune récupération ni génération n’a été lancée.'}

}
) }