Просмотр исходного кода

Add Select to edit, floating Ask the AI, theme switch and banner photo prep

- Select to edit: click or drag in the preview to pick a part, and the AI changes only that part
- Show in the preview: clicking a section name highlights it in the design
- Ask the AI is now a floating button that opens a chat panel
- Light and dark switch in the sidebar, above the user
- Banner photos are prepared in the background: small ones enlarged, big ones made lighter, saved as WebP
- New target column on store_generations (run php artisan migrate)
feature/dashboard
fahmisaad 8 часов назад
Родитель
Сommit
2476475269
30 измененных файлов: 2095 добавлений и 347 удалений
  1. 47
    41
      PROGRESS.md
  2. 12
    2
      app/Http/Controllers/HeroImageController.php
  3. 4
    0
      app/Http/Controllers/StoreController.php
  4. 20
    0
      app/Http/Controllers/StoreGenerationController.php
  5. 53
    0
      app/Jobs/PrepareBannerPhoto.php
  6. 1
    1
      app/Jobs/RunStoreGeneration.php
  7. 3
    1
      app/Models/StoreGeneration.php
  8. 78
    0
      app/StorePlan/Ai/PlanChanges.php
  9. 31
    2
      app/StorePlan/Ai/PlanPrompt.php
  10. 9
    3
      app/StorePlan/Ai/PlanWriter.php
  11. 142
    0
      app/StorePlan/BannerPhoto.php
  12. 25
    0
      database/migrations/2026_11_25_000001_add_target_to_store_generations_table.php
  13. 6
    0
      resources/css/app.css
  14. 1
    1
      resources/js/components/app-sidebar-header.tsx
  15. 2
    0
      resources/js/components/app-sidebar.tsx
  16. 7
    0
      resources/js/components/stores/bento-box.tsx
  17. 364
    95
      resources/js/components/stores/design-chat.tsx
  18. 11
    2
      resources/js/components/stores/featured-picker.tsx
  19. 14
    4
      resources/js/components/stores/hero-picker.tsx
  20. 13
    19
      resources/js/components/stores/layout-picker.tsx
  21. 252
    0
      resources/js/components/stores/preview-highlight.tsx
  22. 406
    0
      resources/js/components/stores/preview-picker.ts
  23. 21
    0
      resources/js/components/stores/section-names.ts
  24. 13
    0
      resources/js/components/stores/video-box.tsx
  25. 86
    0
      resources/js/components/theme-switch.tsx
  26. 277
    176
      resources/js/pages/stores/show.tsx
  27. 2
    0
      resources/js/storefront/renderer.tsx
  28. 2
    0
      resources/js/types/store.ts
  29. 32
    0
      tests/Feature/Stores/HeroImageTest.php
  30. 161
    0
      tests/Feature/Stores/SelectToEditTest.php

+ 47
- 41
PROGRESS.md Просмотреть файл

@@ -177,6 +177,8 @@ Changing from Claude to another AI model (or back) must be a settings change, no
177 177
 ### How chat commands work (added in Step 8)
178 178
 
179 179
 - The same "Ask the AI" box in the Design tab handles design changes and store changes. Each message counts as one AI edit.
180
+- **"Ask the AI" is a floating button (changed 2026-11-25):** a round button stays at the bottom right of the Design tab (`design-chat.tsx`). Clicking it opens a chat panel above it (400 wide; full width on phones) that does not cover the whole page, so the preview can be watched while the AI works. Newest message at the bottom, Enter sends, Shift + Enter for a new line, Escape closes. The button shows "AI is working…" while a request runs and a yellow dot when a change waits for the merchant's OK. Toasts move up on that page so they do not cover the button.
181
+- **Select to edit (added 2026-11-25):** a "Select to edit" button above the preview (also a link inside Ask the AI). The merchant clicks one thing (heading, text, photo, button) or drags a box over an area; a green outline with a tag ("Hero › Heading") shows what will be picked. The section is recognised from the page itself (`data-section` and `data-section-type` on each band; header and footer by tag), so it is instant, exact and free; no picture is sent to an AI. Ask the AI then opens with "Editing: Hero · Text …" and sends `target_section`, `target_label`, `target_detail`; the request saves them in `store_generations.target` and the chat history shows the tag. The AI is told what was selected and that "this" means it (`PlanPrompt::selectionNote`). Only that part can change: `PlanChanges::limitTo` keeps updates to the section, its removal (with menu link fixes) or a new section right after it, and drops theme, other sections, pages, header and footer. Store actions (prices, codes) still work. A whole-store wish ("make the colours black") is skipped and the reply says to ask without selecting. A section that no longer exists is refused. Counts as one AI edit as usual. Code: `components/stores/preview-picker.ts`. Tested with real DeepSeek: a mixed request changed only the heading; "shorten this" changed only the selected text.
180 182
 - Besides design changes, the AI may answer with `actions`: `create_product`, `update_product` (name, price, "was" price, stock, status, per variant for products with options), `create_discount`, `update_discount` (on/off, last day, number of uses) and `create_bundle`. At most 10 per message.
181 183
 - The AI gets the full product list (drafts, stock, choices), the discount codes and today's Malaysian date, so "until the end of the month" works.
182 184
 - `App\Commerce\ChatActions` checks each action with the same rules as the Products and Discounts forms (discount rules are shared through `DiscountCodeRules`). A wrong product, choice or code goes back to the AI once to fix, like a bad design answer.
@@ -199,8 +201,9 @@ Changing from Claude to another AI model (or back) must be a settings change, no
199 201
 
200 202
 - The hero section has 3 layouts: `image-full` (a photo across the whole width, words on top with a dark fade so they stay readable), `split` (words beside a tall photo) and `centered` (words only, as before).
201 203
 - The hero's `image` field names a photo: `upload:12` (a banner photo uploaded in the Design tab, saved in `store_images`) or `product:web-address-name` (that product's main photo). Null means automatic: the store's newest active product photo. With no photos at all, the hero shows a soft pattern in the store's colours.
202
-- The Design tab has a "Hero" box for each hero section: layout buttons, photo thumbnails (Automatic, uploads, product photos) and an upload button (JPG, PNG or WebP, up to 6 MB, at least 600 by 400 pixels). Uploading into a words-only hero switches it to "photo beside words" so the photo shows. Changes are part of the working design, so a live store shows them after "Publish changes".
204
+- The Design tab has a "Hero" box for each hero section: layout buttons, photo thumbnails (Automatic, uploads, product photos) and an upload button (JPG, PNG or WebP, up to 6 MB, at least 300 by 200 pixels; 600 by 400 until 2026-11-25). Uploading into a words-only hero switches it to "photo beside words" so the photo shows. Changes are part of the working design, so a live store shows them after "Publish changes".
203 205
 - The AI is told to prefer photo layouts and is given the list of photo names. A made-up photo name is sent back to it once to fix. A photo already in the design that was later deleted does not block chat edits; that hero just falls back to automatic.
206
+- **Banner photos are got ready in the background (added 2026-11-25):** after upload, the queued job `PrepareBannerPhoto` runs `App\StorePlan\BannerPhoto` (built-in GD, free): small photos are enlarged to 1600 pixels across with a light sharpen, photos with a side over 2400 are made smaller, phone photos are turned upright, and every photo is saved as WebP (quality 82), which also drops hidden details like GPS location. The design points to the photo by id, so it uses the new file by itself; the uploaded file is deleted. If the photo cannot be read, the upload stays in use. Chosen over an AI upscaler (sharper but paid, needs a new key and sends photos out); an AI upscaler can replace `resize()` later. Product photos are not processed yet.
204 207
 - Product cards show the product's second photo when the shopper points at the card. Placeholders show the first letter of the product in the store's heading font instead of plain shapes.
205 208
 
206 209
 ### How the announcement bar and trust row work (added in Step 9 part 2)
@@ -245,6 +248,7 @@ Changing from Claude to another AI model (or back) must be a settings change, no
245 248
 
246 249
 - The Design tab has a **Layouts** box (closed by default) listing every section with its layout in plain words; heroes stay in their own Hero box. `App\StorePlan\SectionLayouts` finds and changes them; only layouts of the section's own type are accepted.
247 250
 - The AI is told what each new layout looks like and when it suits, and can switch layouts by chat ("make the products slide sideways").
251
+- **Show in the preview (added 2026-11-25):** in the Design tab, a section's name (Layouts, Hero, Featured product, Video and Bento boxes) is a button with a small target icon. Clicking it brings the preview into view, scrolls the preview to that section (below the store's sticky header) and outlines it in green with its name for about 2.5 seconds. A section on another page (such as About us) opens that page first. Each section's band in the store carries `data-section="<id>"`; header and footer are found by their tags. Code: `resources/js/components/stores/preview-highlight.tsx`.
248 252
 
249 253
 ### How collections, bento and video work (added in Step 9 part 7)
250 254
 
@@ -292,11 +296,12 @@ Changing from Claude to another AI model (or back) must be a settings change, no
292 296
 - Only paid orders count as sales, on the Malaysian day they were paid. Sales are what shoppers paid, shipping included. Each range is compared with the same length of time just before it; "This month" with the same days of last month.
293 297
 - "Needs attention": orders to ship per store, products with 5 or fewer left (active, not bundles), unpublished design changes, stores designed but not published (several make one line), trial ending in 7 days or plan ended.
294 298
 - Before the first sale the page shows "Get your first sale" (create, design, products, publish) and zero boxes instead of empty charts. No AI note then.
295
-- The stores list moved to the sidebar as a tree: Overview, "Your stores" (Create store first, then each store with Design, Products, Orders with a to-ship badge, Discounts, Settings; green dot live, yellow draft), Account (Billing), and a plan box. Shared on every page as `sidebar` (`HandleInertiaRequests`). The starter kit's Repository and Documentation links are gone. Breadcrumbs say "Overview".
299
+- The stores list moved to the sidebar as a tree: Overview, "Your stores" (Create store first, then each store with Design, Products, Orders with a to-ship badge, Discounts, Settings; each store shows a coloured tile with its first letter, the same colour every time from its web address, with a green (live) or yellow (draft) dot on its corner, so stores can be told apart when the sidebar is folded), Account (Billing), and a plan box. Shared on every page as `sidebar` (`HandleInertiaRequests`). The starter kit's Repository and Documentation links are gone. Breadcrumbs say "Overview".
296 300
 - Store pulse (`app/Dashboard/StorePulse.php`, table `dashboard_pulses`): AI task `pulse` (DeepSeek by default, `AI_PULSE_PROVIDER`/`AI_PULSE_MODEL`, 400 tokens). Written once per Malaysian day per view (all stores, or one store) and saved, so refreshing costs nothing; it loads just after the page (deferred). Only numbers, store names and product names go to the AI, never shoppers' details (the privacy page says so).
297 301
 - "Write again" asks for a fresh note, 3 times a day in all (`AI_PULSE_DAILY_REWRITES`), shown under the button ("2 of 3 left today"). It does not count toward the plan's AI changes. A failed AI answer does not use a turn.
298 302
 - If the AI cannot answer, the note is written from the numbers instead. The buttons under the note (ship, restock, publish) are worked out by us from the numbers, not by the AI.
299 303
 - First real note: 442 tokens in, 63 out.
304
+- **Theme switch (added 2026-11-25):** Light and Dark sit in the sidebar footer, just above the user (`components/theme-switch.tsx`), one click each. With the sidebar folded it is one sun or moon button that flips between them. No System choice there: someone who never chose still follows their device, and the switch highlights how the page looks now. It uses the starter kit's `useAppearance` (browser storage and an `appearance` cookie); Settings → Appearance still offers System.
300 305
 
301 306
 ### Category guides for the AI (agreed 2026-11-17)
302 307
 
@@ -600,42 +605,43 @@ Moved into **Step 9 — Modern store design** on 2026-11-17.
600 605
 
601 606
 Add one line per work session: date, what was done, what is next.
602 607
 
