@foundrykit/menu-plugin 0.1.0 → 0.2.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 (44) hide show
  1. package/README.md +65 -109
  2. package/dist/cache.d.ts +4 -3
  3. package/dist/cache.js +13 -15
  4. package/dist/cache.js.map +1 -1
  5. package/dist/collections/Menus.d.ts +3 -1
  6. package/dist/collections/Menus.js +53 -24
  7. package/dist/collections/Menus.js.map +1 -1
  8. package/dist/endpoints/exportMenusHandler.d.ts +5 -0
  9. package/dist/endpoints/exportMenusHandler.js +20 -13
  10. package/dist/endpoints/exportMenusHandler.js.map +1 -1
  11. package/dist/endpoints/getMenuHandler.d.ts +6 -0
  12. package/dist/endpoints/getMenuHandler.js +45 -42
  13. package/dist/endpoints/getMenuHandler.js.map +1 -1
  14. package/dist/endpoints/importMenusHandler.d.ts +5 -0
  15. package/dist/endpoints/importMenusHandler.js +84 -48
  16. package/dist/endpoints/importMenusHandler.js.map +1 -1
  17. package/dist/exports/client.d.ts +1 -0
  18. package/dist/exports/client.js +1 -0
  19. package/dist/exports/client.js.map +1 -1
  20. package/dist/exports/rsc.d.ts +1 -1
  21. package/dist/exports/rsc.js +1 -1
  22. package/dist/exports/rsc.js.map +1 -1
  23. package/dist/fetchMenu.d.ts +17 -0
  24. package/dist/fetchMenu.js +24 -0
  25. package/dist/fetchMenu.js.map +1 -0
  26. package/dist/fields/MenuItem.d.ts +1 -0
  27. package/dist/fields/MenuItem.js +8 -9
  28. package/dist/fields/MenuItem.js.map +1 -1
  29. package/dist/hooks/useMenu.d.ts +5 -6
  30. package/dist/hooks/useMenu.js +36 -19
  31. package/dist/hooks/useMenu.js.map +1 -1
  32. package/dist/index.d.ts +3 -0
  33. package/dist/index.js +41 -29
  34. package/dist/index.js.map +1 -1
  35. package/dist/utilities/menuIdentity.d.ts +2 -0
  36. package/dist/utilities/menuIdentity.js +9 -0
  37. package/dist/utilities/menuIdentity.js.map +1 -0
  38. package/dist/utilities/requireAdminUser.d.ts +2 -0
  39. package/dist/utilities/requireAdminUser.js +20 -0
  40. package/dist/utilities/requireAdminUser.js.map +1 -0
  41. package/dist/utilities/sanitizeMenuDocument.d.ts +1 -0
  42. package/dist/utilities/sanitizeMenuDocument.js +6 -0
  43. package/dist/utilities/sanitizeMenuDocument.js.map +1 -0
  44. package/package.json +13 -32
package/README.md CHANGED
@@ -1,40 +1,32 @@
1
1
  # @foundrykit/menu-plugin
2
2
 
