Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

refactor(vendor): use CategoryCombobox in product organization form

vholik298eb7441fea
diff --git a/packages/vendor/src/pages/products/[id]/organization/product-organization-form/product-organization-form.tsx b/packages/vendor/src/pages/products/[id]/organization/product-organization-form/product-organization-form.tsx
index 68c44ba8f..c21701ebe 100644
--- a/packages/vendor/src/pages/products/[id]/organization/product-organization-form/product-organization-form.tsx
+++ b/packages/vendor/src/pages/products/[id]/organization/product-organization-form/product-organization-form.tsx
@@ -15,6 +15,7 @@ import {
import { useUpdateProduct } from "@hooks/api/products"
import { useComboboxData } from "@hooks/use-combobox-data"
import { fetchQuery } from "@lib/client"
+import { CategoryCombobox } from "@pages/products/common/components/category-combobox"
type ProductOrganizationFormProps = {
product: ExtendedAdminProduct
@@ -23,8 +24,7 @@ type ProductOrganizationFormProps = {
const ProductOrganizationSchema = zod.object({
type_id: zod.string().nullable(),
collection_id: zod.string().nullable(),
- category_ids: zod.string().nullable(),
- // category_ids: zod.array(zod.string()),
+ categories: zod.array(zod.string()),
tag_ids: zod.array(zod.string()),
})
@@ -38,20 +38,6 @@ export const ProductOrganizationForm = ({
const configs = getFormConfigs("product", "organize")
const fields = getFormFields("product", "organize")
- const categories = useComboboxData({
- queryKey: ["product_categories"],
- queryFn: (params) =>
- fetchQuery("/vendor/product-categories", {
- method: "GET",
- query: params as Record<string, string | number>,
- }),
- getOptions: (data) =>
- data.product_categories.map((category: any) => ({
- label: category.name!,
- value: category.id!,
- })),
- })
-
const collections = useComboboxData({
queryKey: ["product_collections"],
queryFn: (params) =>
@@ -98,7 +84,7 @@ export const ProductOrganizationForm = ({
defaultValues: {
type_id: product.type_id ?? "",
collection_id: product.collection_id ?? "",
- category_ids: product.categories?.[0]?.id || "",
+ categories: product.categories?.map((c) => c.id) || [],
tag_ids: product.tags?.map((t) => t.id) || [],
},
schema: ProductOrganizationSchema,
@@ -113,7 +99,7 @@ export const ProductOrganizationForm = ({
{
type_id: data.type_id ? data.type_id : undefined,
collection_id: data.collection_id ? data.collection_id : undefined,
- categories: data.category_ids ? [{ id: data.category_ids }] : [],
+ categories: data.categories?.map((id) => ({ id })) ?? [],
tags: data.tag_ids?.map((t) => ({ id: t })) ?? [],
},
{
@@ -185,7 +171,7 @@ export const ProductOrganizationForm = ({
/>
<Form.Field
control={form.control}
- name="category_ids"
+ name="categories"
render={({ field }) => {
return (
<Form.Item>
@@ -193,14 +179,7 @@ export const ProductOrganizationForm = ({
{t("products.fields.categories.label")}
</Form.Label>
<Form.Control>
- {/* <CategoryCombobox {...field} /> */}
- <Combobox
- {...field}
- multiple={false}
- options={categories.options}
- onSearchValueChange={categories.onSearchValueChange}
- searchValue={categories.searchValue}
- />
+ <CategoryCombobox {...field} />
</Form.Control>
<Form.ErrorMessage />
</Form.Item>
diff --git a/packages/vendor/src/pages/products/common/components/category-combobox/category-combobox.tsx b/packages/vendor/src/pages/products/common/components/category-combobox/category-combobox.tsx
index 0ba8bf4f0..efbe8621d 100644
--- a/packages/vendor/src/pages/products/common/components/category-combobox/category-combobox.tsx
+++ b/packages/vendor/src/pages/products/common/components/category-combobox/category-combobox.tsx
@@ -4,10 +4,10 @@ import {
TriangleRightMini,
TrianglesMini,
XMarkMini,
-} from "@medusajs/icons"
-import { AdminProductCategoryResponse } from "@medusajs/types"
-import { Divider, Text, clx } from "@medusajs/ui"
-import { Popover as RadixPopover } from "radix-ui"
+} from "@medusajs/icons";
+import { AdminProductCategoryResponse } from "@medusajs/types";
+import { Divider, Text, clx } from "@medusajs/ui";
+import { Popover as RadixPopover } from "radix-ui";
import {
CSSProperties,
ComponentPropsWithoutRef,
@@ -20,60 +20,60 @@ import {
useMemo,
useRef,
useState,
-} from "react"
-import { Trans, useTranslation } from "react-i18next"
-import { TextSkeleton } from "@components/common/skeleton"
-import { useProductCategories } from "@hooks/api/categories"
-import { useDebouncedSearch } from "@hooks/use-debounced-search"
-
-interface CategoryComboboxProps
- extends Omit<
- ComponentPropsWithoutRef<"input">,
- "value" | "defaultValue" | "onChange"
- > {
- value: string[]
- onChange: (value: string[]) => void
+} from "react";
+import { Trans, useTranslation } from "react-i18next";
+import { TextSkeleton } from "../../../../../components/common/skeleton";
+import { useProductCategories } from "../../../../../hooks/api/categories";
+import { useDebouncedSearch } from "../../../../../hooks/use-debounced-search";
+
+interface CategoryComboboxProps extends Omit<
+ ComponentPropsWithoutRef<"input">,
+ "value" | "defaultValue" | "onChange"
+> {
+ value: string[];
+ onChange: (value: string[]) => void;
}
type Level = {
- id: string
- label: string
-}
+ id: string;
+ label: string;
+};
-const TABLUAR_NUM_WIDTH = 8
-const TAG_BASE_WIDTH = 28
+const TABLUAR_NUM_WIDTH = 8;
+const TAG_BASE_WIDTH = 28;
export const CategoryCombobox = forwardRef<
HTMLInputElement,
CategoryComboboxProps
>(({ value, onChange, className, ...props }, ref) => {
- const innerRef = useRef<HTMLInputElement>(null)
+ const innerRef = useRef<HTMLInputElement>(null);
useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
ref,
() => innerRef.current,
- []
- )
-
- const [open, setOpen] = useState(false)
+ [],
+ );
- const { i18n, t } = useTranslation()
+ const [open, setOpen] = useState(false);
- const [level, setLevel] = useState<Level[]>([])
- const { searchValue, onSearchValueChange, query } = useDebouncedSearch()
+ const { i18n, t } = useTranslation();
- const queryParams = {
- q: query,
- parent_category_id: !searchValue ? getParentId(level) : undefined,
- include_descendants_tree: !searchValue ? true : false,
- }
+ const [level, setLevel] = useState<Level[]>([]);
+ const { searchValue, onSearchValueChange, query } = useDebouncedSearch();
const { product_categories, isPending, isError, error } =
- useProductCategories(queryParams, {
- enabled: open,
- })
-
- const [showLoading, setShowLoading] = useState(false)
+ useProductCategories(
+ {
+ q: query,
+ parent_category_id: !searchValue ? getParentId(level) : undefined,
+ include_descendants_tree: !searchValue ? true : false,
+ },
+ {
+ enabled: open,
+ },
+ );
+
+ const [showLoading, setShowLoading] = useState(false);
/**
* We add a small artificial delay to the end of the loading state,
@@ -81,159 +81,167 @@ export const CategoryCombobox = forwardRef<
* navigating between levels or searching.
*/
useEffect(() => {
- let timeoutId: ReturnType<typeof setTimeout> | undefined
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
if (isPending) {
- setShowLoading(true)
+ setShowLoading(true);
} else {
timeoutId = setTimeout(() => {
- setShowLoading(false)
- }, 150)
+ setShowLoading(false);
+ }, 150);
}
return () => {
- clearTimeout(timeoutId)
- }
- }, [isPending])
+ clearTimeout(timeoutId);
+ };
+ }, [isPending]);
useEffect(() => {
if (searchValue) {
- setLevel([])
+ setLevel([]);
}
- }, [searchValue])
+ }, [searchValue]);
function handleLevelUp(e: MouseEvent<HTMLButtonElement>) {
- e.preventDefault()
- e.stopPropagation()
+ e.preventDefault();
+ e.stopPropagation();
- setLevel(level.slice(0, level.length - 1))
+ setLevel(level.slice(0, level.length - 1));
- innerRef.current?.focus()
+ innerRef.current?.focus();
}
function handleLevelDown(option: ProductCategoryOption) {
return (e: MouseEvent<HTMLButtonElement>) => {
- e.preventDefault()
- e.stopPropagation()
+ e.preventDefault();
+ e.stopPropagation();
- setLevel([...level, { id: option.value, label: option.label }])
+ setLevel([...level, { id: option.value, label: option.label }]);
- innerRef.current?.focus()
- }
+ innerRef.current?.focus();
+ };
}
const handleSelect = useCallback(
(option: ProductCategoryOption) => {
return (e: MouseEvent<HTMLButtonElement>) => {
- e.preventDefault()
- e.stopPropagation()
+ e.preventDefault();
+ e.stopPropagation();
if (isSelected(value, option.value)) {
- onChange(value.filter((v) => v !== option.value))
+ onChange(value.filter((v) => v !== option.value));
} else {
- onChange([...value, option.value])
+ onChange([...value, option.value]);
}
- innerRef.current?.focus()
- }
+ innerRef.current?.focus();
+ };
},
- [value, onChange]
- )
+ [value, onChange],
+ );
function handleOpenChange(open: boolean) {
if (!open) {
- onSearchValueChange("")
- setLevel([])
+ onSearchValueChange("");
+ setLevel([]);
}
if (open) {
requestAnimationFrame(() => {
- innerRef.current?.focus()
- })
+ innerRef.current?.focus();
+ });
}
- setOpen(open)
+ setOpen(open);
}
- const options = getOptions(product_categories || [])
+ const options = getOptions(product_categories || []);
- const showTag = value.length > 0
- const showSelected = !open && value.length > 0
+ const showTag = value.length > 0;
+ const showSelected = !open && value.length > 0;
const tagWidth = useMemo(() => {
- const count = value.length
- const digits = count.toString().length
+ const count = value.length;
+ const digits = count.toString().length;
- return TAG_BASE_WIDTH + digits * TABLUAR_NUM_WIDTH
- }, [value])
+ return TAG_BASE_WIDTH + digits * TABLUAR_NUM_WIDTH;
+ }, [value]);
- const showLevelUp = !searchValue && level.length > 0
+ const showLevelUp = !searchValue && level.length > 0;
- const [focusedIndex, setFocusedIndex] = useState<number>(-1)
+ const [focusedIndex, setFocusedIndex] = useState<number>(-1);
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (!open) {
- return
+ return;
}
- const optionsLength = showLevelUp ? options.length + 1 : options.length
+ const optionsLength = showLevelUp ? options.length + 1 : options.length;
if (e.key === "ArrowDown") {
- e.preventDefault()
+ e.preventDefault();
setFocusedIndex((prev) => {
- const nextIndex = prev < optionsLength - 1 ? prev + 1 : prev
- return nextIndex
- })
+ const nextIndex = prev < optionsLength - 1 ? prev + 1 : prev;
+ return nextIndex;
+ });
} else if (e.key === "ArrowUp") {
- e.preventDefault()
+ e.preventDefault();
setFocusedIndex((prev) => {
- return prev > 0 ? prev - 1 : prev
- })
+ return prev > 0 ? prev - 1 : prev;
+ });
} else if (e.key === "ArrowRight") {
- const index = showLevelUp ? focusedIndex - 1 : focusedIndex
- const hasChildren = options[index]?.has_children
+ const index = showLevelUp ? focusedIndex - 1 : focusedIndex;
+ const hasChildren = options[index]?.has_children;
if (!hasChildren || !!searchValue) {
- return
+ return;
}
- e.preventDefault()
+ e.preventDefault();
setLevel([
...level,
{
id: options[index].value,
label: options[index].label,
},
- ])
- setFocusedIndex(0)
+ ]);
+ setFocusedIndex(0);
} else if (e.key === "Enter" && focusedIndex !== -1) {
- e.preventDefault()
+ e.preventDefault();
if (showLevelUp && focusedIndex === 0) {
- setLevel(level.slice(0, level.length - 1))
- setFocusedIndex(0)
- return
+ setLevel(level.slice(0, level.length - 1));
+ setFocusedIndex(0);
+ return;
}
- const index = showLevelUp ? focusedIndex - 1 : focusedIndex
+ const index = showLevelUp ? focusedIndex - 1 : focusedIndex;
- handleSelect(options[index])(e as unknown as MouseEvent<HTMLButtonElement>)
+ handleSelect(options[index])(e as any);
}
},
- [open, focusedIndex, options, level, handleSelect, searchValue, showLevelUp]
- )
+ [
+ open,
+ focusedIndex,
+ options,
+ level,
+ handleSelect,
+ searchValue,
+ showLevelUp,
+ ],
+ );
useEffect(() => {
- window.addEventListener("keydown", handleKeyDown)
+ window.addEventListener("keydown", handleKeyDown);
return () => {
- window.removeEventListener("keydown", handleKeyDown)
- }
- }, [handleKeyDown])
+ window.removeEventListener("keydown", handleKeyDown);
+ };
+ }, [handleKeyDown]);
if (isError) {
- throw error
+ throw error;
}
return (
@@ -242,7 +250,7 @@ export const CategoryCombobox = forwardRef<
asChild
onClick={() => {
if (!open) {
- handleOpenChange(true)
+ handleOpenChange(true);
}
}}
>
@@ -261,56 +269,56 @@ export const CategoryCombobox = forwardRef<
// between levels.
"shadow-borders-interactive-with-active": open,
},
- className
+ className,
)}
style={
{
- "--tag-width": `${tagWidth}px`,
- } as CSSProperties
- }
- >
- {showTag && (
- <button
- type="button"
- onClick={(e) => {
- e.preventDefault()
- onChange([])
- }}
- className="bg-ui-bg-base hover:bg-ui-bg-base-hover txt-compact-small-plus text-ui-fg-subtle focus-within:border-ui-fg-interactive transition-fg absolute left-0.5 top-0.5 flex h-[28px] items-center rounded-[4px] border py-[3px] pl-1.5 pr-1 outline-none"
+ "--tag-width": `${tagWidth}px`,
+ } as CSSProperties
+ }
>
- <span className="tabular-nums">{value.length}</span>
- <XMarkMini className="text-ui-fg-muted" />
- </button>
- )}
- {showSelected && (
- <div className="pointer-events-none absolute inset-y-0 left-[calc(var(--tag-width)+8px)] flex size-full items-center">
- <Text size="small" leading="compact">
- {t("general.selected")}
- </Text>
- </div>
- )}
- <input
+ {showTag && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.preventDefault();
+ onChange([]);
+ }}
+ className="bg-ui-bg-base hover:bg-ui-bg-base-hover txt-compact-small-plus text-ui-fg-subtle focus-within:border-ui-fg-interactive transition-fg absolute start-0.5 top-0.5 flex h-[28px] items-center rounded-[4px] border py-[3px] ps-1.5 pe-1 outline-none"
+ >
+ <span className="tabular-nums">{value.length}</span>
+ <XMarkMini className="text-ui-fg-muted" />
+ </button>
+ )}
+ {showSelected && (
+ <div className="pointer-events-none absolute inset-y-0 start-[calc(var(--tag-width)+8px)] flex size-full items-center">
+ <Text size="small" leading="compact">
+ {t("general.selected")}
+ </Text>
+ </div>
+ )}
+ <input
ref={innerRef}
value={searchValue}
onChange={(e) => {
- onSearchValueChange(e.target.value)
+ onSearchValueChange(e.target.value);
}}
className={clx(
- "txt-compact-small size-full cursor-pointer appearance-none bg-transparent pr-8 outline-none",
+ "txt-compact-small size-full cursor-pointer appearance-none bg-transparent pe-8 outline-none",
"hover:bg-ui-bg-field-hover",
"focus:cursor-text",
"placeholder:text-ui-fg-muted",
{
- "pl-2": !showTag,
- "pl-[calc(var(--tag-width)+8px)]": showTag,
- }
+ "ps-2": !showTag,
+ "ps-[calc(var(--tag-width)+8px)]": showTag,
+ },
)}
{...props}
/>
<button
type="button"
onClick={() => handleOpenChange(true)}
- className="text-ui-fg-muted transition-fg hover:bg-ui-bg-field-hover absolute right-0 flex size-8 items-center justify-center rounded-r outline-none"
+ className="text-ui-fg-muted transition-fg hover:bg-ui-bg-field-hover absolute end-0 flex size-8 items-center justify-center rounded-r outline-none"
>
<TrianglesMini className="text-ui-fg-muted" />
</button>
@@ -320,22 +328,22 @@ export const CategoryCombobox = forwardRef<
sideOffset={4}
role="listbox"
className={clx(
- "shadow-elevation-flyout bg-ui-bg-base -left-2 z-50 w-[var(--radix-popper-anchor-width)] rounded-[8px]",
+ "shadow-elevation-flyout bg-ui-bg-base -start-2 z-50 w-[var(--radix-popper-anchor-width)] rounded-[8px]",
"max-h-[200px] overflow-y-auto",
"data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
"data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
- "data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2"
+ "data-[side=bottom]:slide-in-from-top-2 data-[side=start]:slide-in-from-end-2 data-[side=end]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2",
)}
onInteractOutside={(e) => {
- e.preventDefault()
+ e.preventDefault();
- const target = e.target as HTMLElement
+ const target = e.target as HTMLElement;
if (target.closest("[data-anchor]")) {
- return
+ return;
}
- handleOpenChange(false)
+ handleOpenChange(false);
}}
>
{showLevelUp && (
@@ -345,8 +353,8 @@ export const CategoryCombobox = forwardRef<
data-active={focusedIndex === 0}
role="button"
className={clx(
- "transition-fg grid w-full appearance-none grid-cols-[20px_1fr] items-center justify-center gap-2 rounded-md px-2 py-1.5 text-left outline-none",
- "data-[active=true]:bg-ui-bg-field-hover"
+ "transition-fg grid w-full appearance-none grid-cols-[20px_1fr] items-center justify-center gap-2 rounded-md px-2 py-1.5 text-start outline-none",
+ "data-[active=true]:bg-ui-bg-field-hover",
)}
type="button"
onClick={handleLevelUp}
@@ -373,7 +381,7 @@ export const CategoryCombobox = forwardRef<
"transition-fg bg-ui-bg-base grid cursor-pointer grid-cols-1 items-center gap-2 overflow-hidden",
{
"grid-cols-[1fr_32px]": option.has_children && !searchValue,
- }
+ },
)}
>
<button
@@ -385,8 +393,8 @@ export const CategoryCombobox = forwardRef<
type="button"
role="option"
className={clx(
- "grid h-full w-full appearance-none grid-cols-[20px_1fr] items-center gap-2 overflow-hidden rounded-md px-2 py-1.5 text-left outline-none",
- "data-[active=true]:bg-ui-bg-field-hover"
+ "grid h-full w-full appearance-none grid-cols-[20px_1fr] items-center gap-2 overflow-hidden rounded-md px-2 py-1.5 text-start outline-none",
+ "data-[active=true]:bg-ui-bg-field-hover",
)}
onClick={handleSelect(option)}
onMouseEnter={() =>
@@ -411,13 +419,13 @@ export const CategoryCombobox = forwardRef<
<button
className={clx(
"text-ui-fg-muted flex size-8 appearance-none items-center justify-center rounded-md outline-none",
- "hover:bg-ui-bg-base-hover active:bg-ui-bg-base-pressed"
+ "hover:bg-ui-bg-base-hover active:bg-ui-bg-base-pressed",
)}
type="button"
onClick={handleLevelDown(option)}
tabIndex={-1}
>
- <TriangleRightMini />
+ <TriangleRightMini className="rtl:rotate-180" />
</button>
)}
</div>
@@ -454,45 +462,45 @@ export const CategoryCombobox = forwardRef<
</div>
</RadixPopover.Content>
</RadixPopover.Root>
- )
-})
+ );
+});
-CategoryCombobox.displayName = "CategoryCombobox"
+CategoryCombobox.displayName = "CategoryCombobox";
type ProductCategoryOption = {
- value: string
- label: string
- has_children: boolean
-}
+ value: string;
+ label: string;
+ has_children: boolean;
+};
function getParentId(level: Level[]): string {
if (!level.length) {
- return "null"
+ return "null";
}
- return level[level.length - 1].id
+ return level[level.length - 1].id;
}
function getParentLabel(level: Level[]): string | null {
if (!level.length) {
- return null
+ return null;
}
- return level[level.length - 1].label
+ return level[level.length - 1].label;
}
function getOptions(
- categories: AdminProductCategoryResponse["product_category"][]
+ categories: AdminProductCategoryResponse["product_category"][],
): ProductCategoryOption[] {
return categories.map((cat) => {
return {
value: cat.id,
label: cat.name,
has_children: cat.category_children?.length > 0,
- }
- })
+ };
+ });
}
function isSelected(values: string[], value: string): boolean {
- return values.includes(value)
+ return values.includes(value);
}