From 7db58b482bba7e715c5be23cfe1a84295e95da29 Mon Sep 17 00:00:00 2001 From: Dan Ribbens Date: Thu, 28 Dec 2023 12:56:30 -0500 Subject: [PATCH] fix: custom overrides of breadcrumb and parent fields --- docs/plugins/nested-docs.mdx | 87 +++++++++++++------ .../src/fields/breadcrumbs.ts | 68 +++++++-------- .../src/hooks/resaveChildren.ts | 4 +- packages/plugin-nested-docs/src/index.ts | 25 ++++-- packages/plugin-nested-docs/src/types.ts | 9 ++ .../collections/Categories.ts | 38 ++++++++ test/plugin-nested-docs/config.ts | 9 +- test/plugin-nested-docs/int.spec.ts | 31 +++++++ 8 files changed, 201 insertions(+), 70 deletions(-) create mode 100644 test/plugin-nested-docs/collections/Categories.ts diff --git a/docs/plugins/nested-docs.mdx b/docs/plugins/nested-docs.mdx index 4219262153..27d52fa77c 100644 --- a/docs/plugins/nested-docs.mdx +++ b/docs/plugins/nested-docs.mdx @@ -8,11 +8,21 @@ keywords: plugins, nested, documents, parent, child, sibling, relationship [![NPM](https://img.shields.io/npm/v/@payloadcms/plugin-nested-docs)](https://www.npmjs.com/package/@payloadcms/plugin-nested-docs) -This plugin allows you to easily nest the documents of your application inside of one another. It does so by adding a new `parent` field onto each of your documents that, when selected, attaches itself to the parent's tree. When you edit the great-great-grandparent of a document, for instance, all of its descendants are recursively updated. This is an extremely powerful way of achieving hierarchy within a collection, such as parent/child relationship between pages. +This plugin allows you to easily nest the documents of your application inside of one another. It does so by adding a +new `parent` field onto each of your documents that, when selected, attaches itself to the parent's tree. When you edit +the great-great-grandparent of a document, for instance, all of its descendants are recursively updated. This is an +extremely powerful way of achieving hierarchy within a collection, such as parent/child relationship between pages. -Documents also receive a new `breadcrumbs` field. Once a parent is assigned, these breadcrumbs are populated based on each ancestor up the tree. Breadcrumbs allow you to dynamically generate labels and URLs based on the document's position in the hierarchy. Even if the slug of a parent document changes, or the entire tree is nested another level deep, changes will cascade down the entire tree and all breadcrumbs will reflect those changes. +Documents also receive a new `breadcrumbs` field. Once a parent is assigned, these breadcrumbs are populated based on +each ancestor up the tree. Breadcrumbs allow you to dynamically generate labels and URLs based on the document's +position in the hierarchy. Even if the slug of a parent document changes, or the entire tree is nested another level +deep, changes will cascade down the entire tree and all breadcrumbs will reflect those changes. -With this pattern you can perform whatever side-effects your applications needs on even the most deeply nested documents. For example, you could easily add a custom `fullTitle` field onto each document and inject the parent's title onto it, such as "Parent Title > Child Title". This would allow you to then perform searches and filters based on _that_ field instead of the original title. This is especially useful if you happen to have two documents with identical titles but different parents. +With this pattern you can perform whatever side-effects your applications needs on even the most deeply nested +documents. For example, you could easily add a custom `fullTitle` field onto each document and inject the parent's title +onto it, such as "Parent Title > Child Title". This would allow you to then perform searches and filters based on _that_ +field instead of the original title. This is especially useful if you happen to have two documents with identical titles +but different parents. This plugin is completely open-source and the [source code can be found here](https://github.com/payloadcms/payload/tree/main/packages/plugin-nested-docs). If you need help, check out our [Community Help](https://payloadcms.com/community-help). If you think you've found a bug, please [open a new issue](https://github.com/payloadcms/payload/issues/new?assignees=&labels=plugin%3A%20nested-docs&template=bug_report.md&title=plugin-nested-docs%3A) with as much detail as possible. @@ -29,7 +39,8 @@ With this pattern you can perform whatever side-effects your applications needs ## Installation -Install the plugin using any JavaScript package manager like [Yarn](https://yarnpkg.com), [NPM](https://npmjs.com), or [PNPM](https://pnpm.io): +Install the plugin using any JavaScript package manager like [Yarn](https://yarnpkg.com), [NPM](https://npmjs.com), +or [PNPM](https://pnpm.io): ```bash yarn add @payloadcms/plugin-nested-docs @@ -37,7 +48,8 @@ Install the plugin using any JavaScript package manager like [Yarn](https://yarn ## Basic Usage -In the `plugins` array of your [Payload config](https://payloadcms.com/docs/configuration/overview), call the plugin with [options](#options): +In the `plugins` array of your [Payload config](https://payloadcms.com/docs/configuration/overview), call the plugin +with [options](#options): ```ts import { buildConfig } from 'payload/config' @@ -75,16 +87,18 @@ export default config #### Parent -The `parent` relationship field is automatically added to every document which allows editors to choose another document from the same collection to act as the direct parent. +The `parent` relationship field is automatically added to every document which allows editors to choose another document +from the same collection to act as the direct parent. #### Breadcrumbs -The `breadcrumbs` field is an array which dynamically populates all parent relationships of a document up to the top level and stores the following fields. +The `breadcrumbs` field is an array which dynamically populates all parent relationships of a document up to the top +level and stores the following fields. -| Field | Description | -| ------------ | --------------------------------------------------------------------------- | -| `label` | The label of the breadcrumb. This field is automatically set to either the `collection.admin.useAsTitle` (if defined) or is set to the `ID` of the document. You can also dynamically define the `label` by passing a function to the options property of [`generateLabel`](#generateLabel). | -| `url` | The URL of the breadcrumb. By default, this field is undefined. You can manually define this field by passing a property called function to the plugin options property of [`generateURL`](#generateURL). | +| Field | Description | +|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `label` | The label of the breadcrumb. This field is automatically set to either the `collection.admin.useAsTitle` (if defined) or is set to the `ID` of the document. You can also dynamically define the `label` by passing a function to the options property of [`generateLabel`](#generateLabel). | +| `url` | The URL of the breadcrumb. By default, this field is undefined. You can manually define this field by passing a property called function to the plugin options property of [`generateURL`](#generateURL). | ### Options @@ -94,7 +108,8 @@ An array of collections slugs to enable nested docs. #### `generateLabel` -Each `breadcrumb` has a required `label` field. By default, its value will be set to the collection's `admin.useAsTitle` or fallback the the `ID` of the document. +Each `breadcrumb` has a required `label` field. By default, its value will be set to the collection's `admin.useAsTitle` +or fallback the the `ID` of the document. You can also pass a function to dynamically set the `label` of your breadcrumb. @@ -108,14 +123,16 @@ nestedDocs({ The function takes two arguments and returns a string: -| Argument | Type | Description | -| ------------ | -------- | --------------------------------------------------------------------------- | -| `docs` | `Array` | An array of the breadcrumbs up to that point | -| `doc` | `Object` | The current document being edited | +| Argument | Type | Description | +|----------|----------|----------------------------------------------| +| `docs` | `Array` | An array of the breadcrumbs up to that point | +| `doc` | `Object` | The current document being edited | #### `generateURL` -A function that allows you to dynamically generate each breadcrumb `url`. Each `breadcrumb` has an optional `url` field which is undefined by default. For example, you might want to format a full URL to contain all of the breadcrumbs up to that point, like `/about-us/company/our-team`. +A function that allows you to dynamically generate each breadcrumb `url`. Each `breadcrumb` has an optional `url` field +which is undefined by default. For example, you might want to format a full URL to contain all breadcrumbs up to +that point, like `/about-us/company/our-team`. ```ts // payload.config.ts @@ -125,18 +142,21 @@ nestedDocs({ }) ``` -| Argument | Type | Description | -| ------------ | -------- | --------------------------------------------------------------------------- | -| `docs` | `Array` | An array of the breadcrumbs up to that point | -| `doc` | `Object` | The current document being edited | +| Argument | Type | Description | +|----------|----------|----------------------------------------------| +| `docs` | `Array` | An array of the breadcrumbs up to that point | +| `doc` | `Object` | The current document being edited | #### `parentFieldSlug` -When defined, the `parent` field will not be provided for you automatically, and instead, expects you to add your own `parent` field to each collection manually. This gives you complete control over where you put the field in your admin dashboard, etc. Set this property to the `name` of your custom field. +When defined, the `parent` field will not be provided for you automatically, and instead, expects you to add your +own `parent` field to each collection manually. This gives you complete control over where you put the field in your +admin dashboard, etc. Set this property to the `name` of your custom field. #### `breadcrumbsFieldSlug` -When defined, the `breadcrumbs` field will not be provided for you, and instead, expects your to add your own `breadcrumbs` field to each collection manually. Set this property to the `name` of your custom field. +When defined, the `breadcrumbs` field will not be provided for you, and instead, expects you to add your +own `breadcrumbs` field to each collection manually. Set this property to the `name` of your custom field. Note: @@ -146,7 +166,8 @@ When defined, the `breadcrumbs` field will not be provided for you, and instead, ## Overrides -You can also extend the built-in `parent` and `breadcrumbs` fields per collection by using the `createParentField` and `createBreadcrumbField` methods. They will merge your customizations overtop the plugin's base field configurations. +You can also extend the built-in `parent` and `breadcrumbs` fields per collection by using the `createParentField` +and `createBreadcrumbField` methods. They will merge your customizations overtop the plugin's base field configurations. ```ts import { CollectionConfig } from "payload/types"; @@ -187,9 +208,17 @@ const examplePageConfig: CollectionConfig = { }; ``` + + Note: +
+ If overriding the `name` of either `breadcrumbs` or `parent` fields, you must specify the `breadcrumbsFieldSlug` or `parentFieldSlug` respectively. +
+ ## Localization -This plugin supports localization by default. If the `localization` property is set in your Payload config, the `breadcrumbs` field is automatically localized. For more details on how localization works in Payload, see the [Localization](https://payloadcms.com/docs/localization/overview) docs. +This plugin supports localization by default. If the `localization` property is set in your Payload config, +the `breadcrumbs` field is automatically localized. For more details on how localization works in Payload, see +the [Localization](https://payloadcms.com/docs/localization/overview) docs. ## TypeScript @@ -201,4 +230,10 @@ import { PluginConfig, GenerateURL, GenerateLabel } from '@payloadcms/plugin-nes ## Examples -The [Examples Directory](https://github.com/payloadcms/payload/tree/main/examples) contains an official [Nested Docs Plugin Example](https://github.com/payloadcms/payload/tree/main/examples/nested-docs) which demonstrates exactly how to configure this plugin in Payload and implement it on your front-end. The [Templates Directory](https://github.com/payloadcms/payload/tree/main/templates) also contains an official [Website Template](https://github.com/payloadcms/payload/tree/main/templates/website) and [E-commerce Template](https://github.com/payloadcms/payload/tree/main/templates/ecommere), both of which use this plugin. +The [Examples Directory](https://github.com/payloadcms/payload/tree/main/examples) contains an +official [Nested Docs Plugin Example](https://github.com/payloadcms/payload/tree/main/examples/nested-docs) which +demonstrates exactly how to configure this plugin in Payload and implement it on your front-end. +The [Templates Directory](https://github.com/payloadcms/payload/tree/main/templates) also contains an +official [Website Template](https://github.com/payloadcms/payload/tree/main/templates/website) +and [E-commerce Template](https://github.com/payloadcms/payload/tree/main/templates/ecommere), both of which use this +plugin. diff --git a/packages/plugin-nested-docs/src/fields/breadcrumbs.ts b/packages/plugin-nested-docs/src/fields/breadcrumbs.ts index a79d5d4fe4..862e1a3393 100644 --- a/packages/plugin-nested-docs/src/fields/breadcrumbs.ts +++ b/packages/plugin-nested-docs/src/fields/breadcrumbs.ts @@ -5,45 +5,45 @@ export const createBreadcrumbsField = ( overrides: Partial = {}, ): Field => ({ name: 'breadcrumbs', - type: 'array', localized: true, - fields: [ - { - name: 'doc', - type: 'relationship', - relationTo, - maxDepth: 0, - admin: { - disabled: true, - }, - }, - { - type: 'row', - fields: [ - { - name: 'url', - label: 'URL', - type: 'text', - admin: { - width: '50%', - }, - }, - { - name: 'label', - type: 'text', - admin: { - width: '50%', - }, - }, - ], - }, - ...(overrides?.fields || []), - ], + type: 'array', + ...(overrides || {}), admin: { readOnly: true, ...(overrides?.admin || {}), }, - ...(overrides || {}), + fields: [ + { + name: 'doc', + admin: { + disabled: true, + }, + maxDepth: 0, + relationTo, + type: 'relationship', + }, + { + fields: [ + { + name: 'url', + admin: { + width: '50%', + }, + label: 'URL', + type: 'text', + }, + { + name: 'label', + admin: { + width: '50%', + }, + type: 'text', + }, + ], + type: 'row', + }, + ...(overrides?.fields || []), + ], }) export default createBreadcrumbsField diff --git a/packages/plugin-nested-docs/src/hooks/resaveChildren.ts b/packages/plugin-nested-docs/src/hooks/resaveChildren.ts index 618fac9cbe..58656ec3da 100644 --- a/packages/plugin-nested-docs/src/hooks/resaveChildren.ts +++ b/packages/plugin-nested-docs/src/hooks/resaveChildren.ts @@ -20,6 +20,8 @@ const resaveChildren = }, }) + const breadcrumbSlug = pluginConfig.breadcrumbsFieldSlug || 'breadcrumbs' + try { children.docs.forEach(async (child: any) => { const updateAsDraft = @@ -32,7 +34,7 @@ const resaveChildren = collection: collection.slug, data: { ...child, - breadcrumbs: await populateBreadcrumbs(req, pluginConfig, collection, child), + [breadcrumbSlug]: await populateBreadcrumbs(req, pluginConfig, collection, child), }, depth: 0, draft: updateAsDraft, diff --git a/packages/plugin-nested-docs/src/index.ts b/packages/plugin-nested-docs/src/index.ts index ee20d87c2e..772352fad2 100644 --- a/packages/plugin-nested-docs/src/index.ts +++ b/packages/plugin-nested-docs/src/index.ts @@ -16,30 +16,39 @@ const nestedDocs = if (pluginConfig.collections.indexOf(collection.slug) > -1) { const fields = [...(collection?.fields || [])] - if (!pluginConfig.parentFieldSlug) { + const existingBreadcrumbField = collection.fields.find( + (field) => + 'name' in field && field.name === (pluginConfig?.breadcrumbsFieldSlug || 'breadcrumbs'), + ) + + const existingParentField = collection.fields.find( + (field) => 'name' in field && field.name === (pluginConfig?.parentFieldSlug || 'parent'), + ) + + if (!existingParentField && !pluginConfig.parentFieldSlug) { fields.push(createParentField(collection.slug)) } - if (!pluginConfig.breadcrumbsFieldSlug) { + if (!existingBreadcrumbField && !pluginConfig.breadcrumbsFieldSlug) { fields.push(createBreadcrumbsField(collection.slug)) } return { ...collection, + fields, hooks: { ...(collection.hooks || {}), - beforeChange: [ - async ({ req, data, originalDoc }) => - populateBreadcrumbs(req, pluginConfig, collection, data, originalDoc), - ...(collection?.hooks?.beforeChange || []), - ], afterChange: [ resaveChildren(pluginConfig, collection), resaveSelfAfterCreate(collection), ...(collection?.hooks?.afterChange || []), ], + beforeChange: [ + async ({ data, originalDoc, req }) => + populateBreadcrumbs(req, pluginConfig, collection, data, originalDoc), + ...(collection?.hooks?.beforeChange || []), + ], }, - fields, } } diff --git a/packages/plugin-nested-docs/src/types.ts b/packages/plugin-nested-docs/src/types.ts index 0e52cc585a..f6d67d28e2 100644 --- a/packages/plugin-nested-docs/src/types.ts +++ b/packages/plugin-nested-docs/src/types.ts @@ -15,9 +15,18 @@ export type GenerateLabel = ( ) => string export interface PluginConfig { + /** + * Should be supplied if using an alternative field name for the 'breadcrumbs' field in collections + */ breadcrumbsFieldSlug?: string + /** + * The slugs of the collections this plugin should extend. If you need different configs for different collections, this plugin can be added to your config more than once having different collections. + */ collections: string[] generateLabel?: GenerateLabel generateURL?: GenerateURL + /** + * Should be supplied if using an alternative field name for the 'parent' field in collections + */ parentFieldSlug?: string } diff --git a/test/plugin-nested-docs/collections/Categories.ts b/test/plugin-nested-docs/collections/Categories.ts new file mode 100644 index 0000000000..519bc0c431 --- /dev/null +++ b/test/plugin-nested-docs/collections/Categories.ts @@ -0,0 +1,38 @@ +import type { CollectionConfig } from '../../../packages/payload/src/collections/config/types' + +import { createBreadcrumbsField } from '../../../packages/plugin-nested-docs/src/fields/breadcrumbs' +import createParentField from '../../../packages/plugin-nested-docs/src/fields/parent' + +export const Categories: CollectionConfig = { + access: { + read: () => true, + }, + admin: { + useAsTitle: 'name', + }, + fields: [ + { + name: 'name', + required: true, + type: 'text', + }, + createBreadcrumbsField('categories', { + name: 'categorization', + admin: { + description: 'custom', + }, + fields: [ + { + name: 'test', + type: 'text', + }, + ], + }), + createParentField('categories', { + admin: { + description: 'custom', + }, + }), + ], + slug: 'categories', +} diff --git a/test/plugin-nested-docs/config.ts b/test/plugin-nested-docs/config.ts index baf709fc50..4fd41b4f29 100644 --- a/test/plugin-nested-docs/config.ts +++ b/test/plugin-nested-docs/config.ts @@ -1,12 +1,13 @@ import nestedDocs from '../../packages/plugin-nested-docs/src' import { buildConfigWithDefaults } from '../buildConfigWithDefaults' import { devUser } from '../credentials' +import { Categories } from './collections/Categories' import { Pages } from './collections/Pages' import { Users } from './collections/Users' import { seed } from './seed' export default buildConfigWithDefaults({ - collections: [Pages, Users], + collections: [Pages, Categories, Users], localization: { defaultLocale: 'en', fallback: true, @@ -29,5 +30,11 @@ export default buildConfigWithDefaults({ generateLabel: (_, doc) => doc.title as string, generateURL: (docs) => docs.reduce((url, doc) => `${url}/${doc.slug}`, ''), }), + nestedDocs({ + breadcrumbsFieldSlug: 'categorization', + collections: ['categories'], + generateLabel: (_, doc) => doc.name as string, + generateURL: (docs) => docs.reduce((url, doc) => `${url}/${doc.name}`, ''), + }), ], }) diff --git a/test/plugin-nested-docs/int.spec.ts b/test/plugin-nested-docs/int.spec.ts index ad40e00f1d..d574784e4b 100644 --- a/test/plugin-nested-docs/int.spec.ts +++ b/test/plugin-nested-docs/int.spec.ts @@ -1,3 +1,5 @@ +import type { ArrayField, RelationshipField } from '../../packages/payload/src/fields/config/types' + import payload from '../../packages/payload/src' import { initPayloadTest } from '../helpers/configHelpers' @@ -38,4 +40,33 @@ describe('Nested Docs', () => { ) }) }) + + describe('overrides', () => { + let collection + beforeAll(() => { + collection = payload.config.collections.find(({ slug }) => slug === 'categories') + }) + + it('should allow overriding breadcrumbs field', () => { + const breadcrumbField = collection.fields.find( + (field) => field.type === 'array' && field.name === 'categorization', + ) as ArrayField + const customField = breadcrumbField.fields.find( + (field) => field.type === 'text' && field.name === 'test', + ) as ArrayField + + expect(breadcrumbField.admin.description).toStrictEqual('custom') + expect(customField).toBeDefined() + expect(breadcrumbField.admin.readOnly).toStrictEqual(true) + expect(breadcrumbField.admin.readOnly).toStrictEqual(true) + }) + + it('should allow overriding parent field', () => { + const parentField = collection.fields.find( + (field) => field.type === 'relationship' && field.name === 'parent', + ) as RelationshipField + + expect(parentField.admin.description).toStrictEqual('custom') + }) + }) })