@nitrogenbuilder/connector-payload 0.1.31 → 0.1.33

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.
@@ -1,3 +1,4 @@
1
1
  export declare const NitrogenEditButton: import("react").ComponentType<{
2
2
  collection: string;
3
+ routePattern?: string;
3
4
  }>;
@@ -1,4 +1,5 @@
1
1
  import React from 'react';
2
2
  export declare const NitrogenEditButtonRuntime: React.FC<{
3
3
  collection: string;
4
+ routePattern?: string;
4
5
  }>;
@@ -15,16 +15,44 @@ function getPreferredSiteUrl(data) {
15
15
  const fallbackUrl = isLocalAdmin ? data.frontendUrl : data.developmentUrl;
16
16
  return preferredUrl || fallbackUrl || '';
17
17
  }
18
- export const NitrogenEditButtonRuntime = ({ collection }) => {
18
+ function normalizeRoutePattern(routePattern) {
19
+ if (!routePattern)
20
+ return undefined;
21
+ return routePattern.startsWith('/') ? routePattern : `/${routePattern}`;
22
+ }
23
+ function trimSlashes(value) {
24
+ return value.replace(/^\/+|\/+$/g, '');
25
+ }
26
+ function buildRelativePath(slug, routePattern, templateSlug) {
27
+ const normalizedRoutePattern = normalizeRoutePattern(routePattern);
28
+ if (normalizedRoutePattern) {
29
+ if (normalizedRoutePattern.includes('[...slug]')) {
30
+ return normalizedRoutePattern.replace('[...slug]', slug);
31
+ }
32
+ if (normalizedRoutePattern.includes('[slug]')) {
33
+ return normalizedRoutePattern.replace('[slug]', slug);
34
+ }
35
+ return normalizedRoutePattern.endsWith('/')
36
+ ? `${normalizedRoutePattern}${slug}`
37
+ : normalizedRoutePattern;
38
+ }
39
+ if (templateSlug) {
40
+ return `/${trimSlashes(templateSlug)}/${trimSlashes(slug)}`;
41
+ }
42
+ return `/${trimSlashes(slug)}`;
43
+ }
44
+ export const NitrogenEditButtonRuntime = ({ collection, routePattern }) => {
19
45
  const [id, setId] = useState(undefined);
20
46
  const [token, setToken] = useState(undefined);
21
47
  const [slug, setSlug] = useState(undefined);
22
48
  const [frontendUrl, setFrontendUrl] = useState(undefined);
23
49
  const [instanceUrl, setInstanceUrl] = useState(undefined);
24
50
  const [authorId, setAuthorId] = useState(undefined);
51
+ const [templateSlug, setTemplateSlug] = useState(undefined);
25
52
  useEffect(() => {
26
53
  const segments = window.location.pathname.split('/').filter(Boolean);
27
54
  const docId = segments.length >= 4 ? segments[3] : undefined;
55
+ const shouldResolveTemplateSlug = collection !== 'nitrogen-templates' && !routePattern;
28
56
  if (docId) {
29
57
  setId(docId);
30
58
  fetch(`/api/${collection}/${docId}`)
@@ -38,6 +66,29 @@ export const NitrogenEditButtonRuntime = ({ collection }) => {
38
66
  console.error('Failed to fetch document:', err);
39
67
  });
40
68
  }
69
+ setTemplateSlug(undefined);
70
+ if (shouldResolveTemplateSlug) {
71
+ const params = new URLSearchParams();
72
+ params.set('where[associatedCollection][equals]', collection);
73
+ params.set('where[status][equals]', 'published');
74
+ params.set('limit', '1');
75
+ params.set('depth', '0');
76
+ fetch(`/api/nitrogen-templates?${params.toString()}`)
77
+ .then((res) => res.json())
78
+ .then((data) => {
79
+ const doc = Array.isArray(data?.docs) ? data.docs[0] : undefined;
80
+ if (typeof doc?.slug === 'string') {
81
+ setTemplateSlug(doc.slug);
82
+ }
83
+ else {
84
+ setTemplateSlug(null);
85
+ }
86
+ })
87
+ .catch((err) => {
88
+ console.error('Failed to fetch nitrogen template:', err);
89
+ setTemplateSlug(null);
90
+ });
91
+ }
41
92
  fetch('/api/users/me')
42
93
  .then((res) => res.json())
43
94
  .then((data) => {
@@ -65,7 +116,7 @@ export const NitrogenEditButtonRuntime = ({ collection }) => {
65
116
  .catch((err) => {
66
117
  console.error('Failed to fetch nitrogen settings:', err);
67
118
  });
68
- }, [collection]);
119
+ }, [collection, routePattern]);
69
120
  if (!id || !token || !authorId)
70
121
  return null;
71
122
  const editorBase = instanceUrl ?? '';
@@ -73,13 +124,18 @@ export const NitrogenEditButtonRuntime = ({ collection }) => {
73
124
  const encodedAuthorId = encodeURIComponent(authorId);
74
125
  const developmentFlags = isDevelopmentMode ? '&development=true' : '';
75
126
  const editHref = `${editorBase}/nitrogen-editor?token=${encodeURIComponent(token)}&collection=${encodeURIComponent(collection)}&pageId=${id}&authorId=${encodedAuthorId}&author=${encodedAuthorId}${developmentFlags}`;
76
- const viewHref = collection === 'nitrogen-templates'
77
- ? `${frontendUrl}/nitrogen-templates/${slug}`
78
- : `${frontendUrl}/${slug}`;
127
+ const viewRelativePath = collection === 'nitrogen-templates'
128
+ ? `/nitrogen-templates/${trimSlashes(slug || '')}`
129
+ : buildRelativePath(slug || '', routePattern, templateSlug ?? undefined);
130
+ const viewHref = `${frontendUrl}${viewRelativePath}`;
79
131
  const editButtonVars = isDevelopmentMode
80
132
  ? nitrogenEditDevButtonVars
81
133
  : nitrogenEditLiveButtonVars;
82
- return (_jsxs("div", { style: nitrogenButtonGroupStyle, children: [slug && frontendUrl && (_jsx(Button, { buttonStyle: "primary", el: "anchor", margin: false, newTab: true, url: viewHref, extraButtonProps: {
134
+ return (_jsxs("div", { style: nitrogenButtonGroupStyle, children: [slug &&
135
+ frontendUrl &&
136
+ (collection === 'nitrogen-templates' ||
137
+ routePattern ||
138
+ templateSlug !== undefined) && (_jsx(Button, { buttonStyle: "primary", el: "anchor", margin: false, newTab: true, url: viewHref, extraButtonProps: {
83
139
  style: nitrogenViewButtonVars,
84
140
  }, children: collection === 'nitrogen-templates' ? 'View Template' : 'View Page' })), _jsx(Button, { buttonStyle: "primary", el: "anchor", margin: false, newTab: true, url: editHref, extraButtonProps: {
85
141
  style: editButtonVars,
@@ -1,3 +1,4 @@
1
1
  export declare const NitrogenViewButton: import("react").ComponentType<{
2
2
  collection: string;
3
+ routePattern?: string;
3
4
  }>;
@@ -1,4 +1,5 @@
1
1
  import React from 'react';
2
2
  export declare const NitrogenViewButtonRuntime: React.FC<{
3
3
  collection: string;
4
+ routePattern?: string;
4
5
  }>;
@@ -12,12 +12,40 @@ function getPreferredSiteUrl(data) {
12
12
  const fallbackUrl = isLocalAdmin ? data.frontendUrl : data.developmentUrl;
13
13
  return preferredUrl || fallbackUrl || '';
14
14
  }
15
- export const NitrogenViewButtonRuntime = ({ collection }) => {
15
+ function normalizeRoutePattern(routePattern) {
16
+ if (!routePattern)
17
+ return undefined;
18
+ return routePattern.startsWith('/') ? routePattern : `/${routePattern}`;
19
+ }
20
+ function trimSlashes(value) {
21
+ return value.replace(/^\/+|\/+$/g, '');
22
+ }
23
+ function buildRelativePath(slug, routePattern, templateSlug) {
24
+ const normalizedRoutePattern = normalizeRoutePattern(routePattern);
25
+ if (normalizedRoutePattern) {
26
+ if (normalizedRoutePattern.includes('[...slug]')) {
27
+ return normalizedRoutePattern.replace('[...slug]', slug);
28
+ }
29
+ if (normalizedRoutePattern.includes('[slug]')) {
30
+ return normalizedRoutePattern.replace('[slug]', slug);
31
+ }
32
+ return normalizedRoutePattern.endsWith('/')
33
+ ? `${normalizedRoutePattern}${slug}`
34
+ : normalizedRoutePattern;
35
+ }
36
+ if (templateSlug) {
37
+ return `/${trimSlashes(templateSlug)}/${trimSlashes(slug)}`;
38
+ }
39
+ return `/${trimSlashes(slug)}`;
40
+ }
41
+ export const NitrogenViewButtonRuntime = ({ collection, routePattern }) => {
16
42
  const [slug, setSlug] = useState(undefined);
17
43
  const [siteUrl, setSiteUrl] = useState(undefined);
44
+ const [templateSlug, setTemplateSlug] = useState(undefined);
18
45
  useEffect(() => {
19
46
  const segments = window.location.pathname.split('/').filter(Boolean);
20
47
  const docId = segments.length >= 4 ? segments[3] : undefined;
48
+ const shouldResolveTemplateSlug = collection !== 'nitrogen-templates' && !routePattern;
21
49
  if (!docId)
22
50
  return;
23
51
  fetch(`/api/${collection}/${docId}`)
@@ -30,6 +58,29 @@ export const NitrogenViewButtonRuntime = ({ collection }) => {
30
58
  .catch((err) => {
31
59
  console.error('Failed to fetch document:', err);
32
60
  });
61
+ setTemplateSlug(undefined);
62
+ if (shouldResolveTemplateSlug) {
63
+ const params = new URLSearchParams();
64
+ params.set('where[associatedCollection][equals]', collection);
65
+ params.set('where[status][equals]', 'published');
66
+ params.set('limit', '1');
67
+ params.set('depth', '0');
68
+ fetch(`/api/nitrogen-templates?${params.toString()}`)
69
+ .then((res) => res.json())
70
+ .then((data) => {
71
+ const doc = Array.isArray(data?.docs) ? data.docs[0] : undefined;
72
+ if (typeof doc?.slug === 'string') {
73
+ setTemplateSlug(doc.slug);
74
+ }
75
+ else {
76
+ setTemplateSlug(null);
77
+ }
78
+ })
79
+ .catch((err) => {
80
+ console.error('Failed to fetch nitrogen template:', err);
81
+ setTemplateSlug(null);
82
+ });
83
+ }
33
84
  fetch('/api/globals/nitrogen-settings')
34
85
  .then((res) => res.json())
35
86
  .then((data) => {
@@ -41,11 +92,17 @@ export const NitrogenViewButtonRuntime = ({ collection }) => {
41
92
  .catch((err) => {
42
93
  console.error('Failed to fetch nitrogen settings:', err);
43
94
  });
44
- }, [collection]);
95
+ }, [collection, routePattern]);
45
96
  if (!slug || !siteUrl) {
46
97
  return null;
47
98
  }
48
- const href = `${siteUrl}/${slug}`;
99
+ if (collection !== 'nitrogen-templates' && !routePattern && templateSlug === undefined) {
100
+ return null;
101
+ }
102
+ const relativePath = collection === 'nitrogen-templates'
103
+ ? `/nitrogen-templates/${trimSlashes(slug)}`
104
+ : buildRelativePath(slug, routePattern, templateSlug ?? undefined);
105
+ const href = `${siteUrl}${relativePath}`;
49
106
  return (_jsx(Button, { buttonStyle: "primary", el: "anchor", margin: false, newTab: true, url: href, extraButtonProps: {
50
107
  style: nitrogenViewButtonVars,
51
108
  }, children: "View Page" }));
@@ -2,9 +2,7 @@ import { buildPermalink, buildRelativePermalink, resolveCollection, } from "../c
2
2
  import { getNitrogenSettings, buildDynamicData, buildPageResponse, } from "./helpers";
3
3
  function toArray(value) {
4
4
  if (Array.isArray(value)) {
5
- return value
6
- .map((item) => String(item).trim())
7
- .filter(Boolean);
5
+ return value.map((item) => String(item).trim()).filter(Boolean);
8
6
  }
9
7
  if (typeof value === "string") {
10
8
  return value
@@ -14,6 +12,12 @@ function toArray(value) {
14
12
  }
15
13
  return [];
16
14
  }
15
+ function isTruthyParam(value) {
16
+ return value === true || value === "true" || value === "1" || value === 1;
17
+ }
18
+ function unique(values) {
19
+ return Array.from(new Set(values));
20
+ }
17
21
  async function resolveRelationshipIds(payload, collection, values) {
18
22
  if (values.length === 0)
19
23
  return [];
@@ -39,6 +43,37 @@ async function resolveRelationshipIds(payload, collection, values) {
39
43
  ]);
40
44
  return [...slugMatches.docs, ...titleMatches.docs].map((doc) => doc.id);
41
45
  }
46
+ async function resolveAllRelationshipIds(payload, collection) {
47
+ const result = await payload.find({
48
+ collection,
49
+ limit: 1000,
50
+ depth: 0,
51
+ pagination: false,
52
+ });
53
+ return result.docs.map((doc) => doc.id);
54
+ }
55
+ async function applyRelationshipFilter({ payload, results, key, where, field, collection, includeValues, excludeValues = [], }) {
56
+ const includeIds = await resolveRelationshipIds(payload, collection, includeValues);
57
+ if (includeValues.length > 0) {
58
+ if (includeIds.length === 0) {
59
+ results[key] = {
60
+ data: [],
61
+ total: 0,
62
+ totalPages: 0,
63
+ };
64
+ return false;
65
+ }
66
+ where[field] = { in: unique(includeIds) };
67
+ }
68
+ const excludeIds = await resolveRelationshipIds(payload, collection, excludeValues);
69
+ if (excludeIds.length > 0) {
70
+ where[field] = {
71
+ ...(where[field] ?? {}),
72
+ not_in: unique(excludeIds),
73
+ };
74
+ }
75
+ return true;
76
+ }
42
77
  export const batchEndpoints = [
43
78
  // POST /api/nitrogen/v1/batch-data — Batch fetch multiple collections
44
79
  {
@@ -76,10 +111,7 @@ export const batchEndpoints = [
76
111
  if (!statuses.includes("any")) {
77
112
  where._status = { in: statuses };
78
113
  }
79
- const slugs = [
80
- ...toArray(params.slug),
81
- ...toArray(params.slugs),
82
- ];
114
+ const slugs = [...toArray(params.slug), ...toArray(params.slugs)];
83
115
  if (slugs.length > 0) {
84
116
  where.slug = { in: Array.from(new Set(slugs)) };
85
117
  }
@@ -90,63 +122,117 @@ export const batchEndpoints = [
90
122
  if (titles.length > 0) {
91
123
  where.title = { in: Array.from(new Set(titles)) };
92
124
  }
93
- const categoryIds = await resolveRelationshipIds(payload, "post-category", toArray(params.categories));
94
- if (toArray(params.categories).length > 0) {
95
- if (categoryIds.length === 0) {
96
- results[key] = {
97
- data: [],
98
- total: 0,
99
- totalPages: 0,
100
- };
101
- return;
102
- }
103
- where.categories = { in: Array.from(new Set(categoryIds)) };
125
+ if (!(await applyRelationshipFilter({
126
+ payload,
127
+ results,
128
+ key,
129
+ where,
130
+ field: "categories",
131
+ collection: "post-category",
132
+ includeValues: toArray(params.categories),
133
+ excludeValues: toArray(params.categories_excluded),
134
+ }))) {
135
+ return;
104
136
  }
105
- const excludedCategoryIds = await resolveRelationshipIds(payload, "post-category", toArray(params.categories_excluded));
106
- if (excludedCategoryIds.length > 0) {
107
- where.categories = {
108
- ...(where.categories ?? {}),
109
- not_in: Array.from(new Set(excludedCategoryIds)),
110
- };
137
+ if (!(await applyRelationshipFilter({
138
+ payload,
139
+ results,
140
+ key,
141
+ where,
142
+ field: "tags",
143
+ collection: "tag",
144
+ includeValues: toArray(params.tags),
145
+ excludeValues: toArray(params.tags_excluded),
146
+ }))) {
147
+ return;
111
148
  }
112
- const tagIds = await resolveRelationshipIds(payload, "tag", toArray(params.tags));
113
- if (toArray(params.tags).length > 0) {
114
- if (tagIds.length === 0) {
115
- results[key] = {
116
- data: [],
117
- total: 0,
118
- totalPages: 0,
119
- };
120
- return;
121
- }
122
- where.tags = { in: Array.from(new Set(tagIds)) };
149
+ if (!(await applyRelationshipFilter({
150
+ payload,
151
+ results,
152
+ key,
153
+ where,
154
+ field: "industryTags",
155
+ collection: "industry-tag",
156
+ includeValues: [
157
+ ...toArray(params.industry_tags),
158
+ ...toArray(params.industryTags),
159
+ ],
160
+ excludeValues: toArray(params.industry_tags_excluded),
161
+ }))) {
162
+ return;
123
163
  }
124
- const excludedTagIds = await resolveRelationshipIds(payload, "tag", toArray(params.tags_excluded));
125
- if (excludedTagIds.length > 0) {
126
- where.tags = {
127
- ...(where.tags ?? {}),
128
- not_in: Array.from(new Set(excludedTagIds)),
129
- };
164
+ if (!(await applyRelationshipFilter({
165
+ payload,
166
+ results,
167
+ key,
168
+ where,
169
+ field: "productTags",
170
+ collection: "product-tag",
171
+ includeValues: [
172
+ ...toArray(params.product_tags),
173
+ ...toArray(params.productTags),
174
+ ],
175
+ excludeValues: toArray(params.product_tags_excluded),
176
+ }))) {
177
+ return;
130
178
  }
131
- const featuredIds = await resolveRelationshipIds(payload, "featured-tag", toArray(params.featured));
132
- if (toArray(params.featured).length > 0) {
133
- if (featuredIds.length === 0) {
134
- results[key] = {
135
- data: [],
136
- total: 0,
137
- totalPages: 0,
138
- };
139
- return;
140
- }
141
- where.featuredTags = { in: Array.from(new Set(featuredIds)) };
179
+ if (!(await applyRelationshipFilter({
180
+ payload,
181
+ results,
182
+ key,
183
+ where,
184
+ field: "languageTags",
185
+ collection: "language-tag",
186
+ includeValues: [
187
+ ...toArray(params.language_tags),
188
+ ...toArray(params.languageTags),
189
+ ],
190
+ excludeValues: toArray(params.language_tags_excluded),
191
+ }))) {
192
+ return;
142
193
  }
143
- const excludedFeaturedIds = await resolveRelationshipIds(payload, "featured-tag", toArray(params.featured_excluded));
144
- if (excludedFeaturedIds.length > 0) {
194
+ if (!(await applyRelationshipFilter({
195
+ payload,
196
+ results,
197
+ key,
198
+ where,
199
+ field: "featuredTags",
200
+ collection: "featured-tag",
201
+ includeValues: [
202
+ ...toArray(params.featured),
203
+ ...toArray(params.featured_tags),
204
+ ...toArray(params.featuredTags),
205
+ ],
206
+ excludeValues: [
207
+ ...toArray(params.featured_excluded),
208
+ ...toArray(params.featured_tags_excluded),
209
+ ],
210
+ }))) {
211
+ return;
212
+ }
213
+ if (isTruthyParam(params.featured_only)) {
214
+ const featuredIds = await resolveAllRelationshipIds(payload, "featured-tag");
145
215
  where.featuredTags = {
146
216
  ...(where.featuredTags ?? {}),
147
- not_in: Array.from(new Set(excludedFeaturedIds)),
217
+ in: unique(featuredIds),
148
218
  };
149
219
  }
220
+ if (isTruthyParam(params.exclude_featured)) {
221
+ const featuredIds = await resolveAllRelationshipIds(payload, "featured-tag");
222
+ where.featuredTags = {
223
+ ...(where.featuredTags ?? {}),
224
+ not_in: unique(featuredIds),
225
+ };
226
+ }
227
+ const search = String(params.q ?? params.search ?? "").trim();
228
+ if (search) {
229
+ where.or = [
230
+ ...(where.or ?? []),
231
+ { title: { contains: search } },
232
+ { "meta.description": { contains: search } },
233
+ { content: { contains: search } },
234
+ ];
235
+ }
150
236
  const authors = toArray(params.authors);
151
237
  if (authors.length > 0) {
152
238
  if (collectionSlug === "posts") {
package/dist/index.js CHANGED
@@ -120,7 +120,7 @@ export const nitrogenConnectorPlugin = (options = {}) => (incomingConfig) => {
120
120
  ...beforeControls,
121
121
  {
122
122
  path: "@nitrogenbuilder/connector-payload/components/NitrogenEditButton#NitrogenEditButton",
123
- clientProps: { collection: slug },
123
+ clientProps: { collection: slug, routePattern },
124
124
  },
125
125
  ],
126
126
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nitrogenbuilder/connector-payload",
3
- "version": "0.1.31",
3
+ "version": "0.1.33",
4
4
  "description": "Nitrogen page builder connector plugin for Payload CMS 3.x",
5
5
  "author": "Leonardo Dentzien <leo@torchmedia.ca>",
6
6
  "type": "module",