Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 164 additions & 0 deletions src-frontend/src/components/custom/form/ExtendableSearchInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import React, { useEffect, useRef, useState } from "react";
import { SearchIcon, XIcon } from "lucide-react";
import { useHotkeys } from "react-hotkeys-hook";
import { Button } from "@/components/ui/button";
import { InputGroup, InputGroupInput } from "@/components/ui/input-group";
import { cn } from "@/lib/utils";
import { useDebounceFn } from "ahooks";

export type ExpandableSearchBarProps = {
expandDirection?: "left" | "right";
placeholder?: string;
onValueChange?: (query: string) => void;
className?: string;
defaultOpen?: boolean;
width?: number;
};

// Match Button `size="icon"` (size-9) so this sits flush with SideBarHeader actions.
const COLLAPSED_SIZE = 36;
// Keep this in sync with the `duration-*` class / transitionDuration below.
const TRANSITION_MS = 260;

export function ExpandableSearchBar({
expandDirection = "right",
placeholder = "Search...",
onValueChange,
className = "",
defaultOpen = false,
}: ExpandableSearchBarProps) {
const [open, setOpen] = useState(defaultOpen);
// Whether the form is in the DOM at all.
const [mounted, setMounted] = useState(defaultOpen);
// Whether it's painted at its *expanded* width/opacity (drives the transition).
const [expanded, setExpanded] = useState(defaultOpen);
const [value, setValue] = useState("");

const containerRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const unmountTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const rafIds = useRef<number[]>([]);

const handleClear = () => {
setValue("");
onValueChange?.("");
};

const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
handleOnChange.run(value);
};

const handleOnChange = useDebounceFn((next: string) => {
onValueChange?.(next);
}, { wait: 300 });

// Mount/unmount + expand/collapse orchestration.
// On open: mount immediately at the collapsed size, then flip to expanded
// a couple of frames later so the browser has something to transition *from*.
// On close: collapse immediately, then unmount once the transition ends.
useEffect(() => {
if (unmountTimer.current) clearTimeout(unmountTimer.current);
rafIds.current.forEach(cancelAnimationFrame);
rafIds.current = [];

if (open) {
setMounted(true);
const id1 = requestAnimationFrame(() => {
const id2 = requestAnimationFrame(() => setExpanded(true));
rafIds.current.push(id2);
});
rafIds.current.push(id1);
} else {
setExpanded(false);
unmountTimer.current = setTimeout(() => setMounted(false), TRANSITION_MS);
}

return () => {
if (unmountTimer.current) clearTimeout(unmountTimer.current);
rafIds.current.forEach(cancelAnimationFrame);
rafIds.current = [];
};
}, [open]);

// Click outside to close (only when empty).
useEffect(() => {
function onDocClick(e: MouseEvent) {
if (!containerRef.current?.contains(e.target as Node) && open && value === "") {
setOpen(false);
handleClear();
}
}
document.addEventListener("mousedown", onDocClick);
return () => document.removeEventListener("mousedown", onDocClick);
}, [open, value, onValueChange]);

// Autofocus on open, clear value on close.
useEffect(() => {
if (open) {
const id = setTimeout(() => inputRef.current?.focus(), 120);
return () => clearTimeout(id);
} else {
handleClear();
}
}, [open, onValueChange]);

// Escape to close; Enter is handled by form submit.
useHotkeys("esc", () => {
setOpen(false);
handleClear();
}, {
enabled: open,
preventDefault: true,
enableOnFormTags: true,
});

