52 lines
2.1 KiB
TypeScript
52 lines
2.1 KiB
TypeScript
// Adapted from legacy singleProduct.vue's own fetch (GET /product/:id).
|
|
// The new API has no single-product-detail endpoint (only GET
|
|
// /catalog/products, the flat list), so the product is found in the shared
|
|
// catalogue (stores/catalogStore.ts). When the catalogue is already cached,
|
|
// opening a product costs no request at all.
|
|
//
|
|
// `initial` seeds the page with the ProductSummary the tapped card already
|
|
// holds — the same shape, from the same endpoint — so the detail view renders
|
|
// complete on its first frame instead of mounting blank and jumping when the
|
|
// fetch lands. The lookup still runs, silently, and only replaces the product
|
|
// if the catalogue's copy actually differs (stock moved since the list loaded).
|
|
//
|
|
// The silent refresh waits until the opening morph (ProductMorph.vue, ≤420ms)
|
|
// is over: if the catalogue has to come from the server, parsing it — or
|
|
// swapping the product and re-rendering — mid-animation drops frames.
|
|
import { ref } from 'vue'
|
|
import type { ProductSummary } from '../api/client'
|
|
import { useCatalogStore } from '../stores/catalogStore'
|
|
|
|
const SEEDED_REFRESH_DELAY_MS = 600
|
|
|
|
export function useProductDetail(id: string, initial?: ProductSummary | null) {
|
|
const catalog = useCatalogStore()
|
|
const loading = ref(false)
|
|
const flag = ref(Boolean(initial))
|
|
const notFound = ref(false)
|
|
const productRef = ref<ProductSummary | null>(initial ?? null)
|
|
|
|
const load = async () => {
|
|
const seeded = productRef.value !== null
|
|
if (seeded) await new Promise((resolve) => setTimeout(resolve, SEEDED_REFRESH_DELAY_MS))
|
|
else loading.value = true
|
|
try {
|
|
const products = await catalog.load()
|
|
const found = products.find((p) => p.id === id) ?? null
|
|
if (seeded) {
|
|
if (found && JSON.stringify(found) !== JSON.stringify(productRef.value)) productRef.value = found
|
|
} else {
|
|
productRef.value = found
|
|
notFound.value = !found
|
|
}
|
|
flag.value = true
|
|
} catch (e) {
|
|
console.log(e)
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
return { loading, flag, notFound, productRef, load }
|
|
}
|