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

Combobox #63

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
66 changes: 66 additions & 0 deletions src/app/sandbox/combobox/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"use client";
import { useState } from "react";
import Combobox from "@/components/ui/combobox";
import populateCragsAction from "./server-actions/populate-crags-action";
import populateRoutesAction from "./server-actions/populate-routes-action";

function ComboboxPage() {

async function populateCrags(text: string) {
if (text === "") {
return [];
}
const crags = await populateCragsAction(text);
return crags.map((crag) => ({
value: crag.id,
name: crag.name,
}));
}

async function populateRoutes(text: string) {
if (text === "") {
return [];
}
const routes = await populateRoutesAction(text);
return routes.map((route) => ({
value: route.id,
name: `${route.name}, ${route.crag.name}`,
}));
}

function handleChange(a) {
console.log("handleChange", a);
}

return (
<div className="m-8">
<h3>Combobox demo</h3>

<div className="mt-14 w-80">
<h5>Crag finder</h5>
<div className="mt-4">
<Combobox
value={{
value: "2ab5496f-df5a-47ae-a0d4-ec53ec81c69f",
name: "Kotečnik",
}}
onChange={handleChange}
populate={populateCrags}
/>
</div>
</div>
<div className="mt-14 w-80">
<h5>Route finder</h5>
<div className="mt-4">
<Combobox
value={null}
onChange={handleChange}
populate={populateRoutes}
/>
</div>
</div>
</div>
);
}

export default ComboboxPage;
42 changes: 42 additions & 0 deletions src/app/sandbox/combobox/server-actions/populate-crags-action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"use server";

import { gql } from "urql/core";
import {
ComboboxPopulateCragsDocument,
Crag,
RouteDifficultyVotesDocument,
} from "@/graphql/generated";
import urqlServer from "@/graphql/urql-server";

async function populateCragsAction(
query: string
): Promise<Crag[]> {
const result = await urqlServer().query(ComboboxPopulateCragsDocument, {
input: {
query,
pageSize: 10,
orderBy: { field: "popularity", direction: "DESC" },
},
});

if (result.error) {
return Promise.reject(result.error);
}

return result.data.searchCrags.items;
}

export default populateCragsAction;

gql`
query ComboboxPopulateCrags($input: SearchCragsInput!) {
searchCrags(input: $input) {
items {
__typename
id
name
slug
}
}
}
`;
40 changes: 40 additions & 0 deletions src/app/sandbox/combobox/server-actions/populate-routes-action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"use server";

import { gql } from "urql/core";
import { ComboboxPopulateCragsDocument, ComboboxPopulateRoutesDocument, Route } from "@/graphql/generated";
import urqlServer from "@/graphql/urql-server";

async function populateRoutesAction(query: string): Promise<Route[]> {
const result = await urqlServer().query(ComboboxPopulateRoutesDocument, {
input: {
query,
pageSize: 10,
orderBy: { field: "popularity", direction: "DESC" },
},
});

if (result.error) {
return Promise.reject(result.error);
}

return result.data.searchRoutes.items;
}

export default populateRoutesAction;

gql`
query ComboboxPopulateRoutes($input: SearchRoutesInput!) {
searchRoutes(input: $input) {
items {
__typename
id
name
slug
crag {
id
name
}
}
}
}
`;
121 changes: 121 additions & 0 deletions src/components/ui/combobox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import useForwardedRef from "@/hooks/useForwardedRef";
import {
Combobox as HUICombobox,
ComboboxInput,
ComboboxOption,
ComboboxOptions,
Field,
ComboboxButton,
Label,
} from "@headlessui/react";
import { ForwardedRef, forwardRef, useEffect, useState } from "react";
import IconSearch from "./icons/search";

type TComboboxProps = {
name?: string;
value?: TComboboxValue | null;
type?: string;
onChange: (value: string | null) => void;
label?: string;
placeholder?: string;
description?: string;
errorMessage?: string;
disabled?: boolean;
onBlur?: () => void;
populate: (text: string) => Promise<TComboboxValue[]>;
};

type TComboboxValue = {
value: string;
name: string;
};

const Combobox = forwardRef(function Combobox(
{
value,
onChange,
label,
errorMessage,
disabled,
populate,
}: TComboboxProps,
forwardedRef: ForwardedRef<HTMLInputElement>
) {
const inputRef = useForwardedRef(forwardedRef);

const focusInput = () => {
inputRef.current?.focus();
};

const [selectedValue, setSelectedValue] = useState(value);
const [query, setQuery] = useState("");

const [options, setOptions] = useState<TComboboxValue[]>([]);

useEffect(() => {
populate(query).then((result) => {
setOptions(result);
});
}, [query, populate]);

function handleChange(newValue: TComboboxValue) {
setSelectedValue(newValue);
onChange(newValue?.value || null);
}

return (
<Field disabled={disabled}>
{label && <Label>{label}</Label>}
<HUICombobox
value={selectedValue}
onChange={handleChange}
onClose={() => setQuery("")}
>
<div
className={`focus-within:ring flex items-center rounded-lg border
${!disabled && !errorMessage ? "border-neutral-400" : ""}
${
errorMessage
? "border-red-500 focus-within:ring-red-100"
: "focus-within:ring-blue-100"
}
${
disabled ? "border-neutral-300 bg-neutral-100 text-neutral-400" : ""
}`}
>
<ComboboxInput
ref={inputRef}
onClick={focusInput}
displayValue={(value: TComboboxValue) => value?.name}
onChange={(event) => setQuery(event.target.value)}
className="flex-1 outline-none min-w-0 rounded-lg w-full py-2 placeholder:text-neutral-400 pl-4"
autoComplete="off"
/>
<ComboboxButton>
<div className="px-2">
<IconSearch />
</div>
</ComboboxButton>
</div>
{options.length > 0 && (
<ComboboxOptions
anchor="bottom start"
className="[--anchor-gap:8px] min-w-[calc(var(--input-width)+40px)] overflow-hidden rounded-lg border border-neutral-400 bg-white focus-visible:outline-none focus-visible:ring focus-visible:ring-blue-100"
>
{options.map((option: TComboboxValue) => (
<ComboboxOption
key={option.value}
value={option}
className="flex cursor-pointer justify-between gap-4 py-2 pl-4 pr-2 ui-selected:text-blue-500 ui-active:bg-neutral-100 ui-active:text-blue-500 ui-disabled:cursor-default ui-disabled:text-neutral-400"
>
{option.name}
</ComboboxOption>
))}
</ComboboxOptions>
)}
</HUICombobox>
</Field>
);
});

export default Combobox;
Loading