603
-| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | Next                                                            |
604
-| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
605
-| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                                                                                                                                                                                                                                                                    | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
606
-| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                                                                                                                                                                                                                                                               | Step 2: store plan format, sections, renderer                   |
607
-| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                                                                                                                                                                                                                                                                        | Step 3: swappable AI layer and store generation                 |
608
-| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Step 3: swappable AI layer and store generation                 |
609
-| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                                                                                                                                                                                                                                                                | Add API keys, run the real test, then Step 4                    |
610
-| 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                                                                                                                                                                                                                                                                                                     | Real AI test, then Step 4                                       |
611
-| 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                                                                                                                                                                                                                                                                                                      | Merge into `main`, then Step 4: products                        |
612
-| 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                                                                                                                                                                                                                                                                                                            | Step 4 part 2: cart, Stripe checkout, orders, email             |
613
-| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                                                                                                                                                                                                                                                                                                  | Stripe checkout (needs test keys), orders, email                |
614
-| 2026-11-15 | Step 4 finished on branch `feature/commerce`: checkout with Stripe (test mode), orders for the merchant, order confirmation email. 133 tests pass. A real Stripe test payment worked end to end: order paid, stock lowered, email written to the log.                                                                                                                                                                                                                                                                                                                                  | Merge into `main`, then Step 5: publishing                      |
615
-| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Step 5: publishing                                              |
616
-| 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                                                                                                                                                                                                                                                                                                     | Step 5: publishing                                              |
617
-| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                                                                                                                                                                                                                                                                                                           | Step 5: publishing                                              |
618
-| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                                                                                                                                                                                                                                                                                                   | Step 6: subscription billing                                    |
619
-| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5.                                                                                                                                                                                                                                           | Merge into `main`, then Step 7                                  |
620
-| 2026-11-16 | Step 7 part 1 on branch `feature/malaysia-shipping`: store settings, flat shipping fees (west, east, free over), mark as shipped with tracking and email, WhatsApp buttons, Malay checkout messages, Malaysian phone check. Fixed live-store menu links on pages other than home (bug from Step 5). 178 tests pass; real Stripe test payment with shipping to Sabah worked.                                                                                                                                                                                                            | Merge, then Step 7 part 2 or Step 8                             |
621
-| 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek.                                                                                                                                                                                                    | Merge both branches, then Step 7 part 2 or Step 8               |
622
-| 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                                                                                                                                                                                                                             | Merge branches, then Step 7 part 2 or Step 8                    |
623
-| 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                                                                                                                                                                                                                         | Merge, then product variants                                    |
624
-| 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                                                                                                                                                                                                                              | Merge both branches, then bundles                               |
625
-| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                                                                                                                                                                                                                               | Merge, then chat commands                                       |
626
-| 2026-11-17 | Step 8 part 4 on branch `feature/chat-commands`: chat commands for products, discount codes and bundles, with Confirm and Cancel in the chat. Shared discount rules. Fixed a test that failed by chance (random stock). 233 tests pass; with real DeepSeek, "GLOW15 until end of month + 100ml to RM 52" was proposed, confirmed and saved; a product + bundle request was proposed correctly and cancelled.                                                                                                                                                                           | Merge; then automatic discounts, Step 7 part 2 or Step 9        |
627
-| 2026-11-17 | Step 8 part 5 on branch `feature/automatic-discounts`: automatic discounts (Discounts tab form, best-of-one rule with codes, cart nudge, product page note, order/Stripe/email name, chat command). Step 8 is done. 243 tests pass; real Stripe test payment with "Glow Week" (2 cleansers, −RM 8.40, total RM 83.60) worked, GLOW15 correctly won when typed; real DeepSeek proposed a sunscreen-only sale correctly (cancelled).                                                                                                                                                     | Merge; then Step 7 part 2 or Step 9                             |
628
-| 2026-11-17 | Chat commands can write product descriptions from the product name (same branch, `feature/automatic-discounts`). Real DeepSeek test found the AI guessing bundle contents, so bundle contents are now listed for it; second try was accurate. 244 tests pass.                                                                                                                                                                                                                                                                                                                          | Merge; then Step 7 part 2 or Step 9                             |
629
-| 2026-11-17 | Researched 2026 store design trends and published a comparison page. Added Step 9 — Modern store design (6 parts) and the category guides decision; "Before launch" is now Step 10.                                                                                                                                                                                                                                                                                                                                                                                                    | Step 9 part 1: photos first                                     |
630
-| 2026-11-18 | Step 9 part 1 on branch `redesign/part-1-photo-hero`: full-width and split photo heroes, hero photo upload and picker in the Design tab, automatic product photo, second photo on hover, letter placeholders, AI told about photos. 251 tests pass; checked in the browser at desktop and phone width with a test banner on Luna Skin.                                                                                                                                                                                                                                                 | Merge, then part 2                                              |
631
-| 2026-11-18 | Step 9 part 2 on branch `redesign/part-2-announcement-bar` (from part 1): announcement bar (automatic lines + merchant lines, Settings card) and trust row section with live facts. Plan checker now supports "required if" rules. 257 tests pass; real DeepSeek added a trust row to Luna Skin correctly; checked in the browser.                                                                                                                                                                                                                                                     | Commit; part 3 branches from part 2                             |
632
-| 2026-11-18 | Step 9 part 3 on branch `redesign/part-3-product-page` (from part 2): folding sections (form, chat with merge by title), trust points, sticky phone add-to-cart bar, pairs well with, phone menu, sticky photos. Found and fixed the sticky bar hiding under the header. 261 tests pass; real DeepSeek wrote a sensible "How to use" for the sunscreen (confirmed); checked at phone width.                                                                                                                                                                                            | Commit; part 4 branches from part 3                             |
633
-| 2026-11-19 | Step 9 part 4 on branch `redesign/part-4-style-options` (from part 3): style options, six ready-made looks with a Style box, 12 more fonts, gentle motion, AI style rules. Fixed fade-in hiding a section that was already partly on screen. "More layouts per section" moved to a new part 5; category guides are now part 6 and collections part 7. 266 tests pass; Bold look and a real DeepSeek "more premium and elegant" change both checked in the browser.                                                                                                                     | Commit; part 5 branches from part 4                             |
634
-| 2026-11-19 | Step 9 part 5 on branch `redesign/part-5-section-layouts` (from part 4): 7 new section layouts (products carousel and large, featured stacked, about statement, reviews wall, FAQ cards, newsletter split, footer columns) and a Layouts box. 270 tests pass; every layout checked in the browser on Luna Skin; long About statements now shown a step smaller.                                                                                                                                                                                                                        | Commit; part 6 branches from part 5                             |
635
-| 2026-11-21 | Step 9 part 6 on branch `redesign/part-6-category-guides` (from part 5): category design guides and "looks to avoid" for the AI. 275 tests pass; generated two real test stores with Claude Sonnet (Dapur Mak Teh, food; Seri Anggun, fashion) and they came out clearly different.                                                                                                                                                                                                                                                                                                    | Commit; then part 7 or merge                                    |
636
-| 2026-11-21 | Decided to keep `main` and the redesign apart for comparison. Split reviews out as part 8. Step 9 part 7 on branch `redesign/part-7-collections-bento-video` (from part 6): collections (Products tab, chat, pages, links), shop by, bento and video sections, with AI checks for collection names and video addresses. 282 tests pass; real DeepSeek created two collections for Luna Skin (confirmed) and added shop by and bento correctly; checked in the browser.                                                                                                                 | Commit; part 8 branches from part 7                             |
637
-| 2026-11-22 | Added Video and Bento boxes to the Design tab (same branch, part 7), so both can be added and edited without chat. The merchant added a real YouTube video to Luna Skin by chat; it plays in the preview. 286 tests pass.                                                                                                                                                                                                                                                                                                                                                              | Commit part 7; then part 8                                      |
638
-| 2026-11-22 | Part 7 committed on `redesign/part-7-collections-bento-video`. Part 8 (real reviews) put on hold by the merchant.                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Choose next step                                                |
639
-| 2026-11-22 | Built our own home page on branch `feature/homepage`: content outline like afilink.app with our own look, real plan prices, store-name box that fills the Create store form. 288 tests pass; checked on desktop and phone. Then made the hero picture move like afilink's (pinned scroll on wide screens, plays once on phones, floating tags), fixed tags covering text, added hover lift on the hero pieces and pricing cards, made the store and bubble float, and added six more animations (fade-up, typing bubble, playing chat, changing styles, steps line, shop-types strip). | Commit; choose next step                                        |
640
-| 2026-11-22 | Home page committed. Added the privacy policy (`/privacy`) and terms of service (`/terms`) for Malaysian law, naming the AI companies from the AI settings, linked from the home footer and sign-up. 293 tests pass; checked on desktop and phone.                                                                                                                                                                                                                                                                                                                                     | Commit; lawyer check; choose next                               |
641
-| 2026-11-22 | Redesigned the dashboard on branch `feature/dashboard` (picked from three trend designs: AI note on top of colourful boxes). Stats with filters, needs attention, sales chart, store tree in the sidebar, daily Store pulse from DeepSeek saved per day with 3 "Write again" a day, first-sale steps for new merchants. 303 tests pass; checked on desktop, phone and dark mode.                                                                                                                                                                                                       | Commit; choose next step                                        |
608
+| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | Next                                                            |
609
+| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
610
+| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
611
+| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                                                                                                                                                                                                                                                                                                                                               | Step 2: store plan format, sections, renderer                   |
612
+| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                                                                                                                                                                                                                                                                                                                                                        | Step 3: swappable AI layer and store generation                 |
613
+| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Step 3: swappable AI layer and store generation                 |
614
+| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                                                                                                                                                                                                                                                                                                                                                | Add API keys, run the real test, then Step 4                    |
615
+| 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | Real AI test, then Step 4                                       |
616
+| 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Merge into `main`, then Step 4: products                        |
617
+| 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                                                                                                                                                                                                                                                                                                                                                                                            | Step 4 part 2: cart, Stripe checkout, orders, email             |
618
+| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Stripe checkout (needs test keys), orders, email                |
619
+| 2026-11-15 | Step 4 finished on branch `feature/commerce`: checkout with Stripe (test mode), orders for the merchant, order confirmation email. 133 tests pass. A real Stripe test payment worked end to end: order paid, stock lowered, email written to the log.                                                                                                                                                                                                                                                                                                                                                                                                                  | Merge into `main`, then Step 5: publishing                      |
620
+| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Step 5: publishing                                              |
621
+| 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                                                                                                                                                                                                                                                                                                                                                                                     | Step 5: publishing                                              |
622
+| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                                                                                                                                                                                                                                                                                                                                                                                           | Step 5: publishing                                              |
623
+| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                                                                                                                                                                                                                                                                                                                                                                                   | Step 6: subscription billing                                    |
624
+| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5.                                                                                                                                                                                                                                                                                                                           | Merge into `main`, then Step 7                                  |
625
+| 2026-11-16 | Step 7 part 1 on branch `feature/malaysia-shipping`: store settings, flat shipping fees (west, east, free over), mark as shipped with tracking and email, WhatsApp buttons, Malay checkout messages, Malaysian phone check. Fixed live-store menu links on pages other than home (bug from Step 5). 178 tests pass; real Stripe test payment with shipping to Sabah worked.                                                                                                                                                                                                                                                                                            | Merge, then Step 7 part 2 or Step 8                             |
626
+| 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek.                                                                                                                                                                                                                                                                                    | Merge both branches, then Step 7 part 2 or Step 8               |
627
+| 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Merge branches, then Step 7 part 2 or Step 8                    |
628
+| 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                                                                                                                                                                                                                                                                                                         | Merge, then product variants                                    |
629
+| 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                                                                                                                                                                                                                                                                                                              | Merge both branches, then bundles                               |
630
+| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                                                                                                                                                                                                                                                                                                               | Merge, then chat commands                                       |
631
+| 2026-11-17 | Step 8 part 4 on branch `feature/chat-commands`: chat commands for products, discount codes and bundles, with Confirm and Cancel in the chat. Shared discount rules. Fixed a test that failed by chance (random stock). 233 tests pass; with real DeepSeek, "GLOW15 until end of month + 100ml to RM 52" was proposed, confirmed and saved; a product + bundle request was proposed correctly and cancelled.                                                                                                                                                                                                                                                           | Merge; then automatic discounts, Step 7 part 2 or Step 9        |
632
+| 2026-11-17 | Step 8 part 5 on branch `feature/automatic-discounts`: automatic discounts (Discounts tab form, best-of-one rule with codes, cart nudge, product page note, order/Stripe/email name, chat command). Step 8 is done. 243 tests pass; real Stripe test payment with "Glow Week" (2 cleansers, −RM 8.40, total RM 83.60) worked, GLOW15 correctly won when typed; real DeepSeek proposed a sunscreen-only sale correctly (cancelled).                                                                                                                                                                                                                                     | Merge; then Step 7 part 2 or Step 9                             |
633
+| 2026-11-17 | Chat commands can write product descriptions from the product name (same branch, `feature/automatic-discounts`). Real DeepSeek test found the AI guessing bundle contents, so bundle contents are now listed for it; second try was accurate. 244 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                          | Merge; then Step 7 part 2 or Step 9                             |
634
+| 2026-11-17 | Researched 2026 store design trends and published a comparison page. Added Step 9 — Modern store design (6 parts) and the category guides decision; "Before launch" is now Step 10.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Step 9 part 1: photos first                                     |
635
+| 2026-11-18 | Step 9 part 1 on branch `redesign/part-1-photo-hero`: full-width and split photo heroes, hero photo upload and picker in the Design tab, automatic product photo, second photo on hover, letter placeholders, AI told about photos. 251 tests pass; checked in the browser at desktop and phone width with a test banner on Luna Skin.                                                                                                                                                                                                                                                                                                                                 | Merge, then part 2                                              |
636
+| 2026-11-18 | Step 9 part 2 on branch `redesign/part-2-announcement-bar` (from part 1): announcement bar (automatic lines + merchant lines, Settings card) and trust row section with live facts. Plan checker now supports "required if" rules. 257 tests pass; real DeepSeek added a trust row to Luna Skin correctly; checked in the browser.                                                                                                                                                                                                                                                                                                                                     | Commit; part 3 branches from part 2                             |
637
+| 2026-11-18 | Step 9 part 3 on branch `redesign/part-3-product-page` (from part 2): folding sections (form, chat with merge by title), trust points, sticky phone add-to-cart bar, pairs well with, phone menu, sticky photos. Found and fixed the sticky bar hiding under the header. 261 tests pass; real DeepSeek wrote a sensible "How to use" for the sunscreen (confirmed); checked at phone width.                                                                                                                                                                                                                                                                            | Commit; part 4 branches from part 3                             |
638
+| 2026-11-19 | Step 9 part 4 on branch `redesign/part-4-style-options` (from part 3): style options, six ready-made looks with a Style box, 12 more fonts, gentle motion, AI style rules. Fixed fade-in hiding a section that was already partly on screen. "More layouts per section" moved to a new part 5; category guides are now part 6 and collections part 7. 266 tests pass; Bold look and a real DeepSeek "more premium and elegant" change both checked in the browser.                                                                                                                                                                                                     | Commit; part 5 branches from part 4                             |
639
+| 2026-11-19 | Step 9 part 5 on branch `redesign/part-5-section-layouts` (from part 4): 7 new section layouts (products carousel and large, featured stacked, about statement, reviews wall, FAQ cards, newsletter split, footer columns) and a Layouts box. 270 tests pass; every layout checked in the browser on Luna Skin; long About statements now shown a step smaller.                                                                                                                                                                                                                                                                                                        | Commit; part 6 branches from part 5                             |
640
+| 2026-11-21 | Step 9 part 6 on branch `redesign/part-6-category-guides` (from part 5): category design guides and "looks to avoid" for the AI. 275 tests pass; generated two real test stores with Claude Sonnet (Dapur Mak Teh, food; Seri Anggun, fashion) and they came out clearly different.                                                                                                                                                                                                                                                                                                                                                                                    | Commit; then part 7 or merge                                    |
641
+| 2026-11-21 | Decided to keep `main` and the redesign apart for comparison. Split reviews out as part 8. Step 9 part 7 on branch `redesign/part-7-collections-bento-video` (from part 6): collections (Products tab, chat, pages, links), shop by, bento and video sections, with AI checks for collection names and video addresses. 282 tests pass; real DeepSeek created two collections for Luna Skin (confirmed) and added shop by and bento correctly; checked in the browser.                                                                                                                                                                                                 | Commit; part 8 branches from part 7                             |
642
+| 2026-11-22 | Added Video and Bento boxes to the Design tab (same branch, part 7), so both can be added and edited without chat. The merchant added a real YouTube video to Luna Skin by chat; it plays in the preview. 286 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                              | Commit part 7; then part 8                                      |
643
+| 2026-11-22 | Part 7 committed on `redesign/part-7-collections-bento-video`. Part 8 (real reviews) put on hold by the merchant.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Choose next step                                                |
644
+| 2026-11-22 | Built our own home page on branch `feature/homepage`: content outline like afilink.app with our own look, real plan prices, store-name box that fills the Create store form. 288 tests pass; checked on desktop and phone. Then made the hero picture move like afilink's (pinned scroll on wide screens, plays once on phones, floating tags), fixed tags covering text, added hover lift on the hero pieces and pricing cards, made the store and bubble float, and added six more animations (fade-up, typing bubble, playing chat, changing styles, steps line, shop-types strip).                                                                                 | Commit; choose next step                                        |
645
+| 2026-11-22 | Home page committed. Added the privacy policy (`/privacy`) and terms of service (`/terms`) for Malaysian law, naming the AI companies from the AI settings, linked from the home footer and sign-up. 293 tests pass; checked on desktop and phone.                                                                                                                                                                                                                                                                                                                                                                                                                     | Commit; lawyer check; choose next                               |
646
+| 2026-11-22 | Redesigned the dashboard on branch `feature/dashboard` (picked from three trend designs: AI note on top of colourful boxes). Stats with filters, needs attention, sales chart, store tree in the sidebar, daily Store pulse from DeepSeek saved per day with 3 "Write again" a day, first-sale steps for new merchants. 303 tests pass; checked on desktop, phone and dark mode.                                                                                                                                                                                                                                                                                       | Commit; choose next step                                        |
647
+| 2026-11-25 | On `feature/dashboard` (not committed): store letter tiles in the sidebar; researched courier prices and APIs (J&T, Pos Laju, GDEX, DHL eCommerce): only GDEX has a public developer site, the others need a sales contract, so EasyParcel stays the plan; "Show in the preview": clicking a section name in the Design tab scrolls the preview to it and outlines it; banner photos now accepted from 300×200 and got ready in the background (enlarged, shrunk, upright, WebP); "Ask the AI" is now a floating button that opens a chat panel; Light/Dark switch above the user in the sidebar; Select to edit (click or drag in the preview, Ask the AI changes only that part). 310 tests pass; checked in the browser on desktop and phone preview. | Commit, then EasyParcel demo key                                |

+ 12
- 2
app/Http/Controllers/HeroImageController.php Просмотреть файл

@@ -2,7 +2,9 @@
2 2
 
3 3
 namespace App\Http\Controllers;
4 4
 
5
+use App\Jobs\PrepareBannerPhoto;
5 6
 use App\Models\Store;
7
+use App\StorePlan\BannerPhoto;
6 8
 use App\StorePlan\HeroImages;
7 9
 use App\StorePlan\PlanSchema;
8 10
 use App\StorePlan\PlanValidator;
@@ -46,14 +48,22 @@ class HeroImageController extends Controller
46 48
         $store = $this->ownedStoreWithHero($request, $slug, $sectionId);
47 49
 
48 50
         $request->validate([
49
-            'photo' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:6144', 'dimensions:min_width=600,min_height=400'],
51
+            'photo' => [
52
+                'required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:6144',
53
+                'dimensions:min_width='.BannerPhoto::MIN_WIDTH.',min_height='.BannerPhoto::MIN_HEIGHT.',max_width=8000,max_height=8000',
54
+            ],
50 55
         ], [
51 56
             'photo.max' => __('The photo must be 6 MB or smaller.'),
52 57
             'photo.mimes' => __('Use a JPG, PNG or WebP photo.'),
53
-            'photo.dimensions' => __('Use a photo at least 600 pixels wide and 400 high, so it stays sharp.'),
58
+            'photo.dimensions' => __('Use a photo at least :width pixels wide and :height high, and no bigger than 8000 pixels.', [
59
+                'width' => BannerPhoto::MIN_WIDTH,
60
+                'height' => BannerPhoto::MIN_HEIGHT,
61
+            ]),
54 62
         ]);
55 63
 
56 64
         $image = $store->images()->create(['path' => $request->file('photo')->store("stores/{$store->id}", 'public')]);
65
+        // Enlarged, shrunk or turned upright in the background. The photo shows as uploaded until then.
66
+        PrepareBannerPhoto::dispatch($image);
57 67
         $current = collect(HeroImages::sections($store->plan ?? []))->firstWhere('section_id', $sectionId);
58 68
         $variant = ($current['variant'] ?? 'centered') === 'centered' ? 'split' : $current['variant'];
59 69
 

+ 4
- 0
app/Http/Controllers/StoreController.php Просмотреть файл

@@ -176,6 +176,10 @@ class StoreController extends Controller
176 176
             'type' => $generation->type->value,
177 177
             'status' => $generation->status->value,
178 178
             'instruction' => $generation->instruction,
179
+            // The part selected in the preview, shown as a tag above the request.
180
+            'target' => $generation->target !== null
181
+                ? ['label' => $generation->target['label'], 'detail' => $generation->target['detail'] ?? null]
182
+                : null,
179 183
             'reply' => $generation->reply,
180 184
             'changed' => $generation->changed,
181 185
             // Store changes waiting for (or given) the merchant's OK, in plain sentences.

+ 20
- 0
app/Http/Controllers/StoreGenerationController.php Просмотреть файл

@@ -9,6 +9,7 @@ use App\Enums\GenerationType;
9 9
 use App\Jobs\RunStoreGeneration;
10 10
 use App\Models\Store;
11 11
 use App\Models\StoreGeneration;
12
+use App\StorePlan\Ai\PlanChanges;
12 13
 use Illuminate\Http\RedirectResponse;
13 14
 use Illuminate\Http\Request;
14 15
 use Illuminate\Validation\ValidationException;
@@ -58,8 +59,26 @@ class StoreGenerationController extends Controller
58 59
 
59 60
         $validated = $request->validate([
60 61
             'instruction' => ['required', 'string', 'min:3', 'max:500'],
62
+            // The part of the store the merchant selected in the preview (optional).
63
+            'target_section' => ['nullable', 'string', 'max:64'],
64
+            'target_label' => ['nullable', 'required_with:target_section', 'string', 'max:80'],
65
+            'target_detail' => ['nullable', 'string', 'max:300'],
61 66
         ]);
62 67
 
68
+        $target = null;
69
+
70
+        if (filled($validated['target_section'] ?? null)) {
71
+            if (PlanChanges::findSection($store->plan, $validated['target_section']) === null) {
72
+                return back()->withErrors(['instruction' => __('That part of your store has changed. Please select it again.')]);
73
+            }
74
+
75
+            $target = [
76
+                'section' => $validated['target_section'],
77
+                'label' => $validated['target_label'],
78
+                'detail' => $validated['target_detail'] ?? null,
79
+            ];
80
+        }
81
+
63 82
         if ($this->isBusy($store)) {
64 83
             return $this->refuse($store, __('Your store is already being worked on. Please wait for it to finish.'));
65 84
         }