3
- A [Payload CMS](https://payloadcms.com) v3 plugin that adds a flexible, configurable menu management system to your admin panel. Build navigation menus with support for internal links, external URLs, document references, dropdowns, phone numbers, email links, and more.
3
+ A [Payload CMS](https://payloadcms.com) v3 plugin that adds a configurable menu management system to the admin panel. It lets you model nested navigation, fetch menus by slug, and consume them from regular frontend code without depending on Payload admin UI context.
4
4
 
5
5
  ## Features
6
6
 
7
- - Multiple link types: internal, external, reference, anchor, mailto, tel, custom
8
- - Nested dropdown menus with configurable max depth
9
- - Smart URL input that adapts its UI per link type (baseUrl prefix, country code selector, etc.)
10
- - REST API endpoint to fetch menus by slug
11
- - Built-in server-side caching with automatic invalidation
12
- - `useMenu` React hook for client-side fetching
13
- - Menu export/import endpoints for migration between environments
7
+ - Multiple item types: internal, external, reference, anchor, mailto, tel, custom
8
+ - Nested dropdown menus with configurable depth
9
+ - Admin URL field UI for internal paths, phone numbers, anchors, and email links
10
+ - Public `GET /api/menus/:slug` endpoint with locale and depth support
11
+ - Optional import/export endpoints with admin-only access by default
12
+ - Server-side menu caching with automatic invalidation
13
+ - Frontend-safe `fetchMenu` helper plus a `useMenu` hook built on top of it
14
14
  - Per-item visibility, target, rel, roles, and custom attributes
15
- - Sidebar preview of the menu tree structure
16
- - Field-level validation per link type
15
+ - Localized menu identity using `slug + locale`
17
16
 
18
17
  ## Installation
19
18
 
20
19
  ```bash
21
20
  pnpm add @foundrykit/menu-plugin
22
- # or
23
- npm install @foundrykit/menu-plugin
24
- # or
25
- yarn add @foundrykit/menu-plugin
26
21
  ```
27
22
 
28
23
  ## Quick Start
29
24
 
30
- Add the plugin to your Payload config:
31
-
32
25
  ```ts
33
26
  import { buildConfig } from 'payload'
34
27
  import { menuPlugin } from '@foundrykit/menu-plugin'
35
28
 
36
29
  export default buildConfig({
37
- // ...your config
38
30
  plugins: [
39
31
  menuPlugin({
40
32
  baseUrl: 'https://example.com',
@@ -44,91 +36,79 @@ export default buildConfig({
44
36
  })
45
37
  ```
46
38
 
47
- This adds a `menus` collection to your admin panel where you can create and manage navigation menus.
39
+ This registers a `menus` collection in Payload.
48
40
 
49
41
  ## Configuration
50
42
 
51
43
  | Option | Type | Default | Description |
52
44
  |---|---|---|---|
53
- | `baseUrl` | `string` | `''` | Base URL shown as a prefix for internal links |
54
- | `relationTo` | `string \| string[]` | `'pages'` | Collection(s) available for reference-type links |
55
- | `maxDepth` | `number` | `2` | Maximum nesting depth for dropdown menus |
56
- | `disabled` | `boolean` | `false` | Disable the plugin's endpoints and runtime behaviour while keeping the collection in the database schema |
45
+ | `baseUrl` | `string` | `''` | Base URL prefix shown for internal links in the admin |
46
+ | `cacheTTL` | `number` | `60000` | Server cache TTL in milliseconds |
47
+ | `disabled` | `boolean` | `false` | Keep the collection schema, but disable plugin runtime endpoints, hooks, and admin helper UI |
48
+ | `enableImportExport` | `boolean` | `true` | Register the import/export endpoints |
49
+ | `maxDepth` | `number` | `2` | Maximum nesting depth for dropdown items |
50
+ | `relationTo` | `string \| string[]` | `'pages'` | Collection(s) available for reference links |
51
+ | `requireAdminForImportExport` | `boolean` | `true` | Require an authenticated admin user for import/export endpoints |
57
52
 
58
- ### Example
53
+ Example:
59
54
 
60
55
  ```ts
61
56
  menuPlugin({
62
57
  baseUrl: 'https://mysite.com',
63
- relationTo: ['pages', 'posts', 'products'],
58
+ cacheTTL: 300_000,
64
59
  maxDepth: 3,
60
+ relationTo: ['pages', 'posts', 'products'],
65
61
  })
66
62
  ```
67
63
 
68
- ## Menu Item Types
69
-
70
- Each menu item has a `type` that determines the URL input behaviour:
71
-
72
- | Type | Description | Stored value |
73
- |---|---|---|
74
- | `reference` | Relationship to a Payload document | Relationship field (no URL) |
75
- | `internal` | Internal path with baseUrl prefix | Full URL (e.g. `https://example.com/about`) |
76
- | `external` | External URL | Full URL (e.g. `https://other-site.com`) |
77
- | `anchor` | Anchor link on the current page | `#section-name` |
78
- | `mailto` | Email link | `mailto:user@example.com` |
79
- | `tel` | Phone link with country code selector | `tel:+441234567890` |
80
- | `custom` | Plain text, any value | As entered |
64
+ ## Menu Identity and Locales
81
65
 
82
- ## Dropdown Menus
66
+ Menus are uniquely identified by `slug + locale`.
83
67
 
84
- Menu items can be either a **link** or a **dropdown**. Dropdowns contain a nested array of child items, which can themselves be links or dropdowns (up to `maxDepth` levels).
85
-
86
- ## Advanced Options
87
-
88
- Each menu item has an "Advanced" toggle that reveals additional fields:
89
-
90
- - **Target** — Open in same tab (`_self`) or new tab (`_blank`)
91
- - **Visibility** — Show or hide the item
92
- - **Rel** — Custom `rel` attribute (e.g. `noopener noreferrer`)
93
- - **Roles** — Array of role strings for role-based visibility
94
- - **Attrs** — Custom HTML attributes as text
68
+ - `slug: "main-menu", locale: "en"` and `slug: "main-menu", locale: "fr"` can coexist
69
+ - locale values are normalized to lowercase
70
+ - a menu with no locale is treated as a separate default variant
95
71
 
96
72
  ## REST API
97
73
 
98
74
  ### Get a menu by slug
99
75
 
100
- ```
76
+ ```http
101
77
  GET /api/menus/:slug
102
78
  ```
103
79
 
104
80
  Query parameters:
105
- - `locale` — Filter by locale field
106
- - `depth` — Payload relationship depth (default: `0`)
107
81
 
108
- Response: The full menu document as JSON.
82
+ - `locale`: optional locale variant
83
+ - `depth`: Payload relationship depth, default `0`
84
+
85
+ Example:
109
86
 
110
87
  ```bash
111
- curl https://example.com/api/menus/main-menu?depth=1&locale=en
88
+ curl 'https://example.com/api/menus/main-menu?locale=en&depth=1'
112
89
  ```
113
90
 
114
- ### Export all menus
91
+ ### Export menus
115
92
 
116
- ```
93
+ ```http
117
94
  GET /api/menus-export
118
95
  ```
119
96
 
120
- Returns all menus as a JSON file download.
97
+ By default this requires an authenticated admin user.
121
98
 
122
99
  ### Import menus
123
100
 
124
- ```
101
+ ```http
125
102
  POST /api/menus-import
126
103
  Content-Type: application/json
127
104
  ```
128
105
 
129
- Accepts a JSON array of menu documents (or `{ menus: [...] }`). Upserts by slug — existing menus are updated, new ones are created.
106
+ Accepts either a JSON array of menu documents or `{ "menus": [...] }`.
107
+
108
+ Imports upsert by `slug + locale`.
109
+
110
+ Example response:
130
111
 
131
- Response:
132
112
  ```json
133
113
  {
134
114
  "created": 1,
@@ -137,11 +117,24 @@ Response:
137
117
  }
138
118
  ```
139
119
 
140
- ## Client-Side Usage
120
+ ## Frontend Usage
121
+
122
+ ### `fetchMenu`
123
+
124
+ Use `fetchMenu` anywhere you have a fetch implementation, including server components and non-Payload frontend code.
125
+
126
+ ```ts
127
+ import { fetchMenu } from '@foundrykit/menu-plugin/rsc'
141
128
 
142
- ### `useMenu` Hook
129
+ const menu = await fetchMenu({
130
+ slug: 'main-menu',
131
+ locale: 'en',
132
+ depth: 1,
133
+ baseURL: 'https://example.com',
134
+ })
135
+ ```
143
136
 
144
- A React hook for fetching menus on the client:
137
+ ### `useMenu`
145
138
 
146
139
  ```tsx
147
140
  'use client'
@@ -149,66 +142,29 @@ A React hook for fetching menus on the client:
149
142
  import { useMenu } from '@foundrykit/menu-plugin/client'
150
143
 
151
144
  export function Navigation() {
152
- const { menu, isLoading, error, refetch } = useMenu({
145
+ const { error, isLoading, menu } = useMenu({
153
146
  slug: 'main-menu',
154
147
  locale: 'en',
155
148
  depth: 1,
149
+ baseURL: 'https://example.com',
156
150
  })
157
151
 
158
152
  if (isLoading) return <div>Loading...</div>
159
- if (error) return <div>Error: {error}</div>
153
+ if (error) return <div>{error}</div>
160
154
  if (!menu) return null
161
155
 
162
- return (
163
- <nav>
164
- {menu.items?.map((item: any) => (
165
- <a key={item.id} href={item.url} target={item.target}>
166
- {item.label}
167
- </a>
168
- ))}
169
- </nav>
170
- )
156
+ return <pre>{JSON.stringify(menu, null, 2)}</pre>
171
157
  }
172
158
  ```
173
159
 
174
- The hook includes a 30-second client-side cache and supports abort on unmount.
175
-
176
- ### Options
177
-
178
- | Option | Type | Required | Description |
179
- |---|---|---|---|
180
- | `slug` | `string` | Yes | The menu slug to fetch |
181
- | `locale` | `string` | No | Locale filter |
182
- | `depth` | `number` | No | Relationship population depth (default: `0`) |
183
-
184
- ### Return Value
185
-
186
- | Property | Type | Description |
187
- |---|---|---|
188
- | `menu` | `object \| null` | The fetched menu document |
189
- | `isLoading` | `boolean` | Whether the request is in progress |
190
- | `error` | `string \| null` | Error message if the request failed |
191
- | `refetch` | `() => Promise<void>` | Manually re-fetch the menu |
192
-
193
- ## Server-Side Usage
194
-
195
- You can also query menus using the Payload Local API:
196
-
197
- ```ts
198
- const menu = await payload.find({
199
- collection: 'menus',
200
- where: { slug: { equals: 'main-menu' } },
201
- depth: 1,
202
- })
203
- ```
160
+ `useMenu` includes a 30 second client-side cache and aborts in-flight requests on unmount.
204
161
 
205
162
  ## Caching
206
163
 
207
- The plugin includes automatic server-side caching:
208
-
209
- - Menus are cached after the first API request
210
- - Cache is automatically invalidated when a menu is created, updated, or deleted
211
- - Default TTL is 5 minutes
164
+ - Menus are cached after the first GET request
165
+ - cache keys include `slug`, `locale`, and `depth`
166
+ - cache entries are invalidated on create, update, and delete
167
+ - default server TTL is 60 seconds and is configurable via `cacheTTL`
212
168
 
213
169
  ## Requirements
214
170
 
package/dist/cache.d.ts CHANGED
@@ -2,10 +2,11 @@ export declare class MenuCache {
2
2
  private cache;
3
3
  private ttl;
4
4
  constructor(ttlMs?: number);
5
+ configure(ttlMs: number): void;
5
6
  private buildKey;
6
7
  clear(): void;
7
- get(slug: string, locale?: string): any | undefined;
8
- invalidate(slug: string, locale?: string): void;
9
- set(slug: string, data: any, locale?: string): void;
8
+ get(slug: string, depth?: number, locale?: string): any | undefined;
9
+ invalidate(slug: string): void;
10
+ set(slug: string, data: any, depth?: number, locale?: string): void;
10
11
  }
11
12
  export declare const menuCache: MenuCache;
package/dist/cache.js CHANGED
@@ -4,14 +4,17 @@ export class MenuCache {
4
4
  constructor(ttlMs = 60_000){
5
5
  this.ttl = ttlMs;
6
6
  }
7
- buildKey(slug, locale) {
8
- return locale ? `${slug}:${locale}` : slug;
7
+ configure(ttlMs) {
8
+ this.ttl = ttlMs;
9
+ }
10
+ buildKey(slug, depth = 0, locale) {
11
+ return `${slug}::${locale || '__default'}::${depth}`;
9
12
  }
10
13
  clear() {
11
14
  this.cache.clear();
12
15
  }
13
- get(slug, locale) {
14
- const key = this.buildKey(slug, locale);
16
+ get(slug, depth = 0, locale) {
17
+ const key = this.buildKey(slug, depth, locale);
15
18
  const entry = this.cache.get(key);
16
19
  if (!entry) return undefined;
17
20
  if (Date.now() > entry.expiresAt) {
@@ -20,20 +23,15 @@ export class MenuCache {
20
23
  }
21
24
  return entry.data;
22
25
  }
23
- invalidate(slug, locale) {
24
- if (locale) {
25
- this.cache.delete(this.buildKey(slug, locale));
26
- } else {
27
- // Invalidate all locales for this slug
28
- for (const key of this.cache.keys()){
29
- if (key === slug || key.startsWith(`${slug}:`)) {
30
- this.cache.delete(key);
31
- }
26
+ invalidate(slug) {
27
+ for (const key of this.cache.keys()){
28
+ if (key.startsWith(`${slug}::`)) {
29
+ this.cache.delete(key);
32
30
  }
33
31
  }
34
32
  }
35
- set(slug, data, locale) {
36
- const key = this.buildKey(slug, locale);
33
+ set(slug, data, depth = 0, locale) {
34
+ const key = this.buildKey(slug, depth, locale);
37
35
  this.cache.set(key, {
38
36
  data,
39
37
  expiresAt: Date.now() + this.ttl
package/dist/cache.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cache.ts"],"sourcesContent":["type CacheEntry = {\n data: any\n expiresAt: number\n}\n\nexport class MenuCache {\n private cache = new Map<string, CacheEntry>()\n private ttl: number\n\n constructor(ttlMs = 60_000) {\n this.ttl = ttlMs\n }\n\n private buildKey(slug: string, locale?: string): string {\n return locale ? `${slug}:${locale}` : slug\n }\n\n clear(): void {\n this.cache.clear()\n }\n\n get(slug: string, locale?: string): any | undefined {\n const key = this.buildKey(slug, locale)\n const entry = this.cache.get(key)\n if (!entry) return undefined\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key)\n return undefined\n }\n return entry.data\n }\n\n invalidate(slug: string, locale?: string): void {\n if (locale) {\n this.cache.delete(this.buildKey(slug, locale))\n } else {\n // Invalidate all locales for this slug\n for (const key of this.cache.keys()) {\n if (key === slug || key.startsWith(`${slug}:`)) {\n this.cache.delete(key)\n }\n }\n }\n }\n\n set(slug: string, data: any, locale?: string): void {\n const key = this.buildKey(slug, locale)\n this.cache.set(key, {\n data,\n expiresAt: Date.now() + this.ttl,\n })\n }\n}\n\nexport const menuCache = new MenuCache()\n"],"names":["MenuCache","cache","Map","ttl","ttlMs","buildKey","slug","locale","clear","get","key","entry","undefined","Date","now","expiresAt","delete","data","invalidate","keys","startsWith","set","menuCache"],"mappings":"AAKA,OAAO,MAAMA;IACHC,QAAQ,IAAIC,MAAyB;IACrCC,IAAW;IAEnB,YAAYC,QAAQ,MAAM,CAAE;QAC1B,IAAI,CAACD,GAAG,GAAGC;IACb;IAEQC,SAASC,IAAY,EAAEC,MAAe,EAAU;QACtD,OAAOA,SAAS,GAAGD,KAAK,CAAC,EAAEC,QAAQ,GAAGD;IACxC;IAEAE,QAAc;QACZ,IAAI,CAACP,KAAK,CAACO,KAAK;IAClB;IAEAC,IAAIH,IAAY,EAAEC,MAAe,EAAmB;QAClD,MAAMG,MAAM,IAAI,CAACL,QAAQ,CAACC,MAAMC;QAChC,MAAMI,QAAQ,IAAI,CAACV,KAAK,CAACQ,GAAG,CAACC;QAC7B,IAAI,CAACC,OAAO,OAAOC;QACnB,IAAIC,KAAKC,GAAG,KAAKH,MAAMI,SAAS,EAAE;YAChC,IAAI,CAACd,KAAK,CAACe,MAAM,CAACN;YAClB,OAAOE;QACT;QACA,OAAOD,MAAMM,IAAI;IACnB;IAEAC,WAAWZ,IAAY,EAAEC,MAAe,EAAQ;QAC9C,IAAIA,QAAQ;YACV,IAAI,CAACN,KAAK,CAACe,MAAM,CAAC,IAAI,CAACX,QAAQ,CAACC,MAAMC;QACxC,OAAO;YACL,uCAAuC;YACvC,KAAK,MAAMG,OAAO,IAAI,CAACT,KAAK,CAACkB,IAAI,GAAI;gBACnC,IAAIT,QAAQJ,QAAQI,IAAIU,UAAU,CAAC,GAAGd,KAAK,CAAC,CAAC,GAAG;oBAC9C,IAAI,CAACL,KAAK,CAACe,MAAM,CAACN;gBACpB;YACF;QACF;IACF;IAEAW,IAAIf,IAAY,EAAEW,IAAS,EAAEV,MAAe,EAAQ;QAClD,MAAMG,MAAM,IAAI,CAACL,QAAQ,CAACC,MAAMC;QAChC,IAAI,CAACN,KAAK,CAACoB,GAAG,CAACX,KAAK;YAClBO;YACAF,WAAWF,KAAKC,GAAG,KAAK,IAAI,CAACX,GAAG;QAClC;IACF;AACF;AAEA,OAAO,MAAMmB,YAAY,IAAItB,YAAW"}
1
+ {"version":3,"sources":["../src/cache.ts"],"sourcesContent":["type CacheEntry = {\n data: any\n expiresAt: number\n}\n\nexport class MenuCache {\n private cache = new Map<string, CacheEntry>()\n private ttl: number\n\n constructor(ttlMs = 60_000) {\n this.ttl = ttlMs\n }\n\n configure(ttlMs: number): void {\n this.ttl = ttlMs\n }\n\n private buildKey(slug: string, depth = 0, locale?: string): string {\n return `${slug}::${locale || '__default'}::${depth}`\n }\n\n clear(): void {\n this.cache.clear()\n }\n\n get(slug: string, depth = 0, locale?: string): any | undefined {\n const key = this.buildKey(slug, depth, locale)\n const entry = this.cache.get(key)\n if (!entry) return undefined\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key)\n return undefined\n }\n return entry.data\n }\n\n invalidate(slug: string): void {\n for (const key of this.cache.keys()) {\n if (key.startsWith(`${slug}::`)) {\n this.cache.delete(key)\n }\n }\n }\n\n set(slug: string, data: any, depth = 0, locale?: string): void {\n const key = this.buildKey(slug, depth, locale)\n this.cache.set(key, {\n data,\n expiresAt: Date.now() + this.ttl,\n })\n }\n}\n\nexport const menuCache = new MenuCache()\n"],"names":["MenuCache","cache","Map","ttl","ttlMs","configure","buildKey","slug","depth","locale","clear","get","key","entry","undefined","Date","now","expiresAt","delete","data","invalidate","keys","startsWith","set","menuCache"],"mappings":"AAKA,OAAO,MAAMA;IACHC,QAAQ,IAAIC,MAAyB;IACrCC,IAAW;IAEnB,YAAYC,QAAQ,MAAM,CAAE;QAC1B,IAAI,CAACD,GAAG,GAAGC;IACb;IAEAC,UAAUD,KAAa,EAAQ;QAC7B,IAAI,CAACD,GAAG,GAAGC;IACb;IAEQE,SAASC,IAAY,EAAEC,QAAQ,CAAC,EAAEC,MAAe,EAAU;QACjE,OAAO,GAAGF,KAAK,EAAE,EAAEE,UAAU,YAAY,EAAE,EAAED,OAAO;IACtD;IAEAE,QAAc;QACZ,IAAI,CAACT,KAAK,CAACS,KAAK;IAClB;IAEAC,IAAIJ,IAAY,EAAEC,QAAQ,CAAC,EAAEC,MAAe,EAAmB;QAC7D,MAAMG,MAAM,IAAI,CAACN,QAAQ,CAACC,MAAMC,OAAOC;QACvC,MAAMI,QAAQ,IAAI,CAACZ,KAAK,CAACU,GAAG,CAACC;QAC7B,IAAI,CAACC,OAAO,OAAOC;QACnB,IAAIC,KAAKC,GAAG,KAAKH,MAAMI,SAAS,EAAE;YAChC,IAAI,CAAChB,KAAK,CAACiB,MAAM,CAACN;YAClB,OAAOE;QACT;QACA,OAAOD,MAAMM,IAAI;IACnB;IAEAC,WAAWb,IAAY,EAAQ;QAC7B,KAAK,MAAMK,OAAO,IAAI,CAACX,KAAK,CAACoB,IAAI,GAAI;YACnC,IAAIT,IAAIU,UAAU,CAAC,GAAGf,KAAK,EAAE,CAAC,GAAG;gBAC/B,IAAI,CAACN,KAAK,CAACiB,MAAM,CAACN;YACpB;QACF;IACF;IAEAW,IAAIhB,IAAY,EAAEY,IAAS,EAAEX,QAAQ,CAAC,EAAEC,MAAe,EAAQ;QAC7D,MAAMG,MAAM,IAAI,CAACN,QAAQ,CAACC,MAAMC,OAAOC;QACvC,IAAI,CAACR,KAAK,CAACsB,GAAG,CAACX,KAAK;YAClBO;YACAF,WAAWF,KAAKC,GAAG,KAAK,IAAI,CAACb,GAAG;QAClC;IACF;AACF;AAEA,OAAO,MAAMqB,YAAY,IAAIxB,YAAW"}
@@ -1,4 +1,6 @@
1
1
  import type { CollectionConfig } from 'payload';
2
2
  import { type MenuItemFieldOptions } from '../fields/MenuItem.js';
3
- export type MenusCollectionOptions = MenuItemFieldOptions;
3
+ export type MenusCollectionOptions = MenuItemFieldOptions & {
4
+ disabled?: boolean;
5
+ };
4
6
  export declare const createMenusCollection: (options?: MenusCollectionOptions) => CollectionConfig;
@@ -1,5 +1,6 @@
1
1
  import { menuCache } from '../cache.js';
2
2
  import { createMenuItemFields } from '../fields/MenuItem.js';
3
+ import { buildMenuIdentityKey, normalizeMenuLocale } from '../utilities/menuIdentity.js';
3
4
  export const createMenusCollection = (options)=>({
4
5
  slug: 'menus',
5
6
  access: {
@@ -30,8 +31,7 @@ export const createMenusCollection = (options)=>({
30
31
  description: 'Unique identifier for the menu, used in API requests. E.g. "main-menu", "footer-menu", etc.'
31
32
  },
32
33
  index: true,
33
- required: true,
34
- unique: true
34
+ required: true
35
35
  },
36
36
  {
37
37
  name: 'description',
@@ -49,44 +49,73 @@ export const createMenusCollection = (options)=>({
49
49
  position: 'sidebar'
50
50
  }
51
51
  },
52
+ ...options?.disabled ? [] : [
53
+ {
54
+ name: 'menuPreview',
55
+ type: 'ui',
56
+ admin: {
57
+ components: {
58
+ Field: '@foundrykit/menu-plugin/client#MenuPreview'
59
+ },
60
+ position: 'sidebar'
61
+ }
62
+ }
63
+ ],
52
64
  {
53
- name: 'menuPreview',
54
- type: 'ui',
65
+ name: 'slugLocaleKey',
66
+ type: 'text',
55
67
  admin: {
56
- components: {
57
- Field: 'menu-plugin/client#MenuPreview'
58
- },
59
- position: 'sidebar'
60
- }
68
+ hidden: true
69
+ },
70
+ index: true,
71
+ unique: true
61
72
  },
62
73
  {
63
74
  name: 'items',
64
75
  type: 'array',
65
76
  admin: {
66
- components: {
67
- RowLabel: 'menu-plugin/client#MenuItemRowLabel'
77
+ ...options?.disabled ? {} : {
78
+ components: {
79
+ RowLabel: '@foundrykit/menu-plugin/client#MenuItemRowLabel'
80
+ }
68
81
  }
69
82
  },
70
83
  fields: createMenuItemFields(options)
71
84
  }
72
85
  ],
73
86
  hooks: {
74
- afterChange: [
75
- ({ doc })=>{
76
- if (doc.slug) {
77
- menuCache.invalidate(doc.slug, doc.locale);
78
- }
79
- return doc;
87
+ beforeValidate: [
88
+ ({ data })=>{
89
+ if (!data) return data;
90
+ const normalizedLocale = normalizeMenuLocale(data.locale);
91
+ return {
92
+ ...data,
93
+ locale: normalizedLocale,
94
+ slugLocaleKey: data.slug ? buildMenuIdentityKey(data.slug, normalizedLocale) : data.slugLocaleKey
95
+ };
80
96
  }
81
97
  ],
82
- afterDelete: [
83
- ({ doc })=>{
84
- if (doc.slug) {
85
- menuCache.invalidate(doc.slug, doc.locale);
98
+ ...options?.disabled ? {} : {
99
+ afterChange: [
100
+ ({ doc, previousDoc })=>{
101
+ if (previousDoc?.slug) {
102
+ menuCache.invalidate(previousDoc.slug);
103
+ }
104
+ if (doc.slug) {
105
+ menuCache.invalidate(doc.slug);
106
+ }
107
+ return doc;
86
108
  }
87
- return doc;
88
- }
89
- ]
109
+ ],
110
+ afterDelete: [
111
+ ({ doc })=>{
112
+ if (doc.slug) {
113
+ menuCache.invalidate(doc.slug);
114
+ }
115
+ return doc;
116
+ }
117
+ ]
118
+ }
90
119
  },
91
120
  labels: {
92
121
  plural: 'Menus',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/collections/Menus.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport { menuCache } from '../cache.js'\nimport { createMenuItemFields, type MenuItemFieldOptions } from '../fields/MenuItem.js'\n\nexport type MenusCollectionOptions = MenuItemFieldOptions\n\nexport const createMenusCollection = (options?: MenusCollectionOptions): CollectionConfig => ({\n slug: 'menus',\n access: {\n read: () => true,\n },\n admin: {\n defaultColumns: ['title', 'slug', 'locale', 'items'],\n useAsTitle: 'title',\n },\n fields: [\n {\n name: 'title',\n type: 'text',\n admin: {\n description: 'The name of the menu. E.g. \"Main Menu\", \"Footer Menu\", etc.',\n },\n required: true,\n },\n {\n name: 'slug',\n type: 'text',\n admin: {\n description:\n 'Unique identifier for the menu, used in API requests. E.g. \"main-menu\", \"footer-menu\", etc.',\n },\n index: true,\n required: true,\n unique: true,\n },\n {\n name: 'description',\n type: 'textarea',\n admin: {\n description: 'Optional description for the menu.',\n position: 'sidebar',\n },\n },\n {\n name: 'locale',\n type: 'text',\n admin: {\n description: 'Used for localisation. E.g. \"en\", \"fr\", etc.',\n position: 'sidebar',\n },\n },\n {\n name: 'menuPreview',\n type: 'ui',\n admin: {\n components: {\n Field: 'menu-plugin/client#MenuPreview',\n },\n position: 'sidebar',\n },\n },\n {\n name: 'items',\n type: 'array',\n admin: {\n components: {\n RowLabel: 'menu-plugin/client#MenuItemRowLabel',\n },\n },\n fields: createMenuItemFields(options),\n },\n ],\n hooks: {\n afterChange: [\n ({ doc }) => {\n if (doc.slug) {\n menuCache.invalidate(doc.slug, doc.locale)\n }\n return doc\n },\n ],\n afterDelete: [\n ({ doc }) => {\n if (doc.slug) {\n menuCache.invalidate(doc.slug, doc.locale)\n }\n return doc\n },\n ],\n },\n labels: {\n plural: 'Menus',\n singular: 'Menu',\n },\n timestamps: true,\n})\n"],"names":["menuCache","createMenuItemFields","createMenusCollection","options","slug","access","read","admin","defaultColumns","useAsTitle","fields","name","type","description","required","index","unique","position","components","Field","RowLabel","hooks","afterChange","doc","invalidate","locale","afterDelete","labels","plural","singular","timestamps"],"mappings":"AAEA,SAASA,SAAS,QAAQ,cAAa;AACvC,SAASC,oBAAoB,QAA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version":3,"sources":["../../src/collections/Menus.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport { menuCache } from '../cache.js'\nimport { createMenuItemFields, type MenuItemFieldOptions } from '../fields/MenuItem.js'\nimport { buildMenuIdentityKey, normalizeMenuLocale } from '../utilities/menuIdentity.js'\n\nexport type MenusCollectionOptions = MenuItemFieldOptions & {\n disabled?: boolean\n}\n\nexport const createMenusCollection = (options?: MenusCollectionOptions): CollectionConfig => ({\n slug: 'menus',\n access: {\n read: () => true,\n },\n admin: {\n defaultColumns: ['title', 'slug', 'locale', 'items'],\n useAsTitle: 'title',\n },\n fields: [\n {\n name: 'title',\n type: 'text',\n admin: {\n description: 'The name of the menu. E.g. \"Main Menu\", \"Footer Menu\", etc.',\n },\n required: true,\n },\n {\n name: 'slug',\n type: 'text',\n admin: {\n description:\n 'Unique identifier for the menu, used in API requests. E.g. \"main-menu\", \"footer-menu\", etc.',\n },\n index: true,\n required: true,\n },\n {\n name: 'description',\n type: 'textarea',\n admin: {\n description: 'Optional description for the menu.',\n position: 'sidebar',\n },\n },\n {\n name: 'locale',\n type: 'text',\n admin: {\n description: 'Used for localisation. E.g. \"en\", \"fr\", etc.',\n position: 'sidebar',\n },\n },\n ...(options?.disabled\n ? []\n : [\n {\n name: 'menuPreview',\n type: 'ui',\n admin: {\n components: {\n Field: '@foundrykit/menu-plugin/client#MenuPreview',\n },\n position: 'sidebar',\n },\n } as const,\n ]),\n {\n name: 'slugLocaleKey',\n type: 'text',\n admin: {\n hidden: true,\n },\n index: true,\n unique: true,\n },\n {\n name: 'items',\n type: 'array',\n admin: {\n ...(options?.disabled\n ? {}\n : {\n components: {\n RowLabel: '@foundrykit/menu-plugin/client#MenuItemRowLabel',\n },\n }),\n },\n fields: createMenuItemFields(options),\n },\n ],\n hooks: {\n beforeValidate: [\n ({ data }) => {\n if (!data) return data\n\n const normalizedLocale = normalizeMenuLocale(data.locale)\n\n return {\n ...data,\n locale: normalizedLocale,\n slugLocaleKey: data.slug ? buildMenuIdentityKey(data.slug, normalizedLocale) : data.slugLocaleKey,\n }\n },\n ],\n ...(options?.disabled\n ? {}\n : {\n afterChange: [\n ({ doc, previousDoc }) => {\n if (previousDoc?.slug) {\n menuCache.invalidate(previousDoc.slug)\n }\n if (doc.slug) {\n menuCache.invalidate(doc.slug)\n }\n return doc\n },\n ],\n afterDelete: [\n ({ doc }) => {\n if (doc.slug) {\n menuCache.invalidate(doc.slug)\n }\n return doc\n },\n ],\n }),\n },\n labels: {\n plural: 'Menus',\n singular: 'Menu',\n },\n timestamps: true,\n})\n"],"names":["menuCache","createMenuItemFields","buildMenuIdentityKey","normalizeMenuLocale","createMenusCollection","options","slug","access","read","admin","defaultColumns","useAsTitle","fields","name","type","description","required","index","position","disabled","components","Field","hidden","unique","RowLabel","hooks","beforeValidate","data","normalizedLocale","locale","slugLocaleKey","afterChange","doc","previousDoc","invalidate","afterDelete","labels","plural","singular","timestamps"],"mappings":"AAEA,SAASA,SAAS,QAAQ,cAAa;AACvC,SAASC,oBAAoB,QAAmC,wBAAuB;AACvF,SAASC,oBAAoB,EAAEC,mBAAmB,QAAQ,+BAA8B;AAMxF,OAAO,MAAMC,wBAAwB,CAACC,UAAwD,CAAA;QAC5FC,MAAM;QACNC,QAAQ;YACNC,MAAM,IAAM;QACd;QACAC,OAAO;YACLC,gBAAgB;gBAAC;gBAAS;gBAAQ;gBAAU;aAAQ;YACpDC,YAAY;QACd;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;gBACNL,OAAO;oBACLM,aAAa;gBACf;gBACAC,UAAU;YACZ;YACA;gBACEH,MAAM;gBACNC,MAAM;gBACNL,OAAO;oBACLM,aACE;gBACJ;gBACAE,OAAO;gBACPD,UAAU;YACZ;YACA;gBACEH,MAAM;gBACNC,MAAM;gBACNL,OAAO;oBACLM,aAAa;oBACbG,UAAU;gBACZ;YACF;YACA;gBACEL,MAAM;gBACNC,MAAM;gBACNL,OAAO;oBACLM,aAAa;oBACbG,UAAU;g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A,EAAE"}
@@ -1,2 +1,7 @@
1
1
  import type { PayloadHandler } from 'payload';
2
+ type ExportMenusHandlerOptions = {
3
+ requireAdmin?: boolean;
4
+ };
5
+ export declare const createExportMenusHandler: ({ requireAdmin }?: ExportMenusHandlerOptions) => PayloadHandler;
2
6
  export declare const exportMenusHandler: PayloadHandler;
7
+ export {};
@@ -1,16 +1,23 @@
1
- export const exportMenusHandler = async (req)=>{
2
- const { payload } = req;
3
- const result = await payload.find({
4
- collection: 'menus',
5
- limit: 0,
6
- pagination: false
7
- });
8
- return new Response(JSON.stringify(result.docs, null, 2), {
9
- headers: {
10
- 'Content-Disposition': 'attachment; filename="menus-export.json"',
11
- 'Content-Type': 'application/json'
1
+ import { requireAdminUser } from '../utilities/requireAdminUser.js';
2
+ import { sanitizeMenuDocument } from '../utilities/sanitizeMenuDocument.js';
3
+ export const createExportMenusHandler = ({ requireAdmin = true } = {})=>async (req)=>{
4
+ const { payload } = req;
5
+ if (requireAdmin) {
6
+ const authError = requireAdminUser(req);
7
+ if (authError) return authError;
12
8
  }
13
- });
14
- };
9
+ const result = await payload.find({
10
+ collection: 'menus',
11
+ limit: 0,
12
+ pagination: false
13
+ });
14
+ return new Response(JSON.stringify(result.docs.map((doc)=>sanitizeMenuDocument(doc)), null, 2), {
15
+ headers: {
16
+ 'Content-Disposition': 'attachment; filename="menus-export.json"',
17
+ 'Content-Type': 'application/json'
18
+ }
19
+ });
20
+ };
21
+ export const exportMenusHandler = createExportMenusHandler();
15
22
 
16
23
  //# sourceMappingURL=exportMenusHandler.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/exportMenusHandler.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\n\nexport const exportMenusHandler: PayloadHandler = async (req) => {\n const { payload } = req\n\n const result = await payload.find({\n collection: 'menus',\n limit: 0,\n pagination: false,\n })\n\n return new Response(JSON.stringify(result.docs, null, 2), {\n headers: {\n 'Content-Disposition': 'attachment; filename=\"menus-export.json\"',\n 'Content-Type': 'application/json',\n },\n })\n}\n"],"names":["exportMenusHandler","req","payload","result","find","collection","limit","pagination","Response","JSON","stringify","docs","headers"],"mappings":"AAEA,OAAO,MAAMA,qBAAqC,OAAOC;IACvD,MAAM,EAAEC,OAAO,EAAE,GAAGD;IAEpB,MAAME,SAAS,MAAMD,QAAQE,IAAI,CAAC;QAChCC,YAAY;QACZC,OAAO;QACPC,YAAY;IACd;IAEA,OAAO,IAAIC,SAASC,KAAKC,SAAS,CAACP,OAAOQ,IAAI,EAAE,MAAM,IAAI;QACxDC,SAAS;YACP,uBAAuB;YACvB,gBAAgB;QAClB;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/endpoints/exportMenusHandler.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\n\nimport { requireAdminUser } from '../utilities/requireAdminUser.js'\nimport { sanitizeMenuDocument } from '../utilities/sanitizeMenuDocument.js'\n\ntype ExportMenusHandlerOptions = {\n requireAdmin?: boolean\n}\n\nexport const createExportMenusHandler =\n ({ requireAdmin = true }: ExportMenusHandlerOptions = {}): PayloadHandler =>\n async (req) => {\n const { payload } = req\n\n if (requireAdmin) {\n const authError = requireAdminUser(req)\n if (authError) return authError\n }\n\n const result = await payload.find({\n collection: 'menus',\n limit: 0,\n pagination: false,\n })\n\n return new Response(\n JSON.stringify(result.docs.map((doc) => sanitizeMenuDocument(doc as Record<string, unknown>)), null, 2),\n {\n headers: {\n 'Content-Disposition': 'attachment; filename=\"menus-export.json\"',\n 'Content-Type': 'application/json',\n },\n },\n )\n }\n\nexport const exportMenusHandler = createExportMenusHandler()\n"],"names":["requireAdminUser","sanitizeMenuDocument","createExportMenusHandler","requireAdmin","req","payload","authError","result","find","collection","limit","pagination","Response","JSON","stringify","docs","map","doc","headers","exportMenusHandler"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,oBAAoB,QAAQ,uCAAsC;AAM3E,OAAO,MAAMC,2BACX,CAAC,EAAEC,eAAe,IAAI,EAA6B,GAAG,CAAC,CAAC,GACxD,OAAOC;QACL,MAAM,EAAEC,OAAO,EAAE,GAAGD;QAEpB,IAAID,cAAc;YAChB,MAAMG,YAAYN,iBAAiBI;YACnC,IAAIE,WAAW,OAAOA;QACxB;QAEA,MAAMC,SAAS,MAAMF,QAAQG,IAAI,CAAC;YAChCC,YAAY;YACZC,OAAO;YACPC,YAAY;QACd;QAEA,OAAO,IAAIC,SACTC,KAAKC,SAAS,CAACP,OAAOQ,IAAI,CAACC,GAAG,CAAC,CAACC,MAAQhB,qBAAqBgB,OAAkC,MAAM,IACrG;YACEC,SAAS;gBACP,uBAAuB;gBACvB,gBAAgB;YAClB;QACF;IAEJ,EAAC;AAEH,OAAO,MAAMC,qBAAqBjB,2BAA0B"}
@@ -1,2 +1,8 @@
1
1
  import type { PayloadHandler } from 'payload';
2
+ import { menuCache } from '../cache.js';
3
+ type GetMenuHandlerOptions = {
4
+ cache?: typeof menuCache;
5
+ };
6
+ export declare const createGetMenuHandler: ({ cache }?: GetMenuHandlerOptions) => PayloadHandler;
2
7
  export declare const getMenuHandler: PayloadHandler;
8
+ export {};