@frontic/nuxt 0.3.0 → 0.5.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
@@ -88,14 +96,16 @@ export declare function useFronticSearch<TSearch extends keyof Listings, TFilter
88
96
  resetSorting: () => Promise<void>;
89
97
  /**
90
98
  * Set filter values for a specific field (replaces existing values).
99
+ * For range filters, pass an array with a single { from, to } object.
91
100
  * @param filterField - The field to filter on (e.g., 'properties.color')
92
- * @param filterOptions - Array of values to filter by
101
+ * @param filterOptions - Array of values to filter by, or [{ from, to }] for range filters
93
102
  */
94
103
  filterResult: <K extends keyof TFilters & string>(filterField: K, filterOptions: Array<TFilters[K]>) => Promise<void>;
95
104
  /**
96
- * Add a single filter option to a field (keeps existing values).
105
+ * Add a single filter option to a field (keeps existing values for equals filters).
106
+ * For range filters, pass a { from, to } object — replaces the existing range.
97
107
  * @param filterField - The field to filter on
98
- * @param filterOption - The value to add
108
+ * @param filterOption - The value to add, or { from, to } for range filters
99
109
  */
100
110
  addFilter: <K extends keyof TFilters & string>(filterField: K, filterOption: TFilters[K]) => Promise<void>;