@@ -73,6 +92,7 @@ class StoreGenerationController extends Controller
73 92
         $this->start($request, $store, [
74 93
             'type' => GenerationType::Edit,
75 94
             'instruction' => $validated['instruction'],
95
+            'target' => $target,
76 96
         ]);
77 97
 
78 98
         return to_route('stores.show', $store->slug);

+ 53
- 0
app/Jobs/PrepareBannerPhoto.php Просмотреть файл

@@ -0,0 +1,53 @@
1
+<?php
2
+
3
+namespace App\Jobs;
4
+
5
+use App\Models\StoreImage;
6
+use App\StorePlan\BannerPhoto;
7
+use Illuminate\Contracts\Queue\ShouldQueue;
8
+use Illuminate\Foundation\Queue\Queueable;
9
+use Illuminate\Support\Facades\Log;
10
+use Illuminate\Support\Facades\Storage;
11
+use Throwable;
12
+
13
+/**
14
+ * Runs after a banner photo is uploaded: enlarges small photos, shrinks huge ones, and saves WebP
15
+ * (see BannerPhoto). The design points to the photo by its id, so it picks up the new file by itself.
16
+ * If anything goes wrong, the photo as uploaded stays in use.
17
+ */
18
+class PrepareBannerPhoto implements ShouldQueue
19
+{
20
+    use Queueable;
21
+
22
+    public int $tries = 2;
23
+
24
+    public int $timeout = 120;
25
+
26
+    /** The merchant may delete the photo before this runs. Then there is nothing to do. */
27
+    public bool $deleteWhenMissingModels = true;
28
+
29
+    public function __construct(public StoreImage $image) {}
30
+
31
+    public function handle(BannerPhoto $banner): void
32
+    {
33
+        $original = $this->image->path;
34
+
35
+        if (str_ends_with($original, '.webp') && str_starts_with(basename($original), 'banner-')) {
36
+            return; // Already done.
37
+        }
38
+
39
+        try {
40
+            $prepared = $banner->prepare($original);
41
+        } catch (Throwable $error) {
42
+            Log::warning('Banner photo could not be prepared; the uploaded photo stays in use.', [
43
+                'store_image_id' => $this->image->id,
44
+                'error' => $error->getMessage(),
45
+            ]);
46
+
47
+            return;
48
+        }
49
+
50
+        $this->image->update(['path' => $prepared]);
51
+        Storage::disk('public')->delete($original);
52
+    }
53
+}

+ 1
- 1
app/Jobs/RunStoreGeneration.php Просмотреть файл

@@ -43,7 +43,7 @@ class RunStoreGeneration implements ShouldQueue
43 43
             $store = $generation->store;
44 44
 
45 45
             $result = $generation->type === GenerationType::Edit
46
-                ? $writer->edit($store, (string) $generation->instruction)
46
+                ? $writer->edit($store, (string) $generation->instruction, $generation->target)
47 47
                 : $writer->generate($store);
48 48
 
49 49
             // Compare the design before and after, so the app (not the AI's reply) says whether anything changed.

+ 3
- 1
app/Models/StoreGeneration.php Просмотреть файл

@@ -28,6 +28,7 @@ use Illuminate\Support\Carbon;
28 28
  * @property list<array{type: string, input: array<string, mixed>, summary: string}>|null $actions Store changes waiting for the merchant's OK
29 29
  * @property string|null $actions_status "pending", "confirmed" or "cancelled"
30 30
  * @property string|null $error
31
+ * @property array{section: string, label: string, detail: string|null}|null $target The part the merchant selected in the preview, if any.
31 32
  * @property string|null $provider
32 33
  * @property string|null $model
33 34
  * @property int $input_tokens
@@ -38,7 +39,7 @@ use Illuminate\Support\Carbon;
38 39
  * @property Carbon|null $updated_at
39 40
  * @property-read Store $store
40 41
  */
41
-#[Fillable(['user_id', 'type', 'status', 'is_regeneration', 'instruction'])]
42
+#[Fillable(['user_id', 'type', 'status', 'is_regeneration', 'instruction', 'target'])]
42 43
 class StoreGeneration extends Model
43 44
 {
44 45
     /** @use HasFactory<StoreGenerationFactory> */
@@ -104,6 +105,7 @@ class StoreGeneration extends Model
104 105
             'is_regeneration' => 'boolean',
105 106
             'changed' => 'boolean',
106 107
             'actions' => 'array',
108
+            'target' => 'array',
107 109
             'started_at' => 'datetime',
108 110
             'finished_at' => 'datetime',
109 111
         ];

+ 78
- 0
app/StorePlan/Ai/PlanChanges.php Просмотреть файл

@@ -17,6 +17,84 @@ final class PlanChanges
17 17
      * @param  array<string, mixed>  $changes
18 18
      * @return array<string, mixed>
19 19
      */
20
+    /**
21
+     * Where a section is: its type and page. Header and footer count as sections with no page.
22
+     *
23
+     * @param  array<string, mixed>|null  $plan
24
+     * @return array{type: string, page: string|null}|null Null when the plan has no such section.
25
+     */
26
+    public static function findSection(?array $plan, string $sectionId): ?array
27
+    {
28
+        if ($plan === null) {
29
+            return null;
30
+        }
31
+
32
+        if (in_array($sectionId, ['header', 'footer'], true)) {
33
+            return is_array($plan[$sectionId] ?? null) ? ['type' => $sectionId, 'page' => null] : null;
34
+        }
35
+
36
+        foreach ($plan['pages'] ?? [] as $page) {
37
+            foreach ($page['sections'] ?? [] as $section) {
38
+                if (is_array($section) && ($section['id'] ?? null) === $sectionId) {
39
+                    return ['type' => (string) ($section['type'] ?? ''), 'page' => (string) ($page['id'] ?? '')];
40
+                }
41
+            }
42
+        }
43
+
44
+        return null;
45
+    }
46
+
47
+    /**
48
+     * Keep only the changes to one selected part of the store, so a request about "this" can never
49
+     * touch the rest: updating the section, removing it (with the menu links that pointed to it),
50
+     * or adding a new section right after it. The reply and store actions are kept as they are.
51
+     *
52
+     * @param  array<string, mixed>  $changes
53
+     * @return array<string, mixed>
54
+     */
55
+    public static function limitTo(array $changes, string $sectionId): array
56
+    {
57
+        $kept = array_intersect_key($changes, array_flip(['reply', 'actions']));
58
+
59
+        if (in_array($sectionId, ['header', 'footer'], true)) {
60
+            if (is_array($changes[$sectionId] ?? null)) {
61
+                $kept[$sectionId] = $changes[$sectionId];
62
+            }
63
+
64
+            return $kept;
65
+        }
66
+
67
+        $updates = array_values(array_filter(
68
+            self::list($changes, 'update'),
69
+            fn ($update) => is_array($update) && ($update['id'] ?? null) === $sectionId,
70
+        ));
71
+        $additions = array_values(array_filter(
72
+            self::list($changes, 'add'),
73
+            fn ($addition) => is_array($addition) && ($addition['after'] ?? null) === $sectionId,
74
+        ));
75
+
76
+        if ($updates !== []) {
77
+            $kept['update'] = $updates;
78
+        }
79
+
80
+        if ($additions !== []) {
81
+            $kept['add'] = $additions;
82
+        }
83
+
84
+        if (in_array($sectionId, self::list($changes, 'remove'), true)) {
85
+            $kept['remove'] = [$sectionId];
86
+
87
+            // Links to the removed section may need fixing in the menus.
88
+            foreach (['header', 'footer'] as $part) {
89
+                if (is_array($changes[$part] ?? null)) {
90
+                    $kept[$part] = $changes[$part];
91
+                }
92
+            }
93
+        }
94
+
95
+        return $kept;
96
+    }
97
+
20 98
     public static function apply(array $plan, array $changes): array
