home: ricerca live su tutti i comuni italiani (7894, centroide OSM) + 16 porti; lista vuota finché non digiti; normalizzazione accenti/apostrofi; Invio = ricerca online estero

This commit is contained in:
2026-09-02 11:53:42 +02:00
parent 9e7c97786a
commit 4794f5d467
5 changed files with 8017 additions and 125 deletions
+109 -124
View File
@@ -1,13 +1,12 @@
import QtQuick 2.0
import Sailfish.Silica 1.0
import "../js/tides.js" as Tides
import "../js/comuni.js" as Comuni
Page {
id: page
property var customPorts: [] // porti creati dalla ricerca libera (sessione)
// Campi di ricerca FUORI dal header della lista: gli id dichiarati nel
// Campi di ricerca FUORI dall'header della lista: gli id dichiarati nel
// componente header hanno scope chiuso e le funzioni del Page non li
// vedono (ReferenceError "filter is not defined").
Column {
@@ -20,36 +19,11 @@ Page {
}
SearchField {
id: filter
placeholderText: qsTr("Filter ports…")
onTextChanged: rebuild()
}
Item { width: parent.width; height: Theme.paddingMedium }
TextField {
id: geoField
width: parent.width - 2 * Theme.horizontalPageMargin
anchors.horizontalCenter: parent.horizontalCenter
placeholderText: qsTr("Free search: any city (online)…")
EnterKey.enabled: text.length > 0
EnterKey.onClicked: findCity()
}
Button {
text: qsTr("Find")
anchors.horizontalCenter: parent.horizontalCenter
onClicked: findCity()
}
Label {
id: geoMsg
visible: false
width: parent.width - 2 * Theme.horizontalPageMargin
anchors.horizontalCenter: parent.horizontalCenter
wrapMode: Text.Wrap
color: Theme.errorColor
font.pixelSize: Theme.fontSizeSmall
id: search
placeholderText: qsTr("Search a port or a town…")
onTextChanged: updateList()
EnterKey.enabled: text.trim().length > 0
EnterKey.onClicked: findOnline()
}
}
@@ -59,18 +33,18 @@ Page {
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: parent.bottom
model: ListModel { id: portModel }
header: SectionHeader { text: qsTr("Ports") }
model: ListModel { id: resultModel }
footer: Item {
width: parent.width
height: portModel.count === 0 ? Theme.itemSizeMedium : 0
height: resultModel.count === 0 ? Theme.itemSizeSmall * 1.6 : 0
Label {
visible: portModel.count === 0
visible: resultModel.count === 0
anchors.fill: parent
anchors.margins: Theme.horizontalPageMargin
text: qsTr("No ports match the filter. Try the free city search above.")
text: search.text.trim() === ""
? qsTr("Type to search among all Italian towns and known ports.")
: qsTr("No local results — press Enter to search online.")
color: Theme.secondaryColor
font.pixelSize: Theme.fontSizeSmall
wrapMode: Text.Wrap
@@ -113,66 +87,81 @@ Page {
anchors.verticalCenter: parent.verticalCenter
}
onClicked: {
console.log("[tide] open port:", model.name, "custom:", model.custom)
// model.port (array JS) non è esposto dai ListModel su Qt 5.6:
// si ricostruisce il porto dalle strutture JS tramite l'indice.
var p = model.custom ? page.customPorts[model.customIndex]
: Tides.PORTS[model.realIndex]
page.openDetail(p, model.realIndex, model.custom)
console.log("[tide] open result:", model.name, "kind:", model.kind)
page.openResult(model.kind, model.portIndex, model.name, model.lat, model.lon)
}
}
VerticalScrollDecorator {}
}
function rebuild() {
portModel.clear()
var f = filter.text.toLowerCase()
var pref = appSettings.preferredPort
var i, p
// --- Ricerca live (porti noti + tutti i comuni italiani) ---
function norm(s) {
// minuscolo + apostrofi tipografici -> dritti + accenti rimossi
// ("citta" trova "Città", "sant'angelo" trova "Sant'Angelo")
return s.toLowerCase()
.replace(/[\u2018\u2019]/g, "'")
.replace(/[àáâãä]/g, "a")
.replace(/[èéêë]/g, "e")
.replace(/[ìíîï]/g, "i")
.replace(/[òóôõö]/g, "o")
.replace(/[ùúûü]/g, "u")
}
function rangeOf(cost) {
return "±" + (cost[1][0] + cost[2][0]).toFixed(2) + " m"
}
function updateList() {
var q = norm(search.text.trim())
resultModel.clear()
if (q === "") return
var i, p, name
// porti noti (match su nome o paese)
for (i = 0; i < Tides.PORTS.length; i++) {
p = Tides.PORTS[i]
if (f !== "" && (p[0] + " " + p[1]).toLowerCase().indexOf(f) === -1)
continue
portModel.append({
name: p[0], country: p[1],
range: "±" + (p[4][1][0] + p[4][2][0]).toFixed(2) + " m",
realIndex: i, customIndex: -1, custom: false,
isPreferred: (pref === p[0])
})
if (norm(p[0] + " " + p[1]).indexOf(q) !== -1) {
resultModel.append({
name: p[0], country: p[1],
range: rangeOf(p[4]),
kind: "port", portIndex: i, lat: 0, lon: 0,
isPreferred: (appSettings.preferredPort === p[0])
})
}
}
for (i = 0; i < customPorts.length; i++) {
p = customPorts[i]
if (f !== "" && p[0].toLowerCase().indexOf(f) === -1)
continue
portModel.append({
name: p[0],
country: p[1] !== "" ? p[1] : qsTr("searched city"),
range: "±" + (p[4][1][0] + p[4][2][0]).toFixed(2) + " m",
realIndex: -1, customIndex: i, custom: true,
isPreferred: (pref === p[0])
})
// comuni italiani (max 25 risultati)
var n = 0
for (i = 0; i < Comuni.COMUNI.length && n < 25; i++) {
name = Comuni.COMUNI[i][0]
if (norm(name).indexOf(q) !== -1) {
var lat = Comuni.COMUNI[i][1]
var lon = Comuni.COMUNI[i][2]
resultModel.append({
name: name, country: qsTr("Italy"),
range: rangeOf(Tides.nearestPort(lat, lon).port[4]),
kind: "comune", portIndex: -1, lat: lat, lon: lon,
isPreferred: false
})
n++
}
}
}
// Navigazione centralizzata: pageStack si risolve solo nel contesto del
// Page (nei delegate della lista non è visibile su questo kit).
function openDetail(port, portIndex, custom) {
console.log("[tide] openDetail:", port[0], "custom:", custom)
console.log("[tide] openDetail:", port ? port[0] : "undefined", "custom:", custom)
pageStack.push(Qt.resolvedUrl("DetailPage.qml"),
{ port: port, portIndex: portIndex, custom: custom })
}
// --- Ricerca libera (geocoding) ---
function geoFail(msg) {
geoMsg.text = msg || qsTr("City not found (offline and not in local dataset).")
geoMsg.visible = true
geoMsg.color = Theme.errorColor
}
function geoFound(name, lat, lon, src) {
console.log("[tide] geoFound:", name, lat, lon, src)
if (!name) { geoFail(); return }
function openResult(kind, portIndex, name, lat, lon) {
if (kind === "port") {
page.openDetail(Tides.PORTS[portIndex], portIndex, false)
return
}
// comune italiano: costanti dal porto noto entro 222 km, altrimenti
// stima sintetica da lat/lon (etichettata nella pagina di dettaglio)
var np = Tides.nearestPort(lat, lon)
var cost, flag
if (np.km < 222) {
@@ -182,24 +171,23 @@ Page {
cost = Tides.synthConst(lat, lon)
flag = "synth"
}
var port = [name, "", lat, lon, cost, flag]
customPorts.push(port)
// voce del porto di riferimento con la distanza dalla città cercata
if (np.port !== null && np.port[0].toLowerCase() !== name.toLowerCase()) {
customPorts.push([np.port[0],
"(" + Math.round(np.km) + " km da " + name + ")",
np.port[2], np.port[3], np.port[4].slice(), np.port[5] || ""])
}
rebuild()
geoMsg.text = qsTr("Found %1 (via %2)").arg(name).arg(src)
geoMsg.visible = true
geoMsg.color = Theme.highlightColor
try {
page.openDetail(port, -1, true)
} catch (e) {
console.log("[tide] push DetailPage failed:", e)
geoFail(qsTr("Could not open the detail page: %1").arg(e))
page.openDetail([name, qsTr("Italy"), lat, lon, cost, flag], -1, true)
}
// --- Ricerca online (geocoding Photon) per città estere / non trovate ---
function geoFound(name, lat, lon, src) {
console.log("[tide] geoFound:", name, lat, lon, src)
if (!name) return
var np = Tides.nearestPort(lat, lon)
var cost, flag
if (np.km < 222) {
cost = np.port[4].slice()
flag = "near:" + np.port[0] + ":" + (np.km / 111).toFixed(1)
} else {
cost = Tides.synthConst(lat, lon)
flag = "synth"
}
page.openDetail([name, "", lat, lon, cost, flag], -1, true)
}
function geoXhr(query, cb) {
@@ -213,7 +201,7 @@ Page {
if (!done) {
done = true
console.log("[tide] geoXhr timeout")
cb(null, true)
cb(null)
}
}, 12000)
xhr.open("GET", "https://photon.komoot.io/api/?limit=1&osm_tag=place:city&q="
@@ -229,11 +217,9 @@ Page {
var j = JSON.parse(xhr.responseText)
if (j && j.features && j.features.length > 0) {
var f = j.features[0]
var name = f.properties.name || query
cb(name,
cb(f.properties.name || query,
f.geometry.coordinates[1],
f.geometry.coordinates[0],
"OpenStreetMap")
f.geometry.coordinates[0])
} else {
cb(null)
}
@@ -246,38 +232,37 @@ Page {
xhr.send()
}
function findCity() {
var q = geoField.text.trim()
console.log("[tide] findCity:", q)
function findOnline() {
var q = search.text.trim()
console.log("[tide] findOnline:", q)
if (q === "") return
geoMsg.text = qsTr("Searching…")
geoMsg.visible = true
geoMsg.color = Theme.secondaryColor
// la città cercata è già un porto noto? aprilo direttamente
var ql = q.toLowerCase()
// se è un porto noto, apri direttamente
var ql = norm(q)
for (var i = 0; i < Tides.PORTS.length; i++) {
if (Tides.PORTS[i][0].toLowerCase() === ql) {
geoMsg.visible = false
if (norm(Tides.PORTS[i][0]) === ql) {
page.openDetail(Tides.PORTS[i], i, false)
return
}
}
var loc = Tides.findCityLocal(q)
if (loc) {
geoFound(loc[0], loc[2], loc[3], qsTr("local dataset"))
} else {
geoXhr(q, function(name, lat, lon, src, timeout) {
if (timeout) {
geoFail(qsTr("Geocoding service not reachable (timeout). Check the network."))
return
}
geoFound(name, lat, lon, src)
})
// se è un comune italiano esatto, apri direttamente
for (i = 0; i < Comuni.COMUNI.length; i++) {
if (norm(Comuni.COMUNI[i][0]) === ql) {
page.openResult("comune", -1, Comuni.COMUNI[i][0],
Comuni.COMUNI[i][1], Comuni.COMUNI[i][2])
return
}
}
geoXhr(q, function(name, lat, lon) {
if (!name) {
console.log("[tide] online: non trovato")
return
}
geoFound(name, lat, lon, "OpenStreetMap")
})
}
Component.onCompleted: {
rebuild()
updateList()
var pref = appSettings.preferredPort
if (pref !== "") {
for (var i = 0; i < Tides.PORTS.length; i++) {