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
43 changes: 43 additions & 0 deletions app/Actions/Projects/GetProjects.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace App\Actions\Projects;

use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;

class GetProjects
{
public function get(User $user, array $input, int $perPage = 10): Collection
{
$validated = $this->validate($input);

$projectsQuery = $user->allProjects();

if (! empty($validated['query'])) {
$projectsQuery->where('name', 'like', "%{$validated['query']}%");
}

$page = $validated['page'] ?? 1;

return $projectsQuery
->skip(($page - 1) * $perPage)
->take($perPage)
->get();
}

private function validate(array $input): array
{
return Validator::make($input, [
'query' => [
'nullable',
'string',
],
'page' => [
'nullable',
'integer',
'min:1',
],
])->validate();
}
}
12 changes: 12 additions & 0 deletions app/Http/Controllers/Project/ProjectController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Actions\Projects\CreateProject;
use App\Actions\Projects\DeleteProject;
use App\Actions\Projects\GetProjects;
use App\Actions\Projects\UpdateProject;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProjectResource;
Expand All @@ -12,6 +13,7 @@
use App\Models\UserProject;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Inertia\Inertia;
use Inertia\Response;
use Spatie\RouteAttributes\Attributes\Delete;
Expand Down Expand Up @@ -46,6 +48,16 @@ public function index(): Response
]);
}

#[Get('/json', name: 'projects.json')]
public function json(Request $request): ResourceCollection
{
$this->authorize('viewAny', Project::class);

$projects = app(GetProjects::class)->get(user(), $request->input(), 10);

return ProjectResource::collection($projects);
}

#[Post('/', name: 'projects.store')]
public function store(Request $request): RedirectResponse
{
Expand Down
2 changes: 0 additions & 2 deletions app/Http/Middleware/HandleInertiaRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,6 @@ public function share(Request $request): array
'quote' => ['message' => trim($message), 'author' => trim($author)],
'auth' => $user ? [
'user' => UserResource::make($user->load('projects')),
// TODO: limit projects
'projects' => ProjectResource::collection($user->projects()->get()),
'currentProject' => ProjectResource::make($currentProject),
] : null,
'public_key_text' => __('servers.create.public_key_text', ['public_key' => get_public_key_content()]),
Expand Down
177 changes: 177 additions & 0 deletions resources/js/components/project-select.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { type Project } from '@/types/project';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Button } from '@/components/ui/button';
import { CheckIcon, ChevronsUpDownIcon } from 'lucide-react';
import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { cn } from '@/lib/utils';
import axios from 'axios';
import { ReactNode } from 'react';

interface ProjectSelectProps {
value?: string;
onValueChange: (value: string, project: Project) => void;
placeholder?: string;
trigger?: ReactNode;
className?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
footer?: ReactNode;
onRefetch?: (refetch: () => void) => void;
}

