@usequeek/theme-kit 0.1.44 → 0.2.1

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/README.md CHANGED
@@ -135,7 +135,6 @@ they keep the data already on screen. They return `isLoading`, except
135
135
  | `useAuth()` | `hooks/use-auth` | The signed-in customer and sign-in modal controls |
136
136
  | `useVariantSelection(product, preferredVariantPId?)` | `hooks/use-variant-selection` | Option selection state and the add-to-cart gate; opens on a linked `?variant=` |
137
137
  | `useSearch(query, products, collections)` | `hooks/use-search` | Instant search over data you hold |
138
- | `useAddressAutocomplete(text)` / `useResolveCoordinates()` | `hooks/use-address-autocomplete`, `hooks/use-resolve-coordinates` | Delivery address lookup |
139
138
  | `useHref()` | `hooks/use-href` | Builds a store-relative link |
140
139
  | `useLocales()` | `hooks/use-locales` | The store's languages and the active one |
141
140
  | `useStorefront()` / `useStorefrontLocale()` / `useThemeStrings()` | `provider` | The store, the request locale, the bound `t` |
@@ -165,12 +164,14 @@ items.map((item) => {
165
164
  });
166
165
  ```
167
166
 
168
- `formatWireMoney` hands the string to Intl at the currency's own precision, so a
169
- zero-decimal currency prints no decimals and an amount with more digits than the
170
- currency has is rounded by Intl; it returns an empty string for anything that is
171
- not a plain non-negative decimal. The storefront app keeps a different
172
- `formatWireMoney` (it accepts numbers and negatives and returns an em dash for a
173
- missing amount); the wiring item must converge on one of them.
167
+ `formatWireMoney` hands the string to Intl untouched and follows the same rule
168
+ as `formatMoney`: a whole amount prints without decimals (`₦4,500`), any other
169
+ amount prints all of the currency's minor-unit digits (`US$11.50`, KWD `1.250`,
170
+ never `US$11.5`), a zero-decimal currency never prints decimals, and an amount
171
+ with more digits than the currency has is rounded by Intl. It returns an empty
172
+ string for anything that is not a plain decimal (a leading `-` is allowed). The
173
+ storefront app's own `formatWireMoney` (numbers, em dash for a missing amount)
174
+ prints through these two.
174
175
 
175
176
  The host app supplies the server pricing once, above every theme, with
176
177
  `<CartServerPricingProvider value={pricing}>` (`hooks/use-cart-server-pricing`).
@@ -376,8 +377,8 @@ renders in the British/Nigerian style — `2 October 2026`, never US
376
377
  already holds. Siblings: `formatThemeNumber`, `formatThemeMoney`, and
377
378
  `formatThemeRelativeTime(-1, 'day', locale)` (`hier`, `أمس`, `ontem`, …,
378
379
  `numeric: 'auto'`). `formatThemeMoney` uses the currency's default
379
- decimals (`₦5,000.00`); `formatMoney` shows decimals only when present
380
- (`₦5,000`, `₦0.28`). The fixed-zone display path is `formatShopperDate`
380
+ decimals (`₦5,000.00`); `formatMoney` drops them from a whole amount
381
+ (`₦5,000`) and otherwise prints all of them (`₦0.28`, `US$11.50`). The fixed-zone display path is `formatShopperDate`
381
382
  (`utils/format.ts`, Africa/Lagos, `''` for invalid dates);
382
383
  `formatCount`/`formatMoney` take an optional locale, defaulting to English
383
384
  output. `PostMeta` (`components/blog/post-meta.tsx`) renders its byline
package/client.ts CHANGED
@@ -52,8 +52,6 @@ export * from './hooks/use-search';
52
52
  export * from './hooks/use-posts';
53
53
  export * from './hooks/use-reviews';
54
54
  export * from './hooks/use-variant-selection';
55
- export * from './hooks/use-address-autocomplete';
56
- export * from './hooks/use-resolve-coordinates';
57
55
  export * from './stores/cart-panel-store';
58
56
  export * from './stores/product-modal-store';
59
57
  export * from './stores/search-modal-store';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usequeek/theme-kit",
3
- "version": "0.1.44",
3
+ "version": "0.2.1",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "The runtime a Queek storefront theme is built on: hooks, stores, page renderer, navigation, shared blocks and locale strings.",
package/utils/format.ts CHANGED
@@ -1,18 +1,12 @@
1
1
  /**
2
- * Was hardcoded to `maximumFractionDigits: 0` — which, per Intl's own
3
- * resolution rules, also clamps the (otherwise currency-default 2) minimum
4
- * down to 0, so it silently truncated EVERY fractional-naira amount to a
5
- * whole number, everywhere in the storefront. A ₦0.28 balance (e.g. a tiny
6
- * residual left after a near-100% discount) displayed as "₦0" — the customer
7
- * saw a free checkout, then got asked to actually pay something. The POS
8
- * always shows two decimals.
2
+ * Money display rule (one rule, every formatter in this file): a whole amount
3
+ * shows no decimals (₦5,000, $5), any other amount shows ALL of its currency's
4
+ * minor-unit digits ($11.50, never $11.5; KWD 1.250; JPY never has decimals).
5
+ * The digits come from Intl's own currency data, not a fixed 2.
9
6
  *
10
- * Deliberately NOT matching the POS's always-2-decimals format here: the
11
- * overwhelming majority of storefront prices are whole naira, and putting
12
- * ".00" on every single one would be a large, unrequested visual change
13
- * across every theme. `minimumFractionDigits: 0, maximumFractionDigits: 2`
14
- * shows decimals only when the amount genuinely has them — ₦5,000 stays
15
- * ₦5,000, ₦0.28 now correctly shows as ₦0.28.
7
+ * History: a hardcoded `maximumFractionDigits: 0` once truncated a ₦0.28
8
+ * balance to "₦0"; the next fix (`minimum 0, maximum 2`) printed "$11.5" and
9
+ * rounded a KWD amount to 2 digits.
16
10
  */
17
11
  import {
18
12
  ENGLISH_DISPLAY_LOCALE,
@@ -144,13 +138,68 @@ export function normalizeCurrencyCode(value: unknown, fallback: string = PLATFOR
144
138
  return /^[A-Z]{3}$/.test(cleanFallback) ? cleanFallback : PLATFORM_DEFAULT_CURRENCY;
145
139
  }
146
140
 
141
+ /**
142
+ * What one (locale, currency) needs, built once: `full` at the currency's own
143
+ * minor units (Intl's default for a currency), `whole` with no decimals,
144
+ * `zeroFraction`, the fraction text of a whole amount in that locale's own
145
+ * digits ("00", Arabic-Indic "٠٠", `undefined` for JPY), and `halfMinorUnit`,
146
+ * below which an amount rounds to zero. Intl.NumberFormat construction is the
147
+ * expensive part of formatting, and a product grid formats the same pair
148
+ * hundreds of times.
149
+ */
150
+ interface MoneyFormatters {
151
+ full: Intl.NumberFormat;
152
+ whole: Intl.NumberFormat;
153
+ zeroFraction: string | undefined;
154
+ halfMinorUnit: number;
155
+ }
156
+
157
+ /** Real keys are (store locales x store currencies); the cap only bounds a caller passing arbitrary tags. */
158
+ const MONEY_FORMATTER_CACHE_LIMIT = 256;
159
+ const moneyFormatterCache = new Map<string, MoneyFormatters>();
160
+
161
+ function moneyFormatters(tag: string, code: string): MoneyFormatters {
162
+ const key = `${tag}|${code}`;
163
+ let formatters = moneyFormatterCache.get(key);
164
+ if (!formatters) {
165
+ const full = new Intl.NumberFormat(tag, { style: 'currency', currency: code });
166
+ formatters = {
167
+ full,
168
+ whole: new Intl.NumberFormat(tag, { style: 'currency', currency: code, minimumFractionDigits: 0, maximumFractionDigits: 0 }),
169
+ zeroFraction: full.formatToParts(0).find((part) => part.type === 'fraction')?.value,
170
+ halfMinorUnit: 0.5 / 10 ** (full.resolvedOptions().maximumFractionDigits ?? 2),
171
+ };
172
+ if (moneyFormatterCache.size >= MONEY_FORMATTER_CACHE_LIMIT) moneyFormatterCache.clear();
173
+ moneyFormatterCache.set(key, formatters);
174
+ }
175
+ return formatters;
176
+ }
177
+
178
+ /**
179
+ * The money display rule (see the top of this file). "Whole" is decided by
180
+ * Intl itself AFTER rounding to the currency's digits, so $11.999 prints "$12"
181
+ * and $11.5 prints "$11.50" — never a float test that disagrees with what is
182
+ * printed. An amount that rounds to zero prints as zero, never "-₦0". A decimal
183
+ * string reaches Intl untouched (exact, no float round trip); the cast only
184
+ * satisfies the lib typing. Throws what Intl throws.
185
+ */
186
+ function formatAtMinorUnits(amount: number | string, code: string, tag: string): string {
187
+ const { full, whole, zeroFraction, halfMinorUnit } = moneyFormatters(tag, code);
188
+ const value = (Math.abs(Number(amount)) < halfMinorUnit ? 0 : amount) as number;
189
+ const parts = full.formatToParts(value);
190
+ const fraction = parts.find((part) => part.type === 'fraction')?.value;
191
+ return fraction !== undefined && fraction !== zeroFraction ? parts.map((part) => part.value).join('') : whole.format(value);
192
+ }
193
+
147
194
  /**
148
195
  * Format an amount in a currency (ISO 4217 code), in the shopper's locale.
149
- * Decimals show only when the amount has them (`₦5,000`, `₦0.28`). An invalid
150
- * currency code falls back to the platform default. Never throws.
196
+ * A whole amount shows no decimals (`₦5,000`, `$5`); any other amount shows
197
+ * all of the currency's minor-unit digits (`$11.50`, `₦0.28`, KWD `1.250`).
198
+ * An invalid currency code falls back to the platform default. Never throws.
151
199
  *
152
200
  * @example
153
201
  * formatMoney(5000, 'NGN'); // "₦5,000"
202
+ * formatMoney(11.5, 'USD'); // "US$11.50"
154
203
  */
155
204
  export function formatMoney(
156
205
  amount: number,
@@ -160,12 +209,7 @@ export function formatMoney(
160
209
  const code = normalizeCurrencyCode(currency);
161
210
  const tag = displayTagFor(locale, (l) => Intl.NumberFormat.supportedLocalesOf(l));
162
211
  try {
163
- return new Intl.NumberFormat(tag, {
164
- style: 'currency',
165
- currency: code,
166
- minimumFractionDigits: 0,
167
- maximumFractionDigits: 2,
168
- }).format(amount);
212
+ return formatAtMinorUnits(amount, code, tag);
169
213
  } catch {
170
214
  return `${code} ${amount.toLocaleString(DISPLAY_LOCALE)}`;
171
215
  }
@@ -173,35 +217,28 @@ export function formatMoney(
173
217
 
174
218
  /**
175
219
  * Format a money amount the server sent as a decimal STRING ("4500.00",
176
- * KWD "1.250") without a float round trip: the string reaches Intl untouched,
177
- * at the currency's own precision, with decimals shown only when present (the
178
- * same style as `formatMoney`, which caps at 2 digits). Returns an empty string
179
- * for anything that is not a plain non-negative decimal. Never computes, never throws.
220
+ * KWD "1.250", a refund "-5.00") without a float round trip: the string reaches
221
+ * Intl untouched, under the same rule as `formatMoney` (whole amounts without
222
+ * decimals, any other amount at the currency's full minor units). Returns an
223
+ * empty string for anything that is not a plain decimal. Never computes, never throws.
180
224
  *
181
225
  * @example
182
226
  * formatWireMoney('4500.00', 'NGN'); // "₦4,500"
227
+ * formatWireMoney('11.50', 'USD'); // "US$11.50"
183
228
  */
184
229
  export function formatWireMoney(
185
230
  amount: string,
186
231
  currency = PLATFORM_DEFAULT_CURRENCY,
187
232
  locale?: string | null,
188
233
  ): string {
189
- if (typeof amount !== 'string' || !/^\d+(\.\d+)?$/.test(amount)) {
234
+ if (typeof amount !== 'string' || !/^-?\d+(\.\d+)?$/.test(amount)) {
190
235
  return '';
191
236
  }
192
237
 
193
238
  const code = normalizeCurrencyCode(currency);
194
239
  const tag = displayTagFor(locale, (l) => Intl.NumberFormat.supportedLocalesOf(l));
195
240
  try {
196
- const precision = new Intl.NumberFormat(tag, { style: 'currency', currency: code }).resolvedOptions().maximumFractionDigits ?? 2;
197
-
198
- // Intl parses a decimal string exactly; the cast only satisfies the lib typing.
199
- return new Intl.NumberFormat(tag, {
200
- style: 'currency',
201
- currency: code,
202
- minimumFractionDigits: 0,
203
- maximumFractionDigits: precision,
204
- }).format(amount as unknown as number);
241
+ return formatAtMinorUnits(amount, code, tag);
205
242
  } catch {
206
243
  return `${code} ${amount}`;
207
244
  }
@@ -1,80 +0,0 @@
1
- 'use client';
2
-
3
- import { useEffect, useState } from 'react';
4
- import { useIsThemePreview, useStorefront, useThemeStrings } from '../provider';
5
- import { getQueekClient } from '../sdk/queek-client';
6
-
7
- /** One address suggestion. Pass `place_id` to `useResolveCoordinates` to get its position. */
8
- export interface AddressSuggestion {
9
- description: string;
10
- place_id: string;
11
- }
12
-
13
- const DEBOUNCE_MS = 300;
14
-
15
- /**
16
- * Address suggestions for what the shopper has typed, after a 300 ms pause.
17
- * Nothing is requested for fewer than two characters. A failed request clears
18
- * the suggestions rather than throwing, so the field stays usable.
19
- *
20
- * @example
21
- * const { suggestions, loading } = useAddressAutocomplete(text);
22
- */
23
- export function useAddressAutocomplete(query: string): {
24
- suggestions: AddressSuggestion[];
25
- loading: boolean;
26
- /** Preview notice for the address field to display. */
27
- error: string | null;
28
- } {
29
- const { vendor } = useStorefront();
30
- const isThemePreview = useIsThemePreview();
31
- const t = useThemeStrings();
32
- const [suggestions, setSuggestions] = useState<AddressSuggestion[]>([]);
33
- const [loading, setLoading] = useState(false);
34
-
35
- useEffect(() => {
36
- if (isThemePreview) {
37
- setSuggestions([]);
38
- setLoading(false);
39
- return;
40
- }
41
- if (!query || query.trim().length < 2) {
42
- setSuggestions([]);
43
- return;
44
- }
45
-
46
- let cancelled = false;
47
- const timer = setTimeout(() => {
48
- setLoading(true);
49
- const client = getQueekClient(vendor.slug ?? undefined);
50
- const path = `/client/address/autocomplete?query=${encodeURIComponent(query.trim())}`;
51
-
52
- client
53
- .get<AddressSuggestion[] | { data: AddressSuggestion[] }>(path)
54
- .then((res) => {
55
- if (cancelled) return;
56
- // Backend returns a bare array (not wrapped in envelope). SDK returns
57
- // whatever the server sent — handle both shapes defensively.
58
- const list: unknown = Array.isArray(res)
59
- ? res
60
- : Array.isArray((res as { data?: unknown })?.data)
61
- ? (res as { data: AddressSuggestion[] }).data
62
- : [];
63
- setSuggestions(list as AddressSuggestion[]);
64
- })
65
- .catch(() => {
66
- if (!cancelled) setSuggestions([]);
67
- })
68
- .finally(() => {
69
- if (!cancelled) setLoading(false);
70
- });
71
- }, DEBOUNCE_MS);
72
-
73
- return () => {
74
- cancelled = true;
75
- clearTimeout(timer);
76
- };
77
- }, [query, vendor.slug, isThemePreview]);
78
-
79
- return { suggestions, loading, error: isThemePreview ? t('preview.address') : null };
80
- }
@@ -1,62 +0,0 @@
1
- 'use client';
2
-
3
- import { useState } from 'react';
4
- import { useIsThemePreview, useStorefront, useThemeStrings } from '../provider';
5
- import { getQueekClient } from '../sdk/queek-client';
6
- import { useLocationStore } from '../stores/location-store';
7
-
8
- interface CoordinatesResponse {
9
- lat?: number;
10
- lng?: number;
11
- latitude?: number;
12
- longitude?: number;
13
- formatted_address?: string;
14
- state_id?: string | null;
15
- }
16
-
17
- /**
18
- * Turns a chosen address suggestion into coordinates and saves it as the
19
- * shopper's delivery location. `resolve` returns true when a location was
20
- * saved and false when the API gave no usable position or the request failed.
21
- *
22
- * @example
23
- * const { resolve, resolving } = useResolveCoordinates();
24
- * const ok = await resolve(suggestion.place_id, suggestion.description);
25
- */
26
- export function useResolveCoordinates(): {
27
- resolve: (placeId: string, description: string) => Promise<boolean>;
28
- resolving: boolean;
29
- /** Preview notice for the address field to display. */
30
- error: string | null;
31
- } {
32
- const { vendor } = useStorefront();
33
- const isThemePreview = useIsThemePreview();
34
- const t = useThemeStrings();
35
- const setLocation = useLocationStore((s) => s.setLocation);
36
- const [resolving, setResolving] = useState(false);
37
-
38
- const resolve = async (placeId: string, description: string): Promise<boolean> => {
39
- if (isThemePreview) return false;
40
- setResolving(true);
41
- try {
42
- const client = getQueekClient(vendor.slug ?? undefined);
43
- const res = await client.post<CoordinatesResponse>('/client/geo/resolve', {
44
- place_id: placeId,
45
- });
46
- const data = (res?.data ?? {}) as CoordinatesResponse;
47
- const lat = data.lat ?? data.latitude;
48
- const lng = data.lng ?? data.longitude;
49
- if (typeof lat === 'number' && typeof lng === 'number') {
50
- setLocation(lat, lng, data.formatted_address ?? description, data.state_id ?? null);
51
- return true;
52
- }
53
- return false;
54
- } catch {
55
- return false;
56
- } finally {
57
- setResolving(false);
58
- }
59
- };
60
-
61
- return { resolve, resolving, error: isThemePreview ? t('preview.address') : null };
62
- }