added search on add fields ranking

This commit is contained in:
2026-07-29 16:37:58 +02:00
parent f01bfa06c9
commit eb34cba7bb
+46 -9
View File
@@ -220,23 +220,60 @@ $(document).ready(function () {
dropdownParent: $("#partsModal"), dropdownParent: $("#partsModal"),
minimumResultsForSearch: 0, minimumResultsForSearch: 0,
sorter: function (data) { sorter: function (data) {
return data.sort(function (a, b) { const rawTerm = ((window.__extraFieldSearchTerm || "") + "")
const textA = (a.text || "").toLowerCase(); .toLowerCase()
const textB = (b.text || "").toLowerCase(); .trim();
return textA.localeCompare(textB, "it", { const terms = rawTerm.split(/\s+/).filter(Boolean);
sensitivity: "base", const firstTerm = terms[0] || "";
numeric: true,
}); const scoreOf = function (text) {
const t = (text || "").toLowerCase();
if (!firstTerm) return 3;
if (t === rawTerm) return 0; // match esatto
if (t.indexOf(firstTerm) === 0) return 1; // inizia col primo termine
if (
new RegExp(
"(^|\\s)" +
firstTerm.replace(
/[.*+?^${}()|[\]\\]/g,
"\\$&",
),
).test(t)
)
return 2; // primo termine a inizio parola
return 3; // presente ma non a inizio parola
};
return data.slice().sort(function (a, b) {
const sa = scoreOf(a.text);
const sb = scoreOf(b.text);
if (sa !== sb) return sa - sb;
return (a.text || "")
.toLowerCase()
.localeCompare((b.text || "").toLowerCase(), "it", {
sensitivity: "base",
numeric: true,
});
}); });
}, },
matcher: function (params, data) { matcher: function (params, data) {
if ($.trim(params.term) === "") return data; if ($.trim(params.term) === "") return data;
if (typeof data.text === "undefined") return null; if (typeof data.text === "undefined") return null;
const term = params.term.toLowerCase(); // memorizza il termine per il sorter (Select2 non lo passa al sorter)
window.__extraFieldSearchTerm = params.term;
const terms = params.term
.toLowerCase()
.split(/\s+/)
.filter(Boolean);
const text = data.text.toLowerCase(); const text = data.text.toLowerCase();
return text.indexOf(term) > -1 ? data : null; // AND: tutti i termini devono essere presenti (posizione-indipendente)
for (let i = 0; i < terms.length; i++) {
if (text.indexOf(terms[i]) === -1) return null;
}
return data;
}, },
}); });