From b1a7a98dcad748b86bc43bde96772dd17ad21fba Mon Sep 17 00:00:00 2001 From: Kjell Kind Date: Tue, 1 Dec 2026 14:51:02 +0100 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20show=20authors=20who=20gave=20their?= =?UTF-8?q?=20commit=20past=C3=A9is=20from=20its=20pastel=20count?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/Actions/CreateCommitPastel.php | 5 + .../Controllers/CommitPastelController.php | 20 ++ .../Requests/ListCommitPasteisRequest.php | 35 +++ app/Models/Commit.php | 11 + ..._01_120000_create_commit_pasteis_table.php | 27 +++ .../js/components/commit-pastel-button.tsx | 56 ++++- .../commit-pastel-givers-dialog.tsx | 202 ++++++++++++++++++ routes/web.php | 2 + .../CommitPastelControllerTest.php | 100 +++++++++ tests/Unit/CommitPastelCount.test.tsx | 85 ++++++++ 10 files changed, 542 insertions(+), 1 deletion(-) create mode 100644 app/Http/Requests/ListCommitPasteisRequest.php create mode 100644 database/migrations/2026_12_01_120000_create_commit_pasteis_table.php create mode 100644 resources/js/components/commit-pastel-givers-dialog.tsx create mode 100644 tests/Unit/CommitPastelCount.test.tsx diff --git a/app/Actions/CreateCommitPastel.php b/app/Actions/CreateCommitPastel.php index e11fe78e89..76c1759e2b 100644 --- a/app/Actions/CreateCommitPastel.php +++ b/app/Actions/CreateCommitPastel.php @@ -39,6 +39,11 @@ public function handle(User $user, Commit $commit): bool $recipientCommit->increment('pasteis_count'); User::query()->whereKey($commit->user_id)->increment('pasteis_received'); + DB::table('commit_pasteis')->upsert( + ['commit_id' => $commit->id, 'user_id' => $sender->id, 'count' => 1, 'created_at' => now(), 'updated_at' => now()], + ['commit_id', 'user_id'], + ['count' => DB::raw('commit_pasteis.count + 1'), 'updated_at' => now()], + ); // The count is everyone's to see, and the giver's other devices learn what they have left to give. if ($recipientCommit->status === CommitStatus::Approved) { diff --git a/app/Http/Controllers/CommitPastelController.php b/app/Http/Controllers/CommitPastelController.php index 243d8d72db..a16957bba4 100644 --- a/app/Http/Controllers/CommitPastelController.php +++ b/app/Http/Controllers/CommitPastelController.php @@ -6,6 +6,7 @@ use App\Actions\CreateCommitPastel; use App\Http\Requests\CreateCommitPastelRequest; +use App\Http\Requests\ListCommitPasteisRequest; use App\Models\Commit; use App\Models\User; use Illuminate\Container\Attributes\CurrentUser; @@ -13,6 +14,25 @@ final readonly class CommitPastelController { + /** + * Who gave the commit pastéis and how many each, latest first. People across a block with the author are left out, like everywhere else. + */ + public function index(ListCommitPasteisRequest $request, #[CurrentUser] User $user, Commit $commit): JsonResponse + { + $givers = $commit->pastelGivers() + ->select(['users.*', 'commit_pasteis.count as pasteis']) + ->whereNotIn('users.id', $user->idsAcrossBlocks()) + ->latest('commit_pasteis.updated_at') + ->latest('users.id') + ->cursorPaginate(20); + + foreach ($givers->items() as $giver) { + $giver->makeHidden('pivot'); + } + + return response()->json($givers); + } + public function store(CreateCommitPastelRequest $request, #[CurrentUser] User $user, Commit $commit, CreateCommitPastel $action): JsonResponse { $awarded = $action->handle($user, $commit); diff --git a/app/Http/Requests/ListCommitPasteisRequest.php b/app/Http/Requests/ListCommitPasteisRequest.php new file mode 100644 index 0000000000..e08bba98cd --- /dev/null +++ b/app/Http/Requests/ListCommitPasteisRequest.php @@ -0,0 +1,35 @@ +user(); + assert($user instanceof User); + + $commit = $this->route('commit'); + assert($commit instanceof Commit); + + return $commit->isOwnedBy($user) ? Response::allow() : Response::denyAsNotFound(); + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } +} diff --git a/app/Models/Commit.php b/app/Models/Commit.php index 93adc3ffd7..3a5c407ab8 100644 --- a/app/Models/Commit.php +++ b/app/Models/Commit.php @@ -51,6 +51,7 @@ * @property-read User|null $user * @property-read Profile|null $author * @property-read Collection $stars + * @property-read Collection $pastelGivers * @property-read Commit|null $parent * @property-read Collection $replies * @property-read int $replies_count @@ -199,6 +200,16 @@ public function stars(): BelongsToMany return $this->belongsToMany(User::class, 'stars')->withTimestamps(); } + /** + * Who gave the commit pastéis, with how many each gave as the pivot's count. + * + * @return BelongsToMany + */ + public function pastelGivers(): BelongsToMany + { + return $this->belongsToMany(User::class, 'commit_pasteis')->withPivot('count')->withTimestamps(); + } + /** * @return BelongsToMany */ diff --git a/database/migrations/2026_12_01_120000_create_commit_pasteis_table.php b/database/migrations/2026_12_01_120000_create_commit_pasteis_table.php new file mode 100644 index 0000000000..b478c13122 --- /dev/null +++ b/database/migrations/2026_12_01_120000_create_commit_pasteis_table.php @@ -0,0 +1,27 @@ +foreignUuid('commit_id')->constrained()->cascadeOnDelete(); + $table->foreignUuid('user_id')->constrained()->cascadeOnDelete(); + $table->unsignedInteger('count')->default(0); + $table->timestamps(); + + $table->primary(['commit_id', 'user_id']); + $table->index('user_id'); + $table->index(['commit_id', 'updated_at']); + }); + } +}; diff --git a/resources/js/components/commit-pastel-button.tsx b/resources/js/components/commit-pastel-button.tsx index 18fe022a81..122e207d08 100644 --- a/resources/js/components/commit-pastel-button.tsx +++ b/resources/js/components/commit-pastel-button.tsx @@ -1,8 +1,10 @@ import { router, useHttp, usePage } from '@inertiajs/react'; import { useEffect, useEffectEvent, useRef } from 'react'; +import type { ReactNode } from 'react'; import { toast } from 'sonner'; import { store } from '@/actions/App/Http/Controllers/CommitPastelController'; import { ActionTooltip } from '@/components/action-tooltip'; +import { CommitPastelGiversDialog } from '@/components/commit-pastel-givers-dialog'; import { useCommitNotFound } from '@/hooks/use-deleted-resources'; import { useNow } from '@/hooks/use-now'; import { refreshSharedState, useSharedState } from '@/hooks/use-shared-state'; @@ -71,7 +73,7 @@ export function CommitPastelButton({ const userId = auth.user.id; const isOwn = commit.author.id === userId; - const readOnly = isOwn || commit.status !== 'approved'; + const readOnly = commit.status !== 'approved'; const label = `${formatExactCount(count)} ${count === 1 ? 'pastel' : 'pastéis'}`; const award = async () => { @@ -185,6 +187,19 @@ export function CommitPastelButton({ className, ); + if (isOwn) { + return ( + + {content} + + ); + } + return ( ); } + +/** + * Authors can't give their own commits pastéis, so they see how many others gave, and who gave them. + */ +function PastelCount({ + commit, + count, + label, + className, + children, +}: { + commit: Commit; + count: number; + label: string; + className: string; + children: ReactNode; +}) { + const description = + count === 0 ? 'No pastéis yet' : `${label}, show who gave them`; + + return ( + + + + + + ); +} diff --git a/resources/js/components/commit-pastel-givers-dialog.tsx b/resources/js/components/commit-pastel-givers-dialog.tsx new file mode 100644 index 0000000000..b39c88f44b --- /dev/null +++ b/resources/js/components/commit-pastel-givers-dialog.tsx @@ -0,0 +1,202 @@ +import { Link } from '@inertiajs/react'; +import { useState } from 'react'; +import type { ReactNode } from 'react'; +import { index } from '@/actions/App/Http/Controllers/CommitPastelController'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { UserAvatar } from '@/components/user-avatar'; +import { UserPreview } from '@/components/user-preview'; +import { exactCountTitle, formatCount, formatExactCount } from '@/lib/numbers'; +import { show } from '@/routes/user'; +import type { Commit, CursorPaginated, User } from '@/types'; + +type PastelGiver = Pick & { + pasteis: number; +}; + +/** + * Who gave one of the viewer's own commits pastéis and how many each, latest first, opened from the pastel count. + * + * Pastéis given before givers were recorded, or by people across a block, only count, so the list can name fewer. + */ +export function CommitPastelGiversDialog({ + commit, + count, + children, +}: { + commit: Pick; + count: number; + children: ReactNode; +}) { + const [open, setOpen] = useState(false); + const [givers, setGivers] = useState([]); + const [cursor, setCursor] = useState(null); + const [loading, setLoading] = useState(false); + const [failed, setFailed] = useState(false); + + const load = async (next: string | null = null) => { + setLoading(true); + setFailed(false); + try { + const response = await fetch( + index(commit, { query: { cursor: next } }).url, + { headers: { Accept: 'application/json' } }, + ); + if (!response.ok) throw new Error('Unable to load pastéis'); + const data = + (await response.json()) as CursorPaginated; + setGivers((previous) => + next ? [...previous, ...data.data] : data.data, + ); + setCursor(data.next_cursor); + } catch { + setFailed(true); + } finally { + setLoading(false); + } + }; + + // Loads again each time it opens, so pastéis given in the meantime show up. + const onOpenChange = (next: boolean) => { + setOpen(next); + if (next) { + setGivers([]); + setCursor(null); + void load(); + } + }; + + const listed = givers.reduce((sum, giver) => sum + giver.pasteis, 0); + const unlisted = + !loading && !failed && cursor === null ? count - listed : 0; + + return ( + + {children} + + + + Pastéis from + + + This commit got{' '} + + {formatCount(count)} + {' '} + {count === 1 ? 'pastel' : 'pastéis'}. + + + +
    + {givers.map((giver) => ( +
  • + + setOpen(false)} + className="flex items-center gap-3 rounded-md px-2 py-2 transition-colors hover:bg-accent" + > + + + + {giver.name} + + + @{giver.handle} + + + + + {formatCount(giver.pasteis)} + + + +
  • + ))} + {loading && + Array.from( + { + length: Math.max( + 1, + Math.min(count - listed, 3), + ), + }, + (_, row) => ( +
  • + + +
  • + ), + )} +
