@usequeek/theme-kit 0.5.0 → 0.5.2

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
@@ -138,6 +138,7 @@ they keep the data already on screen. They return `isLoading`, except
138
138
  | `useHref()` | `hooks/use-href` | Builds a store-relative link |
139
139
  | `useLocales()` | `hooks/use-locales` | The store's languages and the active one |
140
140
  | `useStorefront()` / `useStorefrontLocale()` / `useThemeStrings()` | `provider` | The store, the request locale, the bound `t` |
141
+ | `useProductCount()` | `provider` | `(count) => number \| null`: the product count to print, `null` unless the store turned counts on (`config.display.show_product_counts`, off by default). Print every product count through it and render nothing for `null` |
141
142
 
142
143
  ### Cart pricing
143
144
 
@@ -7,6 +7,7 @@ import { useUserStore } from '../stores/user-store';
7
7
  import { useAuthModalStore } from '../stores/auth-modal-store';
8
8
  import { getQueekClient } from '../sdk/queek-client';
9
9
  import { formatCount } from '../utils/format';
10
+ import { Image } from '../components/image';
10
11
 
11
12
  interface FollowData {
12
13
  following: boolean;
@@ -228,8 +229,10 @@ export function FollowCard({ display }: { display?: 'floating' | 'inline' } = {}
228
229
  {previewMessage && <p className="core-follow-card__notice" role="status">{t('preview.action')}</p>}
229
230
  <div className="core-follow-card__body">
230
231
  {vendor.logo && (
231
- <img
232
+ <Image
232
233
  src={vendor.logo}
234
+ variants={vendor.logo_variants}
235
+ intent="avatar"
233
236
  alt={vendor.name ?? ''}
234
237
  className="core-follow-card__logo"
235
238
  />
package/client.ts CHANGED
@@ -14,6 +14,7 @@ export * from './theme-variant-resolver';
14
14
  export * from './shared-blocks';
15
15
  export * from './components/blog';
16
16
  export * from './components/image';
17
+ export * from './media-index';
17
18
  export * from './components/product-metafields';
18
19
  export * from './components/powered-by-queek';
19
20
  export * from './components/language-switcher';
@@ -18,6 +18,8 @@ export function PostMeta({ post, className }: { post: Post; className?: string }
18
18
 
19
19
  const authorName = post.author?.name ?? vendor.name ?? null;
20
20
  const authorAvatar = post.author?.avatar_url ?? vendor.logo ?? null;
21
+ // The vendor's tier map belongs to the vendor's logo only, never to an author's own avatar.
22
+ const avatarVariants = post.author?.avatar_url ? null : vendor.logo_variants;
21
23
  const published = post.published_at
22
24
  ? formatShopperDate(post.published_at, display.locale, { year: 'numeric', month: 'long', day: 'numeric' }, display.timeZone)
23
25
  : '';
@@ -29,6 +31,8 @@ export function PostMeta({ post, className }: { post: Post; className?: string }
29
31
  <span className="core-post-meta__author">
30
32
  <Image
31
33
  src={authorAvatar || undefined}
34
+ variants={avatarVariants}
35
+ intent="avatar"
32
36
  alt={authorName}
33
37
  className="core-post-meta__avatar"
34
38
  placeholder={{ label: authorName, width: 64, height: 64, variant: 'square' }}
@@ -36,6 +36,8 @@ export function RelatedPosts({
36
36
  <div className="core-related__media">
37
37
  <Image
38
38
  src={post.cover_image_url || undefined}
39
+ variants={post.cover_image_variants}
40
+ intent="card2x"
39
41
  alt={post.title}
40
42
  className="core-related__img"
41
43
  placeholder={{ label: post.title, width: 600, height: 400, variant: 'card' }}
@@ -1,6 +1,7 @@
1
1
  'use client';
2
2
 
3
3
  import { useContext, useState, type ImgHTMLAttributes } from 'react';
4
+ import { lookupMediaIndex, useMediaIndex } from '../media-index';
4
5
  import { StorefrontContext } from '../provider';
5
6
  import type { ImageVariants } from '../types/media';
6
7
  import { resolveBrandPalette } from '../utils/brand-palette';
@@ -41,13 +42,21 @@ type ImageProps = ImgHTMLAttributes<HTMLImageElement> & {
41
42
  * Purely additive: when absent — and whenever the API legitimately sends null
42
43
  * (off-host image, SVG, legacy upload) — this component renders the plain
43
44
  * image URL.
45
+ *
46
+ * Omit it (undefined) and a string `src` that is a key of the page's media
47
+ * index (`MediaIndexProvider`) uses that entry. Pass `null` to say "no
48
+ * variants" and skip the lookup.
44
49
  */
45
50
  variants?: ImageVariants | null;
46
51
  /**
47
52
  * What surface this image renders on. Drives which tier is preferred and what
48
53
  * `sizes` is emitted. Only meaningful alongside `variants`. Defaults to 'raw'
49
54
  * ("best available single url, no responsive selection") so passing `variants`
50
- * without an `intent` can never accidentally downgrade a hero.
55
+ * without an `intent` can never accidentally downgrade a hero. When the
56
+ * variants come from the page's media index instead (see `variants`), the
57
+ * intent is ALWAYS 'section' and this prop is ignored: call sites picked
58
+ * theirs when the image rendered the original and the intent did nothing,
59
+ * so honouring it would load a smaller copy than the box needs.
51
60
  */
52
61
  intent?: ImageIntent;
53
62
  };
@@ -69,12 +78,21 @@ type LoadStage = 'primary' | 'original' | 'failed';
69
78
  * @example
70
79
  * <Image src={product.media.image ?? ''} variants={product.media.image_variants} intent="card" alt={product.title} />
71
80
  */
72
- export function Image({ fallback, placeholder, variants, intent = 'raw', onError, ...props }: ImageProps) {
81
+ export function Image({ fallback, placeholder, variants: variantsProp, intent: intentProp, onError, ...props }: ImageProps) {
73
82
  const [stage, setStage] = useState<LoadStage>('primary');
74
83
  // Read context directly — returns null outside a StorefrontProvider
75
84
  // (test environments, isolated captures) without throwing.
76
85
  const storefront = useContext(StorefrontContext);
77
86
 
87
+ // A call site that passes no `variants` (undefined; an explicit null means
88
+ // "none") gets the page's media index entry for its src and the full-bleed-safe
89
+ // 'section' intent, whatever intent the call site named (it was chosen when the
90
+ // image rendered the original). An explicit `variants` keeps its own `intent`.
91
+ const mediaIndex = useMediaIndex();
92
+ const indexed = variantsProp === undefined ? lookupMediaIndex(mediaIndex, props.src) : null;
93
+ const variants = indexed ?? variantsProp;
94
+ const intent = indexed ? 'section' : (intentProp ?? 'raw');
95
+
78
96
  const resolved = resolveImageSources(variants, intent);
79
97
 
80
98
  // The resolved tier WINS over an explicitly-passed `src`. That's the whole
@@ -155,7 +173,9 @@ export function Image({ fallback, placeholder, variants, intent = 'raw', onError
155
173
  loading={loading}
156
174
  src={effectiveSrc}
157
175
  srcSet={effectiveSrcSet}
158
- sizes={effectiveSizes}
176
+ // A call site's own `sizes` wins whenever a srcset is emitted: only it knows a box that is cropped
177
+ // (`object-fit: cover`) and drawn wider than the viewport. Without a srcset `sizes` means nothing.
178
+ sizes={effectiveSrcSet ? (props.sizes ?? effectiveSizes) : undefined}
159
179
  onError={(e) => {
160
180
  // 2-step chain: preferred tier → variants.original → placeholder.
161
181
  if (stage === 'primary') {
@@ -5,12 +5,15 @@ import { useStorefront, useStorefrontLocale } from '../provider';
5
5
  import { createBrowserClient } from '../sdk/client';
6
6
  import { withLocaleQuery } from '../utils/locale';
7
7
  import { toError } from '../utils/to-error';
8
+ import type { ImageVariants } from '../types/media';
8
9
 
9
10
  export interface Category {
10
11
  id: string;
11
12
  slug: string;
12
13
  name: string;
13
14
  image?: string | null;
15
+ /** The API's tier map for `image` (`/collections` sends it); null when the image is not Media-backed. */
16
+ image_variants?: ImageVariants | null;
14
17
  products_count?: number;
15
18
  children?: Category[];
16
19
  }
package/index.ts CHANGED
@@ -33,6 +33,7 @@ export * from './types/app-block';
33
33
  export * from './types/order';
34
34
  export * from './types/page';
35
35
  export * from './types/menu';
36
+ export * from './types/media';
36
37
  export * from './utils/format';
37
38
  export * from './utils/markdown';
38
39
  export * from './utils/menu-link';
@@ -0,0 +1,76 @@
1
+ 'use client';
2
+
3
+ import type { JSX } from 'react';
4
+ import { createContext, useContext, useMemo, type ReactNode } from 'react';
5
+ import type { ImageVariants, MediaIndex } from './types/media';
6
+
7
+ const MediaIndexContext = createContext<MediaIndex | null>(null);
8
+
9
+ /**
10
+ * Hands a page's `media_index` (the API's url → tier-map sidecar on every
11
+ * Page/Post) to every kit `<Image>` and section background below it. An image
12
+ * whose `src` is a key of the index and whose call site passes no `variants`
13
+ * then renders a small responsive copy instead of the original upload, so a
14
+ * theme's section photos need no code change.
15
+ *
16
+ * Nested providers merge, the inner page winning, so a render that combines
17
+ * several pages (page chrome + the page) mounts one provider per page.
18
+ * `index` undefined, null or empty leaves the parent index untouched.
19
+ *
20
+ * @example
21
+ * <MediaIndexProvider index={page.media_index}>
22
+ * <HomePage blocks={page.content} />
23
+ * </MediaIndexProvider>
24
+ */
25
+ export function MediaIndexProvider({
26
+ index,
27
+ children,
28
+ }: {
29
+ index?: MediaIndex | null;
30
+ children: ReactNode;
31
+ }): JSX.Element {
32
+ const parent = useContext(MediaIndexContext);
33
+ const value = useMemo<MediaIndex | null>(() => {
34
+ if (!index || Object.keys(index).length === 0) return parent;
35
+ return parent ? { ...parent, ...index } : index;
36
+ }, [parent, index]);
37
+
38
+ return <MediaIndexContext.Provider value={value}>{children}</MediaIndexContext.Provider>;
39
+ }
40
+
41
+ /** The media index of the page being rendered; null outside a {@link MediaIndexProvider}. */
42
+ export function useMediaIndex(): MediaIndex | null {
43
+ return useContext(MediaIndexContext);
44
+ }
45
+
46
+ /**
47
+ * The tier map for a raw url, or null when there is no index, the url is not a
48
+ * key of it, or the API sent null for it (an off-host image, an SVG, a legacy
49
+ * upload) — the caller then keeps rendering the raw url.
50
+ */
51
+ export function lookupMediaIndex(index: MediaIndex | null | undefined, url: unknown): ImageVariants | null {
52
+ if (!index || typeof url !== 'string' || !Object.prototype.hasOwnProperty.call(index, url)) {
53
+ return null;
54
+ }
55
+ return index[url] ?? null;
56
+ }
57
+
58
+ /**
59
+ * The url for a CSS `background-image`, which has no `srcset` to step up from:
60
+ * the `view` copy only when it holds as many pixels as the original (`view.w` is
61
+ * at least `original.w`, so the same picture in WebP), else the raw url. A
62
+ * background is drawn full-bleed, so a copy with fewer pixels would be softer than
63
+ * what it renders today.
64
+ */
65
+ export function mediaIndexBackgroundUrl(index: MediaIndex | null | undefined, url: string): string {
66
+ const variants = lookupMediaIndex(index, url);
67
+ const view = variants?.view;
68
+ const original = variants?.original;
69
+ if (
70
+ view && typeof view.url === 'string' && view.url.trim() !== '' &&
71
+ typeof view.w === 'number' && typeof original?.w === 'number' && view.w >= original.w
72
+ ) {
73
+ return view.url;
74
+ }
75
+ return url;
76
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usequeek/theme-kit",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
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/page-renderer.tsx CHANGED
@@ -6,6 +6,7 @@ import type { Block, BlockDataMap, MetaobjectsResolved } from './types/block';
6
6
  import type { Product } from './types/product';
7
7
  import { useTheme } from './theme-context';
8
8
  import { useStorefront } from './provider';
9
+ import { mediaIndexBackgroundUrl, useMediaIndex } from './media-index';
9
10
  import { expandDesignTokensPartial } from './utils/brand';
10
11
  import {
11
12
  CoreButtonBlock,
@@ -96,6 +97,7 @@ export function PageRenderer({ blocks }: { blocks: Block[] }): JSX.Element {
96
97
  const { config } = useStorefront();
97
98
  const defaultVariants = config.default_variants ?? {};
98
99
  const editMode = useEditMode();
100
+ const mediaIndex = useMediaIndex();
99
101
 
100
102
  const renderBlock = (block: Block, index: number): JSX.Element | null => {
101
103
  const variant = block.variant ?? defaultVariants[block.type] ?? undefined;
@@ -162,7 +164,10 @@ export function PageRenderer({ blocks }: { blocks: Block[] }): JSX.Element {
162
164
  ...(hasTokenVars ? tokenVars : {}),
163
165
  ...(bgImage
164
166
  ? {
165
- backgroundImage: `url(${bgImage})`,
167
+ // Full-bleed, so the page's `view` copy only when it holds as many
168
+ // pixels as the original (a background has no srcset to step up
169
+ // from); the raw url otherwise.
170
+ backgroundImage: `url(${mediaIndexBackgroundUrl(mediaIndex, bgImage)})`,
166
171
  backgroundSize: 'cover',
167
172
  backgroundPosition: 'center',
168
173
  color: '#fff',
package/provider.tsx CHANGED
@@ -1,7 +1,7 @@
1
1
  'use client';
2
2
 
3
3
  import type { JSX } from 'react';
4
- import { createContext, useContext, useEffect, useMemo, useRef, type ReactNode } from 'react';
4
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, type ReactNode } from 'react';
5
5
  import type { Menu } from './types/menu';
6
6
  import type { ReviewItem } from './types/block';
7
7
  import type { Post } from './types/page';
@@ -227,6 +227,26 @@ export function useIsThemePreview(): boolean {
227
227
  return useStorefront().previewData !== undefined;
228
228
  }
229
229
 
230
+ /**
231
+ * The product count a theme may print, or `null` to print nothing. Counts ("6 products" under a
232
+ * collection title, a number on a category tile, a facet tally) stay hidden unless the store turns
233
+ * them on (`config.display.show_product_counts`, default off). Every theme prints a product count
234
+ * only through this, and renders no element at all for `null`, so no empty span or gap is left.
235
+ *
236
+ * @example
237
+ * const productCount = useProductCount();
238
+ * const shown = productCount(collection.products_count);
239
+ * return shown !== null ? <p>{t('shop.count', { count: shown })}</p> : null;
240
+ */
241
+ export function useProductCount(): (count: number | null | undefined) => number | null {
242
+ const shows = useStorefront().config.display?.show_product_counts === true;
243
+
244
+ return useCallback(
245
+ (count: number | null | undefined): number | null => (shows && typeof count === 'number' && Number.isFinite(count) ? count : null),
246
+ [shows],
247
+ );
248
+ }
249
+
230
250
  /**
231
251
  * Validated request locale for translated reads (`null` = primary).
232
252
  * Browser hooks send `?locale=` when this is set and key their client
package/types/theme.ts CHANGED
@@ -221,7 +221,7 @@ export interface ProductsBlockProps extends ProductsBlockData {
221
221
  }
222
222
 
223
223
  export interface CategoriesBlockProps extends CategoriesBlockData {
224
- categories?: Array<{ id: string; slug: string; name: string; image?: string | null }>;
224
+ categories?: Array<{ id: string; slug: string; name: string; image?: string | null; image_variants?: ImageVariants | null }>;
225
225
  }
226
226
 
227
227
  export interface BlogBlockProps extends BlogBlockData {
package/types/vendor.ts CHANGED
@@ -187,6 +187,14 @@ export interface StorefrontConfig {
187
187
  heading?: string;
188
188
  body?: string;
189
189
  };
190
+ /**
191
+ * Store-wide display choices every theme honours. `show_product_counts` (default false): a theme
192
+ * prints a product count ("6 products") only when the store turns it on; read it through
193
+ * `useProductCount()`, never from here.
194
+ */
195
+ display?: {
196
+ show_product_counts?: boolean;
197
+ };
190
198
  /** Resolved semantic design tokens. Absent for stores that have none. */
191
199
  tokens?: DesignTokens | null;
192
200
  menus?: {
@@ -11,8 +11,13 @@ import type { ImageVariantTier, ImageVariantTierName, ImageVariants } from '../t
11
11
  * (~320px CSS) and the featured/poster card (~620px CSS). Both would
12
12
  * otherwise get the identical 480px `card` url, visibly soft on the poster
13
13
  * ones.
14
+ *
15
+ * `section` is the intent of a merchant-uploaded section photo (a gallery or
16
+ * banner slide, an image block) that may run full-bleed. The `<Image>` applies
17
+ * it by itself when it finds its `src` in the page's media index and the call
18
+ * site named no intent.
14
19
  */
15
- export type ImageIntent = 'avatar' | 'card' | 'card2x' | 'modal' | 'hero' | 'raw';
20
+ export type ImageIntent = 'avatar' | 'card' | 'card2x' | 'modal' | 'hero' | 'section' | 'raw';
16
21
 
17
22
  export interface ResolvedImageSources {
18
23
  src: string | undefined;
@@ -25,7 +30,8 @@ const NONE: ResolvedImageSources = { src: undefined, srcSet: undefined, sizes: u
25
30
  /** Ascending by cap. `thumb` is excluded because it has no width; `original` is
26
31
  * excluded on purpose — it is uncapped and unoptimized (raw jpg/png, possibly
27
32
  * 6000px), so letting a browser pick it off a srcset is the exact regression
28
- * the tier map exists to prevent. `original` survives only as a last-resort
33
+ * the tier map exists to prevent. The single exception is the `section` intent,
34
+ * which appends it as the top candidate only when it is wider than `view`. `original` survives only as a last-resort
29
35
  * `src` for the `raw` intent and as the onError step-2 retry. */
30
36
  const SRCSET_TIERS = ['card', 'card2x', 'view'] as const;
31
37
  type SrcSetTier = (typeof SRCSET_TIERS)[number];
@@ -42,6 +48,7 @@ const INTENT_CEILING: Record<ImageIntent, SrcSetTier | null> = {
42
48
  card2x: 'view',
43
49
  modal: 'card2x',
44
50
  hero: 'view',
51
+ section: 'view',
45
52
  raw: null, // "best single url, no responsive selection"
46
53
  };
47
54
 
@@ -54,6 +61,18 @@ const INTENT_CEILING: Record<ImageIntent, SrcSetTier | null> = {
54
61
  * card2x @768px→768css: DPR2→1536→view(1600) · desktop 620css: DPR2→1240→view
55
62
  * modal 420css: DPR1→420→card(480) · DPR2→840→card2x(800, the ceiling)
56
63
  * hero desktop 700css: DPR1→700→view · DPR2→1400→view(1600)
64
+ * section full-bleed `100vw`: phone 390css DPR2→780→card2x(800) · DPR3→1170→view ·
65
+ * 1440css desktop DPR1→1440→view(1600). Never the 2 MB original on a
66
+ * phone or an ordinary desktop.
67
+ * `section` is the ONE intent whose srcset may end in `original`, and
68
+ * its srcset is `view` + `original` ONLY (see resolveImageSources): a
69
+ * section photo must never look softer than the raw upload it replaces.
70
+ * A cropped (`object-fit: cover`) tall hero on a phone is drawn WIDER
71
+ * than 100vw (a 16:9 photo in a 523px-tall box is drawn ~930px wide), so
72
+ * `sizes="100vw"` would under-measure it and the small tiers would be
73
+ * too soft: a phone gets `view` (WebP, at most 1600px, still about five
74
+ * times lighter than a 2 MB PNG) and only a screen wider than `view`
75
+ * picks the original, which is exactly what that screen is served today.
57
76
  *
58
77
  * `modal` is written as a media query (`(max-width: 456px) 92vw, 420px`,
59
78
  * arithmetically identical to `min(420px, 92vw)`: 420/0.92 = 456.5) rather
@@ -67,6 +86,7 @@ const INTENT_SIZES: Record<ImageIntent, string | undefined> = {
67
86
  card2x: '(max-width: 768px) 100vw, (max-width: 1100px) 50vw, 620px',
68
87
  modal: '(max-width: 456px) 92vw, 420px',
69
88
  hero: '(max-width: 900px) calc(100vw - 32px), 700px',
89
+ section: '100vw',
70
90
  raw: undefined,
71
91
  };
72
92
 
@@ -85,6 +105,7 @@ const INTENT_SRC_ORDER: Record<ImageIntent, ImageVariantTierName[]> = {
85
105
  // very fallback the caller carefully picked. Returning undefined instead
86
106
  // lets the Image component's `resolved.src ?? props.src` defer to it.
87
107
  hero: ['view', 'card2x'],
108
+ section: ['view', 'card2x', 'card'],
88
109
  raw: ['original', 'view', 'card2x', 'card', 'thumb'],
89
110
  };
90
111
 
@@ -99,6 +120,9 @@ function usableTier(tier: ImageVariantTier | null | undefined): tier is ImageVar
99
120
  * - null/undefined `variants` → every field undefined, so the caller's own
100
121
  * `src` prop keeps winning and behavior is byte-identical to today.
101
122
  * - never emits `thumb` in a srcset.
123
+ * - `original` enters a srcset only for the `section` intent, and only as the
124
+ * top candidate, when its real width is strictly wider than `view`; the
125
+ * `section` srcset holds nothing but `view` and `original`.
102
126
  * - never invents a url; null tiers are simply skipped.
103
127
  * - never exceeds the intent's ceiling (downgrade-only).
104
128
  * - dedupes candidates that collapsed to the same width on a small original,
@@ -130,7 +154,8 @@ export function resolveImageSources(
130
154
 
131
155
  const limit = SRCSET_TIERS.indexOf(ceiling);
132
156
  const byWidth = new Map<number, string>();
133
- for (let i = 0; i <= limit; i += 1) {
157
+ // `section` starts at `view`: card and card2x are too small for a box that can be drawn wider than the viewport.
158
+ for (let i = intent === 'section' ? limit : 0; i <= limit; i += 1) {
134
159
  const tier = variants[SRCSET_TIERS[i]];
135
160
  // A tier with no usable width can't carry a `w` descriptor, and mixing
136
161
  // `w` and bare descriptors in one srcset makes the whole attribute invalid.
@@ -144,6 +169,18 @@ export function resolveImageSources(
144
169
  }
145
170
  }
146
171
 
172
+ if (intent === 'section') {
173
+ const original = variants.original;
174
+ if (
175
+ usableTier(original) &&
176
+ typeof original.w === 'number' &&
177
+ Number.isFinite(original.w) &&
178
+ original.w > Math.max(0, ...byWidth.keys())
179
+ ) {
180
+ byWidth.set(original.w, original.url);
181
+ }
182
+ }
183
+
147
184
  if (byWidth.size < 2) {
148
185
  return { src, srcSet: undefined, sizes: undefined };
149
186
  }