Skip to content

Commit

Permalink
fix: custom overrides of breadcrumb and parent fields
Browse files Browse the repository at this point in the history
  • Loading branch information
DanRibbens committed Dec 28, 2023
1 parent 657d14c commit 7db58b4
Show file tree
Hide file tree
Showing 8 changed files with 182 additions and 51 deletions.
91 changes: 63 additions & 28 deletions docs/plugins/nested-docs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

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.
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.

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.

<Banner type="info">
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.
Expand All @@ -29,15 +39,17 @@ 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
```

## 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'
Expand Down Expand Up @@ -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

Expand All @@ -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.

Expand All @@ -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
Expand All @@ -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.

<Banner type="info">
<strong>Note:</strong>
Expand All @@ -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";
Expand Down Expand Up @@ -187,9 +208,17 @@ const examplePageConfig: CollectionConfig = {
};
```

<Banner type="warning">
<strong>Note:</strong>
<br />
If overriding the `name` of either `breadcrumbs` or `parent` fields, you must specify the `breadcrumbsFieldSlug` or `parentFieldSlug` respectively.
</Banner>

## 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

Expand All @@ -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.
26 changes: 13 additions & 13 deletions packages/plugin-nested-docs/src/fields/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,45 +5,45 @@ export const createBreadcrumbsField = (
overrides: Partial<ArrayField> = {},
): Field => ({
name: 'breadcrumbs',
type: 'array',
localized: true,
type: 'array',
...(overrides || {}),
admin: {
readOnly: true,
...(overrides?.admin || {}),
},
fields: [
{
name: 'doc',
type: 'relationship',
relationTo,
maxDepth: 0,
admin: {
disabled: true,
},
maxDepth: 0,
relationTo,
type: 'relationship',
},
{
type: 'row',
fields: [
{
name: 'url',
label: 'URL',
type: 'text',
admin: {
width: '50%',
},
label: 'URL',
type: 'text',
},
{
name: 'label',
type: 'text',
admin: {
width: '50%',
},
type: 'text',
},
],
type: 'row',
},
...(overrides?.fields || []),
],
admin: {
readOnly: true,
...(overrides?.admin || {}),
},
...(overrides || {}),
})

export default createBreadcrumbsField
4 changes: 3 additions & 1 deletion packages/plugin-nested-docs/src/hooks/resaveChildren.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ const resaveChildren =
},
})

const breadcrumbSlug = pluginConfig.breadcrumbsFieldSlug || 'breadcrumbs'

try {
children.docs.forEach(async (child: any) => {
const updateAsDraft =
Expand All @@ -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,
Expand Down
25 changes: 17 additions & 8 deletions packages/plugin-nested-docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

Expand Down
9 changes: 9 additions & 0 deletions packages/plugin-nested-docs/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
38 changes: 38 additions & 0 deletions test/plugin-nested-docs/collections/Categories.ts
Original file line number Diff line number Diff line change
@@ -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',
}
9 changes: 8 additions & 1 deletion test/plugin-nested-docs/config.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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}`, ''),
}),
],
})

0 comments on commit 7db58b4

Please sign in to comment.