Improve recordings list sorting and live show-page status updates.

Add sortable columns with a fixed status width, and keep the show page in sync via Echo, polling, and Alpine hydrate while transcription runs.
This commit is contained in:
ben
2026-08-12 21:27:03 +02:00
parent 5f0f61995c
commit 8a66cf6f63
7 changed files with 344 additions and 67 deletions
+70 -1
View File
@@ -5,6 +5,8 @@ namespace App\Livewire\Recordings;
use App\Models\Recording; use App\Models\Recording;
use Flux\Flux; use Flux\Flux;
use Illuminate\Contracts\View\View; use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Layout; use Livewire\Attributes\Layout;
@@ -25,9 +27,26 @@ class Index extends Component
#[Url(as: 'q', history: true)] #[Url(as: 'q', history: true)]
public string $search = ''; public string $search = '';
#[Url(as: 'sort', history: true)]
public string $sortBy = 'uploaded';
#[Url(as: 'dir', history: true)]
public string $sortDirection = 'desc';
/**
* @var array<string, string>
*/
private const SORTABLE = [
'title' => 'title',
'duration' => 'duration_seconds',
'status' => 'transcription_status',
'uploaded' => 'created_at',
];
public function mount(): void public function mount(): void
{ {
$this->userId = (int) Auth::id(); $this->userId = (int) Auth::id();
$this->normalizeSort();
} }
public function updatedSearch(): void public function updatedSearch(): void
@@ -35,6 +54,22 @@ class Index extends Component
$this->resetPage(); $this->resetPage();
} }
public function sort(string $column): void
{
if ($column !== 'words' && ! array_key_exists($column, self::SORTABLE)) {
return;
}
if ($this->sortBy === $column) {
$this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
} else {
$this->sortBy = $column;
$this->sortDirection = $column === 'uploaded' ? 'desc' : 'asc';
}
$this->resetPage();
}
/** /**
* Re-render when any of this user's recordings broadcast a status change. * Re-render when any of this user's recordings broadcast a status change.
*/ */
@@ -127,7 +162,9 @@ class Index extends Component
$totalCount = $user->recordings()->count(); $totalCount = $user->recordings()->count();
$query = $user->recordings()->latest(); $this->normalizeSort();
$query = $user->recordings();
$search = trim($this->search); $search = trim($this->search);
@@ -135,6 +172,8 @@ class Index extends Component
$query->search($search); $query->search($search);
} }
$this->applySort($query);
$recordings = $query->paginate(20); $recordings = $query->paginate(20);
$pendingCount = $user->recordings() $pendingCount = $user->recordings()
@@ -155,4 +194,34 @@ class Index extends Component
'totalCount' => $totalCount, 'totalCount' => $totalCount,
]); ]);
} }
private function normalizeSort(): void
{
if ($this->sortBy !== 'words' && ! array_key_exists($this->sortBy, self::SORTABLE)) {
$this->sortBy = 'uploaded';
}
if (! in_array($this->sortDirection, ['asc', 'desc'], true)) {
$this->sortDirection = 'desc';
}
}
/**
* @param Builder<Recording>|HasMany<Recording, User> $query
*/
private function applySort(Builder|HasMany $query): void
{
$direction = $this->sortDirection === 'asc' ? 'asc' : 'desc';
if ($this->sortBy === 'words') {
$query->orderByRaw(
'CASE WHEN transcript IS NULL OR TRIM(transcript) = ? THEN 0 ELSE LENGTH(TRIM(transcript)) - LENGTH(REPLACE(TRIM(transcript), ?, ?)) + 1 END '.$direction,
['', ' ', ''],
);
} else {
$query->orderBy(self::SORTABLE[$this->sortBy], $direction);
}
$query->orderByDesc('id');
}
} }
+23
View File
@@ -7,6 +7,7 @@ use Flux\Flux;
use Illuminate\Contracts\View\View; use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Layout; use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component; use Livewire\Component;
#[Layout('layouts.app')] #[Layout('layouts.app')]
@@ -14,6 +15,8 @@ class Show extends Component
{ {
public Recording $recording; public Recording $recording;
public int $userId;
public function mount(Recording $recording): void public function mount(Recording $recording): void
{ {
Gate::authorize('view', $recording); Gate::authorize('view', $recording);
@@ -22,6 +25,22 @@ class Show extends Component
$recording->refresh(); $recording->refresh();
$this->recording = $recording; $this->recording = $recording;
$this->userId = (int) $recording->user_id;
}
/**
* Re-render when this recording broadcasts a status change (same channel as the index).
*
* @param array<string, mixed> $event
*/
#[On('echo-private:user.{userId}.recordings,.RecordingTranscriptionUpdated')]
public function onTranscriptionUpdated(array $event = []): void
{
if (isset($event['id']) && (int) $event['id'] !== (int) $this->recording->id) {
return;
}
$this->recording->refresh();
} }
public function startTranscription(): void public function startTranscription(): void
@@ -64,6 +83,10 @@ class Show extends Component
public function render(): View public function render(): View
{ {
if ($this->recording->isTranscribing()) {
$this->recording->refresh();
}
return view('livewire.recordings.show') return view('livewire.recordings.show')
->title($this->recording->title); ->title($this->recording->title);
} }
+39 -9
View File
@@ -66,12 +66,16 @@ function subscribeToRecording(recordingId, handler) {
channel.listen('.RecordingTranscriptionUpdated', handler); channel.listen('.RecordingTranscriptionUpdated', handler);
return () => { return () => {
window.Echo.leave(channelName); // Prefer stopListening over leave() so a remount does not drop other subscribers.
if (typeof channel.stopListening === 'function') {
channel.stopListening('.RecordingTranscriptionUpdated');
}
}; };
} }
/** /**
* Show-page Alpine component: Echo push + local elapsed tick + optional status hydrate. * Show-page Alpine component: Echo push + local elapsed tick + optional status hydrate.
* Livewire also listens on the user recordings channel and polls while active.
*/ */
export function transcriptionMonitor({ statusUrl, initial }) { export function transcriptionMonitor({ statusUrl, initial }) {
return { return {
@@ -82,6 +86,7 @@ export function transcriptionMonitor({ statusUrl, initial }) {
}, },
pollError: null, pollError: null,
tickTimer: null, tickTimer: null,
hydrateTimer: null,
leaveChannel: null, leaveChannel: null,
get badgeColor() { get badgeColor() {
@@ -108,11 +113,13 @@ export function transcriptionMonitor({ statusUrl, initial }) {
if (this.status.is_active) { if (this.status.is_active) {
this.beginTick(); this.beginTick();
this.hydrateOnce(); this.hydrateOnce();
this.beginHydratePoll();
} }
}, },
destroy() { destroy() {
this.stopTick(); this.stopTick();
this.stopHydratePoll();
if (this.leaveChannel) { if (this.leaveChannel) {
this.leaveChannel(); this.leaveChannel();
@@ -131,12 +138,14 @@ export function transcriptionMonitor({ statusUrl, initial }) {
if (this.status.is_active) { if (this.status.is_active) {
this.beginTick(); this.beginTick();
this.beginHydratePoll();
} else { } else {
this.stopTick(); this.stopTick();
this.stopHydratePoll();
} }
if (wasActive && !this.status.is_active if (wasActive && ! this.status.is_active
&& !this.status.has_transcript && ! this.status.has_transcript
&& this.status.status !== 'failed' && this.status.status !== 'failed'
&& this.status.status !== 'cancelled') { && this.status.status !== 'cancelled') {
window.location.reload(); window.location.reload();
@@ -158,26 +167,47 @@ export function transcriptionMonitor({ statusUrl, initial }) {
} }
}, },
tickElapsed() { beginHydratePoll() {
if (!this.status.is_active || this.status.elapsed_seconds == null) { if (this.hydrateTimer || ! this.statusUrl) {
return; return;
} }
this.status.elapsed_seconds += 1; this.hydrateTimer = setInterval(() => this.hydrateOnce(), 2000);
this.status.elapsed_human = formatElapsed(this.status.elapsed_seconds); },
stopHydratePoll() {
if (this.hydrateTimer) {
clearInterval(this.hydrateTimer);
this.hydrateTimer = null;
}
},
tickElapsed() {
if (! this.status.is_active || this.status.elapsed_seconds == null) {
return;
}
const next = this.status.elapsed_seconds + 1;
this.status = {
...this.status,
elapsed_seconds: next,
elapsed_human: formatElapsed(next),
};
}, },
async hydrateOnce() { async hydrateOnce() {
if (!this.statusUrl) { if (! this.statusUrl) {
return; return;
} }
try { try {
const response = await fetch(this.statusUrl, { const response = await fetch(this.statusUrl, {
headers: { Accept: 'application/json' }, headers: { Accept: 'application/json' },
credentials: 'same-origin',
}); });
if (!response.ok) { if (! response.ok) {
throw new Error('Status request failed (' + response.status + ')'); throw new Error('Status request failed (' + response.status + ')');
} }
@@ -92,39 +92,53 @@
<flux:table :paginate="$recordings"> <flux:table :paginate="$recordings">
<flux:table.columns> <flux:table.columns>
<flux:table.column class="w-12"></flux:table.column> <flux:table.column
<flux:table.column>Title</flux:table.column> sortable
<flux:table.column>Duration</flux:table.column> :sorted="$sortBy === 'title'"
<flux:table.column>Words</flux:table.column> :direction="$sortDirection"
<flux:table.column>Status</flux:table.column> wire:click="sort('title')"
<flux:table.column>Uploaded</flux:table.column> >
Title
</flux:table.column>
<flux:table.column
sortable
:sorted="$sortBy === 'duration'"
:direction="$sortDirection"
wire:click="sort('duration')"
>
Duration
</flux:table.column>
<flux:table.column
sortable
:sorted="$sortBy === 'words'"
:direction="$sortDirection"
wire:click="sort('words')"
>
Words
</flux:table.column>
<flux:table.column
class="w-36"
sortable
:sorted="$sortBy === 'status'"
:direction="$sortDirection"
wire:click="sort('status')"
>
Status
</flux:table.column>
<flux:table.column
sortable
:sorted="$sortBy === 'uploaded'"
:direction="$sortDirection"
wire:click="sort('uploaded')"
>
Uploaded
</flux:table.column>
<flux:table.column class="w-24"></flux:table.column> <flux:table.column class="w-24"></flux:table.column>
</flux:table.columns> </flux:table.columns>
<flux:table.rows> <flux:table.rows>
@foreach ($recordings as $recording) @foreach ($recordings as $recording)
<flux:table.row wire:key="recording-{{ $recording->id }}-{{ $recording->transcription_status }}-{{ $recording->transcription_percent }}"> <flux:table.row wire:key="recording-{{ $recording->id }}-{{ $recording->transcription_status }}-{{ $recording->transcription_percent }}">
<flux:table.cell>
<flux:button
type="button"
variant="ghost"
size="sm"
square
data-audio-url="{{ route('recordings.audio', $recording) }}"
x-bind:aria-label="isPlayingRow({{ $recording->id }}) ? 'Pause' : 'Play'"
x-on:click="togglePlay({{ $recording->id }}, $el.dataset.audioUrl)"
>
<flux:icon.play
variant="micro"
x-show="! isPlayingRow({{ $recording->id }})"
/>
<flux:icon.pause
variant="micro"
x-show="isPlayingRow({{ $recording->id }})"
x-cloak
/>
</flux:button>
</flux:table.cell>
<flux:table.cell class="max-w-xl"> <flux:table.cell class="max-w-xl">
<div class="flex min-w-0 items-center gap-2"> <div class="flex min-w-0 items-center gap-2">
<flux:link <flux:link
@@ -134,6 +148,26 @@
> >
{{ $recording->title }} {{ $recording->title }}
</flux:link> </flux:link>
<flux:button
type="button"
variant="ghost"
size="sm"
square
class="shrink-0"
data-audio-url="{{ route('recordings.audio', $recording) }}"
x-bind:aria-label="isPlayingRow({{ $recording->id }}) ? 'Pause' : 'Play'"
x-on:click="togglePlay({{ $recording->id }}, $el.dataset.audioUrl)"
>
<flux:icon.play
variant="micro"
x-show="! isPlayingRow({{ $recording->id }})"
/>
<flux:icon.pause
variant="micro"
x-show="isPlayingRow({{ $recording->id }})"
x-cloak
/>
</flux:button>
@if ($preview = $recording->transcriptFirstLine()) @if ($preview = $recording->transcriptFirstLine())
<span class="min-w-0 truncate text-sm text-zinc-500 dark:text-zinc-400" title="{{ $preview }}"> <span class="min-w-0 truncate text-sm text-zinc-500 dark:text-zinc-400" title="{{ $preview }}">
{{ $preview }} {{ $preview }}
@@ -147,29 +181,11 @@
{{ $recording->word_count > 0 ? number_format($recording->word_count) : '—' }} {{ $recording->word_count > 0 ? number_format($recording->word_count) : '—' }}
</span> </span>
</flux:table.cell> </flux:table.cell>
<flux:table.cell class="whitespace-normal py-2"> <flux:table.cell class="w-36 whitespace-nowrap">
<x-transcription-status-badge <x-transcription-status-badge
:status="$recording->transcription_status" :status="$recording->transcription_status"
:label="$recording->transcriptionStatusLabel()" :label="$recording->transcriptionStatusLabel()"
/> />
@if ($recording->transcription_status === 'pending' && filled($recording->transcription_progress))
<div
class="mt-1 max-w-[14rem] truncate text-xs text-zinc-500 dark:text-zinc-400"
title="{{ $recording->transcription_progress }}"
>
{{ $recording->transcription_progress }}
</div>
@elseif ($recording->transcription_status === 'processing' && filled($recording->transcription_progress))
<div
class="mt-1 max-w-[14rem] truncate text-xs text-amber-700 dark:text-amber-300"
title="{{ $recording->transcription_progress }}"
>
@if ($recording->transcription_percent)
{{ $recording->transcription_percent }}% ·
@endif
{{ $recording->transcription_progress }}
</div>
@endif
</flux:table.cell> </flux:table.cell>
<flux:table.cell> <flux:table.cell>
{{ $recording->created_at?->format('Y-m-d H:i') }} {{ $recording->created_at?->format('Y-m-d H:i') }}
@@ -1,13 +1,19 @@
<div <div
x-data="transcriptionMonitor(@js([ @if ($recording->isTranscribing())
'statusUrl' => route('recordings.transcription-status', $recording), wire:poll.2s.visible
'initial' => $recording->transcriptionStatusPayload(), @endif
]))"
x-init="
start();
return () => destroy();
"
> >
<div
wire:key="transcription-ui-{{ $recording->id }}-{{ $recording->transcription_status }}-{{ $recording->transcription_percent }}-{{ md5((string) $recording->transcription_progress) }}-{{ $recording->transcribed_at?->timestamp }}"
x-data="transcriptionMonitor(@js([
'statusUrl' => route('recordings.transcription-status', $recording),
'initial' => $recording->transcriptionStatusPayload(),
]))"
x-init="
start();
return () => destroy();
"
>
<div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between"> <div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div> <div>
<flux:link href="{{ route('recordings.index') }}" wire:navigate class="text-sm"> Recordings</flux:link> <flux:link href="{{ route('recordings.index') }}" wire:navigate class="text-sm"> Recordings</flux:link>
@@ -222,4 +228,5 @@
No transcript yet. Transcription starts automatically after upload, or use the button above. No transcript yet. Transcription starts automatically after upload, or use the button above.
</flux:text> </flux:text>
</flux:card> </flux:card>
</div>
</div> </div>
+58 -3
View File
@@ -125,8 +125,8 @@ class IndexTest extends TestCase
Livewire::test(Index::class) Livewire::test(Index::class)
->assertSee('wire:poll', false) ->assertSee('wire:poll', false)
->assertSee('Transcribing locally…') ->assertSee('Transcribing')
->assertSee('40%') ->assertDontSee('Transcribing locally…')
->assertSeeHtml('bg-amber-400'); ->assertSeeHtml('bg-amber-400');
} }
@@ -151,7 +151,7 @@ class IndexTest extends TestCase
Livewire::test(Index::class) Livewire::test(Index::class)
->assertSee('Waiting in line') ->assertSee('Waiting in line')
->assertSee('Queued') ->assertSee('Queued')
->assertSee('Queued — waiting to start…') ->assertDontSee('Queued — waiting to start…')
->assertDontSee('5%') ->assertDontSee('5%')
->assertSeeHtml('bg-zinc-400/15') ->assertSeeHtml('bg-zinc-400/15')
->assertDontSeeHtml('bg-amber-400'); ->assertDontSeeHtml('bg-amber-400');
@@ -282,4 +282,59 @@ class IndexTest extends TestCase
$this->assertDatabaseHas('recordings', ['id' => $recording->id]); $this->assertDatabaseHas('recordings', ['id' => $recording->id]);
} }
public function test_recordings_can_be_sorted_by_title(): void
{
$user = User::factory()->create();
$this->actingAs($user);
Recording::query()->create([
'user_id' => $user->id,
'title' => 'Zebra',
'original_filename' => 'z.mp3',
'file_path' => 'recordings/z.mp3',
'file_size_bytes' => 100,
'transcription_status' => 'done',
'created_at' => now()->subDay(),
]);
Recording::query()->create([
'user_id' => $user->id,
'title' => 'Alpha',
'original_filename' => 'a.mp3',
'file_path' => 'recordings/a.mp3',
'file_size_bytes' => 100,
'transcription_status' => 'done',
'created_at' => now(),
]);
Livewire::test(Index::class)
->call('sort', 'title')
->assertSet('sortBy', 'title')
->assertSet('sortDirection', 'asc')
->assertSeeInOrder(['Alpha', 'Zebra'])
->call('sort', 'title')
->assertSet('sortDirection', 'desc')
->assertSeeInOrder(['Zebra', 'Alpha']);
}
public function test_invalid_sort_column_is_ignored(): void
{
$user = User::factory()->create();
$this->actingAs($user);
Recording::query()->create([
'user_id' => $user->id,
'title' => 'Only one',
'original_filename' => 'one.mp3',
'file_path' => 'recordings/one.mp3',
'file_size_bytes' => 100,
'transcription_status' => 'done',
]);
Livewire::test(Index::class)
->call('sort', 'not_a_column')
->assertSet('sortBy', 'uploaded')
->assertSet('sortDirection', 'desc');
}
} }
+77
View File
@@ -59,4 +59,81 @@ class ShowTest extends TestCase
$this->assertDatabaseMissing('recordings', ['id' => $recording->id]); $this->assertDatabaseMissing('recordings', ['id' => $recording->id]);
} }
public function test_show_polls_while_transcription_is_active(): void
{
$user = User::factory()->create();
$this->actingAs($user);
$recording = Recording::query()->create([
'user_id' => $user->id,
'title' => 'In progress',
'original_filename' => 'active.mp3',
'file_path' => 'recordings/active.mp3',
'file_size_bytes' => 100,
'transcription_status' => 'processing',
'transcription_progress' => 'Queued — waiting to start…',
'transcription_percent' => null,
'transcription_driver' => 'local',
'transcription_started_at' => now(),
]);
Livewire::test(Show::class, ['recording' => $recording])
->assertSee('wire:poll', false)
->assertSee('Queued — waiting to start…');
}
public function test_show_does_not_poll_when_transcription_is_idle(): void
{
$user = User::factory()->create();
$this->actingAs($user);
$recording = Recording::query()->create([
'user_id' => $user->id,
'title' => 'Finished',
'original_filename' => 'done.mp3',
'file_path' => 'recordings/done.mp3',
'file_size_bytes' => 100,
'transcription_status' => 'done',
'transcript' => 'all done',
]);
Livewire::test(Show::class, ['recording' => $recording])
->assertDontSee('wire:poll', false);
}
public function test_show_refreshes_recording_on_transcription_broadcast(): void
{
$user = User::factory()->create();
$this->actingAs($user);
$recording = Recording::query()->create([
'user_id' => $user->id,
'title' => 'Live update',
'original_filename' => 'live.mp3',
'file_path' => 'recordings/live.mp3',
'file_size_bytes' => 100,
'transcription_status' => 'pending',
'transcription_progress' => 'Queued — waiting to start…',
'transcription_driver' => 'local',
'transcription_started_at' => now(),
]);
$component = Livewire::test(Show::class, ['recording' => $recording]);
$recording->update([
'transcription_status' => 'processing',
'transcription_progress' => 'Transcribing locally…',
'transcription_percent' => 40,
]);
$component
->call('onTranscriptionUpdated', [
'id' => $recording->id,
'status' => 'processing',
])
->assertSet('recording.transcription_status', 'processing')
->assertSet('recording.transcription_percent', 40)
->assertSee('Transcribing locally…');
}
} }