Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 | 1x 1x 1x 1x 1x 376x 1x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 40x 39x 38x 38x 38x 1x 4x 131x 32x 131x 131x 376x 131x 11x 11x 11x 131x 10x 10x 8x 8x 8x 2x 2x 131x 7x 131x 4x 4x 4x 4x 4x 3x 3x 1x 1x 1x 3x 131x 3x 3x 3x 3x 3x 3x 2x 2x 2x 1x 1x 1x 3x 131x 4x 4x 4x 4x 4x 4x 3x 9x 3x 1x 1x 1x 2x 1x 1x 1x 1x 4x 131x 4x 16x 3x 4x 4x 4x 4x 131x 4x 2x 2x 2x 2x 2x 131x 2x 2x 1x 131x 4x 4x 4x 3x 3x 131x 2x 2x 2x 2x 2x 2x 2x 16x 4x 6x 8x 4x 2x 131x 2x 2x 1x 1x 1x 131x 1x 4x 2x 768x 197x 197x 3x 2x 1x 2x 3x 1x 6x 6x 6x 1x 1x 2x 281x 6x 95x 1x 1x 36x 15x 9x 3x 17x 1x 1x 1x | // SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
import { useState, useEffect, useCallback } from "react";
import {
RefreshCw,
Plus,
Pencil,
Trash,
Sparkles,
Check,
X,
ChevronUp,
ChevronDown,
ArrowRight,
RotateCcw,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
getGroupHierarchy,
deleteGroupHierarchy,
categorizeProvider,
fixUncategorizedGroups,
getGeminiApiKey,
updateGroupHierarchyEntry,
reorderGroupHierarchyEntry,
renameSuperCategory,
deleteSuperCategory,
} from "@/lib/tauri";
import { ask } from "@tauri-apps/plugin-dialog";
import { groupSamples, groupTitles, superCategoryNames } from "@/lib/group-hierarchy";
import type { Channel, GroupHierarchyEntry } from "@/lib/types";
import { formatCount } from "@/lib/format";
import { cn } from "@/lib/utils";
// Enough channel names for Gemini to tell what a group holds.
const SAMPLES_PER_GROUP = 5;
// Adding to one category sends every other group, so fewer names each keeps the request small.
const SAMPLES_PER_CANDIDATE = 3;
// Each category owns a block of sort orders, so its groups stay together in their own order.
const CATEGORY_SORT_BLOCK = 1000;
// What to call the names Gemini gets from each group, by content type.
const SAMPLE_NAMES: Record<string, string> = {
live: "channel names",
movie: "movie titles",
series: "series titles",
};
interface GroupChipProps {
name: string;
selected: boolean;
/** Groups placed by hand keep their place when Gemini sorts again, so they get a badge. */
userPlaced?: boolean;
/** Uncategorized groups are drawn a little fainter. */
muted?: boolean;
onToggle: () => void;
}
const GroupChip = ({
name,
selected,
userPlaced = false,
muted = false,
onToggle,
}: GroupChipProps) => (
<button
onClick={onToggle}
aria-pressed={selected}
className={cn(
"px-2.5 py-1 rounded-md text-xs transition-all",
selected
? "bg-primary text-primary-foreground ring-2 ring-primary/50"
: muted
? "bg-secondary/70 hover:bg-accent"
: "bg-secondary hover:bg-accent"
)}
>
{name}
{userPlaced && (
<span className="ml-1 text-[9px] bg-primary/20 text-primary px-1 rounded">user</span>
)}
</button>
);
interface CategoryManagerProps {
providerId: string;
contentType: string;
channels: Channel[];
onClose: () => void;
onHierarchyChanged: () => void;
}
export const CategoryManager = ({
providerId,
contentType,
channels,
onClose,
onHierarchyChanged,
}: CategoryManagerProps) => {
const [entries, setEntries] = useState<GroupHierarchyEntry[]>([]);
const [categorizing, setCategorizing] = useState(false);
const [fixingUncategorized, setFixingUncategorized] = useState(false);
const [error, setError] = useState<string | null>(null);
// Editing state
const [renamingCategory, setRenamingCategory] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [newCategoryName, setNewCategoryName] = useState("");
const [movingGroup, setMovingGroup] = useState<string | null>(null);
// Empty categories created by user (not yet in DB)
const [emptyCategories, setEmptyCategories] = useState<string[]>([]);
// AI prompt dialog
const [aiPromptCategory, setAiPromptCategory] = useState<string | null>(null);
const [aiPromptLoading, setAiPromptLoading] = useState(false);
const load = useCallback(
() =>
getGroupHierarchy(providerId, contentType)
.then((h) => {
if (h.length > 0) {
setEntries(h);
// Remove empty categories that now have groups in DB
const dbCatNames = new Set(superCategoryNames(h));
setEmptyCategories((prev) => prev.filter((c) => !dbCatNames.has(c)));
} else {
// No hierarchy yet, so show all provider groups as uncategorized
setEntries(
groupTitles(channels, contentType).map((g, i) => ({
providerId,
contentType,
groupName: g,
superCategory: null,
sortOrder: i,
isUserOverride: false,
}))
);
}
})
.catch(() => {
// silent
}),
[providerId, contentType, channels]
);
useEffect(() => {
load();
}, [load]);
const dbCats = superCategoryNames(entries);
const superCats = [...dbCats, ...emptyCategories.filter((c) => !dbCats.includes(c))];
const uncategorized = entries.filter((e) => !e.superCategory);
/** Shows the error and gives null when no key is set, so the caller can stop. */
const requireGeminiKey = async (): Promise<string | null> => {
const apiKey = await getGeminiApiKey();
if (!apiKey) setError("No Gemini API key configured. Add one in Settings → AI.");
return apiKey || null;
};
/**
* Saves one change, then reloads so the list shows what was stored.
* Gives false when it failed, after showing the error.
*/
const applyChange = async (change: () => Promise<unknown>): Promise<boolean> => {
try {
await change();
await load();
onHierarchyChanged();
return true;
} catch (e) {
setError(String(e));
return false;
}
};
const toggleMoving = (groupName: string) =>
setMovingGroup(movingGroup === groupName ? null : groupName);
const handleRecategorize = async () => {
setCategorizing(true);
setError(null);
try {
const apiKey = await requireGeminiKey();
if (!apiKey) return;
const groupsWithSamples = groupSamples(
channels,
groupTitles(channels, contentType),
contentType,
SAMPLES_PER_GROUP
);
const result = await categorizeProvider(
providerId,
contentType,
apiKey,
groupsWithSamples
);
setEntries(result);
onHierarchyChanged();
} catch (e) {
setError(String(e));
} finally {
setCategorizing(false);
}
};
const handleFixUncategorized = async () => {
Iif (uncategorized.length === 0 || superCats.length === 0) return;
setFixingUncategorized(true);
setError(null);
try {
const apiKey = await requireGeminiKey();
if (!apiKey) return;
const uncatGroups = groupSamples(
channels,
uncategorized.map((e) => e.groupName),
contentType,
SAMPLES_PER_GROUP
);
const result = await fixUncategorizedGroups(
providerId,
contentType,
apiKey,
uncatGroups,
superCats
);
setEntries(result);
onHierarchyChanged();
} catch (e) {
setError(String(e));
} finally {
setFixingUncategorized(false);
}
};
const handleAiPromptSubmit = async () => {
Iif (!aiPromptCategory) return;
setAiPromptLoading(true);
setError(null);
try {
const apiKey = await requireGeminiKey();
if (!apiKey) return;
// Send ALL groups not already in the target category
const candidateGroups = groupSamples(
channels,
entries.filter((e) => e.superCategory !== aiPromptCategory).map((e) => e.groupName),
contentType,
SAMPLES_PER_CANDIDATE
);
if (candidateGroups.length === 0) {
setError("No other groups available to assign.");
setAiPromptCategory(null);
return;
}
const result = await fixUncategorizedGroups(
providerId,
contentType,
apiKey,
candidateGroups,
[aiPromptCategory]
);
setEntries(result);
onHierarchyChanged();
setAiPromptCategory(null);
} catch (e) {
setError(String(e));
} finally {
setAiPromptLoading(false);
}
};
const handleMoveGroup = async (groupName: string, targetCategory: string | null) => {
const siblingSortOrders = entries
.filter((e) => e.superCategory === targetCategory && e.groupName !== groupName)
.map((e) => e.sortOrder);
const newSortOrder = siblingSortOrders.length > 0 ? Math.max(...siblingSortOrders) + 1 : 0;
const moved = await applyChange(() =>
updateGroupHierarchyEntry(
providerId,
contentType,
groupName,
targetCategory,
newSortOrder
)
);
if (moved) setMovingGroup(null);
};
const handleRenameCategory = async (oldName: string) => {
if (!renameValue.trim() || renameValue === oldName) {
setRenamingCategory(null);
return;
}
const renamed = await applyChange(() =>
renameSuperCategory(providerId, contentType, oldName, renameValue.trim())
);
if (renamed) setRenamingCategory(null);
};
const handleDeleteCategory = async (catName: string) => {
const confirmed = await ask(`Delete "${catName}"? Groups will become uncategorized.`, {
title: "Delete Category",
kind: "warning",
});
if (!confirmed) return;
await applyChange(() => deleteSuperCategory(providerId, contentType, catName));
};
const handleCreateCategory = () => {
const name = newCategoryName.trim();
Iif (!name) return;
if (superCats.includes(name)) return;
setEmptyCategories((prev) => [...prev, name]);
setNewCategoryName("");
};
const handleReorderCategory = async (catName: string, direction: "up" | "down") => {
const idx = superCats.indexOf(catName);
const swapIdx = direction === "up" ? idx - 1 : idx + 1;
Iif (swapIdx < 0 || swapIdx >= superCats.length) return;
// Build new category order by swapping the two
const newOrder = [...superCats];
[newOrder[idx], newOrder[swapIdx]] = [newOrder[swapIdx], newOrder[idx]];
// Reassign sort_order for ALL groups, so the category at position i gets block i
await applyChange(async () => {
for (let catIdx = 0; catIdx < newOrder.length; catIdx++) {
const groups = entries.filter((e) => e.superCategory === newOrder[catIdx]);
for (let gi = 0; gi < groups.length; gi++) {
await reorderGroupHierarchyEntry(
providerId,
contentType,
groups[gi].groupName,
catIdx * CATEGORY_SORT_BLOCK + gi
);
}
}
// Uncategorized groups go at the end
const uncatEntries = entries.filter((e) => !e.superCategory);
for (let i = 0; i < uncatEntries.length; i++) {
await reorderGroupHierarchyEntry(
providerId,
contentType,
uncatEntries[i].groupName,
newOrder.length * CATEGORY_SORT_BLOCK + i
);
}
});
};
const handleReset = async () => {
const confirmed = await ask(
"Reset all categories? This removes all category assignments and returns to the original provider groups.",
{ title: "Reset Categories", kind: "warning" }
);
if (!confirmed) return;
await applyChange(async () => {
await deleteGroupHierarchy(providerId, contentType);
setEmptyCategories([]);
});
};
return (
<div className="flex flex-col h-full">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-border">
<div>
<h2 className="text-base font-semibold">Manage Categories</h2>
<p className="text-xs text-muted-foreground mt-0.5">
{contentType} · {formatCount(entries.length, "group")} ·{" "}
{formatCount(superCats.length, "category", "categories")}
</p>
</div>
<div className="flex gap-2">
<Button
size="sm"
variant="ghost"
onClick={handleReset}
title="Reset to original provider groups"
>
<RotateCcw className="h-3.5 w-3.5 mr-1.5" />
Reset
</Button>
<Button
size="sm"
variant="outline"
onClick={handleRecategorize}
disabled={categorizing}
>
<RefreshCw
className={`h-3.5 w-3.5 mr-1.5 ${categorizing ? "animate-spin" : ""}`}
/>
{categorizing ? "Categorizing…" : "Re-categorize All"}
</Button>
<Button size="sm" variant="ghost" onClick={onClose}>
Close
</Button>
</div>
</div>
{error && (
<div className="mx-4 mt-3 p-2.5 rounded-lg bg-destructive/10 text-destructive text-xs">
{error}
<button onClick={() => setError(null)} className="ml-2 underline">
dismiss
</button>
</div>
)}
{/* New category */}
<div className="px-4 pt-3 pb-2 flex items-center gap-2 border-b border-border/50">
<Plus className="h-4 w-4 text-muted-foreground shrink-0" />
<Input
placeholder="New category name…"
value={newCategoryName}
onChange={(e) => setNewCategoryName(e.target.value)}
className="flex-1 h-8 text-xs"
onKeyDown={(e) => e.key === "Enter" && handleCreateCategory()}
/>
<Button
size="sm"
variant="secondary"
onClick={handleCreateCategory}
disabled={!newCategoryName.trim() || superCats.includes(newCategoryName.trim())}
className="h-8 text-xs"
>
Create
</Button>
</div>
{/* Categories list */}
<div className="flex-1 overflow-y-auto p-4 space-y-3">
{superCats.map((catName, catIdx) => {
const groups = entries.filter((e) => e.superCategory === catName);
const isRenaming = renamingCategory === catName;
return (
<div
key={catName}
role="group"
aria-label={catName}
className="rounded-xl border border-border bg-card"
>
{/* Category header */}
<div className="flex items-center gap-2 px-3 py-2.5 border-b border-border/50">
{isRenaming ? (
<div className="flex items-center gap-1.5 flex-1">
<Input
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
className="h-7 text-sm flex-1"
autoFocus
onKeyDown={(e) => {
if (e.key === "Enter")
handleRenameCategory(catName);
if (e.key === "Escape") setRenamingCategory(null);
}}
/>
<button
onClick={() => handleRenameCategory(catName)}
className="text-green-500 hover:text-green-400 p-1"
title="Save name"
>
<Check className="h-3.5 w-3.5" />
</button>
<button
onClick={() => setRenamingCategory(null)}
className="text-muted-foreground hover:text-foreground p-1"
title="Cancel rename"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
) : (
<>
<span className="text-sm font-semibold flex-1">
{catName}
</span>
<span className="text-[10px] text-muted-foreground tabular-nums">
{formatCount(groups.length, "group")}
</span>
<button
onClick={() => {
setRenamingCategory(catName);
setRenameValue(catName);
}}
className="p-1 text-muted-foreground hover:text-foreground rounded hover:bg-accent"
title="Rename"
>
<Pencil className="h-3 w-3" />
</button>
<button
onClick={() => {
setAiPromptCategory(catName);
}}
className="p-1 text-muted-foreground hover:text-primary rounded hover:bg-primary/10"
title="AI: add groups to this category"
>
<Sparkles className="h-3 w-3" />
</button>
<button
onClick={() => handleReorderCategory(catName, "up")}
disabled={catIdx === 0}
className="p-1 text-muted-foreground hover:text-foreground disabled:opacity-20 rounded hover:bg-accent"
title="Move up"
>
<ChevronUp className="h-3.5 w-3.5" />
</button>
<button
onClick={() => handleReorderCategory(catName, "down")}
disabled={catIdx === superCats.length - 1}
className="p-1 text-muted-foreground hover:text-foreground disabled:opacity-20 rounded hover:bg-accent"
title="Move down"
>
<ChevronDown className="h-3.5 w-3.5" />
</button>
<button
onClick={() => handleDeleteCategory(catName)}
className="p-1 text-muted-foreground hover:text-destructive rounded hover:bg-destructive/10"
title="Delete category"
>
<Trash className="h-3 w-3" />
</button>
</>
)}
</div>
{/* Groups */}
<div className="p-2.5 flex flex-wrap gap-1.5">
{groups.map((g) => (
<GroupChip
key={g.groupName}
name={g.groupName}
selected={movingGroup === g.groupName}
userPlaced={g.isUserOverride}
onToggle={() => toggleMoving(g.groupName)}
/>
))}
</div>
</div>
);
})}
{/* Uncategorized */}
{uncategorized.length > 0 && (
<div
role="group"
aria-label="Uncategorized"
className="rounded-xl border-2 border-dashed border-border bg-card/50"
>
<div className="flex items-center gap-2 px-3 py-2.5 border-b border-border/50">
<span className="text-sm font-semibold text-muted-foreground flex-1">
Uncategorized
</span>
<span className="text-[10px] text-muted-foreground tabular-nums">
{formatCount(uncategorized.length, "group")}
</span>
{superCats.length > 0 && (
<Button
size="sm"
variant="outline"
onClick={handleFixUncategorized}
disabled={fixingUncategorized}
className="h-7 text-xs"
>
<Sparkles
className={`h-3 w-3 mr-1 ${fixingUncategorized ? "animate-pulse" : ""}`}
/>
{fixingUncategorized ? "Assigning…" : "Assign All with AI"}
</Button>
)}
</div>
<div className="p-2.5 flex flex-wrap gap-1.5">
{uncategorized.map((g) => (
<GroupChip
key={g.groupName}
name={g.groupName}
selected={movingGroup === g.groupName}
muted
onToggle={() => toggleMoving(g.groupName)}
/>
))}
</div>
</div>
)}
</div>
{/* Move group bar — slides up when a group is selected */}
{movingGroup && (
<div className="border-t-2 border-primary/30 bg-primary/5 p-3 animate-in slide-in-from-bottom-2">
<div className="flex items-center gap-2 mb-2">
<ArrowRight className="h-4 w-4 text-primary shrink-0" />
<span className="text-sm font-medium">
Move <span className="text-primary">"{movingGroup}"</span> to:
</span>
<div className="flex-1" />
<button
onClick={() => setMovingGroup(null)}
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground"
title="Cancel move"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="flex flex-wrap gap-1.5">
{superCats
.filter((cat) => {
const g = entries.find((e) => e.groupName === movingGroup);
return g?.superCategory !== cat;
})
.map((cat) => (
<button
key={cat}
onClick={() => handleMoveGroup(movingGroup, cat)}
className="px-3 py-1.5 rounded-lg text-xs font-medium bg-card border border-border hover:bg-primary hover:text-primary-foreground hover:border-primary transition-all"
>
{cat}
</button>
))}
{entries.find((e) => e.groupName === movingGroup)?.superCategory && (
<button
onClick={() => handleMoveGroup(movingGroup, null)}
className="px-3 py-1.5 rounded-lg text-xs font-medium bg-card border-2 border-dashed border-border hover:bg-muted transition-all text-muted-foreground"
>
Uncategorized
</button>
)}
</div>
</div>
)}
{/* AI prompt dialog */}
{aiPromptCategory && (
<div className="border-t-2 border-primary/30 bg-primary/5 p-3">
<div className="flex items-center gap-2 mb-2">
<Sparkles className="h-4 w-4 text-primary shrink-0" />
<span className="text-sm font-medium">
AI: Add groups to{" "}
<span className="text-primary">"{aiPromptCategory}"</span>
</span>
<div className="flex-1" />
<button
onClick={() => setAiPromptCategory(null)}
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground"
title="Close AI panel"
>
<X className="h-4 w-4" />
</button>
</div>
<p className="text-xs text-muted-foreground mb-2">
Google Gemini looks at the other groups and moves the ones that belong in
this category.
</p>
<div className="flex gap-2">
<Button
size="sm"
onClick={handleAiPromptSubmit}
disabled={aiPromptLoading}
className="text-xs"
>
{aiPromptLoading ? (
<>
<RefreshCw className="h-3 w-3 mr-1 animate-spin" /> Working…
</>
) : (
<>
<Sparkles className="h-3 w-3 mr-1" /> Find & Add Groups
</>
)}
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => setAiPromptCategory(null)}
className="text-xs"
>
Cancel
</Button>
</div>
</div>
)}
{/* Footer */}
<div className="px-4 py-2.5 border-t border-border text-[10px] text-muted-foreground space-y-0.5">
<p>
Click a group to move it ·{" "}
<span className="bg-primary/20 text-primary px-1 rounded text-[9px]">user</span>{" "}
= manually placed (preserved on re-categorize)
</p>
<p>
AI actions send your group and category names, and a few{" "}
{SAMPLE_NAMES[contentType] ?? "names"} from each group, to Google Gemini.
</p>
</div>
</div>
);
};
|