LiDa_Search/js/cesareBrowse.js

612 lines
19 KiB
JavaScript
Raw Normal View History

2022-11-06 17:12:56 +01:00
/**
*
*/
var resetResult;
2022-11-08 10:44:20 +01:00
$(document).ready(function() {
const categoriegrammaticali={"v":"Verbo", "s":"Sostantivo", "a":"Aggettivo", "p":"Pronome", "r":"Articolo", "b":"Avverbio","e":"Preposizione",
"c":"Congiunzione", "i":"Interiezione", "n":"Onomastica", "f":"Citazione", "l":"Locuzione",
"r-e":"Articolo, Preposizione", "b-v":"Avverbio, Verbo", "p-v":"Pronome, Verbo",
"b-p-v":"Avverbio, Pronome, Verbo", "b-p":"Avverbio, Pronome",
"e-p":"Preposizione, Pronome", "a-s":"Aggettivo, Sostantivo",
"e-r":"Preposizione, Articolo", "v-b":"Verbo, Avverbio", "v-p":"Verbo, Pronome",
"v-p-b":"Verbo, Pronome, Avverbio", "p-b":"Pronome, Avverbio",
"p-e":"Pronome, Preposizione", "s-a":"Sostantivo, Aggettivo",}
2022-11-08 10:44:20 +01:00
const cantobadgeclass = 'badge badge-outline-info badge-pill'
2022-11-08 10:44:20 +01:00
2022-11-06 17:12:56 +01:00
const sparqlGenerator = sparqljs.Generator;
const myEngine = new Comunica.QueryEngine();
const sparqlEndpoint = "https://hdnlab1.isti.cnr.it/fuseki/commediaontosintgra/query";
2022-12-06 11:25:04 +01:00
var listaVersi = new Set()
var currentMinimap = ''
var listarisultati = [];
var minimapScrolling = false;
var displayId = 'displaycanto'
var minimapTopPos;
//used in minimap
//
let minimap = document.createElement('div');
let minimapSize = document.createElement('div');
let viewer = document.createElement('div');
let minimapContent = document.createElement('iframe');
let scale = 0.1;
let realScale;
let mappedElement = '';
resetResult=function(){
2022-12-16 10:40:34 +01:00
//console.log('clean result')
cleanSearchResult()
esprlogica = []
}
hideMinimap();
createAllDivCanti()
const start = performance.now();
showCantica('Inferno')
showCantica('Purgatorio')
showCantica('Paradiso')
$("#InfernoCanto_1").attr('style', 'display:block')
drawMinimap("InfernoCanto_1")
const end = performance.now();
console.log(`Load cantiche time: ${end - start} ms`);
2022-11-08 10:44:20 +01:00
2022-12-13 13:44:39 +01:00
$("[data-cg]").hover(function() {
//var properties = $(this).data("cg").split("");
//var cg = properties[0];
//$(this).popover({title: "Proprietà", content: categoriegrammaticali[cg], trigger: "hover"});
var details=getHoverContent($(this).data("cg"))
$(this).popover({title: "Proprietà", content: details, trigger: "hover"});
2022-11-07 11:52:54 +01:00
});
2022-11-08 10:44:20 +01:00
var mmih = 0
var mmiw = 0
$("#" + displayId).scroll(function() {
if (minimapScrolling) {
minimapScrolling = false
console.log('no scroll')
2022-11-07 11:52:54 +01:00
}
2022-11-08 10:44:20 +01:00
else {
console.log('yes scrolling')
console.log("viewer top pos before: " + $('#minimapviewer').offset().top)
trackScrollCanto()
console.log("viewer top pos after: " + $('#minimapviewer').offset().top)
2022-12-06 11:25:04 +01:00
}
2022-11-06 17:12:56 +01:00
});
2022-11-06 17:12:56 +01:00
jQuery(document).delegate('.navig-canto', 'click', function(e) {
$('.canto').each(function() {
2022-11-08 10:44:20 +01:00
$(this).attr("style", 'display:none');
2022-11-06 17:12:56 +01:00
});
// Crea id per la div che contiene il canto
2022-11-08 10:44:20 +01:00
$("#" + $(this).attr('name').replace(" ", "_")).attr('style', 'display:block')
manageMiniMap(this);
2022-12-06 11:25:04 +01:00
2022-11-06 17:12:56 +01:00
});
2022-11-08 10:44:20 +01:00
function manageMiniMap(divElem) {
mmiw = $("#" + displayId).innerWidth();
mmih = $("#" + displayId).innerHeight();
drawMinimap($(divElem).attr('name').replace(" ", "_"))
}
2022-12-06 11:25:04 +01:00
//Query
2022-11-14 09:22:00 +01:00
2022-12-12 13:30:59 +01:00
jQuery(document).delegate('#searchcomm, #searchcomm2', 'click', function(e) {
e.preventDefault();
manageQuery()
});
2022-12-12 13:30:59 +01:00
//Reset
jQuery(document).delegate('#cleanresult', 'click', function(e) {
console.log('clean')
cleanSearchResult()
esprlogica = []
$('#queryText').val("")
});
//Utility functions
2022-12-06 11:25:04 +01:00
function getHoverContent(categ){
//console.log('Categoria '+categ)
if(categ.includes('-')){
categs=categ.split('-')
mycat=[]
for (cat of categs){
mycat.push(cat[0])
}
console.log(mycat.join('-'))
return categoriegrammaticali[mycat.join('-')]
}
if (categ[0]=='v'){
var parser = peg.generate(categoriegrammaticaliGrammar);
//console.log (parser.parse(categ).split(',').filter(prop => prop.length > 0).join())
return parser.parse(categ).split(',').filter(prop => prop.length > 0).join()
}else if(categ[0]=='s'){
var parser = peg.generate(categoriaGrammaticaleSostantivo);
//console.log (parser.parse(categ).split(',').filter(prop => prop.length > 0).join())
return parser.parse(categ).split(',').filter(prop => prop.length > 0).join()
}
//console.log(categ[0])
return categoriegrammaticali[categ[0]]
}
function drawMinimap(name){
showMinimap(name)
currentMinimap = name;
//mmviewer diventa draggable
minimapTopPos = $('#minimapviewer').offset().top
console.log("top viewer init " + minimapTopPos)
$('#minimapviewer').draggable({
axis: "y",
containment: $('#displayminimap'),
scroll: false,
start: function(event, ui) { minimapScrolling = true; },
stop: function(event, ui) { minimapScrolling = false; },
drag: function(event, ui) {
minimapScrolling = true;
trackScrollViewer(ui.offset.top - minimapTopPos);
console.log(ui);
}
});
2022-12-06 11:25:04 +01:00
}
2022-12-12 13:30:59 +01:00
function cleanSearchResult() {
2022-11-08 10:44:20 +01:00
for (verso of listarisultati) {
idverso = '#' + verso
$(idverso).attr('class', 'f6 text-secondary text-nowrap font-weight-lighter')
}
$(".badge").remove();
listarisultati = []
if (currentMinimap != '')
showMinimap(currentMinimap)
}
2022-12-12 13:30:59 +01:00
function manageQuery(){
cleanSearchResult()
esprlogica = []
jsonQuery=getJsonQuery()
console.log("got json query")
if(jsonQuery['QueryAvanzata']==0 && jsonQuery['Clausola0']['queryText']==''){
alert('Digitare una stringa da cercare')
return
}
2022-12-12 13:30:59 +01:00
jsonQuery = buildSQ(jsonQuery)
myquery = new sparqlGenerator().stringify(jsonQuery)
console.log(myquery)
executeQuerySearch(myquery)
}
2022-12-06 11:25:04 +01:00
//minimap management
2022-11-08 10:44:20 +01:00
function showMinimap(element) {
mmplace = document.getElementById('displayminimap')
minimap.className = 'minimap__container'
minimapSize.className = 'minimap__size'
viewer.className = 'minimap__viewer'
viewer.id = 'minimapviewer'
minimapContent.className = 'minimap__content'
2022-11-08 10:44:20 +01:00
minimap.append(minimapSize, viewer, minimapContent);
mmplace.appendChild(minimap)
2022-11-17 16:37:08 +01:00
let html = document.getElementById(element).outerHTML//innerHTML
if (html == null | html == '')
return;
2022-11-08 10:44:20 +01:00
let iFrameDoc = minimapContent.contentWindow.document;
2022-11-17 16:37:08 +01:00
var cssLinkb = document.createElement("link");
cssLinkb.href = "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css";
cssLinkb.rel = "stylesheet";
2022-11-17 16:37:08 +01:00
cssLinkb.type = "text/css";
2022-11-18 14:55:06 +01:00
var cssLinkscroll = document.createElement("link");
cssLinkscroll.href = "./css/browsingldc.css";
cssLinkscroll.rel = "stylesheet";
2022-11-18 14:55:06 +01:00
cssLinkscroll.type = "text/css";
2022-11-08 10:44:20 +01:00
iFrameDoc.open();
iFrameDoc.write(html);
iFrameDoc.close();
2022-11-17 16:37:08 +01:00
iFrameDoc.head.appendChild(cssLinkb);
2022-11-18 14:55:06 +01:00
iFrameDoc.head.appendChild(cssLinkscroll);
mappedElement = element
2022-11-17 16:37:08 +01:00
getDimensionsDiv()
window.addEventListener('scroll', trackScroll)
2022-11-17 16:37:08 +01:00
window.addEventListener('resize', getDimensionsDiv)
}
function getInnerHeight(elm) {
var computed = getComputedStyle(elm),
padding = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom);
return elm.clientHeight - padding
}
2022-12-06 11:25:04 +01:00
function getDimensionsDiv() {
cantoplace = document.getElementById(displayId)
elementplace = document.getElementById(mappedElement)
bodyWidth = elementplace.clientWidth;
bodyRatio = elementplace.clientHeight / bodyWidth;
let winRatio = getInnerHeight(cantoplace) / (cantoplace.clientWidth);
2022-12-06 11:25:04 +01:00
//minimap.style.width='15%';
minimap.style.width = '100%';
2022-12-06 11:25:04 +01:00
realScale = minimap.clientWidth / bodyWidth;
2022-12-06 11:25:04 +01:00
minimapSize.style.paddingTop = `${bodyRatio * 100}%`
viewer.style.paddingTop = `${winRatio * 100}%`;
minimapContent.style.transform = `scale(${realScale})`;
minimapContent.style.width = `${(100 / realScale)}%`;
minimapContent.style.height = `${(100 / realScale)}%`;
//minimapContent.style.height=`100%`;
minimapContent.style.float = 'right';
2022-11-07 11:52:54 +01:00
}
2022-11-17 10:15:29 +01:00
function trackScroll() {
//console.log(window.scrollY)
viewer.style.transform = `translateY(${window.scrollY * realScale}px)`
2022-11-17 10:15:29 +01:00
}
function trackScrollCanto() {
console.log('cantoscrollT*realscale ' + document.getElementById(displayId).scrollTop * realScale + ' top: ' + document.getElementById(displayId).scrollTop)
viewer.style.transform = `translateY(${document.getElementById(displayId).scrollTop * realScale}px)`
}
function trackScrollViewer(toppos) {
console.log('scrollMMView top*1/realScale: ' + toppos * (1 / realScale) + ' top pos: ' + toppos)
did = document.getElementById(displayId)
did.scrollTop = (toppos * (1 / realScale))
}
function hideMinimap() {
2022-11-11 22:11:22 +01:00
$('.canto').each(function() {
$(this).attr("style", 'display:none');
});
$(".minimap__container").remove();
currentMinimap = ''
2022-11-11 22:11:22 +01:00
}
2022-11-08 10:44:20 +01:00
2022-12-06 11:25:04 +01:00
//Cantica management functions
function showCantica(cantica) {
2022-12-14 09:04:42 +01:00
//var listaCanti = new Set()
var setVersi = new Set()
//$("#loader").show();
containerForme = formeprima
if (cantica == 'Paradiso')
containerForme = formeterza
if (cantica == 'Purgatorio')
containerForme = formeseconda
2022-12-16 10:40:34 +01:00
const endlc = performance.now();
console.log(`Load `+cantica+` time: ${endlc - start} ms`);
for (cmpItem of containerForme) {
formaItem = cmpItem.split("_")
2022-12-14 09:04:42 +01:00
//listaCanti = createDivCanti(listaCanti, cantica, 'Canto ' + formaItem[1])
//var forma = new Object()
setVersi = createDivVersi(setVersi, cantica, formaItem[3], 'Canto_' + formaItem[1])
createSpanFormeNew(cantica, 'Canto_' + formaItem[1], formaItem[3], formaItem[0], formaItem[4], formaItem[2])
/*
forma.numverso = formaItem[3];
forma.canto = 'Canto ' + formaItem[1];
forma.pos = formaItem[2];
forma.form = formaItem[0];
forma.catgramm = formaItem[4];
forma.cantica = cantica;
createSpanForme(forma)
*/
}
//$("#loader").hide();
return
}
/*
function createSpanForme(element) {
var spanoccorrenza = $('<span />')
var pos = parseInt(element.pos)
spanoccorrenza.attr('id', element.cantica + "_" + element.canto.replace(" ", "_") + "_" + element.numverso + "_" + pos)
2022-12-13 13:44:39 +01:00
spanoccorrenza.attr('data-cg', element.catgramm)
if (listarisultati.length > 0 && listarisultati.includes(spanoccorrenza.attr('id')))
spanoccorrenza.attr('class', "font-weight-bold mark ")
spanoccorrenza.append(element.form.replaceAll("%20", " "))
elementoverso = $('#' + element.cantica + "_" + element.canto.replace(" ", "_") + "_" + element.numverso)
spanoccorrenza.appendTo(elementoverso)
elementoverso.append('&nbsp;')
}
*/
function createSpanFormeNew(cantica, canto, numverso, forma, catgramm, pos) {
var spanoccorrenza = $('<span />')
var pos = parseInt(pos)
spanoccorrenza.attr('id', cantica + "_" + canto+ "_" + numverso + "_" + pos)
spanoccorrenza.attr('data-cg', catgramm)
2022-12-16 10:40:34 +01:00
//if (listarisultati.length > 0 && listarisultati.includes(spanoccorrenza.attr('id')))
// spanoccorrenza.attr('class', "font-weight-bold mark ")
spanoccorrenza.append(forma+" ")
elementoverso = $('#' + cantica + "_" + canto + "_" + numverso)
spanoccorrenza.appendTo(elementoverso)
//elementoverso.append('&nbsp;')
}
function createDivVersi(setVersi, cantica, num, canto) {
if (setVersi.has(cantica + "_" + num + "_" + canto))
return setVersi
else {
var elementoverso = $('<p />')
2022-12-06 11:25:04 +01:00
elementoverso.append(num + ". ")
elementoverso.attr("style", "line-height: 0.5em")
elementoverso.attr('class', 'f6 text-secondary text-nowrap font-weight-lighter')
elementoverso.attr('id', cantica + "_" + canto + "_" + num)
elementoverso.appendTo('#' + cantica + canto)
setVersi.add(cantica + "_" + num + "_" + canto)
return setVersi
}
}
/*
function createDivCanti(orderedListaCanti, cantica, canto) {
if (orderedListaCanti.has(canto)) {
return orderedListaCanti
}
var divcanto = $('<div />')
var titolocanto = $('<h4 class="titolo-canto pb-2" />')
titolocanto.append(cantica + ", " + canto)
divcanto.attr('class', 'canto')
divcanto.attr('style', 'display:none')
divcanto.attr('id', (cantica + canto).replace(" ", "_"))
titolocanto.appendTo(divcanto)
divcanto.appendTo(' .blog-main')
orderedListaCanti.add(canto)
return orderedListaCanti
}
*/
2022-12-12 13:30:59 +01:00
2022-12-14 09:04:42 +01:00
function createAllDivCanti() {
cantiche=["Inferno", "Purgatorio","Paradiso"]
for (cantica of cantiche){
for (var i=1; i<35; i++){
2022-12-14 09:04:42 +01:00
if(i==34 && cantica!=="Inferno"){
continue
}
canto= "Canto "+i
var divcanto = $('<div />')
var titolocanto = $('<h4 class="titolo-canto pb-2" />')
titolocanto.append(cantica + ", " + canto)
divcanto.attr('class', 'canto')
divcanto.attr('style', 'display:none')
divcanto.attr('id', (cantica + canto).replace(" ", "_"))
titolocanto.appendTo(divcanto)
divcanto.appendTo(' .blog-main')
}
}
}
2022-12-06 11:25:04 +01:00
//execute query
2022-11-11 22:11:22 +01:00
async function executeQuerySearch(query) {
$("#loader").show();
2022-11-11 22:11:22 +01:00
seachbBindingsStream = await myEngine.queryBindings(query, { sources: [{ type: 'sparql', value: sparqlEndpoint },], });
//console.log(query)
2022-11-11 22:11:22 +01:00
alert(query)
try {
var result = new Set()
var resultsInCantica = []
var resultsInCanto = []
2022-11-11 22:11:22 +01:00
seachbBindingsStream.on('data', (binding) => {
//cantica
cantica = binding.get('Cantica').value;
2022-11-11 22:11:22 +01:00
//canto
canto = binding.get('Canto').value;
2022-11-11 22:11:22 +01:00
//numero del verso
numverso = binding.get('NumeroVerso').value;
//posizione del frammento
pos = binding.get('pos').value;
if (!result.has(cantica + "_" + canto.replace(" ", "_") + "_" + numverso + "_" + pos)){
result.add(cantica + "_" + canto.replace(" ", "_") + "_" + numverso + "_" + pos)
resultsInCantica.push(cantica);
resultsInCanto.push(cantica + canto)
}
2022-11-11 22:11:22 +01:00
});
seachbBindingsStream.on('end', () => {
listarisultati = Array.from(result)
cantiche = ["Inferno", "Purgatorio", "Paradiso"]
//evidenzia risultati
for (ris of listarisultati) {
idris = '#' + ris
$(idris).attr('class', "font-weight-bold mark ")
2022-11-12 19:45:14 +01:00
}
//aggiunge badge con totale risultati accanto alle cantiche
i = 0
for (cantica of cantiche) {
i += 1
let count = resultsInCantica.reduce((n, x) => n + (x === cantica), 0);
2022-12-12 13:30:59 +01:00
if (count>0){
var spanbadgecantica = $('<span />');
spanbadgecantica.attr('class', 'badge badge-primary badge-pill ml-1');
spanbadgecantica.append(count)
spanbadgecantica.appendTo($('#cantica' + i))
}
}
//aggiunge badge con totale risultati accanto ai canti
for (cantica of cantiche) {
for (k of Array(35).keys()) {
if (k == 0)
continue
let count = resultsInCanto.reduce((n, x) => n + (x === cantica + 'Canto ' + k), 0);
2022-12-12 13:30:59 +01:00
if (count>0){
var spanbadge = $('<span />');
spanbadge.attr('class', cantobadgeclass);
spanbadge.append(count)
//$("[name='nameofobject']")
spanbadge.appendTo($('[name="' + cantica + 'Canto ' + k + '"]'))
//spanbadge.insertAfter($('[name="'+cantica+'Canto '+k+'"]'))
}
}
}
//aggiorna minimap
if (currentMinimap != '') {
2022-11-12 19:45:14 +01:00
showMinimap(currentMinimap)
2022-11-06 17:12:56 +01:00
}
$("#loader").hide();
2022-11-08 10:44:20 +01:00
2022-11-06 17:12:56 +01:00
});
}
2022-11-08 10:44:20 +01:00
catch (err) {
console.log(err.message);
2022-11-06 17:12:56 +01:00
};
2022-11-06 17:12:56 +01:00
};
2022-11-08 10:44:20 +01:00
/*
* REGOLE DI PARSING PER VISUALIZZAZIONE PROPRIETÀ
*/
var categoriegrammaticaliGrammar=`Expression = head:(Filtro){return 'Verbo,'+head.join()}
Filtro= fhead:("v")? tail:( transitivita? diatesi? impersonalita?
coniugazione? modotempo?
persona? funzione? declinazione?
genere? numero? grado?){return tail}
diatesi= [a|p] {if (text()=='a') return ' Attivo'; else return ' Passivo';}
transitivita=[i|t]? {if (text()=='t') return ' Transitivo'; else if (text()=='i') return ' Intransitivo';}
impersonalita=([*|+])? {if (text()=='*') return ' Impersonale'; else if (text()=='+')return ' Riflessivo';}
coniugazione=[1|2|3|4|5]? {switch(parseInt(text())){
case(1): return ' Prima coniugazione';
case(2): return ' Seconda coniugazione';
case(3): return ' Terza coniugazione';
case(4): return ' Ausiliare essere'
case(5): return ' Ausiliare avere'}}
modotempo=modo:"ip" {return('Presente indicativo')}/
"ib" {return("Passato Prossimo Indicativo")}/
"ii" {return("Imperfetto Indicativo")}/
"ir" {return("Passato Remoto Indicativo")}/
"is" {return( "Trapassato Prossimo Indicativo")}/
"it" {return( "Trapassato Remoto Indicativo")}/
"if" {return("Futuro Semplice Indicativo")}/
"ia" {return("Futuro Anteriore Indicativo")}/
"cp" {return( "Presente Congiuntivo")}/
"ci" {return( "Imperfetto Congiuntivo")}/
"cr" {return( "Passato Congiuntivo")}/
"ct" {return( "Trapassato Congiuntivo")}/
"dp" {return( "Presente Condizionale")}/
"dr" {return( "Passato Condizionale")}/
"mp" {return( "Presente Imperativo")}/
"fp" {return( "Presente Infinito")}/
"fr" {return( "Passato Infinito")}/
"pp" {return( "Presente Participio")}/
"pr" {return( "Passato Participio")}/
"gp" {return( "Presente Gerundio")}/
"gr" {return( "Passato Gerundio")}/
"pf" {return( "Participio Futuro")}
persona="s1" {return('Prima persona singolare')}/
"s2" {return('Seconda persona singolare')}/
"s3" {return('Terza persona singolare')}/
"p1" {return('Prima persona plurale')}/
"p2" {return('Seconda persona plurale')}/
"p3" {return('Terza persona plurale')}
funzione="a" {return('Verbo Funzione Aggettivo')}/
"sm" {return('Verbo Funzione Sostantivo maschile')}/
"sf" {return('Verbo Funzione Sostantivo femminile')}/
"b" {return('Verbo Funzione Avverbio')}/
"l" {return('Verbo Funzione Locuzione')}
declinazione=[1|2|3|4|5] {switch(parseInt(text())){
case(1): return ' Prima declinazione';
case(2): return ' Seconda declinazione';
case(3): return ' Terza declinazione';
case(4): return ' nd'
case(5): return ' nd'}}
genere=[f|m] {if (text()=='f') return ' Femminile'; else if (text()=='m') return ' Maschile';}
numero=[s|p] {if (text()=='s') return ' Singolare'; else if (text()=='p') return ' Plurale';}
grado="c+" {return('Grado c+ singolare')}/
"c-" {return('Grado c-')}/
"c=" {return('Grado c=')}
Integer "integer"
= _ [0-9]+ { return parseInt(text(), 10); }
_ "whitespace"= " "*
`
var categoriaGrammaticaleSostantivo = `
Expression = head:(Filtro){return 'Sostantivo,'+head.join()}
Filtro= fhead:("s")? tail:( genereforma? declinazionesostantivo? generelemma?
numersingolareplurale? locuzione?){return tail}
declinazionesostantivo= [1|2|3]? {switch(parseInt(text())){
case(1): return ' Prima declinazione';
case(2): return ' Seconda declinazione';
case(3): return ' Terza declinazione'}}
genereforma=[m|f]? {if (text()=='m') return ' maschile'; else if (text()=='f') return ' femminile';}
generelemma=[m|f]? {if (text()=='m') return ' maschile'; else if (text()=='f') return ' femminile';}
numersingolareplurale=[s|p]? {if (text()=='s') return ' numero singolare'; else if (text()=='p') return ' numero plurale';}
locuzione="Iv" {return('In Locuzione verbo');}
Integer "integer"
= _ [0-9]+ { return parseInt(text(), 10); }
_ "whitespace"= " "*
`
2022-11-08 10:44:20 +01:00
2022-11-06 17:12:56 +01:00
});