101
111
  /**
@@ -1,19 +1,10 @@
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
- import { makeLogicalFilter, manageFilter, removeFilter } from "../utils/filter-helpers.js";
6
- import {
7
- makeFilterState,
8
- processAvailableFilters,
9
- processAvailableSorts,
10
- processAvailableAggregations,
11
- applyFilterConfig,
12
- countActiveFilters,
13
- parseSortString,
14
- isSortAllowed
15
- } from "../utils/state-helpers.js";
16
- import { fetchListingQuery } from "./listings.js";
5
+ import { makeLogicalFilter, manageFilter, removeFilter, isRangeFilterValue, manageRangeFilter, removeRangeFilter } from "../utils/filter-helpers.js";
6
+ import { makeFilterState, processAvailableFilters, processAvailableSorts, applyFilterConfig, countActiveFilters, parseSortString, isSortAllowed } from "../utils/state-helpers.js";
7
+ import { fetchListingQuery, LISTING_QUERY_KEYS } from "./listings.js";
17
8
  import { useFronticClient } from "./useFronticClient.js";
18
9
  export function useFronticSearch(name, params, options) {
19
10
  const queryCache = useQueryCache();
@@ -28,17 +19,19 @@ export function useFronticSearch(name, params, options) {
28
19
  const orFilter = options?.orFilter ?? [];
29
20
  const filter = options?.filter;
30
21
  const sorting = options?.sorting;
31
- const aggregation = options?.aggregation;
32
22
  const disableSearch = options?.disableSearch ?? false;
33
23
  const disableFilter = options?.disableFilter ?? false;
34
24
  const disableSorting = options?.disableSorting ?? false;
25
+ const limit = options?.limit;
35
26
  const staleTime = options?.staleTime ?? 1e3 * 60 * 5;
27
+ const infinite = options?.infinite ?? false;
28
+ const initialPage = Math.max(1, Math.floor(options?.initialPage ?? 1));
36
29
  const filterConfig = filter || {};
37
30
  const sortConfig = sorting || {};
38
- const aggregationConfig = aggregation || {};
39
31
  const searchTerm = useState(`${cacheKey}-searchTerm`, () => "");
40
32
  const _orFilterList = useState(`${cacheKey}-orFilterList`, () => []);
41
33
  const _andFilterList = useState(`${cacheKey}-andFilterList`, () => []);
34
+ const _rangeFilterList = useState(`${cacheKey}-rangeFilterList`, () => []);
42
35
  const _sortQuery = useState(`${cacheKey}-sortQuery`, () => void 0);
43
36
  const searchState = useState(`${cacheKey}-searchState`, () => ({
44
37
  active: {
@@ -54,13 +47,11 @@ export function useFronticSearch(name, params, options) {
54
47
  available: {
55
48
  filter: [],
56
49
  sorting: [],
57
- aggregation: [],
58
50
  nextPage: false,
59
51
  prevPage: false,
60
52
  count: {
61
53
  filter: 0,
62
54
  sorting: 0,
63
- aggregation: 0,
64
55
  result: 0,
65
56
  page: 0
66
57
  }
@@ -69,49 +60,114 @@ export function useFronticSearch(name, params, options) {
69
60
  const apiQuery = computed(() => ({
70
61
  sort: !disableSorting ? _sortQuery.value : void 0,
71
62
  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
63
+ filter: !disableFilter ? [...makeLogicalFilter("or", _orFilterList.value), ...makeLogicalFilter("and", _andFilterList.value), ..._rangeFilterList.value] : void 0,
64
+ limit
73
65
  }));
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
- });
66
+ const queryConfig = {
67
+ name: listingName,
68
+ params,
69
+ query: apiQuery,
70
+ contextKey,
71
+ contextDomain,
72
+ requestUrl,
73
+ staleTime,
74
+ _client
75
+ };
76
+ let data;
77
+ let status;
78
+ let refresh;
79
+ let refetch;
80
+ let loadNextFn;
81
+ let loadPrevFn;
82
+ let loadPageFn;
83
+ async function fetchPage(pageNumber) {
84
+ const pageQuery = fetchListingQuery({
85
+ ...queryConfig,
86
+ page: ref(pageNumber)
87
+ });
88
+ const response = await pageQuery.query();
89
+ if (response) {
90
+ const baseCacheKey = LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value);
91
+ queryCache.setQueryData(baseCacheKey, response);
92
+ updateState(response);
113
93
  }
114
- });
94
+ return response;
95
+ }
96
+ if (infinite) {
97
+ const infiniteResult = useInfiniteQuery({
98
+ key: () => LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value),
99
+ initialPageParam: initialPage,
100
+ query: async ({ pageParam }) => {
101
+ const pagedQueryFactory = fetchListingQuery({
102
+ ...queryConfig,
103
+ page: ref(pageParam)
104
+ });
105
+ return await pagedQueryFactory.query();
106
+ },
107
+ getNextPageParam: (lastPage) => {
108
+ if (!lastPage || typeof lastPage !== "object") return void 0;
109
+ const page = lastPage.page;
110
+ if (!page || typeof page !== "object") return void 0;
111
+ return page.next ?? void 0;
112
+ },
113
+ getPreviousPageParam: (firstPage) => {
114
+ if (!firstPage || typeof firstPage !== "object") return void 0;
115
+ const page = firstPage.page;
116
+ if (!page || typeof page !== "object") return void 0;
117
+ return page.prev ?? void 0;
118
+ },
119
+ staleTime
120
+ });
121
+ const flattenedData = computed(() => {
122
+ const pages = infiniteResult.data.value?.pages;
123
+ if (!pages?.length) return void 0;
124
+ const lastPage = pages[pages.length - 1];
125
+ const allItems = pages.flatMap((page) => page?.items || []);
126
+ return {
127
+ ...lastPage,
128
+ items: allItems
129
+ };
130
+ });
131
+ data = flattenedData;
132
+ status = infiniteResult.status;
133
+ refresh = infiniteResult.refresh;
134
+ refetch = infiniteResult.refetch;
135
+ loadNextFn = () => infiniteResult.loadNextPage();
136
+ loadPrevFn = () => infiniteResult.loadPreviousPage();
137
+ loadPageFn = async (page) => {
138
+ const cacheKey2 = LISTING_QUERY_KEYS.detail(String(listingName), toValue(params), apiQuery.value);
139
+ queryCache.setQueryData(cacheKey2, { pages: [], pageParams: [] });
140
+ const pagedQueryFactory = fetchListingQuery({
141
+ ...queryConfig,
142
+ page: ref(page)
143
+ });
144
+ const response = await pagedQueryFactory.query();
145
+ if (response) {
146
+ queryCache.setQueryData(cacheKey2, { pages: [response], pageParams: [page] });
147
+ updateState(response);
148
+ }
149
+ return response;
150
+ };
151
+ } else {
152
+ const queryResult = useQuery(fetchListingQuery(queryConfig));
153
+ data = queryResult.data;
154
+ status = queryResult.status;
155
+ refresh = queryResult.refresh;
156
+ refetch = queryResult.refetch;
157
+ loadNextFn = async () => {
158
+ const pageData = data.value?.page;
159
+ if (!pageData?.next) return void 0;
160
+ return await fetchPage(pageData.next);
161
+ };
162
+ loadPrevFn = async () => {
163
+ const pageData = data.value?.page;
164
+ if (!pageData?.prev) return void 0;
165
+ return await fetchPage(pageData.prev);
166
+ };
167
+ loadPageFn = async (page) => {
168
+ return await fetchPage(page);
169
+ };
170
+ }
115
171
  if (!disableSearch) {
116
172
  watch(searchTerm, () => {
117
173
  if (searchTerm.value.trim().length > searchTermThreshold || searchState.value.active.search) {
@@ -134,9 +190,9 @@ export function useFronticSearch(name, params, options) {
134
190
  const pageData = response.page;
135
191
  let activeFilters = makeFilterState(rawFilters);
136
192
  activeFilters = applyFilterConfig(activeFilters, filterConfig);
137
- const availableFilters = processAvailableFilters(rawFilters, filterConfig);
138
- const availableSorts = processAvailableSorts(sortConfig);
139
- const availableAggregations = processAvailableAggregations(rawAggregation, aggregationConfig);
193
+ const availableFilters = processAvailableFilters(rawFilters, rawAggregation, filterConfig);
194
+ const responseHasSort = "sort" in response;
195
+ const availableSorts = processAvailableSorts(sortConfig, responseHasSort);
140
196
  const activeFilterCount = countActiveFilters(activeFilters);
141
197
  searchState.value = {
142
198
  active: {
@@ -152,13 +208,11 @@ export function useFronticSearch(name, params, options) {
152
208
  available: {
153
209
  filter: availableFilters,
154
210
  sorting: availableSorts,
155
- aggregation: availableAggregations,
156
211
  nextPage: pageData?.next !== void 0,
157
212
  prevPage: pageData?.prev !== void 0,
158
213
  count: {
159
214
  filter: availableFilters.length,
160
215
  sorting: availableSorts.length,
161
- aggregation: availableAggregations.length,
162
216
  result: response.total ?? 0,
163
217
  page: pageData?.total ?? 1
164
218
  }
@@ -172,28 +226,6 @@ export function useFronticSearch(name, params, options) {
172
226
  }
173
227
  }
174
228
  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
229
  async function sortResult(sortBy) {
198
230
  if (disableSorting) return;
199
231
  if (!sortBy) {
@@ -216,6 +248,11 @@ export function useFronticSearch(name, params, options) {
216
248
  }
217
249
  async function filterResult(filterField, filterOptions) {
218
250
  if (disableFilter) return;
251
+ if (filterOptions.length > 0 && isRangeFilterValue(filterOptions[0])) {
252
+ _rangeFilterList.value = manageRangeFilter(_rangeFilterList.value, filterField, filterOptions[0]);
253
+ await refreshListing();
254
+ return;
255
+ }
219
256
  const shouldUseOr = orFilter.includes(filterField);
220
257
  const targetList = shouldUseOr ? _orFilterList : _andFilterList;
221
258
  targetList.value = manageFilter(targetList.value, filterField, filterOptions);
@@ -223,6 +260,11 @@ export function useFronticSearch(name, params, options) {
223
260
  }
224
261
  async function addFilterOption(filterField, filterOption) {
225
262
  if (disableFilter) return;
263
+ if (isRangeFilterValue(filterOption)) {
264
+ _rangeFilterList.value = manageRangeFilter(_rangeFilterList.value, filterField, filterOption);
265
+ await refreshListing();
266
+ return;
267
+ }
226
268
  const shouldUseOr = orFilter.includes(filterField);
227
269
  const targetList = shouldUseOr ? _orFilterList : _andFilterList;
228
270
  const existingFilter = targetList.value.find((filter2) => filter2.field === filterField);
@@ -232,6 +274,7 @@ export function useFronticSearch(name, params, options) {
232
274
  }
233
275
  async function removeFilterOption(filterField, filterOption) {
234
276
  if (disableFilter) return;
277
+ _rangeFilterList.value = removeRangeFilter(_rangeFilterList.value, filterField);
235
278
  const shouldUseOr = orFilter.includes(filterField);
236
279
  const targetList = shouldUseOr ? _orFilterList : _andFilterList;
237
280
  targetList.value = removeFilter(targetList.value, filterField, filterOption);
@@ -242,7 +285,9 @@ export function useFronticSearch(name, params, options) {
242
285
  if (!filterField) {
243
286
  _orFilterList.value = [];
244
287
  _andFilterList.value = [];
288
+ _rangeFilterList.value = [];
245
289
  } else {
290
+ _rangeFilterList.value = removeRangeFilter(_rangeFilterList.value, filterField);
246
291
  const shouldUseOr = orFilter.includes(filterField);
247
292
  const targetList = shouldUseOr ? _orFilterList : _andFilterList;
248
293
  targetList.value = removeFilter(targetList.value, filterField);
@@ -257,6 +302,7 @@ export function useFronticSearch(name, params, options) {
257
302
  searchTerm.value = "";
258
303
  _orFilterList.value = [];
259
304
  _andFilterList.value = [];
305
+ _rangeFilterList.value = [];
260
306
  _sortQuery.value = void 0;
261
307
  await refreshListing();
262
308
  }
@@ -282,10 +328,24 @@ export function useFronticSearch(name, params, options) {
282
328
  searchTerm,
283
329
  // ========== Actions ==========
284
330
  /**
285
- * Load the next page of results (infinite scroll).
286
- * Appends new items to existing results.
331
+ * Load the next page of results.
332
+ * Standard mode: replaces current page with the next one.
333
+ * Infinite mode: appends items from the next page.
334
+ */
335
+ loadNext: loadNextFn,
336
+ /**
337
+ * Load the previous page of results.
338
+ * Standard mode: replaces current page with the previous one.
339
+ * Infinite mode: prepends items from the previous page.
287
340
  */