21 99
     {
22 100
         // Theme: merge only the parts that were given.

+ 31
- 2
app/StorePlan/Ai/PlanPrompt.php Просмотреть файл

@@ -14,6 +14,7 @@ use App\Models\Store;
14 14
 use App\StorePlan\HeroImages;
15 15
 use App\StorePlan\PlanSchema;
16 16
 use App\StorePlan\SamplePlan;
17
+use Illuminate\Support\Str;
17 18
 
18 19
 /**
19 20
  * The words we send to the AI. They belong to us and work with any provider.
@@ -394,15 +395,16 @@ final class PlanPrompt
394 395
     /**
395 396
      * @param  array<string, mixed>  $plan
396 397
      */
397
-    public static function editPrompt(array $plan, string $instruction, string $products = ''): string
398
+    public static function editPrompt(array $plan, string $instruction, string $products = '', ?array $target = null): string
398 399
     {
399 400
         $json = json_encode($plan, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
401
+        $selection = $target !== null ? self::selectionNote($target) : '';
400 402
 
401 403
         return <<<TEXT
402 404
         Current store plan (JSON):
403 405
         {$json}
404 406
         {$products}
405
-
407
+        {$selection}
406 408
         The merchant's request:
407 409
         """
408 410
         {$instruction}
@@ -410,6 +412,33 @@ final class PlanPrompt
410 412
         TEXT;
411 413
     }
412 414
 
415
+    /**
416
+     * The part of the store the merchant selected in the preview, and the rule to change only that.
417
+     *
418
+     * @param  array{section: string, label: string, detail: string|null, type: string, page: string|null}  $target
419
+     */
420
+    public static function selectionNote(array $target): string
421
+    {
422
+        $id = $target['section'];
423
+        $where = in_array($id, ['header', 'footer'], true)
424
+            ? "the store's {$id}"
425
+            : "section id: \"{$id}\" (type {$target['type']}, on page \"{$target['page']}\")";
426
+        $detail = filled($target['detail'])
427
+            ? "\nInside it they selected: ".Str::limit((string) $target['detail'], 300)
428
+            : '';
429
+        $allowed = in_array($id, ['header', 'footer'], true)
430
+            ? "change only \"{$id}\""
431
+            : "change only this section: \"update\" it, \"remove\" it, or \"add\" a new section right after it (\"after\": \"{$id}\")";
432
+
433
+        return <<<TEXT
434
+
435
+        The merchant selected a part of their store in the preview before writing the request.
436
+        Selected {$where}{$detail}
437
+        Words like "this" or "here" in the request mean that part. {$allowed}. Do not change the theme, other sections, pages, header or footer: those changes are thrown away. Do every part of the request that is about the selected part. If a part of the request would change the whole store, such as the colours or fonts, skip only that part and say in "reply" that it changes the whole store, so they can ask for it again without selecting. Your answer must contain every change your "reply" mentions. Store actions (products, codes, bundles) are still allowed.
438
+
439
+        TEXT;
440
+    }
441
+
413 442
     /**
414 443
      * Sent when the first answer was rejected, so the AI can correct it once.
415 444
      *

+ 9
- 3
app/StorePlan/Ai/PlanWriter.php Просмотреть файл

@@ -47,7 +47,10 @@ class PlanWriter
47 47
     /**
48 48
      * @throws AiException
49 49
      */
50
-    public function edit(Store $store, string $instruction): PlanResult
50
+    /**
51
+     * @param  array{section: string, label: string, detail: string|null}|null  $target  The part the merchant selected in the preview.
52
+     */
53
+    public function edit(Store $store, string $instruction, ?array $target = null): PlanResult
51 54
     {
52 55
         $plan = $store->plan;
53 56
 
@@ -55,12 +58,15 @@ class PlanWriter
55 58
             throw new AiException('This store has no design to edit yet.', AiException::SETUP);
56 59
         }
57 60
 
61
+        $selected = $target !== null ? PlanChanges::findSection($plan, $target['section']) : null;
62
+
58 63
         return $this->askAndCheck(
59 64
             task: 'edit',
60 65
             system: PlanPrompt::editSystem(),
61
-            prompt: PlanPrompt::editPrompt($plan, $instruction, PlanPrompt::catalogue($store)),
66
+            prompt: PlanPrompt::editPrompt($plan, $instruction, PlanPrompt::catalogue($store), $target !== null && $selected !== null ? [...$target, ...$selected] : null),
62 67
             build: fn (array $answer) => [
63
-                PlanChanges::apply($plan, $answer),
68
+                // With a part selected, only changes to that part are kept, whatever the AI sent.
69
+                PlanChanges::apply($plan, $selected !== null ? PlanChanges::limitTo($answer, $target['section']) : $answer),
64 70
                 is_string($answer['reply'] ?? null) ? Str::limit(trim($answer['reply']), 300) : null,
65 71
                 // Checked now, so a wrong product or code goes back to the AI to fix. Done only once confirmed.
66 72
                 ChatActions::check($store, $answer['actions'] ?? null),

+ 142
- 0
app/StorePlan/BannerPhoto.php Просмотреть файл

@@ -0,0 +1,142 @@
1
+<?php
2
+
3
+namespace App\StorePlan;
4
+
5
+use GdImage;
6
+use Illuminate\Support\Facades\Storage;
7
+use Illuminate\Support\Str;
8
+use RuntimeException;
9
+
10
+/**
11
+ * Gets an uploaded banner photo ready for a wide hero, so merchants can upload what they have.
12
+ *
13
+ * - Small photos are enlarged to 1600 pixels across and lightly sharpened.
14
+ * - Very large photos are made smaller (longest side 2400), so the store loads fast.
15
+ * - Phone photos are turned the right way up.
16
+ * - Everything is saved as WebP. Saving again also drops hidden details such as the GPS location.
17
+ *
18
+ * Built into PHP (GD), so it costs nothing. An AI upscaler could replace `resize()` later.
19
+ */
20
+class BannerPhoto
21
+{
22
+    /** The smallest photo we accept. Enlarging more than about 5 times looks too soft. */
23
+    public const MIN_WIDTH = 300;
24
+
25
+    public const MIN_HEIGHT = 200;
26
+
27
+    /** Small photos are enlarged to this width. */
28
+    public const TARGET_WIDTH = 1600;
29
+
30
+    /** No side is ever longer than this. */
31
+    public const MAX_SIDE = 2400;
32
+
33
+    public const QUALITY = 82;
34
+
35
+    /**
36
+     * Prepare the photo at this path on the "public" disk and save it as a new WebP file.
37
+     * Returns the new file's path. The original file is left for the caller to remove.
38
+     */
39
+    public function prepare(string $path): string
40
+    {
41
+        $disk = Storage::disk('public');
42
+        $contents = $disk->get($path);
43
+
44
+        if ($contents === null) {
45
+            throw new RuntimeException("Banner photo {$path} is missing.");
46
+        }
47
+
48
+        // A 6 MB photo can be very large once opened, so give GD room for this one job.
49
+        ini_set('memory_limit', '512M');
50
+
51
+        $image = @imagecreatefromstring($contents);
52
+
53
+        if (! $image instanceof GdImage) {
54
+            throw new RuntimeException("Banner photo {$path} could not be opened.");
55
+        }
56
+
57
+        $image = $this->turnUpright($image, $contents);
58
+        $image = $this->resize($image);
59
+
60
+        ob_start();
61
+        imagewebp($image, null, self::QUALITY);
62
+        $webp = (string) ob_get_clean();
63
+
64
+        $folder = dirname($path);
65
+        $newPath = ($folder === '.' ? '' : $folder.'/').'banner-'.Str::random(24).'.webp';
66
+        $disk->put($newPath, $webp);
67
+
68
+        return $newPath;
69
+    }
70
+
71
+    /**
72
+     * The size the photo will be saved at.
73
+     *
74
+     * @return array{0: int, 1: int}
75
+     */
76
+    public static function targetSize(int $width, int $height): array
77
+    {
78
+        $scale = min(
79
+            max(1, self::TARGET_WIDTH / $width),
80
+            self::MAX_SIDE / max($width, $height),
81
+        );
82
+
83
+        return [(int) round($width * $scale), (int) round($height * $scale)];
84
+    }
85
+
86
+    private function resize(GdImage $image): GdImage
87
+    {
88
+        $width = imagesx($image);
89
+        $height = imagesy($image);
90
+        [$newWidth, $newHeight] = self::targetSize($width, $height);
91
+
92
+        if ($newWidth === $width && $newHeight === $height) {
93
+            return $image;
94
+        }
95
+
96
+        $resized = imagecreatetruecolor($newWidth, $newHeight);
97
+        // Keep see-through parts of PNG and WebP photos.
98
+        imagealphablending($resized, false);
99
+        imagesavealpha($resized, true);
100
+        imagefill($resized, 0, 0, imagecolorallocatealpha($resized, 0, 0, 0, 127));
101
+        imagecopyresampled($resized, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
102
+
103
+        // Enlarged photos turn a little soft, so sharpen them gently.
104
+        if ($newWidth > $width * 1.05) {
105
+            imageconvolution($resized, [[-1, -1, -1], [-1, 20, -1], [-1, -1, -1]], 12, 0);
106
+        }
107
+
108
+        return $resized;
109
+    }
110
+
111
+    /**
112
+     * Phones often save photos sideways with a note saying which way is up. Follow that note.
113
+     */
114
+    private function turnUpright(GdImage $image, string $contents): GdImage
115
+    {
116
+        if (! function_exists('exif_read_data') || ! str_starts_with($contents, "\xFF\xD8")) {
117
+            return $image;
118
+        }
119
+
120
+        $exif = @exif_read_data('data://image/jpeg;base64,'.base64_encode($contents));
121
+        $orientation = is_array($exif) ? (int) ($exif['Orientation'] ?? 1) : 1;
122
+
123
+        if (in_array($orientation, [2, 4, 5, 7], true)) {
124
+            imageflip($image, IMG_FLIP_HORIZONTAL);
125
+        }
126
+
127
+        $angle = match ($orientation) {
128
+            3, 4 => 180,
129
+            5, 6 => -90,
130
+            7, 8 => 90,
131
+            default => 0,
132
+        };
133
+
134
+        if ($angle === 0) {
135
+            return $image;
136
+        }
137
+
138
+        $turned = imagerotate($image, $angle, 0);
139
+
140
+        return $turned instanceof GdImage ? $turned : $image;
141
+    }
142
+}

+ 25
- 0
database/migrations/2026_11_25_000001_add_target_to_store_generations_table.php Просмотреть файл

@@ -0,0 +1,25 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    /**
10
+     * The part of the store the merchant selected in the preview before asking for a change.
11
+     */
12
+    public function up(): void
13
+    {
14
+        Schema::table('store_generations', function (Blueprint $table) {
15
+            $table->json('target')->nullable()->after('instruction');
16
+        });
17
+    }
18
+
19
+    public function down(): void
20
+    {
21
+        Schema::table('store_generations', function (Blueprint $table) {
22
+            $table->dropColumn('target');
23
+        });
24
+    }
25
+};

+ 6
- 0
resources/css/app.css Просмотреть файл

@@ -562,3 +562,9 @@
562 562
         transform: translateX(-50%);
563 563
     }
564 564
 }
565
+
566
+/* The Design tab's "Ask the AI" button sits at the bottom right, so toasts show above it. */
567
+body:has([data-ai-launcher]) [data-sonner-toaster] {
568
+    --offset-bottom: 88px !important;
569
+    --mobile-offset-bottom: 80px !important;
570
+}

+ 1
- 1
resources/js/components/app-sidebar-header.tsx Просмотреть файл

@@ -9,7 +9,7 @@ export function AppSidebarHeader({
9 9
 }) {
10 10
     return (
11 11
         <header className="flex h-16 shrink-0 items-center gap-2 border-b border-sidebar-border/50 px-6 transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12 md:px-4">
12
-            <div className="flex items-center gap-2">
12
+            <div className="flex min-w-0 items-center gap-2">
13 13
                 <SidebarTrigger className="-ml-1" />
14 14
                 <Breadcrumbs breadcrumbs={breadcrumbs} />
15 15
             </div>

+ 2
- 0
resources/js/components/app-sidebar.tsx Просмотреть файл

@@ -6,6 +6,7 @@ import { NavMain } from '@/components/nav-main';
6 6
 import { NavPlan } from '@/components/nav-plan';
7 7
 import { NavStores } from '@/components/nav-stores';
8 8
 import { NavUser } from '@/components/nav-user';
9
+import { ThemeSwitch } from '@/components/theme-switch';
9 10
 import {
10 11
     Sidebar,
11 12
     SidebarContent,
@@ -57,6 +58,7 @@ export function AppSidebar() {
57 58
 
58 59
             <SidebarFooter>
59 60
                 <NavPlan />
61
+                <ThemeSwitch />
60 62
                 <NavUser />
61 63
             </SidebarFooter>
62 64
         </Sidebar>

+ 7
- 0
resources/js/components/stores/bento-box.tsx Просмотреть файл

@@ -15,6 +15,7 @@ import type {
15 15
     LinkSuggestion,
16 16
     Store,
17 17
 } from '@/types';
18
+import { SectionName } from '@/components/stores/preview-highlight';
18 19
 
19 20
 const selectClass =
20 21
     'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50 md:text-sm';
@@ -219,6 +220,12 @@ function BentoForm({
219 220
 
220 221
     return (
221 222
         <form onSubmit={submit} className="space-y-4" noValidate>
223
+            <SectionName
224
+                target={{ sectionId: id, pageId: 'home', label: 'Bento tiles' }}
225
+                className="text-sm font-medium"
226
+            >
227
+                {bento.heading || 'Bento tiles'}
228
+            </SectionName>
222 229
             <div className="grid gap-3 sm:grid-cols-2">
223 230
                 <div className="grid gap-1.5">
224 231
                     <Label htmlFor={`bento-heading-${id}`}>

+ 364
- 95
resources/js/components/stores/design-chat.tsx Просмотреть файл

@@ -1,8 +1,16 @@
1 1
 import { Form, router } from '@inertiajs/react';
2
-import { CircleAlert, CircleCheck, Send } from 'lucide-react';
3
-import { useState } from 'react';
2
+import {
3
+    CircleAlert,
4
+    CircleCheck,
5
+    Send,
6
+    Sparkles,
7
+    SquareDashedMousePointer,
8
+    X,
9
+} from 'lucide-react';
10
+import { useEffect, useRef, useState } from 'react';
4 11
 import StoreGenerationController from '@/actions/App/Http/Controllers/StoreGenerationController';
5 12
 import InputError from '@/components/input-error';
13
+import type { PreviewSelection } from '@/components/stores/preview-picker';
6 14
 import { Button } from '@/components/ui/button';
7 15
 import { Spinner } from '@/components/ui/spinner';
8 16
 import type { Store, StoreGeneration, UsageCount } from '@/types';
@@ -10,125 +18,386 @@ import type { Store, StoreGeneration, UsageCount } from '@/types';
10 18
 const fieldClass =
11 19
     'w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50';
12 20
 
21
+const examples = [
22
+    'Make the main colour dark green',
23
+    'Add a section with our opening hours',
24
+    'Create a 10% code RAYA10 until the end of the month',
25
+];
26
+
13 27
 /**
14
- * Ask the AI for a small change in plain words, and see the last few requests.
28
+ * "Ask the AI": a round button that stays at the bottom right of the Design tab. Clicking it opens
29
+ * a chat panel above it. The panel does not cover the page, so the preview can be watched while
30
+ * the AI works. It keeps the last few requests, with any changes waiting for the merchant's OK.
15 31
  */
16 32
 export default function DesignChat({
17 33
     store,
18 34
     edits,
19 35
     usage,
20 36
     busy,
37
+    selection,
38
+    onClearSelection,
39
+    onStartSelecting,
21 40
 }: {
22 41
     store: Store;
23 42
     edits: StoreGeneration[];
24 43
     usage: UsageCount;
25 44
     busy: boolean;
45
+    /** The part of the preview the merchant selected. The AI changes only that part. */
46
+    selection: PreviewSelection | null;
47
+    onClearSelection: () => void;
48
+    /** Turn on "Select to edit" in the preview. */
49
+    onStartSelecting: () => void;
26 50
 }) {
51
+    const [open, setOpen] = useState(false);
52
+    const field = useRef<HTMLTextAreaElement>(null);
53
+    const history = useRef<HTMLDivElement>(null);
54
+    const launcher = useRef<HTMLButtonElement>(null);
55
+
27 56
     const left = Math.max(0, usage.limit - usage.used);
28 57
     const disabled = busy || left === 0;
58
+    const working = edits.some(
59
+        (edit) => edit.status === 'queued' || edit.status === 'running',
60
+    );
61
+    const waiting = edits.some(
62
+        (edit) =>
63
+            edit.status === 'completed' && edit.actions_status === 'pending',
64
+    );
65
+    // Newest last, like a chat.
66
+    const ordered = [...edits].reverse();
29 67
 
30
-    return (
31
-        <div className="space-y-4 rounded-xl border p-4">
32
-            <div className="flex flex-wrap items-baseline justify-between gap-2">
33
-                <h3 className="font-medium">Ask the AI</h3>
34
-                <p className="text-xs text-muted-foreground">
35
-                    {left} of {usage.limit} AI edits left
36
-                </p>
37
-            </div>
68
+    // Escape closes the panel and puts the focus back on the button.
69
+    useEffect(() => {
70
+        if (!open) {
71
+            return;
72
+        }
38 73
 
39
-            <Form
40
-                {...StoreGenerationController.edit.form(store.slug)}
41
-                resetOnSuccess
42
-                options={{ preserveScroll: true }}
43
-                className="space-y-2"
44
-            >
45
-                {({ processing, errors }) => (
46
-                    <>
47
-                        <label htmlFor="instruction" className="sr-only">
48
-                            Describe the change you want
49
-                        </label>
50
-                        <textarea
51
-                            id="instruction"
52
-                            name="instruction"
53
-                            required
54
-                            rows={2}
55
-                            minLength={3}
56
-                            maxLength={500}
57
-                            disabled={disabled}
58
-                            className={fieldClass}
59
-                            placeholder="e.g. Make the main colour dark green. Or: Create a 10% code RAYA10 until the end of the month. Or: Set the 100ml moisturiser to RM 52."
74
+        const onKey = (event: KeyboardEvent) => {
75
+            if (event.key === 'Escape') {
76
+                setOpen(false);
77
+                launcher.current?.focus();
78
+            }
79
+        };
80
+
81
+        window.addEventListener('keydown', onKey);
82
+
83
+        return () => window.removeEventListener('keydown', onKey);
84
+    }, [open]);
85
+
86
+    useEffect(() => {
87
+        if (open) {
88
+            field.current?.focus();
89
+        }
90
+    }, [open]);
91
+
92
+    // A new selection opens the panel, ready to type what should change there.
93
+    useEffect(() => {
94
+        if (selection) {
95
+            setOpen(true);
96
+            field.current?.focus();
97
+        }
98
+    }, [selection]);
99
+
100
+    // Keep the newest message in view.
101
+    useEffect(() => {
102
+        if (open && history.current) {
103
+            history.current.scrollTop = history.current.scrollHeight;
104
+        }
105
+    }, [open, edits]);
106
+
107
+    function fillExample(text: string) {
108
+        if (field.current) {
109
+            field.current.value = text;
110
+            field.current.focus();
111
+        }
112
+    }
113
+
114
+    return (
115
+        <>
116
+            {open && (
117
+                <section
118
+                    id="ai-chat-panel"
119
+                    role="dialog"
120
+                    aria-modal="false"
121
+                    aria-labelledby="ai-chat-title"
122
+                    className="fixed inset-x-3 bottom-20 z-40 flex max-h-[75vh] flex-col overflow-hidden rounded-2xl border bg-background shadow-2xl sm:inset-x-auto sm:right-6 sm:bottom-24 sm:max-h-[min(640px,calc(100vh-8rem))] sm:w-[400px]"
123
+                    data-test="ai-chat-panel"
124
+                >
125
+                    <header className="flex items-start gap-3 border-b px-4 py-3">
126
+                        <Sparkles
127
+                            className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400"
128
+                            aria-hidden="true"
60 129
                         />
61
-                        <InputError message={errors.instruction} />
62
-                        <div className="flex flex-wrap items-center justify-between gap-2">
130
+                        <div className="min-w-0 flex-1">
131
+                            <h3 id="ai-chat-title" className="font-medium">
132
+                                Ask the AI
133
+                            </h3>
63 134
                             <p className="text-xs text-muted-foreground">
64
-                                {left === 0
65
-                                    ? 'You have used all the AI edits in your plan.'
66
-                                    : 'One change at a time works best.'}
135
+                                {left} of {usage.limit} AI edits left
67 136
                             </p>
68
-                            <Button
69
-                                size="sm"
70
-                                disabled={disabled || processing}
71
-                                data-test="send-edit-button"
72
-                            >
73
-                                <Send />
74
-                                Send
75
-                            </Button>
76 137
                         </div>
77
-                    </>
78
-                )}
79
-            </Form>
138
+                        <Button
139
+                            variant="ghost"
140
+                            size="icon"
141
+                            className="-mt-1 -mr-2 size-8"
142
+                            onClick={() => {
143
+                                setOpen(false);
144
+                                launcher.current?.focus();
145
+                            }}
146
+                            aria-label="Close Ask the AI"
147
+                        >
148
+                            <X />
149
+                        </Button>
150
+                    </header>
80 151
 
81
-            {edits.length > 0 && (
82
-                <ul
83
-                    className="space-y-3 border-t pt-4"
84
-                    data-test="edit-history"
85
-                >
86
-                    {edits.map((edit) => (
87
-                        <li key={edit.id} className="flex gap-3 text-sm">
88
-                            <span className="mt-0.5 shrink-0">
89
-                                {edit.status === 'completed' ? (
90
-                                    <CircleCheck className="size-4 text-green-600 dark:text-green-400" />
91
-                                ) : edit.status === 'failed' ? (
92
-                                    <CircleAlert className="size-4 text-red-600 dark:text-red-400" />
93
-                                ) : (
94
-                                    <Spinner />
95
-                                )}
96
-                            </span>
97
-                            <div className="min-w-0">
98
-                                <p className="break-words">
99
-                                    {edit.instruction}
100
-                                </p>
101
-                                <p className="mt-0.5 break-words text-muted-foreground">
102
-                                    {edit.status === 'completed'
103
-                                        ? (edit.reply ?? 'Done.')
104
-                                        : edit.status === 'failed'
105
-                                          ? (edit.error ??
106
-                                            'This change failed.')
107
-                                          : 'Working on it…'}
152
+                    <div
153
+                        ref={history}
154
+                        className="min-h-0 flex-1 overflow-y-auto px-4 py-3"
155
+                    >
156
+                        {ordered.length === 0 ? (
157
+                            <div className="space-y-3 text-sm">
158
+                                <p className="text-muted-foreground">
159
+                                    Tell the AI what to change in plain words.
160
+                                    It can change your design, and prepare
161
+                                    discount codes or price changes for your OK.
108 162
                                 </p>
109
-                                {edit.status === 'completed' &&
110
-                                    edit.actions.length > 0 && (
111
-                                        <ProposedActions
112
-                                            store={store}
113
-                                            edit={edit}
114
-                                        />
115
-                                    )}
116
-                                {edit.status === 'completed' &&
117
-                                    edit.changed === false &&
118
-                                    edit.actions.length === 0 && (
119
-                                        <p
120
-                                            className="mt-1 text-xs font-medium text-amber-700 dark:text-amber-400"
121
-                                            data-test="edit-no-change"
163
+                                <div className="flex flex-wrap gap-2">
164
+                                    {examples.map((example) => (
165
+                                        <button
166
+                                            key={example}
167
+                                            type="button"
168
+                                            onClick={() => fillExample(example)}
169
+                                            disabled={disabled}
170
+                                            className="rounded-full border px-3 py-1 text-left text-xs hover:bg-muted disabled:opacity-50"
122 171
                                         >
123
-                                            No change was made to your design.
124
-                                        </p>
125
-                                    )}
172
+                                            {example}
173
+                                        </button>
174
+                                    ))}
175
+                                </div>
126 176
                             </div>
127
-                        </li>
128
-                    ))}
129
-                </ul>
177
+                        ) : (
178
+                            <ul className="space-y-4" data-test="edit-history">
179
+                                {ordered.map((edit) => (
180
+                                    <EditMessage
181
+                                        key={edit.id}
182
+                                        store={store}
183
+                                        edit={edit}
184
+                                    />
185
+                                ))}
186
+                            </ul>
187
+                        )}
188
+                    </div>
189
+
190
+                    <Form
191
+                        {...StoreGenerationController.edit.form(store.slug)}
192
+                        resetOnSuccess
193
+                        options={{ preserveScroll: true }}
194
+                        onSuccess={onClearSelection}
195
+                        className="space-y-2 border-t px-4 py-3"
196
+                    >
197
+                        {({ processing, errors }) => (
198
+                            <>
199
+                                {selection ? (
200
+                                    <div
201
+                                        className="flex items-start gap-2 rounded-lg border border-emerald-600/30 bg-emerald-50 px-2.5 py-2 text-xs text-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-200"
202
+                                        data-test="chat-selection"
203
+                                    >
204
+                                        <SquareDashedMousePointer
205
+                                            className="mt-px size-3.5 shrink-0"
206
+                                            aria-hidden="true"
207
+                                        />
208
+                                        <p className="min-w-0 flex-1 break-words">
209
+                                            <span className="font-semibold">
210
+                                                Editing: {selection.label}
211
+                                            </span>
212
+                                            {selection.detail && (
213
+                                                <> · {selection.detail}</>
214
+                                            )}
215
+                                            <span className="block opacity-75">
216
+                                                Only this part will change.
217
+                                            </span>
218
+                                        </p>
219
+                                        <button
220
+                                            type="button"
221
+                                            onClick={onClearSelection}
222
+                                            className="-m-1 rounded p-1 hover:bg-emerald-600/10"
223
+                                            aria-label="Clear the selected part"
224
+                                        >
225
+                                            <X className="size-3.5" />
226
+                                        </button>
227
+                                        <input
228
+                                            type="hidden"
229
+                                            name="target_section"
230
+                                            value={selection.section}
231
+                                        />
232
+                                        <input
233
+                                            type="hidden"
234
+                                            name="target_label"
235
+                                            value={selection.label}
236
+                                        />
237
+                                        <input
238
+                                            type="hidden"
239
+                                            name="target_detail"
240
+                                            value={selection.detail ?? ''}
241
+                                        />
242
+                                    </div>
243
+                                ) : (
244
+                                    <button
245
+                                        type="button"
246
+                                        onClick={onStartSelecting}
247
+                                        className="inline-flex items-center gap-1.5 text-xs font-medium text-emerald-700 hover:underline dark:text-emerald-400"
248
+                                        data-test="chat-start-selecting"
249
+                                    >
250
+                                        <SquareDashedMousePointer
251
+                                            className="size-3.5"
252
+                                            aria-hidden="true"
253
+                                        />
254
+                                        Select a part of your store to change
255
+                                    </button>
256
+                                )}
257
+                                <label
258
+                                    htmlFor="instruction"
259
+                                    className="sr-only"
260
+                                >
261
+                                    Describe the change you want
262
+                                </label>
263
+                                <textarea
264
+                                    ref={field}
265
+                                    id="instruction"
266
+                                    name="instruction"
267
+                                    required
268
+                                    rows={2}
269
+                                    minLength={3}
270
+                                    maxLength={500}
271
+                                    disabled={disabled}
272
+                                    className={fieldClass}
273
+                                    placeholder={
274
+                                        selection
275
+                                            ? 'What should change here? e.g. Make it shorter'
276
+                                            : 'e.g. Make the main colour dark green'
277
+                                    }
278
+                                    onKeyDown={(event) => {
279
+                                        // Enter sends; Shift + Enter starts a new line.
280
+                                        if (
281
+                                            event.key === 'Enter' &&
282
+                                            !event.shiftKey &&
283
+                                            !event.nativeEvent.isComposing
284
+                                        ) {
285
+                                            event.preventDefault();
286
+                                            event.currentTarget.form?.requestSubmit();
287
+                                        }
288
+                                    }}
289
+                                />
290
+                                <InputError message={errors.instruction} />
291
+                                <div className="flex items-center justify-between gap-2">
292
+                                    <p className="text-xs text-muted-foreground">
293
+                                        {left === 0
294
+                                            ? 'You have used all the AI edits in your plan.'
295
+                                            : busy
296
+                                              ? 'Wait for the current change to finish.'
297
+                                              : 'One change at a time works best.'}
298
+                                    </p>
299
+                                    <Button
300
+                                        size="sm"
301
+                                        disabled={disabled || processing}
302
+                                        data-test="send-edit-button"
303
+                                    >
304
+                                        <Send />
305
+                                        Send
306
+                                    </Button>
307
+                                </div>
308
+                            </>
309
+                        )}
310
+                    </Form>
311
+                </section>
130 312
             )}
131
-        </div>
313
+
314
+            <button
315
+                ref={launcher}
316
+                type="button"
317
+                data-ai-launcher
318
+                aria-expanded={open}
319
+                aria-controls="ai-chat-panel"
320
+                onClick={() => setOpen((value) => !value)}
321
+                className="fixed right-4 bottom-4 z-40 inline-flex items-center gap-2 rounded-full bg-emerald-700 px-4 py-3 text-sm font-medium text-white shadow-lg transition hover:bg-emerald-800 focus-visible:ring-[3px] focus-visible:ring-emerald-500/50 focus-visible:outline-none sm:right-6 sm:bottom-6 dark:bg-emerald-600 dark:hover:bg-emerald-500"
322
+                data-test="ai-chat-button"
323
+            >
324
+                {open ? (
325
+                    <X className="size-4" aria-hidden="true" />
326
+                ) : working ? (
327
+                    <Spinner />
328
+                ) : (
329
+                    <Sparkles className="size-4" aria-hidden="true" />
330
+                )}
331
+                {open ? 'Close' : working ? 'AI is working…' : 'Ask the AI'}
332
+                {!open && waiting && (
333
+                    <>
334
+                        <span
335
+                            className="absolute -top-0.5 -right-0.5 size-3 rounded-full bg-amber-400 ring-2 ring-background"
336
+                            aria-hidden="true"
337
+                        />
338
+                        <span className="sr-only">
339
+                            (a change is waiting for your OK)
340
+                        </span>
341
+                    </>
342
+                )}
343
+            </button>
344
+        </>
345
+    );
346
+}
347
+
348
+/** One request and the AI's answer. */
349
+function EditMessage({ store, edit }: { store: Store; edit: StoreGeneration }) {
350
+    return (
351
+        <li className="space-y-2 text-sm">
352
+            <div className="ml-8 rounded-2xl rounded-br-sm bg-muted px-3 py-2 break-words">
353
+                {edit.target && (
354
+                    <p className="mb-1 flex items-center gap-1 text-xs text-muted-foreground">
355
+                        <SquareDashedMousePointer
356
+                            className="size-3 shrink-0"
357
+                            aria-hidden="true"
358
+                        />
359
+                        <span className="min-w-0 truncate">
360
+                            {edit.target.label}
361
+                            {edit.target.detail && ` · ${edit.target.detail}`}
362
+                        </span>
363
+                    </p>
364
+                )}
365
+                <p>{edit.instruction}</p>
366
+            </div>
367
+            <div className="flex gap-2">
368
+                <span className="mt-0.5 shrink-0">
369
+                    {edit.status === 'completed' ? (
370
+                        <CircleCheck className="size-4 text-green-600 dark:text-green-400" />
371
+                    ) : edit.status === 'failed' ? (
372
+                        <CircleAlert className="size-4 text-red-600 dark:text-red-400" />
373
+                    ) : (
374
+                        <Spinner />
375
+                    )}
376
+                </span>
377
+                <div className="min-w-0">
378
+                    <p className="break-words text-muted-foreground">
379
+                        {edit.status === 'completed'
380
+                            ? (edit.reply ?? 'Done.')
381
+                            : edit.status === 'failed'
382
+                              ? (edit.error ?? 'This change failed.')
383
+                              : 'Working on it…'}
384
+                    </p>
385
+                    {edit.status === 'completed' && edit.actions.length > 0 && (
386
+                        <ProposedActions store={store} edit={edit} />
387
+                    )}
388
+                    {edit.status === 'completed' &&
389
+                        edit.changed === false &&
390
+                        edit.actions.length === 0 && (
391
+                            <p
392
+                                className="mt-1 text-xs font-medium text-amber-700 dark:text-amber-400"
393
+                                data-test="edit-no-change"
394
+                            >
395
+                                No change was made to your design.
396
+                            </p>
397
+                        )}
398
+                </div>
399
+            </div>
400
+        </li>
132 401
     );
133 402
 }
134 403
 

+ 11
- 2
resources/js/components/stores/featured-picker.tsx Просмотреть файл

@@ -5,6 +5,7 @@ import FeaturedProductController from '@/actions/App/Http/Controllers/FeaturedPr
5 5
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
6 6
 import { formatRinggit } from '@/lib/money';
7 7
 import type { FeaturedSection, ProductOption, Store } from '@/types';
8
+import { SectionName } from '@/components/stores/preview-highlight';
8 9
 
9 10
 const fieldClass =
10 11
     'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50 md:text-sm';
@@ -95,7 +96,14 @@ export default function FeaturedPicker({
95 96
                                     key={section.section_id}
96 97
                                     className="grid gap-1.5"
97 98
                                 >
98
-                                    <label htmlFor={id} className="text-sm">
99
+                                    <SectionName
100
+                                        target={{
101
+                                            sectionId: section.section_id,
102
+                                            pageId: section.page_id,
103
+                                            label: 'Featured product',
104
+                                        }}
105
+                                        className="text-sm"
106
+                                    >
99 107
                                         “{section.name}”
100 108
                                         {section.page_id !== 'home' && (
101 109
                                             <span className="text-muted-foreground">
@@ -103,9 +111,10 @@ export default function FeaturedPicker({
103 111
                                                 on {section.page_title}
104 112
                                             </span>
105 113
                                         )}
106
-                                    </label>
114
+                                    </SectionName>
107 115
                                     <select
108 116
                                         id={id}
117
+                                        aria-label={`Product for “${section.name}”`}
109 118
                                         value={
110 119
                                             missing
111 120
                                                 ? ''

+ 14
- 4
resources/js/components/stores/hero-picker.tsx Просмотреть файл

@@ -7,6 +7,7 @@ import InputError from '@/components/input-error';
7 7
 import { Button } from '@/components/ui/button';
8 8
 import { cn } from '@/lib/utils';
9 9
 import type { HeroChoice, HeroSectionInfo, Store } from '@/types';
10
+import { SectionName } from '@/components/stores/preview-highlight';
10 11
 
11 12
 const layouts: { value: HeroSectionInfo['variant']; label: string }[] = [
12 13
     { value: 'image-full', label: 'Full-width photo' },
@@ -127,7 +128,14 @@ function HeroRow({
127 128
     return (
128 129
         <div className="space-y-4 border-t pt-4">
129 130
             {showTitle && (
130
-                <p className="text-sm">
131
+                <SectionName
132
+                    target={{
133
+                        sectionId: section.section_id,
134
+                        pageId: section.page_id,
135
+                        label: 'Hero',
136
+                    }}
137
+                    className="text-sm"
138
+                >
131 139
                     “{section.headline}”
132 140
                     {section.page_id !== 'home' && (
133 141
                         <span className="text-muted-foreground">
@@ -135,7 +143,7 @@ function HeroRow({
135 143
                             on {section.page_title}
136 144
                         </span>
137 145
                     )}
138
-                </p>
146
+                </SectionName>
139 147
             )}
140 148
 
141 149
             <fieldset className="space-y-2">
@@ -224,8 +232,10 @@ function HeroRow({
224 232
                     Upload banner photo
225 233
                 </Button>
226 234
                 <p className="w-full text-xs text-muted-foreground">
227
-                    JPG, PNG or WebP, up to 6 MB. A wide photo at least 1600
228
-                    pixels across looks best.
235
+                    JPG, PNG or WebP, up to 6 MB and at least 300 by 200 pixels.
236
+                    We get it ready for you: small photos are enlarged and big
237
+                    ones made lighter. A wide photo 1600 pixels across looks
238
+                    sharpest.
229 239
                 </p>
230 240
                 <InputError message={upload.errors.photo} />
231 241
             </form>

+ 13
- 19
resources/js/components/stores/layout-picker.tsx Просмотреть файл

@@ -2,28 +2,13 @@ import { router } from '@inertiajs/react';
2 2
 import { ChevronDown, LayoutTemplate } from 'lucide-react';
3 3
 import { useState } from 'react';
4 4
 import SectionLayoutController from '@/actions/App/Http/Controllers/SectionLayoutController';
5
+import { SectionName } from '@/components/stores/preview-highlight';
6
+import { typeNames } from '@/components/stores/section-names';
5 7
 import type { LayoutSection, Store } from '@/types';
6 8
 
7 9
 const fieldClass =
8 10
     'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50 md:text-sm';
9 11
 
10
-/** Section types and layouts in plain words. Unknown ones fall back to their code name. */
11
-const typeNames: Record<string, string> = {
12
-    header: 'Header',
13
-    trust_bar: 'Trust row',
14
-    shop_by: 'Shop by collection',
15
-    bento: 'Bento tiles',
16
-    video: 'Video',
17
-    product_grid: 'Products',
18
-    featured_product: 'Featured product',
19
-    about: 'About',
20
-    testimonials: 'Reviews',
21
-    faq: 'FAQ',
22
-    newsletter: 'Newsletter',
23
-    contact: 'Contact',
24
-    footer: 'Footer',
25
-};
26
-
27 12
 const layoutNames: Record<string, Record<string, string>> = {
28 13
     header: { simple: 'Logo on the left', centered: 'Logo in the middle' },
29 14
     trust_bar: { row: 'Icon row', boxed: 'Small cards' },
@@ -131,7 +116,15 @@ export default function LayoutPicker({
131 116
                             key={section.section_id}
132 117
                             className="grid gap-2 py-3 sm:grid-cols-[1fr_220px] sm:items-center"
133 118
                         >
134
-                            <label htmlFor={id} className="min-w-0 text-sm">
119
+                            <SectionName
120
+                                target={{
121
+                                    sectionId: section.section_id,
122
+                                    pageId: section.page_id,
123
+                                    label:
124
+                                        typeNames[section.type] ?? section.type,
125
+                                }}
126
+                                className="text-sm"
127
+                            >
135 128
                                 <span className="font-medium">
136 129
                                     {typeNames[section.type] ?? section.type}
137 130
                                 </span>
@@ -151,9 +144,10 @@ export default function LayoutPicker({
151 144
                                             on {section.page_title}
152 145
                                         </span>
153 146
                                     )}
154
-                            </label>
147
+                            </SectionName>
155 148
                             <select
156 149
                                 id={id}
150
+                                aria-label={`Layout of ${typeNames[section.type] ?? section.type}`}
157 151
                                 value={section.variant}
158 152
                                 disabled={busy || saving === section.section_id}
159 153
                                 onChange={(event) =>

+ 252
- 0
resources/js/components/stores/preview-highlight.tsx Просмотреть файл

@@ -0,0 +1,252 @@
1
+import { Crosshair } from 'lucide-react';
2
+import { createContext, useCallback, useContext, useMemo, useRef } from 'react';
3
+import type { ReactNode, RefObject } from 'react';
4
+import StoreDesignController from '@/actions/App/Http/Controllers/StoreDesignController';
5
+import { cn } from '@/lib/utils';
6
+
7
+/** What to point at in the preview: a section id ("header" and "footer" included) and its page. */
8
+export type PreviewTarget = {
9
+    sectionId: string;
10
+    /** The page the section is on. Header and footer are on every page, so null. */
11
+    pageId: string | null;
12
+    /** Shown on the outline, such as "Products". */
13
+    label: string;
14
+};
15
+
16
+type Highlighter = {
17
+    show: (target: PreviewTarget) => void;
18
+};
19
+
20
+const OVERLAY_ID = 'sf-design-highlight';
21
+const SHOW_FOR = 2600;
22
+/** How long a section waits for its page to open in the preview. */
23
+const WAIT_FOR_LOAD = 20000;
24
+
25
+function reducedMotion(): boolean {
26
+    return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
27
+}
28
+
29
+/** The section's element in the preview page, or null when it is not on this page. */
30
+function findSection(doc: Document, sectionId: string): HTMLElement | null {
31
+    if (sectionId === 'header') {
32
+        return doc.querySelector<HTMLElement>('.sf-root header');
33
+    }
34
+
35
+    if (sectionId === 'footer') {
36
+        return doc.querySelector<HTMLElement>('.sf-root footer');
37
+    }
38
+
39
+    return doc.querySelector<HTMLElement>(
40
+        `[data-section="${CSS.escape(sectionId)}"]`,
41
+    );
42
+}
43
+
44
+/**
45
+ * Draw a green outline over the section inside the preview, scroll to it, and fade it out.
46
+ * The outline follows the section on every frame, so it stays right while the page scrolls.
47
+ */
48
+function outline(frame: HTMLIFrameElement, target: PreviewTarget): boolean {
49
+    const doc = frame.contentDocument;
50
+    const win = frame.contentWindow;
51
+
52
+    if (!doc || !win || !doc.body) {
53
+        return false;
54
+    }
55
+
56
+    const element = findSection(doc, target.sectionId);
57
+
58
+    if (!element) {
59
+        return false;
60
+    }
61
+
62
+    doc.getElementById(OVERLAY_ID)?.remove();
63
+
64
+    const calm = reducedMotion();
65
+    const box = doc.createElement('div');
66
+    box.id = OVERLAY_ID;
67
+    box.setAttribute('aria-hidden', 'true');
68
+    Object.assign(box.style, {
69
+        position: 'fixed',
70
+        zIndex: '2147483647',
71
+        pointerEvents: 'none',
72
+        border: '3px solid #10b981',
73
+        borderRadius: '10px',
74
+        background: 'rgba(16, 185, 129, 0.08)',
75
+        boxShadow: '0 0 0 4px rgba(16, 185, 129, 0.25)',
76
+        transition: calm ? 'none' : 'opacity 300ms ease',
77
+        opacity: '1',
78
+    } satisfies Partial<CSSStyleDeclaration>);
79
+
80
+    const tag = doc.createElement('span');
81
+    tag.textContent = target.label;
82
+    Object.assign(tag.style, {
83
+        position: 'absolute',
84
+        top: '8px',
85
+        left: '8px',
86
+        padding: '3px 9px',
87
+        borderRadius: '999px',
88
+        background: '#10b981',
89
+        color: '#fff',
90
+        font: '600 12px/1.4 system-ui, sans-serif',
91
+        whiteSpace: 'nowrap',
92
+    } satisfies Partial<CSSStyleDeclaration>);
93
+    box.appendChild(tag);
94
+    doc.body.appendChild(box);
95
+
96
+    // The store's header stays at the top while scrolling, so other sections are shown below it.
97
+    const isHeader = target.sectionId === 'header';
98
+    const header = isHeader ? null : findSection(doc, 'header');
99
+    const headerHeight = header?.offsetHeight ?? 0;
100
+
101
+    // Tall sections line up under the header; short ones sit in the middle of the space left.
102
+    const rect = element.getBoundingClientRect();
103
+    const room = win.innerHeight - headerHeight;
104
+    const pageTop = rect.top + win.scrollY;
105
+    const top = isHeader
106
+        ? 0
107
+        : rect.height > room * 0.8
108
+          ? pageTop - headerHeight - 8
109
+          : pageTop - headerHeight - (room - rect.height) / 2;
110
+    // Scroll only inside the preview; the Design page itself stays where it is.
111
+    win.scrollTo({ top: Math.max(0, top), behavior: calm ? 'auto' : 'smooth' });
112
+
113
+    const started = performance.now();
114
+    const follow = () => {
115
+        if (!box.isConnected) {
116
+            return;
117
+        }
118
+
119
+        const now = element.getBoundingClientRect();
120
+        const ceiling = header
121
+            ? Math.max(header.getBoundingClientRect().bottom, 0)
122
+            : 0;
123
+        const shownTop = Math.max(now.top, ceiling);
124
+        const shownBottom = Math.min(now.bottom, win.innerHeight);
125
+        Object.assign(box.style, {
126
+            top: `${shownTop + 2}px`,
127
+            left: `${now.left + 2}px`,
128
+            width: `${Math.max(now.width - 4, 0)}px`,
129
+            height: `${Math.max(shownBottom - shownTop - 4, 0)}px`,
130
+        });
131
+
132
+        const age = performance.now() - started;
133
+
134
+        if (age > SHOW_FOR) {
135
+            box.style.opacity = '0';
136
+            win.setTimeout(() => box.remove(), calm ? 0 : 320);
137
+
138
+            return;
139
+        }
140
+
141
+        win.requestAnimationFrame(follow);
142
+    };
143
+    follow();
144
+
145
+    return true;
146
+}
147
+
148
+/**
149
+ * Points at sections in the Design tab's preview. Give the result to `PreviewHighlightContext`
150
+ * so every box can use it, and pass `onLoad` to the preview iframe.
151
+ */
152
+export function usePreviewHighlighter({
153
+    frameRef,
154
+    slug,
155
+    homeUrl,
156
+}: {
157
+    frameRef: RefObject<HTMLIFrameElement | null>;
158
+    slug: string;
159
+    homeUrl: string;
160
+}): Highlighter & { onLoad: () => void } {
161
+    // A section on another page waits here while the preview opens that page.
162
+    const waiting = useRef<{ target: PreviewTarget; at: number } | null>(null);
163
+
164
+    const show = useCallback(
165
+        (target: PreviewTarget) => {
166
+            const frame = frameRef.current;
167
+
168
+            if (!frame) {
169
+                return;
170
+            }
171
+
172
+            // Bring the preview into view first, so the outline can be seen.
173
+            frame.scrollIntoView({
174
+                behavior: reducedMotion() ? 'auto' : 'smooth',
175
+                block: 'nearest',
176
+            });
177
+
178
+            if (outline(frame, target)) {
179
+                return;
180
+            }
181
+
182
+            const wanted =
183
+                target.pageId && target.pageId !== 'home'
184
+                    ? StoreDesignController.page[
185
+                          '/stores/{slug}/preview/{pageId}'
186
+                      ].url({ slug, pageId: target.pageId })
187
+                    : homeUrl;
188
+
189
+            if (frame.contentWindow?.location.pathname !== wanted) {
190
+                waiting.current = { target, at: Date.now() };
191
+                frame.src = wanted;
192
+            }
193
+        },
194
+        [frameRef, slug, homeUrl],
195
+    );
196
+
197
+    const onLoad = useCallback(() => {
198
+        const frame = frameRef.current;
199
+        const pending = waiting.current;
200
+        waiting.current = null;
201
+
202
+        if (!frame || !pending || Date.now() - pending.at > WAIT_FOR_LOAD) {
203
+            return;
204
+        }
205
+
206
+        // Give the store page a moment to draw before measuring.
207
+        window.setTimeout(() => outline(frame, pending.target), 150);
208
+    }, [frameRef]);
209
+
210
+    return useMemo(() => ({ show, onLoad }), [show, onLoad]);
211
+}
212
+
213
+export const PreviewHighlightContext = createContext<Highlighter | null>(null);
214
+
215
+/**
216
+ * A section's name that, when clicked, shows the section in the preview.
217
+ * Without a preview around it, it is plain text.
218
+ */
219
+export function SectionName({
220
+    target,
221
+    className,
222
+    children,
223
+}: {
224
+    target: PreviewTarget;
225
+    className?: string;
226
+    children: ReactNode;
227
+}) {
228
+    const highlighter = useContext(PreviewHighlightContext);
229
+
230
+    if (!highlighter) {
231
+        return <span className={className}>{children}</span>;
232
+    }
233
+
234
+    return (
235
+        <button
236
+            type="button"
237
+            onClick={() => highlighter.show(target)}
238
+            title="Show in the preview"
239
+            className={cn(
240
+                'group/name inline-flex max-w-full min-w-0 items-baseline gap-1.5 rounded-sm text-left underline-offset-4 hover:underline focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none',
241
+                className,
242
+            )}
243
+        >
244
+            <span className="min-w-0">{children}</span>
245
+            <Crosshair
246
+                className="size-3.5 shrink-0 translate-y-0.5 self-start text-muted-foreground opacity-60 group-hover/name:opacity-100"
247
+                aria-hidden="true"
248
+            />
249
+            <span className="sr-only">(show in the preview)</span>
250
+        </button>
251
+    );
252
+}

+ 406
- 0
resources/js/components/stores/preview-picker.ts Просмотреть файл

@@ -0,0 +1,406 @@
1
+import { sectionName } from '@/components/stores/section-names';
2
+
3
+/** What the merchant selected in the preview, sent with their next "Ask the AI" message. */
4
+export type PreviewSelection = {
5
+    /** The section's id in the design ("header" and "footer" for those). */
6
+    section: string;
7
+    /** The section in plain words, such as "Hero" or "Products". */
8
+    label: string;
9
+    /** What inside it, such as 'Heading "Quietly luxurious care"'. Null for the whole section. */
10
+    detail: string | null;
11
+};
12
+
13
+type Found = { element: HTMLElement; id: string; type: string };
14
+
15
+const GREEN = '#10b981';
16
+const LAYER = '2147483646';
17
+/** Moving further than this while holding the button draws a box instead of a click. */
18
+const DRAG_START = 6;
19
+
20
+/** The section an element belongs to, or null for parts that are not sections (such as the WhatsApp button). */
21
+function sectionOf(element: Element | null): Found | null {
22
+    const band = element?.closest<HTMLElement>('[data-section]');
23
+
24
+    if (band) {
25
+        return {
26
+            element: band,
27
+            id: band.dataset.section ?? '',
28
+            type: band.dataset.sectionType ?? '',
29
+        };
30
+    }
31
+
32
+    const header = element?.closest<HTMLElement>('.sf-root header');
33
+
34
+    if (header) {
35
+        return { element: header, id: 'header', type: 'header' };
36
+    }
37
+
38
+    const footer = element?.closest<HTMLElement>('.sf-root footer');
39
+
40
+    if (footer) {
41
+        return { element: footer, id: 'footer', type: 'footer' };
42
+    }
43
+
44
+    return null;
45
+}
46
+
47
+function clip(text: string | null | undefined, length = 80): string {
48
+    const clean = (text ?? '').replace(/\s+/g, ' ').trim();
49
+
50
+    return clean.length > length ? `${clean.slice(0, length - 1)}…` : clean;
51
+}
52
+
53
+/** Name one thing on the page in plain words, such as 'Button "Shop now"'. */
54
+function describe(element: HTMLElement): string {
55
+    const tag = element.tagName.toLowerCase();
56
+
57
+    if (tag === 'img') {
58
+        const alt = clip((element as HTMLImageElement).alt, 60);
59
+
60
+        return alt ? `Photo "${alt}"` : 'Photo';
61
+    }
62
+
63
+    if (tag === 'video' || tag === 'iframe') {
64
+        return 'Video';
65
+    }
66
+
67
+    const text = clip(element.innerText || element.textContent);
68
+    const kind = /^h[1-6]$/.test(tag)
69
+        ? 'Heading'
70
+        : tag === 'button' || element.getAttribute('role') === 'button'
71
+          ? 'Button'
72
+          : tag === 'a'
73
+            ? 'Link'
74
+            : 'Text';
75
+
76
+    return text ? `${kind} "${text}"` : kind;
77
+}
78
+
79
+const THING =
80
+    'img, video, iframe, h1, h2, h3, h4, h5, h6, button, a, p, li, blockquote, summary, dt, dd';
81
+
82
+/** The meaningful thing under the pointer (a heading, photo, button…), inside its section. */
83
+function thingAt(target: Element, section: HTMLElement): HTMLElement | null {
84
+    const thing = target.closest<HTMLElement>(THING);
85
+
86
+    return thing && section.contains(thing) && thing !== section ? thing : null;
87
+}
88
+
89
+function overlap(a: DOMRect, b: DOMRect): number {
90
+    const width = Math.min(a.right, b.right) - Math.max(a.left, b.left);
91
+    const height = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top);
92
+
93
+    return width > 0 && height > 0 ? width * height : 0;
94
+}
95
+
96
+function box(
97
+    doc: Document,
98
+    style: Partial<CSSStyleDeclaration>,
99
+): HTMLDivElement {
100
+    const element = doc.createElement('div');
101
+    Object.assign(
102
+        element.style,
103
+        {
104
+            position: 'fixed',
105
+            pointerEvents: 'none',
106
+            zIndex: LAYER,
107
+            display: 'none',
108
+        } satisfies Partial<CSSStyleDeclaration>,
109
+        style,
110
+    );
111
+    doc.body.appendChild(element);
112
+
113
+    return element;
114
+}
115
+
116
+function place(
117
+    element: HTMLElement,
118
+    rect:
119
+        | DOMRect
120
+        | { left: number; top: number; width: number; height: number },
121
+) {
122
+    Object.assign(element.style, {
123
+        display: 'block',
124
+        left: `${rect.left}px`,
125
+        top: `${rect.top}px`,
126
+        width: `${rect.width}px`,
127
+        height: `${rect.height}px`,
128
+    });
129
+}
130
+
131
+/**
132
+ * Turn on "Select to edit" inside the preview. The merchant can:
133
+ * - click one thing (a heading, photo, button…) to pick it and its section, or
134
+ * - drag a box over an area: the section it covers most is picked, with the things inside the box.
135
+ * A green outline shows what would be picked. Escape stops. Returns a function that stops it.
136
+ */
137
+export function startPicker(
138
+    frame: HTMLIFrameElement,
139
+    onPick: (selection: PreviewSelection) => void,
140
+    onCancel: () => void,
141
+): () => void {
142
+    const doc = frame.contentDocument;
143
+    const win = frame.contentWindow;
144
+
145
+    if (!doc || !win || !doc.body) {
146
+        return () => {};
147
+    }
148
+
149
+    // A clear layer over the page catches the pointer, so links and buttons do not react.
150
+    const shield = box(doc, {
151
+        inset: '0',
152
+        pointerEvents: 'auto',
153
+        cursor: 'crosshair',
154
+        background: 'transparent',
155
+        zIndex: '2147483645',
156
+    });
157
+    shield.style.display = 'block';
158
+
159
+    const outline = box(doc, {
160
+        border: `2px solid ${GREEN}`,
161
+        borderRadius: '8px',
162
+        background: 'rgba(16, 185, 129, 0.08)',
163
+    });
164
+    const area = box(doc, {
165
+        border: `2px dashed ${GREEN}`,
166
+        borderRadius: '6px',
167
+        background: 'rgba(16, 185, 129, 0.12)',
168
+    });
169
+    const tag = doc.createElement('span');
170
+    Object.assign(tag.style, {
171
+        position: 'fixed',
172
+        zIndex: '2147483647',
173
+        pointerEvents: 'none',
174
+        display: 'none',
175
+        padding: '3px 9px',
176
+        borderRadius: '999px',
177
+        background: GREEN,
178
+        color: '#fff',
179
+        font: '600 12px/1.4 system-ui, sans-serif',
180
+        whiteSpace: 'nowrap',
181
+        maxWidth: '90vw',
182
+        overflow: 'hidden',
183
+        textOverflow: 'ellipsis',
184
+    } satisfies Partial<CSSStyleDeclaration>);
185
+    doc.body.appendChild(tag);
186
+
187
+    /** The page element under a point, looking through our own layer. */
188
+    const under = (x: number, y: number): Element | null =>
189
+        doc
190
+            .elementsFromPoint(x, y)
191
+            .find(
192
+                (element) =>
193
+                    element !== shield &&
194
+                    element !== outline &&
195
+                    element !== area &&
196
+                    element !== tag,
197
+            ) ?? null;
198
+
199
+    const label = (text: string, rect: DOMRect) => {
200
+        tag.textContent = text;
201
+        tag.style.display = 'block';
202
+        tag.style.left = `${Math.max(rect.left, 4)}px`;
203
+        tag.style.top = `${Math.max(rect.top - 26, 4)}px`;
204
+    };
205
+
206
+    /** What a click at this point would pick. */
207
+    const atPoint = (x: number, y: number) => {
208
+        const target = under(x, y);
209
+        const section = sectionOf(target);
210
+
211
+        if (!target || !section) {
212
+            return null;
213
+        }
214
+
215
+        const thing = thingAt(target, section.element);
216
+
217
+        return { section, thing };
218
+    };
219
+
220
+    /** What a box over this area would pick. */
221
+    const inArea = (rect: DOMRect) => {
222
+        let best: Found | null = null;
223
+        let most = 0;
224
+
225
+        doc.querySelectorAll<HTMLElement>(
226
+            '[data-section], .sf-root header, .sf-root footer',
227
+        ).forEach((element) => {
228
+            const found = sectionOf(element);
229
+            const covered = overlap(rect, element.getBoundingClientRect());
230
+
231
+            if (found && found.element === element && covered > most) {
232
+                best = found;
233
+                most = covered;
234
+            }
235
+        });
236
+
237
+        if (!best) {
238
+            return null;
239
+        }
240
+
241
+        const chosen: Found = best;
242
+        const things = [...chosen.element.querySelectorAll<HTMLElement>(THING)]
243
+            // Things mostly inside the box (at least 60%), so a rough box still catches them.
244
+            .filter((element) => {
245
+                const inside = element.getBoundingClientRect();
246
+                const size = inside.width * inside.height;
247
+
248
+                return size > 0 && overlap(rect, inside) >= size * 0.6;
249
+            })
250
+            // Skip things inside another picked thing, such as a link inside a list item.
251
+            .filter(
252
+                (element, _, all) =>
253
+                    !all.some(
254
+                        (other) => other !== element && other.contains(element),
255
+                    ),
256
+            );
257
+
258
+        return { section: chosen, things };
259
+    };
260
+
261
+    let start: { x: number; y: number } | null = null;
262
+    let dragging = false;
263
+
264
+    const areaRect = (x: number, y: number) =>
265
+        new DOMRect(
266
+            Math.min(start!.x, x),
267
+            Math.min(start!.y, y),
268
+            Math.abs(x - start!.x),
269
+            Math.abs(y - start!.y),
270
+        );
271
+
272
+    const onMove = (event: PointerEvent) => {
273
+        if (
274
+            start &&
275
+            !dragging &&
276
+            Math.hypot(event.clientX - start.x, event.clientY - start.y) >
277
+                DRAG_START
278
+        ) {
279
+            dragging = true;
280
+        }
281
+
282
+        if (dragging) {
283
+            const rect = areaRect(event.clientX, event.clientY);
284
+            place(area, rect);
285
+            const found = inArea(rect);
286
+
287
+            if (found) {
288
+                place(outline, found.section.element.getBoundingClientRect());
289
+                label(
290
+                    `${sectionName(found.section.type)} · area`,
291
+                    found.section.element.getBoundingClientRect(),
292
+                );
293
+            }
294
+
295
+            return;
296
+        }
297
+
298
+        const found = atPoint(event.clientX, event.clientY);
299
+
300
+        if (!found) {
301
+            outline.style.display = 'none';
302
+            tag.style.display = 'none';
303
+
304
+            return;
305
+        }
306
+
307
+        const shown = found.thing ?? found.section.element;
308
+        const rect = shown.getBoundingClientRect();
309
+        place(
310
+            outline,
311
+            new DOMRect(
312
+                rect.left - 3,
313
+                rect.top - 3,
314
+                rect.width + 6,
315
+                rect.height + 6,
316
+            ),
317
+        );
318
+        label(
319
+            found.thing
320
+                ? `${sectionName(found.section.type)} › ${describe(found.thing).split(' "')[0]}`
321
+                : sectionName(found.section.type),
322
+            rect,
323
+        );
324
+    };
325
+
326
+    const onDown = (event: PointerEvent) => {
327
+        if (event.button !== 0) {
328
+            return;
329
+        }
330
+
331
+        event.preventDefault();
332
+        start = { x: event.clientX, y: event.clientY };
333
+        dragging = false;
334
+        // Keep getting the pointer even if it leaves the preview while drawing a box.
335
+        try {
336
+            shield.setPointerCapture(event.pointerId);
337
+        } catch {
338
+            // Not every pointer can be captured; drawing still works inside the preview.
339
+        }
340
+    };
341
+
342
+    const onUp = (event: PointerEvent) => {
343
+        if (!start) {
344
+            return;
345
+        }
346
+
347
+        if (dragging) {
348
+            const found = inArea(areaRect(event.clientX, event.clientY));
349
+            start = null;
350
+            dragging = false;
351
+            area.style.display = 'none';
352
+
353
+            if (found) {
354
+                const detail = found.things
355
+                    .slice(0, 4)
356
+                    .map(describe)
357
+                    .join(', ');
358
+                onPick({
359
+                    section: found.section.id,
360
+                    label: sectionName(found.section.type),
361
+                    detail: detail ? clip(`Area with: ${detail}`, 300) : null,
362
+                });
363
+            }
364
+
365
+            return;
366
+        }
367
+
368
+        start = null;
369
+        const found = atPoint(event.clientX, event.clientY);
370
+
371
+        if (found) {
372
+            onPick({
373
+                section: found.section.id,
374
+                label: sectionName(found.section.type),
375
+                detail: found.thing ? describe(found.thing) : null,
376
+            });
377
+        }
378
+    };
379
+
380
+    const onKey = (event: KeyboardEvent) => {
381
+        if (event.key === 'Escape') {
382
+            onCancel();
383
+        }
384
+    };
385
+
386
+    const onLeave = () => {
387
+        if (!start) {
388
+            outline.style.display = 'none';
389
+            tag.style.display = 'none';
390
+        }
391
+    };
392
+
393
+    shield.addEventListener('pointermove', onMove);
394
+    shield.addEventListener('pointerdown', onDown);
395
+    shield.addEventListener('pointerup', onUp);
396
+    shield.addEventListener('pointerleave', onLeave);
397
+    doc.addEventListener('keydown', onKey);
398
+
399
+    return () => {
400
+        doc.removeEventListener('keydown', onKey);
401
+        shield.remove();
402
+        outline.remove();
403
+        area.remove();
404
+        tag.remove();
405
+    };
406
+}

+ 21
- 0
resources/js/components/stores/section-names.ts Просмотреть файл

@@ -0,0 +1,21 @@
1
+/** Section types in plain words. Unknown ones fall back to their code name. */
2
+export const typeNames: Record<string, string> = {
3
+    header: 'Header',
4
+    hero: 'Hero',
5
+    trust_bar: 'Trust row',
6
+    shop_by: 'Shop by collection',
7
+    bento: 'Bento tiles',
8
+    video: 'Video',
9
+    product_grid: 'Products',
10
+    featured_product: 'Featured product',
11
+    about: 'About',
12
+    testimonials: 'Reviews',
13
+    faq: 'FAQ',
14
+    newsletter: 'Newsletter',
15
+    contact: 'Contact',
16
+    footer: 'Footer',
17
+};
18
+
19
+export function sectionName(type: string): string {
20
+    return typeNames[type] ?? type.replace(/_/g, ' ');
21
+}

+ 13
- 0
resources/js/components/stores/video-box.tsx Просмотреть файл

@@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button';
8 8
 import { Input } from '@/components/ui/input';
9 9
 import { Label } from '@/components/ui/label';
10 10
 import type { HomeSectionInfo, Store, VideoSectionInfo } from '@/types';
11
+import { SectionName } from '@/components/stores/preview-highlight';
11 12
 
12 13
 const selectClass =
13 14
     'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50 md:text-sm';
@@ -157,6 +158,18 @@ function VideoForm({
157 158
 
158 159
     return (
159 160
         <form onSubmit={submit} className="space-y-3" noValidate>
161
+            {video && (
162
+                <SectionName
163
+                    target={{
164
+                        sectionId: video.section_id,
165
+                        pageId: 'home',
166
+                        label: 'Video',
167
+                    }}
168
+                    className="text-sm font-medium"
169
+                >
170
+                    {video.heading || 'Video'}
171
+                </SectionName>
172
+            )}
160 173
             <div className="grid gap-3 sm:grid-cols-[1fr_auto] sm:items-start">
161 174
                 <div className="grid gap-1.5">
162 175
                     <Label htmlFor={`video-url-${key}`}>

+ 86
- 0
resources/js/components/theme-switch.tsx Просмотреть файл

@@ -0,0 +1,86 @@
1
+import type { LucideIcon } from 'lucide-react';
2
+import { Moon, Sun } from 'lucide-react';
3
+import {
4
+    SidebarMenu,
5
+    SidebarMenuButton,
6
+    SidebarMenuItem,
7
+} from '@/components/ui/sidebar';
8
+import type { ResolvedAppearance } from '@/hooks/use-appearance';
9
+import { useAppearance } from '@/hooks/use-appearance';
10
+import { cn } from '@/lib/utils';
11
+
12
+const options: {
13
+    value: ResolvedAppearance;
14
+    icon: LucideIcon;
15
+    label: string;
16
+}[] = [
17
+    { value: 'light', icon: Sun, label: 'Light' },
18
+    { value: 'dark', icon: Moon, label: 'Dark' },
19
+];
20
+
21
+/**
22
+ * Light or dark, in the sidebar just above the user. One click each.
23
+ * Someone who never chose follows their device, and the switch shows how the page looks now.
24
+ * The choice is saved in this browser and a cookie, the same as Settings → Appearance.
25
+ * With the sidebar folded to icons it becomes one button that flips between the two.
26
+ */
27
+export function ThemeSwitch() {
28
+    const { resolvedAppearance, updateAppearance } = useAppearance();
29
+    const other = resolvedAppearance === 'dark' ? 'light' : 'dark';
30
+    const OtherIcon = other === 'dark' ? Moon : Sun;
31
+
32
+    return (
33
+        <SidebarMenu>
34
+            <SidebarMenuItem>
35
+                <div
36
+                    role="radiogroup"
37
+                    aria-label="Theme"
38
+                    className="grid grid-cols-2 gap-0.5 rounded-lg border border-sidebar-border bg-sidebar-accent/50 p-0.5 group-data-[collapsible=icon]:hidden"
39
+                    data-test="theme-switch"
40
+                >
41
+                    {options.map(({ value, icon: Icon, label }) => {
42
+                        const active = resolvedAppearance === value;
43
+
44
+                        return (
45
+                            <button
46
+                                key={value}
47
+                                type="button"
48
+                                role="radio"
49
+                                aria-checked={active}
50
+                                onClick={() => updateAppearance(value)}
51
+                                className={cn(
52
+                                    'inline-flex h-8 items-center justify-center gap-1.5 rounded-md text-sm transition-colors focus-visible:ring-2 focus-visible:ring-sidebar-ring focus-visible:outline-none',
53
+                                    active
54
+                                        ? 'bg-sidebar font-medium text-sidebar-foreground shadow-sm'
55
+                                        : 'text-sidebar-foreground/60 hover:bg-sidebar/60 hover:text-sidebar-foreground',
56
+                                )}
57
+                            >
58
+                                <Icon className="size-4" aria-hidden="true" />
59
+                                {label}
60
+                            </button>
61
+                        );
62
+                    })}
63
+                </div>
64
+
65
+                <SidebarMenuButton
66
+                    className="hidden group-data-[collapsible=icon]:flex"
67
+                    onClick={() => updateAppearance(other)}
68
+                    tooltip={{
69
+                        children:
70
+                            other === 'dark'
71
+                                ? 'Switch to dark theme'
72
+                                : 'Switch to light theme',
73
+                    }}
74
+                    data-test="theme-toggle"
75
+                >
76
+                    <OtherIcon />
77
+                    <span>
78
+                        {other === 'dark'
79
+                            ? 'Switch to dark theme'
80
+                            : 'Switch to light theme'}
81
+                    </span>
82
+                </SidebarMenuButton>
83
+            </SidebarMenuItem>
84
+        </SidebarMenu>
85
+    );
86
+}

+ 277
- 176
resources/js/pages/stores/show.tsx Просмотреть файл

@@ -6,8 +6,9 @@ import {
6 6
     RefreshCw,
7 7
     Smartphone,
8 8
     Sparkles,
9
+    SquareDashedMousePointer,
9 10
 } from 'lucide-react';
10
-import { useEffect, useState } from 'react';
11
+import { useEffect, useRef, useState } from 'react';
11 12
 import StoreDesignController from '@/actions/App/Http/Controllers/StoreDesignController';
12 13
 import StoreGenerationController from '@/actions/App/Http/Controllers/StoreGenerationController';
13 14
 import DesignChat from '@/components/stores/design-chat';
@@ -18,6 +19,12 @@ import LayoutPicker from '@/components/stores/layout-picker';
18 19
 import VideoBox from '@/components/stores/video-box';
19 20
 import StylePicker from '@/components/stores/style-picker';
20 21
 import DesignProgress from '@/components/stores/design-progress';
22
+import {
23
+    PreviewHighlightContext,
24
+    usePreviewHighlighter,
25
+} from '@/components/stores/preview-highlight';
26
+import { startPicker } from '@/components/stores/preview-picker';
27
+import type { PreviewSelection } from '@/components/stores/preview-picker';
21 28
 import PublishPanel from '@/components/stores/publish-panel';
22 29
 import StoreNav from '@/components/stores/store-nav';
23 30
 import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
@@ -104,6 +111,45 @@ export default function ShowStore({
104 111
     const previewUrl = StoreDesignController.preview[
105 112
         '/stores/{slug}/preview'
106 113
     ].url(store.slug);
114
+    const frameRef = useRef<HTMLIFrameElement>(null);
115
+    const highlighter = usePreviewHighlighter({
116
+        frameRef,
117
+        slug: store.slug,
118
+        homeUrl: previewUrl,
119
+    });
120
+    // "Select to edit": pick a part of the preview, then Ask the AI opens to change it.
121
+    const [selecting, setSelecting] = useState(false);
122
+    const [selection, setSelection] = useState<PreviewSelection | null>(null);
123
+    // Counts preview loads, so the picker starts again after the preview reloads.
124
+    const [frameLoads, setFrameLoads] = useState(0);
125
+
126
+    useEffect(() => {
127
+        const frame = frameRef.current;
128
+
129
+        if (!selecting || !frame) {
130
+            return;
131
+        }
132
+
133
+        const stop = startPicker(
134
+            frame,
135
+            (picked) => {
136
+                setSelection(picked);
137
+                setSelecting(false);
138
+            },
139
+            () => setSelecting(false),
140
+        );
141
+        const onKey = (event: KeyboardEvent) => {
142
+            if (event.key === 'Escape') {
143
+                setSelecting(false);
144
+            }
145
+        };
146
+        window.addEventListener('keydown', onKey);
147
+
148
+        return () => {
149
+            stop();
150
+            window.removeEventListener('keydown', onKey);
151
+        };
152
+    }, [selecting, frameLoads, store.design_version]);
107 153
 
108 154
     const busy =
109 155
         generation?.status === 'queued' || generation?.status === 'running';
@@ -144,7 +190,13 @@ export default function ShowStore({
144 190
         <>
145 191
             <Head title={store.name} />
146 192
 
147
-            <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
193
+            <div
194
+                className={cn(
195
+                    'mx-auto w-full max-w-6xl space-y-6 p-4',
196
+                    // Room at the bottom so the "Ask the AI" button never covers the last box.
197
+                    store.has_design && 'pb-24',
198
+                )}
199
+            >
148 200
                 <div className="flex flex-wrap items-start justify-between gap-3">
149 201
                     <div>
150 202
                         <h1 className="text-xl font-semibold">{store.name}</h1>
@@ -182,195 +234,244 @@ export default function ShowStore({
182 234
                 </Card>
183 235
 
184 236
                 {store.has_design ? (
185
-                    <section className="space-y-3">
186
-                        <div className="flex flex-wrap items-center justify-between gap-3">
187
-                            <div>
188
-                                <h2 className="font-medium">Store design</h2>
189
-                                {store.is_published && (
190
-                                    <p className="text-xs text-muted-foreground">
191
-                                        This preview shows your working design,
192
-                                        including changes that are not published
193
-                                        yet.
194
-                                    </p>
195
-                                )}
196
-                            </div>
237
+                    <PreviewHighlightContext.Provider value={highlighter}>
238
+                        <section className="space-y-3">
239
+                            <div className="flex flex-wrap items-center justify-between gap-3">
240
+                                <div>
241
+                                    <h2 className="font-medium">
242
+                                        Store design
243
+                                    </h2>
244
+                                    {store.is_published && (
245
+                                        <p className="text-xs text-muted-foreground">
246
+                                            This preview shows your working
247
+                                            design, including changes that are
248
+                                            not published yet.
249
+                                        </p>
250
+                                    )}
251
+                                </div>
197 252
 
198
-                            <div className="flex items-center gap-2">
199
-                                <ToggleGroup
200
-                                    type="single"
201
-                                    variant="outline"
202
-                                    size="sm"
203
-                                    value={device}
204
-                                    onValueChange={(value) => {
205
-                                        if (value) {
206
-                                            setDevice(value as Device);
253
+                                <div className="flex flex-wrap items-center gap-2">
254
+                                    <Button
255
+                                        variant={
256
+                                            selecting ? 'default' : 'outline'
207 257
                                         }
208
-                                    }}
209
-                                    aria-label="Preview size"
210
-                                >
211
-                                    <ToggleGroupItem
212
-                                        value="desktop"
213
-                                        aria-label="Desktop preview"
214
-                                    >
215
-                                        <Monitor />
216
-                                    </ToggleGroupItem>
217
-                                    <ToggleGroupItem
218
-                                        value="mobile"
219
-                                        aria-label="Mobile preview"
258
+                                        size="sm"
259
+                                        aria-pressed={selecting}
260
+                                        onClick={() =>
261
+                                            setSelecting((value) => !value)
262
+                                        }
263
+                                        data-test="select-to-edit-button"
220 264
                                     >
221
-                                        <Smartphone />
222
-                                    </ToggleGroupItem>
223
-                                </ToggleGroup>
224
-
225
-                                <Button variant="outline" size="sm" asChild>
226
-                                    <a
227
-                                        href={previewUrl}
228
-                                        target="_blank"
229
-                                        rel="noreferrer"
265
+                                        <SquareDashedMousePointer />
266
+                                        {selecting
267
+                                            ? 'Stop selecting'
268
+                                            : 'Select to edit'}
269
+                                    </Button>
270
+                                    <ToggleGroup
271
+                                        type="single"
272
+                                        variant="outline"
273
+                                        size="sm"
274
+                                        value={device}
275
+                                        onValueChange={(value) => {
276
+                                            if (value) {
277
+                                                setDevice(value as Device);
278
+                                            }
279
+                                        }}
280
+                                        aria-label="Preview size"
230 281
                                     >
231
-                                        <ExternalLink />
232
-                                        Open full page
233
-                                    </a>
234
-                                </Button>
235
-
236
-                                <Dialog
237
-                                    open={confirmOpen}
238
-                                    onOpenChange={setConfirmOpen}
239
-                                >
240
-                                    <DialogTrigger asChild>
241
-                                        <Button
242
-                                            variant="outline"
243
-                                            size="sm"
244
-                                            disabled={busy}
245
-                                            data-test="regenerate-button"
282
+                                        <ToggleGroupItem
283
+                                            value="desktop"
284
+                                            aria-label="Desktop preview"
285
+                                        >
286
+                                            <Monitor />
287
+                                        </ToggleGroupItem>
288
+                                        <ToggleGroupItem
289
+                                            value="mobile"
290
+                                            aria-label="Mobile preview"
246 291
                                         >
247
-                                            <RefreshCw />
248
-                                            Regenerate
249
-                                        </Button>
250
-                                    </DialogTrigger>
251
-                                    <DialogContent>
252
-                                        <DialogHeader>
253
-                                            <DialogTitle>
254
-                                                Design this store again?
255
-                                            </DialogTitle>
256
-                                            <DialogDescription>
257
-                                                The AI will create a completely
258
-                                                new design. Your current design
259
-                                                and every change you made to it
260
-                                                will be replaced. You have{' '}
261
-                                                {regenerationsLeft} of{' '}
262
-                                                {usage.regenerations.limit}{' '}
263
-                                                regenerations left
264
-                                                {usage.period === 'month'
265
-                                                    ? ' this month'
266
-                                                    : ''}
267
-                                                .
268
-                                            </DialogDescription>
269
-                                        </DialogHeader>
270
-                                        <DialogFooter>
271
-                                            <DialogClose asChild>
272
-                                                <Button variant="outline">
273
-                                                    Cancel
274
-                                                </Button>
275
-                                            </DialogClose>
276
-                                            <Form
277
-                                                {...StoreGenerationController.generate.form(
278
-                                                    store.slug,
279
-                                                )}
280
-                                                onSuccess={() =>
281
-                                                    setConfirmOpen(false)
282
-                                                }
292
+                                            <Smartphone />
293
+                                        </ToggleGroupItem>
294
+                                    </ToggleGroup>
295
+
296
+                                    <Button variant="outline" size="sm" asChild>
297
+                                        <a
298
+                                            href={previewUrl}
299
+                                            target="_blank"
300
+                                            rel="noreferrer"
301
+                                        >
302
+                                            <ExternalLink />
303
+                                            Open full page
304
+                                        </a>
305
+                                    </Button>
306
+
307
+                                    <Dialog
308
+                                        open={confirmOpen}
309
+                                        onOpenChange={setConfirmOpen}
310
+                                    >
311
+                                        <DialogTrigger asChild>
312
+                                            <Button
313
+                                                variant="outline"
314
+                                                size="sm"
315
+                                                disabled={busy}
316
+                                                data-test="regenerate-button"
283 317
                                             >
284
-                                                {({ processing }) => (
285
-                                                    <Button
286
-                                                        disabled={
287
-                                                            processing ||
288
-                                                            regenerationsLeft ===
289
-                                                                0
290
-                                                        }
291
-                                                        data-test="confirm-regenerate-button"
292
-                                                    >
293
-                                                        Regenerate
318
+                                                <RefreshCw />
319
+                                                Regenerate
320
+                                            </Button>
321
+                                        </DialogTrigger>
322
+                                        <DialogContent>
323
+                                            <DialogHeader>
324
+                                                <DialogTitle>
325
+                                                    Design this store again?
326
+                                                </DialogTitle>
327
+                                                <DialogDescription>
328
+                                                    The AI will create a
329
+                                                    completely new design. Your
330
+                                                    current design and every
331
+                                                    change you made to it will
332
+                                                    be replaced. You have{' '}
333
+                                                    {regenerationsLeft} of{' '}
334
+                                                    {usage.regenerations.limit}{' '}
335
+                                                    regenerations left
336
+                                                    {usage.period === 'month'
337
+                                                        ? ' this month'
338
+                                                        : ''}
339
+                                                    .
340
+                                                </DialogDescription>
341
+                                            </DialogHeader>
342
+                                            <DialogFooter>
343
+                                                <DialogClose asChild>
344
+                                                    <Button variant="outline">
345
+                                                        Cancel
294 346
                                                     </Button>
295
-                                                )}
296
-                                            </Form>
297
-                                        </DialogFooter>
298
-                                    </DialogContent>
299
-                                </Dialog>
347
+                                                </DialogClose>
348
+                                                <Form
349
+                                                    {...StoreGenerationController.generate.form(
350
+                                                        store.slug,
351
+                                                    )}
352
+                                                    onSuccess={() =>
353
+                                                        setConfirmOpen(false)
354
+                                                    }
355
+                                                >
356
+                                                    {({ processing }) => (
357
+                                                        <Button
358
+                                                            disabled={
359
+                                                                processing ||
360
+                                                                regenerationsLeft ===
361
+                                                                    0
362
+                                                            }
363
+                                                            data-test="confirm-regenerate-button"
364
+                                                        >
365
+                                                            Regenerate
366
+                                                        </Button>
367
+                                                    )}
368
+                                                </Form>
369
+                                            </DialogFooter>
370
+                                        </DialogContent>
371
+                                    </Dialog>
372
+                                </div>
300 373
                             </div>
301
-                        </div>
302 374
 
303
-                        {busy && generation && (
304
-                            <DesignProgress generation={generation} />
305
-                        )}
375
+                            {busy && generation && (
376
+                                <DesignProgress generation={generation} />
377
+                            )}
306 378
 
307
-                        {failed && <FailedNotice generation={failed} />}
379
+                            {failed && <FailedNotice generation={failed} />}
308 380
 
309
-                        <div className="flex justify-center rounded-xl border bg-muted/40 p-3">
310
-                            <iframe
311
-                                key={store.design_version ?? 0}
312
-                                title={`Preview of ${store.name}`}
313
-                                src={previewUrl}
381
+                            {selecting && (
382
+                                <p
383
+                                    className="flex items-center gap-2 rounded-lg border border-emerald-600/30 bg-emerald-50 px-3 py-2 text-sm text-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-200"
384
+                                    role="status"
385
+                                >
386
+                                    <SquareDashedMousePointer
387
+                                        className="size-4 shrink-0"
388
+                                        aria-hidden="true"
389
+                                    />
390
+                                    Click a part of your store, or drag a box
391
+                                    around an area. Press Esc to stop.
392
+                                </p>
393
+                            )}
394
+
395
+                            <div
314 396
                                 className={cn(
315
-                                    'h-[70vh] min-h-[480px] rounded-lg border bg-white transition-[width]',
316
-                                    device === 'mobile'
317
-                                        ? 'w-[390px] max-w-full'
318
-                                        : 'w-full',
397
+                                    'flex justify-center rounded-xl border bg-muted/40 p-3',
398
+                                    selecting &&
399
+                                        'border-emerald-500 ring-2 ring-emerald-500/30',
319 400
                                 )}
401
+                            >
402
+                                <iframe
403
+                                    key={store.design_version ?? 0}
404
+                                    ref={frameRef}
405
+                                    onLoad={() => {
406
+                                        highlighter.onLoad();
407
+                                        setFrameLoads((count) => count + 1);
408
+                                    }}
409
+                                    title={`Preview of ${store.name}`}
410
+                                    src={previewUrl}
411
+                                    className={cn(
412
+                                        'h-[70vh] min-h-[480px] rounded-lg border bg-white transition-[width]',
413
+                                        device === 'mobile'
414
+                                            ? 'w-[390px] max-w-full'
415
+                                            : 'w-full',
416
+                                    )}
417
+                                />
418
+                            </div>
419
+
420
+                            <StylePicker
421
+                                store={store}
422
+                                current={style}
423
+                                presets={stylePresets}
424
+                                busy={busy}
425
+                            />
426
+
427
+                            <HeroPicker
428
+                                store={store}
429
+                                sections={heroSections}
430
+                                choices={heroChoices}
431
+                                busy={busy}
432
+                            />
433
+
434
+                            <LayoutPicker
435
+                                store={store}
436
+                                sections={layoutSections}
437
+                                options={layoutOptions}
438
+                                busy={busy}
439
+                            />
440
+
441
+                            <BentoBox
442
+                                store={store}
443
+                                bentos={bentoSections}
444
+                                homeSections={homeSections}
445
+                                photos={heroChoices}
446
+                                links={linkSuggestions}
447
+                                busy={busy}
448
+                            />
449
+
450
+                            <VideoBox
451
+                                store={store}
452
+                                videos={videoSections}
453
+                                homeSections={homeSections}
454
+                                busy={busy}
320 455
                             />
321
-                        </div>
322 456
 
323
-                        <StylePicker
324
-                            store={store}
325
-                            current={style}
326
-                            presets={stylePresets}
327
-                            busy={busy}
328
-                        />
329
-
330
-                        <HeroPicker
331
-                            store={store}
332
-                            sections={heroSections}
333
-                            choices={heroChoices}
334
-                            busy={busy}
335
-                        />
336
-
337
-                        <LayoutPicker
338
-                            store={store}
339
-                            sections={layoutSections}
340
-                            options={layoutOptions}
341
-                            busy={busy}
342
-                        />
343
-
344
-                        <BentoBox
345
-                            store={store}
346
-                            bentos={bentoSections}
347
-                            homeSections={homeSections}
348
-                            photos={heroChoices}
349
-                            links={linkSuggestions}
350
-                            busy={busy}
351
-                        />
352
-
353
-                        <VideoBox
354
-                            store={store}
355
-                            videos={videoSections}
356
-                            homeSections={homeSections}
357
-                            busy={busy}
358
-                        />
359
-
360
-                        <FeaturedPicker
361
-                            store={store}
362
-                            sections={featuredSections}
363
-                            products={productOptions}
364
-                            busy={busy}
365
-                        />
366
-
367
-                        <DesignChat
368
-                            store={store}
369
-                            edits={edits}
370
-                            usage={usage.edits}
371
-                            busy={busy}
372
-                        />
373
-                    </section>
457
+                            <FeaturedPicker
458
+                                store={store}
459
+                                sections={featuredSections}
460
+                                products={productOptions}
461
+                                busy={busy}
462
+                            />
463
+
464
+                            <DesignChat
465
+                                store={store}
466
+                                edits={edits}
467
+                                usage={usage.edits}
468
+                                busy={busy}
469
+                                selection={selection}
470
+                                onClearSelection={() => setSelection(null)}
471
+                                onStartSelecting={() => setSelecting(true)}
472
+                            />
473
+                        </section>
474
+                    </PreviewHighlightContext.Provider>
374 475
                 ) : busy && generation ? (
375 476
                     <DesignProgress generation={generation} />
376 477
                 ) : (

+ 2
- 0
resources/js/storefront/renderer.tsx Просмотреть файл

@@ -122,6 +122,8 @@ function PageBody({ plan, view }: { plan: StorePlan; view: StorefrontView }) {
122 122
             {page?.sections.map((section, index) => (
123 123
                 <div
124 124
                     key={section.id}
125
+                    data-section={section.id}
126
+                    data-section-type={section.type}
125 127
                     className={cn(
126 128
                         'sf-band',
127 129
                         alternate.has(index) && 'sf-band-alt',

+ 2
- 0
resources/js/types/store.ts Просмотреть файл

@@ -28,6 +28,8 @@ export type StoreGeneration = {
28 28
     type: 'generate' | 'edit';
29 29
     status: 'queued' | 'running' | 'completed' | 'failed';
30 30
     instruction: string | null;
31
+    /** The part of the store selected in the preview for this request, if any. */
32
+    target: { label: string; detail: string | null } | null;
31 33
     reply: string | null;
32 34
     /** For a finished edit: whether the design really changed. Checked by the app, not taken from the AI. */
33 35
     changed: boolean | null;

+ 32
- 0
tests/Feature/Stores/HeroImageTest.php Просмотреть файл

@@ -3,6 +3,7 @@
3 3
 namespace Tests\Feature\Stores;
4 4
 
5 5
 use App\Enums\GenerationStatus;
6
+use App\Jobs\PrepareBannerPhoto;
6 7
 use App\Models\Product;
7 8
 use App\Models\Store;
8 9
 use App\Models\StoreImage;
@@ -128,6 +129,9 @@ class HeroImageTest extends TestCase
128 129
 
129 130
         $image = StoreImage::firstOrFail();
130 131
         Storage::disk('public')->assertExists($image->path);
132
+        // Got ready in the background: saved as WebP, and the uploaded file is gone.
133
+        $this->assertStringEndsWith('.webp', $image->path);
134
+        $this->assertCount(1, Storage::disk('public')->allFiles());
131 135
 
132 136
         $section = HeroImages::sections($this->store->fresh()->plan)[0];
133 137
         $this->assertSame('upload:'.$image->id, $section['image']);
@@ -142,6 +146,34 @@ class HeroImageTest extends TestCase
142 146
         $this->assertSame(1, StoreImage::count());
143 147
     }
144 148
 
149
+    public function test_small_banner_photos_are_enlarged_and_huge_ones_made_smaller()
150
+    {
151
+        $hero = $this->heroId();
152
+
153
+        foreach ([[400, 300, 1600, 1200], [3200, 2000, 2400, 1500], [1800, 1000, 1800, 1000]] as [$width, $height, $wantWidth, $wantHeight]) {
154
+            $this->post(route('stores.hero.upload', [$this->store->slug, $hero]), [
155
+                'photo' => UploadedFile::fake()->image('banner.png', $width, $height),
156
+            ])->assertSessionHasNoErrors();
157
+
158
+            $path = StoreImage::latest('id')->firstOrFail()->path;
159
+            $size = getimagesizefromstring(Storage::disk('public')->get($path));
160
+
161
+            $this->assertSame([$wantWidth, $wantHeight], [$size[0], $size[1]], "{$width}x{$height}");
162
+            $this->assertSame('image/webp', $size['mime']);
163
+        }
164
+    }
165
+
166
+    public function test_a_photo_that_cannot_be_prepared_stays_as_uploaded()
167
+    {
168
+        $image = $this->store->images()->create(['path' => "stores/{$this->store->id}/broken.jpg"]);
169
+        Storage::disk('public')->put($image->path, 'not really a photo');
170
+
171
+        PrepareBannerPhoto::dispatch($image);
172
+
173
+        $this->assertSame("stores/{$this->store->id}/broken.jpg", $image->fresh()->path);
174
+        Storage::disk('public')->assertExists($image->path);
175
+    }
176
+
145 177
     public function test_the_checker_allows_photo_layouts_and_photo_names()
146 178
     {
147 179
         $validator = app(PlanValidator::class);

+ 161
- 0
tests/Feature/Stores/SelectToEditTest.php Просмотреть файл

@@ -0,0 +1,161 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Models\Store;
6
+use App\Models\StoreGeneration;
7
+use App\Models\User;
8
+use App\StorePlan\SamplePlan;
9
+use Illuminate\Foundation\Testing\RefreshDatabase;
10
+use Inertia\Testing\AssertableInertia as Assert;
11
+use Tests\Support\ScriptedDriver;
12
+use Tests\TestCase;
13
+
14
+/**
15
+ * The merchant selects a part of the store in the preview, then asks the AI to change "this".
16
+ */
17
+class SelectToEditTest extends TestCase
18
+{
19
+    use RefreshDatabase;
20
+
21
+    private Store $store;
22
+
23
+    protected function setUp(): void
24
+    {
25
+        parent::setUp();
26
+
27
+        $user = User::factory()->create();
28
+        $this->store = Store::factory()->for($user)->create();
29
+        $this->store->plan = SamplePlan::for($this->store);
30
+        $this->store->save();
31
+        $this->actingAs($user);
32
+    }
33
+
34
+    /**
35
+     * @param  array<string, mixed>  $answer
36
+     * @param  array<string, string>  $target
37
+     */
38
+    private function ask(array $answer, array $target, string $instruction = 'Make this shorter'): StoreGeneration
39
+    {
40
+        ScriptedDriver::use([(string) json_encode($answer)]);
41
+
42
+        $this->post(route('stores.edits', $this->store->slug), ['instruction' => $instruction, ...$target])
43
+            ->assertSessionHasNoErrors();
44
+
45
+        return $this->store->generations()->latest('id')->firstOrFail();
46
+    }
47
+
48
+    /**
49
+     * @return array<string, mixed>
50
+     */
51
+    private function section(string $id): array
52
+    {
53
+        foreach ($this->store->fresh()->plan['pages'][0]['sections'] as $section) {
54
+            if ($section['id'] === $id) {
55
+                return $section;
56
+            }
57
+        }
58
+
59
+        $this->fail("No section {$id}.");
60
+    }
61
+
62
+    public function test_only_the_selected_section_changes_whatever_the_ai_sends()
63
+    {
64
+        $before = $this->store->plan;
65
+
66
+        $edit = $this->ask([
67
+            'reply' => 'Shorter now.',
68
+            'update' => [
69
+                ['id' => 'hero', 'content' => ['headline' => 'Short and sweet']],
70
+                ['id' => 'faq', 'content' => ['heading' => 'Not asked for']],
71
+            ],
72
+            'theme' => ['colors' => ['primary' => '#111111']],
73
+            'remove' => ['newsletter'],
74
+        ], [
75
+            'target_section' => 'hero',
76
+            'target_label' => 'Hero',
77
+            'target_detail' => 'Heading "Welcome to our store"',
78
+        ]);
79
+
80
+        $this->assertSame('completed', $edit->status->value);
81
+        $this->assertTrue($edit->changed);
82
+        $this->assertSame(['section' => 'hero', 'label' => 'Hero', 'detail' => 'Heading "Welcome to our store"'], $edit->target);
83
+
84
+        $this->assertSame('Short and sweet', $this->section('hero')['content']['headline']);
85
+        $this->assertEquals($before['theme'], $this->store->fresh()->plan['theme']);
86
+        $this->assertEquals($before['pages'][0]['sections'][8], $this->section('faq'));
87
+        $this->section('newsletter');
88
+
89
+        // The AI was told what was selected.
90
+        $prompt = ScriptedDriver::$requests[0]->prompt;
91
+        $this->assertStringContainsString('section id: "hero" (type hero, on page "home")', $prompt);
92
+        $this->assertStringContainsString('Inside it they selected: Heading "Welcome to our store"', $prompt);
93
+    }
94
+
95
+    public function test_a_section_can_be_removed_or_followed_by_a_new_one()
96
+    {
97
+        $this->ask([
98
+            'reply' => 'Added one below.',
99
+            'add' => [
100
+                ['page' => 'home', 'after' => 'about', 'section' => ['id' => 'more', 'type' => 'about', 'variant' => 'simple', 'content' => ['heading' => 'More', 'body' => 'More about us.', 'stats' => []]]],
101
+                ['page' => 'home', 'after' => 'hero', 'section' => ['id' => 'elsewhere', 'type' => 'about', 'variant' => 'simple', 'content' => ['heading' => 'No', 'body' => 'Not here.', 'stats' => []]]],
102
+            ],
103
+        ], ['target_section' => 'about', 'target_label' => 'About'], 'Add a section below this');
104
+
105
+        $ids = array_column($this->store->fresh()->plan['pages'][0]['sections'], 'id');
106
+        $this->assertSame('more', $ids[array_search('about', $ids, true) + 1]);
107
+        $this->assertNotContains('elsewhere', $ids);
108
+
109
+        $this->ask(['reply' => 'Removed.', 'remove' => ['about', 'faq']], ['target_section' => 'about', 'target_label' => 'About'], 'Remove this');
110
+
111
+        $ids = array_column($this->store->fresh()->plan['pages'][0]['sections'], 'id');
112
+        $this->assertNotContains('about', $ids);
113
+        $this->assertContains('faq', $ids);
114
+    }
115
+
116
+    public function test_the_header_can_be_selected()
117
+    {
118
+        $theme = $this->store->plan['theme'];
119
+
120
+        $this->ask([
121
+            'reply' => 'Renamed.',
122
+            'header' => ['content' => ['logoText' => 'New Name']],
123
+            'footer' => ['content' => ['text' => 'Not asked for']],
124
+            'theme' => ['radius' => 'none'],
125
+        ], ['target_section' => 'header', 'target_label' => 'Header'], 'Change this name');
126
+
127
+        $plan = $this->store->fresh()->plan;
128
+        $this->assertSame('New Name', $plan['header']['content']['logoText']);
129
+        $this->assertNotSame('Not asked for', $plan['footer']['content']['text'] ?? null);
130
+        $this->assertEquals($theme, $plan['theme']);
131
+    }
132
+
133
+    public function test_a_whole_store_change_with_a_part_selected_changes_nothing()
134
+    {
135
+        $edit = $this->ask(
136
+            ['reply' => 'That would change the whole store.', 'theme' => ['colors' => ['primary' => '#111111']]],
137
+            ['target_section' => 'products', 'target_label' => 'Products'],
138
+            'Make the colours dark',
139
+        );
140
+
141
+        $this->assertFalse($edit->changed);
142
+
143
+        $this->get(route('stores.show', $this->store->slug))
144
+            ->assertInertia(fn (Assert $page) => $page
145
+                ->where('edits.0.target.label', 'Products')
146
+                ->where('edits.0.changed', false));
147
+    }
148
+
149
+    public function test_a_section_that_no_longer_exists_is_refused()
150
+    {
151
+        ScriptedDriver::use([]);
152
+
153
+        $this->post(route('stores.edits', $this->store->slug), [
154
+            'instruction' => 'Change this',
155
+            'target_section' => 'gone',
156
+            'target_label' => 'FAQ',
157
+        ])->assertSessionHasErrors('instruction');
158
+
159
+        $this->assertSame(0, $this->store->generations()->count());
160
+    }
161
+}

Загрузка…
Отмена
Сохранить