feat: add tags ability to filter by tags

This commit is contained in:
Zakher Masri
2025-03-11 17:15:21 +03:00
parent 41e6f00685
commit 41f66e23a4
12 changed files with 1127 additions and 37 deletions

View File

@@ -1,11 +1,13 @@
import TemplateGrid from "./components/TemplateGrid";
import Navigation from "./components/Navigation";
import Search from "./components/Search";
import "./App.css";
function App() {
return (
<div>
<div className="min-h-screen">
<Navigation />
<Search />
<TemplateGrid />
</div>
);

View File

@@ -0,0 +1,145 @@
import { Input } from "./ui/input";
import { useStore } from "../store";
import { SearchIcon, XIcon } from "lucide-react";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "./ui/command";
import { cn } from "@/lib/utils";
import { Check, ChevronsUpDown } from "lucide-react";
import React from "react";
const Search = () => {
const { templates, searchQuery, setSearchQuery } = useStore();
const selectedTags = useStore((state) => state.selectedTags);
const addSelectedTag = useStore((state) => state.addSelectedTag);
const removeSelectedTag = useStore((state) => state.removeSelectedTag);
const [open, setOpen] = React.useState(false);
const [tagSearch, setTagSearch] = React.useState("");
// Get all unique tags, safely handle empty templates
const uniqueTags = React.useMemo(() => {
if (!templates || templates.length === 0) return [];
return Array.from(
new Set(templates.flatMap((template) => template.tags || []))
).sort();
}, [templates]);
// Filter tags based on search
const filteredTags = React.useMemo(() => {
if (!tagSearch) return uniqueTags;
return uniqueTags.filter((tag) =>
tag.toLowerCase().includes(tagSearch.toLowerCase())
);
}, [uniqueTags, tagSearch]);
return (
<div className="max-w-xl mx-auto p-12">
<h1 className="text-2xl md:text-3xl xl:text-4xl font-bold text-center mb-8">
Available Templates ({templates?.length || 0})
</h1>
<div className="max-w-xl mx-auto">
<div className="flex flex-row gap-2">
<div className="relative w-full">
<Input
type="text"
placeholder="Search templates..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full"
/>
{searchQuery.length > 0 ? (
<div
className="cursor-pointer"
onClick={() => setSearchQuery("")}
>
<XIcon className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
</div>
) : (
<SearchIcon className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
)}
</div>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="justify-between"
>
Tags
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0">
<Command shouldFilter={false}>
<CommandInput
placeholder="Search tags..."
value={tagSearch}
onValueChange={setTagSearch}
/>
<CommandList>
<CommandEmpty>No tags found.</CommandEmpty>
<CommandGroup>
{filteredTags.map((tag) => (
<CommandItem
key={tag}
value={tag}
onSelect={(value) => {
if (selectedTags.includes(value)) {
removeSelectedTag(value);
} else {
addSelectedTag(value);
}
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
selectedTags.includes(tag)
? "opacity-100"
: "opacity-0"
)}
/>
{tag}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
{selectedTags.length > 0 && (
<div className="flex flex-wrap gap-2 mt-4">
{selectedTags.map((tag) => (
<Badge
key={tag}
variant="default"
className="cursor-pointer pr-1 flex items-center gap-1"
>
{tag}
<div
className="hover:bg-primary-foreground/20 rounded-full p-1"
onClick={() => removeSelectedTag(tag)}
>
<XIcon className="h-3 w-3" />
</div>
</Badge>
))}
</div>
)}
</div>
</div>
);
};
export default Search;

View File

@@ -0,0 +1,35 @@
import { useStore } from "../store";
import { Badge } from "@/components/ui/badge";
const Tags = () => {
const templates = useStore((state) => state.templates);
const selectedTags = useStore((state) => state.selectedTags);
const addSelectedTag = useStore((state) => state.addSelectedTag);
// Get all unique tags
const uniqueTags = Array.from(
new Set(templates.flatMap((template) => template.tags))
).sort();
return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
{/* Available Tags */}
<div className="py-2 flex flex-wrap gap-2">
{uniqueTags
.filter((tag) => !selectedTags.includes(tag))
.map((tag) => (
<Badge
key={tag}
variant="secondary"
className="cursor-pointer hover:bg-blue-100 transition-colors"
onClick={() => addSelectedTag(tag)}
>
{tag}
</Badge>
))}
</div>
</div>
);
};
export default Tags;

View File

@@ -46,7 +46,8 @@ const TemplateGrid: React.FC = () => {
const { templates, setTemplates } = useStore();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const searchQuery = useStore((state) => state.searchQuery);
const selectedTags = useStore((state) => state.selectedTags);
const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(
null
);
@@ -102,9 +103,21 @@ const TemplateGrid: React.FC = () => {
fetchTemplateFiles(template.id);
};
const filteredTemplates = templates.filter((template) =>
template.name.toLowerCase().includes(searchQuery.toLowerCase())
);
const filteredTemplates = templates.filter((template) => {
// Filter by search query
const matchesSearch = template.name
.toLowerCase()
.includes(searchQuery.toLowerCase());
// Filter by selected tags
const matchesTags =
selectedTags.length === 0 ||
selectedTags.every((tag) => template.tags.includes(tag));
return matchesSearch && matchesTags;
});
console.log(filteredTemplates);
const getBase64Config = () => {
if (!templateFiles?.dockerCompose && !templateFiles?.config) return "";
@@ -141,40 +154,12 @@ const TemplateGrid: React.FC = () => {
return (
<>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
<h1 className="text-2xl md:text-3xl xl:text-4xl font-bold text-center mb-8">
Available Templates ({templates.length})
</h1>
<div className="max-w-xl mx-auto mb-12">
<div className="relative">
<Input
type="text"
placeholder="Search templates..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full"
/>
<svg
className="absolute right-3 top-3 h-5 w-5 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
{filteredTemplates.length > 0 ? (
filteredTemplates.map((template) => (
<Card
key={template.id}
className="cursor-pointer hover:shadow-lg transition-all duration-200 h-full"
className=" cursor-pointer hover:shadow-lg transition-all duration-200 h-full max-h-[300px]"
onClick={() => handleTemplateClick(template)}
>
<CardHeader>
@@ -204,7 +189,7 @@ const TemplateGrid: React.FC = () => {
</CardContent>
<CardFooter className="flex justify-between items-center">
<span className="text-sm text-gray-500">
v{template.version}
{template.version}
</span>
<svg
className="w-4 h-4 text-gray-400"

View File

@@ -0,0 +1,35 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,242 @@
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
// CommandInputProps,
CommandItem,
CommandList,
} from "@/components/ui/command";
// import { HelperText } from "@/components/ui/helper-text";
import { Label } from "@/components/ui/label";
import { PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Skeleton } from "@/components/ui/skeleton";
import { LabelProps } from "@radix-ui/react-label";
type ComboboxTypes<T> = {
labelKey?: keyof T | any;
valueKey?: keyof T | any;
data: T[];
width?: string;
texts?: {
noItems?: string;
placeholder?: string;
searchPlaceholder?: string;
};
isLoading?: boolean;
helperText?: any;
popoverClassName?: string;
/** This the same value as the one with the key valueKey */
defaultValue?: string;
preview?: boolean;
hideInput?: boolean;
direction?: "rtl" | "ltr";
inputProps?: any;
// TODO: fix this
// inputProps?: CommandInputProps;
id?: string;
/** The label of the input field */
label?: any;
labelProps?: LabelProps;
/** If true, it will show a red asterisk next to the label*/
isRequired?: boolean;
onChange?: (e: any) => void;
renderOption?: (item: T) => React.ReactNode;
renderSelected?: (item: T) => React.ReactNode;
};
export const Combobox = React.forwardRef<HTMLDivElement, ComboboxTypes<any>>(
(
{
labelKey = "label",
valueKey = "value",
defaultValue = "",
popoverClassName,
direction,
labelProps,
inputProps,
data,
renderOption,
renderSelected,
...props
},
_
) => {
const [open, setOpen] = React.useState(false);
const [value, setValue] = React.useState(defaultValue);
const containerRef = React.useRef<HTMLDivElement>(null);
// function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
// return key.split(".").reduce((o, k) => (o || {})[k], obj);
// }
function getProperty<T>(obj: T, key: string): any {
return key.split(".").reduce((o: any, k: string) => (o || {})[k], obj);
}
const handleOpenChange = (open: boolean) => {
if (!(props.isLoading || props.preview)) {
setOpen(open);
}
};
const selectedItem = data.find(
(item) => getProperty(item, valueKey) === value
);
return (
<div
className={cn(
"relative flex h-fit flex-col gap-2",
props.width === "fit" ? "w-fit" : "w-full"
)}
ref={containerRef}
>
{props.label && <Label {...labelProps}>{props.label}</Label>}
<PopoverPrimitive.Root open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
{props.isLoading ? (
<div className="pb-2">
<Skeleton className="h-[40px] w-full" />
</div>
) : (
<div className="flex flex-col items-start gap-2">
<div
className={cn(
"absolute top-[22px] h-[0.8px] w-full bg-gray-200 transition-all dark:bg-gray-800",
props.preview ? "opacity-100" : "opacity-0"
)}
></div>
<button
role="combobox"
type="button"
aria-expanded={open}
className={cn(
"inline-flex h-10 w-full select-none items-center justify-between rounded-md border py-2 text-sm font-normal ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
props.preview
? "cursor-default rounded-none border-transparent px-0"
: "bg-background px-3"
)}
>
{selectedItem
? renderSelected
? renderSelected(selectedItem)
: getProperty(selectedItem, labelKey)
: props.texts?.placeholder || ". . ."}
{/* {value
? getProperty(
data.find((item: any) => item[valueKey] === value) ||
{},
labelKey,
)
: props.texts?.placeholder || ". . ."} */}
<svg
xmlns="http://www.w3.org/2000/svg"
className={cn(
"size-4 transition-all",
!props.preview
? "visible opacity-100"
: "invisible opacity-0"
)}
aria-label="Chevron down icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="m6 9 6 6 6-6" />
</svg>
</button>
{/* <HelperText helperText={props.helperText} /> */}
</div>
)}
</PopoverTrigger>
<PopoverContent
sideOffset={0}
className={cn(
"w-[--radix-popover-trigger-width] p-0",
props.helperText && "-mt-4"
)}
dir={direction}
// container={containerRef.current}
>
<Command
filter={(value, search) => {
if (value.toLowerCase().includes(search.toLowerCase()))
return 1;
return 0;
}}
>
{!props.hideInput && (
<CommandInput
{...inputProps}
dir={direction}
placeholder={props.texts?.searchPlaceholder || "Search"}
/>
)}
<CommandEmpty>
{props.texts?.noItems || "No items found."}
</CommandEmpty>
<CommandList>
<CommandGroup
className={cn(
"max-h-[200px]",
data.length > 0 && "overflow-y-auto"
)}
>
{data.map((item: any, i) => (
<CommandItem
key={i}
onSelect={() => {
const newValue = getProperty(item, valueKey);
setValue(
newValue === value ? "" : (newValue as string)
);
if (props.onChange) {
props.onChange(
newValue === value ? "" : (newValue as string)
);
}
setOpen(false);
}}
>
<svg
aria-label="Check Icon"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={cn(
"icon",
value === getProperty(item, valueKey)
? "opacity-100"
: "opacity-0"
)}
style={{ marginInlineEnd: "0.5rem" }}
>
<polyline points="20 6 9 17 4 12" />
</svg>
{renderOption
? renderOption(item)
: getProperty(item, labelKey)}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</PopoverPrimitive.Root>
</div>
);
}
);

View File

@@ -0,0 +1,175 @@
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { SearchIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className
)}
{...props}
/>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent className="overflow-hidden p-0">
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
)
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
)}
{...props}
/>
)
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
className
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
)
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View File

@@ -0,0 +1,46 @@
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 z-50 w-72 rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-primary/10 animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -1,4 +1,4 @@
import { create } from 'zustand'
import { create } from "zustand";
interface Template {
id: string;
@@ -17,9 +17,27 @@ interface Template {
interface TemplateStore {
templates: Template[];
setTemplates: (templates: Template[]) => void;
searchQuery: string;
setSearchQuery: (searchQuery: string) => void;
selectedTags: string[];
addSelectedTag: (tag: string) => void;
removeSelectedTag: (tag: string) => void;
}
export const useStore = create<TemplateStore>((set) => ({
templates: [],
setTemplates: (templates) => set({ templates }),
}))
searchQuery: "",
setSearchQuery: (searchQuery) => set({ searchQuery }),
selectedTags: [],
addSelectedTag: (tag) =>
set((state) => ({
selectedTags: state.selectedTags.includes(tag)
? state.selectedTags
: [...state.selectedTags, tag],
})),
removeSelectedTag: (tag) =>
set((state) => ({
selectedTags: state.selectedTags.filter((t) => t !== tag),
})),
}));