288
- loadNext,
341
+ loadPrev: loadPrevFn,
342
+ /**
343
+ * Jump to a specific page number.
344
+ * Standard mode: replaces current page with the requested one.
345
+ * Infinite mode: resets all loaded pages and restarts from the given page.
346
+ * @param page - The page number to load
347
+ */
348
+ loadPage: loadPageFn,
289
349
  /**
290
350
  * Refresh the listing data (uses cache if valid).
291
351
  * Call after external changes that should trigger a refresh.
@@ -301,12 +361,6 @@ export function useFronticSearch(name, params, options) {
301
361
  updateState(data.value);
302
362
  }
303
363
  },
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
364
  /**
311
365
  * Sort results by a specific field. Call without arguments to reset to default.
312
366
  * @param sortBy - Sort string in format 'field:asc' or 'field:desc', or omit to reset
@@ -318,14 +372,16 @@ export function useFronticSearch(name, params, options) {
318
372
  resetSorting,
319
373
  /**
320
374
  * Set filter values for a specific field (replaces existing values).
375
+ * For range filters, pass an array with a single { from, to } object.
321
376
  * @param filterField - The field to filter on (e.g., 'properties.color')
322
- * @param filterOptions - Array of values to filter by
377
+ * @param filterOptions - Array of values to filter by, or [{ from, to }] for range filters
323
378
  */
