Files
TradarrV2/frontend/src/components/SourceFeedsEditor.tsx

113 lines
6.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<void>
}
const FEED_PATHS: Record<string, readonly string[]> = {
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<Record<number, string>>({})
const [error, setError] = useState('')
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const nextId = useRef(urls.length)
const fields = useRef(new Map<number, HTMLInputElement>())
const addButton = useRef<HTMLButtonElement>(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<number, string> = {}
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 (
<form onSubmit={save} noValidate aria-label={`Flux RSS ${sourceName}`} aria-busy={saving} className="space-y-3 min-w-0">
<p id={`feeds-help-${sourceId}`} className="text-sm text-muted-foreground">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.</p>
{Object.keys(errors).length > 1 && <p role="alert" className="text-sm text-destructive">Plusieurs flux RSS sont invalides. Corrigez les champs signalés ci-dessous.</p>}
{rows.map((row, index) => (
<div key={row.id} className="space-y-2 min-w-0">
<Label htmlFor={`feed-${sourceId}-${row.id}`}>URL du flux RSS {sourceName} {index + 1}</Label>
<div className="flex flex-wrap gap-2 min-w-0">
<Input id={`feed-${sourceId}-${row.id}`} type="url" required maxLength={256} autoComplete="off" spellCheck={false}
ref={element => { 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() }} />
<Button type="button" variant="outline" disabled={saving} aria-label={`Retirer le flux RSS ${sourceName} ${index + 1}`} onClick={() => remove(row.id, index)}>Retirer</Button>
</div>
{errors[row.id] && <p id={`feed-error-${sourceId}-${row.id}`} role="alert" className="text-sm text-destructive">{errors[row.id]}</p>}
</div>
))}
<div className="flex flex-wrap gap-2">
<Button ref={addButton} type="button" variant="outline" disabled={saving} aria-label={`Ajouter un flux RSS ${sourceName}`} onClick={add}>Ajouter un flux RSS</Button>
<Button type="submit" disabled={saving} aria-label={`Enregistrer les flux RSS ${sourceName}`}>{saving ? 'Enregistrement…' : 'Enregistrer les flux RSS'}</Button>
</div>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{(saving || saved) && <p role="status">{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.'}</p>}
</form>
)
}