diff --git a/css/browsingldc.css b/css/browsingldc.css index 44f223d..8788817 100644 --- a/css/browsingldc.css +++ b/css/browsingldc.css @@ -22,13 +22,17 @@ * Footer */ + #displaycanto span:hover { - color: red; + color: blue; } + + /* Popover properties */ +/* .popover-header { color: blue; font-size: 13px; @@ -41,6 +45,7 @@ Popover properties color: gray; font-size: 10px; } +*/ /* Minimap @@ -105,21 +110,26 @@ Minimap display: inline-block; } + .Nik_dropdown-content { - display: none; - position: absolute; + /*display: none;*/ + /*position: absolute; top: -60px; left: 50px; - background-color: rgb(252, 252, 252); - min-width: 270px; + background-color: rgb(252, 252, 252);*/ + background-color: #92a8d1; + max-width: 170px; + /*min-width: 70px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); - padding: 8px 8px; - color:red; - font-size: 10; + padding: 8px 8px;*/ + color:blue; + font-size: 10px; z-index: 1; - float: top; + /*float: top;*/ } .Nik_dropdown:hover .Nik_dropdown-content { display: block; } + + diff --git a/index_3.3bis.html b/index_3.3bis.html index ab0daa2..65bc9ed 100644 --- a/index_3.3bis.html +++ b/index_3.3bis.html @@ -8,7 +8,7 @@ - + diff --git a/js/cesareBrowse.js b/js/cesareBrowse.js index 6709655..b5bf080 100644 --- a/js/cesareBrowse.js +++ b/js/cesareBrowse.js @@ -1,10 +1,714 @@ /** * */ - var resetResult; + + +var resetResult; +var lsid; $(document).ready(function() { + lsid=''; + const posyntstruct=`
+
+
+ + ` + + const cantobadgeclass = 'badge badge-outline-info badge-pill' + const sparqlGenerator = sparqljs.Generator; + const myEngine = new Comunica.QueryEngine(); + const sparqlEndpoint = "https://hdnlab1.isti.cnr.it/fuseki/commediaontosintgra/query"; + + var shownSentenceList = new Set() + + var currentMinimap = '' + var listarisultati = []; + var resultSentences = new Set() + var minimapScrolling = false; + var displayId = 'displaycanto' + var minimapTopPos; + var purgatorioLoaded = false; + var paradisoLoaded = false; + + //used in minimap + // + let minimap = document.createElement('div'); + let minimapSize = document.createElement('div'); + let viewer = document.createElement('div'); + let minimapContent = document.createElement('iframe'); + let realScale; + let mappedElement = ''; + + resetResult=function(){ + //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`); + + + + +$(" .Ma, .Co, .Su, .Pa").each(function(idx, element) { + // We cycle through the elements using each() so that we can choose the element specifically that we wish to clean up afterward + var ele = $(element); + ele.tooltip({ + content: (function() {return formatTTContent(ele.attr('title'));}), + classes:{"ui-tooltip":'Nik_dropdown-content'}, + close: function (event, ui) {$(".ui-helper-hidden-accessible").remove();}, + create: function(ev, ui) {$(this).data("ui-tooltip").liveRegion.remove();}, + hide: false, + show: false + + }); + }); + +/* + + $(" .Ma, .Co, .Su, .Pa").tooltip({ + content: (function() {return formatTTContent($(this).attr('title'));}), + classes:{"ui-tooltip":'Nik_dropdown-content'}, + close: function (event, ui) {$(".ui-helper-hidden-accessible").remove();}, + create: function(ev, ui) { + $(this).data("ui-tooltip").liveRegion.remove();}, + hide: false, + show: false + }); + + */ + + + + + + /*$(""[data-cg]").hover(function() { + console.log('here') + var details=getHoverContent($(this).data("cg")) + var index = details.indexOf(","); + var sentencetype= $(this).attr('class'); + + var categoria = ""; + if (index != -1){ + categoria = details.substring(0,index); + details = details.substring(index+1); + }else{ + categoria = details; + details = ""; + } + /*$(this).popover({title: catgramm, content: subcatgramm+"
"+posyntstruct, + html:true, placement: "top", + trigger: "click"}).on("hidden.bs.popover", function(e) { + sentenceId=$(this).attr('class').split(' ')[0].replace('$',''); + resetSentenceStructure(sentenceId) + shownSentenceList.delete(sentenceId) + }) + + .on("shown.bs.popover", function(es){ + + ids=sentencetype.split("_") + sentenceId=$(this).attr('class').split(' ')[0].replace('$','') + lisid=ids[0]+'_'+ids[1]+'_'+ids[3] + lisid=lisid.split(" ")[0] + console.log('show '+lisid) + }); + });*/ + + + jQuery(document).delegate('#sentence', 'click', function(e) { + e.preventDefault(); + sentenceId=$(this).attr('class').split(' ')[0].replace('$','') + console.log(sentenceId) + if (shownSentenceList.has(sentenceId)){ + resetSentenceStructure(sentenceId) + shownSentenceList.delete(sentenceId) + } + else{ + showSentenceStructure (sentenceId) + shownSentenceList.add(sentenceId) + } + + }); + + var mmih = 0 + var mmiw = 0 + + + $("#" + displayId).scroll(function() { + if (minimapScrolling) { + minimapScrolling = false + console.log('no scroll') + } + else { + console.log('yes scrolling') + console.log("viewer top pos before: " + $('#minimapviewer').offset().top) + trackScrollCanto() + console.log("viewer top pos after: " + $('#minimapviewer').offset().top) + } + }); + + + + jQuery(document).delegate('.navig-canto', 'click', function(e) { + $('.canto').each(function() { + $(this).attr("style", 'display:none'); + }); + // Crea id per la div che contiene il canto + $("#" + $(this).attr('name').replace(" ", "_")).attr('style', 'display:block') + manageMiniMap(this); + + }); + + function manageMiniMap(divElem) { + mmiw = $("#" + displayId).innerWidth(); + mmih = $("#" + displayId).innerHeight(); + drawMinimap($(divElem).attr('name').replace(" ", "_")) + } + + //Query + + jQuery(document).delegate('#searchcomm, #searchcomm2', 'click', function(e) { + e.preventDefault(); + manageQuery() + }); + + + //Reset + + jQuery(document).delegate('#cleanresult', 'click', function(e) { + console.log('clean') + cleanSearchResult() + esprlogica = [] + $('#queryText').val("") + + }); + + //Utility functions + + function formatTTContent(categ){ + var details=getHoverContent(categ) + var myitems=details.split(',') + let catgramm=''+myitems[0]+'' + let subcatgramm='' + if (myitems.length>1) + subcatgramm=''+myitems.slice(1,-1)+'' + return (catgramm+subcatgramm) + } + + 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'){ + return parserVerbi.parse(categ).split(',').filter(prop => prop.length > 0).join() + } + if(categ[0]=='s'){ + return parserSostantivi.parse(categ).split(',').filter(prop => prop.length > 0).join() + } + if(categ[0]=='e'){ + return parserPreposizioni.parse(categ).split(',').filter(prop => prop.length > 0).join() + } + if(categ[0]=='b'){ + return parserAvverbi.parse(categ).split(',').filter(prop => prop.length > 0).join() + } + if(categ[0]=='p'){ + return parserPronomi.parse(categ).split(',').filter(prop => prop.length > 0).join() + } + if(categ[0]=='a'){ + return parserAggettivi.parse(categ).split(',').filter(prop => prop.length > 0).join() + } + if(categ[0]=='r'){ + return parserArticolo.parse(categ).split(',').filter(prop => prop.length > 0).join() + } + if (categ[0] == 'f') { + return parserCitazione.parse(categ).split(',').filter(prop => prop.length > 0).join(); + } + if (categ[0] == 'n') { + return parserOnomastica.parse(categ).split(',').filter(prop => prop.length > 0).join(); + } + if (categ[0] == 'c') { + return parserCongiunzione.parse(categ).split(',').filter(prop => prop.length > 0).join(); + } + return categoriegrammaticali[categ[0]] + } + + function drawMinimap(name){ + + showMinimap(name) + currentMinimap = name; + + //mmviewer diventa draggable + var 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); + } + }); + } + + function cleanSearchResult() { + for (forma of listarisultati) { + idforma = '#' + forma + $(idforma).removeClass("font-weight-bold mark ") + } + $(".badge").remove(); + listarisultati = [] + resultSentences=new Set() + if (currentMinimap != '') + showMinimap(currentMinimap) + } + + var unitaRicerca='forma' + + function manageQuery(){ + cleanSearchResult() + esprlogica = [] + jsonQuery=getJsonQuery() + + unitaRicerca=jsonQuery['unitaRicerca'] + console.log("got json query, unita ricerca: "+unitaRicerca) + if(jsonQuery['QueryAvanzata']==0 && jsonQuery['Clausola0']['queryText']==''){ + alert('Digitare una stringa da cercare') + return + } + + jsonQuery = buildSQ(jsonQuery) + + myquery = new sparqlGenerator().stringify(jsonQuery) + console.log(myquery) + executeQuerySearch(myquery) + } + + + + //manage sentence and clauses + + function showSentenceStructure(sentence) { + + sid = '.' + sentence.toString() + //console.log(sid) + $(sid).addClass('font-italic') + + $(sid).each(function(){ + //console.log($(this).attr('class')) + if ($(this).attr('class').includes(' Ma ')){ + $(this).addClass("text-primary font-weight-normal") + } + if ($(this).attr('class').includes(' Su ')){ + $(this).addClass("text-info font-weight-normal") + } + if ($(this).attr('class').includes(' Co ')){ + $(this).addClass("text-warning font-weight-normal") + } + if ($(this).attr('class').includes(' Pc ')){ + $(this).addClass("text-success font-weight-normal") + } + if ($(this).attr('class').includes(' Pa ')){ + $(this).addClass("text-secondary font-weight-normal") + } + }) + + } + + function resetSentenceStructure(sentence) { + $(" ." + sentence).removeClass('text-info font-weight-normal') + $(" ." + sentence).removeClass('text-primary font-weight-normal') + $(" ." + sentence).removeClass('text-secondary font-weight-normal') + $(" ." + sentence).removeClass('text-warning font-weight-normal') + $(" ." + sentence).removeClass('text-success font-weight-normal') + $(" ." + sentence).removeClass('font-italic') + } + + //minimap management + + + 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' + minimap.append(minimapSize, viewer, minimapContent); + + mmplace.appendChild(minimap) + + let html = document.getElementById(element).outerHTML//innerHTML + if (html == null | html == '') + return; + + let iFrameDoc = minimapContent.contentWindow.document; + var cssLinkb = document.createElement("link"); + cssLinkb.href = "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"; + cssLinkb.rel = "stylesheet"; + cssLinkb.type = "text/css"; + + var cssLinkscroll = document.createElement("link"); + cssLinkscroll.href = "./css/browsingldc.css"; + cssLinkscroll.rel = "stylesheet"; + cssLinkscroll.type = "text/css"; + + iFrameDoc.open(); + iFrameDoc.write(html); + iFrameDoc.close(); + + iFrameDoc.head.appendChild(cssLinkb); + iFrameDoc.head.appendChild(cssLinkscroll); + mappedElement = element + + getDimensionsDiv() + + window.addEventListener('scroll', trackScroll) + window.addEventListener('resize', getDimensionsDiv) + } + + + + + function getInnerHeight(elm) { + var computed = getComputedStyle(elm), + padding = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom); + + return elm.clientHeight - padding + } + + function getDimensionsDiv() { + var cantoplace = document.getElementById(displayId) + var elementplace = document.getElementById(mappedElement) + + var bodyWidth = elementplace.clientWidth; + var bodyRatio = elementplace.clientHeight / bodyWidth; + + let winRatio = getInnerHeight(cantoplace) / (cantoplace.clientWidth); + + //minimap.style.width='15%'; + minimap.style.width = '100%'; + + realScale = minimap.clientWidth / bodyWidth; + + 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'; + } + + function trackScroll() { + //console.log(window.scrollY) + viewer.style.transform = `translateY(${window.scrollY * realScale}px)` + } + 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() { + $('.canto').each(function() { + $(this).attr("style", 'display:none'); + }); + $(".minimap__container").remove(); + currentMinimap = '' + } + + //Cantica management functions + + function showCantica(cantica) { + //var listaCanti = new Set() + var setVersi = new Set() + var containerForme = formeprima + var idcantica=1; + if (cantica == 'Paradiso'){ + containerForme = formeterza + idcantica=3 + } + + if (cantica == 'Purgatorio'){ + containerForme = formeseconda + idcantica=2 + } + + const endlc = performance.now(); + console.log(`Load `+cantica+` time: ${endlc - start} ms`); + var elverso, formaItem + for (var cmpItem of containerForme) { + + formaItem = cmpItem.split("_") + var sentenceid=idcantica+"_"+formaItem[1]+"_s_"+formaItem[5] + //createDivVerso(cantica, num, canto, forma, catgram, pos) + if (! setVersi.has(cantica + "_" + formaItem[3] + "_" + 'Canto_' + formaItem[1])){ + elverso=createDivVerso(cantica, formaItem[3], 'Canto_' + formaItem[1], formaItem[0], formaItem[4], formaItem[2], sentenceid,formaItem[6]) + setVersi.add(cantica+ "_" + formaItem[3] + "_" + 'Canto_' + formaItem[1]) + } + else{ + createSpanFormeNew(cantica, 'Canto_' + formaItem[1], formaItem[3], formaItem[0], formaItem[4], formaItem[2], sentenceid,formaItem[6],elverso) + } + + } + return + } + + + function createSpanFormeNew(cantica, canto, numverso, forma, catgramm, pos, sentenceid, clausefunct, elementoverso) { + var spanoccorrenza = $('') + spanoccorrenza.attr('id', pos) + //spanoccorrenza.attr('data-cg', catgramm) + spanoccorrenza.attr('title', catgramm) + spanoccorrenza.attr('class', sentenceid+" "+clausefunct) + + //if (listarisultati.length > 0 && listarisultati.includes(spanoccorrenza.attr('id'))) + // spanoccorrenza.attr('class', "font-weight-bold mark ") + spanoccorrenza.append(forma+" ") + + spanoccorrenza.appendTo(elementoverso) + + } + + function createDivVerso(cantica, num, canto, forma, catgram, pos, sentenceid, clausefunct) { + + var elementoverso = $('

') + + elementoverso.append(num + ". ") + elementoverso.attr("style", "line-height: 0.5em") + + elementoverso.attr('class', 'f6 text-secondary text-nowrap font-weight-lighter '+cantica+' '+canto) + + elementoverso.attr('id', cantica + "_" + canto + "_" + num) + + var spanoccorrenza = $('') + + spanoccorrenza.attr('id', pos) + //spanoccorrenza.attr('data-cg', catgram) + spanoccorrenza.attr('title', catgram) + spanoccorrenza.attr('class', sentenceid+" "+clausefunct) + + spanoccorrenza.append(forma+" ") + spanoccorrenza.appendTo(elementoverso) + + elementoverso.appendTo('#' + cantica + canto) + return elementoverso + + } + + + function createAllDivCanti() { + var cantiche=["Inferno", "Purgatorio","Paradiso"] + for (cantica of cantiche){ + for (var i=1; i<35; i++){ + if(i==34 && cantica!=="Inferno"){ + continue + } + canto= "Canto "+i + var divcanto = $('

') + var titolocanto = $('

') + 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') + } + } + } + + //execute query + + async function executeQuerySearch(query) { + seachbBindingsStream = await myEngine.queryBindings(query, { sources: [{ type: 'sparql', value: sparqlEndpoint },], }); + //console.log(query) + alert(query) + try { + var result = new Set() + var resultClauses = new Set() + + var resultsInCantica = [] + var resultsInCanto = [] + seachbBindingsStream.on('data', (binding) => { + //cantica + if (binding.has('Cantica')) + cantica = binding.get('Cantica').value; + else + cantica='Nessuna' + + + //canto + if (binding.has('Canto')) + canto = binding.get('Canto').value; + else + canto='Canto 0' + + //numero del verso + if (binding.has('NumeroVerso')) + numverso = binding.get('NumeroVerso').value; + else + numverso=0 + //posizione del frammento + if (binding.has('pos')) + pos = binding.get('pos').value; + else{ + pos = 0; + } + + //regione della clausola + var clfrom=binding.get('clfr').value; + var clto=binding.get('clto').value; + var cltype=binding.get('clatype').value + //id del periodo + var sentenceid=binding.get('sentence').value.replace('http://dantenetwork.it/data/commedia/','') + + if (pos>0 && !result.has(pos)){ + + result.add(pos) + resultsInCantica.push(cantica); + resultsInCanto.push(cantica + canto) + } + resultClauses.add(sentenceid + "-" +clfrom+'-'+clto+"-"+cltype+'-'+cantica+'-'+canto) + resultSentences.add(sentenceid) + + }); + seachbBindingsStream.on('end', () => { + var resSent=new Set() + console.log('start rendering...') + listarisultati = Array.from(result) + var listaclausole=Array.from(resultClauses) + + cantiche = ["Inferno", "Purgatorio", "Paradiso"] + + if (!listarisultati.length || unitaRicerca=='frase'){ + + resultsInCantica=[] + resultsInCanto=[] + if (listaclausole.length){ + for (var frase of listaclausole){ + var fraseItems=frase.split('-'); + for (var p=parseInt(fraseItems[1]); p n + (x === cantica), 0); + if (count>0){ + var spanbadgecantica = $(''); + 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 + console.log('results end...') + + //console.log(sid) + var $nctags= $(' .navig-canto') + + + 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); + if (count>0){ + var spanbadge = $(''); + spanbadge.attr('class', cantobadgeclass); + spanbadge.append(count) + //spanbadge.appendTo($('[name="' + cantica + 'Canto ' + k + '"]')) + spanbadge.appendTo($nctags.filter('[name="' + cantica + 'Canto ' + k + '"]')) + //spanbadge.insertAfter($('[name="'+cantica+'Canto '+k+'"]')) + } + } + } + console.log('badge end...') + + //aggiorna minimap + if (currentMinimap != '') { + showMinimap(currentMinimap) + } + + }); + } + catch (err) { + console.log(err.message); + }; + + }; /* * REGOLE DI PARSING PER VISUALIZZAZIONE CATEGORIE GRAMMATICALI @@ -425,10 +1129,10 @@ Filtro= fhead:("c") tail:( tipo? cordinativasubordinativa? tipocoordinativa? tiposubordinativa* complementodue?){return tail} -tipo = "s" {return(' Semplice')}/ +tipo = "lx" {return(' LocuzioneSeparata')}/ "c" {return(" Composta")}/ "l" {return(" Locuzione")}/ - "lx" {return(" LocuzioneSeparata")} + "s" {return(" Semplice")} cordinativasubordinativa = "c" {return(" Coordinativa")}/ "s" {return(" Subordinativa")} @@ -476,671 +1180,4 @@ var parserOnomastica = peg.generate(onomastica); var parserCongiunzione = peg.generate(congiunzione); - - - - - - const cantobadgeclass = 'badge badge-outline-info badge-pill' - - const sparqlGenerator = sparqljs.Generator; - const myEngine = new Comunica.QueryEngine(); - const sparqlEndpoint = "https://hdnlab1.isti.cnr.it/fuseki/commediaontosintgra/query"; - - var shownSentenceList = new Set() - - var currentMinimap = '' - var listarisultati = []; - var resultSentences = new Set() - var minimapScrolling = false; - var displayId = 'displaycanto' - var minimapTopPos; - var purgatorioLoaded = false; - var paradisoLoaded = false; - - //used in minimap - // - let minimap = document.createElement('div'); - let minimapSize = document.createElement('div'); - let viewer = document.createElement('div'); - let minimapContent = document.createElement('iframe'); - let realScale; - let mappedElement = ''; - - resetResult=function(){ - //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`); - - - - /*$("[data-cg]").hover(function() { - var details=getHoverContent($(this).data("cg")) - var index = details.indexOf(","); - var sentencetype= $(this).attr('class'); - - var categoria = ""; - if (index != -1){ - categoria = details.substring(0,index); - details = details.substring(index+1); - }else{ - categoria = details; - details = ""; - } - $(this).popover({title: categoria, content: details+"", html:true, placement: "top", - trigger: "click"}).on("hidden.bs.popover", function(e) { - sentenceId=$(this).attr('class').split(' ')[0].replace('$',''); - resetSentenceStructure(sentenceId) - shownSentenceList.delete(sentenceId) - }); - });*/ - /* - jQuery(document).delegate('#cantica2', 'click', function(e) { - e.preventDefault(); - - if (!purgatorioLoaded){ - showCantica('Purgatorio') - purgatorioLoaded = true; - } - - }); - jQuery(document).delegate('#cantica3', 'click', function(e) { - e.preventDefault(); - - if (!paradisoLoaded){ - showCantica('Paradiso') - paradisoLoaded = true; - } - - }); - */ - - jQuery(document).delegate('#sentence', 'click', function(e) { - e.preventDefault(); - sentenceId=$(this).attr('class').split(' ')[0].replace('$','') - console.log(sentenceId) - if (shownSentenceList.has(sentenceId)){ - resetSentenceStructure(sentenceId) - shownSentenceList.delete(sentenceId) - } - else{ - showSentenceStructure (sentenceId) - shownSentenceList.add(sentenceId) - } - - }); - - var mmih = 0 - var mmiw = 0 - - - $("#" + displayId).scroll(function() { - if (minimapScrolling) { - minimapScrolling = false - console.log('no scroll') - } - else { - console.log('yes scrolling') - console.log("viewer top pos before: " + $('#minimapviewer').offset().top) - trackScrollCanto() - console.log("viewer top pos after: " + $('#minimapviewer').offset().top) - } - }); - - - - jQuery(document).delegate('.navig-canto', 'click', function(e) { - $('.canto').each(function() { - $(this).attr("style", 'display:none'); - }); - // Crea id per la div che contiene il canto - $("#" + $(this).attr('name').replace(" ", "_")).attr('style', 'display:block') - manageMiniMap(this); - - }); - - function manageMiniMap(divElem) { - mmiw = $("#" + displayId).innerWidth(); - mmih = $("#" + displayId).innerHeight(); - drawMinimap($(divElem).attr('name').replace(" ", "_")) - } - - //Query - - jQuery(document).delegate('#searchcomm, #searchcomm2', 'click', function(e) { - e.preventDefault(); - manageQuery() - }); - - - //Reset - - jQuery(document).delegate('#cleanresult', 'click', function(e) { - console.log('clean') - cleanSearchResult() - esprlogica = [] - $('#queryText').val("") - - }); - - //Utility functions - - function getHoverContent(categ){ - //console.log('Categoria '+categ) - - try { - - 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'){ - return parserVerbi.parse(categ).split(',').filter(prop => prop.length > 0).join() - } - if(categ[0]=='s'){ - return parserSostantivi.parse(categ).split(',').filter(prop => prop.length > 0).join() - } - if(categ[0]=='e'){ - return parserPreposizioni.parse(categ).split(',').filter(prop => prop.length > 0).join() - } - if(categ[0]=='b'){ - return parserAvverbi.parse(categ).split(',').filter(prop => prop.length > 0).join() - } - if(categ[0]=='p'){ - return parserPronomi.parse(categ).split(',').filter(prop => prop.length > 0).join() - } - if(categ[0]=='a'){ - return parserAggettivi.parse(categ).split(',').filter(prop => prop.length > 0).join() - } - if(categ[0]=='r'){ - return parserArticolo.parse(categ).split(',').filter(prop => prop.length > 0).join() - } - if (categ[0] == 'f') { - return parserCitazione.parse(categ).split(',').filter(prop => prop.length > 0).join(); - } - if (categ[0] == 'n') { - return parserOnomastica.parse(categ).split(',').filter(prop => prop.length > 0).join(); - } - if (categ[0] == 'c') { - return parserCongiunzione.parse(categ).split(',').filter(prop => prop.length > 0).join(); - }else{ - return categoriegrammaticali[categ[0]] - } - } catch (Exception ) { - console.log("error parsing "+categ) - return ("error parsing "+categ); - } - } - - function drawMinimap(name){ - - showMinimap(name) - currentMinimap = name; - - //mmviewer diventa draggable - var 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); - } - }); - } - - function cleanSearchResult() { - for (forma of listarisultati) { - idforma = '#' + forma - $(idforma).removeClass("font-weight-bold mark ") - } - $(".badge").remove(); - listarisultati = [] - resultSentences=new Set() - if (currentMinimap != '') - showMinimap(currentMinimap) - } - - - 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 - } - jsonQuery = buildSQ(jsonQuery) - - myquery = new sparqlGenerator().stringify(jsonQuery) - console.log(myquery) - executeQuerySearch(myquery) - } - - //manage sentence and clauses - - function showSentenceStructure(sentence) { - - sid = '.' + sentence.toString() - //console.log(sid) - $(sid).addClass('font-italic') - - $(sid).each(function(){ - //console.log($(this).attr('class')) - if ($(this).attr('class').includes(' Ma ')){ - $(this).addClass("text-primary font-weight-normal") - } - if ($(this).attr('class').includes(' Su ')){ - $(this).addClass("text-info font-weight-normal") - } - if ($(this).attr('class').includes(' Co ')){ - $(this).addClass("text-warning font-weight-normal") - } - if ($(this).attr('class').includes(' Pc ')){ - $(this).addClass("text-success font-weight-normal") - } - if ($(this).attr('class').includes(' Pa ')){ - $(this).addClass("text-secondary font-weight-normal") - } - }) - - } - - function resetSentenceStructure(sentence) { - $(" ." + sentence).removeClass('text-info font-weight-normal') - $(" ." + sentence).removeClass('text-primary font-weight-normal') - $(" ." + sentence).removeClass('text-secondary font-weight-normal') - $(" ." + sentence).removeClass('text-warning font-weight-normal') - $(" ." + sentence).removeClass('text-success font-weight-normal') - $(" ." + sentence).removeClass('font-italic') - } - - //minimap management - - - 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' - minimap.append(minimapSize, viewer, minimapContent); - - mmplace.appendChild(minimap) - - let html = document.getElementById(element).outerHTML//innerHTML - if (html == null | html == '') - return; - - let iFrameDoc = minimapContent.contentWindow.document; - var cssLinkb = document.createElement("link"); - cssLinkb.href = "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"; - cssLinkb.rel = "stylesheet"; - cssLinkb.type = "text/css"; - - var cssLinkscroll = document.createElement("link"); - cssLinkscroll.href = "./css/browsingldc.css"; - cssLinkscroll.rel = "stylesheet"; - cssLinkscroll.type = "text/css"; - - iFrameDoc.open(); - iFrameDoc.write(html); - iFrameDoc.close(); - - iFrameDoc.head.appendChild(cssLinkb); - iFrameDoc.head.appendChild(cssLinkscroll); - mappedElement = element - - getDimensionsDiv() - - window.addEventListener('scroll', trackScroll) - window.addEventListener('resize', getDimensionsDiv) - } - - - - - function getInnerHeight(elm) { - var computed = getComputedStyle(elm), - padding = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom); - - return elm.clientHeight - padding - } - - function getDimensionsDiv() { - var cantoplace = document.getElementById(displayId) - var elementplace = document.getElementById(mappedElement) - - var bodyWidth = elementplace.clientWidth; - var bodyRatio = elementplace.clientHeight / bodyWidth; - - let winRatio = getInnerHeight(cantoplace) / (cantoplace.clientWidth); - - //minimap.style.width='15%'; - minimap.style.width = '100%'; - - realScale = minimap.clientWidth / bodyWidth; - - 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'; - } - - function trackScroll() { - //console.log(window.scrollY) - viewer.style.transform = `translateY(${window.scrollY * realScale}px)` - } - 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() { - $('.canto').each(function() { - $(this).attr("style", 'display:none'); - }); - $(".minimap__container").remove(); - currentMinimap = '' - } - - //Cantica management functions - - function showCantica(cantica) { - //var listaCanti = new Set() - var setVersi = new Set() - var containerForme = formeprima - var idcantica=1; - if (cantica == 'Paradiso'){ - containerForme = formeterza - idcantica=3 - } - - if (cantica == 'Purgatorio'){ - containerForme = formeseconda - idcantica=2 - } - - const endlc = performance.now(); - console.log(`Load `+cantica+` time: ${endlc - start} ms`); - var elverso, formaItem - for (var cmpItem of containerForme) { - - formaItem = cmpItem.split("_") - var sentenceid=idcantica+"_"+formaItem[1]+"_s_"+formaItem[5] - //createDivVerso(cantica, num, canto, forma, catgram, pos) - if (! setVersi.has(cantica + "_" + formaItem[3] + "_" + 'Canto_' + formaItem[1])){ - elverso=createDivVerso(cantica, formaItem[3], 'Canto_' + formaItem[1], formaItem[0], formaItem[4], formaItem[2], sentenceid,formaItem[6]) - setVersi.add(cantica+ "_" + formaItem[3] + "_" + 'Canto_' + formaItem[1]) - } - else{ - createSpanFormeNew(cantica, 'Canto_' + formaItem[1], formaItem[3], formaItem[0], formaItem[4], formaItem[2], sentenceid,formaItem[6],elverso) - } - - } - return - } - - - function createSpanFormeNew(cantica, canto, numverso, forma, catgramm, pos, sentenceid, clausefunct, elementoverso) { - var divOccorrenza = $('
') - divOccorrenza.attr('id', pos) - divOccorrenza.attr('class', sentenceid+" "+clausefunct+" "+"Nik_dropdown-content") - - var details=getHoverContent(catgramm); - if (details == null || (typeof details == 'undefined')){ - details = "error details is null for catgramm "+ catgramm; - console.log("error details is null for catgramm "+ catgramm) - } - var index = details.indexOf(","); - var categoria = ""; - if (index != -1){ - categoria = details.substring(0,index); - details = details.substring(index+1); - }else{ - categoria = details; - details = ""; - } - - var divSpan = $('
') - divSpan.attr('class','Nik_dropdown') - var spanWord = $(''); - spanWord.attr('data-cg', catgramm) - - spanWord.append (forma+" "); - divSpan.append(spanWord) - - var pCategoria = $('

