-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1121 lines (990 loc) · 38.7 KB
/
script.js
File metadata and controls
1121 lines (990 loc) · 38.7 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Variable globale pour stocker les initialisations de carte différées
const pendingMapInits = [];
// Variable globale pour stocker le nom de base du fichier RDF (sans extension)
let rdfBaseName = "";
// Chargement des données RDF
let rdfData = {};
// Filtres & recherche
let activeFilters = {
types: new Set(), // types sélectionnés (intersection)
onlyWithImage: false,
};
let currentSearch = ""; // texte de recherche
// Langues
let activeLang = 'all'; // 'all' pour tout afficher, sinon code langue (ex: 'en', 'el', 'fr')
function parseLiteral(item) {
// Supporte {value, lang}, {"@value","@language"}, {"@value","@lang"}, {"value","xml:lang"} ou "texte@en"
if (item && typeof item === 'object') {
const val = item.value ?? item['@value'] ?? item.literal ?? '';
const lang = item.lang ?? item['@language'] ?? item['@lang'] ?? item['xml:lang'] ?? null;
return { text: String(val), lang: lang ? String(lang).toLowerCase() : null };
}
const str = String(item ?? '');
const m = str.match(/^(.*)@([a-zA-Z]{2}(?:-[a-zA-Z]{2})?)$/);
if (m) return { text: m[1], lang: m[2].toLowerCase() };
return { text: str, lang: null };
}
function collectAvailableLangs() {
const langs = new Set();
for (const obj of Object.values(rdfData)) {
for (const [key, raw] of Object.entries(obj)) {
// Prefer the backend structures
if (key.endsWith('__byLang') && typeof raw === 'object') {
Object.keys(raw).forEach(k => {
if (k && k !== 'undefined' && k.trim() !== '') langs.add(String(k).toLowerCase());
});
continue;
}
if (key.endsWith('__detailed') && Array.isArray(raw)) {
raw.forEach(d => {
if (d && d.lang && String(d.lang).trim() !== '') langs.add(String(d.lang).toLowerCase());
});
continue;
}
// Legacy paths: take only explicit languages (no heuristic on characters)
const keyLang = parseLangFromKey(key);
if (keyLang) langs.add(keyLang);
const arr = Array.isArray(raw) ? raw : [raw];
for (const it of arr) {
const { lang } = parseLiteral(it);
if (lang) langs.add(lang);
}
}
}
// Only actually present languages (no baseline/defaults, no empty)
return Array.from(langs).sort();
}
// Helper pour extraire la langue d'une clé de propriété (ex: rdfs:label@en)
function parseLangFromKey(key) {
const m = key.match(/@([a-zA-Z]{2}(?:-[a-zA-Z]{2})?)$/);
return m ? m[1].toLowerCase() : null;
}
// Return values for a predicate using backend language structures when available
function getValuesForLang(obj, pred, lang) {
const byLangKey = `${pred}__byLang`;
const detailedKey = `${pred}__detailed`;
const raw = obj[pred];
// 1) Fast path: __byLang map
const byLang = obj[byLangKey];
if (byLang && typeof byLang === 'object') {
if (lang === 'all') {
// flatten all languages
return Object.values(byLang).flat();
}
const exact = byLang[lang];
if (exact && exact.length) return exact;
const neutral = byLang[''];
if (neutral && neutral.length) return neutral;
if (lang === 'el') {
// heuristique grec si pas de clé
const all = Object.values(byLang).flat();
const greekLike = all.filter(t => typeof t === 'string' && /[\u0370-\u03FF\u1F00-\u1FFF]/.test(t));
if (greekLike.length) return greekLike;
}
return [];
}
// 2) Detailed list {text, lang}
const det = obj[detailedKey];
if (Array.isArray(det)) {
if (lang === 'all') return det.map(d => d.text);
const exact = det.filter(d => (d.lang || '').toLowerCase() === lang.toLowerCase()).map(d => d.text);
if (exact.length) return exact;
const neutral = det.filter(d => !d.lang).map(d => d.text);
if (neutral.length) return neutral;
if (lang === 'el') {
const greekLike = det.filter(d => !d.lang && /[\u0370-\u03FF\u1F00-\u1FFF]/.test(d.text)).map(d => d.text);
if (greekLike.length) return greekLike;
}
return [];
}
// 3) Legacy array of strings
if (Array.isArray(raw)) return filterByActiveLang(raw).map(x => parseLiteral(x).text);
return [];
}
function filterByActiveLang(values) {
if (!Array.isArray(values)) return [];
if (activeLang === 'all') return values;
const exact = values.filter(v => (parseLiteral(v).lang || '').toLowerCase() === activeLang.toLowerCase());
if (exact.length) return exact;
// accept neutral if no exact match
const neutral = values.filter(v => !parseLiteral(v).lang);
if (neutral.length) return neutral;
// heuristic for Greek text without explicit lang
if (activeLang.toLowerCase() === 'el') {
const greekLike = values.filter(v => {
const { text, lang } = parseLiteral(v);
return !lang && typeof text === 'string' && /[\u0370-\u03FF\u1F00-\u1FFF]/.test(text);
});
if (greekLike.length) return greekLike;
}
return [];
}
function pickBestLabel(values) {
if (!Array.isArray(values) || values.length === 0) return null;
// Souple: when a language is selected, prefer that lang, else accept no-lang
if (activeLang !== 'all') {
const exact = values.find(v => (parseLiteral(v).lang || '').toLowerCase() === activeLang.toLowerCase());
if (exact) return parseLiteral(exact).text;
const neutral = values.find(v => !parseLiteral(v).lang);
if (neutral) return parseLiteral(neutral).text;
// small heuristic: if el is selected and text is Greek but no lang
if (activeLang.toLowerCase() === 'el') {
const greekLike = values.find(v => {
const { text, lang } = parseLiteral(v);
return !lang && typeof text === 'string' && /[\u0370-\u03FF\u1F00-\u1FFF]/.test(text);
});
if (greekLike) return parseLiteral(greekLike).text;
}
}
// Fallback preferences when showing all languages
const pref = ['fr','en','el',''];
for (const p of pref) {
const hit = values.find(v => (parseLiteral(v).lang || '') === p);
if (hit) return parseLiteral(hit).text;
}
return parseLiteral(values[0]).text;
}
function objectHasLang(obj, lang) {
if (!obj || !lang || lang === 'all') return true;
const PREF_IRI = "http://www.w3.org/2004/02/skos/core#prefLabel";
const RDFS_IRI = "http://www.w3.org/2000/01/rdf-schema#label";
const hitPref = getValuesForLang(obj, PREF_IRI, lang);
if (hitPref && hitPref.length) return true;
const hitRdfs = getValuesForLang(obj, RDFS_IRI, lang);
if (hitRdfs && hitRdfs.length) return true;
// Any other label-like key
for (const key of Object.keys(obj)) {
const keyLc = key.toLowerCase();
if (keyLc.endsWith('#label') || keyLc.endsWith('#preflabel') || keyLc.includes('label')) {
const vals = getValuesForLang(obj, key, lang);
if (vals && vals.length) return true;
}
}
return false;
}
// Assure la présence d'une colonne de filtres à gauche
function ensureFiltersSidebar() {
const main = document.querySelector('.main-layout');
if (!main) return;
if (!document.getElementById('filters-container')) {
const filters = document.createElement('div');
filters.id = 'filters-container';
filters.className = 'filters-container';
filters.style.width = '260px';
filters.style.flexShrink = '0';
filters.style.paddingRight = '20px';
filters.style.overflowY = 'auto';
filters.innerHTML = `
<div style="position:sticky; top:0; background:#fff8ef; padding:12px; border-radius:8px; border:1px solid #e6dac5;">
<h3 style="margin-top:0">Filters</h3>
<div style="margin:10px 0">
<label style="display:block; font-weight:600; margin-bottom:6px;">Language</label>
<select id="lang-select" style="width:100%; padding:6px; border-radius:6px; border:1px solid #e6dac5; background:#fff;">
<option value="all">All languages</option>
</select>
</div>
<div id="filter-types"></div>
<div style="margin:10px 0">
<label style="display:flex;align-items:center;gap:8px;">
<input type="checkbox" id="filter-has-image" />
<span>With image</span>
</label>
</div>
<button id="filter-clear-btn">Reset</button>
</div>`;
// insérer en premier enfant (colonne gauche)
main.insertBefore(filters, main.firstElementChild);
}
}
function collectAvailableTypes() {
const set = new Set();
const EXCLUDE = new Set([
'http://www.w3.org/2002/07/owl#Class',
'http://www.w3.org/2002/07/owl#ObjectProperty',
'http://www.w3.org/2002/07/owl#DatatypeProperty'
]);
for (const obj of Object.values(rdfData)) {
const types = obj['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'] || [];
types.forEach(t => { if (!EXCLUDE.has(t)) set.add(t); });
}
return Array.from(set).sort();
}
function buildFiltersUI() {
ensureFiltersSidebar();
const typesDiv = document.getElementById('filter-types');
if (!typesDiv) return;
const types = collectAvailableTypes();
if (types.length === 0) {
typesDiv.innerHTML = '<em>ANo type detected</em>';
} else {
typesDiv.innerHTML = '<strong>Types</strong>';
const list = document.createElement('div');
list.style.maxHeight = '260px';
list.style.overflowY = 'auto';
list.style.marginTop = '6px';
types.forEach(t => {
const id = `type-${btoa(t).replace(/[^a-z0-9]/gi,'')}`;
const wrap = document.createElement('label');
wrap.style.display = 'flex';
wrap.style.alignItems = 'center';
wrap.style.gap = '8px';
wrap.style.margin = '4px 0';
wrap.innerHTML = `<input type="checkbox" id="${id}" data-type="${t}"><span>${shortenURI(t)}</span>`;
list.appendChild(wrap);
});
typesDiv.appendChild(list);
// listeners
list.querySelectorAll('input[type="checkbox"]').forEach(cb => {
cb.addEventListener('change', (e) => {
const t = e.target.getAttribute('data-type');
if (e.target.checked) activeFilters.types.add(t); else activeFilters.types.delete(t);
renderAll();
});
});
}
// Lang selector
const langSelect = document.getElementById('lang-select');
if (langSelect) {
const langs = collectAvailableLangs();
const previous = activeLang;
// Reset options (keep the first "all")
langSelect.querySelectorAll('option:not([value="all"])').forEach(o => o.remove());
langs.forEach(l => {
const opt = document.createElement('option');
opt.value = l; opt.textContent = l;
langSelect.appendChild(opt);
});
// Restore selection if available, else default to 'all'
langSelect.value = langs.includes(previous) ? previous : 'all';
activeLang = langSelect.value;
langSelect.onchange = () => { activeLang = langSelect.value; renderAll(); displayHierarchy(); };
}
const imgCb = document.getElementById('filter-has-image');
if (imgCb) {
imgCb.checked = activeFilters.onlyWithImage;
imgCb.onchange = () => { activeFilters.onlyWithImage = imgCb.checked; renderAll(); };
}
const clearBtn = document.getElementById('filter-clear-btn');
if (clearBtn) {
clearBtn.onclick = () => {
activeFilters.types.clear();
activeFilters.onlyWithImage = false;
// reset UI
document.querySelectorAll('#filters-container input[type="checkbox"]').forEach(cb => { cb.checked = false; });
renderAll();
};
}
}
function applyFilters(objects) {
const entries = Object.entries(objects);
const hasTypeFilter = activeFilters.types.size > 0;
const typesFilter = activeFilters.types;
const onlyWithImage = activeFilters.onlyWithImage;
const terms = currentSearch.toLowerCase().split(/\s+/).filter(Boolean);
const filtered = entries.filter(([id, obj]) => {
// Exclusions déjà présentes dans renderCards
const types = obj['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'] || [];
const isDefinedBy = obj['http://www.w3.org/2000/01/rdf-schema#isDefinedBy'] || [];
if (isDefinedBy.includes('http://www.ontologia.fr/OTB/otv.rdf')) return false;
if (types.includes('http://www.w3.org/2002/07/owl#Class')) {
if (activeLang === 'all') return false; // hide classes in "all" view
// when a language is selected, allow classes but they must pass the lang check below
}
if (types.includes('http://www.w3.org/2002/07/owl#ObjectProperty') || types.includes('http://www.w3.org/2002/07/owl#DatatypeProperty')) return false;
// Filtre langue strict: ne garder que les objets ayant au moins un label dans la langue sélectionnée
if (activeLang !== 'all') {
if (!objectHasLang(obj, activeLang)) return false;
}
// Filtre types (intersection au moins 1)
if (hasTypeFilter) {
const ok = types.some(t => typesFilter.has(t));
if (!ok) return false;
}
// Filtre image
if (onlyWithImage) {
const img = getImage(obj);
if (!img) return false;
}
// Filtre recherche plein texte
if (terms.length) {
const label = getLabel(obj).toLowerCase();
const attrText = Object.values(obj).flat().join(' ').toLowerCase();
const ok = terms.every(term => label.includes(term) || attrText.includes(term));
if (!ok) return false;
}
return true;
});
return Object.fromEntries(filtered);
}
function renderAll() {
const filteredObjects = applyFilters(rdfData);
renderCards(filteredObjects);
}
// Hiérarchie des types (remplie lors du chargement des données)
let typeHierarchy = {};
// Affiche un message lorsqu'aucun fichier RDF n'est chargé
function showEmptyMessage() {
const appContainer = document.getElementById('app');
appContainer.innerHTML = '<p class="empty-message">No RDF file loaded. Please import one.</p>';
// Ajoute le bouton Vue SPARQL même sans fichier RDF
ensureFiltersSidebar();
const hierarchyContainer = document.getElementById('hierarchy-container');
if (hierarchyContainer) hierarchyContainer.innerHTML = '';
const toggleBtn = document.getElementById('toggle-container');
if (toggleBtn) {
toggleBtn.innerHTML = `
<button id="map-view-btn">Map View</button>
<button id="sparql-view-btn">SPARQL Endpoint</button>
`;
document.getElementById('map-view-btn').onclick = renderMapView;
document.getElementById('sparql-view-btn').onclick = renderSPARQLView;
}
}
// Affiche le message au chargement initial
showEmptyMessage();
ensureFiltersSidebar();
rdfData = {};
// Fonction pour créer les cartes
function renderCards(objects) {
const appContainer = document.getElementById('app');
appContainer.innerHTML = '';
appContainer.removeAttribute('style');
const fragment = document.createDocumentFragment();
Object.entries(objects).forEach(([id, obj]) => {
const label = getLabel(obj);
// Filtre les objets dont le type est ObjectProperty ou DatatypeProperty
const types = obj["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"] || [];
// Ajout du filtre pour exclure les concepts ayant une propriété isDefinedBy égale à http://www.ontologia.fr/OTB/otv.rdf
const isDefinedBy = obj["http://www.w3.org/2000/01/rdf-schema#isDefinedBy"] || [];
if (isDefinedBy.includes("http://www.ontologia.fr/OTB/otv.rdf")) return;
// Ajout du filtre pour exclure owl#Class (concepts) selon la langue active
if (types.includes("http://www.w3.org/2002/07/owl#Class")) {
if (activeLang === 'all') return; // keep hiding in "all" view to avoid clutter
// else, allow classes to be displayed (language filter already enforced upstream)
}
if (
types.includes("http://www.w3.org/2002/07/owl#ObjectProperty") ||
types.includes("http://www.w3.org/2002/07/owl#DatatypeProperty")
) {
return;
}
if (label === "Unknown Object") return;
const card = document.createElement('div');
card.className = 'card';
card.onclick = () => openModal(label, obj);
const imageUrl = getImage(obj);
if (imageUrl) {
const img = document.createElement('img');
img.src = imageUrl;
img.alt = label;
card.appendChild(img);
}
const title = document.createElement('h2');
title.textContent = label;
card.appendChild(title);
fragment.appendChild(card);
});
appContainer.appendChild(fragment);
// Réinitialise le bouton Vue Carte et ajoute Vue SPARQL après l'affichage des cartes
const toggleBtn = document.getElementById('toggle-container');
if (toggleBtn) {
toggleBtn.innerHTML = `
<button id="map-view-btn">Map View</button>
<button id="sparql-view-btn">SPARQL Endpoint</button>
`;
document.getElementById('map-view-btn').onclick = renderMapView;
document.getElementById('sparql-view-btn').onclick = renderSPARQLView;
}
}
// Affichage de la vue carte
function renderMapView() {
if (Object.keys(rdfData).length === 0) {
alert("Please import a file before using the map.");
return;
}
console.log("renderMapView() activated");
const appContainer = document.getElementById('app');
appContainer.innerHTML = '';
appContainer.removeAttribute('style');
const mapContainer = document.createElement('div');
mapContainer.id = 'map-container';
mapContainer.style.height = '600px';
mapContainer.style.border = 'none';
mapContainer.style.background = 'lightgray';
mapContainer.style.width = '100%';
appContainer.appendChild(mapContainer);
setTimeout(() => {
if (typeof L === "undefined") {
console.error("Leaflet is not loaded.");
return;
}
const map = L.map('map-container').setView([48.85, 2.35], 5);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
const bounds = [];
// Définition des clés dynamiques pour ce fichier RDF
const pleiadesKey = `http://www.ontologia.fr/OTB/${rdfBaseName}#pleiadesCoordinates`;
const latKey = `http://www.ontologia.fr/OTB/${rdfBaseName}#latitude`;
const lonKey = `http://www.ontologia.fr/OTB/${rdfBaseName}#longitude`;
Object.entries(rdfData).forEach(([uri, obj]) => {
let coords = null;
if (obj[pleiadesKey]) {
coords = obj[pleiadesKey];
} else if (obj[latKey] && obj[lonKey]) {
coords = [`${obj[latKey][0]},${obj[lonKey][0]}`];
}
if (!coords) return;
if (typeof coords === "string") {
try {
coords = JSON.parse(coords);
} catch (e) {
coords = [coords];
}
}
if (!Array.isArray(coords)) return;
const [lat, lon] = coords[0].split(',').map(Number);
if (isNaN(lat) || isNaN(lon)) return;
const label = getLabel(obj);
const marker = L.marker([lat, lon]).addTo(map);
const popupContent = `<span style="color:blue; cursor:pointer;" onclick="handleDetailClick('${uri.replace(/'/g, "\\'")}'); event.stopPropagation();">${label}</span>`;
marker.bindPopup(popupContent);
bounds.push([lat, lon]);
});
if (bounds.length > 0) {
map.fitBounds(bounds, { padding: [30, 30] });
}
map.invalidateSize();
console.log("Map with markers displayed.");
}, 300);
// Réinitialise le bouton Vue Grille après l'affichage de la carte
const toggleBtn = document.getElementById('toggle-container');
if (toggleBtn) {
toggleBtn.innerHTML = `<button id="grid-view-btn">Grid View</button>`;
document.getElementById('grid-view-btn').onclick = () => {
closeModal();
renderCards(rdfData);
};
}
}
function getLabel(obj) {
if (!obj) return "Unknown Object";
const PREF_IRI = "http://www.w3.org/2004/02/skos/core#prefLabel";
const RDFS_IRI = "http://www.w3.org/2000/01/rdf-schema#label";
// Try prefLabel then rdfs:label using new backend shape
const lang = activeLang;
let candidates = getValuesForLang(obj, PREF_IRI, lang);
if (!candidates || candidates.length === 0) candidates = getValuesForLang(obj, RDFS_IRI, lang);
// If still nothing, fall back to any label-like key
if (!candidates || candidates.length === 0) {
const all = [];
for (const [key, _] of Object.entries(obj)) {
const keyLc = key.toLowerCase();
if (keyLc.endsWith('#label') || keyLc.endsWith('#preflabel') || keyLc.includes('label')) {
all.push(...getValuesForLang(obj, key, lang));
}
}
candidates = all;
}
if (!candidates || candidates.length === 0) return "Unknown Object";
return String(candidates[0]);
}
function getImage(obj) {
const images = obj["http://xmlns.com/foaf/0.1/depiction"] || [];
return images.length > 0 ? images[0] : null;
}
function openModal(label, obj) {
const modal = document.getElementById('modal');
const modalTitle = document.getElementById('modal-title');
const modalDescription = document.getElementById('modal-description');
modalTitle.textContent = label;
modalDescription.innerHTML = getDetails(obj);
setTimeout(() => {
pendingMapInits.forEach(init => init());
pendingMapInits.length = 0;
}, 100);
modal.style.display = 'block';
}
function getDetails(obj) {
const imageUrl = getImage(obj);
let imageHtml = '';
if (imageUrl) {
imageHtml = `
<div class="detail-item detail-image">
<a href="${imageUrl}" target="_blank">
<img src="${imageUrl}" alt="Image">
</a>
</div>
`;
}
// Définition des clés dynamiques selon rdfBaseName
const pleiadesKey = `http://www.ontologia.fr/OTB/${rdfBaseName}#pleiadesCoordinates`;
const latKey = `http://www.ontologia.fr/OTB/${rdfBaseName}#latitude`;
const lonKey = `http://www.ontologia.fr/OTB/${rdfBaseName}#longitude`;
return imageHtml + Object.entries(obj)
.map(([key, value]) => {
if (key === "http://xmlns.com/foaf/0.1/depiction") return '';
// Gérer la détection dynamique des coordonnées
if (
key === pleiadesKey ||
(key === latKey && obj[lonKey])
) {
let lat, lon;
if (key === latKey) {
lat = parseFloat(value[0]);
lon = parseFloat(obj[lonKey][0]);
} else {
[lat, lon] = value[0].split(',').map(Number);
}
const mapId = `map-${lat}-${lon}-${Math.random().toString(36).substring(2, 8)}`;
pendingMapInits.push(() => {
const map = L.map(mapId).setView([lat, lon], 10);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
L.marker([lat, lon]).addTo(map);
});
// Affiche la carte ET la propriété classique (latitude ou pleiadesCoordinates)
return `
<div class="detail-item">
<strong>Location</strong>:
<div class="modal-map" id="${mapId}"></div>
</div>
<div class="detail-item">
<strong>${shortenURI(key)}</strong>:
<ul><li>${value[0]}</li></ul>
</div>
`;
}
// Filtrage par langue via backend (__byLang / __detailed) si dispo
let values = [];
if (activeLang === 'all') {
const byLang = obj[`${key}__byLang`];
if (byLang) {
values = Object.values(byLang).flat();
} else {
const det = obj[`${key}__detailed`];
values = Array.isArray(det) ? det.map(d => d.text) : (Array.isArray(value) ? value : [value]);
}
} else {
values = getValuesForLang(obj, key, activeLang);
if (!values || values.length === 0) return '';
}
return `
<div class="detail-item">
<strong>${shortenURI(key)}</strong>:
<ul>
${values.map(item => {
const parsed = parseLiteral(item);
const text = parsed.text;
const langBadge = parsed.lang ? ` <span style="opacity:.7;font-size:12px;">(${parsed.lang})</span>` : '';
const label = shortenURI(text);
if (rdfData[text]) {
return `<li class="detail-link" onclick="event.stopPropagation(); handleDetailClick('${text.replace(/'/g, "\\'")}')">${label}${langBadge}</li>`;
} else if (/^https?:\/\/(?!www\.w3\.org)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(\/\S*)?$/.test(text)) {
return `<li class="detail-ext-link"><a href="${text}" target="_blank">${label}</a>${langBadge}</li>`;
} else {
return `<li>${label}${langBadge}</li>`;
}
}).join('')}
</ul>
</div>
`;
})
.join('');
}
function handleDetailClick(uri) {
const obj = rdfData[uri];
if (obj) {
const label = getLabel(obj);
openModal(label, obj);
} else {
// On cherche par label s'il n'existe pas d'objet direct à cet URI
for (const [id, candidate] of Object.entries(rdfData)) {
if (getLabel(candidate) === uri) {
openModal(uri, candidate);
break;
}
}
}
}
function closeModal() {
document.getElementById('modal').style.display = 'none';
}
window.onclick = function(event) {
const modal = document.getElementById('modal');
if (event.target == modal) {
closeModal();
}
};
function searchObjects(query) {
currentSearch = query || '';
renderAll();
}
function shortenURI(uri) {
return uri.includes('#') ? uri.split('#').pop() : uri;
}
document.getElementById('search-input').addEventListener('input', (event) => {
searchObjects(event.target.value);
});
document.getElementById('rdf-upload').addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
// Stocke le nom du fichier sans extension dans la variable globale
rdfBaseName = file.name.split('.')[0];
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('http://localhost:5050/upload', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`Erreur HTTP : ${response.status}`);
}
const data = await response.json();
rdfData = data;
activeLang = 'all';
console.log("rdfData loaded with", Object.keys(rdfData).length, "elements");
// Réinitialise tout pour affichage
typeHierarchy = {};
document.getElementById('app').innerHTML = '';
ensureFiltersSidebar();
buildFiltersUI();
renderAll();
displayHierarchy();
} catch (err) {
console.error("Error during sending or parsing :", err);
alert("Error: the RDF file could not be processed. Please try again.");
}
});
function displayHierarchy() {
const hierarchyContainer = document.getElementById('hierarchy-container');
hierarchyContainer.innerHTML = '';
const classLabels = {};
const subclasses = {};
const instances = {};
// Restaure l'ancienne logique pour détecter toutes les classes (owl#Class) et sous-classes, ainsi que les instances
for (const [uri, obj] of Object.entries(rdfData)) {
const types = obj["http://www.w3.org/1999/02/22-rdf-syntax-ns#type"] || [];
if (types.includes("http://www.w3.org/2002/07/owl#Class")) {
if (activeLang !== 'all' && !objectHasLang(obj, activeLang)) {
// ignorer les classes sans label dans la langue sélectionnée
continue;
}
const label = getLabel(obj);
if (label === "Unknown Object") continue;
classLabels[uri] = label;
const parents = obj["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || [];
parents.forEach(parent => {
if (!subclasses[parent]) subclasses[parent] = new Set();
subclasses[parent].add(uri);
});
}
if (types.includes("http://www.w3.org/2002/07/owl#NamedIndividual")) {
if (activeLang !== 'all' && !objectHasLang(obj, activeLang)) {
// ignorer les individus sans label dans la langue sélectionnée
continue;
}
const label = getLabel(obj);
if (label === "Unknown Object") continue;
const individualTypes = types.filter(t => t !== "http://www.w3.org/2002/07/owl#NamedIndividual");
individualTypes.forEach(cls => {
if (!instances[cls]) instances[cls] = [];
instances[cls].push(label);
});
}
}
function renderClass(uri) {
const li = document.createElement('li');
li.className = 'collapsible';
const labelSpan = document.createElement('span');
labelSpan.className = 'hierarchy-label';
labelSpan.textContent = classLabels[uri] || shortenURI(uri);
labelSpan.style.cursor = 'pointer';
labelSpan.onclick = () => {
// Trouve l'objet correspondant pour ouvrir la carte
const obj = rdfData[uri];
if (obj) {
const label = getLabel(obj);
openModal(label, obj);
}
};
li.appendChild(labelSpan);
const ul = document.createElement('ul');
ul.style.display = 'none';
if (instances[uri]) {
instances[uri].forEach(name => {
const il = document.createElement('li');
il.textContent = name;
il.style.cursor = 'pointer';
il.onclick = () => {
// Trouve l'objet avec ce label
for (const [id, obj] of Object.entries(rdfData)) {
if (getLabel(obj) === name) {
openModal(name, obj);
break;
}
}
};
ul.appendChild(il);
});
}
if (subclasses[uri]) {
subclasses[uri].forEach(child => {
ul.appendChild(renderClass(child));
});
}
if (ul.children.length > 0) {
const toggleBtn = document.createElement('button');
toggleBtn.textContent = '▶';
toggleBtn.style.marginRight = '5px';
toggleBtn.onclick = (e) => {
e.stopPropagation();
if (ul.style.display === 'none') {
ul.style.display = 'block';
toggleBtn.textContent = '▼';
} else {
ul.style.display = 'none';
toggleBtn.textContent = '▶';
}
};
li.insertBefore(toggleBtn, labelSpan);
li.appendChild(ul);
}
return li;
}
// Calcule les racines de la hiérarchie de classes :
// on prend toutes les classes détectées (classLabels) et on enlève celles qui sont enfants (dans `subclasses`).
const allClasses = Object.keys(classLabels);
const childrenSet = new Set();
Object.values(subclasses).forEach(childSet => {
childSet.forEach(c => childrenSet.add(c));
});
let roots = allClasses.filter(c => !childrenSet.has(c));
// Si aucune racine claire (pas d'info subClassOf), on affiche toutes les classes comme racines
if (roots.length === 0) {
roots = allClasses;
}
if (roots.length === 0) {
const emptyMsg = document.createElement('div');
emptyMsg.style.color = '#7a6b5b';
emptyMsg.style.fontStyle = 'italic';
emptyMsg.textContent = 'No classes found to build the hierarchy.';
hierarchyContainer.appendChild(emptyMsg);
return;
}
const tree = document.createElement('ul');
roots.forEach(root => tree.appendChild(renderClass(root)));
hierarchyContainer.appendChild(tree);
}
document.getElementById('map-view-btn').onclick = renderMapView;
// Ajoute la fonction renderSPARQLView à la fin du fichier
function renderSPARQLView() {
// Vérifie s'il y a des données RDF chargées
if (Object.keys(rdfData).length === 0) {
alert("Please import an RDF file before using the SPARQL endpoint.");
return;
}
// Affichage propre et responsive de la vue SPARQL
const appContainer = document.getElementById('app');
appContainer.innerHTML = '';
appContainer.removeAttribute('style');
// Conteneur principal pour le panneau SPARQL
const sparqlContainer = document.createElement('div');
sparqlContainer.className = 'sparql-panel';
const textarea = document.createElement('textarea');
textarea.id = 'sparql-editor';
textarea.placeholder = 'Write your SPARQL query here...';
const executeBtn = document.createElement('button');
executeBtn.textContent = 'Execute';
const resultDiv = document.createElement('div');
resultDiv.id = 'sparql-results';
executeBtn.onclick = async () => {
const query = textarea.value.trim();
if (!query) return;
resultDiv.innerHTML = 'Chargement...';
try {
const response = await fetch('http://localhost:5050/sparql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query })
});
const data = await response.json();
if (data.error) {
resultDiv.innerHTML = `<span class="sparql-error">Erreur : ${data.error}</span>`;
return;
}
const table = document.createElement('table');
data.forEach(row => {
const tr = document.createElement('tr');
row.forEach(cell => {
const td = document.createElement('td');
const shortLabel = shortenURI(cell);
if (rdfData[cell]) {
td.innerHTML = `<span class="sparql-link" onclick="handleDetailClick('${cell.replace(/'/g, "\\'")}')">${shortLabel}</span>`;
} else {
td.textContent = shortLabel;
}
tr.appendChild(td);
});
table.appendChild(tr);
});
resultDiv.innerHTML = '';
resultDiv.appendChild(table);
} catch (e) {
resultDiv.innerHTML = `<span class="sparql-error">Erreur : ${e.message}</span>`;
}
};
sparqlContainer.appendChild(textarea);
sparqlContainer.appendChild(executeBtn);
sparqlContainer.appendChild(resultDiv);
appContainer.appendChild(sparqlContainer);
const toggleBtn = document.getElementById('toggle-container');
if (toggleBtn) {
toggleBtn.innerHTML = `<button id="grid-view-btn">Vue Grille</button>`;
document.getElementById('grid-view-btn').onclick = () => {
// Réafficher la hiérarchie quand on revient à la vue grille
document.getElementById('hierarchy-container').style.display = 'block';
closeModal();
renderAll();
};
}
}
// Ajoute un z-index élevé à .modal pour s'assurer qu'elle s'affiche au-dessus
const modal = document.getElementById('modal');
if (modal) {
modal.style.zIndex = '1000';
}
// Ajout des styles CSS modernes
(function injectModernStyles() {
if (document.getElementById('modern-styles')) return;
const style = document.createElement('style');
style.id = 'modern-styles';
style.textContent = `
body {
font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #fefaf6;
margin: 0;
padding: 0;
}
.card {
background-color: #fffaf0;
border-radius: 12px;
box-shadow: 0 6px 14px rgba(0, 0, 0, 0.1);
padding: 18px;
margin: 10px;
text-align: center;
transition: transform 0.3s ease, box-shadow 0.3s ease;
cursor: pointer;
width: 250px;
display: flex;
flex-direction: column;
justify-content: space-between;
}