return (
<div
ref={containerRef}
className={cn("relative", className)}
style={{ width: expanded ? "100%" : COLLAPSED_SIZE, height: COLLAPSED_SIZE }}
>
<Button
type="button"
variant="secondary"
size="icon"
aria-label={open ? "Close search" : "Open search"}
onClick={() => setOpen((s) => !s)}
className="absolute right-0 z-20 rounded-full bg-secondary hover:bg-secondary"
>
{open ? <XIcon className="size-4" /> : <SearchIcon className="size-4" />}
</Button>

{mounted && (
<form
onSubmit={handleSubmit}
className={cn(
"absolute top-0",
"transition-[width,opacity] duration-260 ease-[cubic-bezier(0.34,1.56,0.64,1)]",
expandDirection === "left" ? "right-0" : "left-0",
expanded ? "opacity-100" : "opacity-0"
)}
style={{ width: expanded ? "100%" : COLLAPSED_SIZE }}
>
<InputGroup className="h-9 border-none overflow-hidden rounded-full">
<InputGroupInput
ref={inputRef}
type="text"
value={value}
onChange={(e) => {
const next = e.target.value;
setValue(next);
if ((e.nativeEvent as InputEvent).isComposing) return;
handleOnChange.run(next);
}}
onCompositionEnd={() => handleOnChange.run(value)}
placeholder={placeholder}
className="whitespace-nowrap overflow-x-auto"
/>
</InputGroup>
</form>
)}
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
Expand Down Expand Up @@ -91,10 +90,7 @@ function DirectorySelectDialog({
>
<FileTreeSuspense
selectedPath={draftPath}
onSelect={(path) => {
console.log(path);
setDraftPath(path);
}}
onSelect={setDraftPath}
/>
</AsyncBoundary>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,19 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";

type SideBarHeaderProps = {
title: string;
children?: React.ReactNode;
actionsClass?: string;
};

export function SideBarHeader({ title, children }: SideBarHeaderProps) {
export function SideBarHeader({ title, children, actionsClass }: SideBarHeaderProps) {
return (
<div className="flex items-center justify-between border-b py-2 pr-3 pl-4">
<span className="h-8 font-medium text-sm leading-8">{title}</span>
<div className="flex gap-2">{children}</div>
<div className={cn("flex gap-2", actionsClass)}>{children}</div>
</div>
);
}
Expand Down
19 changes: 15 additions & 4 deletions src-frontend/src/features/SideBar/views/SkillsView/SkillList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,24 @@ function SkillItem({ skill, index, ref, onDelete }: SkillItemProps) {
);
}

export function SkillList() {
type SkillListProps = {
searchQuery?: string;
};

export function SkillList({ searchQuery }: SkillListProps) {
const { t } = useTranslation(SIDEBAR_NAMESPACE);
const removeTabs = useTabsStore((state) => state.remove);

const query = useGetSkillsSuspenseInfinite(undefined, {
query: { ...PAGINATED_QUERY_DEFAULT_OPTIONS, gcTime: SIDEBAR_QUERY_GC_TIME },
});
const trimmedQuery = searchQuery?.trim();
const query = useGetSkillsSuspenseInfinite(
trimmedQuery ? { query: trimmedQuery } : undefined,
{
query: {
...PAGINATED_QUERY_DEFAULT_OPTIONS,
gcTime: SIDEBAR_QUERY_GC_TIME,
},
},
);

const deleteSkillMutation = useDeleteSkill({
mutation: {
Expand Down
40 changes: 27 additions & 13 deletions src-frontend/src/features/SideBar/views/SkillsView/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { useDebounce } from "ahooks";
import { FileUpIcon, PlusIcon } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { invalidateSkillQueries, useUploadArchive } from "@/api/skill";
import { AsyncBoundary } from "@/components/custom/AsyncBoundary";
import { ExpandableSearchBar } from "@/components/custom/form/ExtendableSearchInput";
import { ButtonGroup } from "@/components/ui/button-group";
import { i18n } from "@/i18n";
import { SIDEBAR_NAMESPACE } from "@/i18n/resources";
import { useTabsStore } from "@/stores/tabs-store";
Expand All @@ -24,6 +28,8 @@ function openSkillCreateTab() {

export function SkillsView() {
const { t } = useTranslation(SIDEBAR_NAMESPACE);
const [searchValue, setSearchValue] = useState("");

const { inputProps, open: openFileDialog } = useFileSelect({
accept: ".zip,application/zip",
multiple: false,
Expand Down Expand Up @@ -55,23 +61,31 @@ export function SkillsView() {
return (
<div className="flex h-full flex-col">
<input {...inputProps} className="hidden" />
<SideBarHeader title={t("skills.header.title")}>
<SideBarHeaderAction
Icon={PlusIcon}
tooltip={t("skills.header.create_tooltip")}
onClick={openSkillCreateTab}
/>
<InstallFromGithubDialog />
<SideBarHeaderAction
Icon={FileUpIcon}
tooltip={t("skills.header.upload_tooltip")}
onClick={handleUploadClick}
disabled={uploadArchiveMutation.isPending}
<SideBarHeader title={t("skills.header.title")} actionsClass="flex-1 ml-4">
<ExpandableSearchBar
className="flex-1"
expandDirection="left"
placeholder={t("skills.header.search_placeholder")}
onValueChange={setSearchValue}
/>
<ButtonGroup>
<SideBarHeaderAction
Icon={PlusIcon}
tooltip={t("skills.header.create_tooltip")}
onClick={openSkillCreateTab}
/>
<InstallFromGithubDialog />
<SideBarHeaderAction
Icon={FileUpIcon}
tooltip={t("skills.header.upload_tooltip")}
onClick={handleUploadClick}
disabled={uploadArchiveMutation.isPending}
/>
</ButtonGroup>
</SideBarHeader>
<div className="flex-1 min-h-0">
<AsyncBoundary skeleton={<SideBarListSkeleton />}>
<SkillList />
<SkillList searchQuery={searchValue} />
</AsyncBoundary>
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions src-frontend/src/i18n/locales/en/sidebar.json
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@
"header": {
"create_tooltip": "Create new skill",
"install_github_tooltip": "Install from GitHub",
"search_placeholder": "Search skills...",
"title": "Skills",
"upload_tooltip": "Upload skill archive"
},
Expand Down
1 change: 1 addition & 0 deletions src-frontend/src/i18n/locales/zh_CN/sidebar.json
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@
"header": {
"create_tooltip": "创建技能",
"install_github_tooltip": "从 GitHub 安装",
"search_placeholder": "搜索技能...",
"title": "技能",
"upload_tooltip": "上传技能归档"
},
Expand Down
11 changes: 7 additions & 4 deletions src-server/src/api/routes/skill.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from dais_skills.scanner.exceptions import (
InvalidRepoUrlError as ScannerInvalidRepoUrlError,
)
from fastapi import APIRouter, BackgroundTasks, File, UploadFile, status
from fastapi import APIRouter, BackgroundTasks, File, Query, UploadFile, status
from fastapi_pagination import Page
from fastapi_pagination.ext.sqlalchemy import apaginate

Expand Down Expand Up @@ -75,9 +75,12 @@ async def clear_and_rematerialize(skill: skill_schemas.SkillRead):
background_tasks.add_task(clear_and_rematerialize, skill_data)

@skills_router.get("/", response_model=Page[skill_schemas.SkillBrief])
async def get_skills(db_session: DbSessionDep):
query = SkillService(db_session).get_skills_query()
return await apaginate(db_session, query)
async def get_skills(
db_session: DbSessionDep,
query: str | None = Query(default=None),
):
db_query = SkillService(db_session).get_skills_query(query)
return await apaginate(db_session, db_query)

@skills_router.post(
"/scan-repo",
Expand Down
11 changes: 9 additions & 2 deletions src-server/src/services/skill.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,19 @@ def relations():
selectinload(skill_models.Skill.resources)
]

def get_skills_query(self):
return (
def get_skills_query(self, query: str | None = None):
stmt = (
select(skill_models.Skill)
.order_by(skill_models.Skill.id.asc())
.options(selectinload(skill_models.Skill.resources))
)
if query:
search_term = f"%{query}%"
stmt = stmt.where(
skill_models.Skill.name.ilike(search_term)
| skill_models.Skill.description.ilike(search_term)
)
return stmt

async def get_all_skills(self) -> list[skill_models.Skill]:
stmt = (
Expand Down
Loading
Loading