'); - pCategoria.attr("style", "color:Blue; font-weight: 600;"); - - pCategoria.append(categoria); - var pDetails = $('

') - pDetails.attr("style", "line-height: 1.5em; color:Red; font-weight: 300;"); - - pCategoria.appendTo(divOccorrenza); - divOccorrenza.append ("


") - - pDetails.append(details); - pDetails.appendTo(divOccorrenza) - divOccorrenza.appendTo(divSpan) - divSpan.appendTo(elementoverso) - } - - function createDivVerso(cantica, numverso, canto, forma, catgramm, pos, sentenceid, clausefunct) { - - var details=getHoverContent(catgramm); - - if (details == null || (typeof details == 'undefined')){ - details = "error details is null for catgramm "+ catgramm; - console.log("error details is null for catgramm "+ catgramm) - } - var index = details.indexOf(","); - - var categoria = ""; - if (index != -1){ - categoria = details.substring(0,index); - details = details.substring(index+1); - }else{ - categoria = details; - details = ""; - } - var elementoverso = $('

') - - elementoverso.append(numverso + ". ") - elementoverso.attr("style", "line-height: 0.5em") - - elementoverso.attr('class', 'f6 text-secondary font-weight-lighter '+cantica+' '+canto) - - elementoverso.attr('id', cantica + "_" + canto + "_" + numverso) - - var divOccorrenza = $('

