implement creating new conversation

This commit is contained in:
2026-05-01 01:36:04 +03:30
parent ba507ca6c3
commit 4776af5c2a
10 changed files with 886 additions and 80 deletions

View File

@@ -17,7 +17,7 @@ class ChatPage extends Component
{ {
public ?int $selectedConversationId = null; public ?int $selectedConversationId = null;
public bool $detailsPanelOpen = true; public bool $detailsPanelOpen = false;
#[On('conversation-selected')] #[On('conversation-selected')]
public function selectConversation(int $conversationId): void public function selectConversation(int $conversationId): void
@@ -29,7 +29,7 @@ class ChatPage extends Component
Gate::authorize('view', $conversation); Gate::authorize('view', $conversation);
$this->selectedConversationId = $conversation->id; $this->selectedConversationId = $conversation->id;
$this->detailsPanelOpen = true; $this->detailsPanelOpen = false;
} }
#[On('conversation-closed')] #[On('conversation-closed')]

View File

@@ -4,11 +4,18 @@ namespace App\Livewire\Chat;
use App\Models\Conversation; use App\Models\Conversation;
use App\Models\ConversationParticipant; use App\Models\ConversationParticipant;
use App\Models\User;
use Flux\Flux;
use Illuminate\Contracts\View\View; use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed; use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component; use Livewire\Component;
class ConversationDetailsPanel extends Component class ConversationDetailsPanel extends Component
@@ -16,11 +23,30 @@ class ConversationDetailsPanel extends Component
#[Locked] #[Locked]
public int $conversationId; public int $conversationId;
public bool $showAddMembersModal = false;
public string $memberSearch = '';
/**
* @var array<int, int>
*/
public array $selectedMemberIds = [];
public string $groupName = '';
public function mount(int $conversationId): void public function mount(int $conversationId): void
{ {
$this->conversationId = $conversationId; $this->conversationId = $conversationId;
} }
#[On('conversation-updated')]
public function refreshConversation(int $conversationId): void
{
if ($conversationId === $this->conversationId) {
unset($this->conversation);
}
}
#[Computed] #[Computed]
public function conversation(): Conversation public function conversation(): Conversation
{ {
@@ -59,6 +85,183 @@ class ConversationDetailsPanel extends Component
->implode(''); ->implode('');
} }
public function canAddMembers(): bool
{
return Gate::allows('addMembers', $this->conversation);
}
public function closeDetails(): void
{
$this->dispatch('conversation-details-toggled');
}
public function openAddMembers(): void
{
Gate::authorize('addMembers', $this->conversation);
$this->resetAddMembersForm();
$this->groupName = $this->conversation->isGroup() ? '' : $this->suggestedGroupName();
$this->showAddMembersModal = true;
}
public function toggleMember(int $userId): void
{
if ($userId === Auth::id()) {
return;
}
if ($this->conversation->participants->contains('user_id', $userId)) {
return;
}
if (! User::query()->whereKey($userId)->exists()) {
return;
}
if (in_array($userId, $this->selectedMemberIds, true)) {
$this->selectedMemberIds = array_values(array_diff($this->selectedMemberIds, [$userId]));
} else {
$this->selectedMemberIds[] = $userId;
}
$this->resetValidation('selectedMemberIds');
unset($this->availableUsers, $this->selectedMembers);
}
public function removeSelectedMember(int $userId): void
{
$this->selectedMemberIds = array_values(array_diff($this->selectedMemberIds, [$userId]));
unset($this->availableUsers, $this->selectedMembers);
}
public function addMembers(): void
{
$conversation = $this->conversation;
Gate::authorize('addMembers', $conversation);
$validated = $this->validate([
'selectedMemberIds' => ['required', 'array', 'min:1'],
'selectedMemberIds.*' => ['integer', Rule::exists('users', 'id')],
'groupName' => ['nullable', 'string', 'max:80'],
]);
$existingMemberIds = $conversation->participants->pluck('user_id');
$memberIds = User::query()
->whereKey($validated['selectedMemberIds'])
->whereKeyNot(Auth::id())
->whereNotIn('id', $existingMemberIds)
->pluck('id')
->values();
if ($memberIds->isEmpty()) {
$this->addError('selectedMemberIds', __('Choose at least one new person.'));
return;
}
DB::transaction(function () use ($conversation, $memberIds): void {
if (! $conversation->isGroup()) {
$conversation->forceFill([
'type' => Conversation::TypeGroup,
'name' => trim($this->groupName) ?: $this->suggestedGroupName($memberIds),
])->save();
ConversationParticipant::query()
->where('conversation_id', $conversation->id)
->where('user_id', Auth::id())
->update(['role' => ConversationParticipant::RoleAdmin]);
}
$memberIds->each(fn (int $memberId) => ConversationParticipant::query()->firstOrCreate([
'conversation_id' => $conversation->id,
'user_id' => $memberId,
], [
'role' => ConversationParticipant::RoleMember,
'joined_at' => now(),
]));
$conversation->touch();
});
$this->resetAddMembersForm();
$this->showAddMembersModal = false;
unset($this->conversation);
Flux::toast(variant: 'success', text: __('Members added.'));
$this->dispatch('conversation-updated', conversationId: $this->conversationId);
}
/**
* @return Collection<int, User>
*/
#[Computed]
public function availableUsers(): Collection
{
$search = trim($this->memberSearch);
$participantIds = $this->conversation->participants->pluck('user_id')->all();
return User::query()
->select(['id', 'name', 'email'])
->whereNotIn('id', $participantIds)
->whereNotIn('id', $this->selectedMemberIds)
->when($search !== '', fn (Builder $query) => $query->where(function (Builder $query) use ($search): void {
$query
->where('name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
}))
->orderBy('name')
->limit(10)
->get();
}
/**
* @return Collection<int, User>
*/
#[Computed]
public function selectedMembers(): Collection
{
return User::query()
->select(['id', 'name', 'email'])
->whereKey($this->selectedMemberIds)
->get()
->sortBy(fn (User $user) => array_search($user->id, $this->selectedMemberIds, true))
->values();
}
private function suggestedGroupName(?Collection $newMemberIds = null): string
{
$participantNames = $this->conversation->participants
->pluck('user.name')
->filter();
if ($newMemberIds) {
$participantNames = $participantNames->merge(
User::query()
->whereKey($newMemberIds->all())
->orderBy('name')
->pluck('name')
);
}
return $participantNames
->unique()
->take(4)
->join(', ');
}
private function resetAddMembersForm(): void
{
$this->reset('memberSearch', 'selectedMemberIds', 'groupName');
$this->resetValidation();
unset($this->availableUsers, $this->selectedMembers);
}
public function render(): View public function render(): View
{ {
return view('livewire.chat.conversation-details-panel'); return view('livewire.chat.conversation-details-panel');

View File

@@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed; use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component; use Livewire\Component;
class ConversationHeader extends Component class ConversationHeader extends Component
@@ -22,6 +23,14 @@ class ConversationHeader extends Component
$this->conversationId = $conversationId; $this->conversationId = $conversationId;
} }
#[On('conversation-updated')]
public function refreshConversation(int $conversationId): void
{
if ($conversationId === $this->conversationId) {
unset($this->conversation);
}
}
#[Computed] #[Computed]
public function conversation(): Conversation public function conversation(): Conversation
{ {

View File

@@ -6,10 +6,14 @@ use App\Models\Conversation;
use App\Models\ConversationParticipant; use App\Models\ConversationParticipant;
use App\Models\User; use App\Models\User;
use Carbon\CarbonInterface; use Carbon\CarbonInterface;
use Flux\Flux;
use Illuminate\Contracts\View\View; use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed; use Livewire\Attributes\Computed;
use Livewire\Attributes\On; use Livewire\Attributes\On;
use Livewire\Component; use Livewire\Component;
@@ -20,7 +24,24 @@ class ConversationList extends Component
public string $search = ''; public string $search = '';
public bool $showCreateConversationModal = false;
public string $createType = Conversation::TypeDirect;
public string $memberSearch = '';
/**
* @var array<int, int>
*/
public array $selectedMemberIds = [];
public string $groupName = '';
public string $groupDescription = '';
#[On('message-created')] #[On('message-created')]
#[On('conversation-created')]
#[On('conversation-updated')]
public function refreshConversations(): void public function refreshConversations(): void
{ {
unset($this->conversations); unset($this->conversations);
@@ -31,6 +52,136 @@ class ConversationList extends Component
$this->dispatch('conversation-selected', conversationId: $conversationId); $this->dispatch('conversation-selected', conversationId: $conversationId);
} }
public function openCreateConversation(): void
{
$this->resetCreateConversationForm();
$this->showCreateConversationModal = true;
}
public function updatedCreateType(string $createType): void
{
if ($createType === Conversation::TypeDirect && count($this->selectedMemberIds) > 1) {
$this->selectedMemberIds = [array_values($this->selectedMemberIds)[0]];
}
$this->resetValidation();
unset($this->candidateUsers, $this->selectedMembers);
}
public function toggleMember(int $userId): void
{
if ($userId === Auth::id()) {
return;
}
if (! User::query()->whereKey($userId)->exists()) {
return;
}
if ($this->createType === Conversation::TypeDirect) {
$this->selectedMemberIds = [$userId];
} elseif (in_array($userId, $this->selectedMemberIds, true)) {
$this->selectedMemberIds = array_values(array_diff($this->selectedMemberIds, [$userId]));
} else {
$this->selectedMemberIds[] = $userId;
}
$this->resetValidation('selectedMemberIds');
unset($this->candidateUsers, $this->selectedMembers);
}
public function removeSelectedMember(int $userId): void
{
$this->selectedMemberIds = array_values(array_diff($this->selectedMemberIds, [$userId]));
unset($this->candidateUsers, $this->selectedMembers);
}
public function createConversation(): void
{
Gate::authorize('create', Conversation::class);
$validated = $this->validate([
'createType' => ['required', Rule::in([Conversation::TypeDirect, Conversation::TypeGroup])],
'selectedMemberIds' => ['required', 'array', 'min:1'],
'selectedMemberIds.*' => ['integer', Rule::exists('users', 'id')],
'groupName' => [
Rule::requiredIf($this->createType === Conversation::TypeGroup),
'nullable',
'string',
'max:80',
],
'groupDescription' => ['nullable', 'string', 'max:180'],
]);
$memberIds = User::query()
->whereKey($validated['selectedMemberIds'])
->whereKeyNot(Auth::id())
->pluck('id')
->map(fn (int $id) => $id)
->values();
if ($memberIds->isEmpty()) {
$this->addError('selectedMemberIds', __('Choose at least one person.'));
return;
}
if ($this->createType === Conversation::TypeDirect && $memberIds->count() !== 1) {
$this->addError('selectedMemberIds', __('Choose one person for a direct conversation.'));
return;
}
$conversation = DB::transaction(function () use ($memberIds, $validated): Conversation {
if ($this->createType === Conversation::TypeDirect) {
$existingConversation = $this->findExistingDirectConversation($memberIds->first());
if ($existingConversation) {
return $existingConversation;
}
}
$conversation = Conversation::query()->create([
'created_by_id' => Auth::id(),
'type' => $this->createType,
'name' => $this->createType === Conversation::TypeGroup ? trim((string) $validated['groupName']) : null,
'description' => $this->createType === Conversation::TypeGroup ? trim((string) ($validated['groupDescription'] ?? '')) ?: null : null,
]);
ConversationParticipant::query()->create([
'conversation_id' => $conversation->id,
'user_id' => Auth::id(),
'role' => ConversationParticipant::RoleAdmin,
'joined_at' => now(),
'last_read_at' => now(),
]);
$memberIds->each(fn (int $memberId) => ConversationParticipant::query()->create([
'conversation_id' => $conversation->id,
'user_id' => $memberId,
'role' => ConversationParticipant::RoleMember,
'joined_at' => now(),
]));
return $conversation;
});
$this->resetCreateConversationForm();
$this->showCreateConversationModal = false;
unset($this->conversations);
Flux::toast(variant: 'success', text: __('Conversation ready.'));
$this->dispatch('conversation-created', conversationId: $conversation->id);
$this->dispatch('conversation-selected', conversationId: $conversation->id);
}
/** /**
* @return Collection<int, Conversation> * @return Collection<int, Conversation>
*/ */
@@ -79,6 +230,42 @@ class ConversationList extends Component
->get(); ->get();
} }
/**
* @return Collection<int, User>
*/
#[Computed]
public function candidateUsers(): Collection
{
$search = trim($this->memberSearch);
return User::query()
->select(['id', 'name', 'email'])
->whereKeyNot(Auth::id())
->whereNotIn('id', $this->selectedMemberIds)
->when($search !== '', fn (Builder $query) => $query->where(function (Builder $query) use ($search): void {
$query
->where('name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
}))
->orderBy('name')
->limit(10)
->get();
}
/**
* @return Collection<int, User>
*/
#[Computed]
public function selectedMembers(): Collection
{
return User::query()
->select(['id', 'name', 'email'])
->whereKey($this->selectedMemberIds)
->get()
->sortBy(fn (User $user) => array_search($user->id, $this->selectedMemberIds, true))
->values();
}
public function titleFor(Conversation $conversation): string public function titleFor(Conversation $conversation): string
{ {
if ($conversation->isGroup()) { if ($conversation->isGroup()) {
@@ -159,6 +346,32 @@ class ConversationList extends Component
?->user; ?->user;
} }
private function findExistingDirectConversation(int $memberId): ?Conversation
{
return Conversation::query()
->forUser(Auth::user())
->where('type', Conversation::TypeDirect)
->whereHas('participants', fn (Builder $participants) => $participants->where('user_id', $memberId))
->withCount('participants')
->get()
->first(fn (Conversation $conversation) => (int) $conversation->participants_count === 2);
}
private function resetCreateConversationForm(): void
{
$this->reset(
'createType',
'memberSearch',
'selectedMemberIds',
'groupName',
'groupDescription',
);
$this->resetValidation();
unset($this->candidateUsers, $this->selectedMembers);
}
public function render(): View public function render(): View
{ {
return view('livewire.chat.conversation-list'); return view('livewire.chat.conversation-list');

View File

@@ -45,6 +45,14 @@ class ConversationView extends Component
$this->markAsRead(); $this->markAsRead();
} }
#[On('conversation-updated')]
public function refreshConversation(int $conversationId): void
{
if ($conversationId === $this->conversationId) {
unset($this->conversation);
}
}
#[Computed] #[Computed]
public function conversation(): Conversation public function conversation(): Conversation
{ {

View File

@@ -72,6 +72,22 @@ class ConversationPolicy
return $this->participates($user, $conversation); return $this->participates($user, $conversation);
} }
public function addMembers(User $user, Conversation $conversation): bool
{
if (! $this->participates($user, $conversation)) {
return false;
}
if (! $conversation->isGroup()) {
return true;
}
return $conversation->participants()
->where('user_id', $user->id)
->where('role', ConversationParticipant::RoleAdmin)
->exists();
}
private function participates(User $user, Conversation $conversation): bool private function participates(User $user, Conversation $conversation): bool
{ {
return $conversation->participants() return $conversation->participants()

View File

@@ -41,10 +41,19 @@
</main> </main>
@if ($selectedConversationId && $detailsPanelOpen) @if ($selectedConversationId && $detailsPanelOpen)
<aside class="hidden h-full w-[21rem] shrink-0 border-s border-zinc-200 bg-zinc-50/70 dark:border-zinc-800 dark:bg-zinc-900/60 2xl:flex"> <aside class="hidden h-full w-[21rem] shrink-0 border-s border-zinc-200 bg-zinc-50/70 dark:border-zinc-800 dark:bg-zinc-900/60 xl:flex">
<livewire:chat.conversation-details-panel <livewire:chat.conversation-details-panel
:conversation-id="$selectedConversationId" :conversation-id="$selectedConversationId"
:key="'conversation-details-'.$selectedConversationId" :key="'conversation-details-desktop-'.$selectedConversationId"
/>
</aside>
<div class="fixed inset-0 z-40 bg-zinc-950/40 backdrop-blur-[2px] xl:hidden" wire:click="toggleDetailsPanel"></div>
<aside class="fixed inset-y-0 end-0 z-50 flex w-full max-w-sm border-s border-zinc-200 bg-zinc-50 shadow-xl dark:border-zinc-800 dark:bg-zinc-900 xl:hidden">
<livewire:chat.conversation-details-panel
:conversation-id="$selectedConversationId"
:key="'conversation-details-mobile-'.$selectedConversationId"
/> />
</aside> </aside>
@endif @endif

View File

@@ -8,9 +8,19 @@
</flux:text> </flux:text>
</div> </div>
<flux:badge color="zinc" size="sm"> <div class="flex items-center gap-2">
{{ trans_choice(':count message|:count messages', $this->conversation->messages_count, ['count' => $this->conversation->messages_count]) }} <flux:badge color="zinc" size="sm">
</flux:badge> {{ trans_choice(':count message|:count messages', $this->conversation->messages_count, ['count' => $this->conversation->messages_count]) }}
</flux:badge>
<flux:button
type="button"
variant="ghost"
icon="x-mark"
wire:click="closeDetails"
aria-label="{{ __('Close details') }}"
/>
</div>
</div> </div>
<div class="mt-6 flex flex-col items-center text-center"> <div class="mt-6 flex flex-col items-center text-center">
@@ -51,8 +61,22 @@
<section> <section>
<div class="flex items-center justify-between gap-3"> <div class="flex items-center justify-between gap-3">
<flux:heading size="sm">{{ __('Participants') }}</flux:heading> <div class="flex items-center gap-2">
<flux:badge size="sm" color="zinc">{{ $this->conversation->participants->count() }}</flux:badge> <flux:heading size="sm">{{ __('Participants') }}</flux:heading>
<flux:badge size="sm" color="zinc">{{ $this->conversation->participants->count() }}</flux:badge>
</div>
@if ($this->canAddMembers())
<flux:button
type="button"
size="sm"
variant="filled"
icon="user-plus"
wire:click="openAddMembers"
>
{{ __('Add') }}
</flux:button>
@endif
</div> </div>
<div class="mt-3 space-y-3"> <div class="mt-3 space-y-3">
@@ -99,4 +123,116 @@
</div> </div>
</section> </section>
</div> </div>
<flux:modal wire:model="showAddMembersModal" class="w-full max-w-xl">
<form wire:submit="addMembers" class="space-y-6">
<div>
<flux:heading size="lg">{{ __('Add people') }}</flux:heading>
<flux:text class="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
@if ($this->conversation->isGroup())
{{ __('Invite more teammates into this group conversation.') }}
@else
{{ __('Adding people will turn this direct chat into a group conversation.') }}
@endif
</flux:text>
</div>
@unless ($this->conversation->isGroup())
<flux:input
wire:model="groupName"
:label="__('Group name')"
:placeholder="__('Name this group')"
autocomplete="off"
/>
@endunless
<div class="space-y-3">
<flux:input
wire:model.live.debounce.250ms="memberSearch"
icon="magnifying-glass"
:label="__('People')"
:placeholder="__('Search people not already here')"
autocomplete="off"
/>
@error('selectedMemberIds')
<flux:text class="text-sm text-red-600 dark:text-red-400">{{ $message }}</flux:text>
@enderror
@if ($this->selectedMembers->isNotEmpty())
<div class="flex flex-wrap gap-2">
@foreach ($this->selectedMembers as $member)
<button
type="button"
wire:key="add-selected-member-{{ $member->id }}"
wire:click="removeSelectedMember({{ $member->id }})"
class="inline-flex items-center gap-2 rounded-full border border-zinc-200 bg-white py-1 pe-2 ps-1 text-sm text-zinc-700 shadow-sm transition hover:border-zinc-300 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:border-zinc-600"
>
<span class="flex size-6 items-center justify-center rounded-full bg-zinc-100 text-[10px] font-semibold dark:bg-zinc-800">
{{ $member->initials() }}
</span>
<span>{{ $member->name }}</span>
<flux:icon.x-mark class="size-3 text-zinc-400" />
</button>
@endforeach
</div>
@endif
<div class="max-h-72 overflow-y-auto rounded-lg border border-zinc-200 bg-zinc-50 p-1 dark:border-zinc-800 dark:bg-zinc-900/60">
@forelse ($this->availableUsers as $candidate)
<button
type="button"
wire:key="add-candidate-{{ $candidate->id }}"
wire:click="toggleMember({{ $candidate->id }})"
class="flex w-full items-center gap-3 rounded-md p-3 text-left transition hover:bg-white focus:outline-none focus-visible:ring-2 focus-visible:ring-accent dark:hover:bg-zinc-900"
>
<flux:avatar
circle
:name="$candidate->name"
:initials="$candidate->initials()"
/>
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-medium text-zinc-900 dark:text-zinc-100">{{ $candidate->name }}</span>
<span class="block truncate text-xs text-zinc-500 dark:text-zinc-400">{{ $candidate->email }}</span>
</span>
<span class="flex size-7 items-center justify-center rounded-full border border-zinc-200 bg-white text-zinc-500 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-300">
<flux:icon.plus class="size-4" />
</span>
</button>
@empty
<div class="flex min-h-32 items-center justify-center p-6 text-center">
<div>
<div class="mx-auto mb-3 flex size-10 items-center justify-center rounded-lg border border-dashed border-zinc-300 text-zinc-400 dark:border-zinc-700">
<flux:icon.user-plus class="size-5" />
</div>
<flux:heading size="sm">{{ __('No people available') }}</flux:heading>
<flux:text class="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
{{ __('Everyone matching your search is already in this conversation.') }}
</flux:text>
</div>
</div>
@endforelse
</div>
</div>
<div class="flex items-center justify-end gap-3 border-t border-zinc-200 pt-4 dark:border-zinc-800">
<flux:modal.close>
<flux:button type="button" variant="ghost">{{ __('Cancel') }}</flux:button>
</flux:modal.close>
<flux:button
type="submit"
variant="primary"
icon="user-plus"
wire:loading.attr="disabled"
wire:target="addMembers"
:disabled="count($selectedMemberIds) === 0"
>
{{ __('Add selected') }}
</flux:button>
</div>
</form>
</flux:modal>
</aside> </aside>

View File

@@ -1,78 +1,33 @@
<div class="flex h-full w-full flex-col"> <div class="flex h-full w-full flex-col">
<div class="shrink-0 border-b border-zinc-200 bg-white/70 p-4 backdrop-blur dark:border-zinc-800 dark:bg-zinc-950/40"> <div class="shrink-0 border-b border-zinc-200 bg-white/80 p-4 backdrop-blur dark:border-zinc-800 dark:bg-zinc-950/50">
<div class="mb-4 flex items-center justify-between gap-3"> <div class="flex items-start justify-between gap-3">
<div> <div class="min-w-0">
<flux:heading size="lg">{{ __('Inbox') }}</flux:heading> <flux:heading size="lg">{{ __('Messages') }}</flux:heading>
<flux:text class="text-sm text-zinc-500 dark:text-zinc-400"> <flux:text class="text-sm text-zinc-500 dark:text-zinc-400">
{{ trans_choice(':count conversation|:count conversations', $this->conversations->count(), ['count' => $this->conversations->count()]) }} {{ trans_choice(':count conversation|:count conversations', $this->conversations->count(), ['count' => $this->conversations->count()]) }}
</flux:text> </flux:text>
</div> </div>
<div class="flex items-center gap-2"> <flux:button
<flux:badge color="emerald" size="sm">{{ __('Live') }}</flux:badge> type="button"
variant="primary"
<flux:dropdown position="bottom" align="end"> size="sm"
<flux:profile icon="plus"
:name="auth()->user()->name" wire:click="openCreateConversation"
:initials="auth()->user()->initials()" class="shrink-0"
icon-trailing="chevron-down" >
aria-label="{{ __('Account menu') }}" {{ __('New') }}
/> </flux:button>
<flux:menu>
<div class="p-2">
<div class="flex items-center gap-3 rounded-lg bg-zinc-50 p-2 dark:bg-zinc-900">
<flux:avatar
circle
:name="auth()->user()->name"
:initials="auth()->user()->initials()"
/>
<div class="min-w-0">
<div class="truncate text-sm font-medium text-zinc-900 dark:text-zinc-100">{{ auth()->user()->name }}</div>
<div class="truncate text-xs text-zinc-500 dark:text-zinc-400">{{ auth()->user()->email }}</div>
</div>
</div>
</div>
<flux:menu.separator />
<flux:menu.item :href="route('profile.edit')" icon="user-circle" wire:navigate>
{{ __('Profile settings') }}
</flux:menu.item>
<flux:menu.item :href="route('security.edit')" icon="shield-check" wire:navigate>
{{ __('Password and 2FA') }}
</flux:menu.item>
<flux:menu.item :href="route('appearance.edit')" icon="swatch" wire:navigate>
{{ __('Appearance') }}
</flux:menu.item>
<flux:menu.separator />
<form method="POST" action="{{ route('logout') }}" class="w-full">
@csrf
<flux:menu.item
as="button"
type="submit"
icon="arrow-right-start-on-rectangle"
class="w-full cursor-pointer"
>
{{ __('Log out') }}
</flux:menu.item>
</form>
</flux:menu>
</flux:dropdown>
</div>
</div> </div>
<flux:input <div class="mt-4">
wire:model.live.debounce.300ms="search" <flux:input
icon="magnifying-glass" wire:model.live.debounce.300ms="search"
:placeholder="__('Search conversations')" icon="magnifying-glass"
aria-label="{{ __('Search conversations') }}" :placeholder="__('Search conversations')"
/> aria-label="{{ __('Search conversations') }}"
/>
</div>
</div> </div>
<div class="relative min-h-0 flex-1 overflow-y-auto p-2" role="list" aria-label="{{ __('Conversations') }}"> <div class="relative min-h-0 flex-1 overflow-y-auto p-2" role="list" aria-label="{{ __('Conversations') }}">
@@ -208,4 +163,187 @@
@endforelse @endforelse
</div> </div>
</div> </div>
<div class="shrink-0 border-t border-zinc-200 bg-white/80 p-3 backdrop-blur dark:border-zinc-800 dark:bg-zinc-950/50">
<flux:dropdown position="top" align="start">
<button
type="button"
class="flex w-full items-center gap-3 rounded-lg p-2 text-left transition hover:bg-zinc-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent dark:hover:bg-zinc-900"
aria-label="{{ __('Account menu') }}"
>
<flux:avatar
circle
:name="auth()->user()->name"
:initials="auth()->user()->initials()"
/>
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-medium text-zinc-900 dark:text-zinc-100">{{ auth()->user()->name }}</span>
<span class="block truncate text-xs text-zinc-500 dark:text-zinc-400">{{ auth()->user()->email }}</span>
</span>
<flux:icon.chevron-up-down class="size-4 text-zinc-400" />
</button>
<flux:menu>
<flux:menu.item :href="route('profile.edit')" icon="user-circle" wire:navigate>
{{ __('Profile settings') }}
</flux:menu.item>
<flux:menu.item :href="route('security.edit')" icon="shield-check" wire:navigate>
{{ __('Password and 2FA') }}
</flux:menu.item>
<flux:menu.item :href="route('appearance.edit')" icon="swatch" wire:navigate>
{{ __('Appearance') }}
</flux:menu.item>
<flux:menu.separator />
<form method="POST" action="{{ route('logout') }}" class="w-full">
@csrf
<flux:menu.item
as="button"
type="submit"
icon="arrow-right-start-on-rectangle"
class="w-full cursor-pointer"
>
{{ __('Log out') }}
</flux:menu.item>
</form>
</flux:menu>
</flux:dropdown>
</div>
<flux:modal wire:model="showCreateConversationModal" class="w-full max-w-2xl">
<form wire:submit="createConversation" class="space-y-6">
<div class="flex items-start justify-between gap-4">
<div>
<flux:heading size="lg">{{ __('New conversation') }}</flux:heading>
<flux:text class="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
{{ __('Start a direct message or create a group with your team.') }}
</flux:text>
</div>
<div class="rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-xs font-medium text-zinc-500 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-400">
{{ trans_choice(':count selected|:count selected', count($selectedMemberIds), ['count' => count($selectedMemberIds)]) }}
</div>
</div>
<flux:radio.group wire:model.live="createType" variant="segmented" class="grid grid-cols-2 gap-2">
<flux:radio value="{{ \App\Models\Conversation::TypeDirect }}" icon="user">
{{ __('Direct') }}
</flux:radio>
<flux:radio value="{{ \App\Models\Conversation::TypeGroup }}" icon="user-group">
{{ __('Group') }}
</flux:radio>
</flux:radio.group>
@if ($createType === \App\Models\Conversation::TypeGroup)
<div class="grid gap-4 sm:grid-cols-2">
<flux:input
wire:model="groupName"
:label="__('Group name')"
:placeholder="__('Product Launch')"
autocomplete="off"
/>
<flux:input
wire:model="groupDescription"
:label="__('Description')"
:placeholder="__('Optional context')"
autocomplete="off"
/>
</div>
@endif
<div class="space-y-3">
<flux:input
wire:model.live.debounce.250ms="memberSearch"
icon="magnifying-glass"
:label="__('People')"
:placeholder="__('Search by name or email')"
autocomplete="off"
/>
@error('selectedMemberIds')
<flux:text class="text-sm text-red-600 dark:text-red-400">{{ $message }}</flux:text>
@enderror
@if ($this->selectedMembers->isNotEmpty())
<div class="flex flex-wrap gap-2">
@foreach ($this->selectedMembers as $member)
<button
type="button"
wire:key="create-selected-member-{{ $member->id }}"
wire:click="removeSelectedMember({{ $member->id }})"
class="inline-flex items-center gap-2 rounded-full border border-zinc-200 bg-white py-1 pe-2 ps-1 text-sm text-zinc-700 shadow-sm transition hover:border-zinc-300 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:border-zinc-600"
>
<span class="flex size-6 items-center justify-center rounded-full bg-zinc-100 text-[10px] font-semibold dark:bg-zinc-800">
{{ $member->initials() }}
</span>
<span>{{ $member->name }}</span>
<flux:icon.x-mark class="size-3 text-zinc-400" />
</button>
@endforeach
</div>
@endif
<div class="max-h-72 overflow-y-auto rounded-lg border border-zinc-200 bg-zinc-50 p-1 dark:border-zinc-800 dark:bg-zinc-900/60">
@forelse ($this->candidateUsers as $candidate)
<button
type="button"
wire:key="create-candidate-{{ $candidate->id }}"
wire:click="toggleMember({{ $candidate->id }})"
class="flex w-full items-center gap-3 rounded-md p-3 text-left transition hover:bg-white focus:outline-none focus-visible:ring-2 focus-visible:ring-accent dark:hover:bg-zinc-900"
>
<flux:avatar
circle
:name="$candidate->name"
:initials="$candidate->initials()"
/>
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-medium text-zinc-900 dark:text-zinc-100">{{ $candidate->name }}</span>
<span class="block truncate text-xs text-zinc-500 dark:text-zinc-400">{{ $candidate->email }}</span>
</span>
<span class="flex size-7 items-center justify-center rounded-full border border-zinc-200 bg-white text-zinc-500 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-300">
<flux:icon.plus class="size-4" />
</span>
</button>
@empty
<div class="flex min-h-32 items-center justify-center p-6 text-center">
<div>
<div class="mx-auto mb-3 flex size-10 items-center justify-center rounded-lg border border-dashed border-zinc-300 text-zinc-400 dark:border-zinc-700">
<flux:icon.user-plus class="size-5" />
</div>
<flux:heading size="sm">{{ __('No people found') }}</flux:heading>
<flux:text class="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
{{ __('Try a different name or email address.') }}
</flux:text>
</div>
</div>
@endforelse
</div>
</div>
<div class="flex items-center justify-end gap-3 border-t border-zinc-200 pt-4 dark:border-zinc-800">
<flux:modal.close>
<flux:button type="button" variant="ghost">{{ __('Cancel') }}</flux:button>
</flux:modal.close>
<flux:button
type="submit"
variant="primary"
icon="chat-bubble-left-right"
wire:loading.attr="disabled"
wire:target="createConversation"
:disabled="count($selectedMemberIds) === 0"
>
{{ $createType === \App\Models\Conversation::TypeGroup ? __('Create group') : __('Start chat') }}
</flux:button>
</div>
</form>
</flux:modal>
</div> </div>

View File

@@ -20,7 +20,7 @@ test('authenticated users can visit the chat dashboard', function () {
$this->actingAs($user) $this->actingAs($user)
->get(route('dashboard')) ->get(route('dashboard'))
->assertOk() ->assertOk()
->assertSee('Inbox') ->assertSee('Messages')
->assertSee('Profile settings') ->assertSee('Profile settings')
->assertSee('Password and 2FA') ->assertSee('Password and 2FA')
->assertDontSee('Repository') ->assertDontSee('Repository')
@@ -41,9 +41,9 @@ test('conversation list only shows conversations the user participates in', func
ConversationParticipant::factory()->for($visibleConversation)->for($teammate)->create(); ConversationParticipant::factory()->for($visibleConversation)->for($teammate)->create();
$hiddenConversation = Conversation::factory() $hiddenConversation = Conversation::factory()
->direct() ->group()
->for($outsider, 'creator') ->for($outsider, 'creator')
->create(); ->create(['name' => 'Hidden Group']);
ConversationParticipant::factory()->for($hiddenConversation)->for($outsider)->create(); ConversationParticipant::factory()->for($hiddenConversation)->for($outsider)->create();
@@ -52,7 +52,53 @@ test('conversation list only shows conversations the user participates in', func
Livewire::test(ConversationList::class) Livewire::test(ConversationList::class)
->assertSee('Visible Teammate') ->assertSee('Visible Teammate')
->assertSee('Opening') ->assertSee('Opening')
->assertDontSee('Hidden Teammate'); ->assertDontSee('Hidden Group');
});
test('users can create direct conversations', function () {
$user = User::factory()->create();
$teammate = User::factory()->create(['name' => 'Direct Partner']);
$this->actingAs($user);
Livewire::test(ConversationList::class)
->call('openCreateConversation')
->call('toggleMember', $teammate->id)
->call('createConversation')
->assertHasNoErrors();
$conversation = Conversation::query()
->where('type', Conversation::TypeDirect)
->whereHas('participants', fn ($query) => $query->where('user_id', $user->id))
->whereHas('participants', fn ($query) => $query->where('user_id', $teammate->id))
->first();
expect($conversation)->not->toBeNull();
expect($conversation->participants()->count())->toBe(2);
});
test('users can create group conversations with members', function () {
$user = User::factory()->create();
$firstMember = User::factory()->create(['name' => 'Launch Lead']);
$secondMember = User::factory()->create(['name' => 'Design Lead']);
$this->actingAs($user);
Livewire::test(ConversationList::class)
->set('createType', Conversation::TypeGroup)
->set('groupName', 'Launch Room')
->call('toggleMember', $firstMember->id)
->call('toggleMember', $secondMember->id)
->call('createConversation')
->assertHasNoErrors();
$conversation = Conversation::query()
->where('type', Conversation::TypeGroup)
->where('name', 'Launch Room')
->first();
expect($conversation)->not->toBeNull();
expect($conversation->participants()->count())->toBe(3);
}); });
test('participants can send messages', function () { test('participants can send messages', function () {
@@ -78,6 +124,34 @@ test('participants can send messages', function () {
->exists())->toBeTrue(); ->exists())->toBeTrue();
}); });
test('participants can add people to a direct conversation', function () {
$user = User::factory()->create();
$teammate = User::factory()->create(['name' => 'Mina Partner']);
$newMember = User::factory()->create(['name' => 'Nima Added']);
$conversation = Conversation::factory()
->direct()
->for($user, 'creator')
->create();
ConversationParticipant::factory()->for($conversation)->for($user)->create();
ConversationParticipant::factory()->for($conversation)->for($teammate)->create();
$this->actingAs($user);
Livewire::test(ConversationDetailsPanel::class, ['conversationId' => $conversation->id])
->call('openAddMembers')
->set('groupName', 'Project Room')
->call('toggleMember', $newMember->id)
->call('addMembers')
->assertHasNoErrors();
$conversation->refresh();
expect($conversation->type)->toBe(Conversation::TypeGroup);
expect($conversation->name)->toBe('Project Room');
expect($conversation->participants()->where('user_id', $newMember->id)->exists())->toBeTrue();
});
test('selected conversations render the stream header and details', function () { test('selected conversations render the stream header and details', function () {
$user = User::factory()->create(); $user = User::factory()->create();
$teammate = User::factory()->create(['name' => 'Mina Partner']); $teammate = User::factory()->create(['name' => 'Mina Partner']);