@frontic/nuxt 0.0.2 → 0.1.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.
Files changed (31) hide show
  1. package/LICENSE +21 -0
  2. package/dist/module.d.mts +87 -10
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +117 -56
  5. package/dist/runtime/composables/blocks.d.ts +0 -0
  6. package/dist/runtime/composables/blocks.js +31 -0
  7. package/dist/runtime/composables/index.js +7 -0
  8. package/dist/runtime/composables/listings.js +15 -9
  9. package/dist/runtime/composables/pages.d.ts +0 -0
  10. package/dist/runtime/composables/pages.js +31 -0
  11. package/dist/runtime/composables/useFronticBlock.d.ts +0 -0
  12. package/dist/runtime/composables/useFronticBlock.js +31 -0
  13. package/dist/runtime/composables/useFronticClient.d.ts +0 -0
  14. package/dist/runtime/composables/useFronticClient.js +67 -0
  15. package/dist/runtime/composables/useFronticContext.d.ts +0 -0
  16. package/dist/runtime/composables/useFronticContext.js +77 -0
  17. package/dist/runtime/composables/useFronticListing.js +26 -201
  18. package/dist/runtime/composables/useFronticPage.d.ts +0 -0
  19. package/dist/runtime/composables/useFronticPage.js +74 -0
  20. package/dist/runtime/composables/useFronticSearch.d.ts +0 -0
  21. package/dist/runtime/composables/useFronticSearch.js +321 -0
  22. package/dist/runtime/server/api/frontic/[...path].d.ts +0 -0
  23. package/dist/runtime/server/api/frontic/[...path].js +21 -0
  24. package/dist/runtime/types/search.d.ts +0 -0
  25. package/dist/runtime/types/search.js +0 -0
  26. package/dist/runtime/utils/state-helpers.js +19 -19
  27. package/dist/types.d.mts +4 -2
  28. package/package.json +20 -20
  29. package/dist/module.cjs +0 -5
  30. package/dist/module.d.ts +0 -48
  31. package/dist/types.d.ts +0 -7
@@ -0,0 +1,77 @@
1
+ import { useFronticClient } from "./useFronticClient.js";
2
+ export function useFronticContext(options) {
3
+ const client = useFronticClient();
4
+ const config = useRuntimeConfig();
5
+ const cookieName = options?.cookieName ?? config.public.frontic?.contextCookieName ?? "fs-context";
6
+ const cookieMaxAge = options?.cookieMaxAge ?? config.public.frontic?.contextCookieMaxAge ?? 60 * 60 * 24 * 365;
7
+ const disableContext = options?.disableContext ?? config.public.frontic?.disableContext ?? false;
8
+ const tokenCookie = disableContext ? null : useCookie(cookieName, { maxAge: cookieMaxAge });
9
+ const token = ref(tokenCookie?.value ?? null);
10
+ const contexts = ref([]);
11
+ const current = ref(null);
12
+ const isLoading = ref(false);
13
+ async function fetchContexts() {
14
+ isLoading.value = true;
15
+ try {
16
+ const [contextList, newToken] = await client.contextList(token.value ?? void 0);
17
+ contexts.value = contextList;
18
+ token.value = newToken;
19
+ if (tokenCookie) {
20
+ tokenCookie.value = newToken;
21
+ }
22
+ if (newToken) {
23
+ current.value = await client.context(newToken);
24
+ }
25
+ } catch (error) {
26
+ console.error("[@frontic/nuxt] Failed to fetch contexts:", error);
27
+ } finally {
28
+ isLoading.value = false;
29
+ }
30
+ }
31
+ async function update(context) {
32
+ if (!token.value) {
33
+ await fetchContexts();
34
+ }
35
+ if (!token.value) {
36
+ console.error("[@frontic/nuxt] No context token available");
37
+ return;
38
+ }
39
+ isLoading.value = true;
40
+ try {
41
+ current.value = await client.contextUpdate(context, token.value);
42
+ } catch (error) {
43
+ console.error("[@frontic/nuxt] Failed to update context:", error);
44
+ } finally {
45
+ isLoading.value = false;
46
+ }
47
+ }
48
+ if (import.meta.client && !disableContext) {
49
+ onMounted(fetchContexts);
50
+ }
51
+ return {
52
+ /**
53
+ * Available context options (regions/locales)
54
+ */
55
+ contexts: readonly(contexts),
56
+ /**
57
+ * Current context (region, locale, scope, token)
58
+ */
59
+ current: readonly(current),
60
+ /**
61
+ * Context token (used for API calls)
62
+ */
63
+ token: readonly(token),
64
+ /**
65
+ * Update the current context (switch locale/region)
66
+ */
67
+ update,
68
+ /**
69
+ * Loading state
70
+ */
71
+ isLoading: readonly(isLoading),
72
+ /**
73
+ * Manually refresh contexts and current context
74
+ */
75
+ refresh: fetchContexts
76
+ };
77
+ }
@@ -1,208 +1,33 @@
1
- import { useQuery, useMutation, useQueryCache } from "@pinia/colada";
2
- import { useDebounceFn } from "@vueuse/core";
3
- import { makeLogicalFilter, manageFilter, removeFilter } from "../utils/filter-helpers.js";
4
- import { makeFilterState, processAvailableFilters, processAvailableSorts, applyFilterConfig, countActiveFilters, parseSortString, isSortAllowed } from "../utils/state-helpers.js";
1
+ import { useQuery } from "@pinia/colada";
5
2
  import { fetchListingQuery } from "./listings.js";
