|
| 1 | +"use client"; |
| 2 | + |
1 | 3 | import Link from "next/link";
|
2 |
| -import { slug } from "github-slugger"; |
| 4 | +import { usePathname, useRouter, useSearchParams } from "next/navigation"; |
3 | 5 |
|
4 | 6 | interface TagProps {
|
5 |
| - children: string; |
| 7 | + tag: string; |
| 8 | + children?: string; |
6 | 9 | }
|
7 |
| -export function Tag({ children }: TagProps) { |
8 |
| - return <span className="tag">{children}</span>; |
| 10 | + |
| 11 | +/** |
| 12 | + * A tag component that can be used to filter content by tag. |
| 13 | + * If no children are provided, the tag string will be displayed. |
| 14 | + */ |
| 15 | +export function Tag({ tag, children }: TagProps) { |
| 16 | + const searchParams = useSearchParams(); |
| 17 | + const pathname = usePathname(); |
| 18 | + const { replace } = useRouter(); |
| 19 | + |
| 20 | + function selectTag() { |
| 21 | + console.log("Tag selected:", tag); |
| 22 | + |
| 23 | + const params = new URLSearchParams(searchParams); |
| 24 | + |
| 25 | + const currentTags = params.get("tags"); |
| 26 | + const tags = currentTags ? currentTags.split(" ") : []; |
| 27 | + if (tags.includes(tag)) { |
| 28 | + // Remove tag |
| 29 | + tags.splice(tags.indexOf(tag), 1); |
| 30 | + } else { |
| 31 | + // Add tag |
| 32 | + tags.push(tag); |
| 33 | + } |
| 34 | + |
| 35 | + params.set("tags", tags.join(" ")); |
| 36 | + // Remove tags parameter if empty |
| 37 | + if (tags.length === 0) { |
| 38 | + params.delete("tags"); |
| 39 | + } |
| 40 | + replace(`${pathname}?${params.toString()}`); |
| 41 | + } |
| 42 | + |
| 43 | + return children ? ( |
| 44 | + <button onClick={selectTag} className="tag"> |
| 45 | + {children} |
| 46 | + </button> |
| 47 | + ) : ( |
| 48 | + <button onClick={selectTag} className="tag"> |
| 49 | + {tag} |
| 50 | + </button> |
| 51 | + ); |
9 | 52 | }
|
0 commit comments