create-nextblock 0.13.8 → 0.13.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/templates/nextblock-template/app/actions/productGridActions.ts +40 -0
- package/templates/nextblock-template/app/api/cms/ecommerce/product-picker/route.ts +151 -0
- package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +3 -0
- package/templates/nextblock-template/app/cms/blocks/components/BlockTypeSelector.tsx +17 -5
- package/templates/nextblock-template/app/cms/blocks/components/MultiEntityPicker.tsx +251 -0
- package/templates/nextblock-template/app/cms/blocks/editors/ProductGridBlockEditor.tsx +375 -18
- package/templates/nextblock-template/app/cms/components/EcommerceActiveContext.tsx +27 -0
- package/templates/nextblock-template/components/blocks/ProductGridClient.tsx +114 -0
- package/templates/nextblock-template/lib/blocks/ProductGridBlock.tsx +78 -139
- package/templates/nextblock-template/lib/blocks/blockRegistry.ts +3 -3
- package/templates/nextblock-template/lib/blocks/blockTypes.ts +19 -0
- package/templates/nextblock-template/lib/blocks/ecommerce-block-schemas.ts +61 -2
- package/templates/nextblock-template/lib/blocks/product-grid-data.ts +210 -0
- package/templates/nextblock-template/package.json +1 -1
- package/templates/nextblock-template/tsconfig.tsbuildinfo +1 -1
package/package.json
CHANGED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
'use server';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
loadProductGridPage,
|
|
5
|
+
type ProductGridQuery,
|
|
6
|
+
} from '../../lib/blocks/product-grid-data';
|
|
7
|
+
import {
|
|
8
|
+
PRODUCT_GRID_MAX_LIMIT,
|
|
9
|
+
PRODUCT_GRID_DEFAULT_PAGE_SIZE,
|
|
10
|
+
} from '../../lib/blocks/ecommerce-block-schemas';
|
|
11
|
+
import type { Product } from '@nextblock-cms/ecommerce/types';
|
|
12
|
+
|
|
13
|
+
export interface ProductGridPageResult {
|
|
14
|
+
products: Product[];
|
|
15
|
+
totalCount: number;
|
|
16
|
+
error?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Pagination for the Product Grid block. Only ever returns published products
|
|
21
|
+
* (`getProducts` defaults to status `active`), so this is safe to call from the
|
|
22
|
+
* storefront. The page size is clamped here because the argument arrives from
|
|
23
|
+
* the client — the unlimited path stays server-render only.
|
|
24
|
+
*/
|
|
25
|
+
export async function fetchProductGridPage(
|
|
26
|
+
query: ProductGridQuery
|
|
27
|
+
): Promise<ProductGridPageResult> {
|
|
28
|
+
try {
|
|
29
|
+
const limit = Math.min(
|
|
30
|
+
Math.max(1, Math.floor(query.limit) || PRODUCT_GRID_DEFAULT_PAGE_SIZE),
|
|
31
|
+
PRODUCT_GRID_MAX_LIMIT
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
const { products, totalCount } = await loadProductGridPage({ ...query, limit });
|
|
35
|
+
return { products, totalCount };
|
|
36
|
+
} catch (error) {
|
|
37
|
+
console.error('[Product Grid] Failed to load page:', error);
|
|
38
|
+
return { products: [], totalCount: 0, error: 'Failed to load products.' };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { NextResponse } from 'next/server';
|
|
2
|
+
import {
|
|
3
|
+
createClient,
|
|
4
|
+
getServiceRoleSupabaseClient,
|
|
5
|
+
verifyPackageOnline,
|
|
6
|
+
} from '@nextblock-cms/db/server';
|
|
7
|
+
|
|
8
|
+
export const dynamic = 'force-dynamic';
|
|
9
|
+
|
|
10
|
+
/** How many products a single search returns before the UI asks for a narrower query. */
|
|
11
|
+
const PRODUCT_PAGE_SIZE = 50;
|
|
12
|
+
/** Guard against an unbounded `ids` list when hydrating labels for an existing selection. */
|
|
13
|
+
const MAX_HYDRATED_IDS = 100;
|
|
14
|
+
|
|
15
|
+
export interface ProductPickerCategory {
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
slug: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ProductPickerProduct {
|
|
22
|
+
id: string;
|
|
23
|
+
title: string;
|
|
24
|
+
slug: string | null;
|
|
25
|
+
sku: string | null;
|
|
26
|
+
status: string | null;
|
|
27
|
+
languageCode: string | null;
|
|
28
|
+
translationGroupId: string | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* PostgREST parses `,`, `.`, `(` and `)` inside an `or(...)` filter, so anything
|
|
33
|
+
* the author types has to be stripped before it is interpolated into one.
|
|
34
|
+
*/
|
|
35
|
+
function sanitizeSearchTerm(term: string): string {
|
|
36
|
+
return term.replace(/[,().*%\\]/g, ' ').trim().slice(0, 80);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Options for the Product Grid block pickers: every category plus a page of
|
|
41
|
+
* products (optionally filtered by `search`). `ids` hydrates labels for an
|
|
42
|
+
* existing selection whose products fall outside the current page.
|
|
43
|
+
*/
|
|
44
|
+
export async function GET(request: Request) {
|
|
45
|
+
try {
|
|
46
|
+
const supabase = createClient();
|
|
47
|
+
const {
|
|
48
|
+
data: { user },
|
|
49
|
+
error: authError,
|
|
50
|
+
} = await supabase.auth.getUser();
|
|
51
|
+
|
|
52
|
+
if (authError || !user) {
|
|
53
|
+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const { data: profile } = await supabase
|
|
57
|
+
.from('profiles')
|
|
58
|
+
.select('role')
|
|
59
|
+
.eq('id', user.id)
|
|
60
|
+
.single();
|
|
61
|
+
|
|
62
|
+
if (!profile || !['ADMIN', 'WRITER'].includes(profile.role)) {
|
|
63
|
+
return NextResponse.json(
|
|
64
|
+
{ error: 'Forbidden: Insufficient permissions' },
|
|
65
|
+
{ status: 403 }
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Fail closed: without the ecommerce package there is no product catalog to
|
|
70
|
+
// browse, and the blocks that use this route are hidden from the picker.
|
|
71
|
+
if (!(await verifyPackageOnline('ecommerce'))) {
|
|
72
|
+
return NextResponse.json(
|
|
73
|
+
{ error: 'The ecommerce package is not active.' },
|
|
74
|
+
{ status: 403 }
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const url = new URL(request.url);
|
|
79
|
+
const search = sanitizeSearchTerm(url.searchParams.get('search') ?? '');
|
|
80
|
+
const ids = (url.searchParams.get('ids') ?? '')
|
|
81
|
+
.split(',')
|
|
82
|
+
.map((id) => id.trim())
|
|
83
|
+
.filter(Boolean)
|
|
84
|
+
.slice(0, MAX_HYDRATED_IDS);
|
|
85
|
+
|
|
86
|
+
// Reading the catalog is admin work behind the role check above.
|
|
87
|
+
const admin = getServiceRoleSupabaseClient();
|
|
88
|
+
|
|
89
|
+
const productColumns =
|
|
90
|
+
'id, title, slug, sku, status, translation_group_id, languages(code)';
|
|
91
|
+
|
|
92
|
+
let productsQuery = admin
|
|
93
|
+
.from('products')
|
|
94
|
+
.select(productColumns)
|
|
95
|
+
.order('created_at', { ascending: false })
|
|
96
|
+
// Fetch one extra row so the UI can tell the author the list was truncated.
|
|
97
|
+
.limit(PRODUCT_PAGE_SIZE + 1);
|
|
98
|
+
|
|
99
|
+
if (search) {
|
|
100
|
+
productsQuery = productsQuery.or(`title.ilike.%${search}%,sku.ilike.%${search}%`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const [categoriesResult, productsResult, selectedResult] = await Promise.all([
|
|
104
|
+
admin.from('categories').select('id, name, slug').order('name', { ascending: true }),
|
|
105
|
+
productsQuery,
|
|
106
|
+
ids.length > 0
|
|
107
|
+
? admin.from('products').select(productColumns).in('id', ids)
|
|
108
|
+
: Promise.resolve({ data: [], error: null }),
|
|
109
|
+
]);
|
|
110
|
+
|
|
111
|
+
if (categoriesResult.error) throw categoriesResult.error;
|
|
112
|
+
if (productsResult.error) throw productsResult.error;
|
|
113
|
+
if (selectedResult.error) throw selectedResult.error;
|
|
114
|
+
|
|
115
|
+
const toPickerProduct = (row: any): ProductPickerProduct => ({
|
|
116
|
+
id: row.id,
|
|
117
|
+
title: row.title,
|
|
118
|
+
slug: row.slug ?? null,
|
|
119
|
+
sku: row.sku ?? null,
|
|
120
|
+
status: row.status ?? null,
|
|
121
|
+
languageCode: row.languages?.code ?? null,
|
|
122
|
+
translationGroupId: row.translation_group_id ?? null,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const productRows = (productsResult.data ?? []) as any[];
|
|
126
|
+
const hasMore = productRows.length > PRODUCT_PAGE_SIZE;
|
|
127
|
+
const products = productRows.slice(0, PRODUCT_PAGE_SIZE).map(toPickerProduct);
|
|
128
|
+
|
|
129
|
+
// Merge the hydrated selection in so already-chosen products always render
|
|
130
|
+
// with a real label, even when a search hides them.
|
|
131
|
+
const byId = new Map(products.map((product) => [product.id, product]));
|
|
132
|
+
for (const row of (selectedResult.data ?? []) as any[]) {
|
|
133
|
+
if (!byId.has(row.id)) byId.set(row.id, toPickerProduct(row));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return NextResponse.json(
|
|
137
|
+
{
|
|
138
|
+
categories: (categoriesResult.data ?? []) as ProductPickerCategory[],
|
|
139
|
+
products: Array.from(byId.values()),
|
|
140
|
+
hasMore,
|
|
141
|
+
},
|
|
142
|
+
{ status: 200 }
|
|
143
|
+
);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
console.error('[Product Picker API] Unexpected error:', error);
|
|
146
|
+
return NextResponse.json(
|
|
147
|
+
{ error: 'Failed to load product picker options.' },
|
|
148
|
+
{ status: 500 }
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -22,6 +22,7 @@ import { FeedbackModal } from "./components/FeedbackModal";
|
|
|
22
22
|
import { CortexGlobalAgentChat } from "./components/CortexGlobalAgentChat";
|
|
23
23
|
import { CortexAiPageContextProvider } from "./components/CortexAiPageContext";
|
|
24
24
|
import { CortexAiActiveProvider } from "./components/CortexAiActiveContext";
|
|
25
|
+
import { EcommerceActiveProvider } from "./components/EcommerceActiveContext";
|
|
25
26
|
import { useAppBranding } from "../../components/AppShell";
|
|
26
27
|
import { resolveMediaUrl } from "../../lib/media/resolveMediaUrl";
|
|
27
28
|
|
|
@@ -257,6 +258,7 @@ export default function CmsClientLayout({
|
|
|
257
258
|
return (
|
|
258
259
|
<CortexAiPageContextProvider>
|
|
259
260
|
<CortexAiActiveProvider isActive={isCortexAiActive}>
|
|
261
|
+
<EcommerceActiveProvider isActive={isEcommerceActive}>
|
|
260
262
|
<div className="relative flex h-full min-h-0 w-full overflow-hidden bg-slate-50 dark:bg-slate-950 md:flex-row">
|
|
261
263
|
<div className="fixed bottom-4 right-4 z-[60] md:hidden">
|
|
262
264
|
<Button
|
|
@@ -516,6 +518,7 @@ export default function CmsClientLayout({
|
|
|
516
518
|
)}
|
|
517
519
|
{isAdmin && isCortexAiActive && <CortexGlobalAgentChat />}
|
|
518
520
|
</div>
|
|
521
|
+
</EcommerceActiveProvider>
|
|
519
522
|
</CortexAiActiveProvider>
|
|
520
523
|
</CortexAiPageContextProvider>
|
|
521
524
|
)
|
|
@@ -16,6 +16,8 @@ import {
|
|
|
16
16
|
} from "@nextblock-cms/ui";
|
|
17
17
|
import { Search, X, Package } from 'lucide-react';
|
|
18
18
|
import { blockRegistry, BlockType } from '../../../../lib/blocks/blockRegistry';
|
|
19
|
+
import { isEcommerceBlockType } from '../../../../lib/blocks/blockTypes';
|
|
20
|
+
import { useEcommerceActive } from '../../components/EcommerceActiveContext';
|
|
19
21
|
import BlockTypeCard from './BlockTypeCard';
|
|
20
22
|
|
|
21
23
|
interface BlockTypeSelectorProps {
|
|
@@ -25,7 +27,8 @@ interface BlockTypeSelectorProps {
|
|
|
25
27
|
allowedBlockTypes?: BlockType[];
|
|
26
28
|
}
|
|
27
29
|
|
|
28
|
-
const
|
|
30
|
+
const ECOMMERCE_CATEGORY = "E-commerce";
|
|
31
|
+
const CATEGORIES = ["All", "Layout", "Content", "Media", "Interactive", ECOMMERCE_CATEGORY, "Custom"];
|
|
29
32
|
|
|
30
33
|
const getBlockCategory = (type: string, isCustomSlug?: boolean): string => {
|
|
31
34
|
if (isCustomSlug) {
|
|
@@ -50,7 +53,7 @@ const getBlockCategory = (type: string, isCustomSlug?: boolean): string => {
|
|
|
50
53
|
case 'cart':
|
|
51
54
|
case 'checkout':
|
|
52
55
|
case 'product_details':
|
|
53
|
-
return
|
|
56
|
+
return ECOMMERCE_CATEGORY;
|
|
54
57
|
default:
|
|
55
58
|
return 'Content';
|
|
56
59
|
}
|
|
@@ -65,6 +68,9 @@ const BlockTypeSelector: React.FC<BlockTypeSelectorProps> = ({
|
|
|
65
68
|
const [searchQuery, setSearchQuery] = React.useState('');
|
|
66
69
|
const [activeCategory, setActiveCategory] = React.useState('All');
|
|
67
70
|
const [customDefs, setCustomDefs] = React.useState<any[]>([]);
|
|
71
|
+
// Store blocks are only offered when the ecommerce package is activated. The
|
|
72
|
+
// context defaults to false outside the CMS layout, so this fails closed.
|
|
73
|
+
const isEcommerceActive = useEcommerceActive();
|
|
68
74
|
|
|
69
75
|
// Reset state and fetch custom blocks when modal is opened
|
|
70
76
|
React.useEffect(() => {
|
|
@@ -93,10 +99,16 @@ const BlockTypeSelector: React.FC<BlockTypeSelectorProps> = ({
|
|
|
93
99
|
onOpenChange(false);
|
|
94
100
|
};
|
|
95
101
|
|
|
102
|
+
const visibleCategories = React.useMemo(
|
|
103
|
+
() => CATEGORIES.filter((category) => category !== ECOMMERCE_CATEGORY || isEcommerceActive),
|
|
104
|
+
[isEcommerceActive]
|
|
105
|
+
);
|
|
106
|
+
|
|
96
107
|
const blockDefs = React.useMemo(() => {
|
|
97
108
|
const coreDefs = Object.values(blockRegistry).filter(
|
|
98
109
|
(blockDef) =>
|
|
99
|
-
!allowedBlockTypes || allowedBlockTypes.includes(blockDef.type)
|
|
110
|
+
(!allowedBlockTypes || allowedBlockTypes.includes(blockDef.type)) &&
|
|
111
|
+
(isEcommerceActive || !isEcommerceBlockType(blockDef.type))
|
|
100
112
|
);
|
|
101
113
|
|
|
102
114
|
const mappedCustomDefs = customDefs.map((def) => ({
|
|
@@ -114,7 +126,7 @@ const BlockTypeSelector: React.FC<BlockTypeSelectorProps> = ({
|
|
|
114
126
|
}));
|
|
115
127
|
|
|
116
128
|
return [...coreDefs, ...mappedCustomDefs];
|
|
117
|
-
}, [allowedBlockTypes, customDefs]);
|
|
129
|
+
}, [allowedBlockTypes, customDefs, isEcommerceActive]);
|
|
118
130
|
|
|
119
131
|
// Memoized filter and search results to prevent re-calculations during key strokes
|
|
120
132
|
const filteredBlockDefs = React.useMemo(() => {
|
|
@@ -174,7 +186,7 @@ const BlockTypeSelector: React.FC<BlockTypeSelectorProps> = ({
|
|
|
174
186
|
|
|
175
187
|
{/* Category Filter Tabs */}
|
|
176
188
|
<div className="flex flex-wrap gap-1.5 pb-3 border-b border-border">
|
|
177
|
-
{
|
|
189
|
+
{visibleCategories.map((category) => (
|
|
178
190
|
<button
|
|
179
191
|
key={category}
|
|
180
192
|
type="button"
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import React from 'react';
|
|
4
|
+
import { Check, ChevronsUpDown, Loader2, Search, X } from 'lucide-react';
|
|
5
|
+
import {
|
|
6
|
+
Badge,
|
|
7
|
+
Button,
|
|
8
|
+
Checkbox,
|
|
9
|
+
Input,
|
|
10
|
+
Popover,
|
|
11
|
+
PopoverContent,
|
|
12
|
+
PopoverTrigger,
|
|
13
|
+
} from '@nextblock-cms/ui';
|
|
14
|
+
import { cn } from '@nextblock-cms/utils';
|
|
15
|
+
|
|
16
|
+
export interface PickerOption {
|
|
17
|
+
id: string;
|
|
18
|
+
label: string;
|
|
19
|
+
/** Secondary line under the label, e.g. a slug or SKU. */
|
|
20
|
+
description?: string | null;
|
|
21
|
+
/** Small trailing tag, e.g. a language code or publish status. */
|
|
22
|
+
badge?: string | null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface MultiEntityPickerProps {
|
|
26
|
+
options: PickerOption[];
|
|
27
|
+
/**
|
|
28
|
+
* Labels for already-selected ids that the current `options` page may not
|
|
29
|
+
* contain (server-filtered lists). Used for the chips only, never listed.
|
|
30
|
+
*/
|
|
31
|
+
selectedOptions?: PickerOption[];
|
|
32
|
+
selectedIds: string[];
|
|
33
|
+
onChange: (ids: string[]) => void;
|
|
34
|
+
placeholder?: string;
|
|
35
|
+
searchPlaceholder?: string;
|
|
36
|
+
emptyMessage?: string;
|
|
37
|
+
/** Singular / plural noun used in the trigger label, e.g. ['category', 'categories']. */
|
|
38
|
+
nouns: [string, string];
|
|
39
|
+
isLoading?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Provide to filter server-side (the component then stops filtering locally).
|
|
42
|
+
* Omit for a fully client-side list.
|
|
43
|
+
*/
|
|
44
|
+
onSearchChange?: (query: string) => void;
|
|
45
|
+
/** Number the selected chips — use when selection order is display order. */
|
|
46
|
+
showOrder?: boolean;
|
|
47
|
+
maxSelected?: number;
|
|
48
|
+
/** Extra line under the control, e.g. "Showing the first 50 products". */
|
|
49
|
+
hint?: React.ReactNode;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export default function MultiEntityPicker({
|
|
53
|
+
options,
|
|
54
|
+
selectedOptions: selectedOptionsProp,
|
|
55
|
+
selectedIds,
|
|
56
|
+
onChange,
|
|
57
|
+
placeholder = 'Select…',
|
|
58
|
+
searchPlaceholder = 'Search…',
|
|
59
|
+
emptyMessage = 'Nothing found.',
|
|
60
|
+
nouns,
|
|
61
|
+
isLoading = false,
|
|
62
|
+
onSearchChange,
|
|
63
|
+
showOrder = false,
|
|
64
|
+
maxSelected,
|
|
65
|
+
hint,
|
|
66
|
+
}: MultiEntityPickerProps) {
|
|
67
|
+
const [open, setOpen] = React.useState(false);
|
|
68
|
+
const [searchQuery, setSearchQuery] = React.useState('');
|
|
69
|
+
const isServerFiltered = typeof onSearchChange === 'function';
|
|
70
|
+
|
|
71
|
+
const labelsById = React.useMemo(
|
|
72
|
+
() =>
|
|
73
|
+
new Map(
|
|
74
|
+
[...options, ...(selectedOptionsProp ?? [])].map((option) => [option.id, option])
|
|
75
|
+
),
|
|
76
|
+
[options, selectedOptionsProp]
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
// Selection order is meaningful (it drives display order), so walk selectedIds
|
|
80
|
+
// rather than options. Ids whose option has not loaded yet still get a chip.
|
|
81
|
+
const selectedOptions = React.useMemo(
|
|
82
|
+
() =>
|
|
83
|
+
selectedIds.map(
|
|
84
|
+
(id) => labelsById.get(id) ?? { id, label: 'Loading…', description: null }
|
|
85
|
+
),
|
|
86
|
+
[selectedIds, labelsById]
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
const filteredOptions = React.useMemo(() => {
|
|
90
|
+
if (isServerFiltered || !searchQuery.trim()) return options;
|
|
91
|
+
const query = searchQuery.trim().toLowerCase();
|
|
92
|
+
return options.filter(
|
|
93
|
+
(option) =>
|
|
94
|
+
option.label.toLowerCase().includes(query) ||
|
|
95
|
+
(option.description ?? '').toLowerCase().includes(query)
|
|
96
|
+
);
|
|
97
|
+
}, [options, searchQuery, isServerFiltered]);
|
|
98
|
+
|
|
99
|
+
const atLimit = typeof maxSelected === 'number' && selectedIds.length >= maxSelected;
|
|
100
|
+
|
|
101
|
+
const handleSearchChange = (value: string) => {
|
|
102
|
+
setSearchQuery(value);
|
|
103
|
+
onSearchChange?.(value);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const toggle = (id: string) => {
|
|
107
|
+
if (selectedIds.includes(id)) {
|
|
108
|
+
onChange(selectedIds.filter((selectedId) => selectedId !== id));
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (atLimit) return;
|
|
112
|
+
onChange([...selectedIds, id]);
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const remove = (id: string) => onChange(selectedIds.filter((selectedId) => selectedId !== id));
|
|
116
|
+
|
|
117
|
+
const [singular, plural] = nouns;
|
|
118
|
+
const triggerLabel =
|
|
119
|
+
selectedIds.length > 0
|
|
120
|
+
? `${selectedIds.length} ${selectedIds.length === 1 ? singular : plural} selected`
|
|
121
|
+
: placeholder;
|
|
122
|
+
|
|
123
|
+
return (
|
|
124
|
+
<div className="space-y-2">
|
|
125
|
+
{selectedOptions.length > 0 && (
|
|
126
|
+
<ul className="flex flex-wrap gap-1.5 rounded-md border bg-muted/30 p-1.5">
|
|
127
|
+
{selectedOptions.map((option, index) => (
|
|
128
|
+
<li key={option.id}>
|
|
129
|
+
<Badge
|
|
130
|
+
variant="secondary"
|
|
131
|
+
className="flex items-center gap-1 rounded-full py-0.5 pl-2 pr-1 text-xs font-normal"
|
|
132
|
+
>
|
|
133
|
+
{showOrder && (
|
|
134
|
+
<span className="text-[10px] font-semibold tabular-nums text-muted-foreground">
|
|
135
|
+
{index + 1}
|
|
136
|
+
</span>
|
|
137
|
+
)}
|
|
138
|
+
<span className="max-w-[180px] truncate">{option.label}</span>
|
|
139
|
+
<button
|
|
140
|
+
type="button"
|
|
141
|
+
onClick={() => remove(option.id)}
|
|
142
|
+
aria-label={`Remove ${option.label}`}
|
|
143
|
+
className="rounded-full p-0.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
|
|
144
|
+
>
|
|
145
|
+
<X className="h-3 w-3" />
|
|
146
|
+
</button>
|
|
147
|
+
</Badge>
|
|
148
|
+
</li>
|
|
149
|
+
))}
|
|
150
|
+
</ul>
|
|
151
|
+
)}
|
|
152
|
+
|
|
153
|
+
<Popover open={open} onOpenChange={setOpen}>
|
|
154
|
+
<PopoverTrigger asChild>
|
|
155
|
+
<Button
|
|
156
|
+
type="button"
|
|
157
|
+
variant="outline"
|
|
158
|
+
role="combobox"
|
|
159
|
+
aria-expanded={open}
|
|
160
|
+
className="h-9 w-full justify-between text-xs font-normal"
|
|
161
|
+
>
|
|
162
|
+
<span className="truncate">{triggerLabel}</span>
|
|
163
|
+
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
|
164
|
+
</Button>
|
|
165
|
+
</PopoverTrigger>
|
|
166
|
+
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
|
|
167
|
+
<div className="flex items-center border-b px-3">
|
|
168
|
+
{isLoading ? (
|
|
169
|
+
<Loader2 className="mr-2 h-4 w-4 shrink-0 animate-spin opacity-50" />
|
|
170
|
+
) : (
|
|
171
|
+
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
|
|
172
|
+
)}
|
|
173
|
+
<Input
|
|
174
|
+
autoFocus
|
|
175
|
+
className="h-9 w-full border-0 bg-transparent py-2 text-xs shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"
|
|
176
|
+
placeholder={searchPlaceholder}
|
|
177
|
+
value={searchQuery}
|
|
178
|
+
onChange={(event) => handleSearchChange(event.target.value)}
|
|
179
|
+
/>
|
|
180
|
+
</div>
|
|
181
|
+
|
|
182
|
+
<div className="max-h-60 overflow-y-auto p-1">
|
|
183
|
+
{filteredOptions.length === 0 ? (
|
|
184
|
+
<p className="py-6 text-center text-xs text-muted-foreground">
|
|
185
|
+
{isLoading ? 'Loading…' : emptyMessage}
|
|
186
|
+
</p>
|
|
187
|
+
) : (
|
|
188
|
+
filteredOptions.map((option) => {
|
|
189
|
+
const isChecked = selectedIds.includes(option.id);
|
|
190
|
+
const isBlocked = !isChecked && atLimit;
|
|
191
|
+
return (
|
|
192
|
+
<button
|
|
193
|
+
key={option.id}
|
|
194
|
+
type="button"
|
|
195
|
+
role="option"
|
|
196
|
+
aria-selected={isChecked}
|
|
197
|
+
disabled={isBlocked}
|
|
198
|
+
onClick={() => toggle(option.id)}
|
|
199
|
+
className={cn(
|
|
200
|
+
'relative flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs outline-none transition-colors',
|
|
201
|
+
isBlocked
|
|
202
|
+
? 'cursor-not-allowed opacity-40'
|
|
203
|
+
: 'cursor-pointer hover:bg-accent hover:text-accent-foreground',
|
|
204
|
+
isChecked && 'bg-accent/40'
|
|
205
|
+
)}
|
|
206
|
+
>
|
|
207
|
+
<Checkbox
|
|
208
|
+
checked={isChecked}
|
|
209
|
+
tabIndex={-1}
|
|
210
|
+
aria-hidden="true"
|
|
211
|
+
className="pointer-events-none h-3.5 w-3.5 shrink-0"
|
|
212
|
+
/>
|
|
213
|
+
<span className="flex min-w-0 flex-col">
|
|
214
|
+
<span className="truncate font-medium">{option.label}</span>
|
|
215
|
+
{option.description && (
|
|
216
|
+
<span className="truncate font-mono text-[10px] leading-tight text-muted-foreground">
|
|
217
|
+
{option.description}
|
|
218
|
+
</span>
|
|
219
|
+
)}
|
|
220
|
+
</span>
|
|
221
|
+
{option.badge && (
|
|
222
|
+
<Badge
|
|
223
|
+
variant="outline"
|
|
224
|
+
className="ml-auto shrink-0 px-1.5 py-0 text-[9px] uppercase"
|
|
225
|
+
>
|
|
226
|
+
{option.badge}
|
|
227
|
+
</Badge>
|
|
228
|
+
)}
|
|
229
|
+
{isChecked && (
|
|
230
|
+
<Check
|
|
231
|
+
className={cn('h-3.5 w-3.5 shrink-0 text-primary', !option.badge && 'ml-auto')}
|
|
232
|
+
/>
|
|
233
|
+
)}
|
|
234
|
+
</button>
|
|
235
|
+
);
|
|
236
|
+
})
|
|
237
|
+
)}
|
|
238
|
+
</div>
|
|
239
|
+
|
|
240
|
+
{atLimit && (
|
|
241
|
+
<p className="border-t px-3 py-2 text-[11px] text-muted-foreground">
|
|
242
|
+
Limit reached ({maxSelected}). Remove one to add another.
|
|
243
|
+
</p>
|
|
244
|
+
)}
|
|
245
|
+
</PopoverContent>
|
|
246
|
+
</Popover>
|
|
247
|
+
|
|
248
|
+
{hint && <p className="text-[11px] leading-snug text-muted-foreground">{hint}</p>}
|
|
249
|
+
</div>
|
|
250
|
+
);
|
|
251
|
+
}
|