CEC-5085: add search on VINs support (#450)

This commit is contained in:
Tristan Timblin
2023-09-22 10:53:58 -07:00
committed by GitHub
parent 3177d65e3d
commit 842c402d05
3 changed files with 139 additions and 4 deletions

View File

@@ -0,0 +1,74 @@
import { useState, useEffect } from "react";
import { useLocalStorage } from "../../useLocalStorage";
const TYPE_VIN = "vin";
/**
* Match VIN with RegEx
* @param {string} vin - potential VIN
* @returns {boolean}
*/
function isVIN(vin) {
var re = new RegExp("^[A-HJ-NPR-Z\\d]{8}[\\dX][A-HJ-NPR-Z\\d]{2}\\d{6}$");
return vin.match(re)
}
/**
* Convert a string into a QueryPart tuple.
* @typedef {"search" | "vin"} Type - the type of value represented
* @typedef {string} Value - the value
* @typedef {[Type, Value]} QueryPart - a tuple representing a substring of a query
* @param {string} part - substring of a query to turn into a QueryPart
* @returns {QueryPart}
*/
function parseQueryPart(part) {
let type = "search";
if (isVIN(part)) {
type = TYPE_VIN;
part = `${part}`;
}
return [type, part];
}
export default function useQuery() {
const [query, setQuery] = useLocalStorage("VEHICLE_SEARCH", "");
const [parts, setParts] = useState([]);
const [search, setSearch] = useState("");
const [vins, setVins] = useState("");
function reset() {
setSearch("");
setVins([]);
}
useEffect(() => {
reset();
const parts = query.replaceAll(" ", ",").split(",").map(parseQueryPart);
setParts(parts);
parts.forEach(([type, value]) => {
if (type === "vin") {
setVins(vins => {
if (vins.length) {
return `${vins},${value}`;
}
return value;
});
}
if (type === "search") {
setSearch(search => `${search} ${value}`.trim());
}
});
}, [query]);
return {
parts,
search,
vins,
query,
setQuery,
}
}