Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { BookOpen, Upload, Trash2, Plus, Save } from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import api from '../../services/api';
import { useOrganizationStore } from '../../store/organizationStore';
import EntitySidebar from '../../components/EntitySidebar';
import BackofficeEntityPage from '../components/BackofficeEntityPage';
const listHref = (organizationId) => `/${organizationId}/backoffice/ontology-library`;
/**
* Bibliothèque d'ontologies : menu + sidebar (comme les autres concepts).
* Entrées par défaut (builtins ★) + entrées sauvegardées (upload/collage).
*/
export default function OntologyLibrary() {
const navigate = useNavigate();
const { id } = useParams();
const { currentOrganization } = useOrganizationStore();
const organizationId = currentOrganization?.id;
const queryClient = useQueryClient();
const isNew = id === 'new';
const base = listHref(organizationId);
const [busy, setBusy] = useState(false);
const [form, setForm] = useState({ name: '', description: '', format: 'turtle' });
const [paste, setPaste] = useState('');
const { data: entries = [], isLoading } = useQuery({
queryKey: ['ontology-library', organizationId],
queryFn: async () => (await api.get('/ontology-library')).data.data?.entries || [],
enabled: !!organizationId,
});
const { data: entry } = useQuery({
queryKey: ['ontology-library-entry', id],
queryFn: async () => (await api.get(`/ontology-library/${id}`)).data.data?.entry,
enabled: !!id && !isNew,
});
const [contentFormat, setContentFormat] = useState('turtle');
const { data: contentData, isFetching: contentLoading } = useQuery({
queryKey: ['ontology-library-content', id, contentFormat],
queryFn: async () => (await api.get(`/ontology-library/${id}/content`, { params: { format: contentFormat } })).data.data,
enabled: !!id && !isNew,
});
useEffect(() => {
if (entry) {
setForm({ name: entry.name || '', description: entry.description || '', format: entry.format || 'turtle' });
}
}, [entry]);
const invalidate = () => {
queryClient.invalidateQueries(['ontology-library', organizationId]);
if (id) queryClient.invalidateQueries(['ontology-library-entry', id]);
};
const uploadAsset = async (file) => {
const formData = new FormData();
formData.append('file', file);
const res = await api.post(`/${organizationId}/semantic-assets`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return res.data?.data;
};
const createEntry = async ({ name, format, key, size }) => {
const res = await api.post('/ontology-library', { organizationId, name, description: form.description, format, key, size });
invalidate();
return res.data?.data?.entry;
};
const onFile = async (file) => {
if (!file) return;
if (!organizationId) return toast.error('Organisation introuvable');
setBusy(true);
try {
const data = await uploadAsset(file);
const format = /\.(jsonld|json)$/i.test(file.name) ? 'jsonld' : 'turtle';
const created = await createEntry({ name: form.name.trim() || data.filename, format, key: data.key, size: data.size });
toast.success('Ontologie ajoutée à la bibliothèque');
navigate(`${base}/${created?._id}`);
} catch (e) {
toast.error(e.response?.data?.message || "Erreur lors de l'ajout");
} finally {
setBusy(false);
}
};
const onPaste = async () => {
if (!paste.trim()) return;
const file = new File([new Blob([paste], { type: 'text/turtle' })], `${form.name.trim() || 'ontologie'}.ttl`, { type: 'text/turtle' });
await onFile(file);
setPaste('');
};
const saveEntry = useMutation({
mutationFn: async () => api.patch(`/ontology-library/${id}`, { name: form.name, description: form.description }),
onSuccess: () => { toast.success('Ontologie mise à jour'); invalidate(); },
onError: (e) => toast.error(e.response?.data?.message || 'Erreur'),
});
const remove = useMutation({
mutationFn: async () => api.delete(`/ontology-library/${id}`),
onSuccess: () => {
toast.success('Ontologie supprimée');
queryClient.invalidateQueries(['ontology-library', organizationId]);
navigate(base);
},
onError: (e) => toast.error(e.response?.data?.message || 'Erreur'),
});
const sidebar = (
<EntitySidebar
items={entries}
selectedId={isNew ? null : id}
getItemHref={(e) => `${base}/${e._id}`}
searchPlaceholder="Rechercher une ontologie..."
emptyMessage="Aucune ontologie"
title="Ontologies"
icon={BookOpen}
iconClass="text-teal-600"
backofficeTo={`${base}/new`}
backofficeManageLabel="Nouvelle ontologie"
backofficeCreateLabel="Ajouter une ontologie"
loading={isLoading}
filterFn={(e) => `${e.name} ${e.description || ''}`}
renderItem={(e, isSelected) => (
<>
<div className="flex items-center">
<BookOpen className={`w-4 h-4 mr-2 flex-shrink-0 ${isSelected ? 'text-teal-400' : 'text-slate-500'}`} />
<span className={`text-sm font-medium truncate flex-1 ${isSelected ? 'text-white' : 'text-slate-300'}`}>
{e.name}{e.scope === 'builtin' ? ' ★' : ''}
</span>
</div>
{e.description && <div className="text-xs text-slate-400 truncate mt-0.5">{e.description}</div>}
</>
)}
/>
);
return (
<BackofficeEntityPage selectedId={isNew ? null : id} sidebar={sidebar}>
<div className="flex-1 min-h-0 overflow-y-auto p-3 sm:p-6">
<div className="max-w-3xl mx-auto space-y-6">
{isNew && (
<div className="bg-white rounded-lg shadow p-6 space-y-4">
<h1 className="text-lg font-semibold text-gray-900">Ajouter une ontologie</h1>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Nom</label>
<input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
placeholder="Ex. Ontologie entreprises"
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
<input type="text" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500" />
</div>
<label className={`inline-flex items-center px-3 py-2 border rounded-lg cursor-pointer ${busy ? 'opacity-50' : 'hover:bg-gray-50'}`}>
<Upload className="w-4 h-4 mr-2" /> Importer un fichier (Turtle/JSON-LD)
<input type="file" accept=".ttl,.turtle,.jsonld,.json,.owl,.rdf,.nt" disabled={busy} className="hidden"
onChange={(e) => { onFile(e.target.files?.[0]); e.target.value = ''; }} />
</label>
<div>
<textarea value={paste} onChange={(e) => setPaste(e.target.value)} rows={5}
placeholder="@prefix owl: <http://www.w3.org/2002/07/owl#> ."
className="w-full px-3 py-2 border border-gray-300 rounded-lg font-mono text-sm focus:ring-2 focus:ring-teal-500" />
<button type="button" onClick={onPaste} disabled={busy || !paste.trim()}
className="mt-1 px-3 py-1.5 text-sm bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50">
Ajouter le contenu collé
</button>
</div>
</div>
)}
{!isNew && id && entry && (
<div className="bg-white rounded-lg shadow p-6 space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-lg font-semibold text-gray-900">
{entry.name} {entry.scope === 'builtin' && <span className="text-xs text-teal-600">★ par défaut</span>}
</h1>
{entry.scope !== 'builtin' && (
<button onClick={() => remove.mutate()} className="flex items-center px-3 py-2 text-red-600 border border-red-300 rounded-lg hover:bg-red-50">
<Trash2 className="w-4 h-4 mr-1" /> Supprimer
</button>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Nom</label>
<input type="text" value={form.name} disabled={entry.scope === 'builtin'}
onChange={(e) => setForm({ ...form, name: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500 disabled:bg-gray-50" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
<input type="text" value={form.description} disabled={entry.scope === 'builtin'}
onChange={(e) => setForm({ ...form, description: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500 disabled:bg-gray-50" />
</div>
{entry.scope !== 'builtin' && (
<button onClick={() => saveEntry.mutate()} disabled={saveEntry.isLoading}
className="flex items-center px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50">
<Save className="w-4 h-4 mr-2" /> {saveEntry.isLoading ? 'Sauvegarde...' : 'Sauvegarder'}
</button>
)}
<div>
<div className="flex items-center justify-between mb-1">
<label className="block text-sm font-medium text-gray-700">
Contenu {contentLoading ? '(chargement…)' : `(${contentData?.format || entry.format || 'turtle'})`}
</label>
<div className="flex gap-1">
{[['turtle', 'Turtle (RDF)'], ['jsonld', 'JSON-LD']].map(([fmt, label]) => (
<button
key={fmt}
type="button"
onClick={() => setContentFormat(fmt)}
className={`px-3 py-1 text-xs rounded-lg border-2 transition-all ${
contentFormat === fmt
? 'border-teal-500 bg-teal-50 text-teal-700'
: 'border-transparent text-gray-600 hover:bg-gray-50'
}`}
>
{label}
</button>
))}
</div>
</div>
<pre className="max-h-[28rem] overflow-auto text-xs leading-relaxed bg-gray-900 text-gray-100 rounded-lg p-3 whitespace-pre-wrap">
{contentData?.content || 'Chargement…'}
</pre>
</div>
</div>
)}
{!isNew && !id && (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<BookOpen className="w-16 h-16 mx-auto mb-4 text-gray-300" />
<p className="text-gray-500">Sélectionnez une ontologie dans la liste, ou ajoutez-en une</p>
<button onClick={() => navigate(`${base}/new`)}
className="mt-6 inline-flex items-center px-5 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700">
<Plus className="w-5 h-5 mr-2" /> Ajouter une ontologie
</button>
</div>
</div>
)}
</div>
</div>
</BackofficeEntityPage>
);
}
|