@cimplify/sdk 0.9.6 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.mjs CHANGED
@@ -793,14 +793,6 @@ var CatalogueQueries = class {
793
793
  async getBundles() {
794
794
  return safe(this.client.get("/api/v1/catalogue/bundles"));
795
795
  }
796
- async getBundle(id) {
797
- const encodedId = encodeURIComponent(id);
798
- return safe(this.client.get(`/api/v1/catalogue/bundles/${encodedId}`));
799
- }
800
- async getBundleBySlug(slug) {
801
- const encodedSlug = encodeURIComponent(slug);
802
- return safe(this.client.get(`/api/v1/catalogue/bundles/slug/${encodedSlug}`));
803
- }
804
796
  async searchBundles(query, limit = 20) {
805
797
  const path = withQuery("/api/v1/catalogue/bundles", { search: query, limit });
806
798
  return safe(this.client.get(path));
@@ -809,18 +801,6 @@ var CatalogueQueries = class {
809
801
  const path = withQuery("/api/v1/catalogue/composites", { limit: options?.limit });
810
802
  return safe(this.client.get(path));
811
803
  }
812
- async getComposite(id) {
813
- const encodedId = encodeURIComponent(id);
814
- return safe(this.client.get(`/api/v1/catalogue/composites/${encodedId}`));
815
- }
816
- async getCompositeByProductId(productId) {
817
- const encodedId = encodeURIComponent(productId);
818
- return safe(
819
- this.client.get(
820
- `/api/v1/catalogue/composites/by-product/${encodedId}`
821
- )
822
- );
823
- }
824
804
  async calculateCompositePrice(compositeId, selections, locationId) {
825
805
  const encodedId = encodeURIComponent(compositeId);
826
806
  return safe(
@@ -6013,256 +5993,6 @@ function useCollection(idOrSlug, options = {}) {
6013
5993
  }, [cacheKey, load]);
6014
5994
  return { collection, products, isLoading, error, refetch };
6015
5995
  }
6016
- var bundleCache = /* @__PURE__ */ new Map();
6017
- var bundleInflight = /* @__PURE__ */ new Map();
6018
- function isLikelySlug3(value) {
6019
- return /^[a-z0-9-]+$/.test(value);
6020
- }
6021
- function buildBundleCacheKey(client, locationId, idOrSlug) {
6022
- return JSON.stringify({
6023
- key: client.getPublicKey(),
6024
- location_id: locationId || "__none__",
6025
- bundle: idOrSlug
6026
- });
6027
- }
6028
- function useBundle(idOrSlug, options = {}) {
6029
- const context = useOptionalCimplify();
6030
- const client = options.client ?? context?.client;
6031
- if (!client) {
6032
- throw new Error("useBundle must be used within CimplifyProvider or passed { client }.");
6033
- }
6034
- const enabled = options.enabled ?? true;
6035
- const locationId = client.getLocationId();
6036
- const previousLocationIdRef = useRef(locationId);
6037
- const requestIdRef = useRef(0);
6038
- const normalizedIdOrSlug = useMemo(() => (idOrSlug || "").trim(), [idOrSlug]);
6039
- const cacheKey = useMemo(
6040
- () => buildBundleCacheKey(client, locationId, normalizedIdOrSlug),
6041
- [client, locationId, normalizedIdOrSlug]
6042
- );
6043
- const cached = bundleCache.get(cacheKey);
6044
- const [bundle, setBundle] = useState(cached?.bundle ?? null);
6045
- const [isLoading, setIsLoading] = useState(
6046
- enabled && normalizedIdOrSlug.length > 0 && !cached
6047
- );
6048
- const [error, setError] = useState(null);
6049
- useEffect(() => {
6050
- if (previousLocationIdRef.current !== locationId) {
6051
- bundleCache.clear();
6052
- bundleInflight.clear();
6053
- previousLocationIdRef.current = locationId;
6054
- }
6055
- }, [locationId]);
6056
- const load = useCallback(
6057
- async (force = false) => {
6058
- if (!enabled || normalizedIdOrSlug.length === 0) {
6059
- setBundle(null);
6060
- setIsLoading(false);
6061
- return;
6062
- }
6063
- const nextRequestId = ++requestIdRef.current;
6064
- setError(null);
6065
- if (!force) {
6066
- const cacheEntry = bundleCache.get(cacheKey);
6067
- if (cacheEntry) {
6068
- setBundle(cacheEntry.bundle);
6069
- setIsLoading(false);
6070
- return;
6071
- }
6072
- }
6073
- setIsLoading(true);
6074
- try {
6075
- const existing = bundleInflight.get(cacheKey);
6076
- const promise = existing ?? (async () => {
6077
- const result = isLikelySlug3(normalizedIdOrSlug) ? await client.catalogue.getBundleBySlug(normalizedIdOrSlug) : await client.catalogue.getBundle(normalizedIdOrSlug);
6078
- if (!result.ok) {
6079
- throw result.error;
6080
- }
6081
- return result.value;
6082
- })();
6083
- if (!existing) {
6084
- bundleInflight.set(cacheKey, promise);
6085
- promise.finally(() => {
6086
- bundleInflight.delete(cacheKey);
6087
- }).catch(() => void 0);
6088
- }
6089
- const value = await promise;
6090
- bundleCache.set(cacheKey, { bundle: value });
6091
- if (nextRequestId === requestIdRef.current) {
6092
- setBundle(value);
6093
- setError(null);
6094
- }
6095
- } catch (loadError) {
6096
- if (nextRequestId === requestIdRef.current) {
6097
- setError(loadError);
6098
- }
6099
- } finally {
6100
- if (nextRequestId === requestIdRef.current) {
6101
- setIsLoading(false);
6102
- }
6103
- }
6104
- },
6105
- [cacheKey, client, enabled, normalizedIdOrSlug]
6106
- );
6107
- useEffect(() => {
6108
- void load(false);
6109
- }, [load]);
6110
- const refetch = useCallback(async () => {
6111
- bundleCache.delete(cacheKey);
6112
- await load(true);
6113
- }, [cacheKey, load]);
6114
- return { bundle, isLoading, error, refetch };
6115
- }
6116
- var compositeCache = /* @__PURE__ */ new Map();
6117
- var compositeInflight = /* @__PURE__ */ new Map();
6118
- function shouldFetchByProductId(idOrProductId, byProductId) {
6119
- if (typeof byProductId === "boolean") {
6120
- return byProductId;
6121
- }
6122
- return idOrProductId.startsWith("prod_");
6123
- }
6124
- function buildCompositeCacheKey(client, locationId, idOrProductId, byProductId) {
6125
- return JSON.stringify({
6126
- key: client.getPublicKey(),
6127
- location_id: locationId || "__none__",
6128
- composite: idOrProductId,
6129
- by_product_id: byProductId
6130
- });
6131
- }
6132
- function useComposite(idOrProductId, options = {}) {
6133
- const context = useOptionalCimplify();
6134
- const client = options.client ?? context?.client;
6135
- if (!client) {
6136
- throw new Error("useComposite must be used within CimplifyProvider or passed { client }.");
6137
- }
6138
- const enabled = options.enabled ?? true;
6139
- const locationId = client.getLocationId();
6140
- const previousLocationIdRef = useRef(locationId);
6141
- const requestIdRef = useRef(0);
6142
- const priceRequestIdRef = useRef(0);
6143
- const normalizedIdOrProductId = useMemo(
6144
- () => (idOrProductId || "").trim(),
6145
- [idOrProductId]
6146
- );
6147
- const byProductId = useMemo(
6148
- () => shouldFetchByProductId(normalizedIdOrProductId, options.byProductId),
6149
- [normalizedIdOrProductId, options.byProductId]
6150
- );
6151
- const cacheKey = useMemo(
6152
- () => buildCompositeCacheKey(client, locationId, normalizedIdOrProductId, byProductId),
6153
- [byProductId, client, locationId, normalizedIdOrProductId]
6154
- );
6155
- const cached = compositeCache.get(cacheKey);
6156
- const [composite, setComposite] = useState(cached?.composite ?? null);
6157
- const [isLoading, setIsLoading] = useState(
6158
- enabled && normalizedIdOrProductId.length > 0 && !cached
6159
- );
6160
- const [error, setError] = useState(null);
6161
- const [priceResult, setPriceResult] = useState(null);
6162
- const [isPriceLoading, setIsPriceLoading] = useState(false);
6163
- useEffect(() => {
6164
- if (previousLocationIdRef.current !== locationId) {
6165
- compositeCache.clear();
6166
- compositeInflight.clear();
6167
- previousLocationIdRef.current = locationId;
6168
- }
6169
- }, [locationId]);
6170
- const load = useCallback(
6171
- async (force = false) => {
6172
- if (!enabled || normalizedIdOrProductId.length === 0) {
6173
- setComposite(null);
6174
- setPriceResult(null);
6175
- setIsLoading(false);
6176
- return;
6177
- }
6178
- const nextRequestId = ++requestIdRef.current;
6179
- setError(null);
6180
- if (!force) {
6181
- const cacheEntry = compositeCache.get(cacheKey);
6182
- if (cacheEntry) {
6183
- setComposite(cacheEntry.composite);
6184
- setIsLoading(false);
6185
- return;
6186
- }
6187
- }
6188
- setIsLoading(true);
6189
- try {
6190
- const existing = compositeInflight.get(cacheKey);
6191
- const promise = existing ?? (async () => {
6192
- const result = byProductId ? await client.catalogue.getCompositeByProductId(normalizedIdOrProductId) : await client.catalogue.getComposite(normalizedIdOrProductId);
6193
- if (!result.ok) {
6194
- throw result.error;
6195
- }
6196
- return result.value;
6197
- })();
6198
- if (!existing) {
6199
- compositeInflight.set(cacheKey, promise);
6200
- promise.finally(() => {
6201
- compositeInflight.delete(cacheKey);
6202
- }).catch(() => void 0);
6203
- }
6204
- const value = await promise;
6205
- compositeCache.set(cacheKey, { composite: value });
6206
- if (nextRequestId === requestIdRef.current) {
6207
- setComposite(value);
6208
- setPriceResult(null);
6209
- setError(null);
6210
- }
6211
- } catch (loadError) {
6212
- if (nextRequestId === requestIdRef.current) {
6213
- setError(loadError);
6214
- }
6215
- } finally {
6216
- if (nextRequestId === requestIdRef.current) {
6217
- setIsLoading(false);
6218
- }
6219
- }
6220
- },
6221
- [byProductId, cacheKey, client, enabled, normalizedIdOrProductId]
6222
- );
6223
- useEffect(() => {
6224
- void load(false);
6225
- }, [load]);
6226
- const calculatePrice = useCallback(
6227
- async (selections, overrideLocationId) => {
6228
- if (!composite) {
6229
- return null;
6230
- }
6231
- const nextRequestId = ++priceRequestIdRef.current;
6232
- setIsPriceLoading(true);
6233
- try {
6234
- const result = await client.catalogue.calculateCompositePrice(
6235
- composite.id,
6236
- selections,
6237
- overrideLocationId
6238
- );
6239
- if (!result.ok) {
6240
- throw result.error;
6241
- }
6242
- if (nextRequestId === priceRequestIdRef.current) {
6243
- setPriceResult(result.value);
6244
- setError(null);
6245
- }
6246
- return result.value;
6247
- } catch (loadError) {
6248
- if (nextRequestId === priceRequestIdRef.current) {
6249
- setError(loadError);
6250
- }
6251
- return null;
6252
- } finally {
6253
- if (nextRequestId === priceRequestIdRef.current) {
6254
- setIsPriceLoading(false);
6255
- }
6256
- }
6257
- },
6258
- [client, composite]
6259
- );
6260
- const refetch = useCallback(async () => {
6261
- compositeCache.delete(cacheKey);
6262
- await load(true);
6263
- }, [cacheKey, load]);
6264
- return { composite, isLoading, error, refetch, calculatePrice, priceResult, isPriceLoading };
6265
- }
6266
5996
  function useSearch(options = {}) {
6267
5997
  const context = useOptionalCimplify();
6268
5998
  const client = options.client ?? context?.client;
@@ -7016,517 +6746,6 @@ function AddOnSelector({
7016
6746
  ] }, addOn.id);
7017
6747
  }) });