') - - divOccorrenza.attr('id', pos) - divOccorrenza.attr('class', sentenceid+" "+clausefunct+" "+"Nik_dropdown-content") - - - var divSpan = $('
') - divSpan.attr('class','Nik_dropdown') - var spanWord = $(''); - spanWord.append (forma+" "); - spanWord.attr('data-cg', catgramm) - - divSpan.append(spanWord) - var pCategoria = $('

'); - pCategoria.attr("style", "color:Blue; font-weight: 600;"); - - var pDetails = $('

') - pDetails.attr("style", "line-height: 1.5em; color:Red; font-weight: 300;"); - pCategoria.append(categoria); - - pCategoria.appendTo(divOccorrenza); - divOccorrenza.append ("


") - pDetails.append(details); - pDetails.appendTo(divOccorrenza) - divOccorrenza.appendTo(divSpan) - divSpan.appendTo(elementoverso) - - - elementoverso.appendTo('#' + cantica + canto) - - return elementoverso - - } - - - function createAllDivCanti() { - cantiche=["Inferno", "Purgatorio","Paradiso"] - for (cantica of cantiche){ - for (var i=1; i<35; i++){ - if(i==34 && cantica!=="Inferno"){ - continue - } - canto= "Canto "+i - var divcanto = $('
') - var titolocanto = $('