324
379
  filterResult,
325
380
  /**
326
- * Add a single filter option to a field (keeps existing values).
381
+ * Add a single filter option to a field (keeps existing values for equals filters).
382
+ * For range filters, pass a { from, to } object — replaces the existing range.
327
383
  * @param filterField - The field to filter on
328
- * @param filterOption - The value to add
384
+ * @param filterOption - The value to add, or { from, to } for range filters
329
385
  */
330
386
  addFilter: addFilterOption,
331
387
  /**
@@ -4,7 +4,8 @@
4
4
  * Export all public types from this file.
5
5
  */
6
6
  export type { FronticOptions, FronticComposable, FronticComposablesConfig } from '../../module.js';
7
- export type { InclusionMode, FilterField, SortField, SortString, ListingFieldConfig, FilterOption, UiFilter, UiSort, UiAggregation, AggregationTotal, } from './listing.js';
7
+ export type { InclusionMode, FilterField, SortField, SortString, ListingFieldConfig, FilterOption, UiFilter, UiSort, AggregationTotal, } from './listing.js';
8
+ export type { RangeFilterValue } from '../utils/filter-helpers.js';
8
9
  export type { SearchState, UseFronticSearchOptions, UseSearchReturn } from './search.js';
9
10
  export type { UseFronticClientOptions } from '../composables/useFronticClient.js';
10
11
  export type { UseFronticBlockOptions } from '../composables/useFronticBlock.js';
@@ -99,6 +99,14 @@ export interface ListingFieldConfig<TFields = Record<string, unknown>> {
99
99
  * sorting: { sort: ['default', 'price.amount:asc', 'price.amount:desc'] }
100
100
  */
101
101
  sort?: Array<keyof TFields & string>;
102
+ /**
103
+ * Display type per field. Value is passed through as-is to UiFilter.type.
104
+ * Use any string that fits your UI rendering logic (e.g., 'range', 'boolean', 'color').
105
+ * Fields without a type config default to 'default'.
106
+ * @example
107
+ * type: { 'price.amount': 'range', 'properties.isNew': 'boolean' }
108
+ */
109
+ type?: Partial<Record<keyof TFields & string, string>>;
102
110
  }
103
111
  /**
104
112
  * Filter option from API response (matches Frontstack response structure)
@@ -122,6 +130,10 @@ export interface UiFilter<TFilters = Record<string, unknown>> {
122
130
  label: string;
123
131
  /** Available filter options with counts and selection state */
124
132
  options: FilterOption[];
133
+ /** Display type for this filter. 'default' unless configured via type config. */
134
+ type: string;
135
+ /** Additional data for this field if available (e.g., min/max/avg for range filters from aggregation response) */
136
+ data?: AggregationTotal;
125
137
  }
126
138
  /**
127
139
  * Statistical aggregation data for a single field from the Fetch API response
@@ -141,32 +153,6 @@ export interface AggregationTotal {
141
153
  /** Total number of possible values for this field */
142
154
  total: number;
143
155
  }