+ + {unlisted > 0 && ( +

+ +{formatCount(unlisted)} more from people not listed +

+ )} + {loading && ( +

+ Loading pastéis… +

+ )} + {failed && ( +
+

+ fatal: could not load pastéis +

+ +
+ )} + {!loading && !failed && cursor && ( + + )} +
+
+ ); +} diff --git a/routes/web.php b/routes/web.php index e4b8c6961f..b7fe97f736 100644 --- a/routes/web.php +++ b/routes/web.php @@ -508,6 +508,8 @@ Route::post('commits/{commit}/star', [CommitStarController::class, 'store']) ->middleware('throttle:stars') ->name('commit-star.store'); + Route::get('commits/{commit}/pasteis', [CommitPastelController::class, 'index']) + ->name('commit-pastel.index'); Route::post('commits/{commit}/pasteis', [CommitPastelController::class, 'store']) ->middleware('throttle:60,1,pasteis:') ->name('commit-pastel.store'); diff --git a/tests/Feature/Controllers/CommitPastelControllerTest.php b/tests/Feature/Controllers/CommitPastelControllerTest.php index b2546d20d7..ede97b9c83 100644 --- a/tests/Feature/Controllers/CommitPastelControllerTest.php +++ b/tests/Feature/Controllers/CommitPastelControllerTest.php @@ -99,3 +99,103 @@ expect($commit->refresh()->pasteis_count)->toBe(0); }); + +it('records who gave a commit pastéis and how many each', function (): void { + $first = User::factory()->create(['pasteis_mode' => true]); + $second = User::factory()->create(['pasteis_mode' => true]); + $commit = Commit::factory()->create(); + + $this->actingAs($first)->postJson(route('commit-pastel.store', $commit))->assertOk(); + $this->postJson(route('commit-pastel.store', $commit))->assertOk(); + $this->actingAs($second)->postJson(route('commit-pastel.store', $commit))->assertOk(); + + expect($commit->pastelGivers()->get()->mapWithKeys(fn (User $giver): array => [$giver->id => $giver->pivot->count])->all()) + ->toEqual([$first->id => 2, $second->id => 1]); +}); + +it('lists who gave their commit pastéis, latest first, with how many each gave', function (): void { + $user = User::factory()->create(); + $commit = Commit::factory()->for($user)->create(); + $first = User::factory()->create(['handle' => 'first']); + $second = User::factory()->create(['handle' => 'second']); + + $commit->pastelGivers()->attach($first, ['count' => 3, 'updated_at' => now()->subMinute()]); + $commit->pastelGivers()->attach($second, ['count' => 1]); + Commit::factory()->for($user)->create()->pastelGivers()->attach(User::factory()->create(), ['count' => 1]); + + $this->actingAs($user)->getJson(route('commit-pastel.index', $commit)) + ->assertOk() + ->assertJsonPath('data.0.id', $second->id) + ->assertJsonPath('data.0.handle', 'second') + ->assertJsonPath('data.0.avatar_url', $second->avatar_url) + ->assertJsonPath('data.0.pasteis', 1) + ->assertJsonMissingPath('data.0.pivot') + ->assertJsonMissingPath('data.0.email') + ->assertJsonPath('data.1.handle', 'first') + ->assertJsonPath('data.1.pasteis', 3) + ->assertJsonCount(2, 'data') + ->assertJsonPath('next_cursor', null); +}); + +it('moves a giver to the top when they give again', function (): void { + $user = User::factory()->create(); + $commit = Commit::factory()->for($user)->create(); + $earlier = User::factory()->create(['pasteis_mode' => true]); + $later = User::factory()->create(['pasteis_mode' => true]); + + $this->actingAs($earlier)->postJson(route('commit-pastel.store', $commit))->assertOk(); + $this->travel(1)->minute(); + $this->actingAs($later)->postJson(route('commit-pastel.store', $commit))->assertOk(); + $this->travel(1)->minute(); + $this->actingAs($earlier)->postJson(route('commit-pastel.store', $commit))->assertOk(); + + $this->actingAs($user)->getJson(route('commit-pastel.index', $commit)) + ->assertOk() + ->assertJsonPath('data.0.id', $earlier->id) + ->assertJsonPath('data.0.pasteis', 2) + ->assertJsonPath('data.1.id', $later->id); +}); + +it('lists who gave their commit pastéis in pages', function (): void { + $user = User::factory()->create(); + $commit = Commit::factory()->for($user)->create(); + + User::factory()->count(21)->create()->each(fn (User $giver) => $commit->pastelGivers()->attach($giver, ['count' => 1])); + + $page = $this->actingAs($user)->getJson(route('commit-pastel.index', $commit)) + ->assertOk() + ->assertJsonCount(20, 'data'); + + $this->getJson(route('commit-pastel.index', ['commit' => $commit, 'cursor' => $page->json('next_cursor')])) + ->assertOk() + ->assertJsonCount(1, 'data') + ->assertJsonPath('next_cursor', null); +}); + +it('leaves out who gave their commit pastéis across a block in either direction', function (bool $userBlocks): void { + $user = User::factory()->create(); + $commit = Commit::factory()->for($user)->create(); + $blocked = User::factory()->create(); + + $commit->pastelGivers()->attach($blocked, ['count' => 1]); + $userBlocks ? $user->blocking()->attach($blocked) : $blocked->blocking()->attach($user); + + $this->actingAs($user)->getJson(route('commit-pastel.index', $commit)) + ->assertOk() + ->assertJsonCount(0, 'data'); +})->with([true, false]); + +it('may not list who gave pastéis to the commit of someone else', function (): void { + $commit = Commit::factory()->create(); + + $commit->pastelGivers()->attach(User::factory()->create(), ['count' => 1]); + + $this->actingAs(User::factory()->create()) + ->getJson(route('commit-pastel.index', $commit)) + ->assertNotFound(); +}); + +it('requires authentication to list who gave a commit pastéis', function (): void { + $this->getJson(route('commit-pastel.index', Commit::factory()->create())) + ->assertUnauthorized(); +}); diff --git a/tests/Unit/CommitPastelCount.test.tsx b/tests/Unit/CommitPastelCount.test.tsx new file mode 100644 index 0000000000..1eeb66f38b --- /dev/null +++ b/tests/Unit/CommitPastelCount.test.tsx @@ -0,0 +1,85 @@ +/// + +import assert from 'node:assert/strict'; +import { createInertiaApp } from '@inertiajs/react'; +import { renderToString } from 'react-dom/server'; +import { test } from 'vite-plus/test'; +import { CommitPastelButton } from '../../resources/js/components/commit-pastel-button'; +import { TooltipProvider } from '../../resources/js/components/ui/tooltip'; +import type { Commit } from '../../resources/js/types'; + +async function render( + user: { id: string }, + commit: Partial = {}, +): Promise { + const day = new Date().toISOString().slice(0, 10); + const result = await createInertiaApp({ + page: { + component: 'pastel', + props: { + auth: { + organizations: [], + user, + pasteis: { remaining: 3, day }, + }, + errors: {}, + }, + url: '/@author/commit', + version: null, + clearHistory: false, + encryptHistory: false, + rescuedProps: [], + rememberedState: {}, + flash: {}, + }, + resolve: () => () => ( + + ), + render: renderToString, + setup: ({ App, props }) => ( + + + + ), + }); + + assert.ok(result); + + return result.body; +} + +for (const status of ['approved', 'pending', 'rejected'] as const) { + test(`authors see their ${status} commit's pastel count and may open who gave them`, async () => { + const body = await render({ id: 'author' }, { status }); + + assert.match(body, /data-test="own-pastel-count"/); + assert.match(body, /aria-label="4 pastéis, show who gave them"/); + assert.doesNotMatch(body, /data-test="award-pastel-button"/); + assert.doesNotMatch(body, /disabled=""/); + }); +} + +test('authors see a disabled count before anyone gave a pastel', async () => { + const body = await render({ id: 'author' }, { pasteis_count: 0 }); + + assert.match(body, /data-test="own-pastel-count"/); + assert.match(body, /aria-label="No pastéis yet"/); + assert.match(body, /disabled=""/); +}); + +test('other readers keep the award button', async () => { + const body = await render({ id: 'viewer' }); + + assert.match(body, /data-test="award-pastel-button"/); + assert.doesNotMatch(body, /data-test="own-pastel-count"/); +}); From 04ddcb4483f0f34d86e9e66e0b7202a22af7e849 Mon Sep 17 00:00:00 2001 From: Kjell Kind Date: Tue, 1 Dec 2026 18:52:25 +0100 Subject: [PATCH 2/2] fix: keep a page that loaded after closing out of the next pastel list Co-Authored-By: Claude Opus 5.5 --- .../commit-pastel-givers-dialog.tsx | 11 +- tests/Unit/CommitPastelGiversDialog.test.tsx | 129 ++++++++++++++++++ 2 files changed, 137 insertions(+), 3 deletions(-) create mode 100644 tests/Unit/CommitPastelGiversDialog.test.tsx diff --git a/resources/js/components/commit-pastel-givers-dialog.tsx b/resources/js/components/commit-pastel-givers-dialog.tsx index b39c88f44b..5f8a44b6ec 100644 --- a/resources/js/components/commit-pastel-givers-dialog.tsx +++ b/resources/js/components/commit-pastel-givers-dialog.tsx @@ -1,5 +1,5 @@ import { Link } from '@inertiajs/react'; -import { useState } from 'react'; +import { useRef, useState } from 'react'; import type { ReactNode } from 'react'; import { index } from '@/actions/App/Http/Controllers/CommitPastelController'; import { Button } from '@/components/ui/button'; @@ -40,8 +40,11 @@ export function CommitPastelGiversDialog({ const [cursor, setCursor] = useState(null); const [loading, setLoading] = useState(false); const [failed, setFailed] = useState(false); + // Counts the openings, so a page still loading when the dialog closed can't land in a later opening's list. + const opening = useRef(0); const load = async (next: string | null = null) => { + const current = opening.current; setLoading(true); setFailed(false); try { @@ -52,19 +55,21 @@ export function CommitPastelGiversDialog({ if (!response.ok) throw new Error('Unable to load pastéis'); const data = (await response.json()) as CursorPaginated; + if (current !== opening.current) return; setGivers((previous) => next ? [...previous, ...data.data] : data.data, ); setCursor(data.next_cursor); } catch { - setFailed(true); + if (current === opening.current) setFailed(true); } finally { - setLoading(false); + if (current === opening.current) setLoading(false); } }; // Loads again each time it opens, so pastéis given in the meantime show up. const onOpenChange = (next: boolean) => { + opening.current += 1; setOpen(next); if (next) { setGivers([]); diff --git a/tests/Unit/CommitPastelGiversDialog.test.tsx b/tests/Unit/CommitPastelGiversDialog.test.tsx new file mode 100644 index 0000000000..0f20a98245 --- /dev/null +++ b/tests/Unit/CommitPastelGiversDialog.test.tsx @@ -0,0 +1,129 @@ +/// +import assert from 'node:assert/strict'; +import * as React from 'react'; +import type { ReactElement, ReactNode } from 'react'; +import { test, vi } from 'vite-plus/test'; + +let state: unknown[] = []; +let cursor = 0; + +vi.doMock('react', () => ({ + ...React, + useRef: (initial: unknown) => { + const index = cursor++; + if (!(index in state)) { + state[index] = { current: initial }; + } + return state[index]; + }, + useState: (initial: unknown) => { + const index = cursor++; + if (!(index in state)) { + state[index] = typeof initial === 'function' ? initial() : initial; + } + return [ + state[index], + (value: unknown) => { + state[index] = + typeof value === 'function' ? value(state[index]) : value; + }, + ]; + }, +})); + +const { CommitPastelGiversDialog } = + await import('../../resources/js/components/commit-pastel-givers-dialog'); + +type Element = ReactElement>; + +function elements(node: ReactNode): Element[] { + if (!React.isValidElement(node)) { + return []; + } + const element = node as Element; + return [ + element, + ...React.Children.toArray(element.props.children as ReactNode).flatMap( + elements, + ), + ]; +} + +function render() { + cursor = 0; + return elements( + CommitPastelGiversDialog({ + commit: { id: 'commit' }, + count: 5, + children: , + }), + ); +} + +function giver(id: string) { + return { id, name: id, handle: id, avatar_url: '', pasteis: 1 }; +} + +function page(ids: string[], next: string | null) { + return new Response( + JSON.stringify({ data: ids.map(giver), next_cursor: next }), + ); +} + +test('ignores a page that was still loading when the dialog closed', async () => { + state = []; + const pending: Array<(response: Response) => void> = []; + const fetch = vi.spyOn(globalThis, 'fetch').mockImplementation( + () => + new Promise((resolve) => { + pending.push(resolve); + }), + ); + const settle = async (index: number, response: Response) => { + pending[index](response); + await new Promise((resolve) => setTimeout(resolve, 0)); + }; + const openChange = (open: boolean) => + (render()[0].props.onOpenChange as (open: boolean) => void)(open); + const listed = () => + render() + .filter( + (element) => + element.type === 'li' && !element.props['aria-hidden'], + ) + // Children.toArray prefixes keys, so `.0:$ana` is the row keyed `ana`. + .map((element) => String(element.key).replace(/^.*\$/u, '')); + + try { + openChange(true); + await settle(0, page(['ana', 'bea'], 'second')); + + const showMore = render().find( + (element) => element.props.children === 'Show more', + )!; + (showMore.props.onClick as () => void)(); + + openChange(false); + openChange(true); + await settle(1, page(['cris'], null)); + + assert.deepEqual(listed(), []); + assert.ok( + render().some( + (element) => element.props.children === 'Loading pastéis…', + ), + ); + + await settle(2, page(['cris', 'ana', 'bea'], null)); + + assert.deepEqual(listed(), ['cris', 'ana', 'bea']); + assert.equal( + render().some( + (element) => element.props.children === 'Loading pastéis…', + ), + false, + ); + } finally { + fetch.mockRestore(); + } +});