Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Use search-a-licious for brand #942

Merged
merged 2 commits into from
Apr 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/components/LogoSearchForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useTranslation } from "react-i18next";

import LabelFilter from "../components/QuestionFilter/LabelFilter";
import { TYPE_WITHOUT_VALUE } from "../const";
import TaxonomyAutoSelect from "./TaxonomyAutoSelect";

export const logoTypeOptions = [
{ value: "", labelKey: "logos.type" },
Expand Down Expand Up @@ -83,6 +84,16 @@ const LogoSearchForm = (props) => {
label={t("logos.value")}
size="small"
/>
) : innerType === "brand" ? (
<TaxonomyAutoSelect
taxonomy="brand"
value={innerValue}
onChange={setInnerValue}
showKey
fullWidth
size="small"
label={t("logos.value")}
/>
) : (
<TextField
fullWidth
Expand All @@ -93,7 +104,6 @@ const LogoSearchForm = (props) => {
/>
)}
</Stack>

<Stack direction={{ xs: "column", sm: "row" }} spacing={1}>
<TextField
fullWidth
Expand Down
147 changes: 147 additions & 0 deletions src/components/TaxonomyAutoSelect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import * as React from "react";
import TextField, { TextFieldProps } from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import { debounce } from "@mui/material/utils";
import searchTaxonomy, { TaxonomyItem, TaxonomyNames } from "../offSearch";
// import { getLang } from "../localeStorageManager";

type TaxonomyAutoSelectProps = Omit<TextFieldProps, "value" | "onChange"> & {
/**
* The taxonly to querry
*/
taxonomy: TaxonomyNames;
onChange: (itemId: string) => void;
value: string;
/**
* The the id bellow the text field
*/
showKey?: boolean;
};

const isOptionEqualToValue = (option: string | TaxonomyItem, value: string) =>
(typeof option === "string" ? option : option.id) === value;

export default function TaxonomyAutoSelect(props: TaxonomyAutoSelectProps) {
const { taxonomy, value, onChange, showKey, fullWidth, ...other } = props;
const [inputValue, setInputValue] = React.useState("");
const [selectedValue, setSelectedValue] = React.useState(null);
const [options, setOptions] = React.useState<
readonly (string | TaxonomyItem)[]
>([]);

const language = "en"; //getLang();

const fetch = React.useMemo(
() =>
debounce(
(
request: { input: string },
callback: (results?: readonly TaxonomyItem[]) => void,
) => {
searchTaxonomy[taxonomy](request.input, language).then(({ data }) => {
callback((data?.options as TaxonomyItem[]) ?? []);
});
},
400,
),
[language],
);

React.useEffect(() => {
let active = true;

if (inputValue === "") {
setOptions(value ? [value] : []);
return undefined;
}

fetch({ input: inputValue }, (results?: readonly TaxonomyItem[]) => {
if (active) {
let newOptions: readonly (string | TaxonomyItem)[] = [];

// if (value) {
// newOptions = [];
// }

if (results) {
newOptions = [...newOptions, ...results];
}

setOptions(newOptions);
}
});

return () => {
active = false;
};
}, [value, inputValue, fetch]);

const selectedOption = options.find((option) =>
isOptionEqualToValue(option, value),
);
return (
<Autocomplete
getOptionLabel={(option) =>
typeof option === "string" ? option : option.text
}
freeSolo
filterOptions={(x) => x}
options={options}
autoComplete
includeInputInList
filterSelectedOptions
value={
selectedValue && selectedValue.id === value ? selectedValue : value
}
isOptionEqualToValue={isOptionEqualToValue}
// noOptionsText="No locations"
onChange={(event: any, newValue: TaxonomyItem | null | string) => {
console.log({ newValue });
if (typeof newValue === "object") {
onChange(newValue.id);
setSelectedValue(newValue);
return;
}
onChange(newValue);
}}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
onBlur={() => {
console.log("blur");
console.log({
inputValue,
value,
selectedOption,
});
if (
inputValue === value ||
(selectedValue && selectedValue.text === inputValue)
) {
return;
}
onChange(inputValue);
}}
fullWidth={fullWidth}
renderInput={(params) => (
<TextField
{...params}
{...other}
onKeyDown={(event) => {
console.log(event.key);
if (event.key === "Enter") {
event.preventDefault();
}
}}
helperText={
showKey && value
? selectedValue && selectedValue.id === value
? selectedValue.id
: `⚠️ unknown: "${value}"`
: ""
}
/>
)}
/>
);
}
2 changes: 2 additions & 0 deletions src/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export const OFF_API_URL_V2 = `${OFF_URL}/api/v2`;
export const OFF_API_URL_V3 = `${OFF_URL}/api/v3`;
export const OFF_IMAGE_URL = `https://static.${OFF_DOMAIN}/images/products`;
export const OFF_SEARCH = `${OFF_URL}/cgi/search.pl`;
export const OFF_SEARCH_A_LISIOUS =
"https://search.openfoodfacts.org/autocomplete";
export const IS_DEVELOPMENT_MODE = process.env.NODE_ENV === "development";
export const URL_ORIGINE = IS_DEVELOPMENT_MODE
? "http://localhost:5173"
Expand Down
88 changes: 88 additions & 0 deletions src/offSearch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import axios, { AxiosResponse } from "axios";
import { OFF_SEARCH_A_LISIOUS } from "./const";

export type TaxonomyNames =
| "additive"
| "allergen"
| "amino_acid"
| "brand"
| "category"
| "country"
| "data_quality"
| "label"
| "food_group"
| "improvement"
| "ingredient"
| "ingredients_analysis"
| "ingredients_processing"
| "language"
| "mineral"
| "misc"
| "nova_group"
| "nucleotide"
| "nutrient"
| "origin"
| "other_nutritional_substance"
| "packaging_material"
| "packaging_recycling"
| "packaging_shape"
| "periods_after_opening"
| "preservation"
| "state"
| "vitamin";

const taxonomy_names: TaxonomyNames[] = [
"additive",
"allergen",
"amino_acid",
"brand",
"category",
"country",
"data_quality",
"label",
"food_group",
"improvement",
"ingredient",
"ingredients_analysis",
"ingredients_processing",
"language",
"mineral",
"misc",
"nova_group",
"nucleotide",
"nutrient",
"origin",
"other_nutritional_substance",
"packaging_material",
"packaging_recycling",
"packaging_shape",
"periods_after_opening",
"preservation",
"state",
"vitamin",
];

const searchTaxonomy = {};

taxonomy_names.forEach((taxonomy) => {
searchTaxonomy[taxonomy] = (querry: string, language?: string) =>
axios.get(
`${OFF_SEARCH_A_LISIOUS}?taxonomy_names=${taxonomy}&q=${querry}&lang=${
language || "en"
}`,
);
});

export type TaxonomyItem = {
id: string;
text: string;
taxonomy_name: string;
};

export default searchTaxonomy as Record<
TaxonomyNames,
(
querry: string,
language?: string,
) => Promise<AxiosResponse<{ options?: TaxonomyItem[] }>>
>;
2 changes: 1 addition & 1 deletion src/robotoff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ const robotoff = {
},

searchLogos(barcode, value, type, count = 25, random = false) {
const formattedValue = ["label", "category"].includes(type)
const formattedValue = value.test(/^[a-z][a-z]:/)
? { taxonomy_value: value }
: { value };

Expand Down
Loading