import { Controller } from '@hotwired/stimulus' import { formatPrice } from '../utils/format-price' export default class extends Controller { static targets = ['price', 'image', 'swatch', 'colorName', 'stockError'] static values = { variants: Array, selected: Number, stockCheckUrl: String, // Two pre-rendered translated templates (see product/show.blade.php) // rather than one — this controller doesn't reimplement Laravel's // pluralization rules, it just picks whichever of these two the // count actually needs and fills in the number. stockErrorOne: String, stockErrorMany: String, } connect() { const params = new URLSearchParams(window.location.search) const urlId = parseInt(params.get('variant')) const urlVariant = this.variantsValue.find(v => v.id === urlId) const initial = urlVariant ?? this.variantsValue[0] // A product can have several independent options (e.g. size + style // + person-count) — this tracks the currently-picked value id per // option handle, and selectVariant() below resolves the full // combination back to one exact variant on every change. this.selections = { ...initial?.options } this.selectedValue = initial?.id // Capture phase, on this controller's own root element (an ancestor // of the checkout module's add-to-cart