diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index 5c6492e..4849b1f 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -46,8 +46,6 @@ public function show(string $locale, int $id) $product = $this->products->getById($id); abort_if($product === null, Response::HTTP_NOT_FOUND); - $product = $this->mergeJustSubmittedReview($product); - [$productOptions, $variantsData] = $this->buildOptionPicker($id); return view('product.show', [ @@ -147,40 +145,6 @@ private function buildOptionPicker(int $productId): array return [$productOptions, $variantsData]; } - /** - * Meilisearch's own write API is itself async — addDocuments() enqueues an - * indexing task and returns immediately, and Laravel\Scout\Engines\ - * MeilisearchEngine::update() never waits on that task, so even - * $product->searchableSync() (which only skips OUR queue) can still land - * the shopper back on this page before Meilisearch has actually processed - * the write. storeReview() flashes the review it just created for exactly - * this one next request; splice it in here rather than trust the index is - * already caught up. Guarded by id so a race the other way — the index - * DID catch up in time — doesn't show the same review twice. - */ - private function mergeJustSubmittedReview(array $product): array - { - $justSubmitted = session('justSubmittedReview'); - - if (! $justSubmitted || (string) ($justSubmitted['product_id'] ?? null) !== (string) $product['id']) { - return $product; - } - - $items = $product['reviews']['items'] ?? []; - - if (collect($items)->contains('id', $justSubmitted['id'])) { - return $product; - } - - $items = [$justSubmitted, ...$items]; - - $product['reviews']['items'] = $items; - $product['reviews']['count'] = count($items); - $product['reviews']['average_rating'] = round(collect($items)->avg('rating'), 1); - - return $product; - } - /** * A storefront-owned, checkout-module-independent stock check — the * product page's "Add to cart" calls this first and only submits to the @@ -214,14 +178,21 @@ public function checkStock(string $locale, Request $request): JsonResponse /** * boboko/core's product_reviews table has no moderation/status column, so * this goes live immediately — no approval queue to land in. + * + * The form submits through Turbo, so the answer is Turbo Streams: the new + * review into the list, the updated count and average, the thank-you in + * place of the form; or, on a validation error, the form again with inline + * errors (422). Nothing goes through the session, so the product page + * itself never reads one (it'll be cached). Without JS this is a plain + * POST that redirects back to the product page, losing the inline errors + * and the thank-you — accepted. + * + * The redirect's ?tab=reviews is a query-string variant of the product + * page: keep that in mind once product pages are cached. */ - public function storeReview(string $locale, Request $request, Product $product): RedirectResponse + public function storeReview(string $locale, Request $request, Product $product): RedirectResponse|Response { - $reviewsUrl = route('product.show', [ - 'locale' => $locale, - 'id' => $product->id, - 'tab' => 'reviews', - ]).'#product-tabs'; + $wantsStream = str_contains((string) $request->header('Accept'), 'text/vnd.turbo-stream.html'); $validator = Validator::make($request->all(), [ 'rating' => ['required', 'integer', 'between:1,5'], @@ -231,7 +202,13 @@ public function storeReview(string $locale, Request $request, Product $product): ]); if ($validator->fails()) { - return redirect($reviewsUrl)->withErrors($validator)->withInput(); + return $wantsStream + ? $this->turboStream('product.streams.review-invalid', [ + 'productId' => $product->id, + 'messages' => $validator->errors(), + 'values' => $request->only('rating', 'content', 'name', 'email'), + ], Response::HTTP_UNPROCESSABLE_ENTITY) + : redirect($this->reviewsUrl($locale, $product)); } $data = $validator->validated(); @@ -251,17 +228,23 @@ public function storeReview(string $locale, Request $request, Product $product): ]); // ReviewServiceProvider also reindexes on the model's `created` event, but - // queued (SCOUT_QUEUE=true) — it wouldn't land before this redirect's page - // load. Syncing here skips our queue too, but Meilisearch's own write API - // is itself async on top of that (see mergeJustSubmittedReview()), so this - // alone still isn't a guarantee — it's the flash below that actually is. + // queued (SCOUT_QUEUE=true). Syncing here skips our queue, so the next + // product page load has it as soon as Meilisearch (itself async) catches + // up. The stream below doesn't wait for the index: it renders the new + // review and the count/average straight from the DB, which is exactly + // what ProductIndexer builds the index's `reviews` from. $product->searchableSync(); - return redirect($reviewsUrl) - ->with('reviewSubmitted', true) - ->with('justSubmittedReview', [ + if (! $wantsStream) { + return redirect($this->reviewsUrl($locale, $product)); + } + + $reviews = ProductReview::where('product_id', $product->id); + + return $this->turboStream('product.streams.review-stored', [ + // Same shape as ProductIndexer::mapReview(), for the shared partial. + 'review' => [ 'id' => $review->id, - 'product_id' => $review->product_id, 'title' => $review->title, 'body' => $review->body, 'rating' => $review->rating, @@ -270,6 +253,25 @@ public function storeReview(string $locale, Request $request, Product $product): 'reply' => null, 'replied_at' => null, 'media' => [], - ]); + ], + 'count' => (clone $reviews)->count(), + 'averageRating' => round((float) (clone $reviews)->avg('rating'), 1), + ]); + } + + private function reviewsUrl(string $locale, Product $product): string + { + return route('product.show', [ + 'locale' => $locale, + 'id' => $product->id, + 'tab' => 'reviews', + ]).'#product-tabs'; + } + + private function turboStream(string $view, array $data, int $status = Response::HTTP_OK): Response + { + return response() + ->view($view, $data, $status) + ->header('Content-Type', 'text/vnd.turbo-stream.html'); } } diff --git a/resources/js/stimulus/focus-on-connect-controller.js b/resources/js/stimulus/focus-on-connect-controller.js new file mode 100644 index 0000000..ccff33e --- /dev/null +++ b/resources/js/stimulus/focus-on-connect-controller.js @@ -0,0 +1,17 @@ +import { Controller } from '@hotwired/stimulus' + +// Moves focus into an element as soon as it lands in the DOM: only rendered +// on markup that arrives through a Turbo Stream (the review form's response), +// never on a normal page load. Focuses the first invalid field if there is +// one (or the first focusable thing inside it, e.g. the rating stars), +// otherwise the element itself (give it tabindex="-1"). +export default class extends Controller { + connect() { + const invalid = this.element.querySelector('[aria-invalid="true"]') + const target = invalid?.matches(FOCUSABLE) ? invalid : invalid?.querySelector(FOCUSABLE) + + ;(target ?? this.element).focus() + } +} + +const FOCUSABLE = 'input:not([type="hidden"]), textarea, select, button, [tabindex]' diff --git a/resources/js/stimulus/index.js b/resources/js/stimulus/index.js index de8ce1c..eac9cd3 100644 --- a/resources/js/stimulus/index.js +++ b/resources/js/stimulus/index.js @@ -10,6 +10,7 @@ import CartCountController from './cart-count-controller' import CarouselController from './carousel-controller' import CustomFieldUploadController from './custom-field-upload-controller' import DropdownController from './dropdown-controller' +import FocusOnConnectController from './focus-on-connect-controller' import FrameScrollController from './frame-scroll-controller' import NavSearchController from './nav-search-controller' import ProductFormController from './product-form-controller' @@ -28,6 +29,7 @@ export function registerControllers(application) { application.register('carousel', CarouselController) application.register('custom-field-upload', CustomFieldUploadController) application.register('dropdown', DropdownController) + application.register('focus-on-connect', FocusOnConnectController) application.register('frame-scroll', FrameScrollController) application.register('nav-search', NavSearchController) application.register('product-form', ProductFormController) diff --git a/resources/views/components/review-form.blade.php b/resources/views/components/review-form.blade.php index 31900a5..3e53107 100644 --- a/resources/views/components/review-form.blade.php +++ b/resources/views/components/review-form.blade.php @@ -1,28 +1,47 @@ -@props(['product']) +{{-- + Review form. Submitted through Turbo (data-turbo="true", Drive stays off + elsewhere): ProductController::storeReview() answers with Turbo Streams. + On a validation error it replaces this form (#product-review-form) with a + copy rendered with `messages` and the entered `values`, and `focus` so + focus-on-connect moves focus to the first invalid field. Never reads the + session (no old() or $errors), so the product page stays cacheable. +--}} +@props([ + 'productId', + 'messages' => null, // Illuminate\Support\MessageBag of validation errors + 'values' => [], + 'focus' => false, +]) -@php $oldRating = (int) old('rating', 0); @endphp +@php + $rating = (int) ($values['rating'] ?? 0); + $error = fn (string $field) => $messages?->first($field); +@endphp