144
- /**
145
- * Processed aggregation ready for UI consumption
146
- * @example
147
- * ```ts
148
- * // Price range aggregation
149
- * { key: 'price.amount', label: 'Price', min: 9.99, max: 299.99, avg: 89.50, total: 150 }
150
- * ```
151
- */
152
- export interface UiAggregation {
153
- /** Aggregation field key (e.g., 'price.amount') */
154
- key: string;
155
- /** Human-readable label for the aggregation */
156
- label: string;
157
- /** Maximum value for this field */
158
- max?: number;
159
- /** Minimum value for this field */
160
- min?: number;
161
- /** Average value for this field */
162
- avg?: number;
163
- /** Sum of all values for this field */
164
- sum?: number;
165
- /** Number of items with this field */
166
- count?: number;
167
- /** Total number of possible values for this field */
168
- total: number;
169
- }
170
156
  /**
171
157
  * Processed sort option ready for UI consumption
172
158
  * @template TSorts - Sort fields type for this listing (provides autocomplete for key/value)
@@ -7,8 +7,8 @@
7
7
  import type { Ref, ShallowRef } from 'vue';
8
8
  import type { UseQueryReturn } from '@pinia/colada';
9
9
  import type { Listings, ListingQueryFilters, ListingQuerySorts, Responses } from '@frontic/stack/generated-types';
10
- import type { FronticRequestOptions, ListingFieldConfig, UiFilter, UiSort, UiAggregation } from './listing.js';
11
- export type { FronticRequestOptions, ListingFieldConfig, FilterOption, UiFilter, UiSort, UiAggregation, AggregationTotal, InclusionMode } from './listing.js';
10
+ import type { FronticRequestOptions, ListingFieldConfig, UiFilter, UiSort } from './listing.js';
11
+ export type { FronticRequestOptions, ListingFieldConfig, FilterOption, UiFilter, UiSort, AggregationTotal, InclusionMode } from './listing.js';
12
12
  export type { Listings, ListingQueryFilters, ListingQuerySorts, Responses };
13
13
  /**
14
14
  * Search state exposed to consumers
@@ -41,12 +41,10 @@ export interface SearchState<TFilters = Record<string, unknown>, TSorts = Record
41
41
  };
42
42
  /** Available options for UI controls */
43
43
  available: {
44
- /** Filter options ready for rendering (keys typed based on listing schema) */
44
+ /** Filter options ready for rendering, including aggregation data when available (keys typed based on listing schema) */
45
45
  filter: UiFilter<TFilters>[];
46
46
  /** Sort options ready for rendering (keys typed based on listing schema) */
47
47
  sorting: UiSort<TSorts>[];
48
- /** Aggregation data for range/statistical UI components (e.g., price sliders) */
49
- aggregation: UiAggregation[];
50
48
  /** Whether next page is available */
51
49
  nextPage: boolean;
52
50
  /** Whether previous page is available */
@@ -57,8 +55,6 @@ export interface SearchState<TFilters = Record<string, unknown>, TSorts = Record
57
55
  filter: number;
58
56
  /** Number of sort options available */
59
57
  sorting: number;
60
- /** Number of aggregation fields available */
61
- aggregation: number;
62
58
  /** Total number of matching items */
63
59
  result: number;
64
60
  /** Total number of pages */
@@ -143,22 +139,6 @@ export interface UseFronticSearchOptions<TSearch extends keyof Listings = keyof
143
139
  * }
144
140
  */
145
141
  sorting?: ListingFieldConfig<TSorts>;
146
- /**
147
- * Aggregation configuration using unified structure
148
- * Controls which aggregation fields to expose and how to label them
149
- * @example
150
- * // Show only price aggregation with a custom label
151
- * aggregation: {
152
- * select: ['price.amount'],
153
- * label: { 'price.amount': 'Price' }
154
- * }
155
- *
156
- * // Show all aggregations with custom labels
157
- * aggregation: {
158
- * label: { 'price.amount': 'Price', 'weight': 'Weight' }
159
- * }
160
- */
161
- aggregation?: ListingFieldConfig;
162
142
  /**
163
143
  * Disable search functionality (default: false)
164
144
  */
@@ -171,10 +151,30 @@ export interface UseFronticSearchOptions<TSearch extends keyof Listings = keyof
171
151
  * Disable sorting functionality (default: false)
172
152
  */
173
153
  disableSorting?: boolean;
154
+ /**
155
+ * Number of items per page (sent as `limit` to the Frontstack API).
156
+ * When omitted, the backend default is used.
157
+ */
158
+ limit?: number;
174
159
  /**
175
160
  * Stale time in milliseconds (default: 5 minutes)
176
161
  */
177
162
  staleTime?: number;