7018
6748
  }
7019
- function CompositeSelector({
7020
- productId,
7021
- onSelectionsChange,
7022
- onPriceChange,
7023
- onReady,
7024
- className
7025
- }) {
7026
- const { composite, isLoading, error, calculatePrice, priceResult, isPriceLoading } = useComposite(productId);
7027
- const [groupSelections, setGroupSelections] = useState({});
7028
- const selections = useMemo(() => {
7029
- const result = [];
7030
- for (const groupSels of Object.values(groupSelections)) {
7031
- for (const [componentId, qty] of Object.entries(groupSels)) {
7032
- if (qty > 0) {
7033
- result.push({ component_id: componentId, quantity: qty });
7034
- }
7035
- }
7036
- }
7037
- return result;
7038
- }, [groupSelections]);
7039
- useEffect(() => {
7040
- onSelectionsChange(selections);
7041
- }, [selections, onSelectionsChange]);
7042
- useEffect(() => {
7043
- onPriceChange?.(priceResult);
7044
- }, [priceResult, onPriceChange]);
7045
- const allGroupsSatisfied = useMemo(() => {
7046
- if (!composite) return false;
7047
- for (const group of composite.groups) {
7048
- const groupSels = groupSelections[group.id] || {};
7049
- const totalSelected = Object.values(groupSels).reduce((sum, q) => sum + q, 0);
7050
- if (totalSelected < group.min_selections) return false;
7051
- }
7052
- return true;
7053
- }, [composite, groupSelections]);
7054
- useEffect(() => {
7055
- onReady?.(allGroupsSatisfied);
7056
- }, [allGroupsSatisfied, onReady]);
7057
- useEffect(() => {
7058
- if (allGroupsSatisfied && selections.length > 0) {
7059
- void calculatePrice(selections);
7060
- }
7061
- }, [selections, allGroupsSatisfied, calculatePrice]);
7062
- const toggleComponent = useCallback(
7063
- (group, component) => {
7064
- setGroupSelections((prev) => {
7065
- const groupSels = { ...prev[group.id] || {} };
7066
- const currentQty = groupSels[component.id] || 0;
7067
- if (currentQty > 0) {
7068
- if (group.min_selections > 0) {
7069
- const totalOthers = Object.entries(groupSels).filter(([id]) => id !== component.id).reduce((sum, [, q]) => sum + q, 0);
7070
- if (totalOthers < group.min_selections) {
7071
- return prev;
7072
- }
7073
- }
7074
- delete groupSels[component.id];
7075
- } else {
7076
- const totalSelected = Object.values(groupSels).reduce((sum, q) => sum + q, 0);
7077
- if (group.max_selections && totalSelected >= group.max_selections) {
7078
- if (group.max_selections === 1) {
7079
- return { ...prev, [group.id]: { [component.id]: 1 } };
7080
- }
7081
- return prev;
7082
- }
7083
- groupSels[component.id] = 1;
7084
- }
7085
- return { ...prev, [group.id]: groupSels };
7086
- });
7087
- },
7088
- []
7089
- );
7090
- const updateQuantity = useCallback(
7091
- (group, componentId, delta) => {
7092
- setGroupSelections((prev) => {
7093
- const groupSels = { ...prev[group.id] || {} };
7094
- const current = groupSels[componentId] || 0;
7095
- const next = Math.max(0, current + delta);
7096
- if (group.max_quantity_per_component && next > group.max_quantity_per_component) {
7097
- return prev;
7098
- }
7099
- if (next === 0) {
7100
- delete groupSels[componentId];
7101
- } else {
7102
- groupSels[componentId] = next;
7103
- }
7104
- return { ...prev, [group.id]: groupSels };
7105
- });
7106
- },
7107
- []
7108
- );
7109
- if (isLoading) {
7110
- return /* @__PURE__ */ jsx("div", { "data-cimplify-composite-selector": true, "data-loading": true, className, children: "Loading options..." });
7111
- }
7112
- if (error || !composite) {
7113
- return null;
7114
- }
7115
- return /* @__PURE__ */ jsxs("div", { "data-cimplify-composite-selector": true, className, children: [
7116
- composite.groups.sort((a, b) => a.display_order - b.display_order).map((group) => {
7117
- const groupSels = groupSelections[group.id] || {};
7118
- const totalSelected = Object.values(groupSels).reduce((sum, q) => sum + q, 0);
7119
- const minMet = totalSelected >= group.min_selections;
7120
- const isSingleSelect = group.max_selections === 1;
7121
- return /* @__PURE__ */ jsxs("div", { "data-cimplify-composite-group": true, children: [
7122
- /* @__PURE__ */ jsxs("div", { "data-cimplify-composite-group-header": true, children: [
7123
- /* @__PURE__ */ jsxs("div", { children: [
7124
- /* @__PURE__ */ jsxs("span", { "data-cimplify-composite-group-name": true, children: [
7125
- group.name,
7126
- group.min_selections > 0 && /* @__PURE__ */ jsx("span", { "data-cimplify-composite-required": true, children: " *" })
7127
- ] }),
7128
- group.description && /* @__PURE__ */ jsx("span", { "data-cimplify-composite-group-description": true, children: group.description }),
7129
- /* @__PURE__ */ jsx("span", { "data-cimplify-composite-group-constraint": true, children: group.min_selections > 0 && group.max_selections ? `Choose ${group.min_selections}\u2013${group.max_selections}` : group.min_selections > 0 ? `Choose at least ${group.min_selections}` : group.max_selections ? `Choose up to ${group.max_selections}` : "Choose as many as you like" })
7130
- ] }),
7131
- !minMet && /* @__PURE__ */ jsx("span", { "data-cimplify-composite-validation": true, children: "Required" })
7132
- ] }),
7133
- /* @__PURE__ */ jsx("div", { "data-cimplify-composite-components": true, children: group.components.filter((c) => c.is_available && !c.is_archived).sort((a, b) => a.display_order - b.display_order).map((component) => {
7134
- const qty = groupSels[component.id] || 0;
7135
- const isSelected = qty > 0;
7136
- const displayName = component.display_name || component.product_id || component.id;
7137
- return /* @__PURE__ */ jsxs(
7138
- "button",
7139
- {
7140
- type: "button",
7141
- role: isSingleSelect ? "radio" : "checkbox",
7142
- "aria-checked": isSelected,
7143
- onClick: () => toggleComponent(group, component),
7144
- "data-cimplify-composite-component": true,
7145
- "data-selected": isSelected || void 0,
7146
- children: [
7147
- /* @__PURE__ */ jsxs("div", { "data-cimplify-composite-component-info": true, children: [
7148
- /* @__PURE__ */ jsx("span", { "data-cimplify-composite-component-name": true, children: displayName }),
7149
- component.is_popular && /* @__PURE__ */ jsx("span", { "data-cimplify-composite-badge": "popular", children: "Popular" }),
7150
- component.is_premium && /* @__PURE__ */ jsx("span", { "data-cimplify-composite-badge": "premium", children: "Premium" }),
7151
- component.display_description && /* @__PURE__ */ jsx("span", { "data-cimplify-composite-component-description": true, children: component.display_description }),
7152
- component.calories != null && /* @__PURE__ */ jsxs("span", { "data-cimplify-composite-component-calories": true, children: [
7153
- component.calories,
7154
- " cal"
7155
- ] })
7156
- ] }),
7157
- group.allow_quantity && isSelected && /* @__PURE__ */ jsxs(
7158
- "span",
7159
- {
7160
- "data-cimplify-composite-qty": true,
7161
- onClick: (e) => e.stopPropagation(),
7162
- children: [
7163
- /* @__PURE__ */ jsx(
7164
- "button",
7165
- {
7166
- type: "button",
7167
- onClick: () => updateQuantity(group, component.id, -1),
7168
- "aria-label": `Decrease ${displayName} quantity`,
7169
- children: "\u2212"
7170
- }
7171
- ),
7172
- /* @__PURE__ */ jsx("span", { children: qty }),
7173
- /* @__PURE__ */ jsx(
7174
- "button",
7175
- {
7176
- type: "button",
7177
- onClick: () => updateQuantity(group, component.id, 1),
7178
- "aria-label": `Increase ${displayName} quantity`,
7179
- children: "+"
7180
- }
7181
- )
7182
- ]
7183
- }
7184
- ),
7185
- component.price && component.price !== "0" && /* @__PURE__ */ jsx(Price, { amount: component.price, prefix: "+" })
7186
- ]
7187
- },
7188
- component.id
7189
- );
7190
- }) })
7191
- ] }, group.id);
7192
- }),
7193
- priceResult && /* @__PURE__ */ jsxs("div", { "data-cimplify-composite-summary": true, children: [
7194
- priceResult.base_price !== "0" && /* @__PURE__ */ jsxs("div", { "data-cimplify-composite-summary-line": true, children: [
7195
- /* @__PURE__ */ jsx("span", { children: "Base" }),
7196
- /* @__PURE__ */ jsx(Price, { amount: priceResult.base_price })
7197
- ] }),
7198
- priceResult.components_total !== "0" && /* @__PURE__ */ jsxs("div", { "data-cimplify-composite-summary-line": true, children: [
7199
- /* @__PURE__ */ jsx("span", { children: "Selections" }),
7200
- /* @__PURE__ */ jsx(Price, { amount: priceResult.components_total })
7201
- ] }),
7202
- /* @__PURE__ */ jsxs("div", { "data-cimplify-composite-summary-total": true, children: [
7203
- /* @__PURE__ */ jsx("span", { children: "Total" }),
7204
- /* @__PURE__ */ jsx(Price, { amount: priceResult.final_price })
7205
- ] })
7206
- ] }),
7207
- isPriceLoading && /* @__PURE__ */ jsx("div", { "data-cimplify-composite-calculating": true, children: "Calculating price..." })
7208
- ] });
7209
- }
7210
- function BundleSelector({
7211
- bundleIdOrSlug,
7212
- onSelectionsChange,
7213
- onReady,
7214
- className
7215
- }) {
7216
- const { bundle, isLoading, error } = useBundle(bundleIdOrSlug);
7217
- const [variantChoices, setVariantChoices] = useState({});
7218
- useEffect(() => {
7219
- if (!bundle) return;
7220
- const defaults = {};
7221
- for (const comp of bundle.components) {
7222
- if (comp.component.variant_id) {
7223
- defaults[comp.component.id] = comp.component.variant_id;
7224
- } else if (comp.variants.length > 0) {
7225
- const defaultVariant = comp.variants.find((v) => v.is_default) || comp.variants[0];
7226
- if (defaultVariant) {
7227
- defaults[comp.component.id] = defaultVariant.id;
7228
- }
7229
- }
7230
- }
7231
- setVariantChoices(defaults);
7232
- }, [bundle]);
7233
- const selections = useMemo(() => {
7234
- if (!bundle) return [];
7235
- return bundle.components.map((comp) => ({
7236
- component_id: comp.component.id,
7237
- variant_id: variantChoices[comp.component.id],
7238
- quantity: comp.component.quantity
7239
- }));
7240
- }, [bundle, variantChoices]);
7241
- useEffect(() => {
7242
- onSelectionsChange(selections);
7243
- }, [selections, onSelectionsChange]);
7244
- useEffect(() => {
7245
- onReady?.(bundle != null && selections.length > 0);
7246
- }, [bundle, selections, onReady]);
7247
- const handleVariantChange = useCallback(
7248
- (componentId, variantId) => {
7249
- setVariantChoices((prev) => ({ ...prev, [componentId]: variantId }));
7250
- },
7251
- []
7252
- );
7253
- if (isLoading) {
7254
- return /* @__PURE__ */ jsx("div", { "data-cimplify-bundle-selector": true, "data-loading": true, className, children: "Loading bundle..." });
7255
- }
7256
- if (error || !bundle) {
7257
- return null;
7258
- }
7259
- return /* @__PURE__ */ jsxs("div", { "data-cimplify-bundle-selector": true, className, children: [
7260
- /* @__PURE__ */ jsx("span", { "data-cimplify-bundle-heading": true, children: "Included in this bundle" }),
7261
- /* @__PURE__ */ jsx("div", { "data-cimplify-bundle-components": true, children: bundle.components.map((comp) => /* @__PURE__ */ jsx(
7262
- BundleComponentCard,
7263
- {
7264
- data: comp,
7265
- selectedVariantId: variantChoices[comp.component.id],
7266
- onVariantChange: (variantId) => handleVariantChange(comp.component.id, variantId)
7267
- },
7268
- comp.component.id
7269
- )) }),
7270
- bundle.bundle_price && /* @__PURE__ */ jsxs("div", { "data-cimplify-bundle-summary": true, children: [
7271
- /* @__PURE__ */ jsx("span", { children: "Bundle price" }),
7272
- /* @__PURE__ */ jsx(Price, { amount: bundle.bundle_price })
7273
- ] }),
7274
- bundle.discount_value && /* @__PURE__ */ jsxs("div", { "data-cimplify-bundle-savings": true, children: [
7275
- /* @__PURE__ */ jsx("span", { children: "You save" }),
7276
- /* @__PURE__ */ jsx(Price, { amount: bundle.discount_value })
7277
- ] })
7278
- ] });
7279
- }
7280
- function BundleComponentCard({
7281
- data,
7282
- selectedVariantId,
7283
- onVariantChange
7284
- }) {
7285
- const { component, product, variants } = data;
7286
- const showVariantPicker = component.allow_variant_choice && variants.length > 1;
7287
- return /* @__PURE__ */ jsxs("div", { "data-cimplify-bundle-component": true, children: [
7288
- /* @__PURE__ */ jsxs("div", { "data-cimplify-bundle-component-header": true, children: [
7289
- /* @__PURE__ */ jsxs("div", { children: [
7290
- component.quantity > 1 && /* @__PURE__ */ jsxs("span", { "data-cimplify-bundle-component-qty": true, children: [
7291
- "\xD7",
7292
- component.quantity
7293
- ] }),
7294
- /* @__PURE__ */ jsx("span", { "data-cimplify-bundle-component-name": true, children: product.name })
7295
- ] }),
7296
- /* @__PURE__ */ jsx(Price, { amount: product.default_price })
7297
- ] }),
7298
- showVariantPicker && /* @__PURE__ */ jsx("div", { "data-cimplify-bundle-variant-picker": true, children: variants.map((variant) => {
7299
- const isSelected = selectedVariantId === variant.id;
7300
- const adjustment = parsePrice(variant.price_adjustment);
7301
- return /* @__PURE__ */ jsxs(
7302
- "button",
7303
- {
7304
- type: "button",
7305
- "aria-selected": isSelected,
7306
- onClick: () => onVariantChange(variant.id),
7307
- "data-cimplify-bundle-variant-option": true,
7308
- "data-selected": isSelected || void 0,
7309
- children: [
7310
- getVariantDisplayName(variant, product.name),
7311
- adjustment !== 0 && /* @__PURE__ */ jsxs("span", { "data-cimplify-bundle-variant-adjustment": true, children: [
7312
- adjustment > 0 ? "+" : "",
7313
- /* @__PURE__ */ jsx(Price, { amount: variant.price_adjustment })
7314
- ] })
7315
- ]
7316
- },
7317
- variant.id
7318
- );
7319
- }) })
7320
- ] });
7321
- }
7322
- function ProductCustomizer({
7323
- product,
7324
- onAddToCart,
7325
- className
7326
- }) {
7327
- const [quantity, setQuantity] = useState(1);
7328
- const [isAdded, setIsAdded] = useState(false);
7329
- const [isSubmitting, setIsSubmitting] = useState(false);
7330
- const [selectedVariantId, setSelectedVariantId] = useState();
7331
- const [selectedVariant, setSelectedVariant] = useState();
7332
- const [selectedAddOnOptionIds, setSelectedAddOnOptionIds] = useState([]);
7333
- const [compositeSelections, setCompositeSelections] = useState([]);
7334
- const [compositePrice, setCompositePrice] = useState(null);
7335
- const [compositeReady, setCompositeReady] = useState(false);
7336
- const [bundleSelections, setBundleSelections] = useState([]);
7337
- const [bundleReady, setBundleReady] = useState(false);
7338
- const cart = useCart();
7339
- const productType = product.type || "product";
7340
- const isComposite = productType === "composite";
7341
- const isBundle = productType === "bundle";
7342
- const isStandard = !isComposite && !isBundle;
7343
- const hasVariants = isStandard && product.variants && product.variants.length > 0;
7344
- const hasAddOns = isStandard && product.add_ons && product.add_ons.length > 0;
7345
- useEffect(() => {
7346
- setQuantity(1);
7347
- setIsAdded(false);
7348
- setIsSubmitting(false);
7349
- setSelectedVariantId(void 0);
7350
- setSelectedVariant(void 0);
7351
- setSelectedAddOnOptionIds([]);
7352
- setCompositeSelections([]);
7353
- setCompositePrice(null);
7354
- setCompositeReady(false);
7355
- setBundleSelections([]);
7356
- setBundleReady(false);
7357
- }, [product.id]);
7358
- const selectedAddOnOptions = useMemo(() => {
7359
- if (!product.add_ons) return [];
7360
- const options = [];
7361
- for (const addOn of product.add_ons) {
7362
- for (const option of addOn.options) {
7363
- if (selectedAddOnOptionIds.includes(option.id)) {
7364
- options.push(option);
7365
- }
7366
- }
7367
- }
7368
- return options;
7369
- }, [product.add_ons, selectedAddOnOptionIds]);
7370
- const normalizedAddOnOptionIds = useMemo(() => {
7371
- if (selectedAddOnOptionIds.length === 0) return [];
7372
- return Array.from(new Set(selectedAddOnOptionIds.map((id) => id.trim()).filter(Boolean))).sort();
7373
- }, [selectedAddOnOptionIds]);
7374
- const localTotalPrice = useMemo(() => {
7375
- if (isComposite && compositePrice) {
7376
- return parsePrice(compositePrice.final_price) * quantity;
7377
- }
7378
- let price = parsePrice(product.default_price);
7379
- if (selectedVariant?.price_adjustment) {
7380
- price += parsePrice(selectedVariant.price_adjustment);
7381
- }
7382
- for (const option of selectedAddOnOptions) {
7383
- if (option.default_price) {
7384
- price += parsePrice(option.default_price);
7385
- }
7386
- }
7387
- return price * quantity;
7388
- }, [product.default_price, selectedVariant, selectedAddOnOptions, quantity, isComposite, compositePrice]);
7389
- const requiredAddOnsSatisfied = useMemo(() => {
7390
- if (!product.add_ons) return true;
7391
- for (const addOn of product.add_ons) {
7392
- if (addOn.is_required) {
7393
- const selectedInGroup = selectedAddOnOptionIds.filter(
7394
- (id) => addOn.options.some((opt) => opt.id === id)
7395
- ).length;
7396
- const minRequired = addOn.min_selections || 1;
7397
- if (selectedInGroup < minRequired) {
7398
- return false;
7399
- }
7400
- }
7401
- }
7402
- return true;
7403
- }, [product.add_ons, selectedAddOnOptionIds]);
7404
- const quoteInput = useMemo(
7405
- () => ({
7406
- productId: product.id,
7407
- quantity,
7408
- variantId: selectedVariantId,
7409
- addOnOptionIds: normalizedAddOnOptionIds.length > 0 ? normalizedAddOnOptionIds : void 0
7410
- }),
7411
- [product.id, quantity, selectedVariantId, normalizedAddOnOptionIds]
7412
- );
7413
- const { quote } = useQuote(quoteInput, {
7414
- enabled: isStandard && requiredAddOnsSatisfied
7415
- });
7416
- const quoteId = quote?.quote_id;
7417
- const quotedTotalPrice = useMemo(() => {
7418
- if (!quote) return void 0;
7419
- const quotedTotal = quote.quoted_total_price_info?.final_price ?? quote.final_price_info.final_price;
7420
- return quotedTotal === void 0 || quotedTotal === null ? void 0 : parsePrice(quotedTotal);
7421
- }, [quote]);
7422
- const displayTotalPrice = quotedTotalPrice ?? localTotalPrice;
7423
- const canAddToCart = useMemo(() => {
7424
- if (isComposite) return compositeReady;
7425
- if (isBundle) return bundleReady;
7426
- return requiredAddOnsSatisfied;
7427
- }, [isComposite, isBundle, compositeReady, bundleReady, requiredAddOnsSatisfied]);
7428
- const handleVariantChange = useCallback(
7429
- (variantId, variant) => {
7430
- setSelectedVariantId(variantId);
7431
- setSelectedVariant(variant);
7432
- },
7433
- []
7434
- );
7435
- const handleAddToCart = async () => {
7436
- if (isSubmitting) return;
7437
- setIsSubmitting(true);
7438
- const options = {
7439
- variantId: selectedVariantId,
7440
- variant: selectedVariant ? { id: selectedVariant.id, name: selectedVariant.name || "", price_adjustment: selectedVariant.price_adjustment } : void 0,
7441
- quoteId,
7442
- addOnOptionIds: normalizedAddOnOptionIds.length > 0 ? normalizedAddOnOptionIds : void 0,
7443
- addOnOptions: selectedAddOnOptions.length > 0 ? selectedAddOnOptions.map((opt) => ({
7444
- id: opt.id,
7445
- name: opt.name,
7446
- add_on_id: opt.add_on_id,
7447
- default_price: opt.default_price
7448
- })) : void 0,
7449
- compositeSelections: isComposite && compositeSelections.length > 0 ? compositeSelections : void 0,
7450
- bundleSelections: isBundle && bundleSelections.length > 0 ? bundleSelections : void 0
7451
- };
7452
- try {
7453
- if (onAddToCart) {
7454
- await onAddToCart(product, quantity, options);
7455
- } else {
7456
- await cart.addItem(product, quantity, options);
7457
- }
7458
- setIsAdded(true);
7459
- setTimeout(() => {
7460
- setIsAdded(false);
7461
- setQuantity(1);
7462
- }, 2e3);
7463
- } catch {
7464
- } finally {
7465
- setIsSubmitting(false);
7466
- }
7467
- };
7468
- return /* @__PURE__ */ jsxs("div", { "data-cimplify-customizer": true, className, children: [
7469
- isComposite && /* @__PURE__ */ jsx(
7470
- CompositeSelector,
7471
- {
7472
- productId: product.id,
7473
- onSelectionsChange: setCompositeSelections,
7474
- onPriceChange: setCompositePrice,
7475
- onReady: setCompositeReady
7476
- }
7477
- ),
7478
- isBundle && /* @__PURE__ */ jsx(
7479
- BundleSelector,
7480
- {
7481
- bundleIdOrSlug: product.slug,
7482
- onSelectionsChange: setBundleSelections,
7483
- onReady: setBundleReady
7484
- }
7485
- ),
7486
- hasVariants && /* @__PURE__ */ jsx(
7487
- VariantSelector,
7488
- {
7489
- variants: product.variants,
7490
- variantAxes: product.variant_axes,
7491
- basePrice: product.default_price,
7492
- selectedVariantId,
7493
- onVariantChange: handleVariantChange
7494
- }
7495
- ),
7496
- hasAddOns && /* @__PURE__ */ jsx(
7497
- AddOnSelector,
7498
- {
7499
- addOns: product.add_ons,
7500
- selectedOptions: selectedAddOnOptionIds,
7501
- onOptionsChange: setSelectedAddOnOptionIds
7502
- }
7503
- ),
7504
- /* @__PURE__ */ jsxs("div", { "data-cimplify-customizer-actions": true, children: [
7505
- /* @__PURE__ */ jsx(
7506
- QuantitySelector,
7507
- {
7508
- value: quantity,
7509
- onChange: setQuantity,
7510
- min: 1
7511
- }
7512
- ),
7513
- /* @__PURE__ */ jsx(
7514
- "button",
7515
- {
7516
- type: "button",
7517
- onClick: handleAddToCart,
7518
- disabled: isAdded || isSubmitting || !canAddToCart,
7519
- "data-cimplify-customizer-submit": true,
7520
- children: isAdded ? "Added to Cart" : /* @__PURE__ */ jsxs(Fragment, { children: [
7521
- "Add to Cart \xB7 ",
7522
- /* @__PURE__ */ jsx(Price, { amount: displayTotalPrice })
7523
- ] })
7524
- }
7525
- )
7526
- ] }),
7527
- !canAddToCart && /* @__PURE__ */ jsx("p", { "data-cimplify-customizer-validation": true, children: "Please select all required options" })
7528
- ] });
7529
- }
7530
6749
  var ASPECT_STYLES = {
7531
6750
  square: { aspectRatio: "1/1" },
7532
6751
  "4/3": { aspectRatio: "4/3" },
@@ -7703,4 +6922,4 @@ function CartSummary({
7703
6922
  ] }) });
7704
6923
  }
7705
6924
 
7706
- export { Ad, AdProvider, AddOnSelector, AddressElement, AuthElement, BundleSelector, CartSummary, CimplifyCheckout, CimplifyProvider, CompositeSelector, ElementsProvider, PaymentElement, Price, ProductCustomizer, ProductImageGallery, QuantitySelector, VariantSelector, getVariantDisplayName, useAds, useBundle, useCart, useCategories, useCheckout, useCimplify, useCollection, useCollections, useComposite, useElements, useElementsReady, useLocations, useOptionalCimplify, useOrder, useProduct, useProducts, useQuote, useSearch };
6925
+ export { Ad, AdProvider, AddOnSelector, AddressElement, AuthElement, CartSummary, CimplifyCheckout, CimplifyProvider, ElementsProvider, PaymentElement, Price, ProductImageGallery, QuantitySelector, VariantSelector, getVariantDisplayName, useAds, useCart, useCategories, useCheckout, useCimplify, useCollection, useCollections, useElements, useElementsReady, useLocations, useOptionalCimplify, useOrder, useProduct, useProducts, useQuote, useSearch };