Skip to content

Commit

Permalink
Add image upload
Browse files Browse the repository at this point in the history
  • Loading branch information
vpodk committed Feb 7, 2024
1 parent 5df50c0 commit 4afef0b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
29 changes: 27 additions & 2 deletions src/app/components/search/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,41 @@ const API_ENDPOINT = "/dupes/search";

export default function SearchForm() {
const inputRef = useRef<HTMLInputElement>(null);
const imageRef = useRef<HTMLInputElement>(null);
const { setProducts } = useContext(SearchContext);

const search = () => {
const input = inputRef.current;
const image = imageRef.current;
const host = location.hostname === "localhost" ? API_URL_DEV : API_URL_PROD;
const endpoint = host + API_ENDPOINT + "?url=";
const url = input && input.value.trim();
const img = image && image.files && image.files[0];

if (input) input.value = "Loading...";

const reset = () => {
if (input) input.value = "";
if (image) image.value = "";
};

if (url) {
fetch(endpoint + encodeURIComponent(url))
.then((res) => res.json())
.then((data) => {
setProducts(data.dupes || []);
reset();
input.value = url;
});
input.value = "Loading...";
} else if (img) {
const data = new FormData();
data.append("image", img);
fetch(endpoint, { method: "POST", body: data })
.then((res) => res.json())
.then((data) => {
setProducts(data.dupes || []);
reset();
});
}
};

Expand All @@ -34,10 +53,16 @@ export default function SearchForm() {
<input
ref={inputRef}
type="url"
required
className="grow px-4 rounded-l-2xl"
placeholder="Enter product URL"
/>
<input
ref={imageRef}
type="file"
className="pr-2"
role="button"
onChange={search}
/>
<button type="submit" className="rounded-r-2xl"></button>
</form>
);
Expand Down
12 changes: 11 additions & 1 deletion src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ body {
width: 100%;
}

header form input,
header form [type='url'],
header form button {
box-shadow: -1px 4px 14px 4px #0000000F;
height: 54px;
Expand All @@ -47,6 +47,16 @@ footer {
color: #304157;
}

header form [type='file']::file-selector-button {
opacity: 0;
}

header form [type='file'] {
width: 54px;
height: 54px;
background: #fff no-repeat left url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%234CADCD'%3E%3Cpath d='M18 15v3H6v-3H4v3c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-3h-2zM7 9l1.41 1.41L11 7.83V16h2V7.83l2.59 2.58L17 9l-5-5-5 5z'/%3E%3C/svg%3E");
}

header form [type='submit'] {
background: url('/search-icon.svg') #4CADCD no-repeat center;
background-size: 24px;
Expand Down

0 comments on commit 4afef0b

Please sign in to comment.