6
- export function useFronticListing(config) {
7
- const queryCache = useQueryCache();
8
- const {
9
- name: listingName,
10
- params = {},
11
- cacheKey = listingName,
12
- contextKey,
13
- searchTermThreshold = 2,
14
- orFilterKeys = [],
15
- filters,
16
- sorts,
17
- enableSearch = true,
18
- enableFilters = true,
19
- enableSort = true,
20
- staleTime = 1e3 * 60 * 5
21
- // 5 minutes
22
- } = config;
23
- const filterConfig = filters || {};
24
- const sortConfig = sorts || {};
25
- const searchTerm = useState(`${cacheKey}-searchTerm`, () => "");
26
- const _orFilterList = useState(`${cacheKey}-orFilterList`, () => []);
27
- const _andFilterList = useState(`${cacheKey}-andFilterList`, () => []);
28
- const _sortQuery = useState(`${cacheKey}-sortQuery`, () => void 0);
29
- const listingState = useState(`${cacheKey}-listingState`, () => ({
30
- sort: void 0,
31
- search: void 0,
32
- filter: void 0
33
- }));
34
- const apiQuery = computed(() => ({
35
- sort: enableSort ? _sortQuery.value : void 0,
36
- search: enableSearch && searchTerm.value && searchTerm.value.trim().length > searchTermThreshold ? searchTerm.value : void 0,
37
- filter: enableFilters ? [...makeLogicalFilter("or", _orFilterList.value), ...makeLogicalFilter("and", _andFilterList.value)] : void 0
38
- }));
39
- const { data, status, refresh } = useQuery(
40
- fetchListingQuery({
41
- listingName,
42
- parameters: params,
43
- query: apiQuery,
44
- contextKey,
45
- staleTime
46
- })
47
- );
48
- const { mutateAsync: loadMore } = useMutation({
49
- mutation: async () => {
50
- const nextPage = data.value?.page;
51
- if (!nextPage?.next) return void 0;
52
- const nextPageQuery = fetchListingQuery({
53
- listingName,
54
- parameters: params,
55
- query: apiQuery,
56
- contextKey,
57
- page: ref(nextPage.next),
58
- staleTime
59
- });
60
- return await nextPageQuery.query();
61
- },
62
- onSuccess: (data2) => {
63
- const newData = data2;
64
- const newItems = newData?.items || [];
65
- if (!newItems.length) return;
66
- const cacheKeyValue = [cacheKey, JSON.stringify(apiQuery.value)];
67
- const oldData = queryCache.getQueryData(cacheKeyValue);
68
- queryCache.setQueryData(cacheKeyValue, {
69
- ...newData,
70
- items: [...oldData?.items || [], ...newItems]
71
- });
72
- }
3
+ export function useFronticListing(name, params, options) {
4
+ const listingQuery = fetchListingQuery({
5
+ name,
6
+ params,
7
+ query: {},
8
+ // No query for simple listing - use useFronticSearch for filtering/sorting
9
+ contextKey: options?.contextKey,
10
+ contextDomain: options?.contextDomain,
11
+ requestUrl: options?.requestUrl,
12
+ staleTime: options?.staleTime
73
13
  });
74
- if (enableSearch) {
75
- watch(searchTerm, (newTerm) => {
76
- if (newTerm.trim().length > searchTermThreshold || listingState.value.search) {
77
- triggerSearchFromInput();
78
- }
79
- });
80
- }
81
- watch(
82
- data,
83
- (newData) => {
84
- if (newData) {
85
- updateState(newData);
86
- }
87
- },
88
- { immediate: true }
89
- );
90
- function updateState(response) {
91
- const rawFilters = response.filter;
92
- let uiFilters = makeFilterState(rawFilters);
93
- uiFilters = applyFilterConfig(uiFilters, filterConfig);
94
- const availableFilters = processAvailableFilters(rawFilters, filterConfig);
95
- const availableSorts = processAvailableSorts(sortConfig);
96
- const activeFilterCount = countActiveFilters(uiFilters);
97
- const pageData = response.page;
98
- listingState.value = {
99
- page: pageData?.current,
100
- sort: _sortQuery.value,
101
- search: apiQuery.value.search,
102
- filter: uiFilters,
103
- availableFilters,
104
- availableSorts,
105
- activeFilterCount,
106
- total: response.total ?? 0
107
- };
108
- }
109
- async function refreshListing() {
110
- await refresh();
111
- if (data.value) {
112
- updateState(data.value);
113
- }
114
- }
115
- const triggerSearchFromInput = useDebounceFn(refreshListing, 200);
116
- async function paginate(direction) {
117
- const pageData = data.value?.page;
118
- const pageNumber = direction === "next" ? pageData?.next : pageData?.prev;
119
- if (!pageNumber) return false;
120
- listingState.value.page = pageNumber;
121
- const pageQuery = fetchListingQuery({
122
- listingName,
123
- parameters: params,
124
- query: apiQuery,
125
- contextKey,
126
- page: ref(pageNumber),
127
- staleTime
128
- });
129
- const response = await pageQuery.query();
130
- if (response) {
131
- updateState(response);
132
- }
133
- return !!response;
134
- }
135
- async function sortItems(sortBy) {
136
- if (!enableSort) return;
137
- const sortValue = parseSortString(sortBy);
138
- if (!sortValue) {
139
- _sortQuery.value = void 0;
140
- } else {
141
- if (!isSortAllowed(sortBy, sortConfig)) return;
142
- _sortQuery.value = sortValue;
143
- }
144
- await refreshListing();
145
- }
146
- async function resetSort() {
147
- if (!enableSort) return;
148
- _sortQuery.value = void 0;
149
- await refreshListing();
150
- }
151
- async function filterItems(filterField, filterOptions) {
152
- if (!enableFilters) return;
153
- const shouldUseOr = orFilterKeys.includes(filterField);
154
- const targetList = shouldUseOr ? _orFilterList : _andFilterList;
155
- targetList.value = manageFilter(targetList.value, filterField, filterOptions);
156
- await refreshListing();
157
- }
158
- async function addFilterOption(filterField, filterOption) {
159
- if (!enableFilters) return;
160
- const shouldUseOr = orFilterKeys.includes(filterField);
161
- const targetList = shouldUseOr ? _orFilterList : _andFilterList;
162
- const existingFilter = targetList.value.find((filter) => filter.field === filterField);
163
- const currentValues = existingFilter ? Array.isArray(existingFilter.value) ? existingFilter.value : [existingFilter.value] : [];
164
- targetList.value = manageFilter(targetList.value, filterField, [...currentValues, filterOption]);
165
- await refreshListing();
166
- }
167
- async function removeFilterOption(filterField, filterOption) {
168
- if (!enableFilters) return;
169
- const shouldUseOr = orFilterKeys.includes(filterField);
170
- const targetList = shouldUseOr ? _orFilterList : _andFilterList;
171
- targetList.value = removeFilter(targetList.value, filterField, filterOption);
172
- await refreshListing();
173
- }
174
- async function resetFilter(filterField) {
175
- if (!enableFilters) return;
176
- if (!filterField) {
177
- _orFilterList.value = [];
178
- _andFilterList.value = [];
179
- } else {
180
- const shouldUseOr = orFilterKeys.includes(filterField);
181
- const targetList = shouldUseOr ? _orFilterList : _andFilterList;
182
- targetList.value = removeFilter(targetList.value, filterField);
183
- }
184
- await refreshListing();
185
- }
186
- async function resetSearch() {
187
- searchTerm.value = "";
188
- await refreshListing();
189
- }
14
+ const { data, status, refresh, refetch } = useQuery(listingQuery);
190
15
  return {
191
- // State
16
+ /**
17
+ * The listing data, typed based on the listing name
18
+ */
192
19
  listing: data,
20
+ /**
21
+ * Query status: 'pending' | 'error' | 'success'
22
+ */
193
23
  status,
194
- state: listingState,
195
- searchTerm,
196
- // Actions
197
- loadMore: () => loadMore(),
198
- refresh: refreshListing,
199
- paginate,
200
- sortItems,
201
- resetSort,
202
- filterItems,
203
- addFilter: addFilterOption,
204
- removeFilter: removeFilterOption,
205
- resetFilter,
206
- resetSearch
24
+ /**
25
+ * Manually refresh the listing data (uses cache if valid)
26
+ */
27
+ refresh,
28
+ /**
29
+ * Force a fresh fetch of the listing data, bypassing cache
30
+ */
31
+ refetch
207
32
  };
208
33
  }
File without changes
@@ -0,0 +1,74 @@
1
+ import { useQuery } from "@pinia/colada";
2
+ import { fetchPageQuery } from "./pages.js";
3
+ export function useFronticPage(slug, options) {
4
+ const requestURL = useRequestURL();
5
+ const config = useRuntimeConfig();
6
+ const pageSlug = computed(() => {
7
+ if (slug) return toValue(slug);
8
+ return `${requestURL.host}${requestURL.pathname}`;
9
+ });
10
+ const pageQuery = fetchPageQuery({
11
+ slug: pageSlug,
12
+ contextKey: options?.contextKey,
13
+ contextDomain: options?.contextDomain,
14
+ requestUrl: options?.requestUrl,
15
+ staleTime: options?.staleTime
16
+ });
17
+ const { data, status, refresh, refetch } = useQuery(pageQuery);
18
+ const redirectOn301 = options?.redirectOn301 ?? config.public.frontic?.redirectOn301 ?? true;
19
+ const throwOn404 = options?.throwOn404 ?? config.public.frontic?.throwOn404 ?? true;
20
+ watch(
21
+ data,
22
+ (page) => {
23
+ if (!page?.route) return;
24
+ if (redirectOn301 && page.route.code === 301 && page.route.redirect) {
25
+ navigateTo(page.route.redirect.path, { redirectCode: 301 });
26
+ } else if (throwOn404 && page.route.code === 404) {
27
+ throw createError({ statusCode: 404, statusMessage: "Page not found" });
28
+ }
29
+ },
30
+ { immediate: true }
31
+ );
32
+ return {
33
+ /**
34
+ * Raw page response
35
+ */
36
+ page: data,
37
+ /**
38
+ * Page data (the actual content block data)
39
+ */
40
+ data: computed(() => data.value?.data),
41
+ /**
42
+ * Page type (e.g., 'ProductCategory', 'Product', 'Brand')
43
+ */
44
+ type: computed(() => data.value?.type),
45
+ /**
46
+ * Block name to render (e.g., 'CategoryFull', 'ProductFull')
47
+ */
48
+ block: computed(() => data.value?.block),
49
+ /**
50
+ * Route metadata (code, redirect, alternates, context)
51
+ */
52
+ route: computed(() => data.value?.route),
53
+ /**
54
+ * Alternate URLs for hreflang tags
55
+ */
56
+ alternates: computed(() => data.value?.route?.alternates),
57
+ /**
58
+ * Suggested route when context changes (for locale switching)
59
+ */
60
+ suggested: computed(() => data.value?.route?.context?.suggested),
61
+ /**
62
+ * Query status: 'pending' | 'error' | 'success'
63
+ */
64
+ status,
65
+ /**
66
+ * Manually refresh the page data (uses cache if valid)
67
+ */
68
+ refresh,
69
+ /**
70
+ * Force a fresh fetch of the page data, bypassing cache
71
+ */
72
+ refetch
73
+ };
74
+ }
File without changes