export function ProjectSelect({
value,
onValueChange,
placeholder = 'Select project...',
trigger,
className,
open: controlledOpen,
onOpenChange: controlledOnOpenChange,
footer,
onRefetch,
}: ProjectSelectProps) {
const [internalOpen, setInternalOpen] = useState(false);
const [query, setQuery] = useState('');
const loadMoreRef = useRef<HTMLDivElement>(null);

const open = controlledOpen !== undefined ? controlledOpen : internalOpen;
const setOpen = controlledOnOpenChange || setInternalOpen;

const { data, isFetching, refetch, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery<Project[]>({
queryKey: ['projects', query],
queryFn: async ({ pageParam = 1 }) => {
const response = await axios.get(route('projects.json', { query: query || '', page: pageParam }));
return response.data;
},
enabled: open,
staleTime: Infinity,
gcTime: 1000 * 60 * 5,
refetchOnMount: false,
refetchOnWindowFocus: false,
initialPageParam: 1,
getNextPageParam: (lastPage, allPages) => {
return lastPage.length === 10 ? allPages.length + 1 : undefined;
},
});

const projects = data?.pages.flat() ?? [];
const selectedProject = projects.find((project) => project.id.toString() === value);
const refetchRef = useRef<(() => void) | null>(null);

const safeRefetch = useCallback(() => {
if (refetchRef.current) {
refetchRef.current();
}
}, []);

useEffect(() => {
if (refetch) {
refetchRef.current = refetch;
}
}, [refetch]);

useEffect(() => {
if (onRefetch && open) {
onRefetch(safeRefetch);
}
}, [onRefetch, open, safeRefetch]);

useEffect(() => {
if (!open || !hasNextPage) return;

let observer: IntersectionObserver | null = null;
const timeoutId = setTimeout(() => {
if (!loadMoreRef.current) return;

observer = new IntersectionObserver(
(entries) => {
const [entry] = entries;
if (entry.isIntersecting && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
},
{ threshold: 0.1 },
);

observer.observe(loadMoreRef.current);
}, 100);

return () => {
clearTimeout(timeoutId);
if (observer) {
observer.disconnect();
}
};
}, [open, hasNextPage, isFetchingNextPage, fetchNextPage, query, projects.length]);

const handleClose = () => {
const commandList = document.querySelector('[data-slot="command-list"]');
if (commandList instanceof HTMLElement) {
commandList.scrollTop = 0;
}
setQuery('');
};

const handleOpenChange = (isOpen: boolean) => {
setOpen(isOpen);
if (!isOpen) {
handleClose();
}
};

const handleSelect = (project: Project) => {
onValueChange(project.id.toString(), project);
setOpen(false);
};

const defaultTrigger = (
<Button variant="outline" role="combobox" aria-expanded={open} className={cn('w-full justify-between', className)}>
{selectedProject ? selectedProject.name : placeholder}
<ChevronsUpDownIcon className="ml-2 size-4 shrink-0 opacity-50" />
</Button>
);

return (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>{trigger || defaultTrigger}</PopoverTrigger>
<PopoverContent className="flex max-h-[400px] w-56 flex-col p-0" align="start">
<Command shouldFilter={false} className="flex flex-col overflow-hidden">
<CommandInput placeholder="Search project..." value={query} onValueChange={setQuery} />
<CommandList className="min-h-0 flex-1 overflow-y-auto" onWheel={(e) => e.stopPropagation()}>
{projects.length === 0 ? (
<div className="text-muted-foreground py-6 text-center text-sm">
{isFetching ? 'Searching...' : query === '' ? 'Start typing to search projects' : 'No projects found.'}
</div>
) : (
<CommandGroup>
{projects.map((project: Project) => (
<CommandItem
key={`project-select-${project.id}`}
value={project.id.toString()}
onSelect={() => handleSelect(project)}
className="truncate"
>
{project.name}
<CheckIcon className={cn('ml-auto', value === project.id.toString() ? 'opacity-100' : 'opacity-0')} />
</CommandItem>
))}
{hasNextPage && (
<div ref={loadMoreRef} className="flex justify-center py-2">
{isFetchingNextPage ? (
<span className="text-muted-foreground text-xs">Loading more...</span>
) : (
<span className="text-muted-foreground text-xs">Scroll for more</span>
)}
</div>
)}
</CommandGroup>
)}
</CommandList>
{footer && <div className="shrink-0 border-t">{footer}</div>}
</Command>
</PopoverContent>
</Popover>
);
}
105 changes: 59 additions & 46 deletions resources/js/components/project-switch.tsx
Original file line number Diff line number Diff line change
@@ -1,68 +1,81 @@
import { type SharedData } from '@/types';
import { type Project } from '@/types/project';
import { useForm, usePage } from '@inertiajs/react';
import { useState } from 'react';
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { ChevronsUpDownIcon, PlusIcon } from 'lucide-react';
import { useInitials } from '@/hooks/use-initials';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import ProjectForm from '@/pages/projects/components/project-form';
import { ProjectSelect } from '@/components/project-select';
import { CommandGroup, CommandItem } from '@/components/ui/command';

export function ProjectSwitch() {
const page = usePage<SharedData>();
const { auth } = page.props;
const [selectedProject, setSelectedProject] = useState(auth.currentProject?.id?.toString() ?? '');
const [open, setOpen] = useState(false);
const [projectFormOpen, setProjectFormOpen] = useState(false);
const [selected, setSelected] = useState<string>(auth.currentProject?.id?.toString() ?? '');
const [refetchFn, setRefetchFn] = useState<(() => void) | null>(null);
const initials = useInitials();
const form = useForm();

const handleProjectChange = (projectId: string) => {
const selectedProject = auth.projects.find((project) => project.id.toString() === projectId);
if (selectedProject) {
setSelectedProject(selectedProject.id.toString());
form.patch(route('projects.switch', { project: projectId, currentPath: window.location.pathname }));
useEffect(() => {
setSelected(auth.currentProject?.id?.toString() ?? '');
}, [auth.currentProject?.id]);

useEffect(() => {
if (!projectFormOpen && open && refetchFn) {
refetchFn();
}
}, [projectFormOpen, open, refetchFn]);

const handleProjectChange = (value: string, project: Project) => {
setSelected(value);
setOpen(false);
form.patch(route('projects.switch', { project: project.id, currentPath: window.location.pathname }));
};

const footer = (
<CommandGroup>
<ProjectForm defaultOpen={projectFormOpen} onOpenChange={setProjectFormOpen}>
<CommandItem
value="create-project"
onSelect={() => {
setProjectFormOpen(true);
}}
className="gap-0"
>
<div className="flex items-center">
<PlusIcon size={5} />
<span className="ml-2">Create new project</span>
</div>
</CommandItem>
</ProjectForm>
</CommandGroup>
);

const trigger = (
<Button variant="ghost" className="px-1!">
Copy link

Copilot AI Nov 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Invalid CSS class syntax. The exclamation mark should come after 'px-1', not inside the string. Change 'px-1!' to 'px-1'.

Suggested change
<Button variant="ghost" className="px-1!">
<Button variant="ghost" className="px-1">

Copilot uses AI. Check for mistakes.
<Avatar className="size-6 rounded-sm">
<AvatarFallback className="rounded-sm">{initials(auth.currentProject?.name ?? '')}</AvatarFallback>
</Avatar>
<span className="hidden lg:flex">{auth.currentProject?.name}</span>
<ChevronsUpDownIcon size={5} />
</Button>
);

return (
<div className="flex items-center">
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="px-1!">
<Avatar className="size-6 rounded-sm">
<AvatarFallback className="rounded-sm">{initials(auth.currentProject?.name ?? '')}</AvatarFallback>
</Avatar>
<span className="hidden lg:flex">{auth.currentProject?.name}</span>
<ChevronsUpDownIcon size={5} />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" align="start">
{auth.projects.map((project) => (
<DropdownMenuCheckboxItem
key={project.id.toString()}
checked={selectedProject === project.id.toString()}
onCheckedChange={() => handleProjectChange(project.id.toString())}
>
{project.name}
</DropdownMenuCheckboxItem>
))}
<DropdownMenuSeparator />
<ProjectForm>
<DropdownMenuItem className="gap-0" asChild onSelect={(e) => e.preventDefault()}>
<div className="flex items-center">
<PlusIcon size={5} />
<span className="ml-2">Create new project</span>
</div>
</DropdownMenuItem>
</ProjectForm>
</DropdownMenuContent>
</DropdownMenu>
<ProjectSelect
value={selected}
onValueChange={handleProjectChange}
trigger={trigger}
open={open}
onOpenChange={setOpen}
footer={footer}
onRefetch={setRefetchFn}
/>
</div>
);
}
Loading