163
+ /**
164
+ * Enable infinite scroll mode.
165
+ * When true, loadNext()/loadPrev() append/prepend items from adjacent pages
166
+ * using Pinia Colada's useInfiniteQuery under the hood.
167
+ * When false (default), pagination replaces the current page.
168
+ */
169
+ infinite?: boolean;
170
+ /**
171
+ * Starting page number for infinite scroll mode.
172
+ * Useful when deep-linking to a specific page (e.g., page 4 from URL).
173
+ * Users can then scroll both forward (loadNext) and backward (loadPrev).
174
+ * Only used when `infinite: true`. Values below 1 are clamped to 1.
175
+ * @default 1
176
+ */
177
+ initialPage?: number;
178
178
  }
179
179
  /**
180
180
  * Return type for the search composable
@@ -193,9 +193,27 @@ export interface UseSearchReturn<TSearch extends keyof Listings = keyof Listings
193
193
  /** Current search term */
194
194
  searchTerm: Ref<string>;
195
195
  /**
196
- * Loads more items in the current search results (infinite scroll)
196
+ * Load the next page of results.
197
+ * Standard mode: replaces current page with the next one.
198
+ * Infinite mode: appends items from the next page.
199
+ * @returns The page response, or undefined if no next page
197
200
  */
198
201
  loadNext: () => Promise<Responses[TSearch] | undefined>;
202
+ /**
203
+ * Load the previous page of results.
204
+ * Standard mode: replaces current page with the previous one.
205
+ * Infinite mode: prepends items from the previous page.
206
+ * @returns The page response, or undefined if no previous page
207
+ */
208
+ loadPrev: () => Promise<Responses[TSearch] | undefined>;
209
+ /**
210
+ * Jump to a specific page number.
211
+ * Standard mode: replaces current page with the requested one.
212
+ * Infinite mode: resets all loaded pages and restarts from the given page.
213
+ * @param page - The page number to load
214
+ * @returns The page response, or undefined if the page doesn't exist
215
+ */
216
+ loadPage: (page: number) => Promise<Responses[TSearch] | undefined>;
199
217
  /**
200
218
  * Fetches the search with current query parameters (uses cache if valid)
201
219
  */
@@ -204,12 +222,6 @@ export interface UseSearchReturn<TSearch extends keyof Listings = keyof Listings
204
222
  * Forces a fresh fetch of the search, bypassing cache
205
223
  */
206
224
  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
225
  /**
214
226
  * Sorts the results by the specified field. Call without arguments to reset to default.
215
227
  * Type-safe: only accepts valid sort strings for this search
@@ -90,6 +90,46 @@ export declare function manageFilter<T = Record<string, unknown>>(filterList: Eq
90
90
  * ```
91
91
  */
92
92
  export declare function removeFilter<T = Record<string, unknown>>(filterList: EqualsFilter<T>[], field: keyof T & string, option?: T[keyof T]): EqualsFilter<T>[];
93
+ /**
94
+ * Value for a range filter (from/to bounds)
95
+ * Pass to addFilter/filterResult to create a range filter instead of an equals filter.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * addFilter('price.amount', { from: 20, to: 100 })
100
+ * addFilter('price.amount', { to: 100 }) // no lower bound
101
+ * ```
102
+ */
103
+ export interface RangeFilterValue {
104
+ from?: number;
105
+ to?: number;
106
+ }
107
+ /**
108
+ * Range filter for the API query
109
+ */
110
+ export interface RangeFilter {
111
+ type: 'range';
112
+ field: string;
113
+ from?: number;
114
+ to?: number;
115
+ }
116
+ /**
117
+ * Type guard to check if a value is a RangeFilterValue (object with from/to)
118
+ */
119
+ export declare function isRangeFilterValue(value: unknown): value is RangeFilterValue;
120
+ /**
121
+ * Creates a range filter for the API query
122
+ */
123
+ export declare function makeRangeFilter(field: string, value: RangeFilterValue): RangeFilter;
124
+ /**
125
+ * Manages range filter operations (add/update) on a range filter list.
126
+ * If a range filter for the field exists, it replaces it; otherwise, adds a new one.
127
+ */
128
+ export declare function manageRangeFilter(filterList: RangeFilter[], field: string, value: RangeFilterValue): RangeFilter[];
129
+ /**
130
+ * Removes a range filter for the specified field
131
+ */
132
+ export declare function removeRangeFilter(filterList: RangeFilter[], field: string): RangeFilter[];
93
133
  /**
94
134
  * Checks if a filter exists for a specific field
95
135
  *
@@ -36,6 +36,32 @@ export function removeFilter(filterList, field, option) {
36
36
  }
37
37
  return manageFilter(filterList, field, newValues);
38
38
  }
39
+ export function isRangeFilterValue(value) {
40
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
41
+ const obj = value;
42
+ return ("from" in obj || "to" in obj) && (!("from" in obj) || typeof obj.from === "number") && (!("to" in obj) || typeof obj.to === "number");
43
+ }
44
+ export function makeRangeFilter(field, value) {
45
+ return {
46
+ type: "range",
47
+ field,
48
+ ...value.from !== void 0 && { from: value.from },
49
+ ...value.to !== void 0 && { to: value.to }
50
+ };
51
+ }
52
+ export function manageRangeFilter(filterList, field, value) {
53
+ const newFilter = makeRangeFilter(field, value);
54
+ const existingIndex = filterList.findIndex((filter) => filter.field === field);
55
+ if (existingIndex !== -1) {
56
+ const newList = [...filterList];
57
+ newList[existingIndex] = newFilter;
58
+ return newList;
59
+ }
60
+ return [...filterList, newFilter];
61
+ }
62
+ export function removeRangeFilter(filterList, field) {
63
+ return filterList.filter((filter) => filter.field !== field);
64
+ }
39
65
  export function hasFilter(filterList, field) {
40
66
  return filterList.some((filter) => filter.field === field);
41
67
  }
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Functions for processing and transforming listing state for UI consumption.
5
5
  */