') - 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') - } - } - } - - //execute query - async function executeQuerySearch(query) { - seachbBindingsStream = await myEngine.queryBindings(query, { sources: [{ type: 'sparql', value: sparqlEndpoint },], }); - //console.log(query) - alert(query) - try { - var result = new Set() - var resultClauses = new Set() - - var resultsInCantica = [] - var resultsInCanto = [] - seachbBindingsStream.on('data', (binding) => { - //cantica - cantica = binding.get('Cantica').value; - - //canto - canto = binding.get('Canto').value; - - //numero del verso - numverso = binding.get('NumeroVerso').value; - //posizione del frammento - pos = binding.get('pos').value; - //regione della clausola - var clfrom=binding.get('clfr').value; - var clto=binding.get('clto').value; - var cltype=binding.get('clatype').value - //id del periodo - var sentenceid=binding.get('sentence').value.replace('http://dantenetwork.it/data/commedia/','') - //console.log(sentenceid) - - if (!result.has(pos)){ - result.add(pos) - resultsInCantica.push(cantica); - resultsInCanto.push(cantica + canto) - } - resultClauses.add(cantica + "_" + canto.replace(" ", "_") + "_" + numverso + "-" +clfrom+'_'+clto+"-"+cltype) - resultSentences.add(sentenceid) - - }); - seachbBindingsStream.on('end', () => { - console.log('start rendering...') - listarisultati = Array.from(result) - - cantiche = ["Inferno", "Purgatorio", "Paradiso"] - - - console.log('periodi end...') - - //evidenzia risultati - for (ris of listarisultati) { - idris = '#' + ris - //$(idris).attr('class', "font-weight-bold mark ") - $(idris).addClass("font-weight-bold mark ") - - } - //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); - if (count>0){ - var spanbadgecantica = $(''); - 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 - console.log('results end...') - 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); - if (count>0){ - var spanbadge = $(''); - spanbadge.attr('class', cantobadgeclass); - spanbadge.append(count) - //$("[name='nameofobject']") - spanbadge.appendTo($('[name="' + cantica + 'Canto ' + k + '"]')) - //spanbadge.insertAfter($('[name="'+cantica+'Canto '+k+'"]')) - } - } - } - console.log('badge end...') - - //aggiorna minimap - if (currentMinimap != '') { - showMinimap(currentMinimap) - } - - }); - } - catch (err) { - console.log(err.message); - }; - - }; - }); diff --git a/js/obsmodule.js b/js/obsmodule.js index fe0d4e0..6283e78 100644 --- a/js/obsmodule.js +++ b/js/obsmodule.js @@ -1,2 +1,2 @@ -import {Runtime, Inspector} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@4/dist/runtime.js"; -import define from "https://api.observablehq.com/@cesare/dsearchcompare.js?v=3"; +import {Runtime, Inspector} from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@5/dist/runtime.js"; +import define from "https://api.observablehq.com/@cesare/commarcdiag@564.js?v=3"; \ No newline at end of file diff --git a/js/utils.js b/js/utils.js index 1d28111..1d8c7d7 100644 --- a/js/utils.js +++ b/js/utils.js @@ -1,37 +1,6 @@ -tq = ` -PREFIX ecrm: -PREFIX orl: -PREFIX ontolex: -PREFIX olires: -PREFIX comm: -SELECT (?form AS ?IRIForma) (?Rappresentazione AS ?Forma) (?lm AS ?Lemma) (?textver AS ?Verso) (?NumVerso AS ?NumeroVerso) (?t_canto AS ?Canto) (?t_cantica AS ?Cantica) WHERE { - ?fa orl:occurrenceOf ?form . - ?ver olires:hasStructuralComponent ?fa . - ?ver ecrm:P190_Has_Symbolic_Content ?textver; - olires:hasNumber ?NumVerso. - ?canto ecrm:P102_has_title ?t_canto; - hasStructuralComponent ?ver. - ?cantica ecrm:P102_has_title ?t_cantica ; - hasStructuralComponent ?canto . - ?form ontolex:writtenRep ?Rappresentazione. - ?lent ontolex:lexicalForm ?form; - ontolex:canonicalForm ?cf. - ?cf ontolex:writtenRep ?lm. - {?form orl:FormaVerboVolgare; - orl:TipoDiatesiVerboVolgare orl:VerboVolgareAttivo. - } - {?form orl:FormaVerboVolgare; - orl:TipoDiatesiVerboVolgare orl:VerboVolgareAttivo. - { ?form orl:FormaVerboVolgare; - orl:TipoDiatesiVerboVolgare orl:VerboVolgareAttivo.} - UNION - { ?form orl:FormaSostantivoVolgare; - orl:TipoNumeroSostantivoVolgare orl:NumeroSingolareSostantivoVolgare. } -} -} ORDER BY (?Cantica) (?Canto) -LIMIT 50 -` + + tqvpvs=` PREFIX ecrm: @@ -153,39 +122,123 @@ PREFIX olires: PREFIX comm: PREFIX syntit: -SELECT (?form as ?IRIForma) (?Rappresentazione as ?Forma) (?lm as ?Lemma) (?textver as ?Verso) (?NumVerso as ?NumeroVerso) -(?t_canto as ?Canto) (?t_cantica as ?Cantica) ?pos ?clatype ?clafunction ?clfr ?clto ?cl ?sentence +SELECT (?t_canto as ?Canto) (?t_cantica as ?Cantica) ?clatype ?clafunction ?clfr ?clto ?cl ?sentence ?cltext ?pos WHERE { - FILTER(REGEX(?Rappresentazione, "^andare$", "i")) . - FILTER(LANGMATCHES(LANG(?Rappresentazione), "it")) + FILTER(REGEX(?Rappresentazione, "^buon$", "i")) . + FILTER(LANGMATCHES(LANG(?Rappresentazione), "it")) + ###condizioni grammaticali + { + ?form ontolex:writtenRep ?Rappresentazione. ?lent ontolex:lexicalForm ?form; ontolex:canonicalForm ?cf. ?cf ontolex:writtenRep ?lm. ?fa orl:occurrenceOf ?form; olires:OccursInRegion ?reg . - ?ver ecrm:P190_Has_Symbolic_Content ?textver; - olires:hasNumber ?NumVerso; - olires:hasStructuralComponent ?fa. ?reg olires:fragmentRegionFrom ?pos . - ?canto ecrm:P102_has_title ?t_canto; - olires:hasStructuralComponent ?ver. + } + ###end + ### condizioni comuni + ?canto ecrm:P102_has_title ?t_canto. ?cantica ecrm:P102_has_title ?t_cantica; olires:hasStructuralComponent ?canto. + ### end + ###condizioni sintattiche + { ?clocc orl:occurrenceOf ?cl ; - olires:occursInRegion ?frag ; - ecrm:P148_has_component ?fa . - - ?sentence a syntit:Sentence ; + ecrm:P148_has_component ?fa ; #condizione join grammaticale sintattica + olires:occursInRegion ?frag . + + ?sentence a syntit:Sentence ; + ecrm:P148i_is_component_of ?canto; syntit:hasSyntacticalComponent ?cl. + ?cl syntit:hasClauseType ?clatype ; ecrm:P190_has_symbolic_content ?cltext ; syntit:hasClauseFunction ?clafunction. ?frag olires:fragmentRegionFrom ?clfr ; olires:fragmentRegionTo ?clto . + } + ### end }` +ontoSparqlQueryMultCond = `PREFIX rdfs: +PREFIX ecrm: +PREFIX hdn: +PREFIX lemon: +PREFIX orl: +PREFIX xsd: +PREFIX ontolex: +PREFIX olires: +PREFIX comm: +PREFIX syntit: + +SELECT (?t_canto as ?Canto) (?t_cantica as ?Cantica) ?clatype ?clafunction ?clfr ?clto ?cl ?sentence ?cltext ?pos +WHERE { + FILTER(REGEX(?Rappresentazione, "^buon$", "i")) . + FILTER(LANGMATCHES(LANG(?Rappresentazione), "it")) + + ### condizioni + ?canto ecrm:P102_has_title ?t_canto. + ?cantica ecrm:P102_has_title ?t_cantica; + olires:hasStructuralComponent ?canto. + ###condizioni end + ###condizioni sintattiche + { + ?clocc orl:occurrenceOf ?cl ; + ecrm:P148_has_component ?fa ; # join grammaticale sintattica + olires:occursInRegion ?frag . + + ?sentence a syntit:Sentence ; + ecrm:P148i_is_component_of ?canto; + syntit:hasSyntacticalComponent ?cl. + + ?cl syntit:hasClauseType ?clatype ; + ecrm:P190_has_symbolic_content ?cltext ; + syntit:hasClauseFunction ?clafunction. + + ?frag olires:fragmentRegionFrom ?clfr ; + olires:fragmentRegionTo ?clto . + } + ###condizioni sintattiche end + }` + + // ?cl syntit:hasClauseType syntit:Dichiarativa. + +ontoSparqlQuerySynt = ` +PREFIX ecrm: +PREFIX orl: +PREFIX ontolex: +PREFIX olires: +PREFIX syntit: +SELECT ?sentence ?clfr ?clto ?clf ?clatype (?t_canto as ?Canto) (?t_cantica as ?Cantica) +WHERE { + FILTER regex(?Rappresentazione,"^persona$","i") . #remove if query_text=='' + FILTER langMatches(lang(?Rappresentazione),"it") #remove if query_text=='' + ?cat ontolex:writtenRep ?Rappresentazione . #remove if query_text=='' + ?fa orl:occurrenceOf ?cat . #remove if query_text=='' + ?clocc ecrm:P148_has_component ?fa . #remove if query_text=='' + ?cl syntit:hasClauseType ?clatype; + ecrm:P190_has_symbolic_content ?cltext; + syntit:hasClauseFunction ?clf. + ?clocc orl:occurrenceOf ?cl; + olires:occursInRegion ?frag. + ?frag olires:fragmentRegionFrom ?clfr; + olires:fragmentRegionTo ?clto. + ?sentence syntit:Sentence; + ecrm:P148i_is_component_of ?cantoIRI; + syntit:hasSyntacticalComponent ?cl. + ?cantica ecrm:P102_has_title ?t_cantica ; + olires:hasStructuralComponent ?cantoIRI . + ?cantoIRI ecrm:P102_has_title ?t_canto . + +} LIMIT 10000 + +` + + + orlprefix = 'https://dantenetwork.it/ontology/orl/current/' syntitprefix='https://dantenetwork.it/ontology/syntit/current/' @@ -195,19 +248,7 @@ var stringInSparql= false; function writesparqlquery(query) { return (query); } -// write the query in natural language -function writesearchValue(form) { - var strq = 'il lemma'; - var strcategoria = 'in tutte le categorie' - - if (form.oggetto.value == 'forma') - strq = 'la forma'; - if (form.categoria.value != 'all') - strcategoria = 'nella categoria ' + form.categoria.value; - - return `Cerco: ${strq} ${form.query.value}, ${form.tipo.value}, ${strcategoria}` -} //restituisce la query per ottenere tutti i versi di una cantica @@ -265,34 +306,44 @@ function getStatements() { return data21 } + + var theguiQ = '' var multipleCondSpQuery = '' var conditions = [] var filters = [] -var unionop = '{"union": {"type": "union", "patterns":[]}, "bgp": {"type": "bgp", "triples":[]}, "group": {"type": "group", "patterns":[]}}' +var unionop = `{"union": {"type": "union", "patterns":[]}, "bgp": {"type": "bgp", "triples":[]}, "group": {"type": "group", "patterns":[]}}` function parseJsonClause(op, tokens, nowhere) { //alert(op) + var idp=-1 + if (nowhere[0].type == 'filter' && nowhere[0].expression.args[0].value == 'Rappresentazione'){ + nowhere.splice(0, 1) + } if (op.trim() == 'OR') { - //multipleCondSpQuery.where.push(JSON.parse(unionop)['union']); - nowhere.push(JSON.parse(unionop)['union']); + //nowhere.unshift(JSON.parse(unionop)['union']); + nowhere.splice(1, 0, JSON.parse(unionop)['union']) + idp=1 } if (op.trim() == 'AND') { - nowhere.push(JSON.parse(unionop)['group']); + //nowhere.push(JSON.parse(unionop)['group']); + nowhere.splice(1, 0, JSON.parse(unionop)['group']) + idp=1 + } for (var mtoken in tokens) { te_op = tokens[mtoken] if ('TERM' in te_op) { cond = theguiQ[te_op['TERM']] - //parsedquery.where.at(-1).patterns - multipleCondSpQuery = buildJsonClause(cond, multipleCondSpQuery, -1, nowhere.at(-1).patterns) + //mywhere=nowhere[idp].patterns; + multipleCondSpQuery = buildStatementClause (cond, multipleCondSpQuery, -1, nowhere[idp].patterns) + } else parseJsonClause(Object.keys(te_op)[0], te_op[Object.keys(te_op)[0]], nowhere.at(-1).patterns) - } } @@ -302,8 +353,8 @@ function buildSPQuery(guiquery) { theguiQ = guiquery; var SparqlParser = sparqljs.Parser; var spqparser = new SparqlParser(); - multipleCondSpQuery = spqparser.parse(ontoSparqlQuery); - mytestq = spqparser.parse(tq); + multipleCondSpQuery = spqparser.parse(ontoSparqlQueryMultCond); + //mytestq = spqparser.parse(tq); var parser = peg.generate(hdnquerygrammar); test = guiquery['EsprLogica'].join(" "); test = test.replaceAll("( ", "(") @@ -327,20 +378,24 @@ function buildSQ(stquery) { var SparqlParser = sparqljs.Parser; var parser = new SparqlParser(); //Prendo la query SPARQL template - const parsedquery = parser.parse(ontoSparqlQuery); + var parsedquery = parser.parse(ontoSparqlQuery); //const parsedquery = parser.parse(tqvpvs); console.log(stquery) if (stquery['EsprLogica'] != null && stquery['EsprLogica'].length > 1) { + parsedquery=parser.parse(ontoSparqlQueryMultCond) buildSPQuery(stquery) return multipleCondSpQuery; } if (stquery['EsprLogica'] != null && stquery['EsprLogica'] != '' && stquery['EsprLogica'].length == 1) { clause = stquery['EsprLogica'] - + if (stquery[clause]['TipoClausola']=='Sintattico'){ + parsedquery = parser.parse(ontoSparqlQuerySynt); + return buildSintacticClause(stquery[clause], parsedquery, 2) + } myquery = buildClause(stquery[clause], parsedquery, 2) return (myquery) } @@ -376,42 +431,35 @@ function buildSQ(stquery) { } - -function buildJsonClause(clause, parsedquery, whereind, theplace) { - //Nick - if (clause['categoria'] != null){ - clause['typeGramm0']=clause['categoria']; - clause['queryText']=clause['query'] - } - - if (clause['queryText']!=null && clause['queryText'].trim() != "") { - if (clause['queryText'].trim().slice(-1) !== '*') - strval = "^" + clause['queryText'].trim() + "$"; - else - strval = clause['queryText'].trim().slice(0, -1) - - parsedquery.where[1].expression.args[1].value = strval; - if (clause['lemma_forma'] == 'lemma') - parsedquery.where[1].expression.args[0].value = "lm"; - } - else { - if (parsedquery.where[1].type == 'filter' && parsedquery.where[1].expression.args[0].value == 'Rappresentazione') - parsedquery.where.splice(1, 1) +function buildStatementClause (clause, parsedquery, whereind, theplace) { + //var tmpgroup=JSON.parse(unionop)['group'] + if (clause['TipoClausola']=="Sintattico"){ + //tmpgroup=JSON.parse(unionop)['group'] + tmpgroup=JSON.parse(syntgroup) } + else tmpgroup=JSON.parse(morphgroup); + if (clause['queryText']!=null && clause['queryText'].trim() != ""){ + //theplace.push(JSON.parse(unionop)['group']); + + var stmt=buildFilterStatement(clause['lemma_forma'], clause['queryText'].trim(), clause['opzioni_testo']) + tmpgroup.patterns.push(stmt) + tmpgroup.patterns.push(JSON.parse(unionop)['bgp']); + tmpgroup.patterns.at(-1).triples.push(JSON.parse(writtenrepresentation)) + } if (clause['typeGramm0'] != null && clause['typeGramm0'] != "all") if (whereind > -1) parsedquery.where[whereind].triples.push(JSON.parse(data21)[clause['typeGramm0']]); else { - //parsedquery.where.at(-1).patterns - theplace.push(JSON.parse(unionop)['bgp']); - theplace.at(-1).triples.push(JSON.parse(data21)[clause['typeGramm0']]); + //theplace.push(JSON.parse(unionop)['bgp']); + //theplace.at(-1).triples.push(JSON.parse(data21)[clause['typeGramm0']]); + tmpgroup.patterns.push(JSON.parse(unionop)['bgp']); + tmpgroup.patterns.at(-1).triples.push(JSON.parse(data21)[clause['typeGramm0']]); + } - - if (clause['typeGramm0'] != null && Object.keys(sottoCategorie).includes(clause['typeGramm0'].trim())) { - //sctmp=JSON.parse(sottoCategorieSostantivi) + sctmp = sottoCategorie[clause['typeGramm0'].trim()] sctk = Object.keys(sctmp) for (ke in sctk) { @@ -424,60 +472,88 @@ function buildJsonClause(clause, parsedquery, whereind, theplace) { if (whereind > -1) parsedquery.where[whereind].triples.push(subcatstat); else - theplace.at(-1).triples.push(subcatstat); + //theplace.at(-1).triples.push(subcatstat); + tmpgroup.patterns.at(-1).triples.push(subcatstat); } } } } - + if (clause['TipoClausola']=="Sintattico"){ + tmpgroup.patterns.push(JSON.parse(unionop)['bgp']); + var functS=clause['functionSyntax']; + var typeS=clause['typeSyntax0'] + console.log(functS+' '+typeS) + if (functS != null && functS != ".+"){ + var myf=buildsyntClause(funzione_clausola[functS]) + if (myf!='') + tmpgroup.patterns.at(-1).triples.push(myf) + } + if (typeS != null && typeS != ".+"){ + myf=buildsyntClause(macrotipi_sint[typeS]) + if (myf!='') + tmpgroup.patterns.at(-1).triples.push(myf) + } + } + + theplace.push(tmpgroup) return parsedquery - + } + + function buildSintacticClause(clause, parsedquery, whereind) { - var functS=clause['functionSyntax']; - var typeS=clause['typeSyntax0'] - if (functS != null && functS != "all"){ - console.log('functS '+funzione_clausola['princ']) - var myf=buildsyntClause(funzione_clausola[functS]) - console.log('myf '+myf) - if (myf=='') - return parsedquery - if (whereind > -1) - parsedquery.where[whereind].triples.push(myf); - else - parsedquery.where.at(-1).patterns.at(-1).triples.push(myf); - } - return parsedquery -} - -function buildClause(clause, parsedquery, whereind) { - if (clause['queryText'].trim() != "") { - if (clause['queryText'].trim().slice(-1) !== '*') - strval = "^" + clause['queryText'].trim() + "$"; - else - strval = clause['queryText'].trim().slice(0, -1) - + + var strval= getStringFilter(clause['queryText'].trim(), clause['opzioni_testo']) parsedquery.where[0].expression.args[1].value = strval; if (clause['lemma_forma'] == 'lemma') parsedquery.where[0].expression.args[0].value = "lm"; } else { if (parsedquery.where[0].type == 'filter' && parsedquery.where[0].expression.args[0].value == 'Rappresentazione') + //remove the filter for text CHANGE! parsedquery.where.splice(0, 1) + parsedquery.where.splice(0, 1) + parsedquery.where[0].triples.splice(2,1) + parsedquery.where[0].triples.splice(1,1) + parsedquery.where[0].triples.splice(0,1) whereind=whereind-1 } + + var functS=clause['functionSyntax']; + var typeS=clause['typeSyntax0'] + console.log(functS+' '+typeS) + if (functS != null && functS != ".+"){ + //console.log('functS '+funzione_clausola['princ']) + var myf=buildsyntClause(funzione_clausola[functS]) + + if (myf=='') + return parsedquery + parsedquery.where.at(-1).triples.push(myf); + } + if (typeS != null && typeS != ".+"){ + myf=buildsyntClause(macrotipi_sint[typeS]) + parsedquery.where.at(-1).triples.push(myf); + } + return parsedquery +} + +function buildClause(clause, parsedquery, whereind) { + if (clause['TipoClausola']=='Sintattico') return buildSintacticClause(clause, parsedquery, whereind) + + + if (clause['typeGramm0'] != null && clause['typeGramm0'] != "all") if (whereind > -1) //parsedquery.where[whereind].triples.push(JSON.parse(data21)[clause['typeGramm0']]); - parsedquery.where[whereind].triples.splice(0, 0, JSON.parse(data21)[clause['typeGramm0']]); + parsedquery.where[2].patterns[0].triples.splice(0, 0, JSON.parse(data21)[clause['typeGramm0']]); else { parsedquery.where.at(-1).patterns.push(JSON.parse(unionop)['bgp']); parsedquery.where.at(-1).patterns.at(-1).triples.push(JSON.parse(data21)[clause['typeGramm0']]); @@ -496,7 +572,7 @@ function buildClause(clause, parsedquery, whereind) { if (sttmts[keval] != null && (sttmts[keval].split(':')[1]) != null) { subcatstat = buildsubcategoryClause(sttmts[keval]) if (whereind > -1) - parsedquery.where[whereind].triples.push(subcatstat); + parsedquery.where[2].patterns[0].triples.push(subcatstat); else parsedquery.where.at(-1).patterns.at(-1).triples.push(subcatstat); } @@ -504,11 +580,96 @@ function buildClause(clause, parsedquery, whereind) { } } + if (clause['queryText'].trim() != "") { + + var strval= getStringFilter(clause['queryText'].trim(), clause['opzioni_testo']) + parsedquery.where[0].expression.args[1].value = strval; + if (clause['lemma_forma'] == 'lemma') + parsedquery.where[0].expression.args[0].value = "lm"; + } + else { + if (parsedquery.where[0].type == 'filter' && parsedquery.where[0].expression.args[0].value == 'Rappresentazione') + parsedquery.where.splice(0, 1) + whereind=whereind-1 + } return parsedquery } +function getStringFilter(filter, opzione){ + var strval = "^" + filter.trim() + "$"; + if (opzione != "") + switch (opzione) { + case 'parola': + strval = "^" + filter.trim() + "$"; + break; + case 'sottostringa': + strval = filter.trim(); + break; + case 'prefisso': + strval = "^" + filter.trim(); + break; + case 'suffisso': + strval = filter.trim() + "$"; + break; + default: + strval = "^" + filter.trim() + "$"; + +}; + return (strval) +} +function buildFilterStatement(target, filter, opzione){ + + var filtertemplate = `{ + "type": "filter", + "expression": { + "type": "operation", + "operator": "regex", + "args": [ + { + "termType": "Variable", + "value": "Rappresentazione" + }, + { + "termType": "Literal", + "value": "^andare$", + "language": "", + "datatype": { + "termType": "NamedNode", + "value": "http://www.w3.org/2001/XMLSchema#string" + } + }, + { + "termType": "Literal", + "value": "i", + "language": "", + "datatype": { + "termType": "NamedNode", + "value": "http://www.w3.org/2001/XMLSchema#string" + } + } + ] + } +}` + + +var statement = JSON.parse(filtertemplate) +/* +if (filter.trim().slice(-1) !== '*') + strval = "^" + filter.trim() + "$"; +else + strval = filter.trim().slice(0, -1) + */ +var strval = getStringFilter(filter, opzione); + +statement.expression.args[1].value = strval; +if (target == 'lemma') + statement.expression.args[0].value = "lm"; + +return (statement) +} + function buildsyntClause(sttmnt) { var tmplate = `{"subject": {"termType": "Variable", "value":"cl"}, @@ -840,7 +1001,11 @@ var sottoCategorie = { } } - +/* +* +* SPARQL statements +* +*/ data21 = `{"verbovolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "https://dantenetwork.it/ontology/orl/current/FormaVerboVolgare"}}, "sostantivovolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "https://dantenetwork.it/ontology/orl/current/FormaSostantivoVolgare"}}, "aggettivovolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "https://dantenetwork.it/ontology/orl/current/FormaAggettivoVolgare"}}, @@ -855,7 +1020,84 @@ data21 = `{"verbovolgare": {"subject": {"termType": "Variable", "value":"form"}, "locuzionevolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "https://dantenetwork.it/ontology/orl/current/FormaLocuzioneVolgare"}} } ` - + +writtenrepresentation=`{"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/ns/lemon/ontolex#writtenRep"}, "object": {"termType": "Variable", "value": "Rappresentazione"}}` + + +var morphgroup=`{"type": "group", + "patterns": [{"type": "bgp", + "triples": [ + {"subject": {"termType": "Variable","value": "form"}, + "predicate": {"termType": "NamedNode", "value": "http://www.w3.org/ns/lemon/ontolex#writtenRep"}, + "object": {"termType": "Variable","value": "Rappresentazione"}}, + {"subject": {"termType": "Variable","value": "lent"}, + "predicate": {"termType": "NamedNode","value": "http://www.w3.org/ns/lemon/ontolex#lexicalForm"}, + "object": {"termType": "Variable", "value": "form"}}, + {"subject": {"termType": "Variable","value": "lent"}, + "predicate": {"termType": "NamedNode","value": "http://www.w3.org/ns/lemon/ontolex#canonicalForm"}, + "object": {"termType": "Variable","value": "cf"}}, + {"subject": {"termType": "Variable","value": "cf"}, + "predicate": {"termType": "NamedNode","value": "http://www.w3.org/ns/lemon/ontolex#writtenRep"}, + "object": {"termType": "Variable","value": "lm"}}, + {"subject": {"termType": "Variable","value": "fa"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/orl/current/occurrenceOf"}, + "object": {"termType": "Variable","value": "form"}}, + {"subject": {"termType": "Variable","value": "fa"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/olires/current/OccursInRegion"}, + "object": {"termType": "Variable", "value": "reg"}}, + {"subject": {"termType": "Variable","value": "reg"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/olires/current/fragmentRegionFrom"}, + "object": {"termType": "Variable","value": "pos"}} + ] + } + ] + } +` +var syntgroup=` { + "type": "group", + "patterns": [ + { + "type": "bgp", + "triples": [ + {"subject": {"termType": "Variable","value": "clocc"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/orl/current/occurrenceOf"}, + "object": {"termType": "Variable","value": "cl"}}, + {"subject": {"termType": "Variable","value": "clocc"}, + "predicate": {"termType": "NamedNode","value": "http://erlangen-crm.org/current/P148_has_component"}, + "object": {"termType": "Variable","value": "fa"}}, + {"subject": {"termType": "Variable","value": "clocc"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/olires/current/occursInRegion"}, + "object": {"termType": "Variable","value": "frag"}}, + {"subject": {"termType": "Variable","value": "sentence"}, + "predicate": {"termType": "NamedNode","value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, + "object": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/syntit/current/Sentence"}}, + {"subject": {"termType": "Variable","value": "sentence"}, + "predicate": {"termType": "NamedNode","value": "http://erlangen-crm.org/current/P148i_is_component_of"}, + "object": {"termType": "Variable","value": "canto"}}, + {"subject": {"termType": "Variable","value": "sentence"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/syntit/current/hasSyntacticalComponent"}, + "object": {"termType": "Variable","value": "cl"}}, + {"subject": {"termType": "Variable","value": "cl"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/syntit/current/hasClauseType"}, + "object": {"termType": "Variable","value": "clatype"}}, + {"subject": {"termType": "Variable","value": "cl"}, + "predicate": {"termType": "NamedNode","value": "http://erlangen-crm.org/current/P190_has_symbolic_content"}, + "object": {"termType": "Variable","value": "cltext"}}, + {"subject": {"termType": "Variable","value": "cl"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/syntit/current/hasClauseFunction"}, + "object": {"termType": "Variable","value": "clafunction"}}, + {"subject": {"termType": "Variable","value": "frag"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/olires/current/fragmentRegionFrom"}, + "object": {"termType": "Variable","value": "clfr"}}, + {"subject": {"termType": "Variable","value": "frag"}, + "predicate": {"termType": "NamedNode","value": "https://dantenetwork.it/ontology/olires/current/fragmentRegionTo"}, + "object": {"termType": "Variable","value": "clto"}} + ] + } + ] + } + +` /* * *Tipi sintattici