Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fresh-turkeys-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ainsleydev/payload-helper": minor
---

Add a reusable `SlugField` helper with a lockable admin component and automatic slug formatting hook.
102 changes: 102 additions & 0 deletions packages/payload-helper/src/fields/Slug/Component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
'use client';

import {
Button,
FieldDescription,
FieldLabel,
TextInput,
useField,
useForm,
useFormFields,
} from '@payloadcms/ui';
import type { TextFieldClientProps } from 'payload';
import type React from 'react';
import { useCallback, useEffect } from 'react';

import { formatSlug } from './formatSlug.js';
import './index.scss';

type SlugComponentProps = {
fieldToUse: string;
checkboxFieldPath: string;
} & TextFieldClientProps;

export const Component: React.FC<SlugComponentProps> = ({
field,
fieldToUse,
checkboxFieldPath: checkboxFieldPathFromProps,
path,
readOnly: readOnlyFromProps,
}) => {
const {
admin: { description } = {},
label,
} = field;

const checkboxFieldPath = path?.includes('.')
? `${path}.${checkboxFieldPathFromProps}`
: checkboxFieldPathFromProps;
const resolvedPath = path || field.name;

const { value, setValue } = useField<string>({ path: resolvedPath });
const { dispatchFields } = useForm();

const checkboxValue = useFormFields(([fields]) => {
return fields[checkboxFieldPath]?.value as string;
});

const targetFieldValue = useFormFields(([fields]) => {
return fields[fieldToUse]?.value as string;
});

useEffect(() => {
if (checkboxValue) {
if (targetFieldValue) {
const formattedSlug = formatSlug(targetFieldValue);

if (value !== formattedSlug) {
setValue(formattedSlug);
}
} else if (value !== '') {
setValue('');
}
}
}, [targetFieldValue, checkboxValue, setValue, value]);

const handleLock = useCallback(
(event: React.MouseEvent<Element>) => {
event.preventDefault();

dispatchFields({
type: 'UPDATE',
path: checkboxFieldPath,
value: !checkboxValue,
});
},
[checkboxValue, checkboxFieldPath, dispatchFields],
);

const readOnly = readOnlyFromProps || checkboxValue;

return (
<div className='field-type slug-field-component'>
<div className='label-wrapper'>
<FieldLabel htmlFor={`field-${resolvedPath}`} label={label} />
<Button className='lock-button' buttonStyle='none' onClick={handleLock}>
{checkboxValue ? 'Unlock' : 'Lock'}
</Button>
</div>
<TextInput
value={value}
onChange={setValue}
path={resolvedPath}
readOnly={Boolean(readOnly)}
/>
<FieldDescription
className={`field-description-${resolvedPath.replace(/\./g, '__')}`}
description={description ?? ''}
path={resolvedPath}
/>
</div>
);
};
21 changes: 21 additions & 0 deletions packages/payload-helper/src/fields/Slug/formatSlug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { FieldHook } from 'payload';

export const formatSlug = (val: string): string => val.replace(/ /g, '-').toLowerCase();

export const formatSlugHook =
(fallback: string): FieldHook =>
({ data, operation, value }) => {
if (typeof value === 'string') {
return formatSlug(value);
}

if (operation === 'create' || !data?.slug) {
const fallbackData = data?.[fallback] || data?.[fallback];

if (fallbackData && typeof fallbackData === 'string') {
return formatSlug(fallbackData);
}
}

return value;
};
12 changes: 12 additions & 0 deletions packages/payload-helper/src/fields/Slug/index.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.slug-field-component {
.label-wrapper {
display: flex;
justify-content: space-between;
align-items: center;
}

.lock-button {
margin: 0;
padding-bottom: 0.3125rem;
}
}
60 changes: 60 additions & 0 deletions packages/payload-helper/src/fields/Slug/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { type CheckboxField, type TextField, deepMerge } from 'payload';

import { formatSlugHook } from './formatSlug.js';

export type Overrides = {
slugOverrides?: Partial<TextField>;
checkboxOverrides?: Partial<CheckboxField>;
description?: string;
};

export type Slug = (fieldToUse?: string, overrides?: Overrides) => [TextField, CheckboxField];

export const SlugField: Slug = (fieldToUse = 'title', overrides = {}) => {
const { slugOverrides, checkboxOverrides } = overrides;

const checkBoxField = deepMerge<CheckboxField, Partial<CheckboxField>>(
{
name: 'slugLock',
type: 'checkbox',
defaultValue: true,
admin: {
hidden: true,
position: 'sidebar',
},
},
checkboxOverrides || {},
);

const slugField = deepMerge<TextField, Partial<TextField>>(
{
name: 'slug',
type: 'text',
index: true,
label: 'Slug',
unique: true,
required: true,
hooks: {
beforeValidate: [formatSlugHook(fieldToUse)],
},
admin: {
position: 'sidebar',
description:
overrides.description ||
'The URL friendly version of the title, users will see this text in the URL bar.',
components: {
Field: {
path: '/fields/Slug/Component#Component',
clientProps: {
fieldToUse,
checkboxFieldPath: checkBoxField.name,
},
},
},
},
},
slugOverrides || {},
);

return [slugField, checkBoxField];
};
2 changes: 2 additions & 0 deletions packages/payload-helper/src/fields/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export { PublishedAt } from './PublishedAt.js';
export type { PublishedAtArgs } from './PublishedAt.js';
export { SlugField } from './Slug/index.js';
export type { Overrides as SlugOverrides, Slug } from './Slug/index.js';
export { URLField } from './URLField.js';
export type { URLFieldArgs } from './URLField.js';
4 changes: 2 additions & 2 deletions packages/payload-helper/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ export {
export { SEOFields } from './common/index.js';

// Fields
export { PublishedAt, URLField } from './fields/index.js';
export type { PublishedAtArgs, URLFieldArgs } from './fields/index.js';
export { PublishedAt, SlugField, URLField } from './fields/index.js';
export type { PublishedAtArgs, Slug, SlugOverrides, URLFieldArgs } from './fields/index.js';

// Email Config Helper
export { defineEmailConfig } from './email/defineEmailConfig.js';
Expand Down
Loading