6
- import type { ListingFieldConfig, UiFilter, UiSort, UiAggregation, AggregationTotal, FilterOption } from '../types/listing.js';
6
+ import type { ListingFieldConfig, UiFilter, UiSort, AggregationTotal, FilterOption } from '../types/listing.js';
7
7
  /**
8
8
  * Frontstack filter response structure
9
9
  */
@@ -39,25 +39,30 @@ interface FrontstackAggregationResponse {
39
39
  */
40
40
  export declare function makeFilterState(filters: FrontstackFilterResponse | undefined): Record<string, FilterOption[]>;
41
41
  /**
42
- * Processes raw filter response into UI-ready filter objects
42
+ * Processes raw filter and aggregation responses into a unified array of UI-ready filter objects.
43
+ * Aggregation data is merged onto matching filters or added as new entries.
43
44
  *
44
45
  * @template TFilters - Filter fields type for this listing (provides typed keys)
45
46
  * @param rawFilters - Raw filter response from Frontstack API
46
- * @param config - Filter configuration (select, mode, label, sort)
47
+ * @param rawAggregation - Raw aggregation response from Frontstack API
48
+ * @param config - Filter configuration (select, mode, label, sort, type)
47
49
  * @returns Array of UiFilter objects ready for rendering (with typed keys)
48
50
  *
49
51
  * @example
50
52
  * ```ts
51
- * const filters = processAvailableFilters<ProductSearchFilters>(response.filter, {
52
- * select: ['properties.color'],
53
+ * const filters = processAvailableFilters<ProductSearchFilters>(response.filter, response.aggregation, {
54
+ * select: ['properties.color', 'price.amount'],
53
55
  * mode: 'include',
54
- * label: { 'properties.color': 'Color' },
55
- * sort: ['properties.color', 'properties.size']
56
+ * label: { 'properties.color': 'Color', 'price.amount': 'Price' },
57
+ * type: { 'price.amount': 'range' },
56
58
  * })
57
- * // [{ key: 'properties.color', label: 'Color', options: [...] }]
59
+ * // [
60
+ * // { key: 'properties.color', label: 'Color', type: 'default', options: [...] },
61
+ * // { key: 'price.amount', label: 'Price', type: 'range', options: [], data: { min: 9.99, max: 299.99, ... } },
62
+ * // ]
58
63
  * ```
59
64
  */
60
- export declare function processAvailableFilters<TFilters = Record<string, unknown>>(rawFilters: FrontstackFilterResponse | undefined, config?: ListingFieldConfig): UiFilter<TFilters>[];
65
+ export declare function processAvailableFilters<TFilters = Record<string, unknown>>(rawFilters: FrontstackFilterResponse | undefined, rawAggregation: FrontstackAggregationResponse | undefined, config?: ListingFieldConfig): UiFilter<TFilters>[];
61
66
  /**
62
67
  * Processes sort configuration into UI-ready sort options
63
68
  *
@@ -82,24 +87,7 @@ export declare function processAvailableFilters<TFilters = Record<string, unknow
82
87
  * // ]
83
88
  * ```
84
89
  */
85
- export declare function processAvailableSorts<TSorts = Record<string, unknown>>(config?: ListingFieldConfig): UiSort<TSorts>[];
86
- /**
87
- * Processes raw aggregation response into UI-ready aggregation objects
88
- *
89
- * @param rawAggregation - Raw aggregation response from Frontstack API
90
- * @param config - Aggregation configuration (select, mode, label, sort)
91
- * @returns Array of UiAggregation objects ready for rendering
92
- *
93
- * @example
94
- * ```ts
95
- * const aggregations = processAvailableAggregations(response.aggregation, {
96
- * select: ['price.amount'],
97
- * label: { 'price.amount': 'Price' }
98
- * })
99
- * // [{ key: 'price.amount', label: 'Price', min: 9.99, max: 299.99, ... }]
100
- * ```
101
- */
102
- export declare function processAvailableAggregations(rawAggregation: FrontstackAggregationResponse | undefined, config?: ListingFieldConfig): UiAggregation[];
90
+ export declare function processAvailableSorts<TSorts = Record<string, unknown>>(config?: ListingFieldConfig, responseHasSort?: boolean): UiSort<TSorts>[];
103
91
  /**
104
92
  * Applies filter configuration to transform the filter state
105
93
  * Handles include/exclude mode and label renaming
@@ -27,27 +27,35 @@ function sortByOrder(items, order, getKey) {
27
27
  return 0;
28
28
  });
29
29
  }
30
- export function processAvailableFilters(rawFilters, config = {}) {
31
- if (!rawFilters) return [];
32
- const { select = [], mode = "include", label: labels = {}, sort: sortOrder } = config;
30
+ export function processAvailableFilters(rawFilters, rawAggregation, config = {}) {
31
+ if (!rawFilters && !rawAggregation) return [];
32
+ const { select = [], mode = "include", label: labels = {}, sort: sortOrder, type: typeConfig = {} } = config;
33
33
  const availableFilters = [];
34
- const responseFilterKeys = Object.keys(rawFilters);
35
- for (const key of responseFilterKeys) {
34
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(rawFilters || {}), ...Object.keys(rawAggregation || {})]);
35
+ for (const key of allKeys) {
36
36
  const isInSelect = select.includes(key);
37
37
  const shouldInclude = select.length === 0 || (mode === "include" ? isInSelect : !isInSelect);
38
38
  if (!shouldInclude) continue;
39
- const filterOptions = rawFilters[key] || [];
40
- if (filterOptions.length === 0) continue;
39
+ const filterOptions = rawFilters?.[key] || [];
40
+ const aggregationData = rawAggregation?.[key]?.total;
41
+ if (filterOptions.length === 0 && !aggregationData) continue;
41
42
  const filterLabel = labels[key] || key;
42
- availableFilters.push({
43
+ const filterType = typeConfig[key] || "default";
44
+ const uiFilter = {
43
45
  key,
44
46
  label: filterLabel,
45
- options: filterOptions
46
- });
47
+ options: filterOptions,
48
+ type: filterType
49
+ };
50
+ if (aggregationData) {
51
+ uiFilter.data = aggregationData;
52
+ }
53
+ availableFilters.push(uiFilter);
47
54
  }
48
55
  return sortByOrder(availableFilters, sortOrder, (f) => f.key);
49
56
  }
50
- export function processAvailableSorts(config = {}) {
57
+ export function processAvailableSorts(config = {}, responseHasSort = true) {
58
+ if (!responseHasSort) return [];
51
59
  const { select = [], mode = "include", label: labels = {}, sort: sortOrder } = config;
52
60
  const availableSorts = Object.entries(labels).filter(([value]) => {
53
61
  if (select.length === 0) return true;
@@ -62,25 +70,6 @@ export function processAvailableSorts(config = {}) {
62
70
  );
63
71
  return sortByOrder(availableSorts, sortOrder, (s) => s.key);
64
72
  }
65
- export function processAvailableAggregations(rawAggregation, config = {}) {
66
- if (!rawAggregation) return [];
67
- const { select = [], mode = "include", label: labels = {}, sort: sortOrder } = config;
68
- const availableAggregations = [];
69
- for (const key of Object.keys(rawAggregation)) {
70
- const isInSelect = select.includes(key);
71
- const shouldInclude = select.length === 0 || (mode === "include" ? isInSelect : !isInSelect);
72
- if (!shouldInclude) continue;
73
- const aggregationData = rawAggregation[key]?.total;
74
- if (!aggregationData) continue;
75
- const aggregationLabel = labels[key] || key;
76
- availableAggregations.push({
77
- key,
78
- label: aggregationLabel,
79
- ...aggregationData
80
- });
81
- }
82
- return sortByOrder(availableAggregations, sortOrder, (a) => a.key);
83
- }
84
73
  export function applyFilterConfig(filters, config = {}) {
85
74
  const { select = [], mode = "include", label: labels = {} } = config;
86
75
  let result = filters;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontic/nuxt",
3
- "version": "0.3.0",
3
+ "version": "0.5.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
  }