@frontic/nuxt 0.3.0 → 0.4.0

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
@@ -6,9 +6,10 @@ Nuxt module for integrating with [Frontstack](https://frontstack.dev) headless c
6
6
 
7
7
  - **Smart caching** via [Pinia Colada](https://pinia-colada.esm.dev/) - stale-while-revalidate, request deduplication, SSR hydration
8
8
  - **Type-safe composables** - Full TypeScript support with generated types from your Frontstack schema
9
- - **Search & filtering** - Ready-to-use search state management with filters, sorting, and pagination
9
+ - **Search & filtering** - Ready-to-use search state management with filters, sorting, pagination, and infinite scroll
10
10
  - **Page routing** - Dynamic page resolution with automatic redirects and 404 handling
11
11
  - **Context management** - Locale and region switching with cookie persistence
12
+ - **Infinite scroll** - Bidirectional infinite loading with deep-link support via Pinia Colada's `useInfiniteQuery`
12
13
  - **Built-in proxy** - CORS-free API requests through your Nuxt server
13
14
 
14
15
  ## Installation
@@ -57,10 +57,24 @@ export declare function useFronticSearch<TSearch extends keyof Listings, TFilter
57
57
  */
58
58
  searchTerm: import("@vue/reactivity").Ref<string, string>;
59
59
  /**
60
- * Load the next page of results (infinite scroll).
61
- * Appends new items to existing results.
60
+ * Load the next page of results.
61
+ * Standard mode: replaces current page with the next one.
62
+ * Infinite mode: appends items from the next page.
62
63
  */
63
- loadNext: (vars: void) => Promise<unknown>;
64
+ loadNext: () => Promise<unknown>;
65
+ /**
66
+ * Load the previous page of results.
67
+ * Standard mode: replaces current page with the previous one.
68
+ * Infinite mode: prepends items from the previous page.
69
+ */
70
+ loadPrev: () => Promise<unknown>;
71
+ /**
72
+ * Jump to a specific page number.
73
+ * Standard mode: replaces current page with the requested one.
74
+ * Infinite mode: resets all loaded pages and restarts from the given page.
75
+ * @param page - The page number to load
76
+ */
77
+ loadPage: (page: number) => Promise<unknown>;
64
78
  /**
65
79
  * Refresh the listing data (uses cache if valid).
66
80
  * Call after external changes that should trigger a refresh.
@@ -71,12 +85,6 @@ export declare function useFronticSearch<TSearch extends keyof Listings, TFilter
71
85
  * Use when you need guaranteed fresh data.
72
86
  */
73
87
  refetch: () => Promise<void>;
74
- /**
75
- * Navigate to next or previous page.
76
- * @param direction - 'next' or 'prev'
77
- * @returns true if navigation was successful, false if no more pages
78
- */
79
- paginate: (direction: "next" | "prev") => Promise<boolean>;
80
88
  /**
81
89
  * Sort results by a specific field. Call without arguments to reset to default.
82
90
  * @param sortBy - Sort string in format 'field:asc' or 'field:desc', or omit to reset
@@ -1,6 +1,6 @@
1
1
  import { useState } from "nuxt/app";
2
- import { computed, watch, ref } from "vue";
3
- import { useQuery, useMutation, useQueryCache } from "@pinia/colada";
2
+ import { computed, watch, ref, toValue } from "vue";
3
+ import { useQuery, useInfiniteQuery, useQueryCache } from "@pinia/colada";
4
4
  import { useDebounceFn } from "@vueuse/core";
5
5
  import { makeLogicalFilter, manageFilter, removeFilter } from "../utils/filter-helpers.js";
6
6
  import {
@@ -13,7 +13,7 @@ import {
13
13
  parseSortString,
14
14
  isSortAllowed
15
15
  } from "../utils/state-helpers.js";
16
- import { fetchListingQuery } from "./listings.js";
16
+ import { fetchListingQuery, LISTING_QUERY_KEYS } from "./listings.js";
17
17
  import { useFronticClient } from "./useFronticClient.js";
18
18
  export function useFronticSearch(name, params, options) {
19
19
  const queryCache = useQueryCache();
@@ -32,7 +32,10 @@ export function useFronticSearch(name, params, options) {
32
32
  const disableSearch = options?.disableSearch ?? false;
33
33
  const disableFilter = options?.disableFilter ?? false;
34
34
  const disableSorting = options?.disableSorting ?? false;
35
+ const limit = options?.limit;
35
36
  const staleTime = options?.staleTime ?? 1e3 * 60 * 5;
37
+ const infinite = options?.infinite ?? false;
38
+ const initialPage = Math.max(1, Math.floor(options?.initialPage ?? 1));
36
39
  const filterConfig = filter || {};
37
40
  const sortConfig = sorting || {};
38
41
  const aggregationConfig = aggregation || {};
@@ -69,49 +72,114 @@ export function useFronticSearch(name, params, options) {
69
72
  const apiQuery = computed(() => ({
70
73
  sort: !disableSorting ? _sortQuery.value : void 0,
71
74
  search: !disableSearch && searchTerm.value && searchTerm.value.trim().length > searchTermThreshold ? searchTerm.value : void 0,
72
- filter: !disableFilter ? [...makeLogicalFilter("or", _orFilterList.value), ...makeLogicalFilter("and", _andFilterList.value)] : void 0
75
+ filter: !disableFilter ? [...makeLogicalFilter("or", _orFilterList.value), ...makeLogicalFilter("and", _andFilterList.value)] : void 0,
76
+ limit
73
77
  }));
74
- const { data, status, refresh, refetch } = useQuery(
75
- fetchListingQuery({
76
- name: listingName,
77
- params,
78
- query: apiQuery,
79
- contextKey,
80
- contextDomain,
81
- requestUrl,
82
- staleTime,
83
- _client
84
- })
85
- );
86
- const { mutateAsync: loadNext } = useMutation({
87
- mutation: async () => {
88
- const nextPage = data.value?.page;
89
- if (!nextPage?.next) return void 0;
90
- const nextPageQuery = fetchListingQuery({
91
- name: listingName,
92
- params,
93
- query: apiQuery,
94
- contextKey,
95
- contextDomain,
96
- requestUrl,
97
- page: ref(nextPage.next),
98
- staleTime,
99
- _client
100
- });
101
- return await nextPageQuery.query();
102
- },
103
- onSuccess: (data2) => {
104
- const newData = data2;
105
- const newItems = newData?.items || [];
106
- if (!newItems.length) return;
107
- const cacheKeyValue = [cacheKey, JSON.stringify(apiQuery.value)];
108
- const oldData = queryCache.getQueryData(cacheKeyValue);
109
- queryCache.setQueryData(cacheKeyValue, {
110
- ...newData,
111
- items: [...oldData?.items || [], ...newItems]
112
- });
78
+ const queryConfig = {
79
+ name: listingName,
80
+ params,
81
+ query: apiQuery,
82
+ contextKey,
83
+ contextDomain,
84
+ requestUrl,
85
+ staleTime,
86
+ _client
87
+ };
88
+ let data;
89
+ let status;
90
+ let refresh;
91
+ let refetch;
92
+ let loadNextFn;
93
+ let loadPrevFn;
94
+ let loadPageFn;
95
+ async function fetchPage(pageNumber) {
96
+ const pageQuery = fetchListingQuery({
97
+ ...queryConfig,
98
+ page: ref(pageNumber)
99
+ });
100
+ const response = await pageQuery.query();
101
+ if (response) {
102
+ const baseCacheKey = LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value);
103
+ queryCache.setQueryData(baseCacheKey, response);
104
+ updateState(response);
113
105
  }
114
- });
106
+ return response;
107
+ }
108
+ if (infinite) {
109
+ const infiniteResult = useInfiniteQuery({
110
+ key: () => LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value),
111
+ initialPageParam: initialPage,
112
+ query: async ({ pageParam }) => {
113
+ const pagedQueryFactory = fetchListingQuery({
114
+ ...queryConfig,
115
+ page: ref(pageParam)
116
+ });
117
+ return await pagedQueryFactory.query();
118
+ },
119
+ getNextPageParam: (lastPage) => {
120
+ if (!lastPage || typeof lastPage !== "object") return void 0;
121
+ const page = lastPage.page;
122
+ if (!page || typeof page !== "object") return void 0;
123
+ return page.next ?? void 0;
124
+ },
125
+ getPreviousPageParam: (firstPage) => {
126
+ if (!firstPage || typeof firstPage !== "object") return void 0;
127
+ const page = firstPage.page;
128
+ if (!page || typeof page !== "object") return void 0;
129
+ return page.prev ?? void 0;
130
+ },
131
+ staleTime
132
+ });
133
+ const flattenedData = computed(() => {
134
+ const pages = infiniteResult.data.value?.pages;
135
+ if (!pages?.length) return void 0;
136
+ const lastPage = pages[pages.length - 1];
137
+ const allItems = pages.flatMap((page) => page?.items || []);
138
+ return {
139
+ ...lastPage,
140
+ items: allItems
141
+ };
142
+ });
143
+ data = flattenedData;
144
+ status = infiniteResult.status;
145
+ refresh = infiniteResult.refresh;
146
+ refetch = infiniteResult.refetch;
147
+ loadNextFn = () => infiniteResult.loadNextPage();
148
+ loadPrevFn = () => infiniteResult.loadPreviousPage();
149
+ loadPageFn = async (page) => {
150
+ const cacheKey2 = LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value);
151
+ queryCache.setQueryData(cacheKey2, { pages: [], pageParams: [] });
152
+ const pagedQueryFactory = fetchListingQuery({
153
+ ...queryConfig,
154
+ page: ref(page)
155
+ });
156
+ const response = await pagedQueryFactory.query();
157
+ if (response) {
158
+ queryCache.setQueryData(cacheKey2, { pages: [response], pageParams: [page] });
159
+ updateState(response);
160
+ }
161
+ return response;
162
+ };
163
+ } else {
164
+ const queryResult = useQuery(fetchListingQuery(queryConfig));
165
+ data = queryResult.data;
166
+ status = queryResult.status;
167
+ refresh = queryResult.refresh;
168
+ refetch = queryResult.refetch;
169
+ loadNextFn = async () => {
170
+ const pageData = data.value?.page;
171
+ if (!pageData?.next) return void 0;
172
+ return await fetchPage(pageData.next);
173
+ };
174
+ loadPrevFn = async () => {
175
+ const pageData = data.value?.page;
176
+ if (!pageData?.prev) return void 0;
177
+ return await fetchPage(pageData.prev);
178
+ };
179
+ loadPageFn = async (page) => {
180
+ return await fetchPage(page);
181
+ };
182
+ }
115
183
  if (!disableSearch) {
116
184
  watch(searchTerm, () => {
117
185
  if (searchTerm.value.trim().length > searchTermThreshold || searchState.value.active.search) {
@@ -135,7 +203,8 @@ export function useFronticSearch(name, params, options) {
135
203
  let activeFilters = makeFilterState(rawFilters);
136
204
  activeFilters = applyFilterConfig(activeFilters, filterConfig);
137
205
  const availableFilters = processAvailableFilters(rawFilters, filterConfig);
138
- const availableSorts = processAvailableSorts(sortConfig);
206
+ const responseHasSort = "sort" in response;
207
+ const availableSorts = processAvailableSorts(sortConfig, responseHasSort);
139
208
  const availableAggregations = processAvailableAggregations(rawAggregation, aggregationConfig);
140
209
  const activeFilterCount = countActiveFilters(activeFilters);
141
210
  searchState.value = {
@@ -172,28 +241,6 @@ export function useFronticSearch(name, params, options) {
172
241
  }
173
242
  }
174
243
  const triggerSearchFromInput = useDebounceFn(refreshListing, searchDebounce);
175
- async function paginate(direction) {
176
- const pageData = data.value?.page;
177
- const pageNumber = direction === "next" ? pageData?.next : pageData?.prev;
178
- if (!pageNumber) return false;
179
- searchState.value.active.page = pageNumber;
180
- const pageQuery = fetchListingQuery({
181
- name: listingName,
182
- params,
183
- query: apiQuery,
184
- contextKey,
185
- contextDomain,
186
- requestUrl,
187
- page: ref(pageNumber),
188
- staleTime,
189
- _client
190
- });
191
- const response = await pageQuery.query();
192
- if (response) {
193
- updateState(response);
194
- }
195
- return !!response;
196
- }
197
244
  async function sortResult(sortBy) {
198
245
  if (disableSorting) return;
199
246
  if (!sortBy) {
@@ -282,10 +329,24 @@ export function useFronticSearch(name, params, options) {
282
329
  searchTerm,
283
330
  // ========== Actions ==========
284
331
  /**
285
- * Load the next page of results (infinite scroll).
286
- * Appends new items to existing results.
332
+ * Load the next page of results.
333
+ * Standard mode: replaces current page with the next one.
334
+ * Infinite mode: appends items from the next page.
335
+ */
336
+ loadNext: loadNextFn,
337
+ /**
338
+ * Load the previous page of results.
339
+ * Standard mode: replaces current page with the previous one.
340
+ * Infinite mode: prepends items from the previous page.
287
341
  */
288
- loadNext,
342
+ loadPrev: loadPrevFn,
343
+ /**
344
+ * Jump to a specific page number.
345
+ * Standard mode: replaces current page with the requested one.
346
+ * Infinite mode: resets all loaded pages and restarts from the given page.
347
+ * @param page - The page number to load
348
+ */
349
+ loadPage: loadPageFn,
289
350
  /**
290
351
  * Refresh the listing data (uses cache if valid).
291
352
  * Call after external changes that should trigger a refresh.
@@ -301,12 +362,6 @@ export function useFronticSearch(name, params, options) {
301
362
  updateState(data.value);
302
363
  }
303
364
  },
304
- /**
305
- * Navigate to next or previous page.
306
- * @param direction - 'next' or 'prev'
307
- * @returns true if navigation was successful, false if no more pages
308
- */
309
- paginate,
310
365
  /**
311
366
  * Sort results by a specific field. Call without arguments to reset to default.
312
367
  * @param sortBy - Sort string in format 'field:asc' or 'field:desc', or omit to reset
@@ -171,10 +171,30 @@ export interface UseFronticSearchOptions<TSearch extends keyof Listings = keyof
171
171
  * Disable sorting functionality (default: false)
172
172
  */
173
173
  disableSorting?: boolean;
174
+ /**
175
+ * Number of items per page (sent as `limit` to the Frontstack API).
176
+ * When omitted, the backend default is used.
177
+ */
178
+ limit?: number;
174
179
  /**
175
180
  * Stale time in milliseconds (default: 5 minutes)
176
181
  */
177
182
  staleTime?: number;
183
+ /**
184
+ * Enable infinite scroll mode.
185
+ * When true, loadNext()/loadPrev() append/prepend items from adjacent pages
186
+ * using Pinia Colada's useInfiniteQuery under the hood.
187
+ * When false (default), pagination replaces the current page.
188
+ */
189
+ infinite?: boolean;
190
+ /**
191
+ * Starting page number for infinite scroll mode.
192
+ * Useful when deep-linking to a specific page (e.g., page 4 from URL).
193
+ * Users can then scroll both forward (loadNext) and backward (loadPrev).
194
+ * Only used when `infinite: true`. Values below 1 are clamped to 1.
195
+ * @default 1
196
+ */
197
+ initialPage?: number;
178
198
  }
179
199
  /**
180
200
  * Return type for the search composable
@@ -193,9 +213,27 @@ export interface UseSearchReturn<TSearch extends keyof Listings = keyof Listings
193
213
  /** Current search term */
194
214
  searchTerm: Ref<string>;
195
215
  /**
196
- * Loads more items in the current search results (infinite scroll)
216
+ * Load the next page of results.
217
+ * Standard mode: replaces current page with the next one.
218
+ * Infinite mode: appends items from the next page.
219
+ * @returns The page response, or undefined if no next page
197
220
  */
198
221
  loadNext: () => Promise<Responses[TSearch] | undefined>;
222
+ /**
223
+ * Load the previous page of results.
224
+ * Standard mode: replaces current page with the previous one.
225
+ * Infinite mode: prepends items from the previous page.
226
+ * @returns The page response, or undefined if no previous page
227
+ */
228
+ loadPrev: () => Promise<Responses[TSearch] | undefined>;
229
+ /**
230
+ * Jump to a specific page number.
231
+ * Standard mode: replaces current page with the requested one.
232
+ * Infinite mode: resets all loaded pages and restarts from the given page.
233
+ * @param page - The page number to load
234
+ * @returns The page response, or undefined if the page doesn't exist
235
+ */
236
+ loadPage: (page: number) => Promise<Responses[TSearch] | undefined>;
199
237
  /**
200
238
  * Fetches the search with current query parameters (uses cache if valid)
201
239
  */
@@ -204,12 +242,6 @@ export interface UseSearchReturn<TSearch extends keyof Listings = keyof Listings
204
242
  * Forces a fresh fetch of the search, bypassing cache
205
243
  */
206
244
  refetch: () => Promise<void>;
207
- /**
208
- * Paginates the results in the specified direction
209
- * @param direction - Direction to paginate ('next' or 'prev')
210
- * @returns Promise<boolean> - Returns true if pagination was successful
211
- */
212
- paginate: (direction: 'next' | 'prev') => Promise<boolean>;
213
245
  /**
214
246
  * Sorts the results by the specified field. Call without arguments to reset to default.
215
247
  * Type-safe: only accepts valid sort strings for this search
@@ -82,7 +82,7 @@ export declare function processAvailableFilters<TFilters = Record<string, unknow
82
82
  * // ]
83
83
  * ```
84
84
  */
85
- export declare function processAvailableSorts<TSorts = Record<string, unknown>>(config?: ListingFieldConfig): UiSort<TSorts>[];
85
+ export declare function processAvailableSorts<TSorts = Record<string, unknown>>(config?: ListingFieldConfig, responseHasSort?: boolean): UiSort<TSorts>[];
86
86
  /**
87
87
  * Processes raw aggregation response into UI-ready aggregation objects
88
88
  *
@@ -47,7 +47,8 @@ export function processAvailableFilters(rawFilters, config = {}) {
47
47
  }
48
48
  return sortByOrder(availableFilters, sortOrder, (f) => f.key);
49
49
  }
50
- export function processAvailableSorts(config = {}) {
50
+ export function processAvailableSorts(config = {}, responseHasSort = true) {
51
+ if (!responseHasSort) return [];
51
52
  const { select = [], mode = "include", label: labels = {}, sort: sortOrder } = config;
52
53
  const availableSorts = Object.entries(labels).filter(([value]) => {
53
54
  if (select.length === 0) return true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontic/nuxt",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Nuxt module for Frontstack headless commerce - zero config data fetching composables with smart caching, page routing, and context management",
5
5
  "license": "MIT",
6
6
  "author": "Frontic",
@@ -44,8 +44,8 @@
44
44
  ],
45
45
  "dependencies": {
46
46
  "@nuxt/kit": "^3.17.0",
47
- "@pinia/colada": "^0.21.0",
48
- "@pinia/colada-nuxt": "^0.3.0",
47
+ "@pinia/colada": "^1.0.0",
48
+ "@pinia/colada-nuxt": "^0.3.2",
49
49
  "@pinia/nuxt": "^0.11.0",
50
50
  "@vueuse/core": "^12.0.0",
51
51
  "pinia": "^3.0.0"
@@ -53,6 +53,8 @@
53
53
  "devDependencies": {
54
54
  "@nuxt/module-builder": "^1.0.2",
55
55
  "@nuxt/schema": "^3.17.0",
56
+ "@nuxt/test-utils": "^4.0.0",
57
+ "@vitest/coverage-v8": "^2",
56
58
  "h3": "^1.15.0",
57
59
  "nitropack": "^2.13.1",
58
60
  "nuxt": "^3.17.0",
@@ -72,6 +74,7 @@
72
74
  "typecheck": "vue-tsc --noEmit",
73
75
  "test": "vitest run",
74
76
  "test:watch": "vitest watch",
77
+ "test:coverage": "vitest run --coverage",
75
78
  "clean": "rm -rf dist .nuxt"
76
79
  }
77
80
  }