Files
2026-11-04 11:10:05 -08:00

662 lines
25 KiB
PHP

<?php
use App\Models\Folder;
use App\Models\Todo;
use App\TodoStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Kanban')] class extends Component
{
#[Locked]
public ?int $editingTodoId = null;
public string $search = '';
public ?int $folderId = null;
public bool $showTodoForm = false;
public string $description = '';
public string $todoStatus = 'open';
public ?string $dueDate = null;
public string $notes = '';
public ?int $formFolderId = null;
#[Locked]
public ?int $confirmingTodoDelete = null;
public function mount(): void
{
$folderId = request()->query('folder');
if ($folderId === null || $folderId === '') {
return;
}
$folderId = (int) $folderId;
if (Folder::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->whereKey($folderId)->exists()) {
$this->folderId = $folderId;
}
}
public function updatedSearch(): void
{
unset($this->columns);
}
public function updatedFolderId(): void
{
$this->folderId = $this->folderId === null || $this->folderId === '' ? null : (int) $this->folderId;
unset($this->columns, $this->filterFolderScope);
}
public function openCreateForm(?string $status = null): void
{
$this->reset('editingTodoId', 'description', 'todoStatus', 'dueDate', 'notes', 'formFolderId');
$this->resetErrorBag();
if ($status !== null && TodoStatus::tryFrom($status) !== null) {
$this->todoStatus = $status;
}
if ($this->folderId !== null) {
$node = $this->folderTree->first(fn (array $node): bool => $node['folder']->id === $this->folderId);
if ($node !== null && auth()->user()->can('create', [Todo::class, $node['folder']])) {
$this->formFolderId = $this->folderId;
}
}
$this->showTodoForm = true;
}
public function openEditForm(int $todoId): void
{
$todo = $this->todoForAction($todoId, 'update');
$this->editingTodoId = $todo->id;
$this->description = $todo->description;
$this->todoStatus = $todo->status->value;
$this->dueDate = $todo->due_date?->format('Y-m-d') ?? '';
$this->notes = $todo->notes ?? '';
$this->formFolderId = $todo->folder_id;
$this->resetErrorBag();
$this->showTodoForm = true;
}
public function saveTodo(): void
{
$validated = $this->validate([
'description' => ['required', 'string', 'max:255'],
'todoStatus' => ['required', Rule::enum(TodoStatus::class)],
'dueDate' => ['nullable', 'date'],
'notes' => ['nullable', 'string', 'max:'.auth()->user()->notesLimit()],
'formFolderId' => ['required', 'integer', Rule::exists('folders', 'id')->whereIn(
'id',
Folder::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->select('folders.id')
)],
]);
$folder = Folder::query()
->visibleTo(auth()->id(), $this->activeWorkspaceId())
->findOrFail($validated['formFolderId']);
abort_unless(auth()->user()->can('create', [Todo::class, $folder]), 403);
$data = [
'folder_id' => $folder->id,
'description' => $validated['description'],
'status' => TodoStatus::from($validated['todoStatus']),
'due_date' => filled($validated['dueDate']) ? Carbon::parse($validated['dueDate']) : null,
'notes' => filled($validated['notes']) ? $validated['notes'] : null,
];
if ($this->editingTodoId !== null) {
$this->todoForAction($this->editingTodoId, 'update')->update($data);
} else {
Todo::create($data + [
'user_id' => auth()->id(),
'position' => Todo::nextPositionFor($folder),
]);
}
$this->reset('showTodoForm', 'editingTodoId', 'description', 'todoStatus', 'dueDate', 'notes', 'formFolderId');
unset($this->columns);
}
public function toggleComplete(int $todoId): void
{
$todo = $this->todoForAction($todoId, 'markComplete');
$data = ['completed_at' => $todo->completed_at === null ? now() : null];
if ($todo->completed_at === null && in_array($todo->status, [TodoStatus::Open, TodoStatus::InProgress], true)) {
$data['status'] = TodoStatus::Completed;
} elseif ($todo->completed_at !== null && $todo->status === TodoStatus::Completed) {
$data['status'] = TodoStatus::Open;
}
$todo->update($data);
unset($this->columns);
}
public function confirmTodoDelete(int $todoId): void
{
$this->todoForAction($todoId, 'delete');
$this->confirmingTodoDelete = $todoId;
$this->modal('confirm-todo-delete')->show();
}
public function deleteTodo(): void
{
$this->todoForAction($this->confirmingTodoDelete ?? 0, 'delete')->delete();
$this->confirmingTodoDelete = null;
$this->modal('confirm-todo-delete')->close();
unset($this->columns);
}
public function resetFilters(): void
{
$this->reset('search', 'folderId');
unset($this->columns, $this->filterFolderScope);
}
public function moveTodo(int $todoId, int $position, string $columnId): void
{
if ($columnId !== 'completed' && TodoStatus::tryFrom($columnId) === null) {
return;
}
$todo = $this->todoForAction($todoId, 'update');
if ($columnId === 'completed') {
$data = ['completed_at' => $todo->completed_at ?? now()];
if ($todo->completed_at === null && in_array($todo->status, [TodoStatus::Open, TodoStatus::InProgress], true)) {
$data['status'] = TodoStatus::Completed;
}
$todo->update($data);
} else {
$todo->update([
'status' => TodoStatus::from($columnId),
'completed_at' => null,
]);
}
$this->reorderColumn($todo->id, $position, $columnId);
}
/**
* Move a todo to the given index of a board column. The reordered todos are
* written back into the slots they already occupy in the user's full
* priority order, so reordering under an active filter permutes the visible
* todos without renumbering them from zero and colliding with the todos the
* filter hides.
*/
private function reorderColumn(int $todoId, int $newIndex, string $columnId): void
{
$visibleIds = $this->columnTodoIds($columnId);
$currentIndex = array_search($todoId, $visibleIds, true);
if ($currentIndex === false) {
return;
}
$newIndex = max(0, min($newIndex, count($visibleIds) - 1));
if ($newIndex === $currentIndex) {
unset($this->columns);
return;
}
$visibleOrder = $visibleIds;
unset($visibleOrder[$currentIndex]);
array_splice($visibleOrder, $newIndex, 0, $todoId);
$ids = Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->priority()->pluck('id')->all();
$slots = array_keys(array_intersect($ids, $visibleIds));
foreach ($slots as $visibleSlot => $slot) {
$ids[$slot] = $visibleOrder[$visibleSlot];
}
foreach ($ids as $position => $id) {
Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->whereKey($id)->update(['position' => $position]);
}
unset($this->columns);
}
/**
* @return list<int>
*/
private function columnTodoIds(string $columnId): array
{
$query = $this->filteredTodoQuery()->priority();
if ($columnId === 'completed') {
$query->where(function (Builder $query): void {
$query->whereNotNull('completed_at')->orWhere('status', TodoStatus::Completed->value);
});
} else {
$query->where('status', $columnId)->whereNull('completed_at');
}
return $query->pluck('id')->all();
}
/**
* @return Builder<Todo>
*/
private function filteredTodoQuery(): Builder
{
return Todo::query()
->visibleTo(auth()->id(), $this->activeWorkspaceId())
->when(
$this->search !== '',
fn (Builder $query) => $query->where('description', 'like', '%'.$this->search.'%')
)
->when(
$this->folderId !== null,
fn (Builder $query) => $query->whereIn('folder_id', $this->filterFolderScope)
);
}
private function descendantIds(int $folderId): array
{
$ids = [$folderId];
foreach ($this->folderTree->where('folder.parent_id', $folderId)->values() as $child) {
$ids = [...$ids, ...$this->descendantIds($child['folder']->id)];
}
return $ids;
}
private function todoForAction(int $todoId, string $ability): Todo
{
$todo = Todo::query()
->visibleTo(auth()->id(), $this->activeWorkspaceId())
->with('folder')
->findOrFail($todoId);
abort_unless(auth()->user()->can($ability, $todo), 403);
return $todo;
}
private function activeWorkspaceId(): int
{
return (int) auth()->user()->current_organization_id;
}
#[Computed]
public function folderTree(): Collection
{
return Folder::treeForVisibleTo(auth()->id(), $this->activeWorkspaceId());
}
#[Computed]
public function filterFolderScope(): array
{
if ($this->folderId === null) {
return [];
}
return $this->descendantIds($this->folderId);
}
#[Computed]
public function hasActiveFilters(): bool
{
return $this->search !== '' || $this->folderId !== null;
}
#[Computed]
public function canCreateTodos(): bool
{
return $this->folderTree->contains(
fn (array $node): bool => auth()->user()->can('create', [Todo::class, $node['folder']])
);
}
/**
* @return list<array{id: string, label: string, color: string, todos: Collection<int, Todo>}>
*/
#[Computed]
public function columns(): array
{
$todos = $this->filteredTodoQuery()
->with('folder.parent')
->priority()
->get();
$columns = collect([
TodoStatus::Open,
TodoStatus::InProgress,
TodoStatus::OnHold,
TodoStatus::Blocked,
TodoStatus::Cancelled,
TodoStatus::Deferred,
])->map(fn (TodoStatus $status): array => [
'id' => $status->value,
'label' => $status->label(),
'color' => $status->badgeColor(),
'todos' => $todos
->filter(fn (Todo $todo): bool => $todo->status === $status && $todo->completed_at === null)
->values(),
]);
$columns->push([
'id' => 'completed',
'label' => TodoStatus::Completed->label(),
'color' => TodoStatus::Completed->badgeColor(),
'todos' => $todos
->filter(fn (Todo $todo): bool => $todo->completed_at !== null || $todo->status === TodoStatus::Completed)
->values(),
]);
return $columns->all();
}
}; ?>
<div class="flex h-full w-full flex-1 flex-col gap-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<div>
<flux:heading size="xl">{{ __('Kanban') }}</flux:heading>
<flux:text class="mt-1">{{ __('Drag todos between columns to update their status.') }}</flux:text>
</div>
<div class="flex flex-wrap items-center gap-2">
<flux:button variant="ghost" icon="list-bullet" :href="route('todos')" wire:navigate>
{{ __('List view') }}
</flux:button>
@if ($this->canCreateTodos)
<flux:button
variant="primary"
wire:click="openCreateForm"
data-test="add-todo-button"
>
{{ __('New Todo') }}
</flux:button>
@endif
</div>
</div>
@if (! $this->canCreateTodos)
<flux:callout variant="warning" icon="folder">
<x-slot name="text">
{{ __('Create a folder you can add todos to before using the board.') }}
</x-slot>
<x-slot name="actions">
<flux:button size="sm" :href="route('folders')" wire:navigate variant="primary">
{{ __('Manage folders') }}
</flux:button>
</x-slot>
</flux:callout>
@endif
<div class="flex flex-wrap items-center gap-2">
<flux:input
size="sm"
type="search"
icon="magnifying-glass"
wire:model.live.debounce.300ms="search"
placeholder="{{ __('Search todos…') }}"
class="w-full sm:w-64"
data-test="search-input"
/>
<flux:select size="sm" wire:model.live="folderId" class="w-full sm:w-56" data-test="folder-filter">
<flux:select.option value="">{{ __('All folders') }}</flux:select.option>
@foreach ($this->folderTree as $node)
<flux:select.option :value="$node['folder']->id">{{ str_repeat('— ', $node['depth']) }}{{ $node['folder']->name }}</flux:select.option>
@endforeach
</flux:select>
@if ($this->hasActiveFilters)
<flux:button size="sm" variant="danger" icon="x-mark" wire:click="resetFilters" class="shrink-0">
{{ __('Clear') }}
</flux:button>
@endif
</div>
<div class="flex gap-4 overflow-x-auto pb-4" data-test="kanban-board">
@foreach ($this->columns as $column)
<section
wire:key="kanban-column-{{ $column['id'] }}"
class="flex w-72 shrink-0 flex-col gap-3 rounded-xl border border-zinc-200 bg-zinc-50/80 p-3 dark:border-zinc-700 dark:bg-zinc-900/60"
data-test="kanban-column-{{ $column['id'] }}"
>
<div class="flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<flux:badge size="sm" :color="$column['color']">{{ $column['label'] }}</flux:badge>
<span class="text-xs font-medium text-zinc-500" data-test="kanban-count-{{ $column['id'] }}">
{{ $column['todos']->count() }}
</span>
</div>
@if ($this->canCreateTodos)
<flux:button
size="sm"
variant="ghost"
icon="plus"
:title="__('Add todo to :status', ['status' => $column['label']])"
wire:click="openCreateForm('{{ $column['id'] }}')"
data-test="kanban-add-{{ $column['id'] }}"
/>
@endif
</div>
<div
wire:sort="moveTodo"
wire:sort:group="kanban"
wire:sort:group-id="{{ $column['id'] }}"
class="flex min-h-24 flex-col gap-2"
data-test="kanban-list-{{ $column['id'] }}"
>
@forelse ($column['todos'] as $todo)
@php
$canUpdateTodo = auth()->user()->can('update', $todo);
$dueColor = $todo->completed_at !== null
? 'zinc'
: ($todo->due_date?->isPast() ? 'red' : ($todo->due_date?->isToday() ? 'amber' : 'zinc'));
@endphp
<div
wire:sort:item="{{ $todo->id }}"
@if (! $canUpdateTodo) wire:sort:ignore @endif
wire:key="kanban-card-{{ $todo->id }}"
data-test="kanban-card-{{ $todo->id }}"
@class([
'group cursor-grab rounded-lg border border-zinc-200 bg-white p-3 shadow-xs transition hover:border-zinc-300 active:cursor-grabbing dark:border-zinc-700 dark:bg-zinc-800 dark:hover:border-zinc-600',
'opacity-80' => $todo->completed_at !== null,
])
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0 flex-1">
<p @class([
'text-sm font-medium text-zinc-900 dark:text-zinc-100',
'line-through text-zinc-400 dark:text-zinc-500' => $todo->completed_at !== null,
])>
{{ $todo->description }}
</p>
@if ($todo->notes)
<flux:text size="sm" class="mt-1 line-clamp-2 text-zinc-500">{{ $todo->notes }}</flux:text>
@endif
</div>
@if ($canUpdateTodo)
<div wire:sort:ignore class="shrink-0">
<flux:dropdown position="bottom" align="end">
<flux:button
size="sm"
variant="ghost"
icon="ellipsis-horizontal"
:title="__('Todo actions')"
data-test="kanban-actions-{{ $todo->id }}"
/>
<flux:menu>
<flux:menu.item icon="pencil-square" wire:click="openEditForm({{ $todo->id }})">
{{ __('Edit') }}
</flux:menu.item>
<flux:menu.item icon="trash" variant="danger" wire:click="confirmTodoDelete({{ $todo->id }})">
{{ __('Delete') }}
</flux:menu.item>
</flux:menu>
</flux:dropdown>
</div>
@endif
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
@can('markComplete', $todo)
<div wire:sort:ignore>
<flux:checkbox
:checked="$todo->completed_at !== null"
:title="$todo->completed_at ? __('Mark as not done') : __('Mark as done')"
wire:click="toggleComplete({{ $todo->id }})"
data-test="kanban-toggle-complete-{{ $todo->id }}"
/>
</div>
@endcan
<div class="flex min-w-0 items-center gap-1.5 text-xs text-zinc-500">
<x-folder-dot :color="$todo->folder?->color" />
<span class="truncate">{{ $todo->folder?->parent?->name }}@if ($todo->folder?->parent) / @endif{{ $todo->folder?->name }}</span>
</div>
@if ($column['id'] === 'completed' && $todo->status !== TodoStatus::Completed)
<flux:badge size="sm" :color="$todo->status->badgeColor()">
{{ $todo->status->label() }}
</flux:badge>
@endif
@if ($todo->due_date)
<flux:badge size="sm" :color="$dueColor">
{{ $todo->due_date->isToday() ? __('Today') : $todo->due_date->format('M j') }}
</flux:badge>
@endif
</div>
</div>
@empty
<div
wire:sort:ignore
class="flex min-h-24 items-center justify-center rounded-lg border border-dashed border-zinc-300 text-xs text-zinc-400 dark:border-zinc-700"
>
{{ __('No todos') }}
</div>
@endforelse
</div>
</section>
@endforeach
</div>
<flux:modal wire:model.self="showTodoForm" class="md:w-xl">
<form wire:submit="saveTodo" class="space-y-6">
<div>
<flux:heading size="lg">{{ $editingTodoId === null ? __('New todo') : __('Edit todo') }}</flux:heading>
<flux:text class="mt-2">{{ __('Add a task with a description and folder. A due date is optional.') }}</flux:text>
</div>
<flux:field>
<flux:label>{{ __('Description') }}</flux:label>
<flux:input
wire:model="description"
type="text"
autofocus
placeholder="{{ __('What needs to be done?') }}"
data-test="description-input"
/>
<flux:error name="description" />
</flux:field>
<flux:field>
<flux:label>{{ __('Status') }}</flux:label>
<flux:select wire:model="todoStatus" data-test="status-select">
@foreach (TodoStatus::cases() as $status)
<flux:select.option :value="$status->value">{{ $status->label() }}</flux:select.option>
@endforeach
</flux:select>
<flux:error name="todoStatus" />
</flux:field>
<flux:field>
<flux:label>{{ __('Due date') }}</flux:label>
<flux:input wire:model="dueDate" type="date" data-test="due-date-input" />
<flux:error name="dueDate" />
</flux:field>
<flux:field>
<flux:label>{{ __('Notes') }}</flux:label>
<flux:textarea
wire:model="notes"
rows="3"
placeholder="{{ __('Add any extra details…') }}"
data-test="notes-input"
/>
<flux:error name="notes" />
</flux:field>
<flux:field>
<flux:label>{{ __('Folder') }}</flux:label>
<flux:select wire:model="formFolderId" data-test="folder-select">
<flux:select.option value="">{{ __('Select a folder…') }}</flux:select.option>
@foreach ($this->folderTree as $node)
<flux:select.option :value="$node['folder']->id">{{ str_repeat('— ', $node['depth']) }}{{ $node['folder']->name }}</flux:select.option>
@endforeach
</flux:select>
<flux:error name="formFolderId" />
</flux:field>
<div class="flex justify-end gap-3">
<flux:modal.close>
<flux:button variant="ghost">{{ __('Cancel') }}</flux:button>
</flux:modal.close>
<flux:button type="submit" variant="primary">{{ __('Save todo') }}</flux:button>
</div>
</form>
</flux:modal>
<flux:modal name="confirm-todo-delete" class="md:w-lg">
<div class="space-y-6">
<div>
<flux:heading size="lg">{{ __('Delete todo?') }}</flux:heading>
<flux:text class="mt-2">{{ __('This todo will be permanently deleted. This action cannot be undone.') }}</flux:text>
</div>
<div class="flex justify-end gap-3">
<flux:modal.close>
<flux:button variant="ghost">{{ __('Cancel') }}</flux:button>
</flux:modal.close>
<flux:button variant="danger" wire:click="deleteTodo">{{ __('Delete') }}</flux:button>
</div>
</div>
</flux:modal>
</div>