hash
stringlengths
40
40
date
stringdate
2020-04-17 22:01:00
2025-03-21 18:34:11
author
stringclasses
90 values
commit_message
stringlengths
9
197
is_merge
bool
1 class
masked_commit_message
stringlengths
4
170
type
stringclasses
8 values
git_diff
stringlengths
160
5.96M
4cd31ce343528e8b666b69d56c19466ef5403437
2024-12-02 08:01:17
Alessio Gravili
fix: prevent workflow destructuring errors for failing tasks (#9649)
false
prevent workflow destructuring errors for failing tasks (#9649)
fix
diff --git a/packages/payload/src/queues/operations/runJobs/runJob/getRunTaskFunction.ts b/packages/payload/src/queues/operations/runJobs/runJob/getRunTaskFunction.ts index 33dff047824..f929fcafce2 100644 --- a/packages/payload/src/queues/operations/runJobs/runJob/getRunTaskFunction.ts +++ b/packages/payload/src/queues/operations/runJobs/runJob/getRunTaskFunction.ts @@ -231,7 +231,7 @@ export const getRunTaskFunction = <TIsInline extends boolean>( return } - let output: object + let output: object = {} try { const runnerOutput = await runner({
5dfcffa281b2af09a30fbac9241c48acbe219c8f
2024-08-12 00:48:49
Paul
feat(plugin-redirects): added new option for redirect type in the redirects collection (#7625)
false
added new option for redirect type in the redirects collection (#7625)
feat
diff --git a/packages/plugin-redirects/src/index.ts b/packages/plugin-redirects/src/index.ts index c3ff6974a55..7ef891a8d8f 100644 --- a/packages/plugin-redirects/src/index.ts +++ b/packages/plugin-redirects/src/index.ts @@ -1,10 +1,24 @@ -import type { CollectionConfig, Config, Field } from 'payload' +import type { CollectionConfig, Config, Field, SelectField } from 'payload' import type { RedirectsPluginConfig } from './types.js' +import { redirectOptions } from './redirectTypes.js' + +export { redirectOptions, redirectTypes } from './redirectTypes.js' export const redirectsPlugin = (pluginConfig: RedirectsPluginConfig) => (incomingConfig: Config): Config => { + const redirectSelectField: SelectField = { + name: 'type', + type: 'select', + label: 'Redirect Type', + options: redirectOptions.filter((option) => + pluginConfig?.redirectTypes?.includes(option.value), + ), + required: true, + ...(pluginConfig?.redirectTypeFieldOverride || {}), + } + const defaultFields: Field[] = [ { name: 'from', @@ -58,6 +72,7 @@ export const redirectsPlugin = ], label: false, }, + ...(pluginConfig?.redirectTypes ? [redirectSelectField] : []), ] const redirectsCollection: CollectionConfig = { diff --git a/packages/plugin-redirects/src/redirectTypes.ts b/packages/plugin-redirects/src/redirectTypes.ts new file mode 100644 index 00000000000..3db8f9aa62b --- /dev/null +++ b/packages/plugin-redirects/src/redirectTypes.ts @@ -0,0 +1,24 @@ +export const redirectTypes = ['301', '302', '303', '307', '308'] as const + +export const redirectOptions: { label: string; value: (typeof redirectTypes)[number] }[] = [ + { + label: '301 - Permanent', + value: '301', + }, + { + label: '302 - Temporary', + value: '302', + }, + { + label: '303 - See Other', + value: '303', + }, + { + label: '307 - Temporary Redirect', + value: '307', + }, + { + label: '308 - Permanent Redirect', + value: '308', + }, +] diff --git a/packages/plugin-redirects/src/types.ts b/packages/plugin-redirects/src/types.ts index 3a6d90af493..751fa9bd082 100644 --- a/packages/plugin-redirects/src/types.ts +++ b/packages/plugin-redirects/src/types.ts @@ -1,8 +1,11 @@ -import type { CollectionConfig, Field } from 'payload' +import type { CollectionConfig, Field, SelectField } from 'payload' +import type { redirectTypes } from './redirectTypes.js' export type FieldsOverride = (args: { defaultFields: Field[] }) => Field[] export type RedirectsPluginConfig = { collections?: string[] overrides?: { fields?: FieldsOverride } & Partial<Omit<CollectionConfig, 'fields'>> + redirectTypeFieldOverride?: Partial<SelectField> + redirectTypes?: (typeof redirectTypes)[number][] } diff --git a/test/plugin-redirects/config.ts b/test/plugin-redirects/config.ts index 469c1fc384f..72e9135b649 100644 --- a/test/plugin-redirects/config.ts +++ b/test/plugin-redirects/config.ts @@ -42,6 +42,10 @@ export default buildConfigWithDefaults({ ] }, }, + redirectTypes: ['301', '302'], + redirectTypeFieldOverride: { + label: 'Redirect Type (Overridden)', + }, }), ], typescript: { diff --git a/test/plugin-redirects/int.spec.ts b/test/plugin-redirects/int.spec.ts index 5020590325d..04bb4f0815f 100644 --- a/test/plugin-redirects/int.spec.ts +++ b/test/plugin-redirects/int.spec.ts @@ -49,6 +49,7 @@ describe('@payloadcms/plugin-redirects', () => { value: page.id, }, }, + type: '301', }, }) @@ -66,6 +67,7 @@ describe('@payloadcms/plugin-redirects', () => { type: 'custom', url: '/test', }, + type: '301', }, }) diff --git a/test/plugin-redirects/payload-types.ts b/test/plugin-redirects/payload-types.ts index 17062e094fe..6cdc93df31d 100644 --- a/test/plugin-redirects/payload-types.ts +++ b/test/plugin-redirects/payload-types.ts @@ -17,6 +17,9 @@ export interface Config { 'payload-preferences': PayloadPreference; 'payload-migrations': PayloadMigration; }; + db: { + defaultIDType: string; + }; globals: {}; locale: 'en' | 'es' | 'de'; user: User & { @@ -26,15 +29,20 @@ export interface Config { export interface UserAuthOperations { forgotPassword: { email: string; + password: string; }; login: { - password: string; email: string; + password: string; }; registerFirstUser: { email: string; password: string; }; + unlock: { + email: string; + password: string; + }; } /** * This interface was referenced by `Config`'s JSON-Schema @@ -80,6 +88,7 @@ export interface Redirect { } | null; url?: string | null; }; + type: '301' | '302'; customField?: string | null; updatedAt: string; createdAt: string;
846f59974c2a7ffce581a7e82c156006c35ff450
2024-03-07 22:36:51
Dan Ribbens
chore(release): v3.0.0-alpha.31 [skip ci]
false
v3.0.0-alpha.31 [skip ci]
chore
diff --git a/package.json b/package.json index 7e578ca634f..0d3882e75f5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "payload-monorepo", - "version": "3.0.0-alpha.30", + "version": "3.0.0-alpha.31", "private": true, "type": "module", "workspaces:": [ diff --git a/packages/db-mongodb/package.json b/packages/db-mongodb/package.json index ee0a8413e36..fef8177712f 100644 --- a/packages/db-mongodb/package.json +++ b/packages/db-mongodb/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/db-mongodb", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "description": "The officially supported MongoDB database adapter for Payload - Update 2", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/db-postgres/package.json b/packages/db-postgres/package.json index 4a83dd279fc..055ce611ee6 100644 --- a/packages/db-postgres/package.json +++ b/packages/db-postgres/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/db-postgres", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "description": "The officially supported Postgres database adapter for Payload", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/graphql/package.json b/packages/graphql/package.json index 787088ba5b7..cd78d47304c 100644 --- a/packages/graphql/package.json +++ b/packages/graphql/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/graphql", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "main": "./src/index.ts", "types": "./src/index.d.ts", "type": "module", diff --git a/packages/next/package.json b/packages/next/package.json index 0d7f3eafc57..ab21f5a2136 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/next", - "version": "3.0.0-alpha.30", + "version": "3.0.0-alpha.31", "main": "./src/index.ts", "types": "./src/index.d.ts", "type": "module", diff --git a/packages/payload/package.json b/packages/payload/package.json index 2d6d1507a9e..7d48ddd58f8 100644 --- a/packages/payload/package.json +++ b/packages/payload/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "MIT", "main": "./src/index.js", diff --git a/packages/plugin-cloud-storage/package.json b/packages/plugin-cloud-storage/package.json index 52c843f697c..d0a1f86751d 100644 --- a/packages/plugin-cloud-storage/package.json +++ b/packages/plugin-cloud-storage/package.json @@ -1,7 +1,7 @@ { "name": "@payloadcms/plugin-cloud-storage", "description": "The official cloud storage plugin for Payload CMS", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "main": "dist/index.js", "types": "dist/index.d.ts", "type": "module", diff --git a/packages/plugin-cloud/package.json b/packages/plugin-cloud/package.json index 5be99c8b0ac..b5b02758467 100644 --- a/packages/plugin-cloud/package.json +++ b/packages/plugin-cloud/package.json @@ -1,7 +1,7 @@ { "name": "@payloadcms/plugin-cloud", "description": "The official Payload Cloud plugin", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "main": "dist/index.js", "types": "dist/index.d.ts", "license": "MIT", diff --git a/packages/plugin-seo/package.json b/packages/plugin-seo/package.json index 509b788ea26..cba2b2e7042 100644 --- a/packages/plugin-seo/package.json +++ b/packages/plugin-seo/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/plugin-seo", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "homepage:": "https://payloadcms.com", "repository": "[email protected]:payloadcms/plugin-seo.git", "description": "SEO plugin for Payload", diff --git a/packages/richtext-lexical/package.json b/packages/richtext-lexical/package.json index bc8efdec021..dced2380e10 100644 --- a/packages/richtext-lexical/package.json +++ b/packages/richtext-lexical/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/richtext-lexical", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "description": "The officially supported Lexical richtext adapter for Payload", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/richtext-slate/package.json b/packages/richtext-slate/package.json index a12b98ddc6b..26617654690 100644 --- a/packages/richtext-slate/package.json +++ b/packages/richtext-slate/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/richtext-slate", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "description": "The officially supported Slate richtext adapter for Payload", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/translations/package.json b/packages/translations/package.json index cb7aeb22c60..b1518d4d6c9 100644 --- a/packages/translations/package.json +++ b/packages/translations/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/translations", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "main": "./dist/exports/index.ts", "types": "./dist/types.d.ts", "type": "module", diff --git a/packages/ui/package.json b/packages/ui/package.json index af0f5db6f36..0726b9f883f 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/ui", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.31", "main": "./src/index.ts", "types": "./dist/index.d.ts", "type": "module",
11cbb774bc32facfd2de10802a6a0bc1019572de
2024-03-21 23:46:19
Elliot DeNolf
chore: update codeowners file
false
update codeowners file
chore
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 6f31a23d783..c90ea45a14d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,32 +1,24 @@ # Order matters. The last matching pattern takes precedence. -### Catch-all ### -* @denolfe @jmikrut @DanRibbens -.* @denolfe @jmikrut @DanRibbens - ### Core ### -/packages/payload/ @denolfe @jmikrut @DanRibbens /packages/payload/src/uploads/ @denolfe /packages/payload/src/admin/ @jmikrut @jacobsfletch @JarrodMFlesch ### Adapters ### -/packages/bundler-*/ @denolfe @jmikrut @DanRibbens @JarrodMFlesch /packages/db-*/ @denolfe @jmikrut @DanRibbens /packages/richtext-*/ @denolfe @jmikrut @DanRibbens @AlessioGr ### Plugins ### -/packages/plugin-*/ @denolfe @jmikrut @DanRibbens @jacobsfletch @JarrodMFlesch @AlessioGr +/packages/plugin-*/ @denolfe @jmikrut @DanRibbens /packages/plugin-cloud*/ @denolfe /packages/plugin-form-builder/ @jacobsfletch /packages/plugin-live-preview*/ @jacobsfletch /packages/plugin-nested-docs/ @jacobsfletch -/packages/plugin-password-protection/ @jmikrut /packages/plugin-redirects/ @jacobsfletch /packages/plugin-search/ @jacobsfletch /packages/plugin-sentry/ @JessChowdhury /packages/plugin-seo/ @jacobsfletch /packages/plugin-stripe/ @jacobsfletch -/packages/plugin-zapier/ @JarrodMFlesch ### Examples ### /examples/ @jacobsfletch @@ -35,8 +27,7 @@ /examples/whitelabel/ @JessChowdhury ### Templates ### -/templates/ @jacobsfletch -/templates/blank/ @denolfe +/templates/ @jacobsfletch @denolfe ### Misc ### /packages/create-payload-app/ @denolfe
fd4fbe8c8b492445ab29d26d9648cff4e98d5708
2021-10-08 05:55:42
James
fix: bug with local API and not passing array / block data
false
bug with local API and not passing array / block data
fix
diff --git a/src/fields/traverseFields.ts b/src/fields/traverseFields.ts index 2146f2fb57a..262a7338b61 100644 --- a/src/fields/traverseFields.ts +++ b/src/fields/traverseFields.ts @@ -345,7 +345,7 @@ const traverseFields = (args: Arguments): void => { if (field.type === 'array' || field.type === 'blocks') { const hasRowsOfNewData = Array.isArray(data[field.name]); - const newRowCount = hasRowsOfNewData ? (data[field.name] as Record<string, unknown>[]).length : 0; + const newRowCount = hasRowsOfNewData ? (data[field.name] as Record<string, unknown>[]).length : undefined; // Handle cases of arrays being intentionally set to 0 if (data[field.name] === '0' || data[field.name] === 0 || data[field.name] === null) {
00874a4406cb80ce8c318b205321b3c82753d89c
2023-08-27 21:23:01
James
chore: builds version tables
false
builds version tables
chore
diff --git a/packages/db-postgres/src/init.ts b/packages/db-postgres/src/init.ts index ec47cecb3f6..48639e7e6c2 100644 --- a/packages/db-postgres/src/init.ts +++ b/packages/db-postgres/src/init.ts @@ -1,7 +1,10 @@ /* eslint-disable no-param-reassign */ import { pgEnum } from 'drizzle-orm/pg-core'; +import toSnakeCase from 'to-snake-case'; import { SanitizedCollectionConfig } from 'payload/dist/collections/config/types'; import type { Init } from 'payload/dist/database/types'; +import { buildVersionGlobalFields } from 'payload/dist/versions/buildGlobalFields'; +import { buildVersionCollectionFields } from 'payload/dist/versions/buildCollectionFields'; import { buildTable } from './schema/build'; import type { PostgresAdapter } from './types'; @@ -16,22 +19,52 @@ export const init: Init = async function init(this: PostgresAdapter) { } this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => { + const tableName = toSnakeCase(collection.slug); + buildTable({ adapter: this, buildRelationships: true, fields: collection.fields, - tableName: collection.slug, + tableName, timestamps: collection.timestamps, }); + + if (collection.versions) { + const versionsTableName = `_${tableName}_versions`; + const versionFields = buildVersionCollectionFields(collection); + + buildTable({ + adapter: this, + buildRelationships: true, + fields: versionFields, + tableName: versionsTableName, + timestamps: true, + }); + } }); this.payload.config.globals.forEach((global) => { + const tableName = toSnakeCase(global.slug); + buildTable({ adapter: this, buildRelationships: true, fields: global.fields, - tableName: global.slug, + tableName, timestamps: false, }); + + if (global.versions) { + const versionsTableName = `_${tableName}_versions`; + const versionFields = buildVersionGlobalFields(global); + + buildTable({ + adapter: this, + buildRelationships: true, + fields: versionFields, + tableName: versionsTableName, + timestamps: true, + }); + } }); }; diff --git a/packages/db-postgres/src/schema/build.ts b/packages/db-postgres/src/schema/build.ts index 17f5bb3a7dd..b9f98ae82c6 100644 --- a/packages/db-postgres/src/schema/build.ts +++ b/packages/db-postgres/src/schema/build.ts @@ -43,7 +43,6 @@ export const buildTable = ({ tableName, timestamps, }: Args): Result => { - const formattedTableName = toSnakeCase(tableName); const columns: Record<string, AnyPgColumnBuilder> = baseColumns; const indexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}; @@ -84,8 +83,8 @@ export const buildTable = ({ indexes, localesColumns, localesIndexes, - newTableName: formattedTableName, - parentTableName: formattedTableName, + newTableName: tableName, + parentTableName: tableName, relationships, })); @@ -94,7 +93,7 @@ export const buildTable = ({ columns.updatedAt = timestamp('updated_at').defaultNow().notNull(); } - const table = pgTable(formattedTableName, columns, (cols) => { + const table = pgTable(tableName, columns, (cols) => { const extraConfig = Object.entries(baseExtraConfig).reduce((config, [key, func]) => { config[key] = func(cols); return config; @@ -106,10 +105,10 @@ export const buildTable = ({ }, extraConfig); }); - adapter.tables[formattedTableName] = table; + adapter.tables[tableName] = table; if (hasLocalizedField) { - const localeTableName = `${formattedTableName}_locales`; + const localeTableName = `${tableName}_locales`; localesColumns.id = serial('id').primaryKey(); localesColumns._locale = adapter.enums._locales('_locale').notNull(); localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id').references(() => table.id, { onDelete: 'cascade' }).notNull(); @@ -158,7 +157,7 @@ export const buildTable = ({ relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](`${formattedRelationTo}_id`).references(() => adapter.tables[formattedRelationTo].id); }); - const relationshipsTableName = `${formattedTableName}_relationships`; + const relationshipsTableName = `${tableName}_relationships`; relationshipsTable = pgTable(relationshipsTableName, relationshipColumns, (cols) => { const result: Record<string, unknown> = {}; @@ -220,7 +219,7 @@ export const buildTable = ({ return result; }); - adapter.relations[`relations_${formattedTableName}`] = tableRelations; + adapter.relations[`relations_${tableName}`] = tableRelations; return { arrayBlockRelations }; }; diff --git a/packages/db-postgres/src/schema/traverseFields.ts b/packages/db-postgres/src/schema/traverseFields.ts index 94eba513bdb..c21e4f6fc66 100644 --- a/packages/db-postgres/src/schema/traverseFields.ts +++ b/packages/db-postgres/src/schema/traverseFields.ts @@ -73,7 +73,7 @@ export const traverseFields = ({ targetIndexes = localesIndexes; } - if (field.unique || field.index) { + if ((field.unique || field.index) && !['array', 'blocks', 'relationship', 'upload', 'group'].includes(field.type)) { targetIndexes[`${field.name}Idx`] = createIndex({ columnName, name: field.name, unique: field.unique }); } } diff --git a/test/postgres/collections/Pages.ts b/test/postgres/collections/Pages.ts new file mode 100644 index 00000000000..e9890da0f6d --- /dev/null +++ b/test/postgres/collections/Pages.ts @@ -0,0 +1,15 @@ +import { CollectionConfig } from '../../../src/collections/config/types'; + +export const Pages: CollectionConfig = { + slug: 'pages', + versions: { + drafts: true, + }, + fields: [ + { + name: 'slug', + type: 'text', + localized: true, + }, + ], +}; diff --git a/test/postgres/collections/People.ts b/test/postgres/collections/People.ts new file mode 100644 index 00000000000..2d107d708a1 --- /dev/null +++ b/test/postgres/collections/People.ts @@ -0,0 +1,11 @@ +import { CollectionConfig } from '../../../src/collections/config/types'; + +export const People: CollectionConfig = { + slug: 'people', + fields: [ + { + name: 'fullName', + type: 'text', + }, + ], +}; diff --git a/test/postgres/config.ts b/test/postgres/config.ts index d29d0dad8f7..4025c006a2b 100644 --- a/test/postgres/config.ts +++ b/test/postgres/config.ts @@ -2,6 +2,8 @@ import { buildConfigWithDefaults } from '../buildConfigWithDefaults'; import { LocalizedArrays } from './collections/LocalizedArrays'; import { LocalizedBlocks } from './collections/LocalizedBlocks'; import { LocalizedGroups } from './collections/LocalizedGroups'; +import { Pages } from './collections/Pages'; +import { People } from './collections/People'; import { Posts } from './collections/Posts'; import { MainMenu } from './globals/MainMenu'; @@ -10,26 +12,9 @@ const config = buildConfigWithDefaults({ LocalizedArrays, LocalizedBlocks, LocalizedGroups, + Pages, + People, Posts, - { - slug: 'pages', - fields: [ - { - name: 'slug', - type: 'text', - localized: true, - }, - ], - }, - { - slug: 'people', - fields: [ - { - name: 'fullName', - type: 'text', - }, - ], - }, ], globals: [ MainMenu,
8589fdefdad4856f4d642c2d9ed8d6ca815c81f6
2022-07-14 01:47:00
James
feat: reorganizes mongo connection
false
reorganizes mongo connection
feat
diff --git a/.vscode/launch.json b/.vscode/launch.json index 8604344c70d..688631f7c0c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -29,55 +29,17 @@ "request": "launch", "name": "Launch Program", "env": { - "PAYLOAD_CONFIG_PATH": "demo/payload.config.ts", "BABEL_ENV": "development" }, - "program": "${workspaceFolder}/demo/index.js", + "program": "${workspaceFolder}/test/dev/index.js", "skipFiles": [ "<node_internals>/**" ], - "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node", - "runtimeArgs": [ - "--nolazy" - ], - }, - { - "type": "node", - "request": "launch", - "name": "Launch Program - Production", - "env": { - "PAYLOAD_CONFIG_PATH": "demo/payload.config.ts", - "NODE_ENV": "production", - "BABEL_ENV": "development" - }, - "program": "${workspaceFolder}/demo/index.js", - "skipFiles": [ - "<node_internals>/**" - ], - "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node", - "outputCapture": "std", "runtimeArgs": [ "--nolazy" ], - }, - { - "type": "chrome", - "request": "launch", - "name": "Launch Chrome against Localhost", - "url": "http://localhost:3000/admin", - "webRoot": "${workspaceFolder}" - }, - { - "type": "node", - "request": "launch", - "name": "Debug Payload Generate Types", - "program": "${workspaceFolder}/src/bin/generateTypes.ts", - "env": { - "PAYLOAD_CONFIG_PATH": "demo/payload.config.ts", - }, - "outFiles": [ - "${workspaceFolder}/dist/**/*.js", - "!**/node_modules/**" + "args": [ + "e2e/fields" ] }, ] diff --git a/src/index.ts b/src/index.ts index 50ece2f45ff..93ce32a9d28 100644 --- a/src/index.ts +++ b/src/index.ts @@ -165,6 +165,11 @@ export class Payload { this.config = loadConfig(this.logger); + // Connect to database + if (this.mongoURL) { + this.mongoMemoryServer = await connectMongoose(this.mongoURL, options.mongoOptions, this.logger); + } + // If not initializing locally, scaffold router if (!this.local) { this.router = express.Router(); @@ -222,10 +227,6 @@ export class Payload { this.authenticate = authenticate(this.config); } - // Connect to database - if (this.mongoURL) { - this.mongoMemoryServer = await connectMongoose(this.mongoURL, options.mongoOptions, this.logger); - } if (typeof options.onInit === 'function') await options.onInit(this); if (typeof this.config.onInit === 'function') await this.config.onInit(this); diff --git a/src/mongoose/connect.ts b/src/mongoose/connect.ts index 3a6ddb58379..6220e00ab33 100644 --- a/src/mongoose/connect.ts +++ b/src/mongoose/connect.ts @@ -35,15 +35,13 @@ const connectMongoose = async ( } try { - if (process.env.PAYLOAD_DROP_DATABASE === 'true') { - mongoose.connection.once('connected', () => { - logger.info('---- DROPPING DATABASE ----'); - mongoose.connection.dropDatabase(); - }); - } - await mongoose.connect(urlToConnect, connectionOptions); + if (process.env.PAYLOAD_DROP_DATABASE === 'true') { + logger.info('---- DROPPING DATABASE ----'); + await mongoose.connection.dropDatabase(); + logger.info('---- DROPPED DATABASE ----'); + } logger.info(successfulConnectionMessage); } catch (err) { diff --git a/test/e2e/buildConfig.ts b/test/e2e/buildConfig.ts index 6b30ba5b5bd..cece6dec52b 100644 --- a/test/e2e/buildConfig.ts +++ b/test/e2e/buildConfig.ts @@ -14,5 +14,6 @@ export function buildConfig(overrides?: Partial<Config>): SanitizedConfig { }), }; } + return buildPayloadConfig(merge(baseConfig, overrides || {})); }
5f7202bbb8933cbae81aa9b16ce05e6fb548e7fd
2025-03-21 18:34:11
Jacob Fletcher
docs: payload proper nouns (#11792)
false
payload proper nouns (#11792)
docs
diff --git a/docs/admin/customizing-css.mdx b/docs/admin/customizing-css.mdx index d65dd4fb721..d0e4c5f4c16 100644 --- a/docs/admin/customizing-css.mdx +++ b/docs/admin/customizing-css.mdx @@ -45,7 +45,7 @@ To override existing styles in a way that the previous rules of specificity woul ```css @layer payload-default { - // my styles within the payload specificity + // my styles within the Payload specificity } ``` diff --git a/docs/authentication/operations.mdx b/docs/authentication/operations.mdx index 88136d37278..026b4221dc0 100644 --- a/docs/authentication/operations.mdx +++ b/docs/authentication/operations.mdx @@ -353,7 +353,7 @@ const token = await payload.forgotPassword({ data: { email: '[email protected]', }, - disableEmail: false, // you can disable the auto-generation of email via local API + disableEmail: false, // you can disable the auto-generation of email via Local API }) ``` @@ -370,7 +370,7 @@ const token = await payload.forgotPassword({ <Banner type="success"> **Tip:** -You can stop the reset-password email from being sent via using the local API. This is helpful if +You can stop the reset-password email from being sent via using the Local API. This is helpful if you need to create user accounts programmatically, but not set their password for them. This effectively generates a reset password token which you can then use to send to a page you create, allowing a user to "complete" their account by setting their password. In the background, you'd diff --git a/docs/configuration/localization.mdx b/docs/configuration/localization.mdx index a03961e111c..9174804a7cd 100644 --- a/docs/configuration/localization.mdx +++ b/docs/configuration/localization.mdx @@ -107,7 +107,7 @@ _\* An asterisk denotes that a property is required._ In some projects you may want to filter the available locales shown in the admin UI selector. You can do this by providing a `filterAvailableLocales` function in your Payload Config. This is called on the server side and is passed the array of locales. This means that you can determine what locales are visible in the localizer selection menu at the top of the admin panel. You could do this per user, or implement a function that scopes these to tenants and more. Here is an example using request headers in a multi-tenant application: ```ts -// ... rest of payload config +// ... rest of Payload config localization: { defaultLocale: 'en', locales: ['en', 'es'], diff --git a/docs/database/migrations.mdx b/docs/database/migrations.mdx index 40b7852eb94..22814120154 100644 --- a/docs/database/migrations.mdx +++ b/docs/database/migrations.mdx @@ -53,7 +53,7 @@ export async function down({ payload, req }: MigrateDownArgs): Promise<void> { ## Using Transactions When migrations are run, each migration is performed in a new [transaction](/docs/database/transactions) for you. All -you need to do is pass the `req` object to any [local API](/docs/local-api/overview) or direct database calls, such as +you need to do is pass the `req` object to any [Local API](/docs/local-api/overview) or direct database calls, such as `payload.db.updateMany()`, to make database changes inside the transaction. Assuming no errors were thrown, the transaction is committed after your `up` or `down` function runs. If the migration errors at any point or fails to commit, it is caught and the transaction gets aborted. This way no change is made to the database if the migration fails. diff --git a/docs/database/transactions.mdx b/docs/database/transactions.mdx index f6ea77250a9..0d4597d596e 100644 --- a/docs/database/transactions.mdx +++ b/docs/database/transactions.mdx @@ -69,7 +69,7 @@ const afterChange: CollectionAfterChangeHook = async ({ req }) => { ## Direct Transaction Access -When writing your own scripts or custom endpoints, you may wish to have direct control over transactions. This is useful for interacting with your database outside of Payload's local API. +When writing your own scripts or custom endpoints, you may wish to have direct control over transactions. This is useful for interacting with your database outside of Payload's Local API. The following functions can be used for managing transactions: @@ -77,7 +77,7 @@ The following functions can be used for managing transactions: - `payload.db.commitTransaction` - Takes the identifier for the transaction, finalizes any changes. - `payload.db.rollbackTransaction` - Takes the identifier for the transaction, discards any changes. -Payload uses the `req` object to pass the transaction ID through to the database adapter. If you are not using the `req` object, you can make a new object to pass the transaction ID directly to database adapter methods and local API calls. +Payload uses the `req` object to pass the transaction ID through to the database adapter. If you are not using the `req` object, you can make a new object to pass the transaction ID directly to database adapter methods and Local API calls. Example: ```ts @@ -91,7 +91,7 @@ const standalonePayloadScript = async () => { const transactionID = await payload.db.beginTransaction() try { - // Make an update using the local API + // Make an update using the Local API await payload.update({ collection: 'posts', data: { @@ -123,7 +123,7 @@ standalonePayloadScript() If you wish to disable transactions entirely, you can do so by passing `false` as the `transactionOptions` in your database adapter configuration. All the official Payload database adapters support this option. -In addition to allowing database transactions to be disabled at the adapter level. You can prevent Payload from using a transaction in direct calls to the local API by adding `disableTransaction: true` to the args. For example: +In addition to allowing database transactions to be disabled at the adapter level. You can prevent Payload from using a transaction in direct calls to the Local API by adding `disableTransaction: true` to the args. For example: ```ts await payload.update({ diff --git a/docs/fields/join.mdx b/docs/fields/join.mdx index 64ff7ea169d..5bd0bfb1317 100644 --- a/docs/fields/join.mdx +++ b/docs/fields/join.mdx @@ -236,11 +236,11 @@ The following query options are supported: | **`sort`** | A string used to order related results | | **`count`** | Whether include the count of related documents or not. Not included by default | -These can be applied to the local API, GraphQL, and REST API. +These can be applied to the Local API, GraphQL, and REST API. ### Local API -By adding `joins` to the local API you can customize the request for each join field by the `name` of the field. +By adding `joins` to the Local API you can customize the request for each join field by the `name` of the field. ```js const result = await payload.find({ @@ -287,7 +287,7 @@ const result = await payload.find({ ### Rest API -The rest API supports the same query options as the local API. You can use the `joins` query parameter to customize the +The REST API supports the same query options as the Local API. You can use the `joins` query parameter to customize the request for each join field by the `name` of the field. For example, an API call to get a document with the related posts limited to 5 and sorted by title: diff --git a/docs/graphql/extending.mdx b/docs/graphql/extending.mdx index 03298c91aa1..7786253c08d 100644 --- a/docs/graphql/extending.mdx +++ b/docs/graphql/extending.mdx @@ -70,7 +70,7 @@ export default buildConfig({ ## Resolver function -In your resolver, make sure you set `depth: 0` if you're returning data directly from the local API so that GraphQL can correctly resolve queries to nested values such as relationship data. +In your resolver, make sure you set `depth: 0` if you're returning data directly from the Local API so that GraphQL can correctly resolve queries to nested values such as relationship data. Your function will receive four arguments you can make use of: diff --git a/docs/graphql/graphql-schema.mdx b/docs/graphql/graphql-schema.mdx index ae238cd9e41..dc5b0e9cba4 100644 --- a/docs/graphql/graphql-schema.mdx +++ b/docs/graphql/graphql-schema.mdx @@ -60,7 +60,7 @@ type Collection1 { } ``` -The above example outputs all your definitions to a file relative from your payload config as `./graphql/schema.graphql`. By default, the file will be output to your current working directory as `schema.graphql`. +The above example outputs all your definitions to a file relative from your Payload config as `./graphql/schema.graphql`. By default, the file will be output to your current working directory as `schema.graphql`. ### Adding an npm script diff --git a/docs/hooks/context.mdx b/docs/hooks/context.mdx index 6acf478778a..54bed46a955 100644 --- a/docs/hooks/context.mdx +++ b/docs/hooks/context.mdx @@ -14,7 +14,7 @@ Context gives you a way forward on otherwise difficult problems such as: 1. **Passing data between Hooks**: Needing data in multiple Hooks from a 3rd party API, it could be retrieved and used in `beforeChange` and later used again in an `afterChange` hook without having to fetch it twice. 2. **Preventing infinite loops**: Calling `payload.update()` on the same document that triggered an `afterChange` hook will create an infinite loop, control the flow by assigning a no-op condition to context -3. **Passing data to local API**: Setting values on the `req.context` and pass it to `payload.create()` you can provide additional data to hooks without adding extraneous fields. +3. **Passing data to Local API**: Setting values on the `req.context` and pass it to `payload.create()` you can provide additional data to hooks without adding extraneous fields. 4. **Passing data between hooks and middleware or custom endpoints**: Hooks could set context across multiple collections and then be used in a final `postMiddleware`. ## How To Use Context diff --git a/docs/jobs-queue/queues.mdx b/docs/jobs-queue/queues.mdx index df93e8c5d87..43c2ab6efe8 100644 --- a/docs/jobs-queue/queues.mdx +++ b/docs/jobs-queue/queues.mdx @@ -39,7 +39,7 @@ export default buildConfig({ tasks: [ // your tasks here ], - // autoRun can optionally be a function that receives payload as an argument + // autoRun can optionally be a function that receives `payload` as an argument autoRun: [ { cron: '0 * * * *', // every hour at minute 0 diff --git a/docs/jobs-queue/tasks.mdx b/docs/jobs-queue/tasks.mdx index 399ed0a6edc..097d8ec4843 100644 --- a/docs/jobs-queue/tasks.mdx +++ b/docs/jobs-queue/tasks.mdx @@ -15,7 +15,7 @@ You can register Tasks on the Payload config, and then create [Jobs](/docs/jobs- Payload Tasks can be configured to automatically retried if they fail, which makes them valuable for "durable" workflows like AI applications where LLMs can return non-deterministic results, and might need to be retried. -Tasks can either be defined within the `jobs.tasks` array in your payload config, or they can be defined inline within a workflow. +Tasks can either be defined within the `jobs.tasks` array in your Payload config, or they can be defined inline within a workflow. ### Defining tasks in the config @@ -25,9 +25,9 @@ Simply add a task to the `jobs.tasks` array in your Payload config. A task consi | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `slug` | Define a slug-based name for this job. This slug needs to be unique among both tasks and workflows. | | `handler` | The function that should be responsible for running the job. You can either pass a string-based path to the job function file, or the job function itself. If you are using large dependencies within your job, you might prefer to pass the string path because that will avoid bundling large dependencies in your Next.js app. Passing a string path is an advanced feature that may require a sophisticated build pipeline in order to work. | -| `inputSchema` | Define the input field schema - payload will generate a type for this schema. | +| `inputSchema` | Define the input field schema - Payload will generate a type for this schema. | | `interfaceName` | You can use interfaceName to change the name of the interface that is generated for this task. By default, this is "Task" + the capitalized task slug. | -| `outputSchema` | Define the output field schema - payload will generate a type for this schema. | +| `outputSchema` | Define the output field schema - Payload will generate a type for this schema. | | `label` | Define a human-friendly label for this task. | | `onFail` | Function to be executed if the task fails. | | `onSuccess` | Function to be executed if the task succeeds. | diff --git a/docs/jobs-queue/workflows.mdx b/docs/jobs-queue/workflows.mdx index e41a5cdc451..a5dbc8d1f24 100644 --- a/docs/jobs-queue/workflows.mdx +++ b/docs/jobs-queue/workflows.mdx @@ -27,7 +27,7 @@ To define a JS-based workflow, simply add a workflow to the `jobs.workflows` arr | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `slug` | Define a slug-based name for this workflow. This slug needs to be unique among both tasks and workflows. | | `handler` | The function that should be responsible for running the workflow. You can either pass a string-based path to the workflow function file, or workflow job function itself. If you are using large dependencies within your workflow, you might prefer to pass the string path because that will avoid bundling large dependencies in your Next.js app. Passing a string path is an advanced feature that may require a sophisticated build pipeline in order to work. | -| `inputSchema` | Define the input field schema - payload will generate a type for this schema. | +| `inputSchema` | Define the input field schema - Payload will generate a type for this schema. | | `interfaceName` | You can use interfaceName to change the name of the interface that is generated for this workflow. By default, this is "Workflow" + the capitalized workflow slug. | | `label` | Define a human-friendly label for this workflow. | | `queue` | Optionally, define the queue name that this workflow should be tied to. Defaults to "default". | diff --git a/docs/local-api/outside-nextjs.mdx b/docs/local-api/outside-nextjs.mdx index 76e394ded50..ad6df58732a 100644 --- a/docs/local-api/outside-nextjs.mdx +++ b/docs/local-api/outside-nextjs.mdx @@ -76,7 +76,7 @@ Note: Install @swc-node/register in your project first. While swc mode is faster #### Option 2: use an alternative runtime like bun -While we do not guarantee support for alternative runtimes, you are free to use them and disable payloads own transpilation by appending the `--disable-transpile` flag to the `payload` command: +While we do not guarantee support for alternative runtimes, you are free to use them and disable Payload's own transpilation by appending the `--disable-transpile` flag to the `payload` command: ```sh bunx --bun payload run src/seed.ts --disable-transpile diff --git a/docs/local-api/overview.mdx b/docs/local-api/overview.mdx index fd3b746de76..cb46d8b5b45 100644 --- a/docs/local-api/overview.mdx +++ b/docs/local-api/overview.mdx @@ -320,7 +320,7 @@ available: // you'll also have to await headers inside your function, or component, like so: // const headers = await nextHeaders() -// If you're using payload outside of Next.js, you'll have to provide headers accordingly. +// If you're using Payload outside of Next.js, you'll have to provide headers accordingly. // result will be formatted as follows: // { diff --git a/docs/migration-guide/overview.mdx b/docs/migration-guide/overview.mdx index 16d57fb944d..b17b01cd8b6 100644 --- a/docs/migration-guide/overview.mdx +++ b/docs/migration-guide/overview.mdx @@ -42,7 +42,7 @@ For more details, see the [Documentation](https://payloadcms.com/docs/getting-st 1. **Install new dependencies of Payload, Next.js and React**: - Refer to the package.json file made in the create-payload-app, including peerDependencies, devDependencies, and dependencies. The core package and plugins require all versions to be synced. Previously, on 2.x it was possible to be running the latest version of payload 2.x with an older version of db-mongodb for example. This is no longer the case. + Refer to the package.json file made in the create-payload-app, including peerDependencies, devDependencies, and dependencies. The core package and plugins require all versions to be synced. Previously, on 2.x it was possible to be running the latest version of Payload 2.x with an older version of db-mongodb for example. This is no longer the case. ```bash pnpm i next react react-dom payload @payloadcms/ui @payloadcms/next diff --git a/docs/plugins/form-builder.mdx b/docs/plugins/form-builder.mdx index b87c2da29f9..7c1ceb20569 100644 --- a/docs/plugins/form-builder.mdx +++ b/docs/plugins/form-builder.mdx @@ -423,7 +423,7 @@ formBuilderPlugin({ ## Email -This plugin relies on the [email configuration](../email/overview) defined in your payload configuration. It will read from your config and attempt to send your emails using the credentials provided. +This plugin relies on the [email configuration](../email/overview) defined in your Payload configuration. It will read from your config and attempt to send your emails using the credentials provided. ### Email formatting diff --git a/docs/typescript/generating-types.mdx b/docs/typescript/generating-types.mdx index 19e5feac07f..a131d729a4c 100644 --- a/docs/typescript/generating-types.mdx +++ b/docs/typescript/generating-types.mdx @@ -212,7 +212,7 @@ appending the field type to the end, i.e. `MetaGroup` or similar. ## Using your types -Now that your types have been generated, payloads local API will now be typed. It is common for users to want to use this in their frontend code, we recommend generating them with Payload and then copying the file over to your frontend codebase. This is the simplest way to get your types into your frontend codebase. +Now that your types have been generated, Payload's Local API will now be typed. It is common for users to want to use this in their frontend code, we recommend generating them with Payload and then copying the file over to your frontend codebase. This is the simplest way to get your types into your frontend codebase. ### Adding an npm script
324af8a5f98e6c2c43bb776b9e0e67aa10a20a8e
2024-11-18 03:16:23
Elliot DeNolf
chore: update all githubusercontent links after branch rename
false
update all githubusercontent links after branch rename
chore
diff --git a/.github/reproduction-guide.md b/.github/reproduction-guide.md index 7817a1eb03a..ae8c890251f 100644 --- a/.github/reproduction-guide.md +++ b/.github/reproduction-guide.md @@ -40,7 +40,7 @@ There are a couple ways run integration tests: - **Granularly** - you can run individual tests in vscode by installing the Jest Runner plugin and using that to run individual tests. Clicking the `debug` button will run the test in debug mode allowing you to set break points. - <img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/github/int-debug.png" /> + <img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/assets/images/github/int-debug.png" /> - **Manually** - you can run all int tests in the `/test/_community/int.spec.ts` file by running the following command: @@ -57,7 +57,7 @@ The easiest way to run E2E tests is to install Once they are installed you can open the `testing` tab in vscode sidebar and drill down to the test you want to run, i.e. `/test/_community/e2e.spec.ts` -<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/github/e2e-debug.png" /> +<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/assets/images/github/e2e-debug.png" /> #### Notes diff --git a/ISSUE_GUIDE.md b/ISSUE_GUIDE.md index 153d85b61eb..bb08e1d2a2d 100644 --- a/ISSUE_GUIDE.md +++ b/ISSUE_GUIDE.md @@ -45,7 +45,7 @@ There are a couple ways to do this: - **Granularly** - you can run individual tests in vscode by installing the Jest Runner plugin and using that to run individual tests. Clicking the `debug` button will run the test in debug mode allowing you to set break points. - <img src="https://raw.githubusercontent.com/payloadcms/payload/main/src/admin/assets/images/github/int-debug.png" /> + <img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/assets/images/github/int-debug.png" /> - **Manually** - you can run all int tests in the `/test/_community/int.spec.ts` file by running the following command: @@ -62,7 +62,7 @@ The easiest way to run E2E tests is to install Once they are installed you can open the `testing` tab in vscode sidebar and drill down to the test you want to run, i.e. `/test/_community/e2e.spec.ts` -<img src="https://raw.githubusercontent.com/payloadcms/payload/main/src/admin/assets/images/github/e2e-debug.png" /> +<img src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/assets/images/github/e2e-debug.png" /> #### Notes diff --git a/examples/auth/next-app/app/_components/Header/index.tsx b/examples/auth/next-app/app/_components/Header/index.tsx index 7e54351c9a4..1642bf4530e 100644 --- a/examples/auth/next-app/app/_components/Header/index.tsx +++ b/examples/auth/next-app/app/_components/Header/index.tsx @@ -1,27 +1,26 @@ -import React from 'react' import Image from 'next/image' import Link from 'next/link' +import React from 'react' import { Gutter } from '../Gutter' -import { HeaderNav } from './Nav' - import classes from './index.module.scss' +import { HeaderNav } from './Nav' export function Header() { return ( <header className={classes.header}> <Gutter className={classes.wrap}> - <Link href="/" className={classes.logo}> + <Link className={classes.logo} href="/"> <picture> <source - srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" media="(prefers-color-scheme: dark)" + srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> <Image - width={150} - height={30} alt="Payload Logo" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + height={30} + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" + width={150} /> </picture> </Link> diff --git a/examples/auth/next-pages/src/components/Header/index.tsx b/examples/auth/next-pages/src/components/Header/index.tsx index da272f702d7..10af77608ee 100644 --- a/examples/auth/next-pages/src/components/Header/index.tsx +++ b/examples/auth/next-pages/src/components/Header/index.tsx @@ -1,27 +1,26 @@ -import React from 'react' import Image from 'next/image' import Link from 'next/link' +import React from 'react' import { Gutter } from '../Gutter' -import { HeaderNav } from './Nav' - import classes from './index.module.scss' +import { HeaderNav } from './Nav' export const Header: React.FC = () => { return ( <header className={classes.header}> <Gutter className={classes.wrap}> - <Link href="/" className={classes.logo}> + <Link className={classes.logo} href="/"> <picture> <source - srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" media="(prefers-color-scheme: dark)" + srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> <Image - width={150} - height={30} alt="Payload Logo" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + height={30} + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" + width={150} /> </picture> </Link> diff --git a/examples/auth/payload/src/app/(app)/_components/Header/index.tsx b/examples/auth/payload/src/app/(app)/_components/Header/index.tsx index d7e4b748eb0..1642bf4530e 100644 --- a/examples/auth/payload/src/app/(app)/_components/Header/index.tsx +++ b/examples/auth/payload/src/app/(app)/_components/Header/index.tsx @@ -3,8 +3,8 @@ import Link from 'next/link' import React from 'react' import { Gutter } from '../Gutter' -import { HeaderNav } from './Nav' import classes from './index.module.scss' +import { HeaderNav } from './Nav' export function Header() { return ( @@ -14,12 +14,12 @@ export function Header() { <picture> <source media="(prefers-color-scheme: dark)" - srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" + srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> <Image alt="Payload Logo" height={30} - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" width={150} /> </picture> diff --git a/examples/custom-server/src/app/layout.tsx b/examples/custom-server/src/app/layout.tsx index 17ccebe819f..e2e94008f1b 100644 --- a/examples/custom-server/src/app/layout.tsx +++ b/examples/custom-server/src/app/layout.tsx @@ -1,13 +1,12 @@ -import React from 'react' import Link from 'next/link' +import React from 'react' import './app.scss' - import classes from './layout.module.scss' export const metadata = { - title: 'Payload Custom Server', description: 'Serve Payload alongside any front-end framework.', + title: 'Payload Custom Server', } export default function RootLayout({ children }: { children: React.ReactNode }) { @@ -15,16 +14,16 @@ export default function RootLayout({ children }: { children: React.ReactNode }) <html lang="en"> <body className={classes.body}> <header className={classes.header}> - <Link href="https://payloadcms.com" target="_blank" rel="noopener noreferrer"> + <Link href="https://payloadcms.com" rel="noopener noreferrer" target="_blank"> <picture> <source media="(prefers-color-scheme: dark)" - srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" + srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> <img - className={classes.logo} alt="Payload Logo" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + className={classes.logo} + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" /> </picture> </Link> diff --git a/examples/draft-preview/next-app/app/_components/Header/index.tsx b/examples/draft-preview/next-app/app/_components/Header/index.tsx index e7345a6b0d3..b71a8db489f 100644 --- a/examples/draft-preview/next-app/app/_components/Header/index.tsx +++ b/examples/draft-preview/next-app/app/_components/Header/index.tsx @@ -1,11 +1,11 @@ -import React from 'react' import Image from 'next/image' import Link from 'next/link' +import React from 'react' + +import type { MainMenu } from '../../../payload-types' -import { MainMenu } from '../../../payload-types' import { CMSLink } from '../CMSLink' import { Gutter } from '../Gutter' - import classes from './index.module.scss' export async function Header() { @@ -20,17 +20,17 @@ export async function Header() { return ( <header className={classes.header}> <Gutter className={classes.wrap}> - <Link href="/" className={classes.logo}> + <Link className={classes.logo} href="/"> <picture> <source - srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" media="(prefers-color-scheme: dark)" + srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> <Image - width={150} - height={30} alt="Payload Logo" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + height={30} + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" + width={150} /> </picture> </Link> diff --git a/examples/draft-preview/next-pages/src/components/Header/index.tsx b/examples/draft-preview/next-pages/src/components/Header/index.tsx index f7f23ecd1b8..c886f29ebcc 100644 --- a/examples/draft-preview/next-pages/src/components/Header/index.tsx +++ b/examples/draft-preview/next-pages/src/components/Header/index.tsx @@ -1,13 +1,14 @@ -import React, { useState } from 'react' +import type { PayloadAdminBarProps, PayloadMeUser } from 'payload-admin-bar' + import Image from 'next/image' import Link from 'next/link' -import { PayloadAdminBarProps, PayloadMeUser } from 'payload-admin-bar' +import React, { useState } from 'react' + +import type { MainMenu } from '../../payload-types' -import { MainMenu } from '../../payload-types' import { AdminBar } from '../AdminBar' import { CMSLink } from '../CMSLink' import { Gutter } from '../Gutter' - import classes from './index.module.scss' type HeaderBarProps = { @@ -18,17 +19,17 @@ export const HeaderBar: React.FC<HeaderBarProps> = ({ children }) => { return ( <header className={classes.header}> <Gutter className={classes.wrap}> - <Link href="/" className={classes.logo}> + <Link className={classes.logo} href="/"> <picture> <source - srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" media="(prefers-color-scheme: dark)" + srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> <Image - width={150} - height={30} alt="Payload Logo" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + height={30} + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" + width={150} /> </picture> </Link> @@ -39,12 +40,12 @@ export const HeaderBar: React.FC<HeaderBarProps> = ({ children }) => { } export const Header: React.FC<{ + adminBarProps: PayloadAdminBarProps globals: { mainMenu: MainMenu } - adminBarProps: PayloadAdminBarProps }> = (props) => { - const { globals, adminBarProps } = props + const { adminBarProps, globals } = props const [user, setUser] = useState<PayloadMeUser>() @@ -56,7 +57,7 @@ export const Header: React.FC<{ return ( <div> - <AdminBar adminBarProps={adminBarProps} user={user} setUser={setUser} /> + <AdminBar adminBarProps={adminBarProps} setUser={setUser} user={user} /> <HeaderBar> {hasNavItems && ( <nav className={classes.nav}> diff --git a/examples/nested-docs/next-app/app/_components/Header/index.tsx b/examples/nested-docs/next-app/app/_components/Header/index.tsx index e7345a6b0d3..b71a8db489f 100644 --- a/examples/nested-docs/next-app/app/_components/Header/index.tsx +++ b/examples/nested-docs/next-app/app/_components/Header/index.tsx @@ -1,11 +1,11 @@ -import React from 'react' import Image from 'next/image' import Link from 'next/link' +import React from 'react' + +import type { MainMenu } from '../../../payload-types' -import { MainMenu } from '../../../payload-types' import { CMSLink } from '../CMSLink' import { Gutter } from '../Gutter' - import classes from './index.module.scss' export async function Header() { @@ -20,17 +20,17 @@ export async function Header() { return ( <header className={classes.header}> <Gutter className={classes.wrap}> - <Link href="/" className={classes.logo}> + <Link className={classes.logo} href="/"> <picture> <source - srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" media="(prefers-color-scheme: dark)" + srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> <Image - width={150} - height={30} alt="Payload Logo" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + height={30} + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" + width={150} /> </picture> </Link> diff --git a/examples/nested-docs/next-pages/src/components/Header/index.tsx b/examples/nested-docs/next-pages/src/components/Header/index.tsx index f7f23ecd1b8..c886f29ebcc 100644 --- a/examples/nested-docs/next-pages/src/components/Header/index.tsx +++ b/examples/nested-docs/next-pages/src/components/Header/index.tsx @@ -1,13 +1,14 @@ -import React, { useState } from 'react' +import type { PayloadAdminBarProps, PayloadMeUser } from 'payload-admin-bar' + import Image from 'next/image' import Link from 'next/link' -import { PayloadAdminBarProps, PayloadMeUser } from 'payload-admin-bar' +import React, { useState } from 'react' + +import type { MainMenu } from '../../payload-types' -import { MainMenu } from '../../payload-types' import { AdminBar } from '../AdminBar' import { CMSLink } from '../CMSLink' import { Gutter } from '../Gutter' - import classes from './index.module.scss' type HeaderBarProps = { @@ -18,17 +19,17 @@ export const HeaderBar: React.FC<HeaderBarProps> = ({ children }) => { return ( <header className={classes.header}> <Gutter className={classes.wrap}> - <Link href="/" className={classes.logo}> + <Link className={classes.logo} href="/"> <picture> <source - srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" media="(prefers-color-scheme: dark)" + srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> <Image - width={150} - height={30} alt="Payload Logo" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + height={30} + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" + width={150} /> </picture> </Link> @@ -39,12 +40,12 @@ export const HeaderBar: React.FC<HeaderBarProps> = ({ children }) => { } export const Header: React.FC<{ + adminBarProps: PayloadAdminBarProps globals: { mainMenu: MainMenu } - adminBarProps: PayloadAdminBarProps }> = (props) => { - const { globals, adminBarProps } = props + const { adminBarProps, globals } = props const [user, setUser] = useState<PayloadMeUser>() @@ -56,7 +57,7 @@ export const Header: React.FC<{ return ( <div> - <AdminBar adminBarProps={adminBarProps} user={user} setUser={setUser} /> + <AdminBar adminBarProps={adminBarProps} setUser={setUser} user={user} /> <HeaderBar> {hasNavItems && ( <nav className={classes.nav}> diff --git a/templates/website/src/Footer/Component.tsx b/templates/website/src/Footer/Component.tsx index 20c628503c3..8665e1db889 100644 --- a/templates/website/src/Footer/Component.tsx +++ b/templates/website/src/Footer/Component.tsx @@ -20,7 +20,7 @@ export async function Footer() { <img alt="Payload Logo" className="max-w-[6rem] invert-0" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> </picture> </Link> diff --git a/templates/website/src/components/Logo/Logo.tsx b/templates/website/src/components/Logo/Logo.tsx index b62b95aaf4e..077ece5bc94 100644 --- a/templates/website/src/components/Logo/Logo.tsx +++ b/templates/website/src/components/Logo/Logo.tsx @@ -6,7 +6,7 @@ export const Logo = () => { <img alt="Payload Logo" className="max-w-[9.375rem] invert dark:invert-0" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> ) } diff --git a/templates/with-vercel-website/src/Footer/Component.tsx b/templates/with-vercel-website/src/Footer/Component.tsx index 20c628503c3..8665e1db889 100644 --- a/templates/with-vercel-website/src/Footer/Component.tsx +++ b/templates/with-vercel-website/src/Footer/Component.tsx @@ -20,7 +20,7 @@ export async function Footer() { <img alt="Payload Logo" className="max-w-[6rem] invert-0" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> </picture> </Link> diff --git a/templates/with-vercel-website/src/components/Logo/Logo.tsx b/templates/with-vercel-website/src/components/Logo/Logo.tsx index b62b95aaf4e..077ece5bc94 100644 --- a/templates/with-vercel-website/src/components/Logo/Logo.tsx +++ b/templates/with-vercel-website/src/components/Logo/Logo.tsx @@ -6,7 +6,7 @@ export const Logo = () => { <img alt="Payload Logo" className="max-w-[9.375rem] invert dark:invert-0" - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-light.svg" + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-light.svg" /> ) } diff --git a/test/live-preview/app/live-preview/_components/Header/index.tsx b/test/live-preview/app/live-preview/_components/Header/index.tsx index d0066daeaf9..46e77196058 100644 --- a/test/live-preview/app/live-preview/_components/Header/index.tsx +++ b/test/live-preview/app/live-preview/_components/Header/index.tsx @@ -3,8 +3,8 @@ import React from 'react' import { getHeader } from '../../_api/getHeader.js' import { Gutter } from '../Gutter/index.js' -import { HeaderNav } from './Nav/index.js' import classes from './index.module.scss' +import { HeaderNav } from './Nav/index.js' const Link = (LinkWithDefault.default || LinkWithDefault) as typeof LinkWithDefault.default @@ -18,7 +18,7 @@ export async function Header() { <img alt="Payload Logo" className={classes.logo} - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" /> </Link> <HeaderNav header={header} /> diff --git a/test/live-preview/prod/app/live-preview/_components/Header/index.tsx b/test/live-preview/prod/app/live-preview/_components/Header/index.tsx index d0066daeaf9..46e77196058 100644 --- a/test/live-preview/prod/app/live-preview/_components/Header/index.tsx +++ b/test/live-preview/prod/app/live-preview/_components/Header/index.tsx @@ -3,8 +3,8 @@ import React from 'react' import { getHeader } from '../../_api/getHeader.js' import { Gutter } from '../Gutter/index.js' -import { HeaderNav } from './Nav/index.js' import classes from './index.module.scss' +import { HeaderNav } from './Nav/index.js' const Link = (LinkWithDefault.default || LinkWithDefault) as typeof LinkWithDefault.default @@ -18,7 +18,7 @@ export async function Header() { <img alt="Payload Logo" className={classes.logo} - src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/payload/src/admin/assets/images/payload-logo-dark.svg" + src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-logo-dark.svg" /> </Link> <HeaderNav header={header} />
2878b4b1bec5c0c9997c1ba2a080640d4d3f8e5f
2022-11-15 19:53:20
Jarrod Flesch
fix: corrects exported custom component type
false
corrects exported custom component type
fix
diff --git a/src/admin/components/forms/CollapsibleLabel/types.ts b/src/admin/components/forms/CollapsibleLabel/types.ts index 59325f2ff59..1b1ffcc5f60 100644 --- a/src/admin/components/forms/CollapsibleLabel/types.ts +++ b/src/admin/components/forms/CollapsibleLabel/types.ts @@ -1,7 +1,7 @@ import React from 'react'; import { Data } from '../Form/types'; -export type CollapsibleHeader = (props: { +export type CollapsibleLabel = (props: { formData: Data, collapsibleData: Data, index?: number, @@ -11,6 +11,6 @@ export type CollapsibleHeader = (props: { export type Props = { fallback: string; path: string; - header?: CollapsibleHeader; + label?: CollapsibleLabel; rowNumber?: number; }
53a09f4989ab24ee57caed9cb677abe72483f511
2024-03-14 20:42:28
Elliot DeNolf
chore(create-payload-app): migrate to esm, adjust init-next tests
false
migrate to esm, adjust init-next tests
chore
diff --git a/.eslintignore b/.eslintignore index 3fc26d90eec..fa111f77021 100644 --- a/.eslintignore +++ b/.eslintignore @@ -9,3 +9,4 @@ **/node_modules **/temp playwright.config.ts +jest.config.js diff --git a/jest.config.js b/jest.config.js index 34d7cb64540..33801d5eef1 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,10 +1,4 @@ -// const nextJest = require('next/jest.js') - -// const createJestConfig = nextJest({ -// // Provide the path to your Next.js app to load next.config.js and .env files in your test environment -// dir: './', -// }) - +/** @type {import('@jest/types').Config} */ const customJestConfig = { extensionsToTreatAsEsm: ['.ts', '.tsx'], globalSetup: './test/jest.setup.ts', @@ -23,5 +17,4 @@ const customJestConfig = { verbose: true, } -// module.exports = createJestConfig(customJestConfig) export default customJestConfig diff --git a/package.json b/package.json index 0593c6b1c93..1fe5716a81f 100644 --- a/package.json +++ b/package.json @@ -142,6 +142,7 @@ "slate": "0.91.4", "swc-plugin-transform-remove-imports": "^1.12.1", "tempfile": "^3.0.0", + "tempy": "^1.0.1", "ts-node": "10.9.1", "tsx": "^4.7.1", "turbo": "^1.12.5", diff --git a/packages/create-payload-app/jest.config.js b/packages/create-payload-app/jest.config.js index b27ed151950..547b8699a5c 100644 --- a/packages/create-payload-app/jest.config.js +++ b/packages/create-payload-app/jest.config.js @@ -1,9 +1,11 @@ -module.exports = { - testEnvironment: 'node', +import baseConfig from '../../jest.config.js' + +/** @type {import('@jest/types').Config} */ +const customJestConfig = { + ...baseConfig, + globalSetup: null, testMatch: ['**/src/**/?(*.)+(spec|test|it-test).[tj]s?(x)'], - testTimeout: 10000, - transform: { - '^.+\\.(ts|tsx)?$': 'ts-jest', - }, - verbose: true, + testTimeout: 20000, } + +export default customJestConfig diff --git a/packages/create-payload-app/package.json b/packages/create-payload-app/package.json index 41d82c0917d..5d91ef40293 100644 --- a/packages/create-payload-app/package.json +++ b/packages/create-payload-app/package.json @@ -2,6 +2,7 @@ "name": "create-payload-app", "version": "1.0.0", "license": "MIT", + "type": "module", "bin": { "create-payload-app": "bin/cli.js" }, @@ -41,7 +42,6 @@ "@types/fs-extra": "^9.0.12", "@types/jest": "^27.0.3", "@types/node": "^16.6.2", - "@types/prompts": "^2.4.1", - "ts-jest": "^29.1.0" + "@types/prompts": "^2.4.1" } } diff --git a/packages/create-payload-app/src/index.ts b/packages/create-payload-app/src/index.ts index c5e28d32e09..e34d74cdd7b 100644 --- a/packages/create-payload-app/src/index.ts +++ b/packages/create-payload-app/src/index.ts @@ -1,5 +1,5 @@ -import { Main } from './main' -import { error } from './utils/log' +import { Main } from './main.js' +import { error } from './utils/log.js' async function main(): Promise<void> { await new Main().init() diff --git a/packages/create-payload-app/src/lib/configure-payload-config.ts b/packages/create-payload-app/src/lib/configure-payload-config.ts index d710a842040..fa8f5e46e64 100644 --- a/packages/create-payload-app/src/lib/configure-payload-config.ts +++ b/packages/create-payload-app/src/lib/configure-payload-config.ts @@ -1,10 +1,10 @@ import fse from 'fs-extra' import path from 'path' -import type { DbDetails } from '../types' +import type { DbDetails } from '../types.js' -import { warning } from '../utils/log' -import { bundlerPackages, dbPackages, editorPackages } from './packages' +import { warning } from '../utils/log.js' +import { bundlerPackages, dbPackages, editorPackages } from './packages.js' /** Update payload config with necessary imports and adapters */ export async function configurePayloadConfig(args: { diff --git a/packages/create-payload-app/src/lib/create-project.spec.ts b/packages/create-payload-app/src/lib/create-project.spec.ts index fb5d1525e25..c07c7986626 100644 --- a/packages/create-payload-app/src/lib/create-project.spec.ts +++ b/packages/create-payload-app/src/lib/create-project.spec.ts @@ -1,10 +1,10 @@ import fse from 'fs-extra' import path from 'path' -import type { BundlerType, CliArgs, DbType, ProjectTemplate } from '../types' -import { createProject } from './create-project' -import { bundlerPackages, dbPackages, editorPackages } from './packages' +import type { BundlerType, CliArgs, DbType, ProjectTemplate } from '../types.js' +import { createProject } from './create-project.js' +import { bundlerPackages, dbPackages, editorPackages } from './packages.js' import exp from 'constants' -import { getValidTemplates } from './templates' +import { getValidTemplates } from './templates.js' const projectDir = path.resolve(__dirname, './tmp') describe('createProject', () => { diff --git a/packages/create-payload-app/src/lib/create-project.ts b/packages/create-payload-app/src/lib/create-project.ts index 554cb120702..4d62b066604 100644 --- a/packages/create-payload-app/src/lib/create-project.ts +++ b/packages/create-payload-app/src/lib/create-project.ts @@ -5,10 +5,10 @@ import fse from 'fs-extra' import ora from 'ora' import path from 'path' -import type { CliArgs, DbDetails, PackageManager, ProjectTemplate } from '../types' +import type { CliArgs, DbDetails, PackageManager, ProjectTemplate } from '../types.js' -import { error, success, warning } from '../utils/log' -import { configurePayloadConfig } from './configure-payload-config' +import { error, success, warning } from '../utils/log.js' +import { configurePayloadConfig } from './configure-payload-config.js' async function createOrFindProjectDir(projectDir: string): Promise<void> { const pathExists = await fse.pathExists(projectDir) diff --git a/packages/create-payload-app/src/lib/init-next.ts b/packages/create-payload-app/src/lib/init-next.ts index 153333b00b4..6837456dd62 100644 --- a/packages/create-payload-app/src/lib/init-next.ts +++ b/packages/create-payload-app/src/lib/init-next.ts @@ -1,18 +1,26 @@ import type { CompilerOptions } from 'typescript' import chalk from 'chalk' -import * as CommentJson from 'comment-json' +import { parse, stringify } from 'comment-json' import { detect } from 'detect-package-manager' import execa from 'execa' import fs from 'fs' import fse from 'fs-extra' import globby from 'globby' import path from 'path' +import { promisify } from 'util' +const readFile = promisify(fs.readFile) +const writeFile = promisify(fs.writeFile) -import type { CliArgs } from '../types' +const filename = fileURLToPath(import.meta.url) +const dirname = path.dirname(filename) -import { copyRecursiveSync } from '../utils/copy-recursive-sync' -import { error, info, debug as origDebug, success, warning } from '../utils/log' +import { fileURLToPath } from 'node:url' + +import type { CliArgs } from '../types.js' + +import { copyRecursiveSync } from '../utils/copy-recursive-sync.js' +import { error, info, debug as origDebug, success, warning } from '../utils/log.js' type InitNextArgs = Pick<CliArgs, '--debug'> & { projectDir?: string @@ -45,13 +53,13 @@ export async function initNext(args: InitNextArgs): Promise<InitNextResult> { ${chalk.bold(`Wrap your existing next.config.js with the withPayload function. Here is an example:`)} - const { withPayload } = require("@payloadcms/next"); + import withPayload from '@payloadcms/next/withPayload' const nextConfig = { - // Your Next.js config - }; + // Your Next.js config here + } - module.exports = withPayload(nextConfig); + export default withPayload(nextConfig) ` @@ -62,10 +70,10 @@ export async function initNext(args: InitNextArgs): Promise<InitNextResult> { async function addPayloadConfigToTsConfig(projectDir: string) { const tsConfigPath = path.resolve(projectDir, 'tsconfig.json') - const userTsConfigContent = await fse.readFile(tsConfigPath, { + const userTsConfigContent = await readFile(tsConfigPath, { encoding: 'utf8', }) - const userTsConfig = CommentJson.parse(userTsConfigContent) as { + const userTsConfig = parse(userTsConfigContent) as { compilerOptions?: CompilerOptions } if (!userTsConfig.compilerOptions && !('extends' in userTsConfig)) { @@ -77,7 +85,7 @@ async function addPayloadConfigToTsConfig(projectDir: string) { ...(userTsConfig.compilerOptions.paths || {}), '@payload-config': ['./payload.config.ts'], } - await fse.writeFile(tsConfigPath, CommentJson.stringify(userTsConfig, null, 2)) + await writeFile(tsConfigPath, stringify(userTsConfig, null, 2), { encoding: 'utf8' }) } } @@ -96,6 +104,11 @@ async function applyPayloadTemplateFiles(args: InitNextArgs): Promise<InitNextRe // Next.js configs can be next.config.js, next.config.mjs, etc. const foundConfig = (await globby('next.config.*js', { cwd: projectDir }))?.[0] + + if (!foundConfig) { + throw new Error(`No next.config.js found at ${projectDir}`) + } + const nextConfigPath = path.resolve(projectDir, foundConfig) if (!fs.existsSync(nextConfigPath)) { return { @@ -107,9 +120,9 @@ async function applyPayloadTemplateFiles(args: InitNextArgs): Promise<InitNextRe } const templateFilesPath = - __dirname.endsWith('dist') || useDistFiles - ? path.resolve(__dirname, '../..', 'dist/app') - : path.resolve(__dirname, '../../../../app') + dirname.endsWith('dist') || useDistFiles + ? path.resolve(dirname, '../..', 'dist/app') + : path.resolve(dirname, '../../../../app') if (debug) logDebug(`Using template files from: ${templateFilesPath}`) @@ -152,7 +165,6 @@ async function installDeps(projectDir: string) { '@payloadcms/db-mongodb', '@payloadcms/next', '@payloadcms/richtext-slate', - '@payloadcms/ui', ].map((pkg) => `${pkg}@alpha`) let exitCode = 0 diff --git a/packages/create-payload-app/src/lib/packages.ts b/packages/create-payload-app/src/lib/packages.ts index 2c936e92973..1511dd2e715 100644 --- a/packages/create-payload-app/src/lib/packages.ts +++ b/packages/create-payload-app/src/lib/packages.ts @@ -1,4 +1,4 @@ -import type { BundlerType, DbType, EditorType } from '../types' +import type { BundlerType, DbType, EditorType } from '../types.js' type DbAdapterReplacement = { configReplacement: string[] diff --git a/packages/create-payload-app/src/lib/parse-project-name.ts b/packages/create-payload-app/src/lib/parse-project-name.ts index be01c0582b3..75448a04790 100644 --- a/packages/create-payload-app/src/lib/parse-project-name.ts +++ b/packages/create-payload-app/src/lib/parse-project-name.ts @@ -1,6 +1,6 @@ import prompts from 'prompts' -import type { CliArgs } from '../types' +import type { CliArgs } from '../types.js' export async function parseProjectName(args: CliArgs): Promise<string> { if (args['--name']) return args['--name'] @@ -9,8 +9,8 @@ export async function parseProjectName(args: CliArgs): Promise<string> { const response = await prompts( { name: 'value', - message: 'Project name?', type: 'text', + message: 'Project name?', validate: (value: string) => !!value.length, }, { diff --git a/packages/create-payload-app/src/lib/parse-template.ts b/packages/create-payload-app/src/lib/parse-template.ts index 845ef114b01..29b51975189 100644 --- a/packages/create-payload-app/src/lib/parse-template.ts +++ b/packages/create-payload-app/src/lib/parse-template.ts @@ -1,6 +1,6 @@ import prompts from 'prompts' -import type { CliArgs, ProjectTemplate } from '../types' +import type { CliArgs, ProjectTemplate } from '../types.js' export async function parseTemplate( args: CliArgs, @@ -16,6 +16,7 @@ export async function parseTemplate( const response = await prompts( { name: 'value', + type: 'select', choices: validTemplates.map((p) => { return { description: p.description, @@ -24,7 +25,6 @@ export async function parseTemplate( } }), message: 'Choose project template', - type: 'select', validate: (value: string) => !!value.length, }, { diff --git a/packages/create-payload-app/src/lib/select-db.ts b/packages/create-payload-app/src/lib/select-db.ts index 0bd68333c68..130930bc12f 100644 --- a/packages/create-payload-app/src/lib/select-db.ts +++ b/packages/create-payload-app/src/lib/select-db.ts @@ -1,7 +1,7 @@ import slugify from '@sindresorhus/slugify' import prompts from 'prompts' -import type { CliArgs, DbDetails, DbType } from '../types' +import type { CliArgs, DbDetails, DbType } from '../types.js' type DbChoice = { dbConnectionPrefix: `${string}/` @@ -37,6 +37,7 @@ export async function selectDb(args: CliArgs, projectName: string): Promise<DbDe const dbTypeRes = await prompts( { name: 'value', + type: 'select', choices: Object.values(dbChoiceRecord).map((dbChoice) => { return { title: dbChoice.title, @@ -44,7 +45,6 @@ export async function selectDb(args: CliArgs, projectName: string): Promise<DbDe } }), message: 'Select a database', - type: 'select', validate: (value: string) => !!value.length, }, { @@ -61,11 +61,11 @@ export async function selectDb(args: CliArgs, projectName: string): Promise<DbDe const dbUriRes = await prompts( { name: 'value', + type: 'text', initial: `${dbChoice.dbConnectionPrefix}${ projectName === '.' ? `payload-${getRandomDigitSuffix()}` : slugify(projectName) }`, message: `Enter ${dbChoice.title.split(' ')[0]} connection string`, // strip beta from title - type: 'text', validate: (value: string) => !!value.length, }, { @@ -76,8 +76,8 @@ export async function selectDb(args: CliArgs, projectName: string): Promise<DbDe ) return { - dbUri: dbUriRes.value, type: dbChoice.value, + dbUri: dbUriRes.value, } } diff --git a/packages/create-payload-app/src/lib/templates.ts b/packages/create-payload-app/src/lib/templates.ts index b38db7e9ff3..958d0c4dfe0 100644 --- a/packages/create-payload-app/src/lib/templates.ts +++ b/packages/create-payload-app/src/lib/templates.ts @@ -1,6 +1,6 @@ -import type { ProjectTemplate } from '../types' +import type { ProjectTemplate } from '../types.js' -import { error, info } from '../utils/log' +import { error, info } from '../utils/log.js' export function validateTemplate(templateName: string): boolean { const validTemplates = getValidTemplates() @@ -16,38 +16,38 @@ export function getValidTemplates(): ProjectTemplate[] { return [ { name: 'blank', - description: 'Blank Template', type: 'starter', + description: 'Blank Template', url: 'https://github.com/payloadcms/payload/templates/blank', }, { name: 'website', - description: 'Website Template', type: 'starter', + description: 'Website Template', url: 'https://github.com/payloadcms/payload/templates/website', }, { name: 'ecommerce', - description: 'E-commerce Template', type: 'starter', + description: 'E-commerce Template', url: 'https://github.com/payloadcms/payload/templates/ecommerce', }, { name: 'plugin', - description: 'Template for creating a Payload plugin', type: 'plugin', + description: 'Template for creating a Payload plugin', url: 'https://github.com/payloadcms/payload-plugin-template', }, { name: 'payload-demo', - description: 'Payload demo site at https://demo.payloadcms.com', type: 'starter', + description: 'Payload demo site at https://demo.payloadcms.com', url: 'https://github.com/payloadcms/public-demo', }, { name: 'payload-website', - description: 'Payload website CMS at https://payloadcms.com', type: 'starter', + description: 'Payload website CMS at https://payloadcms.com', url: 'https://github.com/payloadcms/website-cms', }, ] diff --git a/packages/create-payload-app/src/lib/write-env-file.ts b/packages/create-payload-app/src/lib/write-env-file.ts index 566c98af12e..6244166b4a8 100644 --- a/packages/create-payload-app/src/lib/write-env-file.ts +++ b/packages/create-payload-app/src/lib/write-env-file.ts @@ -1,9 +1,9 @@ import fs from 'fs-extra' import path from 'path' -import type { ProjectTemplate } from '../types' +import type { ProjectTemplate } from '../types.js' -import { error, success } from '../utils/log' +import { error, success } from '../utils/log.js' /** Parse and swap .env.example values and write .env */ export async function writeEnvFile(args: { diff --git a/packages/create-payload-app/src/main.ts b/packages/create-payload-app/src/main.ts index 01190332cbc..38cf29c2b41 100644 --- a/packages/create-payload-app/src/main.ts +++ b/packages/create-payload-app/src/main.ts @@ -2,18 +2,18 @@ import slugify from '@sindresorhus/slugify' import arg from 'arg' import commandExists from 'command-exists' -import type { CliArgs, PackageManager } from './types' - -import { createProject } from './lib/create-project' -import { generateSecret } from './lib/generate-secret' -import { initNext } from './lib/init-next' -import { parseProjectName } from './lib/parse-project-name' -import { parseTemplate } from './lib/parse-template' -import { selectDb } from './lib/select-db' -import { getValidTemplates, validateTemplate } from './lib/templates' -import { writeEnvFile } from './lib/write-env-file' -import { error, success } from './utils/log' -import { helpMessage, successMessage, welcomeMessage } from './utils/messages' +import type { CliArgs, PackageManager } from './types.js' + +import { createProject } from './lib/create-project.js' +import { generateSecret } from './lib/generate-secret.js' +import { initNext } from './lib/init-next.js' +import { parseProjectName } from './lib/parse-project-name.js' +import { parseTemplate } from './lib/parse-template.js' +import { selectDb } from './lib/select-db.js' +import { getValidTemplates, validateTemplate } from './lib/templates.js' +import { writeEnvFile } from './lib/write-env-file.js' +import { error, success } from './utils/log.js' +import { helpMessage, successMessage, welcomeMessage } from './utils/messages.js' export class Main { args: CliArgs diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 716338e668b..31b1b037b9b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -256,6 +256,9 @@ importers: tempfile: specifier: ^3.0.0 version: 3.0.0 + tempy: + specifier: ^1.0.1 + version: 1.0.1 ts-node: specifier: 10.9.1 version: 10.9.1(@swc/[email protected])(@types/[email protected])([email protected]) @@ -341,9 +344,6 @@ importers: '@types/prompts': specifier: ^2.4.1 version: 2.4.9 - ts-jest: - specifier: ^29.1.0 - version: 29.1.2(@babel/[email protected])([email protected])([email protected])([email protected]) packages/db-mongodb: dependencies: @@ -6769,6 +6769,14 @@ packages: - supports-color dev: true + /[email protected]: + resolution: {integrity: sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==} + engines: {node: '>=8'} + dependencies: + clean-stack: 2.2.0 + indent-string: 4.0.0 + dev: true + /[email protected]([email protected]): resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} peerDependencies: @@ -6944,7 +6952,6 @@ packages: /[email protected]: resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==} engines: {node: '>=8'} - dev: false /[email protected]: resolution: {integrity: sha512-VizNcj/RGJiUyQBgzwxzE5oHdeuXY5hSbbmKMlphj1cy1Vl7Pn2asCGbSrru6hSQjmCzqTBPVWAF/whmEOVHbw==} @@ -7594,6 +7601,11 @@ packages: resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==} dev: false + /[email protected]: + resolution: {integrity: sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==} + engines: {node: '>=6'} + dev: true + /[email protected]: resolution: {integrity: sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==} engines: {node: '>=10'} @@ -8160,6 +8172,11 @@ packages: resolution: {integrity: sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==} dev: false + /[email protected]: + resolution: {integrity: sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==} + engines: {node: '>=8'} + dev: true + /[email protected]: resolution: {integrity: sha512-x8dy3RnvYdlUcPOjkEHqozhiwzKNSq7GcPuXFbnyMOCHxX8V3OgIg/pYuabl2sbUPfIJaeAQB7PMOK8DFIdoRA==} engines: {node: '>=12'} @@ -8630,6 +8647,20 @@ packages: hasBin: true dev: false + /[email protected]: + resolution: {integrity: sha512-ua8BhapfP0JUJKC/zV9yHHDW/rDoDxP4Zhn3AkA6/xT6gY7jYXJiaeyBZznYVujhZZET+UgcbZiQ7sN3WqcImg==} + engines: {node: '>=10'} + dependencies: + globby: 11.1.0 + graceful-fs: 4.2.11 + is-glob: 4.0.3 + is-path-cwd: 2.2.0 + is-path-inside: 3.0.3 + p-map: 4.0.0 + rimraf: 3.0.2 + slash: 3.0.0 + dev: true + /[email protected]: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -8703,7 +8734,6 @@ packages: engines: {node: '>=8'} dependencies: path-type: 4.0.0 - dev: false /[email protected]: resolution: {integrity: sha512-GYqKi1aH7PJXxdhTeZBFrg8vUBeKXi+cNprXsC1kpJcbcVnV9wBsrOu1cQEdG0WeQwlfHiy3XvnKfIrJ2R0NzQ==} @@ -10476,7 +10506,6 @@ packages: ignore: 5.3.1 merge2: 1.4.1 slash: 3.0.0 - dev: false /[email protected]: resolution: {integrity: sha512-jOMLD2Z7MAhyG8aJpNOpmziMOP4rPLcc95oQPKXBazW82z+CEgPFBQvEpRUa1KeIMUJo4Wsm+q6uzO/Q/4BksQ==} @@ -11196,6 +11225,11 @@ packages: resolution: {integrity: sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==} engines: {node: '>=8'} + /[email protected]: + resolution: {integrity: sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ==} + engines: {node: '>=6'} + dev: true + /[email protected]: resolution: {integrity: sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==} engines: {node: '>=8'} @@ -13573,6 +13607,13 @@ packages: p-limit: 4.0.0 dev: true + /[email protected]: + resolution: {integrity: sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==} + engines: {node: '>=10'} + dependencies: + aggregate-error: 3.1.0 + dev: true + /[email protected]: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} @@ -13737,7 +13778,6 @@ packages: /[email protected]: resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} engines: {node: '>=8'} - dev: false /[email protected]: resolution: {integrity: sha512-5HviZNaZcfqP95rwpv+1HDgUamezbqdSYTyzjTvwtJSnIH+3vnbmWsItli8OFEndS984VT55M3jduxZbX351gg==} @@ -16449,6 +16489,17 @@ packages: uuid: 3.4.0 dev: true + /[email protected]: + resolution: {integrity: sha512-biM9brNqxSc04Ee71hzFbryD11nX7VPhQQY32AdDmjFvodsRFz/3ufeoTZ6uYkRFfGo188tENcASNs3vTdsM0w==} + engines: {node: '>=10'} + dependencies: + del: 6.1.1 + is-stream: 2.0.1 + temp-dir: 2.0.0 + type-fest: 0.16.0 + unique-string: 2.0.0 + dev: true + /[email protected]: resolution: {integrity: sha512-un0FmiRUQNr5PJqy9kP7c40F5BOfpGlYTrxonDChEZB7pzZxRNp/bt+ymiy9/npwXya9KH99nJ/GXFIiUkYGFQ==} engines: {node: '>=8'} @@ -16890,6 +16941,11 @@ packages: resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==} engines: {node: '>=4'} + /[email protected]: + resolution: {integrity: sha512-eaBzG6MxNzEn9kiwvtre90cXaNLkmadMWa1zQMs3XORCXNbsH/OewwbxC5ia9dCxIxnTAsSxXJaa/p5y8DlvJg==} + engines: {node: '>=10'} + dev: true + /[email protected]: resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} engines: {node: '>=10'} @@ -17024,6 +17080,13 @@ packages: engines: {node: '>=18'} dev: true + /[email protected]: + resolution: {integrity: sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==} + engines: {node: '>=8'} + dependencies: + crypto-random-string: 2.0.0 + dev: true + /[email protected]: resolution: {integrity: sha512-VGXBUVwxKMBUznyffQweQABPRRW1vHZAbadFZud4pLFAqRGvv/96vafgjWFqzourzr8YonlQiPgH0YCJfawoGQ==} engines: {node: '>=12'} diff --git a/test/create-payload-app/int.spec.ts b/test/create-payload-app/int.spec.ts index 4c6195a58b6..717f24fc253 100644 --- a/test/create-payload-app/int.spec.ts +++ b/test/create-payload-app/int.spec.ts @@ -1,9 +1,11 @@ import type { CompilerOptions } from 'typescript' import * as CommentJson from 'comment-json' +import execa from 'execa' import fs from 'fs' import path from 'path' import shelljs from 'shelljs' +import tempy from 'tempy' import { fileURLToPath } from 'url' import { promisify } from 'util' @@ -12,12 +14,13 @@ const filename = fileURLToPath(import.meta.url) const dirname = path.dirname(filename) const readFile = promisify(fs.readFile) +const writeFile = promisify(fs.writeFile) + +const commonNextCreateParams = '--typescript --eslint --no-tailwind --app --import-alias="@/*"' const nextCreateCommands: Partial<Record<'noSrcDir' | 'srcDir', string>> = { - srcDir: - 'pnpm create next-app@latest . --typescript --eslint --no-tailwind --app --import-alias="@/*" --src-dir', - noSrcDir: - 'pnpm create next-app@latest . --typescript --eslint --no-tailwind --app --import-alias="@/*" --no-src-dir', + noSrcDir: `pnpm create next-app@latest . ${commonNextCreateParams} --no-src-dir`, + srcDir: `pnpm create next-app@latest . ${commonNextCreateParams} --src-dir`, } describe('create-payload-app', () => { @@ -34,9 +37,8 @@ describe('create-payload-app', () => { }) describe.each(Object.keys(nextCreateCommands))(`--init-next with %s`, (nextCmdKey) => { - const projectDir = path.resolve(dirname, 'test-app') - - beforeEach(() => { + const projectDir = tempy.directory() + beforeEach(async () => { if (fs.existsSync(projectDir)) { fs.rmdirSync(projectDir, { recursive: true }) } @@ -47,7 +49,20 @@ describe('create-payload-app', () => { } // Create a new Next.js project with default options - shelljs.exec(nextCreateCommands[nextCmdKey], { cwd: projectDir }) + console.log(`Running: ${nextCreateCommands[nextCmdKey]} in ${projectDir}`) + const [cmd, ...args] = nextCreateCommands[nextCmdKey].split(' ') + const { exitCode, stderr } = await execa(cmd, [...args], { cwd: projectDir }) + if (exitCode !== 0) { + console.error({ exitCode, stderr }) + } + + // WARNING: Big WTF here. Replace improper path string inside tsconfig.json. + // For some reason two double quotes are used for the src path when executed in the test environment. + // This is likely ESM-related + const tsConfigPath = path.resolve(projectDir, 'tsconfig.json') + let userTsConfigContent = await readFile(tsConfigPath, { encoding: 'utf8' }) + userTsConfigContent = userTsConfigContent.replace('""@/*""', '"@/*"') + await writeFile(tsConfigPath, userTsConfigContent, { encoding: 'utf8' }) }) afterEach(() => { @@ -78,9 +93,11 @@ describe('create-payload-app', () => { const userTsConfig = CommentJson.parse(userTsConfigContent) as { compilerOptions?: CompilerOptions } - expect(userTsConfig.compilerOptions.paths?.['@payload-config']).toEqual([ + expect(userTsConfig.compilerOptions.paths?.['@payload-config']).toStrictEqual([ './payload.config.ts', ]) + + // TODO: Start the Next.js app and check if it runs }) }) })
92f458dad2b29af6632062b606a9de4167b49722
2024-05-29 23:31:13
Jacob Fletcher
feat(next,ui): improves loading states (#6434)
false
improves loading states (#6434)
feat
diff --git a/next.config.mjs b/next.config.mjs index 29911443e46..dc192996d8f 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -17,7 +17,7 @@ export default withBundleAnalyzer( ignoreBuildErrors: true, }, experimental: { - reactCompiler: false + reactCompiler: false, }, async redirects() { return [ diff --git a/packages/next/src/layouts/Root/index.tsx b/packages/next/src/layouts/Root/index.tsx index 54c8857ef74..118adb89e93 100644 --- a/packages/next/src/layouts/Root/index.tsx +++ b/packages/next/src/layouts/Root/index.tsx @@ -57,11 +57,13 @@ export const RootLayout = async ({ }) const payload = await getPayloadHMR({ config }) + const i18n: I18nClient = await initI18n({ config: config.i18n, context: 'client', language: languageCode, }) + const clientConfig = await createClientConfig({ config, t: i18n.t }) const dir = (rtlLanguages as unknown as AcceptedLanguages[]).includes(languageCode) diff --git a/packages/next/src/utilities/initPage/index.ts b/packages/next/src/utilities/initPage/index.ts index ec2c5795dfa..13dfce30137 100644 --- a/packages/next/src/utilities/initPage/index.ts +++ b/packages/next/src/utilities/initPage/index.ts @@ -47,6 +47,20 @@ export const initPage = async ({ language, }) + const languageOptions = Object.entries(payload.config.i18n.supportedLanguages || {}).reduce( + (acc, [language, languageConfig]) => { + if (Object.keys(payload.config.i18n.supportedLanguages).includes(language)) { + acc.push({ + label: languageConfig.translations.general.thisLanguage, + value: language, + }) + } + + return acc + }, + [], + ) + const req = await createLocalReq( { fallbackLocale: null, @@ -98,6 +112,7 @@ export const initPage = async ({ cookies, docID, globalConfig, + languageOptions, locale, permissions, req, diff --git a/packages/next/src/utilities/initPage/shared.ts b/packages/next/src/utilities/initPage/shared.ts index 96d1004fc1e..c311a3c91ce 100644 --- a/packages/next/src/utilities/initPage/shared.ts +++ b/packages/next/src/utilities/initPage/shared.ts @@ -1,7 +1,6 @@ import type { SanitizedConfig } from 'payload/types' const authRouteKeys: (keyof SanitizedConfig['admin']['routes'])[] = [ - 'account', 'createFirstUser', 'forgot', 'login', diff --git a/packages/next/src/views/API/LocaleSelector/index.tsx b/packages/next/src/views/API/LocaleSelector/index.tsx new file mode 100644 index 00000000000..f451456dd72 --- /dev/null +++ b/packages/next/src/views/API/LocaleSelector/index.tsx @@ -0,0 +1,23 @@ +import { Select } from '@payloadcms/ui/fields/Select' +import { useTranslation } from '@payloadcms/ui/providers/Translation' +import React from 'react' + +export const LocaleSelector: React.FC<{ + localeOptions: { + label: Record<string, string> | string + value: string + }[] + onChange: (value: string) => void +}> = ({ localeOptions, onChange }) => { + const { t } = useTranslation() + + return ( + <Select + label={t('general:locale')} + name="locale" + onChange={(value) => onChange(value)} + options={localeOptions} + path="locale" + /> + ) +} diff --git a/packages/next/src/views/API/index.client.tsx b/packages/next/src/views/API/index.client.tsx index 909db51a2e0..862081a1ef9 100644 --- a/packages/next/src/views/API/index.client.tsx +++ b/packages/next/src/views/API/index.client.tsx @@ -4,7 +4,6 @@ import { CopyToClipboard } from '@payloadcms/ui/elements/CopyToClipboard' import { Gutter } from '@payloadcms/ui/elements/Gutter' import { Checkbox } from '@payloadcms/ui/fields/Checkbox' import { NumberField as NumberInput } from '@payloadcms/ui/fields/Number' -import { Select } from '@payloadcms/ui/fields/Select' import { Form } from '@payloadcms/ui/forms/Form' import { MinimizeMaximize } from '@payloadcms/ui/icons/MinimizeMaximize' import { SetViewActions } from '@payloadcms/ui/providers/Actions' @@ -19,6 +18,7 @@ import * as React from 'react' import { toast } from 'react-toastify' import { SetDocumentStepNav } from '../Edit/Default/SetDocumentStepNav/index.js' +import { LocaleSelector } from './LocaleSelector/index.js' import { RenderJSON } from './RenderJSON/index.js' import './index.scss' @@ -173,15 +173,7 @@ export const APIViewClient: React.FC = () => { path="authenticated" /> </div> - {localeOptions && ( - <Select - label={t('general:locale')} - name="locale" - onChange={(value) => setLocale(value)} - options={localeOptions} - path="locale" - /> - )} + {localeOptions && <LocaleSelector localeOptions={localeOptions} onChange={setLocale} />} <NumberInput label={t('general:depth')} max={10} diff --git a/packages/next/src/views/Account/Settings/LanguageSelector.tsx b/packages/next/src/views/Account/Settings/LanguageSelector.tsx new file mode 100644 index 00000000000..7c8a5cbdc18 --- /dev/null +++ b/packages/next/src/views/Account/Settings/LanguageSelector.tsx @@ -0,0 +1,25 @@ +'use client' +import type { LanguageOptions } from 'payload/types' + +import { ReactSelect } from '@payloadcms/ui/elements/ReactSelect' +import { useTranslation } from '@payloadcms/ui/providers/Translation' +import React from 'react' + +export const LanguageSelector: React.FC<{ + languageOptions: LanguageOptions +}> = (props) => { + const { languageOptions } = props + + const { i18n, switchLanguage } = useTranslation() + + return ( + <ReactSelect + inputId="language-select" + onChange={async ({ value }) => { + await switchLanguage(value) + }} + options={languageOptions} + value={languageOptions.find((language) => language.value === i18n.language)} + /> + ) +} diff --git a/packages/next/src/views/Account/Settings/index.tsx b/packages/next/src/views/Account/Settings/index.tsx index aaf9c3657e4..6af4bc9101c 100644 --- a/packages/next/src/views/Account/Settings/index.tsx +++ b/packages/next/src/views/Account/Settings/index.tsx @@ -1,34 +1,28 @@ -'use client' -import { ReactSelect } from '@payloadcms/ui/elements/ReactSelect' +import type { I18n } from '@payloadcms/translations' +import type { LanguageOptions } from 'payload/types' + import { FieldLabel } from '@payloadcms/ui/forms/FieldLabel' -import { useTranslation } from '@payloadcms/ui/providers/Translation' import React from 'react' import { ToggleTheme } from '../ToggleTheme/index.js' +import { LanguageSelector } from './LanguageSelector.js' import './index.scss' const baseClass = 'payload-settings' export const Settings: React.FC<{ className?: string + i18n: I18n + languageOptions: LanguageOptions }> = (props) => { - const { className } = props - - const { i18n, languageOptions, switchLanguage, t } = useTranslation() + const { className, i18n, languageOptions } = props return ( <div className={[baseClass, className].filter(Boolean).join(' ')}> - <h3>{t('general:payloadSettings')}</h3> + <h3>{i18n.t('general:payloadSettings')}</h3> <div className={`${baseClass}__language`}> - <FieldLabel htmlFor="language-select" label={t('general:language')} /> - <ReactSelect - inputId="language-select" - onChange={async ({ value }) => { - await switchLanguage(value) - }} - options={languageOptions} - value={languageOptions.find((language) => language.value === i18n.language)} - /> + <FieldLabel htmlFor="language-select" label={i18n.t('general:language')} /> + <LanguageSelector languageOptions={languageOptions} /> </div> <ToggleTheme /> </div> diff --git a/packages/next/src/views/Account/index.tsx b/packages/next/src/views/Account/index.tsx index a840a6118da..07eab970b5f 100644 --- a/packages/next/src/views/Account/index.tsx +++ b/packages/next/src/views/Account/index.tsx @@ -9,6 +9,7 @@ import { FormQueryParamsProvider } from '@payloadcms/ui/providers/FormQueryParam import { notFound } from 'next/navigation.js' import React from 'react' +import { getDocumentData } from '../Document/getDocumentData.js' import { getDocumentPermissions } from '../Document/getDocumentPermissions.js' import { EditView } from '../Edit/index.js' import { Settings } from './Settings/index.js' @@ -21,6 +22,7 @@ export const Account: React.FC<AdminViewProps> = async ({ searchParams, }) => { const { + languageOptions, locale, permissions, req, @@ -49,6 +51,13 @@ export const Account: React.FC<AdminViewProps> = async ({ req, }) + const { data, formState } = await getDocumentData({ + id: user.id, + collectionConfig, + locale, + req, + }) + const viewComponentProps: ServerSideEditViewProps = { initPageResult, params, @@ -58,7 +67,7 @@ export const Account: React.FC<AdminViewProps> = async ({ return ( <DocumentInfoProvider - AfterFields={<Settings />} + AfterFields={<Settings i18n={i18n} languageOptions={languageOptions} />} action={`${serverURL}${api}/${userSlug}${user?.id ? `/${user.id}` : ''}`} apiURL={`${serverURL}${api}/${userSlug}${user?.id ? `/${user.id}` : ''}`} collectionSlug={userSlug} @@ -66,6 +75,8 @@ export const Account: React.FC<AdminViewProps> = async ({ hasPublishPermission={hasPublishPermission} hasSavePermission={hasSavePermission} id={user?.id.toString()} + initialData={data} + initialState={formState} isEditing > <DocumentHeader diff --git a/packages/next/src/views/Dashboard/Default/index.client.tsx b/packages/next/src/views/Dashboard/Default/index.client.tsx deleted file mode 100644 index 5bd773019fe..00000000000 --- a/packages/next/src/views/Dashboard/Default/index.client.tsx +++ /dev/null @@ -1,144 +0,0 @@ -'use client' -import type { EntityToGroup, Group } from '@payloadcms/ui/utilities/groupNavItems' -import type { Permissions } from 'payload/auth' -import type { VisibleEntities } from 'payload/types' - -import { getTranslation } from '@payloadcms/translations' -import { Button } from '@payloadcms/ui/elements/Button' -import { Card } from '@payloadcms/ui/elements/Card' -import { SetViewActions } from '@payloadcms/ui/providers/Actions' -import { useAuth } from '@payloadcms/ui/providers/Auth' -import { useConfig } from '@payloadcms/ui/providers/Config' -import { useTranslation } from '@payloadcms/ui/providers/Translation' -import { EntityType, groupNavItems } from '@payloadcms/ui/utilities/groupNavItems' -import React, { Fragment, useEffect, useState } from 'react' - -import './index.scss' - -const baseClass = 'dashboard' - -export const DefaultDashboardClient: React.FC<{ - Link: React.ComponentType - permissions: Permissions - visibleEntities: VisibleEntities -}> = ({ Link, permissions, visibleEntities }) => { - const config = useConfig() - - const { - collections: collectionsConfig, - globals: globalsConfig, - routes: { admin }, - } = config - - const { user } = useAuth() - - const { i18n, t } = useTranslation() - - const [groups, setGroups] = useState<Group[]>([]) - - useEffect(() => { - const collections = collectionsConfig.filter( - (collection) => - permissions?.collections?.[collection.slug]?.read?.permission && - visibleEntities.collections.includes(collection.slug), - ) - - const globals = globalsConfig.filter( - (global) => - permissions?.globals?.[global.slug]?.read?.permission && - visibleEntities.globals.includes(global.slug), - ) - - setGroups( - groupNavItems( - [ - ...(collections.map((collection) => { - const entityToGroup: EntityToGroup = { - type: EntityType.collection, - entity: collection, - } - - return entityToGroup - }) ?? []), - ...(globals.map((global) => { - const entityToGroup: EntityToGroup = { - type: EntityType.global, - entity: global, - } - - return entityToGroup - }) ?? []), - ], - permissions, - i18n, - ), - ) - }, [permissions, user, i18n, visibleEntities, collectionsConfig, globalsConfig]) - - return ( - <Fragment> - <SetViewActions actions={[]} /> - {groups.map(({ entities, label }, groupIndex) => { - return ( - <div className={`${baseClass}__group`} key={groupIndex}> - <h2 className={`${baseClass}__label`}>{label}</h2> - <ul className={`${baseClass}__card-list`}> - {entities.map(({ type, entity }, entityIndex) => { - let title: string - let buttonAriaLabel: string - let createHREF: string - let href: string - let hasCreatePermission: boolean - - if (type === EntityType.collection) { - title = getTranslation(entity.labels.plural, i18n) - buttonAriaLabel = t('general:showAllLabel', { label: title }) - href = `${admin}/collections/${entity.slug}` - createHREF = `${admin}/collections/${entity.slug}/create` - hasCreatePermission = permissions?.collections?.[entity.slug]?.create?.permission - } - - if (type === EntityType.global) { - title = getTranslation(entity.label, i18n) - buttonAriaLabel = t('general:editLabel', { - label: getTranslation(entity.label, i18n), - }) - href = `${admin}/globals/${entity.slug}` - } - - return ( - <li key={entityIndex}> - <Card - Link={Link} - actions={ - hasCreatePermission && type === EntityType.collection ? ( - <Button - Link={Link} - aria-label={t('general:createNewLabel', { - label: getTranslation(entity.labels.singular, i18n), - })} - buttonStyle="icon-label" - el="link" - icon="plus" - iconStyle="with-border" - round - to={createHREF} - /> - ) : undefined - } - buttonAriaLabel={buttonAriaLabel} - href={href} - id={`card-${entity.slug}`} - title={title} - titleAs="h3" - /> - </li> - ) - })} - </ul> - </div> - ) - })} - </Fragment> - ) -} diff --git a/packages/next/src/views/Dashboard/Default/index.tsx b/packages/next/src/views/Dashboard/Default/index.tsx index 8865dd4c5bb..4c624127949 100644 --- a/packages/next/src/views/Dashboard/Default/index.tsx +++ b/packages/next/src/views/Dashboard/Default/index.tsx @@ -2,20 +2,23 @@ import type { Permissions } from 'payload/auth' import type { ServerProps } from 'payload/config' import type { VisibleEntities } from 'payload/types' +import { getTranslation } from '@payloadcms/translations' +import { Button } from '@payloadcms/ui/elements/Button' +import { Card } from '@payloadcms/ui/elements/Card' import { Gutter } from '@payloadcms/ui/elements/Gutter' import { SetStepNav } from '@payloadcms/ui/elements/StepNav' import { WithServerSideProps } from '@payloadcms/ui/elements/WithServerSideProps' import { SetViewActions } from '@payloadcms/ui/providers/Actions' -import React from 'react' +import { EntityType, type groupNavItems } from '@payloadcms/ui/utilities/groupNavItems' +import React, { Fragment } from 'react' -import { DefaultDashboardClient } from './index.client.js' import './index.scss' const baseClass = 'dashboard' export type DashboardProps = ServerProps & { Link: React.ComponentType<any> - + navGroups?: ReturnType<typeof groupNavItems> permissions: Permissions visibleEntities: VisibleEntities } @@ -24,20 +27,22 @@ export const DefaultDashboard: React.FC<DashboardProps> = (props) => { const { Link, i18n, + i18n: { t }, locale, + navGroups, params, payload: { config: { admin: { components: { afterDashboard, beforeDashboard }, }, + routes: { admin: adminRoute }, }, }, payload, permissions, searchParams, user, - visibleEntities, } = props const BeforeDashboards = Array.isArray(beforeDashboard) @@ -82,12 +87,75 @@ export const DefaultDashboard: React.FC<DashboardProps> = (props) => { <SetViewActions actions={[]} /> <Gutter className={`${baseClass}__wrap`}> {Array.isArray(BeforeDashboards) && BeforeDashboards.map((Component) => Component)} + <Fragment> + <SetViewActions actions={[]} /> + {!navGroups || navGroups?.length === 0 ? ( + <p>no nav groups....</p> + ) : ( + navGroups.map(({ entities, label }, groupIndex) => { + return ( + <div className={`${baseClass}__group`} key={groupIndex}> + <h2 className={`${baseClass}__label`}>{label}</h2> + <ul className={`${baseClass}__card-list`}> + {entities.map(({ type, entity }, entityIndex) => { + let title: string + let buttonAriaLabel: string + let createHREF: string + let href: string + let hasCreatePermission: boolean - <DefaultDashboardClient - Link={Link} - permissions={permissions} - visibleEntities={visibleEntities} - /> + if (type === EntityType.collection) { + title = getTranslation(entity.labels.plural, i18n) + buttonAriaLabel = t('general:showAllLabel', { label: title }) + href = `${adminRoute}/collections/${entity.slug}` + createHREF = `${adminRoute}/collections/${entity.slug}/create` + hasCreatePermission = + permissions?.collections?.[entity.slug]?.create?.permission + } + + if (type === EntityType.global) { + title = getTranslation(entity.label, i18n) + buttonAriaLabel = t('general:editLabel', { + label: getTranslation(entity.label, i18n), + }) + href = `${adminRoute}/globals/${entity.slug}` + } + + return ( + <li key={entityIndex}> + <Card + Link={Link} + actions={ + hasCreatePermission && type === EntityType.collection ? ( + <Button + Link={Link} + aria-label={t('general:createNewLabel', { + label: getTranslation(entity.labels.singular, i18n), + })} + buttonStyle="icon-label" + el="link" + icon="plus" + iconStyle="with-border" + round + to={createHREF} + /> + ) : undefined + } + buttonAriaLabel={buttonAriaLabel} + href={href} + id={`card-${entity.slug}`} + title={title} + titleAs="h3" + /> + </li> + ) + })} + </ul> + </div> + ) + }) + )} + </Fragment> {Array.isArray(AfterDashboards) && AfterDashboards.map((Component) => Component)} </Gutter> </div> diff --git a/packages/next/src/views/Dashboard/index.tsx b/packages/next/src/views/Dashboard/index.tsx index 6a3dce0f9a7..109b35736a4 100644 --- a/packages/next/src/views/Dashboard/index.tsx +++ b/packages/next/src/views/Dashboard/index.tsx @@ -1,7 +1,9 @@ +import type { EntityToGroup } from '@payloadcms/ui/utilities/groupNavItems' import type { AdminViewProps } from 'payload/types' import { HydrateClientUser } from '@payloadcms/ui/elements/HydrateClientUser' import { RenderCustomComponent } from '@payloadcms/ui/elements/RenderCustomComponent' +import { EntityType, groupNavItems } from '@payloadcms/ui/utilities/groupNavItems' import LinkImport from 'next/link.js' import React, { Fragment } from 'react' @@ -28,10 +30,46 @@ export const Dashboard: React.FC<AdminViewProps> = ({ initPageResult, params, se const CustomDashboardComponent = config.admin.components?.views?.Dashboard + const collections = config.collections.filter( + (collection) => + permissions?.collections?.[collection.slug]?.read?.permission && + visibleEntities.collections.includes(collection.slug), + ) + + const globals = config.globals.filter( + (global) => + permissions?.globals?.[global.slug]?.read?.permission && + visibleEntities.globals.includes(global.slug), + ) + + const navGroups = groupNavItems( + [ + ...(collections.map((collection) => { + const entityToGroup: EntityToGroup = { + type: EntityType.collection, + entity: collection, + } + + return entityToGroup + }) ?? []), + ...(globals.map((global) => { + const entityToGroup: EntityToGroup = { + type: EntityType.global, + entity: global, + } + + return entityToGroup + }) ?? []), + ], + permissions, + i18n, + ) + const viewComponentProps: DashboardProps = { Link, i18n, locale, + navGroups, params, payload, permissions, diff --git a/packages/next/src/views/Document/getDocumentData.tsx b/packages/next/src/views/Document/getDocumentData.tsx index 86618374df3..4a2ad0b449a 100644 --- a/packages/next/src/views/Document/getDocumentData.tsx +++ b/packages/next/src/views/Document/getDocumentData.tsx @@ -1,41 +1,45 @@ import type { Data, - Payload, - PayloadRequest, + PayloadRequestWithData, SanitizedCollectionConfig, SanitizedGlobalConfig, } from 'payload/types' +import { buildFormState } from '@payloadcms/ui/utilities/buildFormState' +import { reduceFieldsToValues } from '@payloadcms/ui/utilities/reduceFieldsToValues' + export const getDocumentData = async (args: { collectionConfig?: SanitizedCollectionConfig globalConfig?: SanitizedGlobalConfig id?: number | string locale: Locale - payload: Payload - req: PayloadRequest + req: PayloadRequestWithData }): Promise<Data> => { - const { id, collectionConfig, globalConfig, locale, payload, req } = args - - let data: Data + const { id, collectionConfig, globalConfig, locale, req } = args - if (collectionConfig && id !== undefined && id !== null) { - data = await payload.findByID({ - id, - collection: collectionConfig.slug, - depth: 0, - locale: locale.code, - req, + try { + const formState = await buildFormState({ + req: { + ...req, + data: { + id, + collectionSlug: collectionConfig?.slug, + globalSlug: globalConfig?.slug, + locale: locale.code, + operation: (collectionConfig && id) || globalConfig ? 'update' : 'create', + schemaPath: collectionConfig?.slug || globalConfig?.slug, + }, + }, }) - } - if (globalConfig) { - data = await payload.findGlobal({ - slug: globalConfig.slug, - depth: 0, - locale: locale.code, - req, - }) - } + const data = reduceFieldsToValues(formState, true) - return data + return { + data, + formState, + } + } catch (error) { + console.error('Error getting document data', error) // eslint-disable-line no-console + return {} + } } diff --git a/packages/next/src/views/Document/getViewsFromConfig.tsx b/packages/next/src/views/Document/getViewsFromConfig.tsx index 4dafc9096ec..e5fa589e9fd 100644 --- a/packages/next/src/views/Document/getViewsFromConfig.tsx +++ b/packages/next/src/views/Document/getViewsFromConfig.tsx @@ -7,6 +7,8 @@ import type { SanitizedGlobalConfig, } from 'payload/types' +import { notFound } from 'next/navigation.js' + import { APIView as DefaultAPIView } from '../API/index.js' import { EditView as DefaultEditView } from '../Edit/index.js' import { LivePreviewView as DefaultLivePreviewView } from '../LivePreview/index.js' @@ -68,63 +70,91 @@ export const getViewsFromConfig = ({ const [collectionEntity, collectionSlug, segment3, segment4, segment5, ...remainingSegments] = routeSegments - // `../:id`, or `../create` - switch (routeSegments.length) { - case 3: { - switch (segment3) { - case 'create': { - if ('create' in docPermissions && docPermissions?.create?.permission) { - CustomView = getCustomViewByKey(views, 'Default') - DefaultView = DefaultEditView - } else { - ErrorView = UnauthorizedView + if (!docPermissions?.read?.permission) { + notFound() + } else { + // `../:id`, or `../create` + switch (routeSegments.length) { + case 3: { + switch (segment3) { + case 'create': { + if ('create' in docPermissions && docPermissions?.create?.permission) { + CustomView = getCustomViewByKey(views, 'Default') + DefaultView = DefaultEditView + } else { + ErrorView = UnauthorizedView + } + break } - break - } - default: { - if (docPermissions?.read?.permission) { + default: { CustomView = getCustomViewByKey(views, 'Default') DefaultView = DefaultEditView - } else { - ErrorView = UnauthorizedView + break } - break } + break } - break - } - // `../:id/api`, `../:id/preview`, `../:id/versions`, etc - case 4: { - switch (segment4) { - case 'api': { - if (collectionConfig?.admin?.hideAPIURL !== true) { - CustomView = getCustomViewByKey(views, 'API') - DefaultView = DefaultAPIView + // `../:id/api`, `../:id/preview`, `../:id/versions`, etc + case 4: { + switch (segment4) { + case 'api': { + if (collectionConfig?.admin?.hideAPIURL !== true) { + CustomView = getCustomViewByKey(views, 'API') + DefaultView = DefaultAPIView + } + break } - break - } - case 'preview': { - if (livePreviewEnabled) { - DefaultView = DefaultLivePreviewView + case 'preview': { + if (livePreviewEnabled) { + DefaultView = DefaultLivePreviewView + } + break + } + + case 'versions': { + if (docPermissions?.readVersions?.permission) { + CustomView = getCustomViewByKey(views, 'Versions') + DefaultView = DefaultVersionsView + } else { + ErrorView = UnauthorizedView + } + break + } + + default: { + const baseRoute = [adminRoute, 'collections', collectionSlug, segment3] + .filter(Boolean) + .join('/') + + const currentRoute = [baseRoute, segment4, segment5, ...remainingSegments] + .filter(Boolean) + .join('/') + + CustomView = getCustomViewByRoute({ + baseRoute, + currentRoute, + views, + }) + break } - break } + break + } - case 'versions': { + // `../:id/versions/:version`, etc + default: { + if (segment4 === 'versions') { if (docPermissions?.readVersions?.permission) { - CustomView = getCustomViewByKey(views, 'Versions') - DefaultView = DefaultVersionsView + CustomView = getCustomViewByKey(views, 'Version') + DefaultView = DefaultVersionView } else { ErrorView = UnauthorizedView } - break - } - - default: { - const baseRoute = [adminRoute, 'collections', collectionSlug, segment3] + } else { + const baseRoute = [adminRoute, collectionEntity, collectionSlug, segment3] .filter(Boolean) .join('/') @@ -137,37 +167,9 @@ export const getViewsFromConfig = ({ currentRoute, views, }) - break - } - } - break - } - - // `../:id/versions/:version`, etc - default: { - if (segment4 === 'versions') { - if (docPermissions?.readVersions?.permission) { - CustomView = getCustomViewByKey(views, 'Version') - DefaultView = DefaultVersionView - } else { - ErrorView = UnauthorizedView } - } else { - const baseRoute = [adminRoute, collectionEntity, collectionSlug, segment3] - .filter(Boolean) - .join('/') - - const currentRoute = [baseRoute, segment4, segment5, ...remainingSegments] - .filter(Boolean) - .join('/') - - CustomView = getCustomViewByRoute({ - baseRoute, - currentRoute, - views, - }) + break } - break } } } @@ -185,81 +187,81 @@ export const getViewsFromConfig = ({ // eslint-disable-next-line @typescript-eslint/no-unused-vars const [globalEntity, globalSlug, segment3, ...remainingSegments] = routeSegments - switch (routeSegments.length) { - case 2: { - if (docPermissions?.read?.permission) { + if (!docPermissions?.read?.permission) { + notFound() + } else { + switch (routeSegments.length) { + case 2: { CustomView = getCustomViewByKey(views, 'Default') DefaultView = DefaultEditView - } else { - ErrorView = UnauthorizedView + break } - break - } - case 3: { - // `../:slug/api`, `../:slug/preview`, `../:slug/versions`, etc - switch (segment3) { - case 'api': { - if (globalConfig?.admin?.hideAPIURL !== true) { - CustomView = getCustomViewByKey(views, 'API') - DefaultView = DefaultAPIView + case 3: { + // `../:slug/api`, `../:slug/preview`, `../:slug/versions`, etc + switch (segment3) { + case 'api': { + if (globalConfig?.admin?.hideAPIURL !== true) { + CustomView = getCustomViewByKey(views, 'API') + DefaultView = DefaultAPIView + } + break } - break - } - case 'preview': { - if (livePreviewEnabled) { - DefaultView = DefaultLivePreviewView + case 'preview': { + if (livePreviewEnabled) { + DefaultView = DefaultLivePreviewView + } + break } - break - } - case 'versions': { - if (docPermissions?.readVersions?.permission) { - CustomView = getCustomViewByKey(views, 'Versions') - DefaultView = DefaultVersionsView - } else { - ErrorView = UnauthorizedView + case 'versions': { + if (docPermissions?.readVersions?.permission) { + CustomView = getCustomViewByKey(views, 'Versions') + DefaultView = DefaultVersionsView + } else { + ErrorView = UnauthorizedView + } + break } - break - } - default: { - if (docPermissions?.read?.permission) { - CustomView = getCustomViewByKey(views, 'Default') - DefaultView = DefaultEditView - } else { - ErrorView = UnauthorizedView + default: { + if (docPermissions?.read?.permission) { + CustomView = getCustomViewByKey(views, 'Default') + DefaultView = DefaultEditView + } else { + ErrorView = UnauthorizedView + } + break } - break } + break } - break - } - default: { - // `../:slug/versions/:version`, etc - if (segment3 === 'versions') { - if (docPermissions?.readVersions?.permission) { - CustomView = getCustomViewByKey(views, 'Version') - DefaultView = DefaultVersionView + default: { + // `../:slug/versions/:version`, etc + if (segment3 === 'versions') { + if (docPermissions?.readVersions?.permission) { + CustomView = getCustomViewByKey(views, 'Version') + DefaultView = DefaultVersionView + } else { + ErrorView = UnauthorizedView + } } else { - ErrorView = UnauthorizedView + const baseRoute = [adminRoute, 'globals', globalSlug].filter(Boolean).join('/') + + const currentRoute = [baseRoute, segment3, ...remainingSegments] + .filter(Boolean) + .join('/') + + CustomView = getCustomViewByRoute({ + baseRoute, + currentRoute, + views, + }) } - } else { - const baseRoute = [adminRoute, 'globals', globalSlug].filter(Boolean).join('/') - - const currentRoute = [baseRoute, segment3, ...remainingSegments] - .filter(Boolean) - .join('/') - - CustomView = getCustomViewByRoute({ - baseRoute, - currentRoute, - views, - }) + break } - break } } } diff --git a/packages/next/src/views/Document/index.tsx b/packages/next/src/views/Document/index.tsx index 4c57b3b052d..9b8ab134947 100644 --- a/packages/next/src/views/Document/index.tsx +++ b/packages/next/src/views/Document/index.tsx @@ -63,12 +63,11 @@ export const Document: React.FC<AdminViewProps> = async ({ let apiURL: string let action: string - const data = await getDocumentData({ + const { data, formState } = await getDocumentData({ id, collectionConfig, globalConfig, locale, - payload, req, }) @@ -191,6 +190,8 @@ export const Document: React.FC<AdminViewProps> = async ({ hasPublishPermission={hasPublishPermission} hasSavePermission={hasSavePermission} id={id} + initialData={data} + initialState={formState} isEditing={isEditing} > {!ViewOverride && ( diff --git a/packages/next/src/views/Edit/Default/Auth/APIKey.tsx b/packages/next/src/views/Edit/Default/Auth/APIKey.tsx index 6e6483a4e46..d6607b0183b 100644 --- a/packages/next/src/views/Edit/Default/Auth/APIKey.tsx +++ b/packages/next/src/views/Edit/Default/Auth/APIKey.tsx @@ -25,7 +25,7 @@ export const APIKey: React.FC<{ enabled: boolean; readOnly?: boolean }> = ({ const { t } = useTranslation() const config = useConfig() - const apiKey = useFormFields(([fields]) => fields[path]) + const apiKey = useFormFields(([fields]) => (fields && fields[path]) || null) const validate = (val) => text(val, { diff --git a/packages/next/src/views/Edit/Default/Auth/index.tsx b/packages/next/src/views/Edit/Default/Auth/index.tsx index 208b2638d2f..71fbaa9d253 100644 --- a/packages/next/src/views/Edit/Default/Auth/index.tsx +++ b/packages/next/src/views/Edit/Default/Auth/index.tsx @@ -7,6 +7,7 @@ import { Email } from '@payloadcms/ui/fields/Email' import { Password } from '@payloadcms/ui/fields/Password' import { useFormFields, useFormModified } from '@payloadcms/ui/forms/Form' import { useConfig } from '@payloadcms/ui/providers/Config' +import { useDocumentInfo } from '@payloadcms/ui/providers/DocumentInfo' import { useTranslation } from '@payloadcms/ui/providers/Translation' import React, { useCallback, useEffect, useState } from 'react' import { toast } from 'react-toastify' @@ -32,10 +33,11 @@ export const Auth: React.FC<Props> = (props) => { } = props const [changingPassword, setChangingPassword] = useState(requirePassword) - const enableAPIKey = useFormFields(([fields]) => fields.enableAPIKey) + const enableAPIKey = useFormFields(([fields]) => (fields && fields?.enableAPIKey) || null) const dispatchFields = useFormFields((reducer) => reducer[1]) const modified = useFormModified() const { i18n, t } = useTranslation() + const { isInitializing } = useDocumentInfo() const { routes: { api }, @@ -85,12 +87,15 @@ export const Auth: React.FC<Props> = (props) => { return null } + const disabled = readOnly || isInitializing + return ( <div className={[baseClass, className].filter(Boolean).join(' ')}> {!disableLocalStrategy && ( <React.Fragment> <Email autoComplete="email" + disabled={disabled} label={t('general:email')} name="email" readOnly={readOnly} @@ -100,7 +105,7 @@ export const Auth: React.FC<Props> = (props) => { <div className={`${baseClass}__changing-password`}> <Password autoComplete="off" - disabled={readOnly} + disabled={disabled} label={t('authentication:newPassword')} name="password" required @@ -108,12 +113,11 @@ export const Auth: React.FC<Props> = (props) => { <ConfirmPassword disabled={readOnly} /> </div> )} - <div className={`${baseClass}__controls`}> {changingPassword && !requirePassword && ( <Button buttonStyle="secondary" - disabled={readOnly} + disabled={disabled} onClick={() => handleChangePassword(false)} size="small" > @@ -123,7 +127,7 @@ export const Auth: React.FC<Props> = (props) => { {!changingPassword && !requirePassword && ( <Button buttonStyle="secondary" - disabled={readOnly} + disabled={disabled} id="change-password" onClick={() => handleChangePassword(true)} size="small" @@ -134,7 +138,7 @@ export const Auth: React.FC<Props> = (props) => { {operation === 'update' && ( <Button buttonStyle="secondary" - disabled={readOnly} + disabled={disabled} onClick={() => unlock()} size="small" > @@ -147,6 +151,7 @@ export const Auth: React.FC<Props> = (props) => { {useAPIKey && ( <div className={`${baseClass}__api-key`}> <Checkbox + disabled={disabled} label={t('authentication:enableAPIKey')} name="enableAPIKey" readOnly={readOnly} @@ -155,7 +160,12 @@ export const Auth: React.FC<Props> = (props) => { </div> )} {verify && ( - <Checkbox label={t('authentication:verified')} name="_verified" readOnly={readOnly} /> + <Checkbox + disabled={disabled} + label={t('authentication:verified')} + name="_verified" + readOnly={readOnly} + /> )} </div> ) diff --git a/packages/next/src/views/Edit/Default/SetDocumentStepNav/index.tsx b/packages/next/src/views/Edit/Default/SetDocumentStepNav/index.tsx index ed00d67dfb6..6644bf0b19c 100644 --- a/packages/next/src/views/Edit/Default/SetDocumentStepNav/index.tsx +++ b/packages/next/src/views/Edit/Default/SetDocumentStepNav/index.tsx @@ -24,7 +24,7 @@ export const SetDocumentStepNav: React.FC<{ const view: string | undefined = props?.view || undefined - const { isEditing, title } = useDocumentInfo() + const { isEditing, isInitializing, title } = useDocumentInfo() const { isEntityVisible } = useEntityVisibility() const isVisible = isEntityVisible({ collectionSlug, globalSlug }) @@ -41,38 +41,41 @@ export const SetDocumentStepNav: React.FC<{ useEffect(() => { const nav: StepNavItem[] = [] - if (collectionSlug) { - nav.push({ - label: getTranslation(pluralLabel, i18n), - url: isVisible ? `${admin}/collections/${collectionSlug}` : undefined, - }) + if (!isInitializing) { + if (collectionSlug) { + nav.push({ + label: getTranslation(pluralLabel, i18n), + url: isVisible ? `${admin}/collections/${collectionSlug}` : undefined, + }) - if (isEditing) { + if (isEditing) { + nav.push({ + label: (useAsTitle && useAsTitle !== 'id' && title) || `${id}`, + url: isVisible ? `${admin}/collections/${collectionSlug}/${id}` : undefined, + }) + } else { + nav.push({ + label: t('general:createNew'), + }) + } + } else if (globalSlug) { nav.push({ - label: (useAsTitle && useAsTitle !== 'id' && title) || `${id}`, - url: isVisible ? `${admin}/collections/${collectionSlug}/${id}` : undefined, + label: title, + url: isVisible ? `${admin}/globals/${globalSlug}` : undefined, }) - } else { + } + + if (view) { nav.push({ - label: t('general:createNew'), + label: view, }) } - } else if (globalSlug) { - nav.push({ - label: title, - url: isVisible ? `${admin}/globals/${globalSlug}` : undefined, - }) - } - if (view) { - nav.push({ - label: view, - }) + if (drawerDepth <= 1) setStepNav(nav) } - - if (drawerDepth <= 1) setStepNav(nav) }, [ setStepNav, + isInitializing, isEditing, pluralLabel, id, diff --git a/packages/next/src/views/Edit/Default/index.tsx b/packages/next/src/views/Edit/Default/index.tsx index c1d7512db1a..0d83d5bd500 100644 --- a/packages/next/src/views/Edit/Default/index.tsx +++ b/packages/next/src/views/Edit/Default/index.tsx @@ -3,7 +3,6 @@ import type { FormProps } from '@payloadcms/ui/forms/Form' import { DocumentControls } from '@payloadcms/ui/elements/DocumentControls' import { DocumentFields } from '@payloadcms/ui/elements/DocumentFields' -import { FormLoadingOverlayToggle } from '@payloadcms/ui/elements/Loading' import { Upload } from '@payloadcms/ui/elements/Upload' import { Form } from '@payloadcms/ui/forms/Form' import { useAuth } from '@payloadcms/ui/providers/Auth' @@ -14,7 +13,6 @@ import { useDocumentInfo } from '@payloadcms/ui/providers/DocumentInfo' import { useEditDepth } from '@payloadcms/ui/providers/EditDepth' import { useFormQueryParams } from '@payloadcms/ui/providers/FormQueryParams' import { OperationProvider } from '@payloadcms/ui/providers/Operation' -import { useTranslation } from '@payloadcms/ui/providers/Translation' import { getFormState } from '@payloadcms/ui/utilities/getFormState' import { useRouter } from 'next/navigation.js' import { useSearchParams } from 'next/navigation.js' @@ -52,6 +50,7 @@ export const DefaultEditView: React.FC = () => { initialData: data, initialState, isEditing, + isInitializing, onSave: onSaveFromContext, } = useDocumentInfo() @@ -64,8 +63,6 @@ export const DefaultEditView: React.FC = () => { const depth = useEditDepth() const { reportUpdate } = useDocumentEvents() - const { i18n } = useTranslation() - const { admin: { user: userSlug }, collections, @@ -183,23 +180,13 @@ export const DefaultEditView: React.FC = () => { action={action} className={`${baseClass}__form`} disableValidationOnSubmit - disabled={!hasSavePermission} - initialState={initialState} + disabled={isInitializing || !hasSavePermission} + initialState={!isInitializing && initialState} + isInitializing={isInitializing} method={id ? 'PATCH' : 'POST'} onChange={[onChange]} onSuccess={onSave} > - <FormLoadingOverlayToggle - action={operation} - // formIsLoading={isLoading} - // loadingSuffix={getTranslation(collectionConfig.labels.singular, i18n)} - name={`collection-edit--${ - typeof collectionConfig?.labels?.singular === 'string' - ? collectionConfig.labels.singular - : i18n.t('general:document') - }`} - type="withoutNav" - /> {BeforeDocument} {preventLeaveWithoutSaving && <LeaveWithoutSaving />} <SetDocumentStepNav diff --git a/packages/next/src/views/Edit/index.client.tsx b/packages/next/src/views/Edit/index.client.tsx index a597e8b5198..b2304714065 100644 --- a/packages/next/src/views/Edit/index.client.tsx +++ b/packages/next/src/views/Edit/index.client.tsx @@ -1,6 +1,5 @@ 'use client' -import { LoadingOverlay } from '@payloadcms/ui/elements/Loading' import { SetViewActions } from '@payloadcms/ui/providers/Actions' import { useComponentMap } from '@payloadcms/ui/providers/ComponentMap' import { useDocumentInfo } from '@payloadcms/ui/providers/DocumentInfo' @@ -16,9 +15,8 @@ export const EditViewClient: React.FC = () => { globalSlug, }) - // Allow the `DocumentInfoProvider` to hydrate - if (!Edit || (!collectionSlug && !globalSlug)) { - return <LoadingOverlay /> + if (!Edit) { + return null } return ( diff --git a/packages/next/src/views/List/index.tsx b/packages/next/src/views/List/index.tsx index d8127d2717f..ae4883909f3 100644 --- a/packages/next/src/views/List/index.tsx +++ b/packages/next/src/views/List/index.tsx @@ -13,7 +13,6 @@ import React, { Fragment } from 'react' import type { DefaultListViewProps, ListPreferences } from './Default/types.js' -import { UnauthorizedView } from '../Unauthorized/index.js' import { DefaultListView } from './Default/index.js' export { generateListMetadata } from './meta.js' @@ -41,7 +40,7 @@ export const ListView: React.FC<AdminViewProps> = async ({ const collectionSlug = collectionConfig?.slug if (!permissions?.collections?.[collectionSlug]?.read?.permission) { - return <UnauthorizedView initPageResult={initPageResult} searchParams={searchParams} /> + notFound() } let listPreferences: ListPreferences diff --git a/packages/next/src/views/LivePreview/index.client.tsx b/packages/next/src/views/LivePreview/index.client.tsx index eb9dd68245d..f3ebd9e0c7a 100644 --- a/packages/next/src/views/LivePreview/index.client.tsx +++ b/packages/next/src/views/LivePreview/index.client.tsx @@ -6,7 +6,6 @@ import type { ClientCollectionConfig, ClientConfig, ClientGlobalConfig, Data } f import { DocumentControls } from '@payloadcms/ui/elements/DocumentControls' import { DocumentFields } from '@payloadcms/ui/elements/DocumentFields' -import { LoadingOverlay } from '@payloadcms/ui/elements/Loading' import { Form } from '@payloadcms/ui/forms/Form' import { SetViewActions } from '@payloadcms/ui/providers/Actions' import { useComponentMap } from '@payloadcms/ui/providers/ComponentMap' @@ -66,6 +65,7 @@ const PreviewView: React.FC<Props> = ({ initialData, initialState, isEditing, + isInitializing, onSave: onSaveFromProps, } = useDocumentInfo() @@ -120,11 +120,6 @@ const PreviewView: React.FC<Props> = ({ [serverURL, apiRoute, id, operation, schemaPath, getDocPreferences], ) - // Allow the `DocumentInfoProvider` to hydrate - if (!collectionSlug && !globalSlug) { - return <LoadingOverlay /> - } - return ( <Fragment> <OperationProvider operation={operation}> @@ -133,6 +128,7 @@ const PreviewView: React.FC<Props> = ({ className={`${baseClass}__form`} disabled={!hasSavePermission} initialState={initialState} + isInitializing={isInitializing} method={id ? 'PATCH' : 'POST'} onChange={[onChange]} onSuccess={onSave} diff --git a/packages/next/src/views/Login/LoginForm/index.tsx b/packages/next/src/views/Login/LoginForm/index.tsx index 3fd27dbb8ef..b50dd226142 100644 --- a/packages/next/src/views/Login/LoginForm/index.tsx +++ b/packages/next/src/views/Login/LoginForm/index.tsx @@ -8,7 +8,6 @@ const Link = (LinkImport.default || LinkImport) as unknown as typeof LinkImport. import type { FormState, PayloadRequestWithData } from 'payload/types' -import { FormLoadingOverlayToggle } from '@payloadcms/ui/elements/Loading' import { Email } from '@payloadcms/ui/fields/Email' import { Password } from '@payloadcms/ui/fields/Password' import { Form } from '@payloadcms/ui/forms/Form' @@ -60,7 +59,6 @@ export const LoginForm: React.FC<{ redirect={typeof searchParams?.redirect === 'string' ? searchParams.redirect : admin} waitForAutocomplete > - <FormLoadingOverlayToggle action="loading" name="login-form" /> <div className={`${baseClass}__inputWrap`}> <Email autoComplete="email" diff --git a/packages/next/src/views/Logout/index.tsx b/packages/next/src/views/Logout/index.tsx index 59d74d554d9..29f28b7abf1 100644 --- a/packages/next/src/views/Logout/index.tsx +++ b/packages/next/src/views/Logout/index.tsx @@ -1,6 +1,5 @@ import type { AdminViewProps } from 'payload/types' -import { MinimalTemplate } from '@payloadcms/ui/templates/Minimal' import React from 'react' import { LogoutClient } from './LogoutClient.js' @@ -26,15 +25,13 @@ export const LogoutView: React.FC< } = initPageResult return ( - <MinimalTemplate className={baseClass}> - <div className={`${baseClass}__wrap`}> - <LogoutClient - adminRoute={admin} - inactivity={inactivity} - redirect={searchParams.redirect as string} - /> - </div> - </MinimalTemplate> + <div className={`${baseClass}__wrap`}> + <LogoutClient + adminRoute={admin} + inactivity={inactivity} + redirect={searchParams.redirect as string} + /> + </div> ) } diff --git a/packages/next/src/views/ResetPassword/index.client.tsx b/packages/next/src/views/ResetPassword/index.client.tsx index 936993d2b82..f538e3eab8c 100644 --- a/packages/next/src/views/ResetPassword/index.client.tsx +++ b/packages/next/src/views/ResetPassword/index.client.tsx @@ -72,9 +72,9 @@ export const ResetPasswordClient: React.FC<Args> = ({ token }) => { const PasswordToConfirm = () => { const { t } = useTranslation() - const { value: confirmValue } = useFormFields(([fields]) => { - return fields['confirm-password'] - }) + const { value: confirmValue } = useFormFields( + ([fields]) => (fields && fields?.['confirm-password']) || null, + ) const validate = React.useCallback( (value: string) => { diff --git a/packages/next/src/views/Version/SelectLocales/index.tsx b/packages/next/src/views/Version/SelectLocales/index.tsx index 56d74ba32ec..896f5209806 100644 --- a/packages/next/src/views/Version/SelectLocales/index.tsx +++ b/packages/next/src/views/Version/SelectLocales/index.tsx @@ -1,3 +1,4 @@ +'use client' import { ReactSelect } from '@payloadcms/ui/elements/ReactSelect' import { useLocale } from '@payloadcms/ui/providers/Locale' import { useTranslation } from '@payloadcms/ui/providers/Translation' diff --git a/packages/next/src/withPayload.js b/packages/next/src/withPayload.js index 760874cb4db..65d0e80107a 100644 --- a/packages/next/src/withPayload.js +++ b/packages/next/src/withPayload.js @@ -4,6 +4,12 @@ * @returns {import('next').NextConfig} * */ export const withPayload = (nextConfig = {}) => { + if (nextConfig.experimental?.staleTimes?.dynamic) { + console.warn( + 'Payload detected a non-zero value for the `staleTimes.dynamic` option in your Next.js config. This may cause stale data to load in the Admin Panel. To clear this warning, remove the `staleTimes.dynamic` option from your Next.js config or set it to 0. In the future, Next.js may support scoping this option to specific routes.', + ) + } + return { ...nextConfig, experimental: { diff --git a/packages/payload/src/admin/LanguageOptions.ts b/packages/payload/src/admin/LanguageOptions.ts new file mode 100644 index 00000000000..5566ed16987 --- /dev/null +++ b/packages/payload/src/admin/LanguageOptions.ts @@ -0,0 +1,4 @@ +export type LanguageOptions = { + label: string + value: string +}[] diff --git a/packages/payload/src/admin/types.ts b/packages/payload/src/admin/types.ts index 2dc3221f73d..5e78ef47920 100644 --- a/packages/payload/src/admin/types.ts +++ b/packages/payload/src/admin/types.ts @@ -1,3 +1,4 @@ +export type { LanguageOptions } from './LanguageOptions.js' export type { RichTextAdapter, RichTextAdapterProvider, RichTextFieldProps } from './RichText.js' export type { CellComponentProps, DefaultCellComponentProps } from './elements/Cell.js' export type { ConditionalDateProps } from './elements/DatePicker.js' @@ -26,6 +27,7 @@ export type { } from './forms/FieldDescription.js' export type { Data, FilterOptionsResult, FormField, FormState, Row } from './forms/Form.js' export type { LabelProps, SanitizedLabelProps } from './forms/Label.js' + export type { RowLabel, RowLabelComponent } from './forms/RowLabel.js' export type { diff --git a/packages/payload/src/admin/views/types.ts b/packages/payload/src/admin/views/types.ts index 2e44bd4b5cc..56804910de7 100644 --- a/packages/payload/src/admin/views/types.ts +++ b/packages/payload/src/admin/views/types.ts @@ -5,6 +5,7 @@ import type { SanitizedCollectionConfig } from '../../collections/config/types.j import type { Locale } from '../../config/types.js' import type { SanitizedGlobalConfig } from '../../globals/config/types.js' import type { PayloadRequestWithData } from '../../types/index.js' +import type { LanguageOptions } from '../LanguageOptions.js' export type AdminViewConfig = { Component: AdminViewComponent @@ -40,6 +41,7 @@ export type InitPageResult = { cookies: Map<string, string> docID?: string globalConfig?: SanitizedGlobalConfig + languageOptions: LanguageOptions locale: Locale permissions: Permissions req: PayloadRequestWithData diff --git a/packages/plugin-stripe/src/ui/LinkToDoc.tsx b/packages/plugin-stripe/src/ui/LinkToDoc.tsx index 04ba99831b2..fea33401b6e 100644 --- a/packages/plugin-stripe/src/ui/LinkToDoc.tsx +++ b/packages/plugin-stripe/src/ui/LinkToDoc.tsx @@ -11,7 +11,7 @@ export const LinkToDoc: CustomComponent<UIField> = () => { const { custom } = useFieldProps() const { isTestKey, nameOfIDField, stripeResourceType } = custom - const field = useFormFields(([fields]) => fields[nameOfIDField]) + const field = useFormFields(([fields]) => (fields && fields?.[nameOfIDField]) || null) const { value: stripeID } = field || {} const stripeEnv = isTestKey ? 'test/' : '' diff --git a/packages/richtext-slate/src/field/RichText.tsx b/packages/richtext-slate/src/field/RichText.tsx index f11a5bab5f4..b96ac8ce49a 100644 --- a/packages/richtext-slate/src/field/RichText.tsx +++ b/packages/richtext-slate/src/field/RichText.tsx @@ -73,7 +73,7 @@ const RichTextField: React.FC< path: pathFromProps, placeholder, plugins, - readOnly, + readOnly: readOnlyFromProps, required, style, validate = richTextValidate, @@ -102,12 +102,16 @@ const RichTextField: React.FC< [validate, required, i18n], ) - const { path: pathFromContext } = useFieldProps() + const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const { initialValue, path, schemaPath, setValue, showError, value } = useField({ - path: pathFromContext || pathFromProps || name, - validate: memoizedValidate, - }) + const { formInitializing, initialValue, path, schemaPath, setValue, showError, value } = useField( + { + path: pathFromContext || pathFromProps || name, + validate: memoizedValidate, + }, + ) + + const disabled = readOnlyFromProps || readOnlyFromContext || formInitializing const editor = useMemo(() => { let CreatedEditor = withEnterBreakOut(withHistory(withReact(createEditor()))) @@ -241,12 +245,12 @@ const RichTextField: React.FC< }) if (ops && Array.isArray(ops) && ops.length > 0) { - if (!readOnly && val !== defaultRichTextValue && val !== value) { + if (!disabled && val !== defaultRichTextValue && val !== value) { setValue(val) } } }, - [editor?.operations, readOnly, setValue, value], + [editor?.operations, disabled, setValue, value], ) useEffect(() => { @@ -263,16 +267,16 @@ const RichTextField: React.FC< }) } - if (readOnly) { + if (disabled) { setClickableState('disabled') } return () => { - if (readOnly) { + if (disabled) { setClickableState('enabled') } } - }, [readOnly]) + }, [disabled]) // useEffect(() => { // // If there is a change to the initial value, we need to reset Slate history @@ -289,7 +293,7 @@ const RichTextField: React.FC< 'field-type', className, showError && 'error', - readOnly && `${baseClass}--read-only`, + disabled && `${baseClass}--read-only`, ] .filter(Boolean) .join(' ') @@ -344,6 +348,7 @@ const RichTextField: React.FC< if (Button) { return ( <ElementButtonProvider + disabled={disabled} fieldProps={props} key={element.name} path={path} @@ -444,7 +449,7 @@ const RichTextField: React.FC< }) }} placeholder={getTranslation(placeholder, i18n)} - readOnly={readOnly} + readOnly={disabled} renderElement={renderElement} renderLeaf={renderLeaf} spellCheck diff --git a/packages/richtext-slate/src/field/elements/Button.tsx b/packages/richtext-slate/src/field/elements/Button.tsx index df897dd190c..a671b0eae45 100644 --- a/packages/richtext-slate/src/field/elements/Button.tsx +++ b/packages/richtext-slate/src/field/elements/Button.tsx @@ -8,15 +8,26 @@ import { useSlate } from 'slate-react' import type { ButtonProps } from './types.js' import '../buttons.scss' +import { useElementButton } from '../providers/ElementButtonProvider.js' import { isElementActive } from './isActive.js' import { toggleElement } from './toggle.js' export const baseClass = 'rich-text__button' export const ElementButton: React.FC<ButtonProps> = (props) => { - const { type = 'type', children, className, el = 'button', format, onClick, tooltip } = props + const { + type = 'type', + children, + className, + disabled: disabledFromProps, + el = 'button', + format, + onClick, + tooltip, + } = props const editor = useSlate() + const { disabled: disabledFromContext } = useElementButton() const [showTooltip, setShowTooltip] = useState(false) const defaultOnClick = useCallback( @@ -30,9 +41,11 @@ export const ElementButton: React.FC<ButtonProps> = (props) => { const Tag: ElementType = el + const disabled = disabledFromProps || disabledFromContext + return ( <Tag - {...(el === 'button' && { type: 'button' })} + {...(el === 'button' && { type: 'button', disabled })} className={[ baseClass, className, diff --git a/packages/richtext-slate/src/field/elements/types.ts b/packages/richtext-slate/src/field/elements/types.ts index 671348fc191..708c60a2c87 100644 --- a/packages/richtext-slate/src/field/elements/types.ts +++ b/packages/richtext-slate/src/field/elements/types.ts @@ -3,6 +3,7 @@ import type { ElementType } from 'react' export type ButtonProps = { children?: React.ReactNode className?: string + disabled?: boolean el?: ElementType format: string onClick?: (e: React.MouseEvent) => void diff --git a/packages/richtext-slate/src/field/providers/ElementButtonProvider.tsx b/packages/richtext-slate/src/field/providers/ElementButtonProvider.tsx index 99b93cfbc37..cc2847aed50 100644 --- a/packages/richtext-slate/src/field/providers/ElementButtonProvider.tsx +++ b/packages/richtext-slate/src/field/providers/ElementButtonProvider.tsx @@ -5,6 +5,7 @@ import type { FormFieldBase } from '@payloadcms/ui/fields/shared' import React from 'react' type ElementButtonContextType = { + disabled?: boolean fieldProps: FormFieldBase & { name: string richTextComponentMap: Map<string, React.ReactNode> diff --git a/packages/translations/src/languages/he.ts b/packages/translations/src/languages/he.ts index 92db7f09377..ffc4f893c9f 100644 --- a/packages/translations/src/languages/he.ts +++ b/packages/translations/src/languages/he.ts @@ -22,16 +22,19 @@ export const heTranslations: DefaultTranslationsObject = { failedToUnlock: 'ביטול נעילה נכשל', forceUnlock: 'אלץ ביטול נעילה', forgotPassword: 'שכחתי סיסמה', - forgotPasswordEmailInstructions: 'אנא הזן את כתובת הדוא"ל שלך למטה. תקבל הודעה עם הוראות לאיפוס הסיסמה שלך.', + forgotPasswordEmailInstructions: + 'אנא הזן את כתובת הדוא"ל שלך למטה. תקבל הודעה עם הוראות לאיפוס הסיסמה שלך.', forgotPasswordQuestion: 'שכחת סיסמה?', generate: 'יצירה', generateNewAPIKey: 'יצירת מפתח API חדש', - generatingNewAPIKeyWillInvalidate: 'יצירת מפתח API חדש תבטל את המפתח הקודם. האם אתה בטוח שברצונך להמשיך?', + generatingNewAPIKeyWillInvalidate: + 'יצירת מפתח API חדש תבטל את המפתח הקודם. האם אתה בטוח שברצונך להמשיך?', lockUntil: 'נעילה עד', logBackIn: 'התחברות מחדש', logOut: 'התנתקות', loggedIn: 'כדי להתחבר עם משתמש אחר, יש להתנתק תחילה.', - loggedInChangePassword: 'כדי לשנות את הסיסמה שלך, יש לעבור ל<a href="{{serverURL}}">חשבון</a> שלך ולערוך את הסיסמה שם.', + loggedInChangePassword: + 'כדי לשנות את הסיסמה שלך, יש לעבור ל<a href="{{serverURL}}">חשבון</a> שלך ולערוך את הסיסמה שם.', loggedOutInactivity: 'התנתקת בשל חוסר פעילות.', loggedOutSuccessfully: 'התנתקת בהצלחה.', loggingOut: 'מתנתק...', @@ -43,7 +46,8 @@ export const heTranslations: DefaultTranslationsObject = { logoutSuccessful: 'התנתקות הצליחה.', logoutUser: 'התנתקות משתמש', newAPIKeyGenerated: 'נוצר מפתח API חדש.', - newAccountCreated: 'נוצר חשבון חדש עבורך כדי לגשת אל <a href="{{serverURL}}">{{serverURL}}</a>. אנא לחץ על הקישור הבא או הדבק את ה-URL בדפדפן שלך כדי לאמת את הדוא"ל שלך: <a href="{{verificationURL}}">{{verificationURL}}</a>.<br> לאחר אימות כתובת הדוא"ל, תוכל להתחבר בהצלחה.', + newAccountCreated: + 'נוצר חשבון חדש עבורך כדי לגשת אל <a href="{{serverURL}}">{{serverURL}}</a>. אנא לחץ על הקישור הבא או הדבק את ה-URL בדפדפן שלך כדי לאמת את הדוא"ל שלך: <a href="{{verificationURL}}">{{verificationURL}}</a>.<br> לאחר אימות כתובת הדוא"ל, תוכל להתחבר בהצלחה.', newPassword: 'סיסמה חדשה', passed: 'אימות הצליח', passwordResetSuccessfully: 'איפוס הסיסמה הצליח.', @@ -61,9 +65,11 @@ export const heTranslations: DefaultTranslationsObject = { verify: 'אמת', verifyUser: 'אמת משתמש', verifyYourEmail: 'אמת את כתובת הדוא"ל שלך', - youAreInactive: 'לא היית פעיל לזמן קצר ובקרוב תתנתק אוטומטית כדי לשמור על האבטחה של חשבונך. האם ברצונך להישאר מחובר?', - youAreReceivingResetPassword: 'קיבלת הודעה זו מכיוון שאתה (או מישהו אחר) ביקשת לאפס את הסיסמה של החשבון שלך. אנא לחץ על הקישור הבא או הדבק אותו בשורת הכתובת בדפדפן שלך כדי להשלים את התהליך:', - youDidNotRequestPassword: 'אם לא ביקשת זאת, אנא התעלם מההודעה והסיסמה שלך תישאר ללא שינוי.' + youAreInactive: + 'לא היית פעיל לזמן קצר ובקרוב תתנתק אוטומטית כדי לשמור על האבטחה של חשבונך. האם ברצונך להישאר מחובר?', + youAreReceivingResetPassword: + 'קיבלת הודעה זו מכיוון שאתה (או מישהו אחר) ביקשת לאפס את הסיסמה של החשבון שלך. אנא לחץ על הקישור הבא או הדבק אותו בשורת הכתובת בדפדפן שלך כדי להשלים את התהליך:', + youDidNotRequestPassword: 'אם לא ביקשת זאת, אנא התעלם מההודעה והסיסמה שלך תישאר ללא שינוי.', }, error: { accountAlreadyActivated: 'חשבון זה כבר הופעל.', @@ -339,7 +345,8 @@ export const heTranslations: DefaultTranslationsObject = { type: 'סוג', aboutToPublishSelection: 'אתה עומד לפרסם את כל ה{{label}} שנבחרו. האם אתה בטוח?', aboutToRestore: 'אתה עומד לשחזר את מסמך {{label}} למצב שהיה בו בתאריך {{versionDate}}.', - aboutToRestoreGlobal: 'אתה עומד לשחזר את {{label}} הגלובלי למצב שהיה בו בתאריך {{versionDate}}.', + aboutToRestoreGlobal: + 'אתה עומד לשחזר את {{label}} הגלובלי למצב שהיה בו בתאריך {{versionDate}}.', aboutToRevertToPublished: 'אתה עומד להחזיר את השינויים במסמך הזה לגרסה שפורסמה. האם אתה בטוח?', aboutToUnpublish: 'אתה עומד לבטל את הפרסום של מסמך זה. האם אתה בטוח?', aboutToUnpublishSelection: 'אתה עומד לבטל את הפרסום של כל ה{{label}} שנבחרו. האם אתה בטוח?', diff --git a/packages/ui/src/elements/DocumentFields/index.tsx b/packages/ui/src/elements/DocumentFields/index.tsx index 7d6d46181dd..da341d03274 100644 --- a/packages/ui/src/elements/DocumentFields/index.tsx +++ b/packages/ui/src/elements/DocumentFields/index.tsx @@ -62,6 +62,7 @@ export const DocumentFields: React.FC<Args> = ({ <RenderFields className={`${baseClass}__fields`} fieldMap={mainFields} + forceRender={10} path="" permissions={docPermissions?.fields} readOnly={readOnly} @@ -76,6 +77,7 @@ export const DocumentFields: React.FC<Args> = ({ <div className={`${baseClass}__sidebar-fields`}> <RenderFields fieldMap={sidebarFields} + forceRender={10} path="" permissions={docPermissions?.fields} readOnly={readOnly} diff --git a/packages/ui/src/elements/DocumentHeader/Tabs/Tab/index.scss b/packages/ui/src/elements/DocumentHeader/Tabs/Tab/index.scss index 298474ebd89..f8094928754 100644 --- a/packages/ui/src/elements/DocumentHeader/Tabs/Tab/index.scss +++ b/packages/ui/src/elements/DocumentHeader/Tabs/Tab/index.scss @@ -82,7 +82,9 @@ } &__count { - padding: 0px 7px; + min-width: 22px; + text-align: center; + padding: 2px 7px; background-color: var(--theme-elevation-100); border-radius: 1px; } diff --git a/packages/ui/src/elements/DocumentHeader/Tabs/tabs/VersionsPill/index.tsx b/packages/ui/src/elements/DocumentHeader/Tabs/tabs/VersionsPill/index.tsx index d11096bbd1c..ec0e3baefbf 100644 --- a/packages/ui/src/elements/DocumentHeader/Tabs/tabs/VersionsPill/index.tsx +++ b/packages/ui/src/elements/DocumentHeader/Tabs/tabs/VersionsPill/index.tsx @@ -1,5 +1,5 @@ 'use client' -import React from 'react' +import React, { Fragment } from 'react' import { useDocumentInfo } from '../../../../../providers/DocumentInfo/index.js' import { baseClass } from '../../Tab/index.js' @@ -7,9 +7,18 @@ import { baseClass } from '../../Tab/index.js' export const VersionsPill: React.FC = () => { const { versions } = useDocumentInfo() - if (versions?.totalDocs > 0) { - return <span className={`${baseClass}__count`}>{versions?.totalDocs?.toString()}</span> - } + // To prevent CLS (versions are currently loaded client-side), render non-breaking space if there are no versions + // The pill is already conditionally rendered to begin with based on whether the document is version-enabled + // documents that are version enabled _always_ have at least one version + const hasVersions = versions?.totalDocs > 0 - return null + return ( + <span + className={[`${baseClass}__count`, hasVersions ? `${baseClass}__count--has-count` : ''] + .filter(Boolean) + .join(' ')} + > + {hasVersions ? versions.totalDocs.toString() : <Fragment>&nbsp;</Fragment>} + </span> + ) } diff --git a/packages/ui/src/elements/ReactSelect/index.tsx b/packages/ui/src/elements/ReactSelect/index.tsx index 7bebdf68994..56c05caeaef 100644 --- a/packages/ui/src/elements/ReactSelect/index.tsx +++ b/packages/ui/src/elements/ReactSelect/index.tsx @@ -3,7 +3,7 @@ import type { KeyboardEventHandler } from 'react' import { arrayMove } from '@dnd-kit/sortable' import { getTranslation } from '@payloadcms/translations' -import React from 'react' +import React, { useEffect, useId } from 'react' import Select from 'react-select' import CreatableSelect from 'react-select/creatable' @@ -13,6 +13,7 @@ export type { Option } from './types.js' import { useTranslation } from '../../providers/Translation/index.js' import { DraggableSortable } from '../DraggableSortable/index.js' +import { ShimmerEffect } from '../ShimmerEffect/index.js' import { ClearIndicator } from './ClearIndicator/index.js' import { Control } from './Control/index.js' import { DropdownIndicator } from './DropdownIndicator/index.js' @@ -31,6 +32,12 @@ const createOption = (label: string) => ({ const SelectAdapter: React.FC<ReactSelectAdapterProps> = (props) => { const { i18n, t } = useTranslation() const [inputValue, setInputValue] = React.useState('') // for creatable select + const uuid = useId() + const [hasMounted, setHasMounted] = React.useState(false) + + useEffect(() => { + setHasMounted(true) + }, []) const { className, @@ -60,6 +67,10 @@ const SelectAdapter: React.FC<ReactSelectAdapterProps> = (props) => { .filter(Boolean) .join(' ') + if (!hasMounted) { + return <ShimmerEffect height="calc(var(--base) * 2 + 2px)" /> + } + if (!isCreatable) { return ( <Select @@ -83,6 +94,7 @@ const SelectAdapter: React.FC<ReactSelectAdapterProps> = (props) => { }} filterOption={filterOption} getOptionValue={getOptionValue} + instanceId={uuid} isClearable={isClearable} isDisabled={disabled} isSearchable={isSearchable} @@ -154,6 +166,7 @@ const SelectAdapter: React.FC<ReactSelectAdapterProps> = (props) => { }} filterOption={filterOption} inputValue={inputValue} + instanceId={uuid} isClearable={isClearable} isDisabled={disabled} isSearchable={isSearchable} diff --git a/packages/ui/src/elements/RenderTitle/index.tsx b/packages/ui/src/elements/RenderTitle/index.tsx index c650aff6600..82eb5fbcc81 100644 --- a/packages/ui/src/elements/RenderTitle/index.tsx +++ b/packages/ui/src/elements/RenderTitle/index.tsx @@ -1,5 +1,5 @@ 'use client' -import React from 'react' +import React, { Fragment } from 'react' import { useDocumentInfo } from '../../providers/DocumentInfo/index.js' import { IDLabel } from '../IDLabel/index.js' @@ -18,9 +18,7 @@ export type RenderTitleProps = { export const RenderTitle: React.FC<RenderTitleProps> = (props) => { const { className, element = 'h1', fallback, title: titleFromProps } = props - const documentInfo = useDocumentInfo() - - const { id, title: titleFromContext } = documentInfo + const { id, isInitializing, title: titleFromContext } = useDocumentInfo() const title = titleFromProps || titleFromContext || fallback @@ -28,6 +26,9 @@ export const RenderTitle: React.FC<RenderTitleProps> = (props) => { const Tag = element + // Render and invisible character to prevent layout shift when the title populates from context + const EmptySpace = <Fragment>&nbsp;</Fragment> + return ( <Tag className={[className, baseClass, idAsTitle && `${baseClass}--has-id`] @@ -35,7 +36,13 @@ export const RenderTitle: React.FC<RenderTitleProps> = (props) => { .join(' ')} title={title} > - {idAsTitle ? <IDLabel className={`${baseClass}__id`} id={id} /> : title || null} + {isInitializing ? ( + EmptySpace + ) : ( + <Fragment> + {idAsTitle ? <IDLabel className={`${baseClass}__id`} id={id} /> : title || EmptySpace} + </Fragment> + )} </Tag> ) } diff --git a/packages/ui/src/fields/Array/index.tsx b/packages/ui/src/fields/Array/index.tsx index 4c07d7f6aa3..ab5e51983a0 100644 --- a/packages/ui/src/fields/Array/index.tsx +++ b/packages/ui/src/fields/Array/index.tsx @@ -71,7 +71,6 @@ export const _ArrayField: React.FC<ArrayFieldProps> = (props) => { } = props const { indexPath, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext const minRows = minRowsProp ?? required ? 1 : 0 const { setDocFieldPreferences } = useDocumentInfo() @@ -116,6 +115,8 @@ export const _ArrayField: React.FC<ArrayFieldProps> = (props) => { const { errorPaths, + formInitializing, + formProcessing, path, rows = [], schemaPath, @@ -128,6 +129,8 @@ export const _ArrayField: React.FC<ArrayFieldProps> = (props) => { validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + const addRow = useCallback( async (rowIndex: number) => { await addFieldRow({ path, rowIndex, schemaPath }) @@ -187,7 +190,7 @@ export const _ArrayField: React.FC<ArrayFieldProps> = (props) => { const fieldErrorCount = errorPaths.length const fieldHasErrors = submitted && errorPaths.length > 0 - const showRequired = readOnly && rows.length === 0 + const showRequired = disabled && rows.length === 0 const showMinRows = rows.length < minRows || (required && rows.length === 0) return ( @@ -257,7 +260,7 @@ export const _ArrayField: React.FC<ArrayFieldProps> = (props) => { errorPath.startsWith(`${path}.${i}.`), ).length return ( - <DraggableSortableItem disabled={readOnly || !isSortable} id={row.id} key={row.id}> + <DraggableSortableItem disabled={disabled || !isSortable} id={row.id} key={row.id}> {(draggableSortableItemProps) => ( <ArrayRow {...draggableSortableItemProps} @@ -274,7 +277,7 @@ export const _ArrayField: React.FC<ArrayFieldProps> = (props) => { moveRow={moveRow} path={path} permissions={permissions} - readOnly={readOnly} + readOnly={disabled} removeRow={removeRow} row={row} rowCount={rows.length} @@ -307,7 +310,7 @@ export const _ArrayField: React.FC<ArrayFieldProps> = (props) => { )} </DraggableSortable> )} - {!readOnly && !hasMaxRows && ( + {!disabled && !hasMaxRows && ( <Button buttonStyle="icon-label" className={`${baseClass}__add-row`} diff --git a/packages/ui/src/fields/Blocks/index.tsx b/packages/ui/src/fields/Blocks/index.tsx index 144e67049f6..416d113b6af 100644 --- a/packages/ui/src/fields/Blocks/index.tsx +++ b/packages/ui/src/fields/Blocks/index.tsx @@ -76,7 +76,6 @@ const _BlocksField: React.FC<BlocksFieldProps> = (props) => { } = props const { indexPath, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext const minRows = minRowsProp ?? required ? 1 : 0 const { setDocFieldPreferences } = useDocumentInfo() @@ -118,6 +117,8 @@ const _BlocksField: React.FC<BlocksFieldProps> = (props) => { const { errorPaths, + formInitializing, + formProcessing, path, permissions, rows = [], @@ -131,6 +132,8 @@ const _BlocksField: React.FC<BlocksFieldProps> = (props) => { validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + const addRow = useCallback( async (rowIndex: number, blockType: string) => { await addFieldRow({ @@ -201,7 +204,7 @@ const _BlocksField: React.FC<BlocksFieldProps> = (props) => { const fieldHasErrors = submitted && fieldErrorCount + (valid ? 0 : 1) > 0 const showMinRows = rows.length < minRows || (required && rows.length === 0) - const showRequired = readOnly && rows.length === 0 + const showRequired = disabled && rows.length === 0 return ( <div @@ -274,7 +277,7 @@ const _BlocksField: React.FC<BlocksFieldProps> = (props) => { errorPath.startsWith(`${path}.${i}`), ).length return ( - <DraggableSortableItem disabled={readOnly || !isSortable} id={row.id} key={row.id}> + <DraggableSortableItem disabled={disabled || !isSortable} id={row.id} key={row.id}> {(draggableSortableItemProps) => ( <BlockRow {...draggableSortableItemProps} @@ -291,7 +294,7 @@ const _BlocksField: React.FC<BlocksFieldProps> = (props) => { moveRow={moveRow} path={path} permissions={permissions} - readOnly={readOnly} + readOnly={disabled} removeRow={removeRow} row={row} rowCount={rows.length} @@ -327,7 +330,7 @@ const _BlocksField: React.FC<BlocksFieldProps> = (props) => { )} </DraggableSortable> )} - {!readOnly && !hasMaxRows && ( + {!disabled && !hasMaxRows && ( <Fragment> <DrawerToggler className={`${baseClass}__drawer-toggler`} slug={drawerSlug}> <Button diff --git a/packages/ui/src/fields/Checkbox/index.tsx b/packages/ui/src/fields/Checkbox/index.tsx index f8f6bc51191..99b207012c7 100644 --- a/packages/ui/src/fields/Checkbox/index.tsx +++ b/packages/ui/src/fields/Checkbox/index.tsx @@ -62,20 +62,21 @@ const CheckboxField: React.FC<CheckboxFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { path, setValue, showError, value } = useField({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField({ disableFormData, path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + const onToggle = useCallback(() => { - if (!readOnly) { + if (!disabled) { setValue(!value) if (typeof onChangeFromProps === 'function') onChangeFromProps(!value) } - }, [onChangeFromProps, readOnly, setValue, value]) + }, [onChangeFromProps, disabled, setValue, value]) const checked = checkedFromProps || Boolean(value) @@ -89,7 +90,7 @@ const CheckboxField: React.FC<CheckboxFieldProps> = (props) => { showError && 'error', className, value && `${baseClass}--checked`, - readOnly && `${baseClass}--read-only`, + disabled && `${baseClass}--read-only`, ] .filter(Boolean) .join(' ')} @@ -111,7 +112,7 @@ const CheckboxField: React.FC<CheckboxFieldProps> = (props) => { name={path} onToggle={onToggle} partialChecked={partialChecked} - readOnly={readOnly} + readOnly={disabled} required={required} /> {CustomDescription !== undefined ? ( diff --git a/packages/ui/src/fields/Code/index.tsx b/packages/ui/src/fields/Code/index.tsx index 02972a74e78..57d37a8c239 100644 --- a/packages/ui/src/fields/Code/index.tsx +++ b/packages/ui/src/fields/Code/index.tsx @@ -64,13 +64,14 @@ const CodeField: React.FC<CodeFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { path, setValue, showError, value } = useField({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField({ path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + return ( <div className={[ @@ -78,7 +79,7 @@ const CodeField: React.FC<CodeFieldProps> = (props) => { baseClass, className, showError && 'error', - readOnly && 'read-only', + disabled && 'read-only', ] .filter(Boolean) .join(' ')} @@ -98,9 +99,9 @@ const CodeField: React.FC<CodeFieldProps> = (props) => { {BeforeInput} <CodeEditor defaultLanguage={prismToMonacoLanguageMap[language] || language} - onChange={readOnly ? () => null : (val) => setValue(val)} + onChange={disabled ? () => null : (val) => setValue(val)} options={editorOptions} - readOnly={readOnly} + readOnly={disabled} value={(value as string) || ''} /> {AfterInput} diff --git a/packages/ui/src/fields/Collapsible/index.tsx b/packages/ui/src/fields/Collapsible/index.tsx index ef9dc5c43ff..00b94949a45 100644 --- a/packages/ui/src/fields/Collapsible/index.tsx +++ b/packages/ui/src/fields/Collapsible/index.tsx @@ -24,6 +24,7 @@ import type { FieldMap } from '../../providers/ComponentMap/buildComponentMap/ty import type { FormFieldBase } from '../shared/index.js' import { FieldDescription } from '../../forms/FieldDescription/index.js' +import { useFormInitializing, useFormProcessing } from '../../forms/Form/context.js' export type CollapsibleFieldProps = FormFieldBase & { fieldMap: FieldMap @@ -52,6 +53,10 @@ const CollapsibleField: React.FC<CollapsibleFieldProps> = (props) => { schemaPath, siblingPermissions, } = useFieldProps() + + const formInitializing = useFormInitializing() + const formProcessing = useFormProcessing() + const path = pathFromContext || pathFromProps const { i18n } = useTranslation() @@ -117,7 +122,7 @@ const CollapsibleField: React.FC<CollapsibleFieldProps> = (props) => { if (typeof collapsedOnMount !== 'boolean') return null - const readOnly = readOnlyFromProps || readOnlyFromContext + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing return ( <Fragment> @@ -152,7 +157,7 @@ const CollapsibleField: React.FC<CollapsibleFieldProps> = (props) => { margins="small" path={path} permissions={siblingPermissions} - readOnly={readOnly} + readOnly={disabled} schemaPath={schemaPath} /> </CollapsibleElement> diff --git a/packages/ui/src/fields/DateTime/index.tsx b/packages/ui/src/fields/DateTime/index.tsx index b30ec7e0fb7..8e40520fc29 100644 --- a/packages/ui/src/fields/DateTime/index.tsx +++ b/packages/ui/src/fields/DateTime/index.tsx @@ -67,12 +67,12 @@ const DateTimeField: React.FC<DateFieldProps> = (props) => { const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const { path, setValue, showError, value } = useField<Date>({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField<Date>({ path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) - const readOnly = readOnlyFromProps || readOnlyFromContext + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing return ( <div @@ -81,7 +81,7 @@ const DateTimeField: React.FC<DateFieldProps> = (props) => { baseClass, className, showError && `${baseClass}--has-error`, - readOnly && 'read-only', + disabled && 'read-only', ] .filter(Boolean) .join(' ')} @@ -102,10 +102,10 @@ const DateTimeField: React.FC<DateFieldProps> = (props) => { <DatePickerField {...datePickerProps} onChange={(incomingDate) => { - if (!readOnly) setValue(incomingDate?.toISOString() || null) + if (!disabled) setValue(incomingDate?.toISOString() || null) }} placeholder={getTranslation(placeholder, i18n)} - readOnly={readOnly} + readOnly={disabled} value={value} /> {AfterInput} diff --git a/packages/ui/src/fields/Email/index.tsx b/packages/ui/src/fields/Email/index.tsx index 5c43177d0a3..0b01b597bad 100644 --- a/packages/ui/src/fields/Email/index.tsx +++ b/packages/ui/src/fields/Email/index.tsx @@ -60,16 +60,17 @@ const EmailField: React.FC<EmailFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { path, setValue, showError, value } = useField({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField({ path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + return ( <div - className={[fieldBaseClass, 'email', className, showError && 'error', readOnly && 'read-only'] + className={[fieldBaseClass, 'email', className, showError && 'error', disabled && 'read-only'] .filter(Boolean) .join(' ')} style={{ @@ -88,7 +89,7 @@ const EmailField: React.FC<EmailFieldProps> = (props) => { {BeforeInput} <input autoComplete={autoComplete} - disabled={readOnly} + disabled={disabled} id={`field-${path.replace(/\./g, '__')}`} name={path} onChange={setValue} diff --git a/packages/ui/src/fields/Group/index.tsx b/packages/ui/src/fields/Group/index.tsx index 62f642eb699..ed382585b64 100644 --- a/packages/ui/src/fields/Group/index.tsx +++ b/packages/ui/src/fields/Group/index.tsx @@ -11,7 +11,11 @@ import { useCollapsible } from '../../elements/Collapsible/provider.js' import { ErrorPill } from '../../elements/ErrorPill/index.js' import { FieldDescription } from '../../forms/FieldDescription/index.js' import { useFieldProps } from '../../forms/FieldPropsProvider/index.js' -import { useFormSubmitted } from '../../forms/Form/context.js' +import { + useFormInitializing, + useFormProcessing, + useFormSubmitted, +} from '../../forms/Form/context.js' import { RenderFields } from '../../forms/RenderFields/index.js' import { useField } from '../../forms/useField/index.js' import { withCondition } from '../../forms/withCondition/index.js' @@ -54,10 +58,12 @@ const GroupField: React.FC<GroupFieldProps> = (props) => { const isWithinRow = useRow() const isWithinTab = useTabs() const { errorPaths } = useField({ path }) + const formInitializing = useFormInitializing() + const formProcessing = useFormProcessing() const submitted = useFormSubmitted() const errorCount = errorPaths.length const fieldHasErrors = submitted && errorCount > 0 - const readOnly = readOnlyFromProps || readOnlyFromContext + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing const isTopLevel = !(isWithinCollapsible || isWithinGroup || isWithinRow) @@ -108,7 +114,7 @@ const GroupField: React.FC<GroupFieldProps> = (props) => { margins="small" path={path} permissions={permissions?.fields} - readOnly={readOnly} + readOnly={disabled} schemaPath={schemaPath} /> </div> diff --git a/packages/ui/src/fields/JSON/index.tsx b/packages/ui/src/fields/JSON/index.tsx index 77f3cd4b880..8d8325b73b8 100644 --- a/packages/ui/src/fields/JSON/index.tsx +++ b/packages/ui/src/fields/JSON/index.tsx @@ -64,12 +64,14 @@ const JSONFieldComponent: React.FC<JSONFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { initialValue, path, setValue, showError, value } = useField<string>({ - path: pathFromContext || pathFromProps || name, - validate: memoizedValidate, - }) + const { formInitializing, formProcessing, initialValue, path, setValue, showError, value } = + useField<string>({ + path: pathFromContext || pathFromProps || name, + validate: memoizedValidate, + }) + + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing const handleMount = useCallback( (editor, monaco) => { @@ -92,7 +94,7 @@ const JSONFieldComponent: React.FC<JSONFieldProps> = (props) => { const handleChange = useCallback( (val) => { - if (readOnly) return + if (disabled) return setStringValue(val) try { @@ -103,14 +105,16 @@ const JSONFieldComponent: React.FC<JSONFieldProps> = (props) => { setJsonError(e) } }, - [readOnly, setValue, setStringValue], + [disabled, setValue, setStringValue], ) useEffect(() => { - if (hasLoadedValue) return + if (hasLoadedValue || value === undefined) return + setStringValue( value || initialValue ? JSON.stringify(value ? value : initialValue, null, 2) : '', ) + setHasLoadedValue(true) }, [initialValue, value, hasLoadedValue]) @@ -121,7 +125,7 @@ const JSONFieldComponent: React.FC<JSONFieldProps> = (props) => { baseClass, className, showError && 'error', - readOnly && 'read-only', + disabled && 'read-only', ] .filter(Boolean) .join(' ')} @@ -145,7 +149,7 @@ const JSONFieldComponent: React.FC<JSONFieldProps> = (props) => { onChange={handleChange} onMount={handleMount} options={editorOptions} - readOnly={readOnly} + readOnly={disabled} value={stringValue} /> {AfterInput} diff --git a/packages/ui/src/fields/Number/index.tsx b/packages/ui/src/fields/Number/index.tsx index 14223d0c1f9..a052cd76495 100644 --- a/packages/ui/src/fields/Number/index.tsx +++ b/packages/ui/src/fields/Number/index.tsx @@ -73,13 +73,16 @@ const NumberFieldComponent: React.FC<NumberFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { path, setValue, showError, value } = useField<number | number[]>({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField< + number | number[] + >({ path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + const handleChange = useCallback( (e) => { const val = parseFloat(e.target.value) @@ -104,7 +107,7 @@ const NumberFieldComponent: React.FC<NumberFieldProps> = (props) => { const handleHasManyChange = useCallback( (selectedOption) => { - if (!readOnly) { + if (!disabled) { let newValue if (!selectedOption) { newValue = [] @@ -117,7 +120,7 @@ const NumberFieldComponent: React.FC<NumberFieldProps> = (props) => { setValue(newValue) } }, - [readOnly, setValue], + [disabled, setValue], ) // useEffect update valueToRender: @@ -145,7 +148,7 @@ const NumberFieldComponent: React.FC<NumberFieldProps> = (props) => { 'number', className, showError && 'error', - readOnly && 'read-only', + disabled && 'read-only', hasMany && 'has-many', ] .filter(Boolean) @@ -166,7 +169,7 @@ const NumberFieldComponent: React.FC<NumberFieldProps> = (props) => { {hasMany ? ( <ReactSelect className={`field-${path.replace(/\./g, '__')}`} - disabled={readOnly} + disabled={disabled} filterOption={(_, rawInput) => { // eslint-disable-next-line no-restricted-globals const isOverHasMany = Array.isArray(value) && value.length >= maxRows @@ -194,7 +197,7 @@ const NumberFieldComponent: React.FC<NumberFieldProps> = (props) => { <div> {BeforeInput} <input - disabled={readOnly} + disabled={disabled} id={`field-${path.replace(/\./g, '__')}`} max={max} min={min} diff --git a/packages/ui/src/fields/Password/index.tsx b/packages/ui/src/fields/Password/index.tsx index 37c88924e9d..f5337a596c1 100644 --- a/packages/ui/src/fields/Password/index.tsx +++ b/packages/ui/src/fields/Password/index.tsx @@ -32,7 +32,7 @@ const PasswordField: React.FC<PasswordFieldProps> = (props) => { CustomLabel, autoComplete, className, - disabled, + disabled: disabledFromProps, errorProps, label, labelProps, @@ -52,14 +52,22 @@ const PasswordField: React.FC<PasswordFieldProps> = (props) => { [validate, required], ) - const { formProcessing, path, setValue, showError, value } = useField({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField({ path: pathFromProps || name, validate: memoizedValidate, }) + const disabled = disabledFromProps || formInitializing || formProcessing + return ( <div - className={[fieldBaseClass, 'password', className, showError && 'error'] + className={[ + fieldBaseClass, + 'password', + className, + showError && 'error', + disabled && 'read-only', + ] .filter(Boolean) .join(' ')} style={{ @@ -75,10 +83,9 @@ const PasswordField: React.FC<PasswordFieldProps> = (props) => { /> <div className={`${fieldBaseClass}__wrap`}> <FieldError CustomError={CustomError} path={path} {...(errorProps || {})} /> - <input autoComplete={autoComplete} - disabled={formProcessing || disabled} + disabled={disabled} id={`field-${path.replace(/\./g, '__')}`} name={path} onChange={setValue} diff --git a/packages/ui/src/fields/RadioGroup/index.tsx b/packages/ui/src/fields/RadioGroup/index.tsx index 0c68e8e1878..4d8c7edf8f5 100644 --- a/packages/ui/src/fields/RadioGroup/index.tsx +++ b/packages/ui/src/fields/RadioGroup/index.tsx @@ -68,9 +68,10 @@ const RadioGroupField: React.FC<RadioFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext const { + formInitializing, + formProcessing, path, setValue, showError, @@ -80,6 +81,8 @@ const RadioGroupField: React.FC<RadioFieldProps> = (props) => { validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + const value = valueFromContext || valueFromProps return ( @@ -90,7 +93,7 @@ const RadioGroupField: React.FC<RadioFieldProps> = (props) => { className, `${baseClass}--layout-${layout}`, showError && 'error', - readOnly && `${baseClass}--read-only`, + disabled && `${baseClass}--read-only`, ] .filter(Boolean) .join(' ')} @@ -132,13 +135,13 @@ const RadioGroupField: React.FC<RadioFieldProps> = (props) => { onChangeFromProps(optionValue) } - if (!readOnly) { + if (!disabled) { setValue(optionValue) } }} option={optionIsObject(option) ? option : { label: option, value: option }} path={path} - readOnly={readOnly} + readOnly={disabled} uuid={uuid} /> </li> diff --git a/packages/ui/src/fields/Relationship/index.tsx b/packages/ui/src/fields/Relationship/index.tsx index ebe8ba9d35b..c7f9c3c9a23 100644 --- a/packages/ui/src/fields/Relationship/index.tsx +++ b/packages/ui/src/fields/Relationship/index.tsx @@ -14,7 +14,6 @@ import { FieldDescription } from '../../forms/FieldDescription/index.js' import { FieldError } from '../../forms/FieldError/index.js' import { FieldLabel } from '../../forms/FieldLabel/index.js' import { useFieldProps } from '../../forms/FieldPropsProvider/index.js' -import { useFormProcessing } from '../../forms/Form/context.js' import { useField } from '../../forms/useField/index.js' import { withCondition } from '../../forms/withCondition/index.js' import { useDebouncedCallback } from '../../hooks/useDebouncedCallback.js' @@ -72,7 +71,6 @@ const RelationshipField: React.FC<RelationshipFieldProps> = (props) => { const { i18n, t } = useTranslation() const { permissions } = useAuth() const { code: locale } = useLocale() - const formProcessing = useFormProcessing() const hasMultipleRelations = Array.isArray(relationTo) const [options, dispatchOptions] = useReducer(optionsReducer, []) const [lastFullyLoadedRelation, setLastFullyLoadedRelation] = useState(-1) @@ -93,15 +91,23 @@ const RelationshipField: React.FC<RelationshipFieldProps> = (props) => { [validate, required], ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { filterOptions, initialValue, path, setValue, showError, value } = useField< - Value | Value[] - >({ + const { + filterOptions, + formInitializing, + formProcessing, + initialValue, + path, + setValue, + showError, + value, + } = useField<Value | Value[]>({ path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) + const readOnly = readOnlyFromProps || readOnlyFromContext || formInitializing + const valueRef = useRef(value) valueRef.current = value diff --git a/packages/ui/src/fields/Select/index.tsx b/packages/ui/src/fields/Select/index.tsx index a1fa9ce97b6..ee5873b8b21 100644 --- a/packages/ui/src/fields/Select/index.tsx +++ b/packages/ui/src/fields/Select/index.tsx @@ -73,16 +73,17 @@ const SelectField: React.FC<SelectFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { path, setValue, showError, value } = useField({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField({ path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + const onChange = useCallback( (selectedOption) => { - if (!readOnly) { + if (!disabled) { let newValue if (!selectedOption) { newValue = null @@ -103,7 +104,7 @@ const SelectField: React.FC<SelectFieldProps> = (props) => { setValue(newValue) } }, - [readOnly, hasMany, setValue, onChangeFromProps], + [disabled, hasMany, setValue, onChangeFromProps], ) return ( @@ -125,7 +126,7 @@ const SelectField: React.FC<SelectFieldProps> = (props) => { onChange={onChange} options={options} path={path} - readOnly={readOnly} + readOnly={disabled} required={required} showError={showError} style={style} diff --git a/packages/ui/src/fields/Tabs/index.tsx b/packages/ui/src/fields/Tabs/index.tsx index 8a0d3b0211a..dc4f77ca120 100644 --- a/packages/ui/src/fields/Tabs/index.tsx +++ b/packages/ui/src/fields/Tabs/index.tsx @@ -54,6 +54,7 @@ const TabsField: React.FC<TabsFieldProps> = (props) => { readOnly: readOnlyFromContext, schemaPath, } = useFieldProps() + const readOnly = readOnlyFromProps || readOnlyFromContext const path = pathFromContext || pathFromProps || name const { getPreference, setPreference } = usePreferences() diff --git a/packages/ui/src/fields/Text/index.tsx b/packages/ui/src/fields/Text/index.tsx index 89b08f1374e..f3292f90feb 100644 --- a/packages/ui/src/fields/Text/index.tsx +++ b/packages/ui/src/fields/Text/index.tsx @@ -60,13 +60,14 @@ const TextField: React.FC<TextFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { formProcessing, path, setValue, showError, value } = useField({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField({ path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + const renderRTL = isFieldRTL({ fieldLocalized: localized, fieldRTL: rtl, @@ -80,7 +81,7 @@ const TextField: React.FC<TextFieldProps> = (props) => { const handleHasManyChange = useCallback( (selectedOption) => { - if (!readOnly) { + if (!disabled) { let newValue if (!selectedOption) { newValue = [] @@ -93,7 +94,7 @@ const TextField: React.FC<TextFieldProps> = (props) => { setValue(newValue) } }, - [readOnly, setValue], + [disabled, setValue], ) // useEffect update valueToRender: @@ -140,7 +141,7 @@ const TextField: React.FC<TextFieldProps> = (props) => { } path={path} placeholder={placeholder} - readOnly={formProcessing || readOnly} + readOnly={disabled} required={required} rtl={renderRTL} showError={showError} diff --git a/packages/ui/src/fields/Textarea/index.tsx b/packages/ui/src/fields/Textarea/index.tsx index 132e2dfaf19..7480482b654 100644 --- a/packages/ui/src/fields/Textarea/index.tsx +++ b/packages/ui/src/fields/Textarea/index.tsx @@ -66,13 +66,14 @@ const TextareaField: React.FC<TextareaFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { path, setValue, showError, value } = useField<string>({ + const { formInitializing, formProcessing, path, setValue, showError, value } = useField<string>({ path: pathFromContext || pathFromProps || name, validate: memoizedValidate, }) + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing + return ( <TextareaInput AfterInput={AfterInput} @@ -90,7 +91,7 @@ const TextareaField: React.FC<TextareaFieldProps> = (props) => { }} path={path} placeholder={getTranslation(placeholder, i18n)} - readOnly={readOnly} + readOnly={disabled} required={required} rows={rows} rtl={isRTL} diff --git a/packages/ui/src/fields/Upload/index.tsx b/packages/ui/src/fields/Upload/index.tsx index 0949b2e8a08..076a9fe7a6a 100644 --- a/packages/ui/src/fields/Upload/index.tsx +++ b/packages/ui/src/fields/Upload/index.tsx @@ -52,12 +52,14 @@ const _Upload: React.FC<UploadFieldProps> = (props) => { ) const { path: pathFromContext, readOnly: readOnlyFromContext } = useFieldProps() - const readOnly = readOnlyFromProps || readOnlyFromContext - const { filterOptions, path, setValue, showError, value } = useField<string>({ - path: pathFromContext || pathFromProps, - validate: memoizedValidate, - }) + const { filterOptions, formInitializing, formProcessing, path, setValue, showError, value } = + useField<string>({ + path: pathFromContext || pathFromProps, + validate: memoizedValidate, + }) + + const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing const onChange = useCallback( (incomingValue) => { @@ -83,7 +85,7 @@ const _Upload: React.FC<UploadFieldProps> = (props) => { labelProps={labelProps} onChange={onChange} path={path} - readOnly={readOnly} + readOnly={disabled} relationTo={relationTo} required={required} serverURL={serverURL} diff --git a/packages/ui/src/forms/FieldPropsProvider/index.tsx b/packages/ui/src/forms/FieldPropsProvider/index.tsx index 2619ed5f42a..d47f92e7ad8 100644 --- a/packages/ui/src/forms/FieldPropsProvider/index.tsx +++ b/packages/ui/src/forms/FieldPropsProvider/index.tsx @@ -32,6 +32,7 @@ export type Props = { children: React.ReactNode custom?: Record<any, string> indexPath?: string + isForceRendered?: boolean path: string permissions?: FieldPermissions readOnly: boolean diff --git a/packages/ui/src/forms/Form/context.ts b/packages/ui/src/forms/Form/context.ts index 25d9a355dcd..f0fb689499a 100644 --- a/packages/ui/src/forms/Form/context.ts +++ b/packages/ui/src/forms/Form/context.ts @@ -13,6 +13,7 @@ const FormWatchContext = createContext({} as Context) const SubmittedContext = createContext(false) const ProcessingContext = createContext(false) const ModifiedContext = createContext(false) +const InitializingContext = createContext(false) const FormFieldsContext = createSelectorContext<FormFieldsContextType>([{}, () => null]) /** @@ -25,6 +26,7 @@ const useWatchForm = (): Context => useContext(FormWatchContext) const useFormSubmitted = (): boolean => useContext(SubmittedContext) const useFormProcessing = (): boolean => useContext(ProcessingContext) const useFormModified = (): boolean => useContext(ModifiedContext) +const useFormInitializing = (): boolean => useContext(InitializingContext) /** * Get and set the value of a form field based on a selector @@ -46,12 +48,14 @@ export { FormContext, FormFieldsContext, FormWatchContext, + InitializingContext, ModifiedContext, ProcessingContext, SubmittedContext, useAllFormFields, useForm, useFormFields, + useFormInitializing, useFormModified, useFormProcessing, useFormSubmitted, diff --git a/packages/ui/src/forms/Form/getSiblingData.ts b/packages/ui/src/forms/Form/getSiblingData.ts index a36b47839c6..736ef8768d0 100644 --- a/packages/ui/src/forms/Form/getSiblingData.ts +++ b/packages/ui/src/forms/Form/getSiblingData.ts @@ -6,9 +6,12 @@ const { unflatten } = flatleyImport import { reduceFieldsToValues } from '../../utilities/reduceFieldsToValues.js' export const getSiblingData = (fields: FormState, path: string): Data => { + if (!fields) return null + if (path.indexOf('.') === -1) { return reduceFieldsToValues(fields, true) } + const siblingFields = {} // Determine if the last segment of the path is an array-based row diff --git a/packages/ui/src/forms/Form/index.tsx b/packages/ui/src/forms/Form/index.tsx index 4443453221b..bac74ad77d4 100644 --- a/packages/ui/src/forms/Form/index.tsx +++ b/packages/ui/src/forms/Form/index.tsx @@ -33,6 +33,7 @@ import { FormContext, FormFieldsContext, FormWatchContext, + InitializingContext, ModifiedContext, ProcessingContext, SubmittedContext, @@ -60,6 +61,7 @@ export const Form: React.FC<FormProps> = (props) => { // fields: fieldsFromProps = collection?.fields || global?.fields, handleResponse, initialState, // fully formed initial field state + isInitializing: initializingFromProps, onChange, onSubmit, onSuccess, @@ -86,13 +88,16 @@ export const Form: React.FC<FormProps> = (props) => { } = config const [disabled, setDisabled] = useState(disabledFromProps || false) + const [isMounted, setIsMounted] = useState(false) const [modified, setModified] = useState(false) + const [initializing, setInitializing] = useState(initializingFromProps) const [processing, setProcessing] = useState(false) const [submitted, setSubmitted] = useState(false) const formRef = useRef<HTMLFormElement>(null) const contextRef = useRef({} as FormContextType) const fieldsReducer = useReducer(fieldReducer, {}, () => initialState) + /** * `fields` is the current, up-to-date state/data of all fields in the form. It can be modified by using dispatchFields, * which calls the fieldReducer, which then updates the state. @@ -489,8 +494,10 @@ export const Form: React.FC<FormProps> = (props) => { ) useEffect(() => { - if (typeof disabledFromProps === 'boolean') setDisabled(disabledFromProps) - }, [disabledFromProps]) + if (initializingFromProps !== undefined) { + setInitializing(initializingFromProps) + } + }, [initializingFromProps]) contextRef.current.submit = submit contextRef.current.getFields = getFields @@ -513,6 +520,15 @@ export const Form: React.FC<FormProps> = (props) => { contextRef.current.removeFieldRow = removeFieldRow contextRef.current.replaceFieldRow = replaceFieldRow contextRef.current.uuid = uuid + contextRef.current.initializing = initializing + + useEffect(() => { + setIsMounted(true) + }, []) + + useEffect(() => { + if (typeof disabledFromProps === 'boolean') setDisabled(disabledFromProps) + }, [disabledFromProps]) useEffect(() => { if (typeof submittedFromProps === 'boolean') setSubmitted(submittedFromProps) @@ -521,7 +537,7 @@ export const Form: React.FC<FormProps> = (props) => { useEffect(() => { if (initialState) { contextRef.current = { ...initContextState } as FormContextType - dispatchFields({ type: 'REPLACE_STATE', state: initialState }) + dispatchFields({ type: 'REPLACE_STATE', optimize: false, state: initialState }) } }, [initialState, dispatchFields]) @@ -597,13 +613,15 @@ export const Form: React.FC<FormProps> = (props) => { }} > <SubmittedContext.Provider value={submitted}> - <ProcessingContext.Provider value={processing}> - <ModifiedContext.Provider value={modified}> - <FormFieldsContext.Provider value={fieldsReducer}> - {children} - </FormFieldsContext.Provider> - </ModifiedContext.Provider> - </ProcessingContext.Provider> + <InitializingContext.Provider value={!isMounted || (isMounted && initializing)}> + <ProcessingContext.Provider value={processing}> + <ModifiedContext.Provider value={modified}> + <FormFieldsContext.Provider value={fieldsReducer}> + {children} + </FormFieldsContext.Provider> + </ModifiedContext.Provider> + </ProcessingContext.Provider> + </InitializingContext.Provider> </SubmittedContext.Provider> </FormWatchContext.Provider> </FormContext.Provider> diff --git a/packages/ui/src/forms/Form/initContextState.ts b/packages/ui/src/forms/Form/initContextState.ts index 81dcedb2cc1..bad62c5d106 100644 --- a/packages/ui/src/forms/Form/initContextState.ts +++ b/packages/ui/src/forms/Form/initContextState.ts @@ -37,6 +37,7 @@ export const initContextState: Context = { getField: (): FormField => undefined, getFields: (): FormState => ({}), getSiblingData, + initializing: undefined, removeFieldRow: () => undefined, replaceFieldRow: () => undefined, replaceState: () => undefined, diff --git a/packages/ui/src/forms/Form/types.ts b/packages/ui/src/forms/Form/types.ts index fbaef436676..2e9681f9bf6 100644 --- a/packages/ui/src/forms/Form/types.ts +++ b/packages/ui/src/forms/Form/types.ts @@ -35,6 +35,7 @@ export type FormProps = ( fields?: Field[] handleResponse?: (res: Response) => void initialState?: FormState + isInitializing?: boolean log?: boolean onChange?: ((args: { formState: FormState }) => Promise<FormState>)[] onSubmit?: (fields: FormState, data: Data) => void @@ -197,6 +198,7 @@ export type Context = { getField: GetField getFields: GetFields getSiblingData: GetSiblingData + initializing: boolean removeFieldRow: ({ path, rowIndex }: { path: string; rowIndex: number }) => void replaceFieldRow: ({ data, diff --git a/packages/ui/src/forms/RenderFields/index.tsx b/packages/ui/src/forms/RenderFields/index.tsx index 6a9cf93603e..7b4c4cd6347 100644 --- a/packages/ui/src/forms/RenderFields/index.tsx +++ b/packages/ui/src/forms/RenderFields/index.tsx @@ -22,8 +22,9 @@ export const RenderFields: React.FC<Props> = (props) => { { rootMargin: '1000px', }, - forceRender, + Boolean(forceRender), ) + const isIntersecting = Boolean(entry?.isIntersecting) const isAboveViewport = entry?.boundingClientRect?.top < 0 const shouldRender = forceRender || isIntersecting || isAboveViewport @@ -67,6 +68,9 @@ export const RenderFields: React.FC<Props> = (props) => { isHidden, } = f + const forceRenderChildren = + (typeof forceRender === 'number' && fieldIndex <= forceRender) || true + const name = 'name' in f ? f.name : undefined return ( @@ -74,7 +78,7 @@ export const RenderFields: React.FC<Props> = (props) => { CustomField={CustomField} custom={custom} disabled={disabled} - fieldComponentProps={fieldComponentProps} + fieldComponentProps={{ ...fieldComponentProps, forceRender: forceRenderChildren }} indexPath={indexPath !== undefined ? `${indexPath}.${fieldIndex}` : `${fieldIndex}`} isHidden={isHidden} key={fieldIndex} diff --git a/packages/ui/src/forms/RenderFields/types.ts b/packages/ui/src/forms/RenderFields/types.ts index bd8f0e06e2e..3dbe618fc05 100644 --- a/packages/ui/src/forms/RenderFields/types.ts +++ b/packages/ui/src/forms/RenderFields/types.ts @@ -5,7 +5,14 @@ import type { FieldMap } from '../../providers/ComponentMap/buildComponentMap/ty export type Props = { className?: string fieldMap: FieldMap - forceRender?: boolean + /** + * Controls the rendering behavior of the fields, i.e. defers rendering until they intersect with the viewport using the Intersection Observer API. + * + * If true, the fields will be rendered immediately, rather than waiting for them to intersect with the viewport. + * + * If a number is provided, will immediately render fields _up to that index_. + */ + forceRender?: boolean | number indexPath?: string margins?: 'small' | false operation?: Operation diff --git a/packages/ui/src/forms/Submit/index.tsx b/packages/ui/src/forms/Submit/index.tsx index 0ae36d3f822..92e91c2385a 100644 --- a/packages/ui/src/forms/Submit/index.tsx +++ b/packages/ui/src/forms/Submit/index.tsx @@ -4,7 +4,7 @@ import React, { forwardRef } from 'react' import type { Props } from '../../elements/Button/types.js' import { Button } from '../../elements/Button/index.js' -import { useForm, useFormProcessing } from '../Form/context.js' +import { useForm, useFormInitializing, useFormProcessing } from '../Form/context.js' import './index.scss' const baseClass = 'form-submit' @@ -12,9 +12,10 @@ const baseClass = 'form-submit' export const FormSubmit = forwardRef<HTMLButtonElement, Props>((props, ref) => { const { type = 'submit', buttonId: id, children, disabled: disabledFromProps } = props const processing = useFormProcessing() + const initializing = useFormInitializing() const { disabled } = useForm() - const canSave = !(disabledFromProps || processing || disabled) + const canSave = !(disabledFromProps || initializing || processing || disabled) return ( <div className={baseClass}> diff --git a/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/index.ts b/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/index.ts index 22836119906..0382705adf0 100644 --- a/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/index.ts +++ b/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/index.ts @@ -1,4 +1,5 @@ -import type { Data, Field as FieldSchema, PayloadRequestWithData } from 'payload/types' +import type { User } from 'payload/auth' +import type { Data, Field as FieldSchema } from 'payload/types' import { iterateFields } from './iterateFields.js' @@ -6,17 +7,25 @@ type Args = { data: Data fields: FieldSchema[] id?: number | string - req: PayloadRequestWithData + locale: string | undefined siblingData: Data + user: User } -export const calculateDefaultValues = async ({ id, data, fields, req }: Args): Promise<Data> => { +export const calculateDefaultValues = async ({ + id, + data, + fields, + locale, + user, +}: Args): Promise<Data> => { await iterateFields({ id, data, fields, - req, + locale, siblingData: data, + user, }) return data diff --git a/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/iterateFields.ts b/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/iterateFields.ts index 8294c4b8a25..c3bc1c095a4 100644 --- a/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/iterateFields.ts +++ b/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/iterateFields.ts @@ -1,4 +1,5 @@ -import type { Data, Field, PayloadRequestWithData, TabAsField } from 'payload/types' +import type { User } from 'payload/auth' +import type { Data, Field, TabAsField } from 'payload/types' import { defaultValuePromise } from './promise.js' @@ -6,16 +7,18 @@ type Args<T> = { data: T fields: (Field | TabAsField)[] id?: number | string - req: PayloadRequestWithData + locale: string | undefined siblingData: Data + user: User } export const iterateFields = async <T>({ id, data, fields, - req, + locale, siblingData, + user, }: Args<T>): Promise<void> => { const promises = [] fields.forEach((field) => { @@ -24,8 +27,9 @@ export const iterateFields = async <T>({ id, data, field, - req, + locale, siblingData, + user, }), ) }) diff --git a/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/promise.ts b/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/promise.ts index fbae14a3960..14f8021f6ac 100644 --- a/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/promise.ts +++ b/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/promise.ts @@ -1,12 +1,7 @@ +import type { User } from 'payload/auth' import type { Data } from 'payload/types' -import { - type Field, - type PayloadRequestWithData, - type TabAsField, - fieldAffectsData, - tabHasName, -} from 'payload/types' +import { type Field, type TabAsField, fieldAffectsData, tabHasName } from 'payload/types' import { getDefaultValue } from 'payload/utilities' import { iterateFields } from './iterateFields.js' @@ -15,8 +10,9 @@ type Args<T> = { data: T field: Field | TabAsField id?: number | string - req: PayloadRequestWithData + locale: string | undefined siblingData: Data + user: User } // TODO: Make this works for rich text subfields @@ -24,8 +20,9 @@ export const defaultValuePromise = async <T>({ id, data, field, - req, + locale, siblingData, + user, }: Args<T>): Promise<void> => { if (fieldAffectsData(field)) { if ( @@ -34,8 +31,8 @@ export const defaultValuePromise = async <T>({ ) { siblingData[field.name] = await getDefaultValue({ defaultValue: field.defaultValue, - locale: req.locale, - user: req.user, + locale, + user, value: siblingData[field.name], }) } @@ -52,8 +49,9 @@ export const defaultValuePromise = async <T>({ id, data, fields: field.fields, - req, + locale, siblingData: groupData, + user, }) break @@ -70,8 +68,9 @@ export const defaultValuePromise = async <T>({ id, data, fields: field.fields, - req, + locale, siblingData: row, + user, }), ) }) @@ -97,8 +96,9 @@ export const defaultValuePromise = async <T>({ id, data, fields: block.fields, - req, + locale, siblingData: row, + user, }), ) } @@ -115,8 +115,9 @@ export const defaultValuePromise = async <T>({ id, data, fields: field.fields, - req, + locale, siblingData, + user, }) break @@ -136,8 +137,9 @@ export const defaultValuePromise = async <T>({ id, data, fields: field.fields, - req, + locale, siblingData: tabSiblingData, + user, }) break @@ -148,8 +150,9 @@ export const defaultValuePromise = async <T>({ id, data, fields: field.tabs.map((tab) => ({ ...tab, type: 'tab' })), - req, + locale, siblingData, + user, }) break diff --git a/packages/ui/src/forms/buildStateFromSchema/index.tsx b/packages/ui/src/forms/buildStateFromSchema/index.tsx index 62e4b9204b4..2522d095c5e 100644 --- a/packages/ui/src/forms/buildStateFromSchema/index.tsx +++ b/packages/ui/src/forms/buildStateFromSchema/index.tsx @@ -41,8 +41,9 @@ export const buildStateFromSchema = async (args: Args): Promise<FormState> => { id, data: fullData, fields: fieldSchema, - req, + locale: req.locale, siblingData: fullData, + user: req.user, }) await iterateFields({ diff --git a/packages/ui/src/forms/useField/index.tsx b/packages/ui/src/forms/useField/index.tsx index 0183b625223..513a279a45c 100644 --- a/packages/ui/src/forms/useField/index.tsx +++ b/packages/ui/src/forms/useField/index.tsx @@ -16,6 +16,7 @@ import { useFieldProps } from '../FieldPropsProvider/index.js' import { useForm, useFormFields, + useFormInitializing, useFormModified, useFormProcessing, useFormSubmitted, @@ -36,6 +37,7 @@ export const useField = <T,>(options: Options): FieldType<T> => { const submitted = useFormSubmitted() const processing = useFormProcessing() + const initializing = useFormInitializing() const { user } = useAuth() const { id } = useDocumentInfo() const operation = useOperation() @@ -108,6 +110,7 @@ export const useField = <T,>(options: Options): FieldType<T> => { errorMessage: field?.errorMessage, errorPaths: field?.errorPaths || [], filterOptions, + formInitializing: initializing, formProcessing: processing, formSubmitted: submitted, initialValue, @@ -137,6 +140,7 @@ export const useField = <T,>(options: Options): FieldType<T> => { readOnly, permissions, filterOptions, + initializing, ], ) diff --git a/packages/ui/src/forms/useField/types.ts b/packages/ui/src/forms/useField/types.ts index 899898216d2..c0b597790cb 100644 --- a/packages/ui/src/forms/useField/types.ts +++ b/packages/ui/src/forms/useField/types.ts @@ -14,6 +14,7 @@ export type FieldType<T> = { errorMessage?: string errorPaths?: string[] filterOptions?: FilterOptionsResult + formInitializing: boolean formProcessing: boolean formSubmitted: boolean initialValue?: T diff --git a/packages/ui/src/providers/DocumentInfo/index.tsx b/packages/ui/src/providers/DocumentInfo/index.tsx index f332d1f7bed..59f7730344d 100644 --- a/packages/ui/src/providers/DocumentInfo/index.tsx +++ b/packages/ui/src/providers/DocumentInfo/index.tsx @@ -9,7 +9,6 @@ import React, { createContext, useCallback, useContext, useEffect, useRef, useSt import type { DocumentInfoContext, DocumentInfoProps } from './types.js' -import { LoadingOverlay } from '../../elements/Loading/index.js' import { formatDocTitle } from '../../utilities/formatDocTitle.js' import { getFormState } from '../../utilities/getFormState.js' import { hasSavePermission as getHasSavePermission } from '../../utilities/hasSavePermission.js' @@ -39,40 +38,60 @@ export const DocumentInfoProvider: React.FC< globalSlug, hasPublishPermission: hasPublishPermissionFromProps, hasSavePermission: hasSavePermissionFromProps, + initialData: initialDataFromProps, + initialState: initialStateFromProps, onLoadError, onSave: onSaveFromProps, } = props + const { + admin: { dateFormat }, + collections, + globals, + routes: { api }, + serverURL, + } = useConfig() + + const collectionConfig = collections.find((c) => c.slug === collectionSlug) + const globalConfig = globals.find((g) => g.slug === globalSlug) + const docConfig = collectionConfig || globalConfig + + const { i18n } = useTranslation() + + const [documentTitle, setDocumentTitle] = useState(() => { + if (!initialDataFromProps) return '' + + return formatDocTitle({ + collectionConfig, + data: { ...initialDataFromProps, id }, + dateFormat, + fallback: id?.toString(), + globalConfig, + i18n, + }) + }) + const [isLoading, setIsLoading] = useState(false) const [isError, setIsError] = useState(false) - const [documentTitle, setDocumentTitle] = useState('') - const [data, setData] = useState<Data>() - const [initialState, setInitialState] = useState<FormState>() + const [data, setData] = useState<Data>(initialDataFromProps) + const [initialState, setInitialState] = useState<FormState>(initialStateFromProps) const [publishedDoc, setPublishedDoc] = useState<TypeWithID & TypeWithTimestamps>(null) const [versions, setVersions] = useState<PaginatedDocs<TypeWithVersion<any>>>(null) - const [docPermissions, setDocPermissions] = useState<DocumentPermissions>(null) - const [hasSavePermission, setHasSavePermission] = useState<boolean>(null) - const [hasPublishPermission, setHasPublishPermission] = useState<boolean>(null) + const [docPermissions, setDocPermissions] = useState<DocumentPermissions>(docPermissionsFromProps) + const [hasSavePermission, setHasSavePermission] = useState<boolean>(hasSavePermissionFromProps) + const [hasPublishPermission, setHasPublishPermission] = useState<boolean>( + hasPublishPermissionFromProps, + ) + const isInitializing = initialState === undefined || data === undefined const hasInitializedDocPermissions = useRef(false) const [unpublishedVersions, setUnpublishedVersions] = useState<PaginatedDocs<TypeWithVersion<any>>>(null) const { getPreference, setPreference } = usePreferences() - const { i18n } = useTranslation() const { permissions } = useAuth() const { code: locale } = useLocale() + const prevLocale = useRef(locale) - const { - admin: { dateFormat }, - collections, - globals, - routes: { api }, - serverURL, - } = useConfig() - - const collectionConfig = collections.find((c) => c.slug === collectionSlug) - const globalConfig = globals.find((g) => g.slug === globalSlug) - const docConfig = collectionConfig || globalConfig const versionsConfig = docConfig?.versions const baseURL = `${serverURL}${api}` @@ -296,7 +315,7 @@ export const DocumentInfoProvider: React.FC< ) } }, - [serverURL, api, permissions, i18n.language, locale, collectionSlug, globalSlug, isEditing], + [serverURL, api, permissions, i18n.language, locale, collectionSlug, globalSlug], ) const getDocPreferences = useCallback(() => { @@ -372,47 +391,67 @@ export const DocumentInfoProvider: React.FC< useEffect(() => { const abortController = new AbortController() + const localeChanged = locale !== prevLocale.current - const getInitialState = async () => { - setIsError(false) - setIsLoading(true) + if ( + initialStateFromProps === undefined || + initialDataFromProps === undefined || + localeChanged + ) { + if (localeChanged) prevLocale.current = locale - try { - const result = await getFormState({ - apiRoute: api, - body: { - id, - collectionSlug, - globalSlug, - locale, - operation, - schemaPath: collectionSlug || globalSlug, - }, - onError: onLoadError, - serverURL, - signal: abortController.signal, - }) - - setData(reduceFieldsToValues(result, true)) - setInitialState(result) - } catch (err) { - if (!abortController.signal.aborted) { - if (typeof onLoadError === 'function') { - void onLoadError() + const getInitialState = async () => { + setIsError(false) + setIsLoading(true) + + try { + const result = await getFormState({ + apiRoute: api, + body: { + id, + collectionSlug, + globalSlug, + locale, + operation, + schemaPath: collectionSlug || globalSlug, + }, + onError: onLoadError, + serverURL, + signal: abortController.signal, + }) + + setData(reduceFieldsToValues(result, true)) + setInitialState(result) + } catch (err) { + if (!abortController.signal.aborted) { + if (typeof onLoadError === 'function') { + void onLoadError() + } + setIsError(true) + setIsLoading(false) } - setIsError(true) - setIsLoading(false) } + setIsLoading(false) } - setIsLoading(false) - } - void getInitialState() + void getInitialState() + } return () => { abortController.abort() } - }, [api, operation, collectionSlug, serverURL, id, globalSlug, locale, onLoadError]) + }, [ + api, + operation, + collectionSlug, + serverURL, + id, + globalSlug, + locale, + onLoadError, + initialDataFromProps, + initialStateFromProps, + ]) useEffect(() => { void getVersions() @@ -445,10 +484,6 @@ export const DocumentInfoProvider: React.FC< hasPublishPermission === null ) { await getDocPermissions(data) - } else { - setDocPermissions(docPermissions) - setHasSavePermission(hasSavePermission) - setHasPublishPermission(hasPublishPermission) } } @@ -469,10 +504,6 @@ export const DocumentInfoProvider: React.FC< if (isError) notFound() - if (!initialState || isLoading) { - return <LoadingOverlay /> - } - const value: DocumentInfoContext = { ...props, docConfig, @@ -484,6 +515,8 @@ export const DocumentInfoProvider: React.FC< hasSavePermission, initialData: data, initialState, + isInitializing, + isLoading, onSave, publishedDoc, setDocFieldPreferences, diff --git a/packages/ui/src/providers/DocumentInfo/types.ts b/packages/ui/src/providers/DocumentInfo/types.ts index 755c3198e8a..4843a04a1bd 100644 --- a/packages/ui/src/providers/DocumentInfo/types.ts +++ b/packages/ui/src/providers/DocumentInfo/types.ts @@ -29,6 +29,8 @@ export type DocumentInfoProps = { hasPublishPermission?: boolean hasSavePermission?: boolean id: null | number | string + initialData?: Data + initialState?: FormState isEditing?: boolean onLoadError?: (data?: any) => Promise<void> | void onSave?: (data: Data) => Promise<void> | void @@ -41,6 +43,8 @@ export type DocumentInfoContext = DocumentInfoProps & { getVersions: () => Promise<void> initialData: Data initialState?: FormState + isInitializing: boolean + isLoading: boolean preferencesKey?: string publishedDoc?: TypeWithID & TypeWithTimestamps & { _status?: string } setDocFieldPreferences: ( diff --git a/packages/ui/src/providers/Root/index.tsx b/packages/ui/src/providers/Root/index.tsx index 16cdcb8fd07..664d9f0522b 100644 --- a/packages/ui/src/providers/Root/index.tsx +++ b/packages/ui/src/providers/Root/index.tsx @@ -1,6 +1,6 @@ 'use client' import type { I18nClient, Language } from '@payloadcms/translations' -import type { ClientConfig } from 'payload/types' +import type { ClientConfig, LanguageOptions } from 'payload/types' import * as facelessUIImport from '@faceless-ui/modal' import * as facelessUIImport3 from '@faceless-ui/scroll-info' @@ -10,7 +10,6 @@ import { Slide, ToastContainer } from 'react-toastify' import type { ComponentMap } from '../ComponentMap/buildComponentMap/types.js' import type { Theme } from '../Theme/index.js' -import type { LanguageOptions } from '../Translation/index.js' import { LoadingOverlayProvider } from '../../elements/LoadingOverlay/index.js' import { NavProvider } from '../../elements/Nav/context.js' diff --git a/packages/ui/src/providers/Translation/index.tsx b/packages/ui/src/providers/Translation/index.tsx index 3c6e9bf3afc..fb1a6d11bca 100644 --- a/packages/ui/src/providers/Translation/index.tsx +++ b/packages/ui/src/providers/Translation/index.tsx @@ -7,7 +7,7 @@ import type { TFunction, } from '@payloadcms/translations' import type { Locale } from 'date-fns' -import type { ClientConfig } from 'payload/types' +import type { ClientConfig, LanguageOptions } from 'payload/types' import { t } from '@payloadcms/translations' import { importDateFNSLocale } from '@payloadcms/translations' @@ -16,11 +16,6 @@ import React, { createContext, useContext, useEffect, useState } from 'react' import { useRouteCache } from '../RouteCache/index.js' -export type LanguageOptions = { - label: string - value: string -}[] - type ContextType< TAdditionalTranslations = {}, TAdditionalClientTranslationKeys extends string = never, diff --git a/packages/ui/src/utilities/getFormState.ts b/packages/ui/src/utilities/getFormState.ts index 34e679d3b02..288da62f803 100644 --- a/packages/ui/src/utilities/getFormState.ts +++ b/packages/ui/src/utilities/getFormState.ts @@ -8,14 +8,16 @@ export const getFormState = async (args: { onError?: (data?: any) => Promise<void> | void serverURL: SanitizedConfig['serverURL'] signal?: AbortSignal + token?: string }): Promise<FormState> => { - const { apiRoute, body, onError, serverURL, signal } = args + const { apiRoute, body, onError, serverURL, signal, token } = args const res = await fetch(`${serverURL}${apiRoute}/form-state`, { body: JSON.stringify(body), credentials: 'include', headers: { 'Content-Type': 'application/json', + ...(token ? { Authorization: `JWT ${token}` } : {}), }, method: 'POST', signal, diff --git a/packages/ui/src/utilities/reduceFieldsToValues.ts b/packages/ui/src/utilities/reduceFieldsToValues.ts index 0d88d9b2a94..113deb42242 100644 --- a/packages/ui/src/utilities/reduceFieldsToValues.ts +++ b/packages/ui/src/utilities/reduceFieldsToValues.ts @@ -16,6 +16,8 @@ export const reduceFieldsToValues = ( ): Data => { let data = {} + if (!fields) return data + Object.keys(fields).forEach((key) => { if (ignoreDisableFormData === true || !fields[key]?.disableFormData) { data[key] = fields[key]?.value diff --git a/test/access-control/e2e.spec.ts b/test/access-control/e2e.spec.ts index 137d2e364e7..d31ac4cefb4 100644 --- a/test/access-control/e2e.spec.ts +++ b/test/access-control/e2e.spec.ts @@ -170,12 +170,12 @@ describe('access control', () => { test('should not have list url', async () => { await page.goto(restrictedUrl.list) - await expect(page.locator('.unauthorized')).toBeVisible() + await expect(page.locator('.not-found')).toBeVisible() }) test('should not have create url', async () => { await page.goto(restrictedUrl.create) - await expect(page.locator('.unauthorized')).toBeVisible() + await expect(page.locator('.not-found')).toBeVisible() }) test('should not have access to existing doc', async () => { @@ -321,13 +321,12 @@ describe('access control', () => { name: 'unrestricted-123', }, }) - await page.goto(unrestrictedURL.edit(unrestrictedDoc.id.toString())) - + const field = page.locator('#field-userRestrictedDocs') + await expect(field.locator('input')).toBeEnabled() const addDocButton = page.locator( '#userRestrictedDocs-add-new button.relationship-add-new__add-button.doc-drawer__toggler', ) - await addDocButton.click() const documentDrawer = page.locator('[id^=doc-drawer_user-restricted-collection_1_]') await expect(documentDrawer).toBeVisible() diff --git a/test/admin/components/FieldDescription/index.tsx b/test/admin/components/FieldDescription/index.tsx index fad5b340dc7..74bca4b675d 100644 --- a/test/admin/components/FieldDescription/index.tsx +++ b/test/admin/components/FieldDescription/index.tsx @@ -7,7 +7,8 @@ import React from 'react' export const FieldDescriptionComponent: DescriptionComponent = () => { const { path } = useFieldProps() - const { value } = useFormFields(([fields]) => fields[path]) + const field = useFormFields(([fields]) => (fields && fields?.[path]) || null) + const { value } = field || {} return ( <div className={`field-description-${path}`}> diff --git a/test/admin/components/views/CustomView/index.client.tsx b/test/admin/components/views/CustomView/index.client.tsx index 485b5548295..8bf7b4e521a 100644 --- a/test/admin/components/views/CustomView/index.client.tsx +++ b/test/admin/components/views/CustomView/index.client.tsx @@ -23,16 +23,15 @@ export const ClientForm: React.FC = () => { > <CustomPassword /> <ConfirmPassword /> - <FormSubmit>Submit</FormSubmit> </Form> ) } const CustomPassword: React.FC = () => { - const confirmPassword = useFormFields(([fields]) => { - return fields['confirm-password'] - }) + const confirmPassword = useFormFields( + ([fields]) => (fields && fields?.['confirm-password']) || null, + ) const confirmValue = confirmPassword.value diff --git a/test/admin/e2e/2/e2e.spec.ts b/test/admin/e2e/2/e2e.spec.ts index 0d4cfc5da6c..509a512282c 100644 --- a/test/admin/e2e/2/e2e.spec.ts +++ b/test/admin/e2e/2/e2e.spec.ts @@ -114,7 +114,7 @@ describe('admin2', () => { // prefill search with "a" from the query param await page.goto(`${postsUrl.list}?search=dennis`) - await page.waitForURL(`${postsUrl.list}?search=dennis`) + await page.waitForURL(new RegExp(`${postsUrl.list}\\?search=dennis`)) // input should be filled out, list should filter await expect(page.locator('.search-filter__input')).toHaveValue('dennis') @@ -624,7 +624,7 @@ describe('admin2', () => { test('should delete many', async () => { await page.goto(postsUrl.list) - await page.waitForURL(postsUrl.list) + await page.waitForURL(new RegExp(postsUrl.list)) // delete should not appear without selection await expect(page.locator('#confirm-delete')).toHaveCount(0) // select one row diff --git a/test/auth/e2e.spec.ts b/test/auth/e2e.spec.ts index 4f51bf4ba89..861db5e07ec 100644 --- a/test/auth/e2e.spec.ts +++ b/test/auth/e2e.spec.ts @@ -119,22 +119,18 @@ describe('auth', () => { await page.locator('#change-password').click() await page.locator('#field-password').fill('password') await page.locator('#field-confirm-password').fill('password') - await saveDocAndAssert(page) - await expect(page.locator('#field-email')).toHaveValue(emailBeforeSave) }) test('should have up-to-date user in `useAuth` hook', async () => { await page.goto(url.account) - + await page.waitForURL(url.account) await expect(page.locator('#users-api-result')).toHaveText('Hello, world!') await expect(page.locator('#use-auth-result')).toHaveText('Hello, world!') - const field = page.locator('#field-custom') await field.fill('Goodbye, world!') await saveDocAndAssert(page) - await expect(page.locator('#users-api-result')).toHaveText('Goodbye, world!') await expect(page.locator('#use-auth-result')).toHaveText('Goodbye, world!') }) diff --git a/test/fields-relationship/e2e.spec.ts b/test/fields-relationship/e2e.spec.ts index 7df9e37ef47..ee2060445e0 100644 --- a/test/fields-relationship/e2e.spec.ts +++ b/test/fields-relationship/e2e.spec.ts @@ -18,6 +18,7 @@ import type { import { ensureAutoLoginAndCompilationIsDone, initPageConsoleErrorCatch, + openCreateDocDrawer, openDocControls, openDocDrawer, saveDocAndAssert, @@ -141,19 +142,13 @@ describe('fields - relationship', () => { test('should create relationship', async () => { await page.goto(url.create) - const field = page.locator('#field-relationship') - + await expect(field.locator('input')).toBeEnabled() await field.click({ delay: 100 }) - const options = page.locator('.rs__option') - await expect(options).toHaveCount(2) // two docs - - // Select a relationship await options.nth(0).click() await expect(field).toContainText(relationOneDoc.id) - await saveDocAndAssert(page) }) @@ -186,30 +181,20 @@ describe('fields - relationship', () => { test('should create hasMany relationship', async () => { await page.goto(url.create) - const field = page.locator('#field-relationshipHasMany') + await expect(field.locator('input')).toBeEnabled() await field.click({ delay: 100 }) - const options = page.locator('.rs__option') - await expect(options).toHaveCount(2) // Two relationship options - const values = page.locator('#field-relationshipHasMany .relationship--multi-value-label__text') - - // Add one relationship await options.locator(`text=${relationOneDoc.id}`).click() await expect(values).toHaveText([relationOneDoc.id]) await expect(values).not.toHaveText([anotherRelationOneDoc.id]) - - // Add second relationship await field.click({ delay: 100 }) await options.locator(`text=${anotherRelationOneDoc.id}`).click() await expect(values).toHaveText([relationOneDoc.id, anotherRelationOneDoc.id]) - - // No options left await field.locator('.rs__input').click({ delay: 100 }) await expect(page.locator('.rs__menu')).toHaveText('No options') - await saveDocAndAssert(page) await wait(200) await expect(values).toHaveText([relationOneDoc.id, anotherRelationOneDoc.id]) @@ -257,49 +242,30 @@ describe('fields - relationship', () => { async function runFilterOptionsTest(fieldName: string) { await page.reload() await page.goto(url.edit(docWithExistingRelations.id)) - - // fill the first relation field const field = page.locator('#field-relationship') - + await expect(field.locator('input')).toBeEnabled() await field.click({ delay: 100 }) const options = page.locator('.rs__option') - await options.nth(0).click() await expect(field).toContainText(relationOneDoc.id) - - // then verify that the filtered field's options match let filteredField = page.locator(`#field-${fieldName} .react-select`) await filteredField.click({ delay: 100 }) let filteredOptions = filteredField.locator('.rs__option') await expect(filteredOptions).toHaveCount(1) // one doc await filteredOptions.nth(0).click() await expect(filteredField).toContainText(relationOneDoc.id) - - // change the first relation field await field.click({ delay: 100 }) await options.nth(1).click() await expect(field).toContainText(anotherRelationOneDoc.id) - - // Need to wait form state to come back - // before clicking save - await wait(2000) - - // Now, save the document. This should fail, as the filitered field doesn't match the selected relationship value + await wait(2000) // Need to wait form state to come back before clicking save await page.locator('#action-save').click() await expect(page.locator('.Toastify')).toContainText(`is invalid: ${fieldName}`) - - // then verify that the filtered field's options match filteredField = page.locator(`#field-${fieldName} .react-select`) - await filteredField.click({ delay: 100 }) - filteredOptions = filteredField.locator('.rs__option') - await expect(filteredOptions).toHaveCount(2) // two options because the currently selected option is still there await filteredOptions.nth(1).click() await expect(filteredField).toContainText(anotherRelationOneDoc.id) - - // Now, saving the document should succeed await saveDocAndAssert(page) } @@ -433,30 +399,17 @@ describe('fields - relationship', () => { test('should open document drawer and append newly created docs onto the parent field', async () => { await page.goto(url.edit(docWithExistingRelations.id)) - - const field = page.locator('#field-relationshipHasMany') - - // open the document drawer - const addNewButton = field.locator( - 'button.relationship-add-new__add-button.doc-drawer__toggler', - ) - await addNewButton.click() + await openCreateDocDrawer(page, '#field-relationshipHasMany') const documentDrawer = page.locator('[id^=doc-drawer_relation-one_1_]') await expect(documentDrawer).toBeVisible() - - // fill in the field and save the document, keep the drawer open for further testing const drawerField = documentDrawer.locator('#field-name') await drawerField.fill('Newly created document') const saveButton = documentDrawer.locator('#action-save') await saveButton.click() await expect(page.locator('.Toastify')).toContainText('successfully') - - // count the number of values in the field to ensure only one was added await expect( page.locator('#field-relationshipHasMany .value-container .rs__multi-value'), ).toHaveCount(1) - - // save the same document again to ensure the relationship field doesn't receive duplicative values await drawerField.fill('Updated document') await saveButton.click() await expect(page.locator('.Toastify')).toContainText('Updated successfully') @@ -469,12 +422,9 @@ describe('fields - relationship', () => { describe('existing relationships', () => { test('should highlight existing relationship', async () => { await page.goto(url.edit(docWithExistingRelations.id)) - const field = page.locator('#field-relationship') - - // Check dropdown options + await expect(field.locator('input')).toBeEnabled() await field.click({ delay: 100 }) - await expect(page.locator('.rs__option--is-selected')).toHaveCount(1) await expect(page.locator('.rs__option--is-selected')).toHaveText(relationOneDoc.id) }) diff --git a/test/fields/collections/Relationship/e2e.spec.ts b/test/fields/collections/Relationship/e2e.spec.ts index 93a3e2eebaa..be3a19e9149 100644 --- a/test/fields/collections/Relationship/e2e.spec.ts +++ b/test/fields/collections/Relationship/e2e.spec.ts @@ -12,7 +12,7 @@ import { ensureAutoLoginAndCompilationIsDone, exactText, initPageConsoleErrorCatch, - openDocDrawer, + openCreateDocDrawer, saveDocAndAssert, saveDocHotkeyAndAssert, } from '../../../helpers.js' @@ -77,26 +77,20 @@ describe('relationship', () => { test('should create inline relationship within field with many relations', async () => { await page.goto(url.create) - - await openDocDrawer(page, '#relationship-add-new .relationship-add-new__add-button') - + await openCreateDocDrawer(page, '#field-relationship') await page .locator('#field-relationship .relationship-add-new__relation-button--text-fields') .click() - const textField = page.locator('.drawer__content #field-text') + await expect(textField).toBeEnabled() const textValue = 'hello' - await textField.fill(textValue) - await page.locator('[id^=doc-drawer_text-fields_1_] #action-save').click() await expect(page.locator('.Toastify')).toContainText('successfully') await page.locator('[id^=close-drawer__doc-drawer_text-fields_1_]').click() - await expect( page.locator('#field-relationship .relationship--single-value__text'), ).toContainText(textValue) - await page.locator('#action-save').click() await expect(page.locator('.Toastify')).toContainText('successfully') }) @@ -105,7 +99,7 @@ describe('relationship', () => { await page.goto(url.create) await page.waitForURL(`**/${url.create}`) // Open first modal - await openDocDrawer(page, '#relationToSelf-add-new .relationship-add-new__add-button') + await openCreateDocDrawer(page, '#field-relationToSelf') // Fill first modal's required relationship field await page.locator('[id^=doc-drawer_relationship-fields_1_] #field-relationship').click() @@ -115,11 +109,10 @@ describe('relationship', () => { ) .click() - // Open second modal - await openDocDrawer( - page, + const secondModalButton = page.locator( '[id^=doc-drawer_relationship-fields_1_] #relationToSelf-add-new button', ) + await secondModalButton.click() // Fill second modal's required relationship field await page.locator('[id^=doc-drawer_relationship-fields_2_] #field-relationship').click() @@ -249,7 +242,7 @@ describe('relationship', () => { await page.goto(url.create) await page.waitForURL(`**/${url.create}`) // First fill out the relationship field, as it's required - await openDocDrawer(page, '#relationship-add-new .relationship-add-new__add-button') + await openCreateDocDrawer(page, '#field-relationship') await page .locator('#field-relationship .relationship-add-new__relation-button--text-fields') .click() @@ -264,7 +257,7 @@ describe('relationship', () => { // Create a new doc for the `relationshipHasMany` field await expect.poll(() => page.url(), { timeout: POLL_TOPASS_TIMEOUT }).not.toContain('create') - await openDocDrawer(page, '#field-relationshipHasMany .relationship-add-new__add-button') + await openCreateDocDrawer(page, '#field-relationshipHasMany') const value = 'Hello, world!' await page.locator('.drawer__content #field-text').fill(value) @@ -313,7 +306,7 @@ describe('relationship', () => { test('should save using hotkey in edit document drawer', async () => { await page.goto(url.create) // First fill out the relationship field, as it's required - await openDocDrawer(page, '#relationship-add-new .relationship-add-new__add-button') + await openCreateDocDrawer(page, '#field-relationship') await page.locator('#field-relationship .value-container').click() await wait(500) // Select "Seeded text document" relationship @@ -354,7 +347,7 @@ describe('relationship', () => { test.skip('should bypass min rows validation when no rows present and field is not required', async () => { await page.goto(url.create) // First fill out the relationship field, as it's required - await openDocDrawer(page, '#relationship-add-new .relationship-add-new__add-button') + await openCreateDocDrawer(page, '#field-relationship') await page.locator('#field-relationship .value-container').click() await page.getByText('Seeded text document', { exact: true }).click() @@ -366,7 +359,7 @@ describe('relationship', () => { await page.goto(url.create) await page.waitForURL(url.create) // First fill out the relationship field, as it's required - await openDocDrawer(page, '#relationship-add-new .relationship-add-new__add-button') + await openCreateDocDrawer(page, '#field-relationship') await page.locator('#field-relationship .value-container').click() await page.getByText('Seeded text document', { exact: true }).click() @@ -425,7 +418,7 @@ describe('relationship', () => { await createRelationshipFieldDoc({ value: textDoc.id, relationTo: 'text-fields' }) await page.goto(url.list) - await page.waitForURL(url.list) + await page.waitForURL(new RegExp(url.list)) await wait(400) await page.locator('.list-controls__toggle-columns').click() @@ -439,6 +432,7 @@ describe('relationship', () => { await wait(400) const conditionField = page.locator('.condition__field') + await expect(conditionField.locator('input')).toBeEnabled() await conditionField.click() await wait(400) @@ -447,6 +441,7 @@ describe('relationship', () => { await wait(400) const operatorField = page.locator('.condition__operator') + await expect(operatorField.locator('input')).toBeEnabled() await operatorField.click() await wait(400) @@ -455,6 +450,7 @@ describe('relationship', () => { await wait(400) const valueField = page.locator('.condition__value') + await expect(valueField.locator('input')).toBeEnabled() await valueField.click() await wait(400) diff --git a/test/fields/collections/RichText/e2e.spec.ts b/test/fields/collections/RichText/e2e.spec.ts index 4f93ceb6df2..689b9908dd8 100644 --- a/test/fields/collections/RichText/e2e.spec.ts +++ b/test/fields/collections/RichText/e2e.spec.ts @@ -183,8 +183,6 @@ describe('Rich Text', () => { test('should not create new url link when read only', async () => { await navigateToRichTextFields() - - // Attempt to open link popup const modalTrigger = page.locator('.rich-text--read-only .rich-text__toolbar button .link') await expect(modalTrigger).toBeDisabled() }) @@ -421,19 +419,14 @@ describe('Rich Text', () => { }) test('should not take value from previous block', async () => { await navigateToRichTextFields() - - // check first block value - const textField = page.locator('#field-blocks__0__text') - await expect(textField).toHaveValue('Regular text') - - // remove the first block + await page.locator('#field-blocks').scrollIntoViewIfNeeded() + await expect(page.locator('#field-blocks__0__text')).toBeVisible() + await expect(page.locator('#field-blocks__0__text')).toHaveValue('Regular text') const editBlock = page.locator('#blocks-row-0 .popup-button') await editBlock.click() const removeButton = page.locator('#blocks-row-0').getByRole('button', { name: 'Remove' }) await expect(removeButton).toBeVisible() await removeButton.click() - - // check new first block value const richTextField = page.locator('#field-blocks__0__text') const richTextValue = await richTextField.innerText() expect(richTextValue).toContain('Rich text') diff --git a/test/fields/e2e.spec.ts b/test/fields/e2e.spec.ts index 90d8df697d6..6223fab907d 100644 --- a/test/fields/e2e.spec.ts +++ b/test/fields/e2e.spec.ts @@ -146,12 +146,13 @@ describe('fields', () => { test('should create', async () => { const input = '{"foo": "bar"}' - await page.goto(url.create) - const json = page.locator('.json-field .inputarea') - await json.fill(input) - - await saveDocAndAssert(page, '.form-submit button') + await page.waitForURL(url.create) + await expect(() => expect(page.locator('.json-field .code-editor')).toBeVisible()).toPass({ + timeout: POLL_TOPASS_TIMEOUT, + }) + await page.locator('.json-field .inputarea').fill(input) + await saveDocAndAssert(page) await expect(page.locator('.json-field')).toContainText('"foo": "bar"') }) }) @@ -256,13 +257,15 @@ describe('fields', () => { test('should have disabled admin sorting', async () => { await page.goto(url.create) - const field = page.locator('#field-disableSort .array-actions__action-chevron') + const field = page.locator('#field-disableSort > div > div > .array-actions__action-chevron') expect(await field.count()).toEqual(0) }) test('the drag handle should be hidden', async () => { await page.goto(url.create) - const field = page.locator('#field-disableSort .collapsible__drag') + const field = page.locator( + '#field-disableSort > .blocks-field__rows > div > div > .collapsible__drag', + ) expect(await field.count()).toEqual(0) }) }) @@ -275,13 +278,15 @@ describe('fields', () => { test('should have disabled admin sorting', async () => { await page.goto(url.create) - const field = page.locator('#field-disableSort .array-actions__action-chevron') + const field = page.locator('#field-disableSort > div > div > .array-actions__action-chevron') expect(await field.count()).toEqual(0) }) test('the drag handle should be hidden', async () => { await page.goto(url.create) - const field = page.locator('#field-disableSort .collapsible__drag') + const field = page.locator( + '#field-disableSort > .blocks-field__rows > div > div > .collapsible__drag', + ) expect(await field.count()).toEqual(0) }) }) diff --git a/test/helpers.ts b/test/helpers.ts index fdbb8a3b3c8..feb24b2f0a6 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -75,6 +75,10 @@ export async function ensureAutoLoginAndCompilationIsDone({ await page.goto(adminURL) await page.waitForURL(adminURL) + await expect(() => expect(page.locator('.template-default')).toBeVisible()).toPass({ + timeout: POLL_TOPASS_TIMEOUT, + }) + await expect(() => expect(page.url()).not.toContain(`${adminRoute}${loginRoute}`)).toPass({ timeout: POLL_TOPASS_TIMEOUT, }) @@ -85,7 +89,6 @@ export async function ensureAutoLoginAndCompilationIsDone({ timeout: POLL_TOPASS_TIMEOUT, }) - // Check if hero is there await expect(page.locator('.dashboard__label').first()).toBeVisible() } @@ -200,6 +203,16 @@ export async function openDocDrawer(page: Page, selector: string): Promise<void> await wait(500) // wait for drawer form state to initialize } +export async function openCreateDocDrawer(page: Page, fieldSelector: string): Promise<void> { + await wait(500) // wait for parent form state to initialize + const relationshipField = page.locator(fieldSelector) + await expect(relationshipField.locator('input')).toBeEnabled() + const addNewButton = relationshipField.locator('.relationship-add-new__add-button') + await expect(addNewButton).toBeVisible() + await addNewButton.click() + await wait(500) // wait for drawer form state to initialize +} + export async function closeNav(page: Page): Promise<void> { if (!(await page.locator('.template-default.template-default--nav-open').isVisible())) return await page.locator('.nav-toggler >> visible=true').click() diff --git a/test/localization/e2e.spec.ts b/test/localization/e2e.spec.ts index 31bf66fdd68..e4cc3f69cec 100644 --- a/test/localization/e2e.spec.ts +++ b/test/localization/e2e.spec.ts @@ -123,27 +123,15 @@ describe('Localization', () => { test('create arabic post, add english', async () => { await page.goto(url.create) - const newLocale = 'ar' - - // Change to Arabic await changeLocale(page, newLocale) - await fillValues({ description, title: arabicTitle }) await saveDocAndAssert(page) - - // Change back to English await changeLocale(page, defaultLocale) - - // Localized field should not be populated await expect(page.locator('#field-title')).toBeEmpty() await expect(page.locator('#field-description')).toHaveValue(description) - - // Add English - await fillValues({ description, title }) await saveDocAndAssert(page) - await expect(page.locator('#field-title')).toHaveValue(title) await expect(page.locator('#field-description')).toHaveValue(description) }) @@ -175,56 +163,45 @@ describe('Localization', () => { await page.goto(url.edit(id)) await page.waitForURL(`**${url.edit(id)}`) await openDocControls(page) - - // duplicate document await page.locator('#action-duplicate').click() await expect(page.locator('.Toastify')).toContainText('successfully') await expect.poll(() => page.url(), { timeout: POLL_TOPASS_TIMEOUT }).not.toContain(id) - - // check fields await expect(page.locator('#field-title')).toHaveValue(englishTitle) await changeLocale(page, spanishLocale) - + await expect(page.locator('#field-title')).toBeEnabled() await expect(page.locator('#field-title')).toHaveValue(spanishTitle) - + await expect(page.locator('#field-localizedCheckbox')).toBeEnabled() + await page.reload() // TODO: remove this line, the checkbox _is not_ checked, but Playwright is unable to detect it without a reload for some reason await expect(page.locator('#field-localizedCheckbox')).not.toBeChecked() }) test('should duplicate localized checkbox correctly', async () => { await page.goto(url.create) await page.waitForURL(url.create) - await changeLocale(page, defaultLocale) await fillValues({ description, title: englishTitle }) + await expect(page.locator('#field-localizedCheckbox')).toBeEnabled() await page.locator('#field-localizedCheckbox').click() - await page.locator('#action-save').click() - // wait for navigation to update route await expect.poll(() => page.url(), { timeout: POLL_TOPASS_TIMEOUT }).not.toContain('create') const collectionUrl = page.url() - // ensure spanish is not checked await changeLocale(page, spanishLocale) - + await expect(page.locator('#field-localizedCheckbox')).toBeEnabled() + await page.reload() // TODO: remove this line, the checkbox _is not_ checked, but Playwright is unable to detect it without a reload for some reason await expect(page.locator('#field-localizedCheckbox')).not.toBeChecked() - - // duplicate doc await changeLocale(page, defaultLocale) await openDocControls(page) await page.locator('#action-duplicate').click() - - // wait for navigation to update route await expect .poll(() => page.url(), { timeout: POLL_TOPASS_TIMEOUT }) .not.toContain(collectionUrl) - - // finally change locale to spanish await changeLocale(page, spanishLocale) - + await expect(page.locator('#field-localizedCheckbox')).toBeEnabled() + await page.reload() // TODO: remove this line, the checkbox _is not_ checked, but Playwright is unable to detect it without a reload for some reason await expect(page.locator('#field-localizedCheckbox')).not.toBeChecked() }) test('should duplicate even if missing some localized data', async () => { - // create a localized required doc await page.goto(urlWithRequiredLocalizedFields.create) await changeLocale(page, defaultLocale) await page.locator('#field-title').fill(englishTitle) @@ -233,21 +210,12 @@ describe('Localization', () => { await page.fill('#field-layout__0__text', 'test') await expect(page.locator('#field-layout__0__text')).toHaveValue('test') await saveDocAndAssert(page) - const originalID = await page.locator('.id-label').innerText() - - // duplicate await openDocControls(page) await page.locator('#action-duplicate').click() await expect(page.locator('.id-label')).not.toContainText(originalID) - - // verify that the locale did copy await expect(page.locator('#field-title')).toHaveValue(englishTitle) - - // await the success toast await expect(page.locator('.Toastify')).toContainText('successfully duplicated') - - // expect that the document has a new id await expect(page.locator('.id-label')).not.toContainText(originalID) }) }) diff --git a/test/plugin-form-builder/e2e.spec.ts b/test/plugin-form-builder/e2e.spec.ts index e96fdfec061..1af13e00c96 100644 --- a/test/plugin-form-builder/e2e.spec.ts +++ b/test/plugin-form-builder/e2e.spec.ts @@ -107,9 +107,6 @@ test.describe('Form Builder', () => { }) test('can create form submission', async () => { - await page.goto(submissionsUrl.list) - await page.waitForURL(submissionsUrl.list) - const { docs } = await payload.find({ collection: 'forms', }) diff --git a/test/uploads/e2e.spec.ts b/test/uploads/e2e.spec.ts index 5be19bd986d..debec00f8e6 100644 --- a/test/uploads/e2e.spec.ts +++ b/test/uploads/e2e.spec.ts @@ -254,7 +254,7 @@ describe('uploads', () => { ) }) - test('Should render adminThumbnail when using a function', async () => { + test('should render adminThumbnail when using a function', async () => { await page.reload() // Flakey test, it likely has to do with the test that comes before it. Trace viewer is not helpful when it fails. await page.goto(adminThumbnailFunctionURL.list) await page.waitForURL(adminThumbnailFunctionURL.list) @@ -267,7 +267,7 @@ describe('uploads', () => { ) }) - test('Should render adminThumbnail when using a specific size', async () => { + test('should render adminThumbnail when using a specific size', async () => { await page.goto(adminThumbnailSizeURL.list) await page.waitForURL(adminThumbnailSizeURL.list) @@ -280,7 +280,7 @@ describe('uploads', () => { await expect(audioUploadImage).toBeVisible() }) - test('Should detect correct mimeType', async () => { + test('should detect correct mimeType', async () => { await page.goto(mediaURL.create) await page.waitForURL(mediaURL.create) await page.setInputFiles('input[type="file"]', path.resolve(dirname, './image.png')) diff --git a/test/versions/e2e.spec.ts b/test/versions/e2e.spec.ts index 763fc8a8f64..af0789b048b 100644 --- a/test/versions/e2e.spec.ts +++ b/test/versions/e2e.spec.ts @@ -26,6 +26,7 @@ import type { Page } from '@playwright/test' import { expect, test } from '@playwright/test' import path from 'path' +import { wait } from 'payload/utilities' import { fileURLToPath } from 'url' import type { PayloadTestSDK } from '../helpers/sdk/index.js' @@ -162,31 +163,19 @@ describe('versions', () => { const title = 'autosave title' const description = 'autosave description' await page.goto(autosaveURL.create) - - // fill the fields + // gets redirected from /create to /slug/id due to autosave + await page.waitForURL(new RegExp(`${autosaveURL.edit('')}`)) + await wait(500) + await expect(page.locator('#field-title')).toBeEnabled() await page.locator('#field-title').fill(title) + await expect(page.locator('#field-description')).toBeEnabled() await page.locator('#field-description').fill(description) - - // wait for autosave await waitForAutoSaveToRunAndComplete(page) - - // go to list await page.goto(autosaveURL.list) - - // expect the status to be draft await expect(findTableCell(page, '_status', title)).toContainText('Draft') - - // select the row - // await page.locator('.row-1 .select-row__checkbox').click() await selectTableRow(page, title) - - // click the publish many await page.locator('.publish-many__toggle').click() - - // confirm the dialog await page.locator('#confirm-publish').click() - - // expect the status to be published await expect(findTableCell(page, '_status', title)).toContainText('Published') }) @@ -278,21 +267,19 @@ describe('versions', () => { test('collection — tab displays proper number of versions', async () => { await page.goto(url.list) - const linkToDoc = page .locator('tbody tr .cell-title a', { hasText: exactText('Title With Many Versions 11'), }) .first() - expect(linkToDoc).toBeTruthy() await linkToDoc.click() - const versionsTab = page.locator('.doc-tab', { hasText: 'Versions', }) await versionsTab.waitFor({ state: 'visible' }) - + const versionsPill = versionsTab.locator('.doc-tab__count--has-count') + await versionsPill.waitFor({ state: 'visible' }) const versionCount = await versionsTab.locator('.doc-tab__count').first().textContent() expect(versionCount).toBe('11') }) @@ -322,32 +309,21 @@ describe('versions', () => { test('should restore version with correct data', async () => { await page.goto(url.create) await page.waitForURL(url.create) - - // publish a doc await page.locator('#field-title').fill('v1') await page.locator('#field-description').fill('hello') await saveDocAndAssert(page) - - // save a draft await page.locator('#field-title').fill('v2') await saveDocAndAssert(page, '#action-save-draft') - - // go to versions list view const savedDocURL = page.url() await page.goto(`${savedDocURL}/versions`) - await page.waitForURL(`${savedDocURL}/versions`) - - // select the first version (row 2) + await page.waitForURL(new RegExp(`${savedDocURL}/versions`)) const row2 = page.locator('tbody .row-2') const versionID = await row2.locator('.cell-id').textContent() await page.goto(`${savedDocURL}/versions/${versionID}`) - await page.waitForURL(`${savedDocURL}/versions/${versionID}`) - - // restore doc + await page.waitForURL(new RegExp(`${savedDocURL}/versions/${versionID}`)) await page.locator('.pill.restore-version').click() await page.locator('button:has-text("Confirm")').click() - await page.waitForURL(savedDocURL) - + await page.waitForURL(new RegExp(savedDocURL)) await expect(page.locator('#field-title')).toHaveValue('v1') }) @@ -385,16 +361,12 @@ describe('versions', () => { test('global - should autosave', async () => { const url = new AdminUrlUtil(serverURL, autoSaveGlobalSlug) - // fill out global title and wait for autosave await page.goto(url.global(autoSaveGlobalSlug)) await page.waitForURL(`**/${autoSaveGlobalSlug}`) const titleField = page.locator('#field-title') - await titleField.fill('global title') await waitForAutoSaveToRunAndComplete(page) await expect(titleField).toHaveValue('global title') - - // refresh the page and ensure value autosaved await page.goto(url.global(autoSaveGlobalSlug)) await expect(page.locator('#field-title')).toHaveValue('global title') }) @@ -405,41 +377,25 @@ describe('versions', () => { const englishTitle = 'english title' const spanishTitle = 'spanish title' const newDescription = 'new description' - await page.goto(autosaveURL.create) // gets redirected from /create to /slug/id due to autosave - await page.waitForURL(`${autosaveURL.list}/**`) - await expect(() => expect(page.url()).not.toContain(`/create`)).toPass({ - timeout: POLL_TOPASS_TIMEOUT, - }) + await page.waitForURL(new RegExp(`${autosaveURL.edit('')}`)) + await wait(500) const titleField = page.locator('#field-title') - const descriptionField = page.locator('#field-description') - - // fill out en doc + await expect(titleField).toBeEnabled() await titleField.fill(englishTitle) + const descriptionField = page.locator('#field-description') + await expect(descriptionField).toBeEnabled() await descriptionField.fill('description') await waitForAutoSaveToRunAndComplete(page) - - // change locale to spanish await changeLocale(page, es) - // set localized title field await titleField.fill(spanishTitle) await waitForAutoSaveToRunAndComplete(page) - - // change locale back to en await changeLocale(page, en) - // verify en loads its own title await expect(titleField).toHaveValue(englishTitle) - // change non-localized description field await descriptionField.fill(newDescription) await waitForAutoSaveToRunAndComplete(page) - - // change locale to spanish await changeLocale(page, es) - - // reload page in spanish - // title should not be english title - // description should be new description await page.reload() await expect(titleField).toHaveValue(spanishTitle) await expect(descriptionField).toHaveValue(newDescription) @@ -487,41 +443,30 @@ describe('versions', () => { }) test('collection — autosave should only update the current document', async () => { - // create and save first doc await page.goto(autosaveURL.create) - // Should redirect from /create to /[collectionslug]/[new id] due to auto-save - await page.waitForURL(`${autosaveURL.list}/**`) - await expect(() => expect(page.url()).not.toContain(`/create`)).toPass({ - timeout: POLL_TOPASS_TIMEOUT, - }) // Make sure this doesnt match for list view and /create view, but ONLY for the ID edit view - + // gets redirected from /create to /slug/id due to autosave + await page.waitForURL(new RegExp(`${autosaveURL.edit('')}`)) + await wait(500) + await expect(page.locator('#field-title')).toBeEnabled() await page.locator('#field-title').fill('first post title') + await expect(page.locator('#field-description')).toBeEnabled() await page.locator('#field-description').fill('first post description') await saveDocAndAssert(page) await waitForAutoSaveToComplete(page) // Make sure nothing is auto-saving before next steps - - // create and save second doc await page.goto(autosaveURL.create) - // Should redirect from /create to /[collectionslug]/[new id] due to auto-save - await page.waitForURL(`${autosaveURL.list}/**`) - await expect(() => expect(page.url()).not.toContain(`/create`)).toPass({ - timeout: POLL_TOPASS_TIMEOUT, - }) // Make sure this doesnt match for list view and /create view, but only for the ID edit view - + // gets redirected from /create to /slug/id due to autosave + await page.waitForURL(new RegExp(`${autosaveURL.edit('')}`)) await waitForAutoSaveToComplete(page) // Make sure nothing is auto-saving before next steps - + await wait(500) + await expect(page.locator('#field-title')).toBeEnabled() await page.locator('#field-title').fill('second post title') + await expect(page.locator('#field-description')).toBeEnabled() await page.locator('#field-description').fill('second post description') - // publish changes await saveDocAndAssert(page) await waitForAutoSaveToComplete(page) // Make sure nothing is auto-saving before next steps - - // update second doc and wait for autosave await page.locator('#field-title').fill('updated second post title') await page.locator('#field-description').fill('updated second post description') await waitForAutoSaveToRunAndComplete(page) - - // verify that the first doc is unchanged await page.goto(autosaveURL.list) const secondRowLink = page.locator('tbody tr:nth-child(2) .cell-title a') const docURL = await secondRowLink.getAttribute('href')
f968b92968f1aa1127984c2f101aa051fc4f158d
2023-10-09 01:40:35
Tylan Davis
fix: removes quotes in keywords
false
removes quotes in keywords
fix
diff --git a/docs/live-preview/overview.mdx b/docs/live-preview/overview.mdx index a3330aa2221..04781e5ab5d 100644 --- a/docs/live-preview/overview.mdx +++ b/docs/live-preview/overview.mdx @@ -3,7 +3,7 @@ title: Live Preview label: Overview order: 10 desc: With Live Preview you can render your front-end application directly within the Admin panel. Your changes take effect as you type. No save needed. -keywords: 'live preview', 'preview', 'live', 'iframe', 'iframe preview', 'visual editing', 'design' +keywords: live preview, preview, live, iframe, iframe preview, visual editing, design --- **With Live Preview you can render your front-end application directly within the Admin panel. As you type, your changes take effect in real-time. No need to save a draft or publish your changes.**
696a215dd0de2c534402cb9c7de12478937ebe79
2023-06-26 21:15:52
Alessio Gravili
feat: move some stuff over to the new adapter pattern (#2880)
false
move some stuff over to the new adapter pattern (#2880)
feat
diff --git a/src/auth/operations/resetPassword.ts b/src/auth/operations/resetPassword.ts index 237bab9b83b..9fa8c8f0825 100644 --- a/src/auth/operations/resetPassword.ts +++ b/src/auth/operations/resetPassword.ts @@ -75,15 +75,12 @@ async function resetPassword(args: Arguments): Promise<Result> { user._verified = true; } - const { updatedDocs } = await payload.db.update({ + const doc = await payload.db.updateOne({ collection: collectionConfig.slug, - where: { - id: { equals: user.id }, - }, + id: user.id, data: user, }); - const doc = sanitizeInternalFields(updatedDocs[0]); await authenticateLocalStrategy({ password: data.password, doc }); diff --git a/src/auth/operations/unlock.ts b/src/auth/operations/unlock.ts index 4c0e36257f6..5f9eda6fdf5 100644 --- a/src/auth/operations/unlock.ts +++ b/src/auth/operations/unlock.ts @@ -24,7 +24,7 @@ async function unlock(args: Args): Promise<boolean> { }, req, req: { - payload, + locale, }, overrideAccess, } = args; @@ -49,6 +49,7 @@ async function unlock(args: Args): Promise<boolean> { collection: collectionConfig.slug, where: { email: { equals: data.email.toLowerCase() } }, limit: 1, + locale, }); const [user] = docs; diff --git a/src/auth/operations/verifyEmail.ts b/src/auth/operations/verifyEmail.ts index 878a6a68ab1..9b2afa86092 100644 --- a/src/auth/operations/verifyEmail.ts +++ b/src/auth/operations/verifyEmail.ts @@ -32,11 +32,9 @@ async function verifyEmail(args: Args): Promise<boolean> { if (!user) throw new APIError('Verification token is invalid.', httpStatus.BAD_REQUEST); if (user && user._verified === true) throw new APIError('This account has already been activated.', httpStatus.ACCEPTED); - await req.payload.db.update({ + await req.payload.db.updateOne({ collection: collection.config.slug, - where: { - id: user.id, - }, + id: user.id, data: { _verified: true, _verificationToken: undefined, diff --git a/src/collections/config/types.ts b/src/collections/config/types.ts index 0bf8f1ece69..0c1ac23f9e7 100644 --- a/src/collections/config/types.ts +++ b/src/collections/config/types.ts @@ -4,6 +4,7 @@ import { AggregatePaginateModel, IndexDefinition, IndexOptions, Model, PaginateM import { GraphQLInputObjectType, GraphQLNonNull, GraphQLObjectType } from 'graphql'; import { Response } from 'express'; import { Config as GeneratedTypes } from 'payload/generated-types'; +import { Where } from '../../types'; import { Access, Endpoint, EntityDescription, GeneratePreviewURL } from '../../config/types'; import { Field } from '../../fields/config/types'; import { PayloadRequest } from '../../express/types'; @@ -28,7 +29,7 @@ interface PassportLocalModel { } export interface CollectionModel extends Model<any>, PaginateModel<any>, AggregatePaginateModel<any>, PassportLocalModel { - buildQuery: (args: BuildQueryArgs) => Promise<Record<string, unknown>> + buildQuery: (args: BuildQueryArgs) => Promise<Record<string, unknown>> // TODO: Delete this } export interface AuthCollectionModel extends CollectionModel { @@ -99,13 +100,13 @@ export type AfterChangeHook<T extends TypeWithID = any> = (args: { export type BeforeReadHook<T extends TypeWithID = any> = (args: { doc: T; req: PayloadRequest; - query: { [key: string]: any }; + query: Where; }) => any; export type AfterReadHook<T extends TypeWithID = any> = (args: { doc: T; req: PayloadRequest; - query?: { [key: string]: any }; + query?: Where; findMany?: boolean }) => any; diff --git a/src/collections/graphql/resolvers/findVersionByID.ts b/src/collections/graphql/resolvers/findVersionByID.ts index e2e8ada8a4a..d3562195c1b 100644 --- a/src/collections/graphql/resolvers/findVersionByID.ts +++ b/src/collections/graphql/resolvers/findVersionByID.ts @@ -1,10 +1,11 @@ /* eslint-disable no-param-reassign */ import { Response } from 'express'; -import { Collection } from '../../config/types'; +import { Collection, TypeWithID } from '../../config/types'; import { PayloadRequest } from '../../../express/types'; import findVersionByID from '../../operations/findVersionByID'; +import type { TypeWithVersion } from '../../../versions/types'; -export type Resolver = ( +export type Resolver<T extends TypeWithID = any> = ( _: unknown, args: { locale?: string @@ -16,7 +17,7 @@ export type Resolver = ( req: PayloadRequest, res: Response } -) => Promise<Document> +) => Promise<TypeWithVersion<T>> export default function findVersionByIDResolver(collection: Collection): Resolver { return async function resolver(_, args, context) { diff --git a/src/collections/operations/deleteByID.ts b/src/collections/operations/deleteByID.ts index 6e6196831f1..0e77d8e4de1 100644 --- a/src/collections/operations/deleteByID.ts +++ b/src/collections/operations/deleteByID.ts @@ -1,6 +1,5 @@ import { Config as GeneratedTypes } from 'payload/generated-types'; import { PayloadRequest } from '../../express/types'; -import sanitizeInternalFields from '../../utilities/sanitizeInternalFields'; import { Forbidden, NotFound } from '../../errors'; import executeAccess from '../../auth/executeAccess'; import { BeforeOperationHook, Collection } from '../config/types'; @@ -40,7 +39,6 @@ async function deleteByID<TSlug extends keyof GeneratedTypes['collections']>(inc const { depth, collection: { - Model, config: collectionConfig, }, id, @@ -80,34 +78,31 @@ async function deleteByID<TSlug extends keyof GeneratedTypes['collections']>(inc // Retrieve document // ///////////////////////////////////// - const query = await Model.buildQuery({ - payload, - locale: req.locale, + const { docs } = await req.payload.db.find({ + collection: collectionConfig.slug, where: combineQueries({ id: { equals: id } }, accessResults), + locale: req.locale, + limit: 1, }); - const docToDelete = await Model.findOne(query); + const [docToDelete] = docs; if (!docToDelete && !hasWhereAccess) throw new NotFound(t); if (!docToDelete && hasWhereAccess) throw new Forbidden(t); - const resultToDelete = docToDelete.toJSON({ virtuals: true }); - await deleteAssociatedFiles({ config, collectionConfig, doc: resultToDelete, t, overrideDelete: true }); + await deleteAssociatedFiles({ config, collectionConfig, doc: docToDelete, t, overrideDelete: true }); // ///////////////////////////////////// // Delete document // ///////////////////////////////////// - const doc = await Model.findOneAndDelete({ _id: id }); - let result: Document = doc.toJSON({ virtuals: true }); + let result = await req.payload.db.deleteOne({ + collection: collectionConfig.slug, + id, + }); - // custom id type reset - result.id = result._id; - result = JSON.stringify(result); - result = JSON.parse(result); - result = sanitizeInternalFields(result); // ///////////////////////////////////// // Delete Preferences diff --git a/src/collections/operations/findByID.ts b/src/collections/operations/findByID.ts index ea825254511..9f340567ff0 100644 --- a/src/collections/operations/findByID.ts +++ b/src/collections/operations/findByID.ts @@ -8,6 +8,7 @@ import executeAccess from '../../auth/executeAccess'; import replaceWithDraftIfAvailable from '../../versions/drafts/replaceWithDraftIfAvailable'; import { afterRead } from '../../fields/hooks/afterRead'; import { combineQueries } from '../../database/combineQueries'; +import { FindArgs } from '../../database/types'; export type Arguments = { collection: Collection @@ -42,14 +43,13 @@ async function findByID<T extends TypeWithID>( const { depth, collection: { - Model, config: collectionConfig, }, id, req, req: { t, - payload, + locale, }, disableErrors, currentDepth, @@ -67,22 +67,25 @@ async function findByID<T extends TypeWithID>( // If errors are disabled, and access returns false, return null if (accessResult === false) return null; - const query = await Model.buildQuery({ - where: combineQueries({ _id: { equals: id } }, accessResult), - payload, - locale: req.locale, - }); + + const findArgs: FindArgs = { + collection: collectionConfig.slug, + where: combineQueries({ id: { equals: id } }, accessResult), + locale, + limit: 1, + }; // ///////////////////////////////////// // Find by ID // ///////////////////////////////////// - if (!query.$and[0]._id) throw new NotFound(t); + if (!findArgs.where.and[0].id) throw new NotFound(t); if (!req.findByID) req.findByID = {}; if (!req.findByID[collectionConfig.slug]) { - const nonMemoizedFindByID = async (q) => Model.findOne(q, {}).lean(); + const nonMemoizedFindByID = async (query: FindArgs) => (await req.payload.db.find(query)).docs[0]; + req.findByID[collectionConfig.slug] = memoize(nonMemoizedFindByID, { isPromise: true, maxSize: 100, @@ -92,7 +95,7 @@ async function findByID<T extends TypeWithID>( }); } - let result = await req.findByID[collectionConfig.slug](query); + let result = await req.findByID[collectionConfig.slug](findArgs) as T; if (!result) { if (!disableErrors) { @@ -113,7 +116,6 @@ async function findByID<T extends TypeWithID>( if (collectionConfig.versions?.drafts && draftEnabled) { result = await replaceWithDraftIfAvailable({ - payload, entity: collectionConfig, entityType: 'collection', doc: result, @@ -132,7 +134,7 @@ async function findByID<T extends TypeWithID>( result = await hook({ req, - query, + query: findArgs.where, doc: result, }) || result; }, Promise.resolve()); @@ -160,7 +162,7 @@ async function findByID<T extends TypeWithID>( result = await hook({ req, - query, + query: findArgs.where, doc: result, }) || result; }, Promise.resolve()); diff --git a/src/collections/operations/findVersionByID.ts b/src/collections/operations/findVersionByID.ts index 0ddf6d6cdbd..aeefbb4e5fa 100644 --- a/src/collections/operations/findVersionByID.ts +++ b/src/collections/operations/findVersionByID.ts @@ -1,7 +1,7 @@ /* eslint-disable no-underscore-dangle */ import httpStatus from 'http-status'; import { PayloadRequest } from '../../express/types'; -import { Collection } from '../config/types'; +import { Collection, TypeWithID } from '../config/types'; import { APIError, Forbidden, NotFound } from '../../errors'; import executeAccess from '../../auth/executeAccess'; import { TypeWithVersion } from '../../versions/types'; @@ -19,7 +19,7 @@ export type Arguments = { depth?: number } -async function findVersionByID<T extends TypeWithVersion<T> = any>(args: Arguments): Promise<T> { +async function findVersionByID<T extends TypeWithID = any>(args: Arguments): Promise<TypeWithVersion<T>> { const { depth, collection: { diff --git a/src/collections/operations/restoreVersion.ts b/src/collections/operations/restoreVersion.ts index 7d9997ae0b1..56f96660268 100644 --- a/src/collections/operations/restoreVersion.ts +++ b/src/collections/operations/restoreVersion.ts @@ -5,11 +5,11 @@ import { Collection, TypeWithID } from '../config/types'; import { APIError, Forbidden, NotFound } from '../../errors'; import executeAccess from '../../auth/executeAccess'; import { hasWhereAccessResult } from '../../auth/types'; -import sanitizeInternalFields from '../../utilities/sanitizeInternalFields'; import { afterChange } from '../../fields/hooks/afterChange'; import { afterRead } from '../../fields/hooks/afterRead'; import { getLatestCollectionVersion } from '../../versions/getLatestCollectionVersion'; import { combineQueries } from '../../database/combineQueries'; +import { FindArgs } from '../../database/types'; export type Arguments = { collection: Collection @@ -25,7 +25,6 @@ export type Arguments = { async function restoreVersion<T extends TypeWithID = any>(args: Arguments): Promise<T> { const { collection: { - Model, config: collectionConfig, }, id, @@ -50,16 +49,20 @@ async function restoreVersion<T extends TypeWithID = any>(args: Arguments): Prom const VersionModel = payload.versions[collectionConfig.slug]; - let rawVersion = await VersionModel.findOne({ - _id: id, + + const { docs: versionDocs } = await req.payload.db.findVersions({ + collection: collectionConfig.slug, + where: { id: { equals: id } }, + locale, + limit: 1, }); + const [rawVersion] = versionDocs; + if (!rawVersion) { throw new NotFound(t); } - rawVersion = rawVersion.toJSON({ virtuals: true }); - const parentDocID = rawVersion.parent; // ///////////////////////////////////// @@ -73,13 +76,16 @@ async function restoreVersion<T extends TypeWithID = any>(args: Arguments): Prom // Retrieve document // ///////////////////////////////////// - const query = await Model.buildQuery({ + const findArgs: FindArgs = { + collection: collectionConfig.slug, where: combineQueries({ id: { equals: parentDocID } }, accessResults), - payload, locale, - }); + limit: 1, + }; + + const { docs } = await req.payload.db.find(findArgs); - const doc = await Model.findOne(query); + const [doc] = docs; if (!doc && !hasWherePolicy) throw new NotFound(t); if (!doc && hasWherePolicy) throw new Forbidden(t); @@ -91,8 +97,7 @@ async function restoreVersion<T extends TypeWithID = any>(args: Arguments): Prom const prevDocWithLocales = await getLatestCollectionVersion({ payload, id: parentDocID, - query, - Model, + query: findArgs, config: collectionConfig, }); @@ -100,18 +105,12 @@ async function restoreVersion<T extends TypeWithID = any>(args: Arguments): Prom // Update // ///////////////////////////////////// - let result = await Model.findByIdAndUpdate( - { _id: parentDocID }, - rawVersion.version, - { new: true }, - ); - - result = result.toJSON({ virtuals: true }); + let result = await req.payload.db.updateOne({ + collection: collectionConfig.slug, + id: parentDocID, + data: rawVersion.version, - // custom id type reset - result.id = result._id; - result = JSON.parse(JSON.stringify(result)); - result = sanitizeInternalFields(result); + }); // ///////////////////////////////////// // Save `previousDoc` as a version after restoring diff --git a/src/collections/operations/update.ts b/src/collections/operations/update.ts index e69dfab5411..d4493a801ad 100644 --- a/src/collections/operations/update.ts +++ b/src/collections/operations/update.ts @@ -5,7 +5,7 @@ import { Where } from '../../types'; import { BulkOperationResult, Collection } from '../config/types'; import sanitizeInternalFields from '../../utilities/sanitizeInternalFields'; import executeAccess from '../../auth/executeAccess'; -import { APIError, ValidationError } from '../../errors'; +import { APIError } from '../../errors'; import { PayloadRequest } from '../../express/types'; import { saveVersion } from '../../versions/saveVersion'; import { uploadFiles } from '../../uploads/uploadFiles'; @@ -56,7 +56,6 @@ async function update<TSlug extends keyof GeneratedTypes['collections']>( depth, collection, collection: { - Model, config: collectionConfig, }, where, @@ -243,27 +242,14 @@ async function update<TSlug extends keyof GeneratedTypes['collections']>( // ///////////////////////////////////// if (!shouldSaveDraft) { - try { - result = await Model.findByIdAndUpdate( - { _id: id }, - result, - { new: true }, - ); - } catch (error) { - // Handle uniqueness error from MongoDB - throw error.code === 11000 && error.keyValue - ? new ValidationError([{ - message: 'Value must be unique', - field: Object.keys(error.keyValue)[0], - }], t) - : error; - } + result = await req.payload.db.updateOne({ + collection: collectionConfig.slug, + locale, + id, + data: result, + }); } - result = JSON.parse(JSON.stringify(result)); - result.id = result._id as string | number; - result = sanitizeInternalFields(result); - // ///////////////////////////////////// // Create version // ///////////////////////////////////// diff --git a/src/collections/operations/updateByID.ts b/src/collections/operations/updateByID.ts index 3232d26685b..e4227772786 100644 --- a/src/collections/operations/updateByID.ts +++ b/src/collections/operations/updateByID.ts @@ -1,11 +1,9 @@ import httpStatus from 'http-status'; import { Config as GeneratedTypes } from 'payload/generated-types'; import { DeepPartial } from 'ts-essentials'; -import { Document } from '../../types'; import { Collection } from '../config/types'; -import sanitizeInternalFields from '../../utilities/sanitizeInternalFields'; import executeAccess from '../../auth/executeAccess'; -import { APIError, Forbidden, NotFound, ValidationError } from '../../errors'; +import { APIError, Forbidden, NotFound } from '../../errors'; import { PayloadRequest } from '../../express/types'; import { hasWhereAccessResult } from '../../auth/types'; import { saveVersion } from '../../versions/saveVersion'; @@ -20,6 +18,7 @@ import { deleteAssociatedFiles } from '../../uploads/deleteAssociatedFiles'; import { unlinkTempFiles } from '../../uploads/unlinkTempFiles'; import { generatePasswordSaltHash } from '../../auth/strategies/local/generatePasswordSaltHash'; import { combineQueries } from '../../database/combineQueries'; +import { FindArgs } from '../../database/types'; export type Arguments<T extends { [field: string | number | symbol]: unknown }> = { collection: Collection @@ -57,7 +56,6 @@ async function updateByID<TSlug extends keyof GeneratedTypes['collections']>( depth, collection, collection: { - Model, config: collectionConfig, }, id, @@ -85,7 +83,6 @@ async function updateByID<TSlug extends keyof GeneratedTypes['collections']>( const { password } = data; const shouldSaveDraft = Boolean(draftArg && collectionConfig.versions.drafts); const shouldSavePassword = Boolean(password && collectionConfig.auth && !shouldSaveDraft); - const lean = !shouldSavePassword; // ///////////////////////////////////// // Access @@ -98,26 +95,24 @@ async function updateByID<TSlug extends keyof GeneratedTypes['collections']>( // Retrieve document // ///////////////////////////////////// - const query = await Model.buildQuery({ + + const findArgs: FindArgs = { + collection: collectionConfig.slug, where: combineQueries({ id: { equals: id } }, accessResults), - payload, locale, - }); + limit: 1, + }; - const doc = await getLatestCollectionVersion({ + const docWithLocales = await getLatestCollectionVersion({ payload, - Model, config: collectionConfig, id, - query, - lean, + query: findArgs, }); - if (!doc && !hasWherePolicy) throw new NotFound(t); - if (!doc && hasWherePolicy) throw new Forbidden(t); + if (!docWithLocales && !hasWherePolicy) throw new NotFound(t); + if (!docWithLocales && hasWherePolicy) throw new Forbidden(t); - let docWithLocales: Document = JSON.stringify(lean ? doc : doc.toJSON({ virtuals: true })); - docWithLocales = JSON.parse(docWithLocales); const originalDoc = await afterRead({ depth: 0, @@ -147,7 +142,7 @@ async function updateByID<TSlug extends keyof GeneratedTypes['collections']>( // Delete any associated files // ///////////////////////////////////// - await deleteAssociatedFiles({ config, collectionConfig, files: filesToUpload, doc, t, overrideDelete: false }); + await deleteAssociatedFiles({ config, collectionConfig, files: filesToUpload, doc: docWithLocales, t, overrideDelete: false }); // ///////////////////////////////////// // beforeValidate - Fields @@ -235,24 +230,14 @@ async function updateByID<TSlug extends keyof GeneratedTypes['collections']>( // ///////////////////////////////////// if (!shouldSaveDraft) { - try { - result = await Model.findByIdAndUpdate( - { _id: id }, - dataToUpdate, - { new: true }, - ); - } catch (error) { - // Handle uniqueness error from MongoDB - throw error.code === 11000 && error.keyValue - ? new ValidationError([{ message: 'Value must be unique', field: Object.keys(error.keyValue)[0] }], t) - : error; - } + result = await req.payload.db.updateOne({ + collection: collectionConfig.slug, + locale, + id, + data: dataToUpdate, + }); } - result = JSON.parse(JSON.stringify(result)); - result.id = result._id as string | number; - result = sanitizeInternalFields(result); - // ///////////////////////////////////// // Create version // ///////////////////////////////////// diff --git a/src/database/types.ts b/src/database/types.ts index 66bcb9a337e..e46a2b91bc8 100644 --- a/src/database/types.ts +++ b/src/database/types.ts @@ -25,8 +25,10 @@ import type { UploadField, } from '../fields/config/types'; import type { TypeWithID } from '../collections/config/types'; +import type { TypeWithID as GlobalsTypeWithID } from '../globals/config/types'; import type { Payload } from '../payload'; import type { Document, Where } from '../types'; +import type { TypeWithVersion } from '../versions/types'; export interface DatabaseAdapter { /** @@ -116,12 +118,12 @@ export interface DatabaseAdapter { // operations find: <T = TypeWithID>(args: FindArgs) => Promise<PaginatedDocs<T>>; - // TODO: ADD findGlobal method - findVersions: <T = TypeWithID>(args: FindVersionArgs) => Promise<PaginatedDocs<T>>; - findGlobalVersions: <T = TypeWithID>(args: FindGlobalVersionArgs) => Promise<PaginatedDocs<T>>; + findGlobal: FindGlobal; + + findVersions: <T = TypeWithID>(args: FindVersionArgs) => Promise<PaginatedDocs<TypeWithVersion<T>>>; + findGlobalVersions: <T = TypeWithID>(args: FindGlobalVersionArgs) => Promise<PaginatedDocs<TypeWithVersion<T>>>; findOne: FindOne; create: Create; - update: Update; updateOne: UpdateOne; deleteOne: DeleteOne; deleteMany: DeleteMany; @@ -134,7 +136,7 @@ export type QueryDraftsArgs = { limit?: number pagination?: boolean sortProperty?: string - sortOrder?: string + sortOrder?: SortArgs locale?: string } @@ -144,10 +146,11 @@ export type FindArgs = { page?: number skip?: number versions?: boolean + /** Setting limit to 1 is equal to the previous Model.findOne(). Setting limit to 0 disables the limit */ limit?: number pagination?: boolean sortProperty?: string - sortOrder?: string + sortOrder?: SortArgs locale?: string } @@ -160,7 +163,7 @@ export type FindVersionArgs = { limit?: number pagination?: boolean sortProperty?: string - sortOrder?: string + sortOrder?: SortArgs locale?: string } @@ -173,10 +176,19 @@ export type FindGlobalVersionArgs = { limit?: number pagination?: boolean sortProperty?: string - sortOrder?: string + sortOrder?: SortArgs locale?: string } +export type FindGlobalArgs = { + slug: string + locale?: string + where: Where +} + +type FindGlobal = <T extends GlobalsTypeWithID = any>(args: FindGlobalArgs) => Promise<T> + + export type FindOneArgs = { collection: string where: Where @@ -186,6 +198,7 @@ export type FindOneArgs = { } } + type FindOne = (args: FindOneArgs) => Promise<PaginatedDocs> export type CreateArgs = { @@ -195,30 +208,18 @@ export type CreateArgs = { type Create = (args: CreateArgs) => Promise<Document> -type UpdateArgs = { - collection: string - data: Record<string, unknown> - where: Where - draft?: boolean - locale?: string -} - -type Update = (args: UpdateArgs) => Promise<Document> - -type UpdateOneArgs = { +export type UpdateOneArgs = { collection: string, data: Record<string, unknown>, - where: Where, - draft?: boolean + id: string | number, locale?: string } type UpdateOne = (args: UpdateOneArgs) => Promise<Document> -type DeleteOneArgs = { +export type DeleteOneArgs = { collection: string, - data: Record<string, unknown>, - where: Where, + id: string | number, } type DeleteOne = (args: DeleteOneArgs) => Promise<Document> @@ -252,7 +253,7 @@ export type BuildSortParam = (args: { locale: string }) => { sortProperty: string - sortOrder: string + sortOrder: SortArgs } export type PaginatedDocs<T = any> = { @@ -326,3 +327,5 @@ export type FieldGenerator<TSchema, TField> = { config: SanitizedConfig, options: BuildSchemaOptions, } + +export type SortArgs = 'asc' | 'desc'; diff --git a/src/express/types.ts b/src/express/types.ts index 41f15177b56..fce4c8e952b 100644 --- a/src/express/types.ts +++ b/src/express/types.ts @@ -5,7 +5,7 @@ import { UploadedFile } from 'express-fileupload'; import { Payload } from '../payload'; import { Collection, TypeWithID } from '../collections/config/types'; import { User } from '../auth/types'; -import { Document } from '../types'; +import { FindArgs } from '../database/types'; /** Express request with some Payload related context added */ export declare type PayloadRequest<U = any> = Request & { @@ -46,6 +46,6 @@ export declare type PayloadRequest<U = any> = Request & { payloadUploadSizes?: Record<string, Buffer>; /** Cache of documents related to the current request */ findByID?: { - [slug: string]: (q: unknown) => Document; + [slug: string]: (q: FindArgs) => Promise<TypeWithID>; }; }; diff --git a/src/globals/operations/findOne.ts b/src/globals/operations/findOne.ts index 7a21fce67e6..af7708b5f08 100644 --- a/src/globals/operations/findOne.ts +++ b/src/globals/operations/findOne.ts @@ -1,6 +1,5 @@ import executeAccess from '../../auth/executeAccess'; import { AccessResult } from '../../config/types'; -import sanitizeInternalFields from '../../utilities/sanitizeInternalFields'; import replaceWithDraftIfAvailable from '../../versions/drafts/replaceWithDraftIfAvailable'; import { afterRead } from '../../fields/hooks/afterRead'; import { SanitizedGlobalConfig } from '../config/types'; @@ -23,7 +22,6 @@ async function findOne<T extends Record<string, unknown>>(args: Args): Promise<T globalConfig, req, req: { - payload, locale, }, slug, @@ -33,8 +31,6 @@ async function findOne<T extends Record<string, unknown>>(args: Args): Promise<T overrideAccess = false, } = args; - const { globals: { Model } } = payload; - // ///////////////////////////////////// // Retrieve and execute access // ///////////////////////////////////// @@ -45,30 +41,15 @@ async function findOne<T extends Record<string, unknown>>(args: Args): Promise<T accessResult = await executeAccess({ req }, globalConfig.access.read); } - const query = await Model.buildQuery({ - where: combineQueries({ globalType: { equals: slug } }, accessResult), - payload, - locale, - overrideAccess, - globalSlug: slug, - }); - // ///////////////////////////////////// // Perform database operation // ///////////////////////////////////// - let doc = await Model.findOne(query).lean() as any; - - if (!doc) { - doc = {}; - } else if (doc._id) { - doc.id = doc._id; - delete doc._id; - } - - doc = JSON.stringify(doc); - doc = JSON.parse(doc); - doc = sanitizeInternalFields(doc); + let doc = await req.payload.db.findGlobal({ + slug, + locale, + where: overrideAccess ? { globalType: { equals: slug } } : combineQueries({ globalType: { equals: slug } }, accessResult), + }); // ///////////////////////////////////// // Replace document with draft if available @@ -76,7 +57,6 @@ async function findOne<T extends Record<string, unknown>>(args: Args): Promise<T if (globalConfig.versions?.drafts && draftEnabled) { doc = await replaceWithDraftIfAvailable({ - payload, entity: globalConfig, entityType: 'global', doc, diff --git a/src/mongoose/create.ts b/src/mongoose/create.ts index 42575e3b646..094e2b76e79 100644 --- a/src/mongoose/create.ts +++ b/src/mongoose/create.ts @@ -1,6 +1,6 @@ import type { MongooseAdapter } from '.'; import { CreateArgs } from '../database/types'; -import { Document } from '../../types'; +import { Document } from '../types'; export async function create<T = unknown>( this: MongooseAdapter, @@ -16,6 +16,8 @@ export async function create<T = unknown>( // custom id type reset result.id = result._id; result = JSON.parse(JSON.stringify(result)); - result._verificationToken = verificationToken; + if (verificationToken) { + result._verificationToken = verificationToken; + } return result; } diff --git a/src/mongoose/deleteOne.ts b/src/mongoose/deleteOne.ts new file mode 100644 index 00000000000..1b6cf1c13fe --- /dev/null +++ b/src/mongoose/deleteOne.ts @@ -0,0 +1,24 @@ +import type { MongooseAdapter } from '.'; +import type { DeleteOneArgs } from '../database/types'; +import sanitizeInternalFields from '../utilities/sanitizeInternalFields'; +import { Document } from '../types'; + +export async function deleteOne<T = unknown>( + this: MongooseAdapter, + { collection, id }: DeleteOneArgs, +): Promise<T> { + const Model = this.collections[collection]; + + const doc = await Model.findOneAndDelete({ _id: id }); + + let result: Document = doc.toJSON({ virtuals: true }); + + // custom id type reset + result.id = result._id; + result = JSON.stringify(result); + result = JSON.parse(result); + result = sanitizeInternalFields(result); + + + return result; +} diff --git a/src/mongoose/findGlobal.ts b/src/mongoose/findGlobal.ts new file mode 100644 index 00000000000..c924530abcd --- /dev/null +++ b/src/mongoose/findGlobal.ts @@ -0,0 +1,33 @@ +import type { MongooseAdapter } from '.'; +import { FindGlobalArgs } from '../database/types'; +import sanitizeInternalFields from '../utilities/sanitizeInternalFields'; +import { TypeWithID } from '../globals/config/types'; + +export async function findGlobal<T extends TypeWithID = any>( + this: MongooseAdapter, + { slug, locale, where }: FindGlobalArgs, +): Promise<T> { + const Model = this.globals; + + const query = await Model.buildQuery({ + where, + payload: this.payload, + locale, + globalSlug: slug, + }); + + let doc = await Model.findOne(query).lean() as any; + + if (!doc) { + doc = {}; + } else if (doc._id) { + doc.id = doc._id; + delete doc._id; + } + + doc = JSON.parse(JSON.stringify(doc)); + doc = sanitizeInternalFields(doc); + + + return doc; +} diff --git a/src/mongoose/findGlobalVersions.ts b/src/mongoose/findGlobalVersions.ts index da8300f7964..812044bec8c 100644 --- a/src/mongoose/findGlobalVersions.ts +++ b/src/mongoose/findGlobalVersions.ts @@ -3,11 +3,12 @@ import { PaginatedDocs } from './types'; import { FindGlobalVersionArgs } from '../database/types'; import sanitizeInternalFields from '../utilities/sanitizeInternalFields'; import flattenWhereToOperators from '../database/flattenWhereToOperators'; +import type { TypeWithVersion } from '../versions/types'; export async function findGlobalVersions<T = unknown>( this: MongooseAdapter, { global, where, page, limit, sortProperty, sortOrder, locale, pagination, skip }: FindGlobalVersionArgs, -): Promise<PaginatedDocs<T>> { +): Promise<PaginatedDocs<TypeWithVersion<T>>> { const Model = this.versions[global]; let useEstimatedCount = false; diff --git a/src/mongoose/findVersions.ts b/src/mongoose/findVersions.ts index d04d629d1f1..71da9057f64 100644 --- a/src/mongoose/findVersions.ts +++ b/src/mongoose/findVersions.ts @@ -3,11 +3,12 @@ import { PaginatedDocs } from './types'; import { FindVersionArgs } from '../database/types'; import sanitizeInternalFields from '../utilities/sanitizeInternalFields'; import flattenWhereToOperators from '../database/flattenWhereToOperators'; +import type { TypeWithVersion } from '../versions/types'; export async function findVersions<T = unknown>( this: MongooseAdapter, { collection, where, page, limit, sortProperty, sortOrder, locale, pagination, skip }: FindVersionArgs, -): Promise<PaginatedDocs<T>> { +): Promise<PaginatedDocs<TypeWithVersion<T>>> { const Model = this.versions[collection]; let useEstimatedCount = false; diff --git a/src/mongoose/index.ts b/src/mongoose/index.ts index 6320d2c034c..01be4089e6e 100644 --- a/src/mongoose/index.ts +++ b/src/mongoose/index.ts @@ -8,9 +8,12 @@ import { queryDrafts } from './queryDrafts'; import { GlobalModel } from '../globals/config/types'; import { find } from './find'; import { create } from './create'; +import { updateOne } from './updateOne'; +import { deleteOne } from './deleteOne'; import { findVersions } from './findVersions'; import { findGlobalVersions } from './findGlobalVersions'; import type { Payload } from '../index'; +import { findGlobal } from './findGlobal'; export interface Args { payload: Payload, @@ -59,7 +62,10 @@ export function mongooseAdapter({ payload, url, connectOptions }: Args): Mongoos queryDrafts, find, findVersions, + findGlobal, findGlobalVersions, create, + updateOne, + deleteOne, }; } diff --git a/src/mongoose/init.ts b/src/mongoose/init.ts index 20b57505b48..90954298e0f 100644 --- a/src/mongoose/init.ts +++ b/src/mongoose/init.ts @@ -2,7 +2,6 @@ import mongoose from 'mongoose'; import paginate from 'mongoose-paginate-v2'; import mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2'; -import { SanitizedConfig } from 'payload/config'; import { buildVersionCollectionFields } from '../versions/buildCollectionFields'; import getBuildQueryPlugin from './queries/buildQuery'; import buildCollectionSchema from './models/buildCollectionSchema'; @@ -12,6 +11,8 @@ import { getVersionsModelName } from '../versions/getVersionsModelName'; import type { MongooseAdapter } from '.'; import { buildGlobalModel } from './models/buildGlobalModel'; import { buildVersionGlobalFields } from '../versions/buildGlobalFields'; +import type { SanitizedConfig } from '../config/types'; + export async function init( this: MongooseAdapter, diff --git a/src/mongoose/queries/buildSortParam.ts b/src/mongoose/queries/buildSortParam.ts index b2026e15ce7..4b1c9c96f5a 100644 --- a/src/mongoose/queries/buildSortParam.ts +++ b/src/mongoose/queries/buildSortParam.ts @@ -1,6 +1,7 @@ import { Config } from '../../config/types'; import { getLocalizedSortProperty } from './getLocalizedSortProperty'; import { Field } from '../../fields/config/types'; +import type { SortArgs } from '../../database/types'; type Args = { sort: string @@ -10,9 +11,9 @@ type Args = { locale: string } -export const buildSortParam = ({ sort, config, fields, timestamps, locale }: Args): [string, string] => { +export const buildSortParam = ({ sort, config, fields, timestamps, locale }: Args): [string, SortArgs] => { let sortProperty: string; - let sortOrder = 'desc'; + let sortOrder: SortArgs = 'desc'; if (!sort) { if (timestamps) { diff --git a/src/mongoose/updateOne.ts b/src/mongoose/updateOne.ts new file mode 100644 index 00000000000..774740e5ce2 --- /dev/null +++ b/src/mongoose/updateOne.ts @@ -0,0 +1,36 @@ +import { t } from 'i18next'; +import type { MongooseAdapter } from '.'; +import type { UpdateOneArgs } from '../database/types'; +import { ValidationError } from '../errors'; +import sanitizeInternalFields from '../utilities/sanitizeInternalFields'; + +export async function updateOne<T = unknown>( + this: MongooseAdapter, + { collection, data, id, locale }: UpdateOneArgs, +): Promise<T> { + const Model = this.collections[collection]; + + let result; + try { + result = await Model.findByIdAndUpdate( + { _id: id, locale }, + data, + { new: true }, + ); + } catch (error) { + // Handle uniqueness error from MongoDB + throw error.code === 11000 && error.keyValue + ? new ValidationError([{ + message: 'Value must be unique', + field: Object.keys(error.keyValue)[0], + }], t) + : error; + } + + result = JSON.parse(JSON.stringify(result)); + result.id = result._id as string | number; + result = sanitizeInternalFields(result); + + + return result; +} diff --git a/src/payload.ts b/src/payload.ts index 7a0cb3cdc8f..7d412c5a7f0 100644 --- a/src/payload.ts +++ b/src/payload.ts @@ -233,7 +233,7 @@ export class BasePayload<TGeneratedTypes extends GeneratedTypes> { registerGraphQLSchema(this); } - if (this.db.init) { + if (this.db?.init) { await this.db?.init({ config: this.config }); } diff --git a/src/versions/drafts/replaceWithDraftIfAvailable.ts b/src/versions/drafts/replaceWithDraftIfAvailable.ts index fffb6675093..b35f3416f35 100644 --- a/src/versions/drafts/replaceWithDraftIfAvailable.ts +++ b/src/versions/drafts/replaceWithDraftIfAvailable.ts @@ -2,14 +2,14 @@ import { Payload } from '../../payload'; import { docHasTimestamps, PayloadRequest, Where } from '../../types'; import { hasWhereAccessResult } from '../../auth'; import { AccessResult } from '../../config/types'; -import { CollectionModel, SanitizedCollectionConfig, TypeWithID } from '../../collections/config/types'; +import { SanitizedCollectionConfig, TypeWithID } from '../../collections/config/types'; import sanitizeInternalFields from '../../utilities/sanitizeInternalFields'; import { appendVersionToQueryKey } from './appendVersionToQueryKey'; import { SanitizedGlobalConfig } from '../../globals/config/types'; import { combineQueries } from '../../database/combineQueries'; +import { FindVersionArgs } from '../../database/types'; type Arguments<T> = { - payload: Payload entity: SanitizedCollectionConfig | SanitizedGlobalConfig entityType: 'collection' | 'global' doc: T @@ -19,15 +19,12 @@ type Arguments<T> = { } const replaceWithDraftIfAvailable = async <T extends TypeWithID>({ - payload, entity, entityType, doc, req, accessResult, }: Arguments<T>): Promise<T> => { - const VersionModel = payload.versions[entity.slug] as CollectionModel; - const queryToBuild: Where = { and: [ { @@ -60,17 +57,21 @@ const replaceWithDraftIfAvailable = async <T extends TypeWithID>({ versionAccessResult = appendVersionToQueryKey(accessResult); } - const query = await VersionModel.buildQuery({ - where: combineQueries(queryToBuild, versionAccessResult), - payload, + + const findVersionArgs: FindVersionArgs = { locale: req.locale, - globalSlug: entityType === 'global' ? entity.slug : undefined, - }); + where: combineQueries(queryToBuild, versionAccessResult), + collection: entity.slug, + limit: 1, + sortProperty: 'updatedAt', + sortOrder: 'desc', + + }; + + const { docs: versionDocs } = await req.payload.db.findVersions<T>(findVersionArgs); + + let draft = versionDocs[0]; - let draft = await VersionModel.findOne(query, {}, { - lean: true, - sort: { updatedAt: 'desc' }, - }); if (!draft) { return doc; diff --git a/src/versions/getLatestCollectionVersion.ts b/src/versions/getLatestCollectionVersion.ts index e636b39947f..189131446c8 100644 --- a/src/versions/getLatestCollectionVersion.ts +++ b/src/versions/getLatestCollectionVersion.ts @@ -1,39 +1,39 @@ import { docHasTimestamps } from '../types'; import { Payload } from '../payload'; -import { CollectionModel, SanitizedCollectionConfig, TypeWithID } from '../collections/config/types'; +import { SanitizedCollectionConfig, TypeWithID } from '../collections/config/types'; +import { TypeWithVersion } from './types'; +import { FindArgs } from '../database/types'; type Args = { payload: Payload - query: Record<string, unknown> - lean?: boolean + query: FindArgs id: string | number - Model: CollectionModel config: SanitizedCollectionConfig } export const getLatestCollectionVersion = async <T extends TypeWithID = any>({ payload, config, - Model, query, id, - lean = true, }: Args): Promise<T> => { - let latestVersion; + let latestVersion: TypeWithVersion<T>; if (config.versions?.drafts) { - latestVersion = await payload.versions[config.slug].findOne({ - parent: id, - }, {}, { - sort: { updatedAt: 'desc' }, - lean, + const { docs } = await payload.db.findVersions<T>({ + collection: config.slug, + where: { parent: { equals: id } }, + sortProperty: 'updatedAt', + sortOrder: 'desc', }); + [latestVersion] = docs; } - const doc = await Model.findOne(query, {}, { lean }); + const { docs } = await payload.db.find<T>(query); + const [doc] = docs; + if (!latestVersion || (docHasTimestamps(doc) && latestVersion.updatedAt < doc.updatedAt)) { - doc.id = doc._id; return doc; } diff --git a/src/versions/saveVersion.ts b/src/versions/saveVersion.ts index 8ed0a451e24..13b9df0d1d4 100644 --- a/src/versions/saveVersion.ts +++ b/src/versions/saveVersion.ts @@ -50,10 +50,22 @@ export const saveVersion = async ({ if (autosave) { const query: FilterQuery<unknown> = {}; if (collection) query.parent = id; - const latestVersion = await VersionModel.findOne(query, {}, { sort: { updatedAt: 'desc' } }); + const { docs } = await payload.db.findVersions({ + collection: entityConfig.slug, + limit: 1, + where: { + parent: { + equals: id, + }, + }, + sortOrder: 'desc', + sortProperty: 'updatedAt', + }); + const [latestVersion] = docs; + // overwrite the latest version if it's set to autosave - if (latestVersion?.autosave === true) { + if ((latestVersion as any)?.autosave === true) { createNewVersion = false; const data: Record<string, unknown> = { @@ -64,7 +76,7 @@ export const saveVersion = async ({ result = await VersionModel.findByIdAndUpdate( { - _id: latestVersion._id, + _id: latestVersion.id, }, data, { new: true, lean: true }, diff --git a/test/admin/e2e.spec.ts b/test/admin/e2e.spec.ts index 46eebd74671..031f446712a 100644 --- a/test/admin/e2e.spec.ts +++ b/test/admin/e2e.spec.ts @@ -297,7 +297,7 @@ describe('admin', () => { await createPost(); await page.locator('.list-controls__toggle-columns').click(); - await wait(500); // Wait for column toggle UI, should probably use waitForSelector + await page.waitForSelector('.column-selector'); // Waiting for column toggle UI const numberOfColumns = await page.locator(columnCountLocator).count(); await expect(await page.locator('table >> thead >> tr >> th:nth-child(2)')).toHaveText('ID'); @@ -306,13 +306,13 @@ describe('admin', () => { // Remove ID column await idButton.click(); - await wait(100); + await wait(200); await expect(await page.locator(columnCountLocator)).toHaveCount(numberOfColumns - 1); await expect(await page.locator('table >> thead >> tr >> th:nth-child(2)')).toHaveText('Number'); // Add back ID column await idButton.click(); - await wait(100); + await wait(200); await expect(await page.locator(columnCountLocator)).toHaveCount(numberOfColumns); await expect(await page.locator('table >> thead >> tr >> th:nth-child(2)')).toHaveText('ID'); }); diff --git a/test/generateGraphQLSchema.ts b/test/generateGraphQLSchema.ts index 4ede12af24a..c1d2dbe3cd8 100644 --- a/test/generateGraphQLSchema.ts +++ b/test/generateGraphQLSchema.ts @@ -4,9 +4,24 @@ import { generateGraphQLSchema } from '../src/bin/generateGraphQLSchema'; const [testConfigDir] = process.argv.slice(2); -const testDir = path.resolve(__dirname, testConfigDir); -setPaths(testDir); -generateGraphQLSchema(); +let testDir; +if (testConfigDir) { + testDir = path.resolve(__dirname, testConfigDir); + setPaths(testDir); + generateGraphQLSchema(); +} else { + // Generate graphql schema for entire directory + testDir = __dirname; + + fs.readdirSync(__dirname, { withFileTypes: true }) + .filter((f) => f.isDirectory()) + .forEach((dir) => { + const suiteDir = path.resolve(testDir, dir.name); + const configFound = setPaths(suiteDir); + if (configFound) generateGraphQLSchema(); + }); +} + // Set config path and TS output path using test dir function setPaths(dir) {
6217c70fb57950c1e178e595e78751b114cec0f3
2024-04-05 23:43:14
James
chore: prebuilds fields and admin in ci
false
prebuilds fields and admin in ci
chore
diff --git a/app/live-preview/_api/fetchDoc.ts b/app/live-preview/_api/fetchDoc.ts deleted file mode 100644 index d1dc1c2a3a9..00000000000 --- a/app/live-preview/_api/fetchDoc.ts +++ /dev/null @@ -1,35 +0,0 @@ -import QueryString from 'qs' - -import { PAYLOAD_SERVER_URL } from './serverURL.js' - -export const fetchDoc = async <T>(args: { - collection: string - depth?: number - id?: string - slug?: string -}): Promise<T> => { - const { id, slug, collection, depth = 2 } = args || {} - - const queryString = QueryString.stringify( - { - ...(slug ? { 'where[slug][equals]': slug } : {}), - ...(depth ? { depth } : {}), - }, - { addQueryPrefix: true }, - ) - - const doc: T = await fetch(`${PAYLOAD_SERVER_URL}/api/${collection}${queryString}`, { - cache: 'no-store', - headers: { - 'Content-Type': 'application/json', - }, - method: 'GET', - }) - ?.then((res) => res.json()) - ?.then((res) => { - if (res.errors) throw new Error(res?.errors?.[0]?.message ?? 'Error fetching doc') - return res?.docs?.[0] - }) - - return doc -} diff --git a/app/live-preview/_api/fetchDocs.ts b/app/live-preview/_api/fetchDocs.ts deleted file mode 100644 index 104f5e2586e..00000000000 --- a/app/live-preview/_api/fetchDocs.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { PAYLOAD_SERVER_URL } from './serverURL.js' - -export const fetchDocs = async <T>(collection: string): Promise<T[]> => { - const docs: T[] = await fetch(`${PAYLOAD_SERVER_URL}/api/${collection}?depth=0&limit=100`, { - cache: 'no-store', - headers: { - 'Content-Type': 'application/json', - }, - method: 'GET', - }) - ?.then((res) => res.json()) - ?.then((res) => { - if (res.errors) throw new Error(res?.errors?.[0]?.message ?? 'Error fetching docs') - - return res?.docs - }) - - return docs -} diff --git a/app/live-preview/_api/fetchFooter.ts b/app/live-preview/_api/fetchFooter.ts deleted file mode 100644 index 26b531b6204..00000000000 --- a/app/live-preview/_api/fetchFooter.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { Footer } from '../../../test/live-preview/payload-types.js' - -import { PAYLOAD_SERVER_URL } from './serverURL.js' - -export async function fetchFooter(): Promise<Footer> { - if (!PAYLOAD_SERVER_URL) throw new Error('PAYLOAD_SERVER_URL not found') - - const footer = await fetch(`${PAYLOAD_SERVER_URL}/api/globals/footer`, { - cache: 'no-store', - headers: { - 'Content-Type': 'application/json', - }, - method: 'GET', - }) - .then((res) => { - if (!res.ok) throw new Error('Error fetching doc') - return res.json() - }) - ?.then((res) => { - if (res?.errors) throw new Error(res?.errors[0]?.message || 'Error fetching footer') - return res - }) - - return footer -} diff --git a/app/live-preview/_api/fetchHeader.ts b/app/live-preview/_api/fetchHeader.ts deleted file mode 100644 index 79a35adb5df..00000000000 --- a/app/live-preview/_api/fetchHeader.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { Header } from '../../../test/live-preview/payload-types.js' - -import { PAYLOAD_SERVER_URL } from './serverURL.js' - -export async function fetchHeader(): Promise<Header> { - if (!PAYLOAD_SERVER_URL) throw new Error('PAYLOAD_SERVER_URL not found') - - const header = await fetch(`${PAYLOAD_SERVER_URL}/api/globals/header`, { - cache: 'no-store', - headers: { - 'Content-Type': 'application/json', - }, - method: 'GET', - }) - ?.then((res) => { - if (!res.ok) throw new Error('Error fetching doc') - return res.json() - }) - ?.then((res) => { - if (res?.errors) throw new Error(res?.errors[0]?.message || 'Error fetching header') - return res - }) - - return header -} diff --git a/test/admin/e2e.spec.ts b/test/admin/e2e.spec.ts index fad521a7712..3f8d8e6217b 100644 --- a/test/admin/e2e.spec.ts +++ b/test/admin/e2e.spec.ts @@ -72,7 +72,10 @@ describe('admin', () => { beforeAll(async ({ browser }) => { process.env.SEED_IN_CONFIG_ONINIT = 'false' // Makes it so the payload config onInit seed is not run. Otherwise, the seed would be run unnecessarily twice for the initial test run - once for beforeEach and once for onInit - ;({ payload, serverURL } = await initPayloadE2ENoConfig<Config>({ dirname })) + ;({ payload, serverURL } = await initPayloadE2ENoConfig<Config>({ + dirname, + prebuild: Boolean(process.env.CI), + })) geoUrl = new AdminUrlUtil(serverURL, geoCollectionSlug) postsUrl = new AdminUrlUtil(serverURL, postsCollectionSlug) customViewsURL = new AdminUrlUtil(serverURL, customViews2CollectionSlug) diff --git a/test/dev.js b/test/dev.js index 124bedb1d8a..ca40005042e 100644 --- a/test/dev.js +++ b/test/dev.js @@ -1,15 +1,11 @@ import minimist from 'minimist' import { MongoMemoryReplSet } from 'mongodb-memory-server' import { nextDev } from 'next/dist/cli/next-dev.js' -import { dirname, resolve } from 'path' -import { fileURLToPath } from 'url' -import open, { openApp, apps } from 'open' +import open from 'open' +import { getNextJSRootDir } from './helpers/getNextJSRootDir.js' import { createTestHooks } from './testHooks.js' -const _filename = fileURLToPath(import.meta.url) -const _dirname = dirname(_filename) - process.env.PAYLOAD_DROP_DATABASE = 'true' const { @@ -26,7 +22,7 @@ process.env.PAYLOAD_DROP_DATABASE = 'true' const { afterTest, beforeTest } = await createTestHooks(testSuiteArg) await beforeTest() -const rootDir = resolve(_dirname, '../') +const rootDir = getNextJSRootDir(testSuiteArg) // Open the admin if the -o flag is passed if (args.o) { diff --git a/test/fields/e2e.spec.ts b/test/fields/e2e.spec.ts index 8f22ec34a07..3ea9cd1d823 100644 --- a/test/fields/e2e.spec.ts +++ b/test/fields/e2e.spec.ts @@ -44,7 +44,10 @@ let serverURL: string describe('fields', () => { beforeAll(async ({ browser }) => { process.env.SEED_IN_CONFIG_ONINIT = 'false' // Makes it so the payload config onInit seed is not run. Otherwise, the seed would be run unnecessarily twice for the initial test run - once for beforeEach and once for onInit - ;({ payload, serverURL } = await initPayloadE2ENoConfig({ dirname })) + ;({ payload, serverURL } = await initPayloadE2ENoConfig({ + dirname, + prebuild: Boolean(process.env.CI), + })) const context = await browser.newContext() page = await context.newPage() diff --git a/test/helpers/getNextJSRootDir.js b/test/helpers/getNextJSRootDir.js new file mode 100644 index 00000000000..996e80fc154 --- /dev/null +++ b/test/helpers/getNextJSRootDir.js @@ -0,0 +1,25 @@ +import fs from 'fs' +import { dirname, resolve } from 'path' +import { fileURLToPath } from 'url' + +const _filename = fileURLToPath(import.meta.url) +const _dirname = dirname(_filename) + +export const getNextJSRootDir = (testSuite) => { + const testSuiteDir = resolve(_dirname, `../${testSuite}`) + + let hasNextConfig = false + + try { + fs.accessSync(`${testSuiteDir}/next.config.mjs`, fs.constants.F_OK) + hasNextConfig = true + } catch (err) { + // Swallow err - no config found + } + + if (hasNextConfig) return testSuiteDir + + // If no next config found in test suite, + // return monorepo root dir + return resolve(_dirname, '../../') +} diff --git a/test/helpers/initPayloadE2ENoConfig.ts b/test/helpers/initPayloadE2ENoConfig.ts index c3c1643cc9a..b381a074669 100644 --- a/test/helpers/initPayloadE2ENoConfig.ts +++ b/test/helpers/initPayloadE2ENoConfig.ts @@ -1,18 +1,19 @@ import { createServer } from 'http' import nextImport from 'next' import nextBuild from 'next/dist/build/index.js' -import path from 'path' import { wait } from 'payload/utilities' import { parse } from 'url' import type { GeneratedTypes } from './sdk/types.js' import { createTestHooks } from '../testHooks.js' +import { getNextJSRootDir } from './getNextJSRootDir.js' import { PayloadTestSDK } from './sdk/index.js' import startMemoryDB from './startMemoryDB.js' type Args = { dirname: string + prebuild?: boolean } type Result<T extends GeneratedTypes<T>> = { @@ -22,6 +23,7 @@ type Result<T extends GeneratedTypes<T>> = { export async function initPayloadE2ENoConfig<T extends GeneratedTypes<T>>({ dirname, + prebuild, }: Args): Promise<Result<T>> { const testSuiteName = dirname.split('/').pop() const { beforeTest } = await createTestHooks(testSuiteName) @@ -33,27 +35,18 @@ export async function initPayloadE2ENoConfig<T extends GeneratedTypes<T>>({ await startMemoryDB() - // process.env.CI = 'true' - - if (process.env.CI) { - await nextBuild.default( - path.resolve(dirname, '../../'), - false, - false, - false, - true, - true, - false, - 'default', - ) + const dir = getNextJSRootDir(testSuiteName) + + if (prebuild) { + await nextBuild.default(dir, false, false, false, true, true, false, 'default') } // @ts-expect-error const app = nextImport({ - dev: !process.env.CI, + dev: !prebuild, hostname: 'localhost', port, - dir: path.resolve(dirname, '../../'), + dir, }) const handle = app.getRequestHandler() diff --git a/test/helpers/startMemoryDB.ts b/test/helpers/startMemoryDB.ts index cc67692aa01..d5f64f70786 100644 --- a/test/helpers/startMemoryDB.ts +++ b/test/helpers/startMemoryDB.ts @@ -22,7 +22,5 @@ export default async () => { global._mongoMemoryServer = db process.env.MONGODB_MEMORY_SERVER_URI = `${global._mongoMemoryServer.getUri()}&retryWrites=true` - - console.log(process.env.MONGODB_MEMORY_SERVER_URI) } } diff --git a/test/live-preview/app/(payload)/admin/[[...segments]]/not-found.tsx b/test/live-preview/app/(payload)/admin/[[...segments]]/not-found.tsx new file mode 100644 index 00000000000..8b7a445fe7b --- /dev/null +++ b/test/live-preview/app/(payload)/admin/[[...segments]]/not-found.tsx @@ -0,0 +1,22 @@ +/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ +import type { Metadata } from 'next' + +import config from '@payload-config' +/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */ +import { NotFoundPage, generatePageMetadata } from '@payloadcms/next/views/NotFound/index.js' + +type Args = { + params: { + segments: string[] + } + searchParams: { + [key: string]: string | string[] + } +} + +export const generateMetadata = ({ params }: Args): Promise<Metadata> => + generatePageMetadata({ config, params }) + +const NotFound = ({ params, searchParams }: Args) => NotFoundPage({ config, params, searchParams }) + +export default NotFound diff --git a/test/live-preview/app/(payload)/admin/[[...segments]]/page.tsx b/test/live-preview/app/(payload)/admin/[[...segments]]/page.tsx new file mode 100644 index 00000000000..ee9bd415c36 --- /dev/null +++ b/test/live-preview/app/(payload)/admin/[[...segments]]/page.tsx @@ -0,0 +1,22 @@ +/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ +import type { Metadata } from 'next' + +import config from '@payload-config' +/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */ +import { RootPage, generatePageMetadata } from '@payloadcms/next/views/Root/index.js' + +type Args = { + params: { + segments: string[] + } + searchParams: { + [key: string]: string | string[] + } +} + +export const generateMetadata = ({ params, searchParams }: Args): Promise<Metadata> => + generatePageMetadata({ config, params, searchParams }) + +const Page = ({ params, searchParams }: Args) => RootPage({ config, params, searchParams }) + +export default Page diff --git a/test/live-preview/app/(payload)/api/[...slug]/route.ts b/test/live-preview/app/(payload)/api/[...slug]/route.ts new file mode 100644 index 00000000000..eacae29614a --- /dev/null +++ b/test/live-preview/app/(payload)/api/[...slug]/route.ts @@ -0,0 +1,9 @@ +/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ +/* DO NOT MODIFY it because it could be re-written at any time. */ +import config from '@payload-config' +import { REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes/index.js' + +export const GET = REST_GET(config) +export const POST = REST_POST(config) +export const DELETE = REST_DELETE(config) +export const PATCH = REST_PATCH(config) diff --git a/test/live-preview/app/(payload)/api/graphql-playground/route.ts b/test/live-preview/app/(payload)/api/graphql-playground/route.ts new file mode 100644 index 00000000000..7832c8ba921 --- /dev/null +++ b/test/live-preview/app/(payload)/api/graphql-playground/route.ts @@ -0,0 +1,6 @@ +/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ +/* DO NOT MODIFY it because it could be re-written at any time. */ +import config from '@payload-config' +import { GRAPHQL_PLAYGROUND_GET } from '@payloadcms/next/routes/index.js' + +export const GET = GRAPHQL_PLAYGROUND_GET(config) diff --git a/test/live-preview/app/(payload)/api/graphql/route.ts b/test/live-preview/app/(payload)/api/graphql/route.ts new file mode 100644 index 00000000000..4caee1b7cb1 --- /dev/null +++ b/test/live-preview/app/(payload)/api/graphql/route.ts @@ -0,0 +1,6 @@ +/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ +/* DO NOT MODIFY it because it could be re-written at any time. */ +import config from '@payload-config' +import { GRAPHQL_POST } from '@payloadcms/next/routes/index.js' + +export const POST = GRAPHQL_POST(config) diff --git a/test/live-preview/app/(payload)/custom.scss b/test/live-preview/app/(payload)/custom.scss new file mode 100644 index 00000000000..ddfc972f495 --- /dev/null +++ b/test/live-preview/app/(payload)/custom.scss @@ -0,0 +1,8 @@ +#custom-css { + font-family: monospace; + background-image: url('/placeholder.png'); +} + +#custom-css::after { + content: 'custom-css'; +} diff --git a/test/live-preview/app/(payload)/layout.tsx b/test/live-preview/app/(payload)/layout.tsx new file mode 100644 index 00000000000..88fedb40424 --- /dev/null +++ b/test/live-preview/app/(payload)/layout.tsx @@ -0,0 +1,15 @@ +/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ +import configPromise from '@payload-config' +import { RootLayout } from '@payloadcms/next/layouts/Root/index.js' +/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */ +import React from 'react' + +import './custom.scss' + +type Args = { + children: React.ReactNode +} + +const Layout = ({ children }: Args) => <RootLayout config={configPromise}>{children}</RootLayout> + +export default Layout diff --git a/app/live-preview/(pages)/[slug]/page.client.tsx b/test/live-preview/app/live-preview/(pages)/[slug]/page.client.tsx similarity index 100% rename from app/live-preview/(pages)/[slug]/page.client.tsx rename to test/live-preview/app/live-preview/(pages)/[slug]/page.client.tsx diff --git a/app/live-preview/(pages)/[slug]/page.tsx b/test/live-preview/app/live-preview/(pages)/[slug]/page.tsx similarity index 100% rename from app/live-preview/(pages)/[slug]/page.tsx rename to test/live-preview/app/live-preview/(pages)/[slug]/page.tsx diff --git a/app/live-preview/(pages)/posts/[slug]/page.client.tsx b/test/live-preview/app/live-preview/(pages)/posts/[slug]/page.client.tsx similarity index 95% rename from app/live-preview/(pages)/posts/[slug]/page.client.tsx rename to test/live-preview/app/live-preview/(pages)/posts/[slug]/page.client.tsx index e5c52f80482..0d8182945bc 100644 --- a/app/live-preview/(pages)/posts/[slug]/page.client.tsx +++ b/test/live-preview/app/live-preview/(pages)/posts/[slug]/page.client.tsx @@ -3,7 +3,7 @@ import { useLivePreview } from '@payloadcms/live-preview-react' import React from 'react' -import type { Post as PostType } from '../../../../../test/live-preview/payload-types.js' +import type { Post as PostType } from '../../../../../payload-types.js' import { PAYLOAD_SERVER_URL } from '../../../_api/serverURL.js' import { Blocks } from '../../../_components/Blocks/index.js' diff --git a/app/live-preview/(pages)/posts/[slug]/page.tsx b/test/live-preview/app/live-preview/(pages)/posts/[slug]/page.tsx similarity index 90% rename from app/live-preview/(pages)/posts/[slug]/page.tsx rename to test/live-preview/app/live-preview/(pages)/posts/[slug]/page.tsx index 91053d29347..c6476a1304a 100644 --- a/app/live-preview/(pages)/posts/[slug]/page.tsx +++ b/test/live-preview/app/live-preview/(pages)/posts/[slug]/page.tsx @@ -1,7 +1,7 @@ import { notFound } from 'next/navigation.js' import React from 'react' -import type { Post } from '../../../../../test/live-preview/payload-types.js' +import type { Post } from '../../../../../payload-types.js' import { fetchDoc } from '../../../_api/fetchDoc.js' import { fetchDocs } from '../../../_api/fetchDocs.js' diff --git a/test/live-preview/app/live-preview/_api/fetchDoc.ts b/test/live-preview/app/live-preview/_api/fetchDoc.ts new file mode 100644 index 00000000000..829b3fca698 --- /dev/null +++ b/test/live-preview/app/live-preview/_api/fetchDoc.ts @@ -0,0 +1,35 @@ +import type { Where } from 'payload/types' + +import config from '@payload-config' +import { getPayloadHMR } from '@payloadcms/next/utilities/getPayloadHMR.js' + +export const fetchDoc = async <T>(args: { + collection: string + depth?: number + slug?: string +}): Promise<T> => { + const payload = await getPayloadHMR({ config }) + const { slug, collection, depth = 2 } = args || {} + + const where: Where = {} + + if (slug) { + where.slug = { + equals: slug, + } + } + + try { + const { docs } = await payload.find({ + collection, + depth, + where, + }) + + if (docs[0]) return docs[0] as T + } catch (err) { + console.log('Error fetching doc', err) + } + + throw new Error('Error fetching doc') +} diff --git a/test/live-preview/app/live-preview/_api/fetchDocs.ts b/test/live-preview/app/live-preview/_api/fetchDocs.ts new file mode 100644 index 00000000000..1fe18db2e69 --- /dev/null +++ b/test/live-preview/app/live-preview/_api/fetchDocs.ts @@ -0,0 +1,20 @@ +import config from '@payload-config' +import { getPayloadHMR } from '@payloadcms/next/utilities/getPayloadHMR.js' + +export const fetchDocs = async <T>(collection: string): Promise<T[]> => { + const payload = await getPayloadHMR({ config }) + + try { + const { docs } = await payload.find({ + collection, + depth: 0, + limit: 100, + }) + + return docs as T[] + } catch (err) { + console.error(err) + } + + throw new Error('Error fetching docs') +} diff --git a/test/live-preview/app/live-preview/_api/fetchFooter.ts b/test/live-preview/app/live-preview/_api/fetchFooter.ts new file mode 100644 index 00000000000..6f295c92592 --- /dev/null +++ b/test/live-preview/app/live-preview/_api/fetchFooter.ts @@ -0,0 +1,20 @@ +import config from '@payload-config' +import { getPayloadHMR } from '@payloadcms/next/utilities/getPayloadHMR.js' + +import type { Footer } from '../../../payload-types.js' + +export async function fetchFooter(): Promise<Footer> { + const payload = await getPayloadHMR({ config }) + + try { + const footer = await payload.findGlobal({ + slug: 'footer', + }) + + return footer as Footer + } catch (err) { + console.error(err) + } + + throw new Error('Error fetching footer.') +} diff --git a/test/live-preview/app/live-preview/_api/fetchHeader.ts b/test/live-preview/app/live-preview/_api/fetchHeader.ts new file mode 100644 index 00000000000..b86c10a605d --- /dev/null +++ b/test/live-preview/app/live-preview/_api/fetchHeader.ts @@ -0,0 +1,20 @@ +import config from '@payload-config' +import { getPayloadHMR } from '@payloadcms/next/utilities/getPayloadHMR.js' + +import type { Header } from '../../../payload-types.js' + +export async function fetchHeader(): Promise<Header> { + const payload = await getPayloadHMR({ config }) + + try { + const header = await payload.findGlobal({ + slug: 'header', + }) + + return header as Header + } catch (err) { + console.error(err) + } + + throw new Error('Error fetching header.') +} diff --git a/app/live-preview/_api/serverURL.ts b/test/live-preview/app/live-preview/_api/serverURL.ts similarity index 100% rename from app/live-preview/_api/serverURL.ts rename to test/live-preview/app/live-preview/_api/serverURL.ts diff --git a/app/live-preview/_blocks/ArchiveBlock/index.module.scss b/test/live-preview/app/live-preview/_blocks/ArchiveBlock/index.module.scss similarity index 100% rename from app/live-preview/_blocks/ArchiveBlock/index.module.scss rename to test/live-preview/app/live-preview/_blocks/ArchiveBlock/index.module.scss diff --git a/app/live-preview/_blocks/ArchiveBlock/index.tsx b/test/live-preview/app/live-preview/_blocks/ArchiveBlock/index.tsx similarity index 100% rename from app/live-preview/_blocks/ArchiveBlock/index.tsx rename to test/live-preview/app/live-preview/_blocks/ArchiveBlock/index.tsx diff --git a/app/live-preview/_blocks/ArchiveBlock/types.ts b/test/live-preview/app/live-preview/_blocks/ArchiveBlock/types.ts similarity index 59% rename from app/live-preview/_blocks/ArchiveBlock/types.ts rename to test/live-preview/app/live-preview/_blocks/ArchiveBlock/types.ts index 9a810028be6..b28c15a1a13 100644 --- a/app/live-preview/_blocks/ArchiveBlock/types.ts +++ b/test/live-preview/app/live-preview/_blocks/ArchiveBlock/types.ts @@ -1,4 +1,4 @@ -import type { Page } from '../../../../test/live-preview/payload-types.js' +import type { Page } from '../../../../payload-types.js' export type ArchiveBlockProps = Extract< Exclude<Page['layout'], undefined>[0], diff --git a/app/live-preview/_blocks/CallToAction/index.module.scss b/test/live-preview/app/live-preview/_blocks/CallToAction/index.module.scss similarity index 100% rename from app/live-preview/_blocks/CallToAction/index.module.scss rename to test/live-preview/app/live-preview/_blocks/CallToAction/index.module.scss diff --git a/app/live-preview/_blocks/CallToAction/index.tsx b/test/live-preview/app/live-preview/_blocks/CallToAction/index.tsx similarity index 93% rename from app/live-preview/_blocks/CallToAction/index.tsx rename to test/live-preview/app/live-preview/_blocks/CallToAction/index.tsx index d66ee2a3d50..857810241a1 100644 --- a/app/live-preview/_blocks/CallToAction/index.tsx +++ b/test/live-preview/app/live-preview/_blocks/CallToAction/index.tsx @@ -1,6 +1,6 @@ import React from 'react' -import type { Page } from '../../../../test/live-preview/payload-types.js' +import type { Page } from '../../../../payload-types.js' import { Gutter } from '../../_components/Gutter/index.js' import { CMSLink } from '../../_components/Link/index.js' diff --git a/app/live-preview/_blocks/Content/index.module.scss b/test/live-preview/app/live-preview/_blocks/Content/index.module.scss similarity index 100% rename from app/live-preview/_blocks/Content/index.module.scss rename to test/live-preview/app/live-preview/_blocks/Content/index.module.scss diff --git a/app/live-preview/_blocks/Content/index.tsx b/test/live-preview/app/live-preview/_blocks/Content/index.tsx similarity index 93% rename from app/live-preview/_blocks/Content/index.tsx rename to test/live-preview/app/live-preview/_blocks/Content/index.tsx index 8f3ba77b46c..330200a5bbc 100644 --- a/app/live-preview/_blocks/Content/index.tsx +++ b/test/live-preview/app/live-preview/_blocks/Content/index.tsx @@ -1,6 +1,6 @@ import React, { Fragment } from 'react' -import type { Page } from '../../../../test/live-preview/payload-types.js' +import type { Page } from '../../../../payload-types.js' import { Gutter } from '../../_components/Gutter/index.js' import { CMSLink } from '../../_components/Link/index.js' diff --git a/app/live-preview/_blocks/MediaBlock/index.module.scss b/test/live-preview/app/live-preview/_blocks/MediaBlock/index.module.scss similarity index 100% rename from app/live-preview/_blocks/MediaBlock/index.module.scss rename to test/live-preview/app/live-preview/_blocks/MediaBlock/index.module.scss diff --git a/app/live-preview/_blocks/MediaBlock/index.tsx b/test/live-preview/app/live-preview/_blocks/MediaBlock/index.tsx similarity index 93% rename from app/live-preview/_blocks/MediaBlock/index.tsx rename to test/live-preview/app/live-preview/_blocks/MediaBlock/index.tsx index 800ebf0ad2c..c80c2fffd9c 100644 --- a/app/live-preview/_blocks/MediaBlock/index.tsx +++ b/test/live-preview/app/live-preview/_blocks/MediaBlock/index.tsx @@ -2,7 +2,7 @@ import type { StaticImageData } from 'next/image.js' import React from 'react' -import type { Page } from '../../../../test/live-preview/payload-types.js' +import type { Page } from '../../../../payload-types.js' import { Gutter } from '../../_components/Gutter/index.js' import { Media } from '../../_components/Media/index.js' diff --git a/app/live-preview/_blocks/RelatedPosts/index.module.scss b/test/live-preview/app/live-preview/_blocks/RelatedPosts/index.module.scss similarity index 100% rename from app/live-preview/_blocks/RelatedPosts/index.module.scss rename to test/live-preview/app/live-preview/_blocks/RelatedPosts/index.module.scss diff --git a/app/live-preview/_blocks/RelatedPosts/index.tsx b/test/live-preview/app/live-preview/_blocks/RelatedPosts/index.tsx similarity index 94% rename from app/live-preview/_blocks/RelatedPosts/index.tsx rename to test/live-preview/app/live-preview/_blocks/RelatedPosts/index.tsx index c421decae03..2a20aa19f85 100644 --- a/app/live-preview/_blocks/RelatedPosts/index.tsx +++ b/test/live-preview/app/live-preview/_blocks/RelatedPosts/index.tsx @@ -1,6 +1,6 @@ import React from 'react' -import type { Post } from '../../../../test/live-preview/payload-types.js' +import type { Post } from '../../../../payload-types.js' import { Card } from '../../_components/Card/index.js' import { Gutter } from '../../_components/Gutter/index.js' diff --git a/app/live-preview/_blocks/Relationships/index.module.scss b/test/live-preview/app/live-preview/_blocks/Relationships/index.module.scss similarity index 100% rename from app/live-preview/_blocks/Relationships/index.module.scss rename to test/live-preview/app/live-preview/_blocks/Relationships/index.module.scss diff --git a/app/live-preview/_blocks/Relationships/index.tsx b/test/live-preview/app/live-preview/_blocks/Relationships/index.tsx similarity index 98% rename from app/live-preview/_blocks/Relationships/index.tsx rename to test/live-preview/app/live-preview/_blocks/Relationships/index.tsx index aac29b6a084..fb825da6ce0 100644 --- a/app/live-preview/_blocks/Relationships/index.tsx +++ b/test/live-preview/app/live-preview/_blocks/Relationships/index.tsx @@ -1,6 +1,6 @@ import React, { Fragment } from 'react' -import type { Page } from '../../../../test/live-preview/payload-types.js' +import type { Page } from '../../../../payload-types.js' import { Gutter } from '../../_components/Gutter/index.js' import RichText from '../../_components/RichText/index.js' diff --git a/app/live-preview/_components/BackgroundColor/index.module.scss b/test/live-preview/app/live-preview/_components/BackgroundColor/index.module.scss similarity index 100% rename from app/live-preview/_components/BackgroundColor/index.module.scss rename to test/live-preview/app/live-preview/_components/BackgroundColor/index.module.scss diff --git a/app/live-preview/_components/BackgroundColor/index.tsx b/test/live-preview/app/live-preview/_components/BackgroundColor/index.tsx similarity index 100% rename from app/live-preview/_components/BackgroundColor/index.tsx rename to test/live-preview/app/live-preview/_components/BackgroundColor/index.tsx diff --git a/app/live-preview/_components/Blocks/index.tsx b/test/live-preview/app/live-preview/_components/Blocks/index.tsx similarity index 97% rename from app/live-preview/_components/Blocks/index.tsx rename to test/live-preview/app/live-preview/_components/Blocks/index.tsx index cd126bb2513..9df8595f261 100644 --- a/app/live-preview/_components/Blocks/index.tsx +++ b/test/live-preview/app/live-preview/_components/Blocks/index.tsx @@ -1,6 +1,6 @@ import React, { Fragment } from 'react' -import type { Page } from '../../../../test/live-preview/payload-types.js' +import type { Page } from '../../../../payload-types.js' import type { RelationshipsBlockProps } from '../../_blocks/Relationships/index.js' import type { VerticalPaddingOptions } from '../VerticalPadding/index.js' diff --git a/app/live-preview/_components/Button/index.module.scss b/test/live-preview/app/live-preview/_components/Button/index.module.scss similarity index 100% rename from app/live-preview/_components/Button/index.module.scss rename to test/live-preview/app/live-preview/_components/Button/index.module.scss diff --git a/app/live-preview/_components/Button/index.tsx b/test/live-preview/app/live-preview/_components/Button/index.tsx similarity index 100% rename from app/live-preview/_components/Button/index.tsx rename to test/live-preview/app/live-preview/_components/Button/index.tsx diff --git a/app/live-preview/_components/Card/index.module.scss b/test/live-preview/app/live-preview/_components/Card/index.module.scss similarity index 100% rename from app/live-preview/_components/Card/index.module.scss rename to test/live-preview/app/live-preview/_components/Card/index.module.scss diff --git a/app/live-preview/_components/Card/index.tsx b/test/live-preview/app/live-preview/_components/Card/index.tsx similarity index 97% rename from app/live-preview/_components/Card/index.tsx rename to test/live-preview/app/live-preview/_components/Card/index.tsx index fb05f073818..b4ee0787b8c 100644 --- a/app/live-preview/_components/Card/index.tsx +++ b/test/live-preview/app/live-preview/_components/Card/index.tsx @@ -1,7 +1,7 @@ import LinkWithDefault from 'next/link.js' import React, { Fragment } from 'react' -import type { Post } from '../../../../test/live-preview/payload-types.js' +import type { Post } from '../../../../payload-types.js' import { Media } from '../Media/index.js' import classes from './index.module.scss' diff --git a/app/live-preview/_components/Chevron/index.tsx b/test/live-preview/app/live-preview/_components/Chevron/index.tsx similarity index 100% rename from app/live-preview/_components/Chevron/index.tsx rename to test/live-preview/app/live-preview/_components/Chevron/index.tsx diff --git a/app/live-preview/_components/CollectionArchive/PopulateByCollection/index.module.scss b/test/live-preview/app/live-preview/_components/CollectionArchive/PopulateByCollection/index.module.scss similarity index 100% rename from app/live-preview/_components/CollectionArchive/PopulateByCollection/index.module.scss rename to test/live-preview/app/live-preview/_components/CollectionArchive/PopulateByCollection/index.module.scss diff --git a/app/live-preview/_components/CollectionArchive/PopulateByCollection/index.tsx b/test/live-preview/app/live-preview/_components/CollectionArchive/PopulateByCollection/index.tsx similarity index 98% rename from app/live-preview/_components/CollectionArchive/PopulateByCollection/index.tsx rename to test/live-preview/app/live-preview/_components/CollectionArchive/PopulateByCollection/index.tsx index b2f4a8f22c0..242d2ddb18e 100644 --- a/app/live-preview/_components/CollectionArchive/PopulateByCollection/index.tsx +++ b/test/live-preview/app/live-preview/_components/CollectionArchive/PopulateByCollection/index.tsx @@ -3,7 +3,7 @@ import qs from 'qs' import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react' -import type { Post } from '../../../../../test/live-preview/payload-types.js' +import type { Post } from '../../../../../payload-types.js' import type { ArchiveBlockProps } from '../../../_blocks/ArchiveBlock/types.js' import { PAYLOAD_SERVER_URL } from '../../../_api/serverURL.js' diff --git a/app/live-preview/_components/CollectionArchive/PopulateBySelection/index.module.scss b/test/live-preview/app/live-preview/_components/CollectionArchive/PopulateBySelection/index.module.scss similarity index 100% rename from app/live-preview/_components/CollectionArchive/PopulateBySelection/index.module.scss rename to test/live-preview/app/live-preview/_components/CollectionArchive/PopulateBySelection/index.module.scss diff --git a/app/live-preview/_components/CollectionArchive/PopulateBySelection/index.tsx b/test/live-preview/app/live-preview/_components/CollectionArchive/PopulateBySelection/index.tsx similarity index 100% rename from app/live-preview/_components/CollectionArchive/PopulateBySelection/index.tsx rename to test/live-preview/app/live-preview/_components/CollectionArchive/PopulateBySelection/index.tsx diff --git a/app/live-preview/_components/CollectionArchive/index.tsx b/test/live-preview/app/live-preview/_components/CollectionArchive/index.tsx similarity index 100% rename from app/live-preview/_components/CollectionArchive/index.tsx rename to test/live-preview/app/live-preview/_components/CollectionArchive/index.tsx diff --git a/app/live-preview/_components/Footer/index.module.scss b/test/live-preview/app/live-preview/_components/Footer/index.module.scss similarity index 100% rename from app/live-preview/_components/Footer/index.module.scss rename to test/live-preview/app/live-preview/_components/Footer/index.module.scss diff --git a/app/live-preview/_components/Footer/index.tsx b/test/live-preview/app/live-preview/_components/Footer/index.tsx similarity index 100% rename from app/live-preview/_components/Footer/index.tsx rename to test/live-preview/app/live-preview/_components/Footer/index.tsx diff --git a/app/live-preview/_components/Gutter/index.module.scss b/test/live-preview/app/live-preview/_components/Gutter/index.module.scss similarity index 100% rename from app/live-preview/_components/Gutter/index.module.scss rename to test/live-preview/app/live-preview/_components/Gutter/index.module.scss diff --git a/app/live-preview/_components/Gutter/index.tsx b/test/live-preview/app/live-preview/_components/Gutter/index.tsx similarity index 100% rename from app/live-preview/_components/Gutter/index.tsx rename to test/live-preview/app/live-preview/_components/Gutter/index.tsx diff --git a/app/live-preview/_components/Header/Nav/index.module.scss b/test/live-preview/app/live-preview/_components/Header/Nav/index.module.scss similarity index 100% rename from app/live-preview/_components/Header/Nav/index.module.scss rename to test/live-preview/app/live-preview/_components/Header/Nav/index.module.scss diff --git a/app/live-preview/_components/Header/Nav/index.tsx b/test/live-preview/app/live-preview/_components/Header/Nav/index.tsx similarity index 100% rename from app/live-preview/_components/Header/Nav/index.tsx rename to test/live-preview/app/live-preview/_components/Header/Nav/index.tsx diff --git a/app/live-preview/_components/Header/index.module.scss b/test/live-preview/app/live-preview/_components/Header/index.module.scss similarity index 100% rename from app/live-preview/_components/Header/index.module.scss rename to test/live-preview/app/live-preview/_components/Header/index.module.scss diff --git a/app/live-preview/_components/Header/index.tsx b/test/live-preview/app/live-preview/_components/Header/index.tsx similarity index 100% rename from app/live-preview/_components/Header/index.tsx rename to test/live-preview/app/live-preview/_components/Header/index.tsx diff --git a/app/live-preview/_components/Hero/index.tsx b/test/live-preview/app/live-preview/_components/Hero/index.tsx similarity index 100% rename from app/live-preview/_components/Hero/index.tsx rename to test/live-preview/app/live-preview/_components/Hero/index.tsx diff --git a/app/live-preview/_components/Link/index.tsx b/test/live-preview/app/live-preview/_components/Link/index.tsx similarity index 94% rename from app/live-preview/_components/Link/index.tsx rename to test/live-preview/app/live-preview/_components/Link/index.tsx index d7e632088ae..a940a83e4cb 100644 --- a/app/live-preview/_components/Link/index.tsx +++ b/test/live-preview/app/live-preview/_components/Link/index.tsx @@ -1,7 +1,7 @@ import LinkWithDefault from 'next/link.js' import React from 'react' -import type { Page, Post } from '../../../../test/live-preview/payload-types.js' +import type { Page, Post } from '../../../../payload-types.js' import type { Props as ButtonProps } from '../Button/index.js' import { Button } from '../Button/index.js' diff --git a/app/live-preview/_components/Media/Image/index.module.scss b/test/live-preview/app/live-preview/_components/Media/Image/index.module.scss similarity index 100% rename from app/live-preview/_components/Media/Image/index.module.scss rename to test/live-preview/app/live-preview/_components/Media/Image/index.module.scss diff --git a/app/live-preview/_components/Media/Image/index.tsx b/test/live-preview/app/live-preview/_components/Media/Image/index.tsx similarity index 100% rename from app/live-preview/_components/Media/Image/index.tsx rename to test/live-preview/app/live-preview/_components/Media/Image/index.tsx diff --git a/app/live-preview/_components/Media/Video/index.module.scss b/test/live-preview/app/live-preview/_components/Media/Video/index.module.scss similarity index 100% rename from app/live-preview/_components/Media/Video/index.module.scss rename to test/live-preview/app/live-preview/_components/Media/Video/index.module.scss diff --git a/app/live-preview/_components/Media/Video/index.tsx b/test/live-preview/app/live-preview/_components/Media/Video/index.tsx similarity index 100% rename from app/live-preview/_components/Media/Video/index.tsx rename to test/live-preview/app/live-preview/_components/Media/Video/index.tsx diff --git a/app/live-preview/_components/Media/index.tsx b/test/live-preview/app/live-preview/_components/Media/index.tsx similarity index 92% rename from app/live-preview/_components/Media/index.tsx rename to test/live-preview/app/live-preview/_components/Media/index.tsx index d4555438a69..61934ad5b1e 100644 --- a/app/live-preview/_components/Media/index.tsx +++ b/test/live-preview/app/live-preview/_components/Media/index.tsx @@ -11,7 +11,7 @@ export const Media: React.FC<Props> = (props) => { const { className, htmlElement = 'div', resource } = props const isVideo = typeof resource !== 'string' && resource?.mimeType?.includes('video') - const Tag = (htmlElement as ElementType) || Fragment + const Tag = (htmlElement) || Fragment return ( <Tag diff --git a/app/live-preview/_components/Media/types.ts b/test/live-preview/app/live-preview/_components/Media/types.ts similarity index 89% rename from app/live-preview/_components/Media/types.ts rename to test/live-preview/app/live-preview/_components/Media/types.ts index 4612310be93..932aaf82b71 100644 --- a/app/live-preview/_components/Media/types.ts +++ b/test/live-preview/app/live-preview/_components/Media/types.ts @@ -1,7 +1,7 @@ import type { StaticImageData } from 'next/image' import type { ElementType, Ref } from 'react' -import type { Media as MediaType } from '../../../payload-types' +import type { Media as MediaType } from '../../../payload-types.js' export interface Props { alt?: string diff --git a/app/live-preview/_components/PageRange/index.module.scss b/test/live-preview/app/live-preview/_components/PageRange/index.module.scss similarity index 100% rename from app/live-preview/_components/PageRange/index.module.scss rename to test/live-preview/app/live-preview/_components/PageRange/index.module.scss diff --git a/app/live-preview/_components/PageRange/index.tsx b/test/live-preview/app/live-preview/_components/PageRange/index.tsx similarity index 100% rename from app/live-preview/_components/PageRange/index.tsx rename to test/live-preview/app/live-preview/_components/PageRange/index.tsx diff --git a/app/live-preview/_components/Pagination/index.module.scss b/test/live-preview/app/live-preview/_components/Pagination/index.module.scss similarity index 100% rename from app/live-preview/_components/Pagination/index.module.scss rename to test/live-preview/app/live-preview/_components/Pagination/index.module.scss diff --git a/app/live-preview/_components/Pagination/index.tsx b/test/live-preview/app/live-preview/_components/Pagination/index.tsx similarity index 100% rename from app/live-preview/_components/Pagination/index.tsx rename to test/live-preview/app/live-preview/_components/Pagination/index.tsx diff --git a/app/live-preview/_components/RichText/index.module.scss b/test/live-preview/app/live-preview/_components/RichText/index.module.scss similarity index 100% rename from app/live-preview/_components/RichText/index.module.scss rename to test/live-preview/app/live-preview/_components/RichText/index.module.scss diff --git a/app/live-preview/_components/RichText/index.tsx b/test/live-preview/app/live-preview/_components/RichText/index.tsx similarity index 100% rename from app/live-preview/_components/RichText/index.tsx rename to test/live-preview/app/live-preview/_components/RichText/index.tsx diff --git a/app/live-preview/_components/RichText/serializeLexical.tsx b/test/live-preview/app/live-preview/_components/RichText/serializeLexical.tsx similarity index 100% rename from app/live-preview/_components/RichText/serializeLexical.tsx rename to test/live-preview/app/live-preview/_components/RichText/serializeLexical.tsx diff --git a/app/live-preview/_components/RichText/serializeSlate.tsx b/test/live-preview/app/live-preview/_components/RichText/serializeSlate.tsx similarity index 100% rename from app/live-preview/_components/RichText/serializeSlate.tsx rename to test/live-preview/app/live-preview/_components/RichText/serializeSlate.tsx diff --git a/app/live-preview/_components/VerticalPadding/index.module.scss b/test/live-preview/app/live-preview/_components/VerticalPadding/index.module.scss similarity index 100% rename from app/live-preview/_components/VerticalPadding/index.module.scss rename to test/live-preview/app/live-preview/_components/VerticalPadding/index.module.scss diff --git a/app/live-preview/_components/VerticalPadding/index.tsx b/test/live-preview/app/live-preview/_components/VerticalPadding/index.tsx similarity index 100% rename from app/live-preview/_components/VerticalPadding/index.tsx rename to test/live-preview/app/live-preview/_components/VerticalPadding/index.tsx diff --git a/app/live-preview/_css/app.scss b/test/live-preview/app/live-preview/_css/app.scss similarity index 100% rename from app/live-preview/_css/app.scss rename to test/live-preview/app/live-preview/_css/app.scss diff --git a/app/live-preview/_css/colors.scss b/test/live-preview/app/live-preview/_css/colors.scss similarity index 100% rename from app/live-preview/_css/colors.scss rename to test/live-preview/app/live-preview/_css/colors.scss diff --git a/app/live-preview/_css/common.scss b/test/live-preview/app/live-preview/_css/common.scss similarity index 100% rename from app/live-preview/_css/common.scss rename to test/live-preview/app/live-preview/_css/common.scss diff --git a/app/live-preview/_css/queries.scss b/test/live-preview/app/live-preview/_css/queries.scss similarity index 100% rename from app/live-preview/_css/queries.scss rename to test/live-preview/app/live-preview/_css/queries.scss diff --git a/app/live-preview/_css/type.scss b/test/live-preview/app/live-preview/_css/type.scss similarity index 100% rename from app/live-preview/_css/type.scss rename to test/live-preview/app/live-preview/_css/type.scss diff --git a/app/live-preview/_heros/HighImpact/index.module.scss b/test/live-preview/app/live-preview/_heros/HighImpact/index.module.scss similarity index 100% rename from app/live-preview/_heros/HighImpact/index.module.scss rename to test/live-preview/app/live-preview/_heros/HighImpact/index.module.scss diff --git a/app/live-preview/_heros/HighImpact/index.tsx b/test/live-preview/app/live-preview/_heros/HighImpact/index.tsx similarity index 100% rename from app/live-preview/_heros/HighImpact/index.tsx rename to test/live-preview/app/live-preview/_heros/HighImpact/index.tsx diff --git a/app/live-preview/_heros/LowImpact/index.module.scss b/test/live-preview/app/live-preview/_heros/LowImpact/index.module.scss similarity index 100% rename from app/live-preview/_heros/LowImpact/index.module.scss rename to test/live-preview/app/live-preview/_heros/LowImpact/index.module.scss diff --git a/app/live-preview/_heros/LowImpact/index.tsx b/test/live-preview/app/live-preview/_heros/LowImpact/index.tsx similarity index 100% rename from app/live-preview/_heros/LowImpact/index.tsx rename to test/live-preview/app/live-preview/_heros/LowImpact/index.tsx diff --git a/app/live-preview/_heros/PostHero/index.module.scss b/test/live-preview/app/live-preview/_heros/PostHero/index.module.scss similarity index 100% rename from app/live-preview/_heros/PostHero/index.module.scss rename to test/live-preview/app/live-preview/_heros/PostHero/index.module.scss diff --git a/app/live-preview/_heros/PostHero/index.tsx b/test/live-preview/app/live-preview/_heros/PostHero/index.tsx similarity index 96% rename from app/live-preview/_heros/PostHero/index.tsx rename to test/live-preview/app/live-preview/_heros/PostHero/index.tsx index 6c6d7507fd3..7cf19c4f5d6 100644 --- a/app/live-preview/_heros/PostHero/index.tsx +++ b/test/live-preview/app/live-preview/_heros/PostHero/index.tsx @@ -1,7 +1,7 @@ import LinkWithDefault from 'next/link.js' import React, { Fragment } from 'react' -import type { Post } from '../../../../test/live-preview/payload-types.js' +import type { Post } from '../../../../payload-types.js' import { PAYLOAD_SERVER_URL } from '../../_api/serverURL.js' import { Gutter } from '../../_components/Gutter/index.js' diff --git a/app/live-preview/_utilities/formatDateTime.ts b/test/live-preview/app/live-preview/_utilities/formatDateTime.ts similarity index 100% rename from app/live-preview/_utilities/formatDateTime.ts rename to test/live-preview/app/live-preview/_utilities/formatDateTime.ts diff --git a/app/live-preview/_utilities/toKebabCase.ts b/test/live-preview/app/live-preview/_utilities/toKebabCase.ts similarity index 100% rename from app/live-preview/_utilities/toKebabCase.ts rename to test/live-preview/app/live-preview/_utilities/toKebabCase.ts diff --git a/app/live-preview/cssVariables.js b/test/live-preview/app/live-preview/cssVariables.js similarity index 100% rename from app/live-preview/cssVariables.js rename to test/live-preview/app/live-preview/cssVariables.js diff --git a/app/live-preview/layout.tsx b/test/live-preview/app/live-preview/layout.tsx similarity index 100% rename from app/live-preview/layout.tsx rename to test/live-preview/app/live-preview/layout.tsx diff --git a/app/live-preview/not-found.tsx b/test/live-preview/app/live-preview/not-found.tsx similarity index 100% rename from app/live-preview/not-found.tsx rename to test/live-preview/app/live-preview/not-found.tsx diff --git a/app/live-preview/page.tsx b/test/live-preview/app/live-preview/page.tsx similarity index 100% rename from app/live-preview/page.tsx rename to test/live-preview/app/live-preview/page.tsx diff --git a/test/live-preview/next-env.d.ts b/test/live-preview/next-env.d.ts new file mode 100644 index 00000000000..4f11a03dc6c --- /dev/null +++ b/test/live-preview/next-env.d.ts @@ -0,0 +1,5 @@ +/// <reference types="next" /> +/// <reference types="next/image-types/global" /> + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/test/live-preview/next.config.mjs b/test/live-preview/next.config.mjs new file mode 100644 index 00000000000..b2ea0371928 --- /dev/null +++ b/test/live-preview/next.config.mjs @@ -0,0 +1,3 @@ +import nextConfig from '../../next.config.mjs' + +export default nextConfig diff --git a/test/live-preview/tsconfig.json b/test/live-preview/tsconfig.json new file mode 100644 index 00000000000..b85fda49c88 --- /dev/null +++ b/test/live-preview/tsconfig.json @@ -0,0 +1,52 @@ +{ + "compilerOptions": { + "lib": [ + "dom", + "dom.iterable", + "esnext" + ], + "allowJs": true, + "skipLibCheck": true, + "strict": false, + "noEmit": true, + "incremental": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve", + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@payload-config": ["./config.ts"], + "@payloadcms/ui/assets": ["../../packages/ui/src/assets/index.ts"], + "@payloadcms/ui/elements/*": ["../../packages/ui/src/elements/*/index.tsx"], + "@payloadcms/ui/fields/*": ["../../packages/ui/src/fields/*/index.tsx"], + "@payloadcms/ui/forms/*": ["../../packages/ui/src/forms/*/index.tsx"], + "@payloadcms/ui/graphics/*": ["../../packages/ui/src/graphics/*/index.tsx"], + "@payloadcms/ui/hooks/*": ["../../packages/ui/src/hooks/*.ts"], + "@payloadcms/ui/icons/*": ["../../packages/ui/src/icons/*/index.tsx"], + "@payloadcms/ui/providers/*": ["../../packages/ui/src/providers/*/index.tsx"], + "@payloadcms/ui/templates/*": ["../../packages/ui/src/templates/*/index.tsx"], + "@payloadcms/ui/utilities/*": ["../../packages/ui/src/utilities/*.ts"], + "@payloadcms/ui/scss": ["../../packages/ui/src/scss.scss"], + "@payloadcms/ui/scss/app.scss": ["../../packages/ui/src/scss/app.scss"], + "payload/types": ["../../packages/payload/src/exports/types/index.ts"], + "@payloadcms/next/*": ["../../packages/next/src/*"], + "@payloadcms/next": ["../../packages/next/src/exports/*"], + } + }, + "include": [ + "next-env.d.ts", + ".next/types/**/*.ts", + "**/*.ts", + "**/*.tsx" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/test/tsconfig.json b/test/tsconfig.json index 6b11763be6c..e2ac241919c 100644 --- a/test/tsconfig.json +++ b/test/tsconfig.json @@ -39,9 +39,12 @@ "@payloadcms/ui/scss": ["./packages/ui/src/scss.scss"], "@payloadcms/ui/scss/app.scss": ["./packages/ui/src/scss/app.scss"], "payload/types": ["./packages/payload/src/exports/types/index.ts"], + "@payloadcms/next/*": ["./packages/next/src/*"], + "@payloadcms/next": ["./packages/next/src/exports/*"], + "@payload-config": ["./_community/config.ts"] } }, "exclude": ["dist", "build", "node_modules", ".eslintrc.js", "dist/**/*.js", "**/dist/**/*.js"], - "include": ["./**/*.ts", ".next/types/**/*.ts", "setup.js"], + "include": ["./**/*.ts", ".next/types/**/*.ts", "setup.js", "helpers/getNextJSRootDir.js"], "references": [] } diff --git a/tsconfig.json b/tsconfig.json index 55baff19c7f..ab94c2a8c5d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -36,8 +36,11 @@ } ], "paths": { + "payload/types": [ + "./packages/payload/src/exports/types.ts" + ], "@payload-config": [ - "./test/_community/config.ts" + "./test/fields/config.ts" ], "@payloadcms/live-preview": [ "./packages/live-preview/src"
ffa56e6c8167ae0f63886efb0f6bf5a381c52b98
2020-10-27 06:11:49
Elliot DeNolf
fix: /me only works on current user's collection
false
/me only works on current user's collection
fix
diff --git a/src/auth/operations/me.js b/src/auth/operations/me.js index 65471b01913..2a5a4ed6908 100644 --- a/src/auth/operations/me.js +++ b/src/auth/operations/me.js @@ -1,11 +1,20 @@ const jwt = require('jsonwebtoken'); +const httpStatus = require('http-status'); const getExtractJWT = require('../getExtractJWT'); +const { APIError } = require('../../errors'); + async function me({ req }) { const extractJWT = getExtractJWT(this.config); if (req.user) { + const requestedSlug = req.route.path.split('/').filter((r) => r !== '')[0]; const user = { ...req.user }; + + if (user.collection !== requestedSlug) { + throw new APIError('Incorrect collection', httpStatus.FORBIDDEN); + } + delete user.collection; const response = {
ded891e390a93f71963762c0200c97a0beec5cad
2021-11-29 18:48:59
James
fix: ensures sorting by _id instead of improper id
false
ensures sorting by _id instead of improper id
fix
diff --git a/src/collections/operations/find.ts b/src/collections/operations/find.ts index 919527fe7c2..fe1b0b83321 100644 --- a/src/collections/operations/find.ts +++ b/src/collections/operations/find.ts @@ -98,28 +98,30 @@ async function find<T extends TypeWithID = any>(incomingArgs: Arguments): Promis // Find // ///////////////////////////////////// - let sortParam: Record<string, string>; + let sortProperty: string; + let sortOrder = 'desc'; if (!args.sort) { if (collectionConfig.timestamps) { - sortParam = { createdAt: 'desc' }; + sortProperty = 'createdAt'; } else { - sortParam = { _id: 'desc' }; + sortProperty = '_id'; } } else if (args.sort.indexOf('-') === 0) { - sortParam = { - [args.sort.substring(1)]: 'desc', - }; + sortProperty = args.sort.substring(1); } else { - sortParam = { - [args.sort]: 'asc', - }; + sortProperty = args.sort; + sortOrder = 'asc'; } + if (sortProperty === 'id') sortProperty = '_id'; + const optionsToExecute = { page: page || 1, limit: limit || 10, - sort: sortParam, + sort: { + [sortProperty]: sortOrder, + }, lean: true, leanWithId: true, useEstimatedCount,
485991bd48c3512acca8dd94b3ab6c160bf1f153
2022-04-05 05:14:49
Dan Ribbens
feat: filter relationship options in admin ui using filterOptions
false
filter relationship options in admin ui using filterOptions
feat
diff --git a/demo/collections/RelationshipA.ts b/demo/collections/RelationshipA.ts index ba787292236..9dab529476f 100644 --- a/demo/collections/RelationshipA.ts +++ b/demo/collections/RelationshipA.ts @@ -56,6 +56,16 @@ const RelationshipA: CollectionConfig = { hasMany: true, localized: true, }, + { + name: 'filterRelationship', + type: 'relationship', + relationTo: 'relationship-b', + filterOptions: { + disableRelation: { + not_equals: true, + }, + }, + }, { name: 'demoHiddenField', type: 'text', diff --git a/demo/collections/RelationshipB.ts b/demo/collections/RelationshipB.ts index 969565cf13e..8fd50cece7f 100644 --- a/demo/collections/RelationshipB.ts +++ b/demo/collections/RelationshipB.ts @@ -17,6 +17,13 @@ const RelationshipB: CollectionConfig = { name: 'title', type: 'text', }, + { + name: 'disableRelation', // used on RelationshipA.filterRelationship field + type: 'checkbox', + admin: { + position: 'sidebar', + }, + }, { name: 'post', label: 'Post', diff --git a/docs/fields/relationship.mdx b/docs/fields/relationship.mdx index 9906f22cc6a..9f8fa40267a 100644 --- a/docs/fields/relationship.mdx +++ b/docs/fields/relationship.mdx @@ -22,6 +22,7 @@ keywords: relationship, fields, config, configuration, documentation, Content Ma | ---------------- | ----------- | | **`name`** * | To be used as the property name when stored and retrieved from the database. | | **`relationTo`** * | Provide one or many collection `slug`s to be able to assign relationships to. | +| **`filterOptions`** | A query to filter which options appear in the UI and validate against. [More](#filtering-relationship-options). | | **`hasMany`** | Boolean when, if set to `true`, allows this field to have many relations instead of only one. | | **`maxDepth`** | Sets a number limit on iterations of related documents to populate when queried. [Depth](/docs/getting-started/concepts#depth) | | **`label`** | Used as a field label in the Admin panel and to name the generated GraphQL type. | @@ -44,6 +45,45 @@ keywords: relationship, fields, config, configuration, documentation, Content Ma The <a href="/docs/getting-started/concepts#depth">Depth</a> parameter can be used to automatically populate related documents that are returned by the API. </Banner> +### Filtering relationship options + +Options can be dynamically limited by supply a query that is used for validating input and querying relationships in the UI. The `filterOptions` property can be a `Where` query or a function that returns one. When using a function, it will be called with an argument object with the following properties: + +| Property | Description | +| ------------- | -------------| +| `relationTo` | The `slug` of the collection of the items relation | +| `data` | An object of the full collection or global document | +| `siblingData` | An object of the document data limited to fields within the same parent to the field | +| `id` | The value of the collection `id`, will be `undefined` on create request | +| `user` | The currently authenticated user object | + +```js + const relationshipField = { + name: 'purchase', + type: 'relationship', + relationTo: ['products', 'services'], + filterOptions: ({relationTo, siblingData, }) => { + // returns a Where query dynamically by the type of relationship + if (relationTo === 'products') { + return { + 'product.stock': { is_greater_than: siblingData.quantity } + } + } + if (relationTo === 'services') { + return { + 'services.isAvailable': { equals: true } + } + } + }, + }; +``` + +You can learn more about writing queries [here](/docs/queries/overview). + +<Banner type="warning"> + When a relationship field has both `filterOptions` and `validate` the server side validation will not enforce `filterOptions` unless you call the relationship field validate imported from `payload/fields/validations` in the validate function. +</Banner> + ### How the data is saved Given the variety of options possible within the `relationship` field type, the shape of the data needed for creating and updating these fields can vary. The following sections will describe the variety of data shapes that can arise from this field. diff --git a/src/admin/components/forms/field-types/Relationship/index.tsx b/src/admin/components/forms/field-types/Relationship/index.tsx index bb4d36a946d..d4ab3355ffb 100644 --- a/src/admin/components/forms/field-types/Relationship/index.tsx +++ b/src/admin/components/forms/field-types/Relationship/index.tsx @@ -1,7 +1,8 @@ import React, { useCallback, useEffect, useState, useReducer, } from 'react'; -import { useConfig } from '@payloadcms/config-provider'; +import equal from 'deep-equal'; +import { useAuth, useConfig } from '@payloadcms/config-provider'; import qs from 'qs'; import withCondition from '../../withCondition'; import ReactSelect from '../../../elements/ReactSelect'; @@ -13,18 +14,31 @@ import FieldDescription from '../../FieldDescription'; import { relationship } from '../../../../../fields/validations'; import { Where } from '../../../../../types'; import { PaginatedDocs } from '../../../../../mongoose/types'; -import { useFormProcessing } from '../../Form/context'; +import { useFormProcessing, useWatchForm } from '../../Form/context'; import optionsReducer from './optionsReducer'; import { Props, Option, ValueWithRelation, GetResults } from './types'; import { createRelationMap } from './createRelationMap'; import { useDebouncedCallback } from '../../../../hooks/useDebouncedCallback'; import './index.scss'; +import { useDocumentInfo } from '../../../utilities/DocumentInfo'; +import { filterOptionsProps } from '../../../../../fields/config/types'; const maxResultsPerRequest = 10; const baseClass = 'relationship'; +const getFilterOptionsQuery = (filterOptions, options: filterOptionsProps): Where => { + let query = {}; + if (typeof filterOptions === 'object') { + query = filterOptions; + } + if (typeof filterOptions === 'function') { + query = filterOptions(options); + } + return query; +}; + const Relationship: React.FC<Props> = (props) => { const { relationTo, @@ -34,6 +48,7 @@ const Relationship: React.FC<Props> = (props) => { required, label, hasMany, + filterOptions, admin: { readOnly, style, @@ -52,6 +67,10 @@ const Relationship: React.FC<Props> = (props) => { collections, } = useConfig(); + const { id } = useDocumentInfo(); + const { user } = useAuth(); + const { getData, getSiblingData } = useWatchForm(); + const formProcessing = useFormProcessing(); const hasMultipleRelations = Array.isArray(relationTo); @@ -59,6 +78,7 @@ const Relationship: React.FC<Props> = (props) => { const [lastFullyLoadedRelation, setLastFullyLoadedRelation] = useState(-1); const [lastLoadedPage, setLastLoadedPage] = useState(1); const [errorLoading, setErrorLoading] = useState(''); + const [optionFilters, setOptionFilters] = useState<{[relation: string]: Where}>({}); const [hasLoadedValueOptions, setHasLoadedValueOptions] = useState(false); const [search, setSearch] = useState(''); @@ -107,9 +127,13 @@ const Relationship: React.FC<Props> = (props) => { where: Where } = { where: { - id: { - not_in: relationMap[relation], - }, + and: [ + { + id: { + not_in: relationMap[relation], + }, + }, + ], }, limit: maxResultsPerRequest, page: lastLoadedPageToUse, @@ -118,9 +142,15 @@ const Relationship: React.FC<Props> = (props) => { }; if (searchArg) { - query.where[fieldToSearch] = { - like: searchArg, - }; + query.where.and.push({ + [fieldToSearch]: { + like: searchArg, + }, + }); + } + + if (optionFilters[relation]) { + query.where.and.push(optionFilters[relation]); } const response = await fetch(`${serverURL}${api}/${relation}?${qs.stringify(query)}`); @@ -148,7 +178,7 @@ const Relationship: React.FC<Props> = (props) => { } }, Promise.resolve()); } - }, [api, collections, serverURL, errorLoading, relationTo, hasMany, hasMultipleRelations]); + }, [relationTo, hasMany, errorLoading, collections, optionFilters, serverURL, api, hasMultipleRelations]); const findOptionsByValue = useCallback((): Option | Option[] => { if (value) { @@ -261,6 +291,25 @@ const Relationship: React.FC<Props> = (props) => { } }, [hasMany, hasMultipleRelations, relationTo, initialValue, hasLoadedValueOptions, errorLoading, collections, api, serverURL]); + useEffect(() => { + const relations = Array.isArray(relationTo) ? relationTo : [relationTo]; + const newOptionFilters = {}; + if (typeof filterOptions !== 'undefined') { + relations.forEach((relation) => { + newOptionFilters[relation] = getFilterOptionsQuery(filterOptions, { + id, + data: getData(), + siblingData: getSiblingData(path), + relationTo: relation, + user, + }); + }); + } + if (!equal(newOptionFilters, optionFilters)) { + setOptionFilters(newOptionFilters); + } + }, [relationTo, filterOptions, optionFilters, id, getData, getSiblingData, path, user]); + useEffect(() => { setHasLoadedValueOptions(false); getResults({ diff --git a/src/fields/config/schema.ts b/src/fields/config/schema.ts index 99db233dc1b..65aa5d944e6 100644 --- a/src/fields/config/schema.ts +++ b/src/fields/config/schema.ts @@ -208,6 +208,10 @@ export const relationship = baseField.keys({ ), name: joi.string().required(), maxDepth: joi.number(), + filterOptions: joi.alternatives().try( + joi.object(), + joi.func(), + ), }); export const blocks = baseField.keys({ diff --git a/src/fields/config/types.ts b/src/fields/config/types.ts index b25a1aa2359..e4497213757 100644 --- a/src/fields/config/types.ts +++ b/src/fields/config/types.ts @@ -1,7 +1,7 @@ /* eslint-disable no-use-before-define */ import { CSSProperties } from 'react'; import { Editor } from 'slate'; -import { Operation } from '../../types'; +import { Operation, Where } from '../../types'; import { TypeWithID } from '../../collections/config/types'; import { PayloadRequest } from '../../express/types'; import { ConditionalDateProps } from '../../admin/components/elements/DatePicker/types'; @@ -202,11 +202,20 @@ export type SelectField = FieldBase & { hasMany?: boolean } +export type filterOptionsProps = { + id: string | number, + user: Partial<User>, + data: unknown, + siblingData: unknown, + relationTo: string, +} + export type RelationshipField = FieldBase & { type: 'relationship'; relationTo: string | string[]; hasMany?: boolean; maxDepth?: number; + filterOptions?: Where | ((options: filterOptionsProps) => Where); } type RichTextPlugin = (editor: Editor) => Editor; diff --git a/src/fields/validations.ts b/src/fields/validations.ts index a8d31688f27..f39626b9224 100644 --- a/src/fields/validations.ts +++ b/src/fields/validations.ts @@ -3,7 +3,8 @@ import { ArrayField, BlockField, CheckboxField, - CodeField, DateField, + CodeField, + DateField, EmailField, NumberField, PointField, @@ -16,6 +17,9 @@ import { UploadField, Validate, } from './config/types'; +import canUseDOM from '../utilities/canUseDOM'; +import payload from '../index'; +import { TypeWithID } from '../collections/config/types'; const defaultMessage = 'This field is required.'; @@ -148,9 +152,39 @@ export const upload: Validate<unknown, unknown, UploadField> = (value: string, { return defaultMessage; }; -export const relationship: Validate<unknown, unknown, RelationshipField> = (value, { required }) => { - if (value || !required) return true; - return defaultMessage; +export const relationship: Validate<unknown, unknown, RelationshipField> = async (value: string | string[], { required, relationTo, filterOptions, id, data, siblingData, user }) => { + if ((!value || (Array.isArray(value) && value.length === 0)) && required) { + return defaultMessage; + } + if (!canUseDOM && typeof filterOptions !== 'undefined' && value) { + const options = []; + const collections = typeof relationTo === 'string' ? [relationTo] : relationTo; + const values: string[] = typeof value === 'string' ? [value] : value; + await Promise.all(collections.map(async (collection) => { + const optionFilter = typeof filterOptions === 'function' ? filterOptions({ + id, + data, + siblingData, + user, + relationTo: collection, + }) : filterOptions; + const result = await payload.find({ + collection, + depth: 0, + where: { + and: [ + { id: { in: values } }, + optionFilter, + ], + }, + }); + options.concat(result.docs.map((item: TypeWithID) => String(item.id))); + })); + if (values.some((input) => options.some((option) => (option === input)))) { + return 'This field has an invalid selection'; + } + return true; + } }; export const array: Validate<unknown, unknown, ArrayField> = (value, { minRows, maxRows, required }) => { diff --git a/src/webpack/getBaseConfig.ts b/src/webpack/getBaseConfig.ts index def6a2fa977..9bd8ed813ed 100644 --- a/src/webpack/getBaseConfig.ts +++ b/src/webpack/getBaseConfig.ts @@ -56,6 +56,7 @@ export default (config: SanitizedConfig): Configuration => ({ 'payload-user-css': config.admin.css, 'payload-scss-overrides': config.admin.scss, dotenv: mockDotENVPath, + [path.resolve(__dirname, '../index.ts')]: mockModulePath, }, extensions: ['.ts', '.tsx', '.js', '.json'], },
f15172374525af98710864c3660b292c10709029
2024-12-02 07:58:13
Alessio Gravili
feat(ui): export TabsProvider and TabComponent (#9647)
false
export TabsProvider and TabComponent (#9647)
feat
diff --git a/packages/ui/src/exports/client/index.ts b/packages/ui/src/exports/client/index.ts index 999bf065fb4..c92e960441d 100644 --- a/packages/ui/src/exports/client/index.ts +++ b/packages/ui/src/exports/client/index.ts @@ -145,7 +145,9 @@ export { RelationshipField } from '../../fields/Relationship/index.js' export { RichTextField } from '../../fields/RichText/index.js' export { RowField } from '../../fields/Row/index.js' export { SelectField, SelectInput } from '../../fields/Select/index.js' -export { TabsField } from '../../fields/Tabs/index.js' +export { TabsField, TabsProvider } from '../../fields/Tabs/index.js' +export { TabComponent } from '../../fields/Tabs/Tab/index.js' + export { TextField, TextInput } from '../../fields/Text/index.js' export { JoinField } from '../../fields/Join/index.js' export type { TextInputProps } from '../../fields/Text/index.js'
f06257e7ff363ddfe7e99efa70f2b4d1f119e422
2024-03-06 02:43:34
Dan Ribbens
chore(release): v3.0.0-alpha.15 [skip ci]
false
v3.0.0-alpha.15 [skip ci]
chore
diff --git a/package.json b/package.json index a747901bec5..5fef0fc45b8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "payload-monorepo", - "version": "3.0.0-alpha.14", + "version": "3.0.0-alpha.15", "private": true, "workspaces:": [ "packages/*" diff --git a/packages/db-mongodb/package.json b/packages/db-mongodb/package.json index ec8f29983d1..49b168ec4ba 100644 --- a/packages/db-mongodb/package.json +++ b/packages/db-mongodb/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/db-mongodb", - "version": "3.0.0-alpha.14", + "version": "3.0.0-alpha.15", "description": "The officially supported MongoDB database adapter for Payload - Update 2", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/graphql/package.json b/packages/graphql/package.json index dad2c127a7d..2addfa0f5cb 100644 --- a/packages/graphql/package.json +++ b/packages/graphql/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/graphql", - "version": "3.0.0-alpha.14", + "version": "3.0.0-alpha.15", "main": "./src/index.ts", "types": "./src/index.d.ts", "scripts": { diff --git a/packages/next/package.json b/packages/next/package.json index 0d5a565fc29..42a3fcf03b7 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/next", - "version": "3.0.0-alpha.14", + "version": "3.0.0-alpha.15", "main": "./src/index.ts", "types": "./src/index.d.ts", "bin": { diff --git a/packages/payload/package.json b/packages/payload/package.json index 8435cec094b..b2312949cfa 100644 --- a/packages/payload/package.json +++ b/packages/payload/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "3.0.0-alpha.14", + "version": "3.0.0-alpha.15", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "MIT", "main": "./dist/index.js", diff --git a/packages/richtext-slate/package.json b/packages/richtext-slate/package.json index f98c59cbd11..83a0059d3f8 100644 --- a/packages/richtext-slate/package.json +++ b/packages/richtext-slate/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/richtext-slate", - "version": "3.0.0-alpha.14", + "version": "3.0.0-alpha.15", "description": "The officially supported Slate richtext adapter for Payload", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/translations/package.json b/packages/translations/package.json index f7019f0a61d..072ba852088 100644 --- a/packages/translations/package.json +++ b/packages/translations/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/translations", - "version": "3.0.0-alpha.14", + "version": "3.0.0-alpha.15", "main": "./dist/exports/index.ts", "types": "./dist/types.d.ts", "scripts": { diff --git a/packages/ui/package.json b/packages/ui/package.json index ba4176d8e66..1175fa824a5 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/ui", - "version": "3.0.0-alpha.14", + "version": "3.0.0-alpha.15", "main": "./src/index.ts", "types": "./dist/index.d.ts", "scripts": {
0e7a6ad5ab7267ac9167f2c59bcf2882d5d3cb49
2024-04-29 04:33:02
Alessio Gravili
fix(richtext-lexical): prevent link modal from showing if selection spans further than the link
false
prevent link modal from showing if selection spans further than the link
fix
diff --git a/packages/richtext-lexical/src/field/features/link/plugins/floatingLinkEditor/LinkEditor/index.tsx b/packages/richtext-lexical/src/field/features/link/plugins/floatingLinkEditor/LinkEditor/index.tsx index c5f6f99d58f..5534458b25e 100644 --- a/packages/richtext-lexical/src/field/features/link/plugins/floatingLinkEditor/LinkEditor/index.tsx +++ b/packages/richtext-lexical/src/field/features/link/plugins/floatingLinkEditor/LinkEditor/index.tsx @@ -11,6 +11,7 @@ import { formatDrawerSlug } from '@payloadcms/ui/elements/Drawer' import { useConfig } from '@payloadcms/ui/providers/Config' import { useEditDepth } from '@payloadcms/ui/providers/EditDepth' import { useTranslation } from '@payloadcms/ui/providers/Translation' +import { $isLineBreakNode } from 'lexical' import { $getSelection, $isRangeSelection, @@ -68,10 +69,19 @@ export function LinkEditor({ anchorElem }: { anchorElem: HTMLElement }): React.R // Handle the data displayed in the floating link editor & drawer when you click on a link node if ($isRangeSelection(selection)) { - const node = getSelectedNode(selection) - selectedNodeDomRect = editor.getElementByKey(node.getKey())?.getBoundingClientRect() - const linkParent: LinkNode = $findMatchingParent(node, $isLinkNode) - if (linkParent == null) { + const focusNode = getSelectedNode(selection) + selectedNodeDomRect = editor.getElementByKey(focusNode.getKey())?.getBoundingClientRect() + const focusLinkParent: LinkNode = $findMatchingParent(focusNode, $isLinkNode) + + const badNode = selection.getNodes().find((node) => { + // Prevent link modal from showing if selection spans further than the link: https://github.com/facebook/lexical/issues/4064 + const linkNode = $findMatchingParent(node, $isLinkNode) + if (!linkNode?.is(focusLinkParent) && !linkNode && !$isLineBreakNode(node)) { + return node + } + }) + + if (focusLinkParent == null || badNode) { setIsLink(false) setIsAutoLink(false) setLinkUrl('') @@ -87,24 +97,24 @@ export function LinkEditor({ anchorElem }: { anchorElem: HTMLElement }): React.R linkType: undefined, newTab: undefined, url: '', - ...linkParent.getFields(), + ...focusLinkParent.getFields(), }, - text: linkParent.getTextContent(), + text: focusLinkParent.getTextContent(), } - if (linkParent.getFields()?.linkType === 'custom') { - setLinkUrl(linkParent.getFields()?.url ?? '') + if (focusLinkParent.getFields()?.linkType === 'custom') { + setLinkUrl(focusLinkParent.getFields()?.url ?? '') setLinkLabel('') } else { // internal link setLinkUrl( - `/admin/collections/${linkParent.getFields()?.doc?.relationTo}/${ - linkParent.getFields()?.doc?.value + `/admin/collections/${focusLinkParent.getFields()?.doc?.relationTo}/${ + focusLinkParent.getFields()?.doc?.value }`, ) const relatedField = config.collections.find( - (coll) => coll.slug === linkParent.getFields()?.doc?.relationTo, + (coll) => coll.slug === focusLinkParent.getFields()?.doc?.relationTo, ) const label = t('fields:linkedTo', { label: getTranslation(relatedField.labels.singular, i18n), @@ -116,7 +126,7 @@ export function LinkEditor({ anchorElem }: { anchorElem: HTMLElement }): React.R setIsLink(true) setSelectedNodes(selection ? selection?.getNodes() : []) - if ($isAutoLinkNode(linkParent)) { + if ($isAutoLinkNode(focusLinkParent)) { setIsAutoLink(true) } else { setIsAutoLink(false)
284f66e6d80f03038d0783f675d059d68779c0dd
2023-10-24 00:01:34
dependabot[bot]
chore(deps): bump graphql in /packages/plugin-stripe/demo (#3815)
false
bump graphql in /packages/plugin-stripe/demo (#3815)
chore
diff --git a/packages/plugin-stripe/demo/yarn.lock b/packages/plugin-stripe/demo/yarn.lock index dee005e137c..0a2292166ef 100644 --- a/packages/plugin-stripe/demo/yarn.lock +++ b/packages/plugin-stripe/demo/yarn.lock @@ -2429,9 +2429,9 @@ graphql-type-json@^0.3.2: integrity sha512-J+vjof74oMlCWXSvt0DOf2APEdZOCdubEvGDUAlqH//VBYcOYsGgRW7Xzorr44LvkjiuvecWc8fChxuZZbChtg== graphql@^16.6.0: - version "16.6.0" - resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.6.0.tgz#c2dcffa4649db149f6282af726c8c83f1c7c5fdb" - integrity sha512-KPIBPDlW7NxrbT/eh4qPXz5FiFdL5UbaA0XUNz2Rp3Z3hqBSkbj0GVjwFDztsWVauZUWsbKHgMg++sk8UX0bkw== + version "16.8.1" + resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.8.1.tgz#1930a965bef1170603702acdb68aedd3f3cf6f07" + integrity sha512-59LZHPdGZVh695Ud9lRzPBVTtlX9ZCV150Er2W43ro37wVof0ctenSaskPPjN7lVTIN8mSZt8PHUNKZuNQUuxw== gzip-size@^6.0.0: version "6.0.0"
76067b4e5091570abdbbd5784c37bc3ef4444c0c
2022-08-07 01:21:51
James
chore: bumps payload
false
bumps payload
chore
diff --git a/dev/package.json b/dev/package.json index 654c0530514..0d2ec967983 100644 --- a/dev/package.json +++ b/dev/package.json @@ -15,7 +15,7 @@ "@azure/storage-blob": "^12.11.0", "dotenv": "^8.2.0", "express": "^4.17.1", - "payload": "^1.0.16" + "payload": "^1.0.18" }, "devDependencies": { "@types/express": "^4.17.9", diff --git a/dev/yarn.lock b/dev/yarn.lock index 32bc0d6bd65..96dac361057 100644 --- a/dev/yarn.lock +++ b/dev/yarn.lock @@ -6731,10 +6731,10 @@ [email protected]: resolved "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz#1d408b3fdb76923b9543d96fb4c9dfd535d9cb5d" integrity sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg== -payload@^1.0.16: - version "1.0.16" - resolved "https://registry.npmjs.org/payload/-/payload-1.0.16.tgz#9a6a5e6506dcb201beedaa1d241eef5a10166c44" - integrity sha512-zcnU7UVUjRvgIX4sXwHfWvNoAd8aHkzkMTWpA4x1aitwMLkGvy73CL5wG4yNjSMNrAXSAAOsAPhK2/xsDdJoiQ== +payload@^1.0.18: + version "1.0.18" + resolved "https://registry.npmjs.org/payload/-/payload-1.0.18.tgz#a9e82e150b76de2cb8593e3d7f3988680a1466d9" + integrity sha512-ikVmcB1K9+0p6zNv/+0MY03J62nc7hoyUo536VjQTPC473MeNqTPG/cPbuLufq2fIGgWPYyUXFuYMNppyZxFIA== dependencies: "@babel/cli" "^7.12.8" "@babel/core" "^7.11.6" diff --git a/package.json b/package.json index cde45fe562a..4348cd61196 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,7 @@ "eslint-plugin-import": "2.25.4", "eslint-plugin-prettier": "^4.0.0", "nodemon": "^2.0.6", - "payload": "^1.0.16", + "payload": "^1.0.18", "prettier": "^2.7.1", "ts-node": "^9.1.1", "typescript": "^4.1.3" diff --git a/yarn.lock b/yarn.lock index 524714dd21a..bb31cafec8b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7289,10 +7289,10 @@ [email protected]: resolved "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz#1d408b3fdb76923b9543d96fb4c9dfd535d9cb5d" integrity sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg== -payload@^1.0.16: - version "1.0.16" - resolved "https://registry.npmjs.org/payload/-/payload-1.0.16.tgz#9a6a5e6506dcb201beedaa1d241eef5a10166c44" - integrity sha512-zcnU7UVUjRvgIX4sXwHfWvNoAd8aHkzkMTWpA4x1aitwMLkGvy73CL5wG4yNjSMNrAXSAAOsAPhK2/xsDdJoiQ== +payload@^1.0.18: + version "1.0.18" + resolved "https://registry.npmjs.org/payload/-/payload-1.0.18.tgz#a9e82e150b76de2cb8593e3d7f3988680a1466d9" + integrity sha512-ikVmcB1K9+0p6zNv/+0MY03J62nc7hoyUo536VjQTPC473MeNqTPG/cPbuLufq2fIGgWPYyUXFuYMNppyZxFIA== dependencies: "@babel/cli" "^7.12.8" "@babel/core" "^7.11.6"
f14e187545b759ac4623189d5e31f25382728cc0
2022-03-16 22:39:37
Dan Ribbens
feat: allow empty string radio and select option values (#479)
false
allow empty string radio and select option values (#479)
feat
diff --git a/demo/collections/Select.ts b/demo/collections/Select.ts index aa85c5cce37..94f563c5000 100644 --- a/demo/collections/Select.ts +++ b/demo/collections/Select.ts @@ -8,7 +8,7 @@ const Select: CollectionConfig = { }, fields: [ { - name: 'Select', + name: 'select', type: 'select', options: [{ value: 'one', @@ -24,7 +24,7 @@ const Select: CollectionConfig = { required: true, }, { - name: 'SelectHasMany', + name: 'selectHasMany', type: 'select', options: [{ value: 'one', @@ -41,7 +41,7 @@ const Select: CollectionConfig = { hasMany: true, }, { - name: 'SelectJustStrings', + name: 'selectJustStrings', type: 'select', options: ['blue', 'green', 'yellow'], label: 'Select Just Strings', @@ -49,7 +49,20 @@ const Select: CollectionConfig = { hasMany: true, }, { - name: 'Radio', + name: 'selectWithEmptyString', + type: 'select', + defaultValue: '', + options: [{ + value: '', + label: 'None', + }, { + value: 'option', + label: 'Option', + }], + required: true, + }, + { + name: 'radio', type: 'radio', options: [{ value: 'one', @@ -64,6 +77,22 @@ const Select: CollectionConfig = { label: 'Choose From', required: true, }, + { + name: 'radioWithEmptyString', + type: 'radio', + defaultValue: '', + options: [{ + value: '', + label: 'None', + }, { + value: 'one', + label: 'One', + }, { + value: 'two', + label: 'Two', + }], + required: true, + }, ], }; diff --git a/src/admin/components/forms/field-types/Select/index.tsx b/src/admin/components/forms/field-types/Select/index.tsx index 98cfe9c581b..4b1cd82532d 100644 --- a/src/admin/components/forms/field-types/Select/index.tsx +++ b/src/admin/components/forms/field-types/Select/index.tsx @@ -7,7 +7,7 @@ import { Props } from './types'; import SelectInput from './Input'; const formatOptions = (options: Option[]): OptionObject[] => options.map((option) => { - if (typeof option === 'object' && option.value) { + if (typeof option === 'object' && (option.value || option.value === '')) { return option; } @@ -42,7 +42,7 @@ const Select: React.FC<Props> = (props) => { useEffect(() => { setOptions(formatOptions(optionsFromProps)); - }, [optionsFromProps]) + }, [optionsFromProps]); const memoizedValidate = useCallback((value) => { const validationResult = validate(value, { required, options }); diff --git a/src/fields/config/schema.ts b/src/fields/config/schema.ts index bacb00ebf08..99db233dc1b 100644 --- a/src/fields/config/schema.ts +++ b/src/fields/config/schema.ts @@ -119,14 +119,14 @@ export const select = baseField.keys({ options: joi.array().items(joi.alternatives().try( joi.string(), joi.object({ - value: joi.string().required(), + value: joi.string().required().allow(''), label: joi.string().required(), }), )).required(), hasMany: joi.boolean().default(false), defaultValue: joi.alternatives().try( - joi.string(), - joi.array().items(joi.string()), + joi.string().allow(''), + joi.array().items(joi.string().allow('')), ), }); @@ -136,11 +136,11 @@ export const radio = baseField.keys({ options: joi.array().items(joi.alternatives().try( joi.string(), joi.object({ - value: joi.string().required(), + value: joi.string().required().allow(''), label: joi.string().required(), }), )).required(), - defaultValue: joi.string(), + defaultValue: joi.string().allow(''), admin: baseAdminFields.keys({ layout: joi.string().valid('vertical', 'horizontal'), }), diff --git a/src/fields/validations.spec.ts b/src/fields/validations.spec.ts index 6d16efaf5b9..8c0c6cb7067 100644 --- a/src/fields/validations.spec.ts +++ b/src/fields/validations.spec.ts @@ -1,5 +1,5 @@ -import { text, textarea, password } from './validations'; +import { text, textarea, password, select } from './validations'; const minLengthMessage = (length: number) => `This value must be longer than the minimum length of ${length} characters.`; const maxLengthMessage = (length: number) => `This value must be shorter than the max length of ${length} characters.`; @@ -122,4 +122,124 @@ describe('Field Validations', () => { expect(result).toBe(true); }); }); + + describe('select', () => { + const arrayOptions = { + options: ['one', 'two', 'three'], + }; + const optionsRequired = { + required: true, + options: [{ + value: 'one', + label: 'One', + }, { + value: 'two', + label: 'two', + }, { + value: 'three', + label: 'three', + }], + }; + const optionsWithEmptyString = { + options: [{ + value: '', + label: 'None', + }, { + value: 'option', + label: 'Option', + }], + }; + it('should allow valid input', () => { + const val = 'one'; + const result = select(val, arrayOptions); + expect(result).toStrictEqual(true); + }); + it('should prevent invalid input', () => { + const val = 'bad'; + const result = select(val, arrayOptions); + expect(result).not.toStrictEqual(true); + }); + it('should allow null input', () => { + const val = null; + const result = select(val, arrayOptions); + expect(result).toStrictEqual(true); + }); + it('should allow undefined input', () => { + let val; + const result = select(val, arrayOptions); + expect(result).toStrictEqual(true); + }); + it('should prevent empty string input', () => { + const val = ''; + const result = select(val, arrayOptions); + expect(result).not.toStrictEqual(true); + }); + it('should prevent undefined input with required', () => { + let val; + const result = select(val, optionsRequired); + expect(result).not.toStrictEqual(true); + }); + it('should prevent undefined input with required and hasMany', () => { + let val; + const result = select(val, { ...optionsRequired, hasMany: true }); + expect(result).not.toStrictEqual(true); + }); + it('should prevent empty array input with required and hasMany', () => { + const result = select([], { ...optionsRequired, hasMany: true }); + expect(result).not.toStrictEqual(true); + }); + it('should prevent empty string input with required', () => { + const result = select('', { ...optionsRequired }); + expect(result).not.toStrictEqual(true); + }); + it('should prevent empty string array input with required and hasMany', () => { + const result = select([''], { ...optionsRequired, hasMany: true }); + expect(result).not.toStrictEqual(true); + }); + it('should prevent null input with required and hasMany', () => { + const val = null; + const result = select(val, { ...optionsRequired, hasMany: true }); + expect(result).not.toStrictEqual(true); + }); + it('should allow valid input with option objects', () => { + const val = 'one'; + const result = select(val, optionsRequired); + expect(result).toStrictEqual(true); + }); + it('should prevent invalid input with option objects', () => { + const val = 'bad'; + const result = select(val, optionsRequired); + expect(result).not.toStrictEqual(true); + }); + it('should allow empty string input with option object', () => { + const val = ''; + const result = select(val, optionsWithEmptyString); + expect(result).toStrictEqual(true); + }); + it('should allow empty string input with option object and required', () => { + const val = ''; + const result = select(val, { ...optionsWithEmptyString, required: true }); + expect(result).toStrictEqual(true); + }); + it('should allow valid input with hasMany', () => { + const val = ['one', 'two']; + const result = select(val, arrayOptions); + expect(result).toStrictEqual(true); + }); + it('should prevent invalid input with hasMany', () => { + const val = ['one', 'bad']; + const result = select(val, arrayOptions); + expect(result).not.toStrictEqual(true); + }); + it('should allow valid input with hasMany option objects', () => { + const val = ['one', 'three']; + const result = select(val, { ...optionsRequired, hasMany: true }); + expect(result).toStrictEqual(true); + }); + it('should prevent invalid input with hasMany option objects', () => { + const val = ['three', 'bad']; + const result = select(val, { ...optionsRequired, hasMany: true }); + expect(result).not.toStrictEqual(true); + }); + }); }); diff --git a/src/fields/validations.ts b/src/fields/validations.ts index 9aa7a9598a1..06f1c7bc687 100644 --- a/src/fields/validations.ts +++ b/src/fields/validations.ts @@ -35,7 +35,7 @@ export const text: Validate = (value: string, options = {}) => { } if (options.required) { - if (typeof value !== 'string' || (typeof value === 'string' && value?.length === 0)) { + if (typeof value !== 'string' || value?.length === 0) { return defaultMessage; } } @@ -162,15 +162,17 @@ export const array: Validate = (value, options = {}) => { }; export const select: Validate = (value, options = {}) => { - if (Array.isArray(value) && value.find((input) => !options.options.find((option) => (option === input || option.value === input)))) { + if (Array.isArray(value) && value.some((input) => !options.options.some((option) => (option === input || option.value === input)))) { return 'This field has an invalid selection'; } - if (typeof value === 'string' && !options.options.find((option) => (option === value || option.value === value))) { + if (typeof value === 'string' && !options.options.some((option) => (option === value || option.value === value))) { return 'This field has an invalid selection'; } - if (options.required && !value) { + if (options.required && ( + (typeof value === 'undefined' || value === null) || (options.hasMany && Array.isArray(value) && (value as [])?.length === 0)) + ) { return defaultMessage; } diff --git a/src/graphql/schema/buildObjectType.ts b/src/graphql/schema/buildObjectType.ts index 746e9175bfa..067c5154c88 100644 --- a/src/graphql/schema/buildObjectType.ts +++ b/src/graphql/schema/buildObjectType.ts @@ -21,6 +21,7 @@ import withNullableType from './withNullableType'; import { BaseFields } from '../../collections/graphql/types'; import { toWords } from '../../utilities/formatLabels'; import createRichTextRelationshipPromise from '../../fields/richText/relationshipPromise'; +import formatOptions from '../utilities/formatOptions'; type LocaleInputType = { locale: { @@ -157,23 +158,7 @@ function buildObjectType(name: string, fields: Field[], parentName: string, base field, new GraphQLEnumType({ name: combineParentName(parentName, field.name), - values: field.options.reduce((values, option) => { - if (optionIsObject(option)) { - return { - ...values, - [formatName(option.value)]: { - value: option.value, - }, - }; - } - - return { - ...values, - [formatName(option)]: { - value: option, - }, - }; - }, {}), + values: formatOptions(field), }), ), }), @@ -183,27 +168,7 @@ function buildObjectType(name: string, fields: Field[], parentName: string, base let type: GraphQLType = new GraphQLEnumType({ name: fullName, - values: field.options.reduce((values, option) => { - if (typeof option === 'object' && option.value) { - return { - ...values, - [formatName(option.value)]: { - value: option.value, - }, - }; - } - - if (typeof option === 'string') { - return { - ...values, - [formatName(option)]: { - value: option, - }, - }; - } - - return values; - }, {}), + values: formatOptions(field), }); type = field.hasMany ? new GraphQLList(type) : type; diff --git a/src/graphql/utilities/formatName.ts b/src/graphql/utilities/formatName.ts index b7011f6b658..979b9bf9ccc 100644 --- a/src/graphql/utilities/formatName.ts +++ b/src/graphql/utilities/formatName.ts @@ -1,4 +1,4 @@ -const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; +const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const formatName = (string: string): string => { let sanitizedString = String(string); @@ -19,7 +19,7 @@ const formatName = (string: string): string => { .replace(/'/g, '_') .replace(/ /g, ''); - return formatted; + return formatted || '_'; }; export default formatName; diff --git a/src/graphql/utilities/formatOptions.ts b/src/graphql/utilities/formatOptions.ts new file mode 100644 index 00000000000..a532a3cc7b3 --- /dev/null +++ b/src/graphql/utilities/formatOptions.ts @@ -0,0 +1,25 @@ +import { optionIsObject, RadioField, SelectField } from '../../fields/config/types'; +import formatName from './formatName'; + +const formatOptions = (field: RadioField | SelectField) => { + return field.options.reduce((values, option) => { + if (optionIsObject(option)) { + return { + ...values, + [formatName(option.value)]: { + value: option.value, + }, + }; + } + + return { + ...values, + [formatName(option)]: { + value: option, + }, + }; + }, {}); +}; + + +export default formatOptions;
ec9196e33ca01e6a15097943b4be6dee6ea5202f
2022-12-26 22:43:11
Dan Ribbens
fix: select field crash on missing value option
false
select field crash on missing value option
fix
diff --git a/src/admin/components/forms/field-types/Select/Input.tsx b/src/admin/components/forms/field-types/Select/Input.tsx index ee9bf043371..b8b2e025a7d 100644 --- a/src/admin/components/forms/field-types/Select/Input.tsx +++ b/src/admin/components/forms/field-types/Select/Input.tsx @@ -65,15 +65,15 @@ const SelectInput: React.FC<SelectInputProps> = (props) => { valueToRender = value.map((val) => { const matchingOption = options.find((option) => option.value === val); return { - label: getTranslation(matchingOption.label, i18n), - value: matchingOption.value, + label: matchingOption ? getTranslation(matchingOption.label, i18n) : val, + value: matchingOption?.value ?? val, }; }); } else if (value) { const matchingOption = options.find((option) => option.value === value); valueToRender = { - label: getTranslation(matchingOption.label, i18n), - value: matchingOption.value, + label: matchingOption ? getTranslation(matchingOption.label, i18n) : value, + value: matchingOption?.value ?? value, }; }
686085496a5bb677361e72c5e6504ab232d9da66
2022-09-17 02:35:57
Dan Ribbens
chore(release): v1.1.3
false
v1.1.3
chore
diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fa74286c91..658b54b7f08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## [1.1.3](https://github.com/payloadcms/payload/compare/v1.1.2...v1.1.3) (2022-09-16) + + +### Bug Fixes + +* adjust prevPage and nextPage graphql typing ([#1140](https://github.com/payloadcms/payload/issues/1140)) ([b3bb421](https://github.com/payloadcms/payload/commit/b3bb421c6ca4176974488b3270384386a151560c)) +* duplicate with relationships ([eabb981](https://github.com/payloadcms/payload/commit/eabb981243e005facb5fff6d9222903d4704ca55)) + ## [1.1.2](https://github.com/payloadcms/payload/compare/v1.1.1...v1.1.2) (2022-09-14) diff --git a/package.json b/package.json index 85cf44a37f9..fbab8546e30 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "1.1.2", + "version": "1.1.3", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "MIT", "author": {
1aa257df4b460cdbc94c14b170f363e74faa0c56
2023-06-07 00:37:24
Jacob Fletcher
chore: uses discord vanity urls (#2786)
false
uses discord vanity urls (#2786)
chore
diff --git a/contributing.md b/contributing.md index 6d255d1e6bd..34d1aa0de01 100644 --- a/contributing.md +++ b/contributing.md @@ -22,7 +22,7 @@ If you're an incredibly awesome person and want to help us make Payload even bet ### Before Starting -To help us work on new features, you can create a new feature request post in [GitHub Discussion](https://github.com/payloadcms/payload/discussions) or discuss it in our [Discord](https://discord.com/invite/r6sCXqVk3v). New functionality often has large implications across the entire Payload repo, so it is best to discuss the architecture and approach before starting work on a pull request. +To help us work on new features, you can create a new feature request post in [GitHub Discussion](https://github.com/payloadcms/payload/discussions) or discuss it in our [Discord](https://discord.com/invite/payload). New functionality often has large implications across the entire Payload repo, so it is best to discuss the architecture and approach before starting work on a pull request. ### Code diff --git a/examples/auth/cms/README.md b/examples/auth/cms/README.md index 776c943ae9c..9e7f1ccf9d7 100644 --- a/examples/auth/cms/README.md +++ b/examples/auth/cms/README.md @@ -63,5 +63,5 @@ The easiest way to deploy your project is to use [Payload Cloud](https://payload ## Questions -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). +If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). diff --git a/examples/email/README.md b/examples/email/README.md index a710dc14611..41efa2a44ed 100644 --- a/examples/email/README.md +++ b/examples/email/README.md @@ -60,4 +60,4 @@ For more information on integrating email, check out these resources: ## Questions -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). +If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). diff --git a/examples/form-builder/cms/README.md b/examples/form-builder/cms/README.md index 8da97f3b4be..3da52fa67e3 100644 --- a/examples/form-builder/cms/README.md +++ b/examples/form-builder/cms/README.md @@ -44,5 +44,5 @@ The easiest way to deploy your project is to use [Payload Cloud](https://payload ## Questions -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). +If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). diff --git a/examples/multi-tenant/README.md b/examples/multi-tenant/README.md index 29562cdb9a4..082d5625ad2 100644 --- a/examples/multi-tenant/README.md +++ b/examples/multi-tenant/README.md @@ -129,4 +129,4 @@ The easiest way to deploy your project is to use [Payload Cloud](https://payload ## Questions -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). +If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). diff --git a/examples/preview/cms/README.md b/examples/preview/cms/README.md index 4123d1d7bdc..867a4c4d1b9 100644 --- a/examples/preview/cms/README.md +++ b/examples/preview/cms/README.md @@ -67,4 +67,4 @@ The easiest way to deploy your project is to use [Payload Cloud](https://payload ## Questions -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). +If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). diff --git a/examples/redirects/cms/README.md b/examples/redirects/cms/README.md index 7bece6011fe..5c00f6654ef 100644 --- a/examples/redirects/cms/README.md +++ b/examples/redirects/cms/README.md @@ -48,4 +48,4 @@ The easiest way to deploy your project is to use [Payload Cloud](https://payload ## Questions -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). +If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). diff --git a/examples/virtual-fields/README.md b/examples/virtual-fields/README.md index 14bbf857817..c8a345db217 100644 --- a/examples/virtual-fields/README.md +++ b/examples/virtual-fields/README.md @@ -77,4 +77,4 @@ The easiest way to deploy your project is to use [Payload Cloud](https://payload ## Questions -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). +If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). diff --git a/examples/whitelabel/README.md b/examples/whitelabel/README.md index b1779c694e7..9a81dbcc73b 100644 --- a/examples/whitelabel/README.md +++ b/examples/whitelabel/README.md @@ -52,4 +52,4 @@ The easiest way to deploy your project is to use [Payload Cloud](https://payload ## Questions -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). +If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions).
ed5da473b5faf70143c91afc3ba4219ff135071c
2023-10-25 02:11:24
dependabot[bot]
chore(deps): bump next in /examples/redirects/next-pages (#3850)
false
bump next in /examples/redirects/next-pages (#3850)
chore
diff --git a/examples/redirects/next-pages/package.json b/examples/redirects/next-pages/package.json index ccdfa279216..b139868c430 100644 --- a/examples/redirects/next-pages/package.json +++ b/examples/redirects/next-pages/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "escape-html": "^1.0.3", - "next": "^13.1.6", + "next": "^13.5.0", "react": "18.2.0", "react-dom": "18.2.0", "sass": "^1.55.0", diff --git a/examples/redirects/next-pages/yarn.lock b/examples/redirects/next-pages/yarn.lock index 398ca34a089..2cff584c24f 100644 --- a/examples/redirects/next-pages/yarn.lock +++ b/examples/redirects/next-pages/yarn.lock @@ -36,10 +36,10 @@ resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz#b520529ec21d8e5945a1851dfd1c32e94e39ff45" integrity sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA== -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/env/-/env-13.2.1.tgz#082d42cfc0c794e9185d7b4133d71440ba2e795d" - integrity sha512-Hq+6QZ6kgmloCg8Kgrix+4F0HtvLqVK3FZAnlAoS0eonaDemHe1Km4kwjSWRE3JNpJNcKxFHF+jsZrYo0SxWoQ== +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/env/-/env-13.5.0.tgz#a61dee2f29b09985847eabcc4c8a815031267a36" + integrity sha512-mxhf/BskjPURT+qEjNP7wBvqre2q6OXEIbydF8BrH+duSSJQnB4/vzzuJDoahYwTXiUaXpouAnMWHZdG0HU62g== "@next/eslint-plugin-next@^13.1.6": version "13.2.1" @@ -48,70 +48,50 @@ dependencies: glob "7.1.7" -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-android-arm-eabi/-/swc-android-arm-eabi-13.2.1.tgz#67f2580fbbe05ee006220688972c5e3a555fc741" - integrity sha512-Yua7mUpEd1wzIT6Jjl3dpRizIfGp9NR4F2xeRuQv+ae+SDI1Em2WyM9m46UL+oeW5GpMiEHoaBagr47RScZFmQ== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-android-arm64/-/swc-android-arm64-13.2.1.tgz#460a02b69eb23bb5f402266bcea9cadae59415c1" - integrity sha512-Bifcr2f6VwInOdq1uH/9lp8fH7Nf7XGkIx4XceVd32LPJqG2c6FZU8ZRBvTdhxzXVpt5TPtuXhOP4Ij9UPqsVw== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-13.2.1.tgz#8b8530ff417802027471aee2419f78a58a863ccb" - integrity sha512-gvqm+fGMYxAkwBapH0Vvng5yrb6HTkIvZfY4oEdwwYrwuLdkjqnJygCMgpNqIFmAHSXgtlWxfYv1VC8sjN81Kw== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-13.2.1.tgz#80aebb3329a1e4568a28de1ee177780b3d50330c" - integrity sha512-HGqVqmaZWj6zomqOZUVbO5NhlABL0iIaxTmd0O5B0MoMa5zpDGoaHSG+fxgcWMXcGcxmUNchv1NfNOYiTKoHOg== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-freebsd-x64/-/swc-freebsd-x64-13.2.1.tgz#250ea2ab7e1734f22d11c677c463fab9ac33a516" - integrity sha512-N/a4JarAq+E+g+9K2ywJUmDIgU2xs2nA+BBldH0oq4zYJMRiUhL0iaN9G4e72VmGOJ61L/3W6VN8RIUOwTLoqQ== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm-gnueabihf/-/swc-linux-arm-gnueabihf-13.2.1.tgz#fe6bb29ed348a5f8ecae3740df22a8d8130c474a" - integrity sha512-WaFoerF/eRbhbE57TaIGJXbQAERADZ/RZ45u6qox9beb5xnWsyYgzX+WuN7Tkhyvga0/aMuVYFzS9CEay7D+bw== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-13.2.1.tgz#4781b927fc5e421f3cea2b29e5d38e5e4837b198" - integrity sha512-R+Jhc1/RJTnncE9fkePboHDNOCm1WJ8daanWbjKhfPySMyeniKYRwGn5SLYW3S8YlRS0QVdZaaszDSZWgUcsmA== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-13.2.1.tgz#c2ba0a121b0255ba62450916bc70e6d0e26cbc98" - integrity sha512-oI1UfZPidGAVddlL2eOTmfsuKV9EaT1aktIzVIxIAgxzQSdwsV371gU3G55ggkurzfdlgF3GThFePDWF0d8dmw== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-13.2.1.tgz#573c220f8b087e5d131d1fba58d3e1a670b220ad" - integrity sha512-PCygPwrQmS+7WUuAWWioWMZCzZm4PG91lfRxToLDg7yIm/3YfAw5N2EK2TaM9pzlWdvHQAqRMX/oLvv027xUiA== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-13.2.1.tgz#950b5bb920b322ca7b447efbd12a9c7a10c3a642" - integrity sha512-sUAKxo7CFZYGHNxheGh9nIBElLYBM6md/liEGfOTwh/xna4/GTTcmkGWkF7PdnvaYNgcPIQgHIMYiAa6yBKAVw== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-13.2.1.tgz#dbff3c4f5a3812a7059dac05804148a0f98682db" - integrity sha512-qDmyEjDBpl/vBXxuOOKKWmPQOcARcZIMach1s7kjzaien0SySut/PHRlj56sosa81Wt4hTGhfhZ1R7g1n7+B8w== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-13.2.1.tgz#7d2c17be7b8d9963984f5c15cc2588127101f620" - integrity sha512-2joqFQ81ZYPg6DcikIzQn3DgjKglNhPAozx6dL5sCNkr1CPMD0YIkJgT3CnYyMHQ04Qi3Npv0XX3MD6LJO8OCA== - -"@next/[email protected]": - version "13.2.1" - resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-13.2.1.tgz#09713c6a925461f414e89422851326d1625bd4d2" - integrity sha512-r3+0fSaIZT6N237iMzwUhfNwjhAFvXjqB+4iuW+wcpxW+LHm1g/IoxN8eSRcb8jPItC86JxjAxpke0QL97qd6g== +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-13.5.0.tgz#45ea191e13593088572d0048d4ddfc1fcdb3c8ed" + integrity sha512-DavPD8oRjSoCRJana5DCAWdRZ4nbS7/pPw13DlnukFfMPJUk5hCAC3+NbqEyekS/X1IBFdZWSV2lJIdzTn4s6w== + +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-13.5.0.tgz#582e8df7d563c057581bc118fff1cea79391d6e7" + integrity sha512-s5QSKKB0CTKFWp3CNMC5GH1YOipH1Jjr5P3w+RQTC4Aybo6xPqeWp/UyDW0fxmLRq0e1zgnOMgDQRdxAkoThrw== + +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-13.5.0.tgz#7ee0a43b6635eca1e80a887304b7bfe31254a4a6" + integrity sha512-E0fCKA8F2vfgZWwcv4iq642No75EiACSNUBNGvc5lx/ylqAUdNwE/9+x2SHv+LPUXFhZ6hZLR0Qox/oKgZqFlg== + +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-13.5.0.tgz#99a1efd6b68a4d0dfdc24b81f14cd8b8251425a9" + integrity sha512-jG/blDDLndFRUcafCQO4TOI3VuoIZh3jQriZ7JaVCgAEZe0D1EUrxKdbBarZ74isutHZ6DpNGRDi/0OHFZpJAA== + +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-13.5.0.tgz#7c85acd45879a20d8fb102b3212e792924d02e93" + integrity sha512-6JWR7U41uNL6HGwNbGg3Oedt+FN4YuA126sHWKTq3ic5kkhEusIIdVo7+WcswVJl8nTMB1yT3gEPwygQbVYVUA== + +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-13.5.0.tgz#23aad9ab7621f53bb947b727e659d85e74b0e31a" + integrity sha512-uY+wrYfD5QUossqznwidOpJYmmcBwojToZx55shihtbTl6afVYzOxsUbRXLdWmZAa36ckxXpqkvuFNS8icQuug== + +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-13.5.0.tgz#5a45686335e5f54342faf9d9ed25f55a4107ce7f" + integrity sha512-lWZ5vJTULxTOdLcRmrllNgAdDRSDwk8oqJMyDxpqS691NG5uhle9ZwRj3g1F1/vHNkDa+B7PmWhQgG0nmlbKZg== + +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-13.5.0.tgz#b9990965762aaa109bdeb7b49cbdc7e4af7f9014" + integrity sha512-jirQXnVCU9hi3cHzgd33d4qSBXn1/0gUT/KtXqy9Ux9OTcIcjJT3TcAzoLJLTdhRg7op3MZoSnuFeWl8kmGGNw== + +"@next/[email protected]": + version "13.5.0" + resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-13.5.0.tgz#4385c5d9c0db39c2623aed566b3ec7fedaf6f190" + integrity sha512-Q8QYLyWcMMUp3DohI04VyJbLNCfFMNTxYNhujvJD2lowuqnqApUBP2DxI/jCZRMFWgKi76n5u8UboLVeYXn6jA== "@nodelib/[email protected]": version "2.1.5" @@ -139,10 +119,10 @@ resolved "https://registry.yarnpkg.com/@payloadcms/eslint-config/-/eslint-config-0.0.1.tgz#4324702ddef6c773b3f3033795a13e6b50c95a92" integrity sha512-Il59+0C4E/bI6uM2hont3I+oABWkJZbfbItubje5SGMrXkymUq8jT/UZRk0eCt918bB7gihxDXx8guFnR/aNIw== -"@swc/[email protected]": - version "0.4.14" - resolved "https://registry.yarnpkg.com/@swc/helpers/-/helpers-0.4.14.tgz#1352ac6d95e3617ccb7c1498ff019654f1e12a74" - integrity sha512-4C7nX/dvpzB7za4Ql9K81xK3HPxCpHMgwTZVyf+9JQ6VUbn9jjZVN7/Nkdz/Ugzs2CSjqnL/UPXroiVBVHUWUw== +"@swc/[email protected]": + version "0.5.2" + resolved "https://registry.yarnpkg.com/@swc/helpers/-/helpers-0.5.2.tgz#85ea0c76450b61ad7d10a37050289eded783c27d" + integrity sha512-E4KcWTpoLHqwPHLxidpOqQbcrZVgi0rsmmZXUle1jXmJfuIf/UWpczUJ7MZZ5tlxytgJXyp0w4PGkkeLiuIdZw== dependencies: tslib "^2.4.0" @@ -370,6 +350,13 @@ braces@^3.0.2, braces@~3.0.2: dependencies: fill-range "^7.0.1" [email protected]: + version "1.6.0" + resolved "https://registry.yarnpkg.com/busboy/-/busboy-1.6.0.tgz#966ea36a9502e43cdb9146962523b92f531f6893" + integrity sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA== + dependencies: + streamsearch "^1.1.0" + call-bind@^1.0.0, call-bind@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c" @@ -899,6 +886,11 @@ glob-parent@^6.0.1: dependencies: is-glob "^4.0.3" +glob-to-regexp@^0.4.1: + version "0.4.1" + resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" + integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw== + [email protected]: version "7.1.7" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.7.tgz#3b193e9233f01d42d0b3f78294bbeeb418f94a90" @@ -956,6 +948,11 @@ gopd@^1.0.1: dependencies: get-intrinsic "^1.1.3" +graceful-fs@^4.1.2: + version "4.2.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" + integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== + grapheme-splitter@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz#9cf3a665c6247479896834af35cf1dbb4400767e" @@ -1331,30 +1328,29 @@ natural-compare@^1.4.0: resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== -next@^13.1.6: - version "13.2.1" - resolved "https://registry.yarnpkg.com/next/-/next-13.2.1.tgz#34d823f518632b36379863228ed9f861c335b9c0" - integrity sha512-qhgJlDtG0xidNViJUPeQHLGJJoT4zDj/El7fP3D3OzpxJDUfxsm16cK4WTMyvSX1ciIfAq05u+0HqFAa+VJ+Hg== +next@^13.5.0: + version "13.5.0" + resolved "https://registry.yarnpkg.com/next/-/next-13.5.0.tgz#3a3ce5b8c89c4fff9c6f0b2452bcb03f63d8c84c" + integrity sha512-mhguN5JPZXhhrD/nNcezXgKoxN8GT8xZvvGhUQV2ETiaNm+KHRWT1rCbrF5FlbG2XCcLRKOmOe3D5YQgXmJrDQ== dependencies: - "@next/env" "13.2.1" - "@swc/helpers" "0.4.14" + "@next/env" "13.5.0" + "@swc/helpers" "0.5.2" + busboy "1.6.0" caniuse-lite "^1.0.30001406" postcss "8.4.14" styled-jsx "5.1.1" + watchpack "2.4.0" + zod "3.21.4" optionalDependencies: - "@next/swc-android-arm-eabi" "13.2.1" - "@next/swc-android-arm64" "13.2.1" - "@next/swc-darwin-arm64" "13.2.1" - "@next/swc-darwin-x64" "13.2.1" - "@next/swc-freebsd-x64" "13.2.1" - "@next/swc-linux-arm-gnueabihf" "13.2.1" - "@next/swc-linux-arm64-gnu" "13.2.1" - "@next/swc-linux-arm64-musl" "13.2.1" - "@next/swc-linux-x64-gnu" "13.2.1" - "@next/swc-linux-x64-musl" "13.2.1" - "@next/swc-win32-arm64-msvc" "13.2.1" - "@next/swc-win32-ia32-msvc" "13.2.1" - "@next/swc-win32-x64-msvc" "13.2.1" + "@next/swc-darwin-arm64" "13.5.0" + "@next/swc-darwin-x64" "13.5.0" + "@next/swc-linux-arm64-gnu" "13.5.0" + "@next/swc-linux-arm64-musl" "13.5.0" + "@next/swc-linux-x64-gnu" "13.5.0" + "@next/swc-linux-x64-musl" "13.5.0" + "@next/swc-win32-arm64-msvc" "13.5.0" + "@next/swc-win32-ia32-msvc" "13.5.0" + "@next/swc-win32-x64-msvc" "13.5.0" normalize-path@^3.0.0, normalize-path@~3.0.0: version "3.0.0" @@ -1642,6 +1638,11 @@ slate@^0.84.0: resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.0.2.tgz#adbc361d9c62df380125e7f161f71c826f1e490c" integrity sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw== +streamsearch@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/streamsearch/-/streamsearch-1.1.0.tgz#404dd1e2247ca94af554e841a8ef0eaa238da764" + integrity sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg== + string.prototype.trimend@^1.0.6: version "1.0.6" resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.6.tgz#c4a27fa026d979d79c04f17397f250a462944533" @@ -1783,6 +1784,14 @@ uri-js@^4.2.2: dependencies: punycode "^2.1.0" [email protected]: + version "2.4.0" + resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.0.tgz#fa33032374962c78113f93c7f2fb4c54c9862a5d" + integrity sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg== + dependencies: + glob-to-regexp "^0.4.1" + graceful-fs "^4.1.2" + which-boxed-primitive@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz#13757bc89b209b049fe5d86430e21cf40a89a8e6" @@ -1832,3 +1841,8 @@ yocto-queue@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== + [email protected]: + version "3.21.4" + resolved "https://registry.yarnpkg.com/zod/-/zod-3.21.4.tgz#10882231d992519f0a10b5dd58a38c9dabbb64db" + integrity sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw==
7b263be01bc1d7bd68d063980dfa784324bac217
2024-04-21 00:27:22
Paul
chore: add missing translations (#5929)
false
add missing translations (#5929)
chore
diff --git a/packages/next/src/routes/rest/auth/forgotPassword.ts b/packages/next/src/routes/rest/auth/forgotPassword.ts index eeeae27a54d..660790da76b 100644 --- a/packages/next/src/routes/rest/auth/forgotPassword.ts +++ b/packages/next/src/routes/rest/auth/forgotPassword.ts @@ -4,6 +4,7 @@ import { forgotPasswordOperation } from 'payload/operations' import type { CollectionRouteHandler } from '../types.js' export const forgotPassword: CollectionRouteHandler = async ({ collection, req }) => { + const { t } = req await forgotPasswordOperation({ collection, data: { @@ -16,8 +17,7 @@ export const forgotPassword: CollectionRouteHandler = async ({ collection, req } return Response.json( { - // TODO(translate) - message: 'Success', + message: t('general:success'), }, { status: httpStatus.OK, diff --git a/packages/next/src/routes/rest/auth/login.ts b/packages/next/src/routes/rest/auth/login.ts index bf987b15c40..4c84d081590 100644 --- a/packages/next/src/routes/rest/auth/login.ts +++ b/packages/next/src/routes/rest/auth/login.ts @@ -6,7 +6,7 @@ import { isNumber } from 'payload/utilities' import type { CollectionRouteHandler } from '../types.js' export const login: CollectionRouteHandler = async ({ collection, req }) => { - const { searchParams } = req + const { searchParams, t } = req const depth = searchParams.get('depth') const result = await loginOperation({ @@ -31,8 +31,7 @@ export const login: CollectionRouteHandler = async ({ collection, req }) => { return Response.json( { - // TODO(translate) - message: 'Auth Passed', + message: t('authentication:passed'), ...result, }, { diff --git a/packages/next/src/routes/rest/auth/logout.ts b/packages/next/src/routes/rest/auth/logout.ts index 0f9168daf8c..5742f59a083 100644 --- a/packages/next/src/routes/rest/auth/logout.ts +++ b/packages/next/src/routes/rest/auth/logout.ts @@ -5,6 +5,7 @@ import { logoutOperation } from 'payload/operations' import type { CollectionRouteHandler } from '../types.js' export const logout: CollectionRouteHandler = async ({ collection, req }) => { + const { t } = req const result = await logoutOperation({ collection, req, @@ -13,7 +14,7 @@ export const logout: CollectionRouteHandler = async ({ collection, req }) => { if (!result) { return Response.json( { - message: 'Logout failed.', + message: t('error:logoutFailed'), }, { status: httpStatus.BAD_REQUEST, @@ -28,8 +29,7 @@ export const logout: CollectionRouteHandler = async ({ collection, req }) => { return Response.json( { - // TODO(translate) - message: 'Logout successful.', + message: t('authentication:logoutSuccessful'), }, { headers: new Headers({ diff --git a/packages/next/src/routes/rest/auth/refresh.ts b/packages/next/src/routes/rest/auth/refresh.ts index 2f1fe634bf6..1effc88d075 100644 --- a/packages/next/src/routes/rest/auth/refresh.ts +++ b/packages/next/src/routes/rest/auth/refresh.ts @@ -6,13 +6,13 @@ import { refreshOperation } from 'payload/operations' import type { CollectionRouteHandler } from '../types.js' export const refresh: CollectionRouteHandler = async ({ collection, req }) => { + const { t } = req const token = typeof req.data?.token === 'string' ? req.data.token : extractJWT(req) if (!token) { return Response.json( { - // TODO(translate) - message: 'Token not provided.', + message: t('error:tokenNotProvided'), }, { status: httpStatus.UNAUTHORIZED, @@ -38,8 +38,7 @@ export const refresh: CollectionRouteHandler = async ({ collection, req }) => { return Response.json( { - // TODO(translate) - message: 'Token refresh successful', + message: t('authentication:tokenRefreshSuccessful'), ...result, }, { diff --git a/packages/next/src/routes/rest/auth/registerFirstUser.ts b/packages/next/src/routes/rest/auth/registerFirstUser.ts index 44c20760446..abb714f918c 100644 --- a/packages/next/src/routes/rest/auth/registerFirstUser.ts +++ b/packages/next/src/routes/rest/auth/registerFirstUser.ts @@ -6,7 +6,7 @@ import { registerFirstUserOperation } from 'payload/operations' import type { CollectionRouteHandler } from '../types.js' export const registerFirstUser: CollectionRouteHandler = async ({ collection, req }) => { - const data = req.data + const { data, t } = req if (data?.password !== data['confirm-password']) { throw new ValidationError([ @@ -36,8 +36,7 @@ export const registerFirstUser: CollectionRouteHandler = async ({ collection, re return Response.json( { exp: result.exp, - // TODO(translate) - message: 'Successfully registered first user.', + message: t('authentication:successfullyRegisteredFirstUser'), token: result.token, user: result.user, }, diff --git a/packages/next/src/routes/rest/auth/resetPassword.ts b/packages/next/src/routes/rest/auth/resetPassword.ts index a69ee22cf4a..4a9a5dfabb3 100644 --- a/packages/next/src/routes/rest/auth/resetPassword.ts +++ b/packages/next/src/routes/rest/auth/resetPassword.ts @@ -5,7 +5,7 @@ import { resetPasswordOperation } from 'payload/operations' import type { CollectionRouteHandler } from '../types.js' export const resetPassword: CollectionRouteHandler = async ({ collection, req }) => { - const { searchParams } = req + const { searchParams, t } = req const depth = searchParams.get('depth') const result = await resetPasswordOperation({ @@ -30,8 +30,7 @@ export const resetPassword: CollectionRouteHandler = async ({ collection, req }) return Response.json( { - // TODO(translate) - message: 'Password reset successfully.', + message: t('authentication:passwordResetSuccessfully'), ...result, }, { diff --git a/packages/next/src/routes/rest/auth/unlock.ts b/packages/next/src/routes/rest/auth/unlock.ts index 00b2d9c9761..c81a77f94cf 100644 --- a/packages/next/src/routes/rest/auth/unlock.ts +++ b/packages/next/src/routes/rest/auth/unlock.ts @@ -4,6 +4,8 @@ import { unlockOperation } from 'payload/operations' import type { CollectionRouteHandler } from '../types.js' export const unlock: CollectionRouteHandler = async ({ collection, req }) => { + const { t } = req + await unlockOperation({ collection, data: { email: req.data.email as string }, @@ -12,8 +14,7 @@ export const unlock: CollectionRouteHandler = async ({ collection, req }) => { return Response.json( { - // TODO(translate) - message: 'Success', + message: t('general:success'), }, { status: httpStatus.OK, diff --git a/packages/next/src/routes/rest/auth/verifyEmail.ts b/packages/next/src/routes/rest/auth/verifyEmail.ts index 99d8f956642..f2a49774061 100644 --- a/packages/next/src/routes/rest/auth/verifyEmail.ts +++ b/packages/next/src/routes/rest/auth/verifyEmail.ts @@ -4,6 +4,7 @@ import { verifyEmailOperation } from 'payload/operations' import type { CollectionRouteHandlerWithID } from '../types.js' export const verifyEmail: CollectionRouteHandlerWithID = async ({ id, collection, req }) => { + const { t } = req await verifyEmailOperation({ collection, req, @@ -12,8 +13,7 @@ export const verifyEmail: CollectionRouteHandlerWithID = async ({ id, collection return Response.json( { - // TODO(translate) - message: 'Email verified successfully.', + message: t('authentication:emailVerified'), }, { status: httpStatus.OK, diff --git a/packages/next/src/views/LivePreview/Toolbar/Controls/index.tsx b/packages/next/src/views/LivePreview/Toolbar/Controls/index.tsx index 9c9da963b3b..673365a82da 100644 --- a/packages/next/src/views/LivePreview/Toolbar/Controls/index.tsx +++ b/packages/next/src/views/LivePreview/Toolbar/Controls/index.tsx @@ -6,6 +6,7 @@ import { Popup, PopupList } from '@payloadcms/ui/elements/Popup' import { Chevron } from '@payloadcms/ui/icons/Chevron' import { LinkIcon } from '@payloadcms/ui/icons/Link' import { X } from '@payloadcms/ui/icons/X' +import { useTranslation } from '@payloadcms/ui/providers/Translation' import React from 'react' import { useLivePreviewContext } from '../../Context/context.js' @@ -14,14 +15,16 @@ import './index.scss' const baseClass = 'live-preview-toolbar-controls' const zoomOptions = [50, 75, 100, 125, 150, 200] -const customOption = { - label: 'Custom', // TODO: Add i18n to this string - value: 'custom', -} export const ToolbarControls: React.FC<EditViewProps> = () => { const { breakpoint, breakpoints, setBreakpoint, setPreviewWindowType, setZoom, url, zoom } = useLivePreviewContext() + const { t } = useTranslation() + + const customOption = { + label: t('general:custom'), + value: 'custom', + } return ( <div className={baseClass}> diff --git a/packages/next/src/views/Logout/LogoutClient.tsx b/packages/next/src/views/Logout/LogoutClient.tsx index 9fabdd42ed1..ec792bfce9a 100644 --- a/packages/next/src/views/Logout/LogoutClient.tsx +++ b/packages/next/src/views/Logout/LogoutClient.tsx @@ -44,6 +44,5 @@ export const LogoutClient: React.FC<{ ) } - // TODO(i18n): needs translation in all languages - return <Fragment>Logging Out...</Fragment> + return <Fragment>{t('authentication:loggingOut')}</Fragment> } diff --git a/packages/richtext-slate/src/data/validation.ts b/packages/richtext-slate/src/data/validation.ts index bae493178dc..ebf7a49012f 100644 --- a/packages/richtext-slate/src/data/validation.ts +++ b/packages/richtext-slate/src/data/validation.ts @@ -9,12 +9,12 @@ export const richTextValidate: Validate< unknown, RichTextField<any[], AdapterArguments>, RichTextField<any[], AdapterArguments> -> = (value, { required }) => { +> = (value, { req, required }) => { + const { t } = req if (required) { const stringifiedDefaultValue = JSON.stringify(defaultRichTextValue) if (value && JSON.stringify(value) !== stringifiedDefaultValue) return true - // TODO: translate this string - return 'This field is required.' + return t('validation:required') } return true diff --git a/packages/translations/src/clientKeys.ts b/packages/translations/src/clientKeys.ts index 9a13f38c384..37d8e8e88bf 100644 --- a/packages/translations/src/clientKeys.ts +++ b/packages/translations/src/clientKeys.ts @@ -12,6 +12,7 @@ export const clientTranslationKeys = [ 'authentication:createFirstUser', 'authentication:emailNotValid', 'authentication:emailSent', + 'authentication:emailVerified', 'authentication:enableAPIKey', 'authentication:failedToUnlock', 'authentication:forceUnlock', @@ -23,16 +24,22 @@ export const clientTranslationKeys = [ 'authentication:logBackIn', 'authentication:loggedOutInactivity', 'authentication:loggedOutSuccessfully', + 'authentication:loggingOut', 'authentication:login', 'authentication:logOut', 'authentication:logout', 'authentication:logoutUser', + 'authentication:logoutSuccessful', 'authentication:newAPIKeyGenerated', 'authentication:newPassword', + 'authentication:passed', + 'authentication:passwordResetSuccessfully', 'authentication:resetPassword', 'authentication:stayLoggedIn', + 'authentication:successfullyRegisteredFirstUser', 'authentication:successfullyUnlocked', 'authentication:unableToVerify', + 'authentication:tokenRefreshSuccessful', 'authentication:verified', 'authentication:verifiedSuccessfully', 'authentication:verify', @@ -43,6 +50,7 @@ export const clientTranslationKeys = [ 'error:correctInvalidFields', 'error:deletingTitle', 'error:loadingDocument', + 'error:logoutFailed', 'error:noMatchedField', 'error:notAllowedToAccessPage', 'error:previewing', @@ -51,6 +59,7 @@ export const clientTranslationKeys = [ 'error:unauthorized', 'error:unknown', 'error:unspecific', + 'error:tokenNotProvided', 'fields:addLabel', 'fields:addLink', @@ -113,6 +122,7 @@ export const clientTranslationKeys = [ 'general:createNewLabel', 'general:creating', 'general:creatingNewLabel', + 'general:custom', 'general:dark', 'general:dashboard', 'general:delete', @@ -182,6 +192,7 @@ export const clientTranslationKeys = [ 'general:stayOnThisPage', 'general:submissionSuccessful', 'general:submit', + 'general:success', 'general:successfullyCreated', 'general:successfullyDeleted', 'general:thisLanguage', diff --git a/packages/translations/src/languages/en.ts b/packages/translations/src/languages/en.ts index 49f29c81e16..5d98f298276 100644 --- a/packages/translations/src/languages/en.ts +++ b/packages/translations/src/languages/en.ts @@ -19,6 +19,7 @@ export const en: Language = { createFirstUser: 'Create first user', emailNotValid: 'The email provided is not valid', emailSent: 'Email Sent', + emailVerified: 'Email verified successfully.', enableAPIKey: 'Enable API Key', failedToUnlock: 'Failed to unlock', forceUnlock: 'Force Unlock', @@ -38,22 +39,28 @@ export const en: Language = { 'To change your password, go to your <0>account</0> and edit your password there.', loggedOutInactivity: 'You have been logged out due to inactivity.', loggedOutSuccessfully: 'You have been logged out successfully.', + loggingOut: 'Logging out...', login: 'Login', loginAttempts: 'Login Attempts', loginUser: 'Login user', loginWithAnotherUser: 'To log in with another user, you should <0>log out</0> first.', logout: 'Logout', + logoutSuccessful: 'Logout successful.', logoutUser: 'Logout user', newAPIKeyGenerated: 'New API Key Generated.', newAccountCreated: 'A new account has just been created for you to access <a href="{{serverURL}}">{{serverURL}}</a> Please click on the following link or paste the URL below into your browser to verify your email: <a href="{{verificationURL}}">{{verificationURL}}</a><br> After verifying your email, you will be able to log in successfully.', newPassword: 'New Password', + passed: 'Authentication Passed', + passwordResetSuccessfully: 'Password reset successfully.', resetPassword: 'Reset Password', resetPasswordExpiration: 'Reset Password Expiration', resetPasswordToken: 'Reset Password Token', resetYourPassword: 'Reset Your Password', stayLoggedIn: 'Stay logged in', + successfullyRegisteredFirstUser: 'Successfully registered first user.', successfullyUnlocked: 'Successfully unlocked', + tokenRefreshSuccessful: 'Token refresh successful.', unableToVerify: 'Unable to Verify', verified: 'Verified', verifiedSuccessfully: 'Verified Successfully', @@ -83,6 +90,7 @@ export const en: Language = { loadingDocument: 'There was a problem loading the document with ID of {{id}}.', localesNotSaved_one: 'The following locale could not be saved:', localesNotSaved_other: 'The following locales could not be saved:', + logoutFailed: 'Logout failed.', missingEmail: 'Missing email.', missingIDOfDocument: 'Missing ID of document to update.', missingIDOfVersion: 'Missing ID of version.', @@ -96,6 +104,7 @@ export const en: Language = { previewing: 'There was a problem previewing this document.', problemUploadingFile: 'There was a problem while uploading the file.', tokenInvalidOrExpired: 'Token is either invalid or has expired.', + tokenNotProvided: 'Token not provided.', unPublishingDocument: 'There was a problem while un-publishing this document.', unableToDeleteCount: 'Unable to delete {{count}} out of {{total}} {{label}}.', unableToUpdateCount: 'Unable to update {{count}} out of {{total}} {{label}}.', @@ -185,6 +194,7 @@ export const en: Language = { createdAt: 'Created At', creating: 'Creating', creatingNewLabel: 'Creating new {{label}}', + custom: 'Custom', dark: 'Dark', dashboard: 'Dashboard', delete: 'Delete', @@ -261,6 +271,7 @@ export const en: Language = { stayOnThisPage: 'Stay on this page', submissionSuccessful: 'Submission Successful.', submit: 'Submit', + success: 'Success', successfullyCreated: '{{label}} successfully created.', successfullyDuplicated: '{{label}} successfully duplicated.', thisLanguage: 'English',
08b3e8f18f0aa620d537f3258b2e080600e0f43e
2022-02-20 22:52:42
James
fix: ensures empty hasMany relationships save as empty arrays
false
ensures empty hasMany relationships save as empty arrays
fix
diff --git a/src/admin/components/forms/field-types/Relationship/createRelationMap.ts b/src/admin/components/forms/field-types/Relationship/createRelationMap.ts index 03020867477..adabd837634 100644 --- a/src/admin/components/forms/field-types/Relationship/createRelationMap.ts +++ b/src/admin/components/forms/field-types/Relationship/createRelationMap.ts @@ -27,12 +27,12 @@ export const createRelationMap: CreateRelationMap = ({ } }; - if (hasMany) { - (value as Value[] || []).forEach((val, i) => { + if (hasMany && Array.isArray(value)) { + value.forEach((val) => { if (hasMultipleRelations) { - add(value[i].relationTo, value[i].value); + add(val.relationTo, val.value); } else { - add(relationTo, value[i]); + add(relationTo, val); } }); } else if (hasMultipleRelations) { diff --git a/src/fields/traverseFields.ts b/src/fields/traverseFields.ts index 9c2d96d0a84..8221f0c491d 100644 --- a/src/fields/traverseFields.ts +++ b/src/fields/traverseFields.ts @@ -106,7 +106,8 @@ const traverseFields = (args: Arguments): void => { } } - if (field.type === 'relationship' && field.hasMany && (data[field.name] === '' || data[field.name] === 'none' || data[field.name] === 'null')) { + // if (field.type === 'relationship' && field.hasMany && (data[field.name] === '' || data[field.name] === 'none' || data[field.name] === 'null')) { + if (field.type === 'relationship' && field.hasMany && (data[field.name] === '' || data[field.name] === 'none' || data[field.name] === 'null' || data[field.name] === null)) { dataCopy[field.name] = []; }
b06ca700be36cc3a945f81e3fa23ebb53d06ca23
2023-01-15 20:11:54
James
fix: #1877, #1867 - mimeTypes and imageSizes no longer cause error in admin ui
false
#1877, #1867 - mimeTypes and imageSizes no longer cause error in admin ui
fix
diff --git a/src/admin/components/forms/Form/buildStateFromSchema/addFieldStatePromise.ts b/src/admin/components/forms/Form/buildStateFromSchema/addFieldStatePromise.ts index b1572d9d266..dfc96a1c04f 100644 --- a/src/admin/components/forms/Form/buildStateFromSchema/addFieldStatePromise.ts +++ b/src/admin/components/forms/Form/buildStateFromSchema/addFieldStatePromise.ts @@ -191,7 +191,7 @@ export const addFieldStatePromise = async ({ id, operation, fields: field.fields, - data: data?.[field.name], + data: data?.[field.name] || {}, fullData, parentPassesCondition: passesCondition, path: `${path}${field.name}.`, diff --git a/test/uploads/config.ts b/test/uploads/config.ts index 93cc7ce21b6..c4a9f1c0b76 100644 --- a/test/uploads/config.ts +++ b/test/uploads/config.ts @@ -39,6 +39,7 @@ export default buildConfig({ upload: { staticURL: '/media', staticDir: './media', + mimeTypes: ['image/png', 'image/jpg', 'image/jpeg', 'image/svg+xml'], resizeOptions: { width: 1280, height: 720,
ae6c71b3b5b09ad2f0bc4fe9bc29a3f3eea50dce
2024-11-22 22:13:48
Jacob Fletcher
fix(live-preview): client-side live preview cannot clear all array rows (#9439)
false
client-side live preview cannot clear all array rows (#9439)
fix
diff --git a/packages/live-preview/src/traverseFields.ts b/packages/live-preview/src/traverseFields.ts index 271ff5f00bd..86064e5f084 100644 --- a/packages/live-preview/src/traverseFields.ts +++ b/packages/live-preview/src/traverseFields.ts @@ -25,6 +25,14 @@ export const traverseFields = <T>(args: { switch (fieldSchema.type) { case 'array': + if ( + !incomingData[fieldName] && + incomingData[fieldName] !== undefined && + result?.[fieldName] !== undefined + ) { + result[fieldName] = [] + } + if (Array.isArray(incomingData[fieldName])) { result[fieldName] = incomingData[fieldName].map((incomingRow, i) => { if (!result[fieldName]) { @@ -85,7 +93,7 @@ export const traverseFields = <T>(args: { break case 'group': - + // falls through case 'tabs': if (!result[fieldName]) { result[fieldName] = {} @@ -100,8 +108,9 @@ export const traverseFields = <T>(args: { }) break - case 'relationship': + case 'relationship': + // falls through case 'upload': // Handle `hasMany` relationships if (fieldSchema.hasMany && Array.isArray(incomingData[fieldName])) { diff --git a/test/live-preview/int.spec.ts b/test/live-preview/int.spec.ts index 0b744c89b6e..4df7b919ad5 100644 --- a/test/live-preview/int.spec.ts +++ b/test/live-preview/int.spec.ts @@ -169,6 +169,53 @@ describe('Collections - Live Preview', () => { expect(mergedData._numberOfRequests).toEqual(0) }) + it('— arrays - can clear all rows', async () => { + const initialData: Partial<Page> = { + title: 'Test Page', + arrayOfRelationships: [ + { + id: '123', + relationshipInArrayMonoHasOne: testPost.id, + }, + ], + } + + const mergedData = await mergeData({ + depth: 1, + fieldSchema: schemaJSON, + incomingData: { + ...initialData, + arrayOfRelationships: [], + }, + initialData, + serverURL, + returnNumberOfRequests: true, + collectionPopulationRequestHandler, + }) + + expect(mergedData.arrayOfRelationships).toEqual([]) + expect(mergedData._numberOfRequests).toEqual(0) + + // do the same but with arrayOfRelationships: 0 + + const mergedData2 = await mergeData({ + depth: 1, + fieldSchema: schemaJSON, + incomingData: { + ...initialData, + // @ts-expect-error eslint-disable-next-line + arrayOfRelationships: 0, // this is how form state represents an empty array + }, + initialData, + serverURL, + returnNumberOfRequests: true, + collectionPopulationRequestHandler, + }) + + expect(mergedData2.arrayOfRelationships).toEqual([]) + expect(mergedData2._numberOfRequests).toEqual(0) + }) + it('— uploads - adds and removes media', async () => { const initialData: Partial<Page> = { title: 'Test Page',
dfdea0d4eb1b1fb97a6da8a76d99ff1af244512d
2024-10-01 00:48:03
Paul
chore: update vscode launch settings for debugging test suites (#8399)
false
update vscode launch settings for debugging test suites (#8399)
chore
diff --git a/.vscode/launch.json b/.vscode/launch.json index 43bdde6cb77..2bf9d41eb16 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,14 +10,14 @@ "cwd": "${workspaceFolder}" }, { - "command": "node --no-deprecation test/dev.js _community", + "command": "pnpm tsx --no-deprecation test/dev.ts _community", "cwd": "${workspaceFolder}", "name": "Run Dev Community", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js storage-uploadthing", + "command": "pnpm tsx --no-deprecation test/dev.ts storage-uploadthing", "cwd": "${workspaceFolder}", "name": "Uploadthing", "request": "launch", @@ -25,7 +25,7 @@ "envFile": "${workspaceFolder}/test/storage-uploadthing/.env" }, { - "command": "node --no-deprecation test/dev.js live-preview", + "command": "pnpm tsx --no-deprecation test/dev.ts live-preview", "cwd": "${workspaceFolder}", "name": "Run Dev Live Preview", "request": "launch", @@ -43,28 +43,28 @@ } }, { - "command": "node --no-deprecation test/dev.js admin", + "command": "pnpm tsx --no-deprecation test/dev.ts admin", "cwd": "${workspaceFolder}", "name": "Run Dev Admin", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js auth", + "command": "pnpm tsx --no-deprecation test/dev.ts auth", "cwd": "${workspaceFolder}", "name": "Run Dev Auth", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js fields-relationship", + "command": "pnpm tsx --no-deprecation test/dev.ts fields-relationship", "cwd": "${workspaceFolder}", "name": "Run Dev Fields-Relationship", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js login-with-username", + "command": "pnpm tsx --no-deprecation test/dev.ts login-with-username", "cwd": "${workspaceFolder}", "name": "Run Dev Login-With-Username", "request": "launch", @@ -81,21 +81,21 @@ } }, { - "command": "node --no-deprecation test/dev.js collections-graphql", + "command": "pnpm tsx --no-deprecation test/dev.ts collections-graphql", "cwd": "${workspaceFolder}", "name": "Run Dev GraphQL", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js fields", + "command": "pnpm tsx --no-deprecation test/dev.ts fields", "cwd": "${workspaceFolder}", "name": "Run Dev Fields", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js versions", + "command": "pnpm tsx --no-deprecation test/dev.ts versions", "cwd": "${workspaceFolder}", "name": "Run Dev Postgres", "request": "launch", @@ -105,35 +105,35 @@ } }, { - "command": "node --no-deprecation test/dev.js versions", + "command": "pnpm tsx --no-deprecation test/dev.ts versions", "cwd": "${workspaceFolder}", "name": "Run Dev Versions", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js localization", + "command": "pnpm tsx --no-deprecation test/dev.ts localization", "cwd": "${workspaceFolder}", "name": "Run Dev Localization", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js locked-documents", + "command": "pnpm tsx --no-deprecation test/dev.ts locked-documents", "cwd": "${workspaceFolder}", "name": "Run Dev Locked Documents", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js uploads", + "command": "pnpm tsx --no-deprecation test/dev.ts uploads", "cwd": "${workspaceFolder}", "name": "Run Dev Uploads", "request": "launch", "type": "node-terminal" }, { - "command": "node --no-deprecation test/dev.js field-error-states", + "command": "pnpm tsx --no-deprecation test/dev.ts field-error-states", "cwd": "${workspaceFolder}", "name": "Run Dev Field Error States", "request": "launch",
465d8b02453873c432498e6f12c9b859459b39ae
2023-06-13 21:55:02
PatrikKozak
chore: updates authentication/api-keys docs
false
updates authentication/api-keys docs
chore
diff --git a/docs/authentication/config.mdx b/docs/authentication/config.mdx index 0aa9d59b67a..8d97c877958 100644 --- a/docs/authentication/config.mdx +++ b/docs/authentication/config.mdx @@ -17,7 +17,7 @@ To enable Authentication on a collection, define an `auth` property and set it t | **`useAPIKey`** | Payload Authentication provides for API keys to be set on each user within an Authentication-enabled Collection. [More](/docs/authentication/config#api-keys) | | **`tokenExpiration`** | How long (in seconds) to keep the user logged in. JWTs and HTTP-only cookies will both expire at the same time. | | **`maxLoginAttempts`** | Only allow a user to attempt logging in X amount of times. Automatically locks out a user from authenticating if this limit is passed. Set to `0` to disable. | -| **`lockTime`** | Set the time (in milliseconds) that a user should be locked out if they fail authentication more times than `maxLoginAttempts` allows for. | +| **`lockTime`** | Set the time (in milliseconds) that a user should be locked out if they fail authentication more times than `maxLoginAttempts` allows for. | | **`depth`** | How many levels deep a `user` document should be populated when creating the JWT and binding the `user` to the express `req`. Defaults to `0` and should only be modified if absolutely necessary, as this will affect performance. | | **`cookies`** | Set cookie options, including `secure`, `sameSite`, and `domain`. For advanced users. | | **`forgotPassword`** | Customize the way that the `forgotPassword` operation functions. [More](/docs/authentication/config#forgot-password) | @@ -29,10 +29,12 @@ To enable Authentication on a collection, define an `auth` property and set it t To integrate with third-party APIs or services, you might need the ability to generate API keys that can be used to identify as a certain user within Payload. +In Payload, users are essentially documents within a collection. Just like you can authenticate as a user with an email and password, which is considered as our default local auth strategy, you can also authenticate as a user with an API key. API keys are generated on a user-by-user basis, similar to email and passwords, and are meant to represent a single user. + For example, if you have a third-party service or external app that needs to be able to perform protected actions at its discretion, you have two options: 1. Create a user for the third-party app, and log in each time to receive a token before you attempt to access any protected actions -1. Enable API key support for the Collection, where you can generate a non-expiring API key per user in the collection +1. Enable API key support for the Collection, where you can generate a non-expiring API key per user in the collection. This is particularly useful as you can create a "user" that reflects an integration with a specific external service and assign a "role" or specific access only needed by that service/integration. Alternatively, you could create a "super admin" user and assign an API key to that user so that any requests made with that API key are considered as being made by that super user. Technically, both of these options will work for third-party integrations but the second option with API key is simpler, because it reduces the amount of work that your integrations need to do to be authenticated properly. @@ -45,7 +47,7 @@ To enable API keys on a collection, set the `useAPIKey` auth option to `true`. F #### Authenticating via API Key -To authenticate REST or GraphQL API requests using an API key, set the `Authorization` header. The header is case-sensitive and needs the slug of the `auth.useAPIKey` enabled collection, then " API-Key ", followed by the `apiKey` that has been assigned. Payload's built-in middleware will then assign the user document to `req.user` and handle requests with the proper access control. +To authenticate REST or GraphQL API requests using an API key, set the `Authorization` header. The header is case-sensitive and needs the slug of the `auth.useAPIKey` enabled collection, then " API-Key ", followed by the `apiKey` that has been assigned. Payload's built-in middleware will then assign the user document to `req.user` and handle requests with the proper access control. By doing this, Payload recognizes the request being made as a request by the user associated with that API key. **For example, using Fetch:** @@ -59,6 +61,8 @@ const response = await fetch("http://localhost:3000/api/pages", { }); ``` +Our authentication strategies ensure uniform access control across all strategies. This enables you to utilize your existing access control configurations with both API keys and the standard email/password authentication. This consistency can aid in maintaining granular control over your API keys. + ### Forgot Password You can customize how the Forgot Password workflow operates with the following options on the `auth.forgotPassword` property:
313ea52e3d6923702aba12eab674c0545124ad7f
2024-04-09 22:47:43
James
chore: getRequestLanguage now defaults
false
getRequestLanguage now defaults
chore
diff --git a/packages/next/src/utilities/getRequestLanguage.ts b/packages/next/src/utilities/getRequestLanguage.ts index 6ca0b8b1aa9..0adf954e8a8 100644 --- a/packages/next/src/utilities/getRequestLanguage.ts +++ b/packages/next/src/utilities/getRequestLanguage.ts @@ -7,7 +7,7 @@ import { matchLanguage } from '@payloadcms/translations' type GetRequestLanguageArgs = { config: SanitizedConfig cookies: Map<string, string> | ReadonlyRequestCookies - defaultLanguage?: string + defaultLanguage?: AcceptedLanguages headers: Request['headers'] } @@ -26,5 +26,5 @@ export const getRequestLanguage = ({ config.i18n.fallbackLanguage || defaultLanguage - return matchLanguage(reqLanguage) + return matchLanguage(reqLanguage) || defaultLanguage }
be61f8ab96e629a2a0b3a543a4d8f4ff70380997
2023-08-01 00:50:34
James
chore: revises paths
false
revises paths
chore
diff --git a/packages/db-mongodb/src/find.ts b/packages/db-mongodb/src/find.ts index 7ba3223f625..5e1eadb69f5 100644 --- a/packages/db-mongodb/src/find.ts +++ b/packages/db-mongodb/src/find.ts @@ -1,11 +1,11 @@ import type { PaginateOptions } from 'mongoose'; +import sanitizeInternalFields from 'payload/dist/utilities/sanitizeInternalFields'; +import type { Find } from 'payload/dist/database/types'; +import flattenWhereToOperators from 'payload/dist/database/flattenWhereToOperators'; +import { PayloadRequest } from 'payload/dist/express/types'; +import { buildSortParam } from './queries/buildSortParam'; import type { MongooseAdapter } from '.'; -import type { Find } from '../../types'; -import sanitizeInternalFields from '../../../utilities/sanitizeInternalFields'; -import flattenWhereToOperators from '../../flattenWhereToOperators'; -import { buildSortParam } from './src/queries/buildSortParam'; import { withSession } from './withSession'; -import { PayloadRequest } from '../../../express/types'; export const find: Find = async function find( this: MongooseAdapter, diff --git a/packages/db-mongodb/src/findGlobal.ts b/packages/db-mongodb/src/findGlobal.ts index 7c0c044a953..45fb56c250e 100644 --- a/packages/db-mongodb/src/findGlobal.ts +++ b/packages/db-mongodb/src/findGlobal.ts @@ -1,9 +1,9 @@ +import { combineQueries } from 'payload/dist/database/combineQueries'; +import type { FindGlobal } from 'payload/dist/database/types'; +import sanitizeInternalFields from 'payload/dist/utilities/sanitizeInternalFields'; +import { PayloadRequest } from 'payload/dist/express/types'; import type { MongooseAdapter } from '.'; -import { combineQueries } from '../../combineQueries'; -import type { FindGlobal } from '../../types'; -import sanitizeInternalFields from '../../../utilities/sanitizeInternalFields'; import { withSession } from './withSession'; -import { PayloadRequest } from '../../../express/types'; export const findGlobal: FindGlobal = async function findGlobal( this: MongooseAdapter,
af4ed27d154cb35a452f91142c534e71041a259c
2023-02-01 04:49:49
James
chore: reduces width of block selector tiles on bigger screens
false
reduces width of block selector tiles on bigger screens
chore
diff --git a/src/admin/components/forms/field-types/Blocks/BlocksDrawer/index.scss b/src/admin/components/forms/field-types/Blocks/BlocksDrawer/index.scss index 7ab15fe2736..82c70587220 100644 --- a/src/admin/components/forms/field-types/Blocks/BlocksDrawer/index.scss +++ b/src/admin/components/forms/field-types/Blocks/BlocksDrawer/index.scss @@ -22,7 +22,7 @@ &__block { margin: base(0.5); - width: calc(25% - #{base(1)}); + width: calc(12.5% - #{base(1)}); } &__default-image { @@ -31,6 +31,12 @@ padding-top: base(0.75); } + @include large-break { + &__block { + width: calc(20% - #{base(1)}); + } + } + @include mid-break { &__wrapper { margin-top: base(1.5);
027dff8363915f34730bb058cf8b6bec88619bed
2022-10-25 22:00:47
Elliot DeNolf
chore(release): v1.1.18
false
v1.1.18
chore
diff --git a/CHANGELOG.md b/CHANGELOG.md index 06244eed009..64f94989ca1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ +## [1.1.18](https://github.com/payloadcms/payload/compare/v1.1.17...v1.1.18) (2022-10-25) + ## [1.1.17](https://github.com/payloadcms/payload/compare/v1.1.16...v1.1.17) (2022-10-25) diff --git a/package.json b/package.json index 8ad7480c9db..85e584b4d2f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "1.1.17", + "version": "1.1.18", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "MIT", "engines": {
71a3e5ba1037fe447dccad4a490fdfb1623ba0b0
2023-10-24 02:31:58
Jacob Fletcher
fix: prevents document sidebar from collapsing
false
prevents document sidebar from collapsing
fix
diff --git a/packages/payload/src/admin/components/elements/DocumentFields/index.scss b/packages/payload/src/admin/components/elements/DocumentFields/index.scss index 2512d9fa7d0..152f6e52f37 100644 --- a/packages/payload/src/admin/components/elements/DocumentFields/index.scss +++ b/packages/payload/src/admin/components/elements/DocumentFields/index.scss @@ -7,6 +7,10 @@ &--has-sidebar { .document-fields { + &__main { + width: 66.66%; + } + &__edit { [dir='ltr'] & { top: 0; @@ -52,6 +56,7 @@ width: 33.33%; height: calc(100vh - var(--doc-controls-height)); min-width: var(--doc-sidebar-width); + flex-shrink: 0; } &__sidebar { diff --git a/test/fields/collections/Tabs/index.ts b/test/fields/collections/Tabs/index.ts index 59c16d3cc29..6c86ade01a2 100644 --- a/test/fields/collections/Tabs/index.ts +++ b/test/fields/collections/Tabs/index.ts @@ -12,6 +12,16 @@ const TabsFields: CollectionConfig = { }, versions: true, fields: [ + { + name: 'sidebarField', + type: 'text', + label: 'Sidebar Field', + admin: { + position: 'sidebar', + description: + 'This should not collapse despite there being many tabs pushing the main fields open.', + }, + }, { type: 'tabs', tabs: [
2118c6c47f5c59161318964cc100c61e1ba986b9
2025-02-05 06:42:07
James Mikrut
feat: exposes helpful args to ts schema gen (#10984)
false
exposes helpful args to ts schema gen (#10984)
feat
diff --git a/packages/payload/src/config/types.ts b/packages/payload/src/config/types.ts index 51991d94d26..9c524ec7f1f 100644 --- a/packages/payload/src/config/types.ts +++ b/packages/payload/src/config/types.ts @@ -1,6 +1,7 @@ import type { DefaultTranslationKeys, DefaultTranslationsObject, + I18n, I18nClient, I18nOptions, TFunction, @@ -1122,7 +1123,16 @@ export type Config = { * Allows you to modify the base JSON schema that is generated during generate:types. This JSON schema will be used * to generate the TypeScript interfaces. */ - schema?: Array<(args: { jsonSchema: JSONSchema4 }) => JSONSchema4> + schema?: Array< + (args: { + collectionIDFieldTypes: { + [key: string]: 'number' | 'string' + } + config: SanitizedConfig + i18n: I18n + jsonSchema: JSONSchema4 + }) => JSONSchema4 + > } /** * Customize the handling of incoming file uploads for collections that have uploads enabled. diff --git a/packages/payload/src/utilities/configToJSONSchema.ts b/packages/payload/src/utilities/configToJSONSchema.ts index ba2b9c3cde2..fc6b1a1af36 100644 --- a/packages/payload/src/utilities/configToJSONSchema.ts +++ b/packages/payload/src/utilities/configToJSONSchema.ts @@ -1102,7 +1102,7 @@ export function configToJSONSchema( if (config?.typescript?.schema?.length) { for (const schema of config.typescript.schema) { - jsonSchema = schema({ jsonSchema }) + jsonSchema = schema({ collectionIDFieldTypes, config, i18n, jsonSchema }) } }
e0afeeca974d0a0cac7aca8e40f9436449c902b5
2023-10-11 03:03:15
Jarrod Flesch
fix: API tab breadcrumbs and results indentation (#3564)
false
API tab breadcrumbs and results indentation (#3564)
fix
diff --git a/packages/payload/src/admin/components/views/API/index.scss b/packages/payload/src/admin/components/views/API/index.scss index ca700943c00..9a052ad2c5c 100644 --- a/packages/payload/src/admin/components/views/API/index.scss +++ b/packages/payload/src/admin/components/views/API/index.scss @@ -7,6 +7,10 @@ gap: calc(var(--base) * 2); align-items: flex-start; + ul { + padding-left: calc(var(--base) * 1); + } + &--fullscreen { padding-left: 0; .query-inspector__configuration { @@ -173,6 +177,10 @@ } } + &__row-line--nested { + margin-left: 25px; + } + &__bracket { position: relative; diff --git a/packages/payload/src/admin/components/views/API/index.tsx b/packages/payload/src/admin/components/views/API/index.tsx index 1670ce3e3de..e148011fabf 100644 --- a/packages/payload/src/admin/components/views/API/index.tsx +++ b/packages/payload/src/admin/components/views/API/index.tsx @@ -1,6 +1,8 @@ import * as React from 'react' import { useTranslation } from 'react-i18next' +import type { EditViewProps } from '../types' + import { Chevron } from '../..' import { requests } from '../../../api' import CopyToClipboard from '../../elements/CopyToClipboard' @@ -11,6 +13,7 @@ import { MinimizeMaximize } from '../../icons/MinimizeMaximize' import { useConfig } from '../../utilities/Config' import { useDocumentInfo } from '../../utilities/DocumentInfo' import { useLocale } from '../../utilities/Locale' +import { SetStepNav } from '../collections/Edit/SetStepNav' import './index.scss' const chars = { @@ -119,12 +122,19 @@ const RecursivelyRenderObjectData = ({ } if (type === 'date' || type === 'string' || type === 'null' || type === 'number') { + const parentHasKey = Boolean(parentType === 'object' && key) + + const rowClasses = [ + `${baseClass}__row-line`, + `${baseClass}__value-type--${type}`, + `${baseClass}__row-line--${objectKey ? 'nested' : 'top'}`, + ] + .filter(Boolean) + .join(' ') + return ( - <li - className={`${baseClass}__row-line ${baseClass}__value-type--${type}`} - key={`${key}-${keyIndex}`} - > - {parentType === 'object' ? <span>{`"${key}": `}</span> : null} + <li className={rowClasses} key={`${key}-${keyIndex}`}> + {parentHasKey ? <span>{`"${key}": `}</span> : null} {type === 'string' ? ( <span className={`${baseClass}__value`}>{`"${value}"`}</span> @@ -156,7 +166,8 @@ function createURL(url: string) { } } -export const API = ({ apiURL }) => { +export const API: React.FC<EditViewProps> = (props) => { + const { apiURL } = props const { i18n } = useTranslation() const { localization, @@ -201,8 +212,15 @@ export const API = ({ apiURL }) => { const classes = [baseClass, fullscreen && `${baseClass}--fullscreen`].filter(Boolean).join(' ') + let isEditing: boolean + + if ('collection' in props) { + isEditing = props?.isEditing + } + return ( <Gutter className={classes} right={false}> + <SetStepNav collection={collection} global={global} id={id} isEditing={isEditing} /> <div className={`${baseClass}__configuration`}> <div className={`${baseClass}__api-url`}> <span className={`${baseClass}__label`}> diff --git a/packages/payload/src/admin/components/views/collections/Edit/SetStepNav.tsx b/packages/payload/src/admin/components/views/collections/Edit/SetStepNav.tsx index 75cbfd1065c..0792f41bdab 100644 --- a/packages/payload/src/admin/components/views/collections/Edit/SetStepNav.tsx +++ b/packages/payload/src/admin/components/views/collections/Edit/SetStepNav.tsx @@ -13,7 +13,7 @@ import { useConfig } from '../../../utilities/Config' export const SetStepNav: React.FC< | { collection: SanitizedCollectionConfig - id: string + id: number | string isEditing: boolean } | { @@ -27,7 +27,7 @@ export const SetStepNav: React.FC< let pluralLabel: SanitizedCollectionConfig['labels']['plural'] let slug: string let isEditing = false - let id: string | undefined + let id: number | string | undefined if ('collection' in props) { const { @@ -70,7 +70,7 @@ export const SetStepNav: React.FC< if (isEditing) { nav.push({ - label: useAsTitle && useAsTitle !== 'id' ? title || `[${t('untitled')}]` : id, + label: useAsTitle && useAsTitle !== 'id' ? title || `[${t('untitled')}]` : `${id}`, }) } else { nav.push({
959f01739c30450f3a6d052dd6083fdacf1527a4
2023-03-09 19:39:09
William Killerud
fix: check relationships indexed access for undefined
false
check relationships indexed access for undefined
fix
diff --git a/src/admin/components/forms/field-types/Relationship/createRelationMap.ts b/src/admin/components/forms/field-types/Relationship/createRelationMap.ts index 91b925bd1c7..e12ca5f1e84 100644 --- a/src/admin/components/forms/field-types/Relationship/createRelationMap.ts +++ b/src/admin/components/forms/field-types/Relationship/createRelationMap.ts @@ -31,7 +31,11 @@ export const createRelationMap: CreateRelationMap = ({ const add = (relation: string, id: unknown) => { if (((typeof id === 'string') || typeof id === 'number') && typeof relation === 'string') { - relationMap[relation].push(id); + if (relationMap[relation]) { + relationMap[relation].push(id); + } else { + relationMap[relation] = [id]; + } } };
db8e805a967ba5f494bab07106f77ca884de1402
2024-03-28 01:25:19
Alessio Gravili
fix: improve error path merging from server, make sure no new or removed rows/values coming from the server are being considered outside addFieldRow
false
improve error path merging from server, make sure no new or removed rows/values coming from the server are being considered outside addFieldRow
fix
diff --git a/packages/payload/src/admin/forms/Form.ts b/packages/payload/src/admin/forms/Form.ts index 8b9f6577094..8501b5ff29d 100644 --- a/packages/payload/src/admin/forms/Form.ts +++ b/packages/payload/src/admin/forms/Form.ts @@ -8,7 +8,7 @@ export type Data = { export type Row = { blockType?: string collapsed?: boolean - errorPaths?: Set<string> + errorPaths?: string[] id: string } @@ -19,7 +19,7 @@ export type FilterOptionsResult = { export type FormField = { disableFormData?: boolean errorMessage?: string - errorPaths?: Set<string> + errorPaths?: string[] fieldSchema?: Field filterOptions?: FilterOptionsResult initialValue: unknown diff --git a/packages/ui/src/fields/Array/ArrayRow.tsx b/packages/ui/src/fields/Array/ArrayRow.tsx index 6540dd42380..f592a24a6a4 100644 --- a/packages/ui/src/fields/Array/ArrayRow.tsx +++ b/packages/ui/src/fields/Array/ArrayRow.tsx @@ -70,7 +70,7 @@ export const ArrayRow: React.FC<ArrayRowProps> = ({ '0', )}` - const errorCount = row.errorPaths?.size + const errorCount = row.errorPaths?.length const fieldHasErrors = errorCount > 0 && hasSubmitted const classNames = [ diff --git a/packages/ui/src/fields/Array/index.tsx b/packages/ui/src/fields/Array/index.tsx index 71bdfa54174..6fdf0285996 100644 --- a/packages/ui/src/fields/Array/index.tsx +++ b/packages/ui/src/fields/Array/index.tsx @@ -181,7 +181,7 @@ export const _ArrayField: React.FC<ArrayFieldProps> = (props) => { const hasMaxRows = maxRows && rows.length >= maxRows const fieldErrorCount = - rows.reduce((total, row) => total + (row?.errorPaths?.size || 0), 0) + (valid ? 0 : 1) + rows.reduce((total, row) => total + (row?.errorPaths?.length || 0), 0) + (valid ? 0 : 1) const fieldHasErrors = submitted && fieldErrorCount > 0 diff --git a/packages/ui/src/fields/Blocks/index.tsx b/packages/ui/src/fields/Blocks/index.tsx index 4c783a0451a..57828b27d6e 100644 --- a/packages/ui/src/fields/Blocks/index.tsx +++ b/packages/ui/src/fields/Blocks/index.tsx @@ -192,7 +192,7 @@ const _BlocksField: React.FC<BlocksFieldProps> = (props) => { const hasMaxRows = maxRows && rows.length >= maxRows - const fieldErrorCount = rows.reduce((total, row) => total + (row?.errorPaths?.size || 0), 0) + const fieldErrorCount = rows.reduce((total, row) => total + (row?.errorPaths?.length || 0), 0) const fieldHasErrors = submitted && fieldErrorCount + (valid ? 0 : 1) > 0 const showMinRows = rows.length < minRows || (required && rows.length === 0) diff --git a/packages/ui/src/forms/Form/fieldReducer.ts b/packages/ui/src/forms/Form/fieldReducer.ts index a9dd4626075..da4af320372 100644 --- a/packages/ui/src/forms/Form/fieldReducer.ts +++ b/packages/ui/src/forms/Form/fieldReducer.ts @@ -17,14 +17,13 @@ const ObjectId = (ObjectIdImport.default || export function fieldReducer(state: FormState, action: FieldAction): FormState { switch (action.type) { case 'REPLACE_STATE': { - const newState = {} - if (action.optimize !== false) { // Only update fields that have changed // by comparing old value / initialValue to new // .. // This is a performance enhancement for saving // large documents with hundreds of fields + const newState = {} Object.entries(action.state).forEach(([path, field]) => { const oldField = state[path] @@ -36,12 +35,10 @@ export function fieldReducer(state: FormState, action: FieldAction): FormState { newState[path] = oldField } }) - } else { - // If we're not optimizing, just set the state to the new state - return action.state + return newState } - - return newState + // If we're not optimizing, just set the state to the new state + return action.state } case 'REMOVE': { diff --git a/packages/ui/src/forms/Form/index.tsx b/packages/ui/src/forms/Form/index.tsx index 80b43a45051..598b6655f09 100644 --- a/packages/ui/src/forms/Form/index.tsx +++ b/packages/ui/src/forms/Form/index.tsx @@ -5,7 +5,7 @@ import type { FormState } from 'payload/types' import isDeepEqual from 'deep-equal' import { useRouter } from 'next/navigation.js' import { serialize } from 'object-to-formdata' -import { wait } from 'payload/utilities' +import { deepCopyObject, wait } from 'payload/utilities' import QueryString from 'qs' import React, { useCallback, useEffect, useReducer, useRef, useState } from 'react' import { toast } from 'react-toastify' @@ -544,7 +544,11 @@ export const Form: React.FC<FormProps> = (props) => { ) if (changed) { - dispatchFields({ type: 'REPLACE_STATE', optimize: false, state: newState }) + dispatchFields({ + type: 'REPLACE_STATE', + optimize: false, + state: newState, + }) } } } diff --git a/packages/ui/src/forms/Form/mergeErrorPaths.ts b/packages/ui/src/forms/Form/mergeErrorPaths.ts new file mode 100644 index 00000000000..32b2148d712 --- /dev/null +++ b/packages/ui/src/forms/Form/mergeErrorPaths.ts @@ -0,0 +1,38 @@ +import { arraysHaveSameStrings } from '@payloadcms/ui/utilities/arraysHaveSameStrings' + +export const mergeErrorPaths = ( + existing?: string[], + incoming?: string[], +): { + changed: boolean + result?: string[] +} => { + if (!existing) { + return { + changed: false, + result: undefined, + } + } + + const existingErrorPaths: string[] = [] + const incomingErrorPaths: string[] = [] + + if (Array.isArray(incoming) && incoming?.length) { + incoming.forEach((path) => incomingErrorPaths.push(path)) + } + + if (Array.isArray(existing) && existing?.length) { + existing.forEach((path) => existingErrorPaths.push(path)) + } + + if (!arraysHaveSameStrings(existingErrorPaths, incomingErrorPaths)) { + return { + changed: true, + result: incomingErrorPaths, + } + } + return { + changed: false, + result: existing, + } +} diff --git a/packages/ui/src/forms/Form/mergeServerFormState.ts b/packages/ui/src/forms/Form/mergeServerFormState.ts index b5f55ad2c32..7906736dc64 100644 --- a/packages/ui/src/forms/Form/mergeServerFormState.ts +++ b/packages/ui/src/forms/Form/mergeServerFormState.ts @@ -1,10 +1,8 @@ import type { FormState } from 'payload/types' -import isDeepEqual from 'deep-equal' +import { mergeErrorPaths } from './mergeErrorPaths.js' -import { arraysHaveSameStrings } from '../../utilities/arraysHaveSameStrings.js' - -const propsToCheck = ['passesCondition', 'valid', 'errorMessage'] +const serverPropsToAccept = ['passesCondition', 'valid', 'errorMessage'] /** * Merges certain properties from the server state into the client state. These do not include values, @@ -14,51 +12,70 @@ const propsToCheck = ['passesCondition', 'valid', 'errorMessage'] * is the thing we want to keep in sync with the server (where it's calculated) on the client. */ export const mergeServerFormState = ( - oldState: FormState, - newState: FormState, + existingState: FormState, + incomingState: FormState, ): { changed: boolean; newState: FormState } => { let changed = false - if (oldState) { - Object.entries(newState).forEach(([path, newFieldState]) => { - if (!oldState[path]) return - - newFieldState.initialValue = oldState[path].initialValue - newFieldState.value = oldState[path].value + if (existingState) { + Object.entries(existingState).forEach(([path, newFieldState]) => { + if (!incomingState[path]) return - const oldErrorPaths: string[] = [] - const newErrorPaths: string[] = [] + /** + * Handle error paths + */ - if (oldState[path].errorPaths instanceof Set) { - oldState[path].errorPaths.forEach((path) => oldErrorPaths.push(path)) - } - - if ( - newFieldState.errorPaths && - !Array.isArray(newFieldState.errorPaths) && - typeof newFieldState.errorPaths - ) { - Object.values(newFieldState.errorPaths).forEach((path) => newErrorPaths.push(path)) - } - - if (!arraysHaveSameStrings(oldErrorPaths, newErrorPaths)) { - changed = true + const errorPathsResult = mergeErrorPaths( + newFieldState.errorPaths, + incomingState[path].errorPaths as unknown as string[], + ) + if (errorPathsResult.result) { + if (errorPathsResult.changed) { + changed = errorPathsResult.changed + } + newFieldState.errorPaths = errorPathsResult.result } - propsToCheck.forEach((prop) => { - if (newFieldState[prop] != oldState[path][prop]) { + /** + * Handle the rest which is in serverPropsToAccept + */ + serverPropsToAccept.forEach((prop) => { + if (incomingState[path]?.[prop] !== newFieldState[prop]) { changed = true + if (!(prop in incomingState[path])) { + delete newFieldState[prop] + } else { + newFieldState[prop] = incomingState[path][prop] + } } }) - if ( - Array.isArray(newFieldState.rows) && - !isDeepEqual(newFieldState.rows, oldState[path].rows) - ) { - changed = true + /** + * Handle rows + */ + if (Array.isArray(newFieldState.rows) && newFieldState?.rows.length) { + let i = 0 + for (const row of newFieldState.rows) { + const incomingRow = incomingState[path]?.rows?.[i] + if (incomingRow) { + const errorPathsRowResult = mergeErrorPaths( + row.errorPaths, + incomingRow.errorPaths as unknown as string[], + ) + if (errorPathsRowResult.result) { + if (errorPathsResult.changed) { + changed = true + } + incomingRow.errorPaths = errorPathsRowResult.result + } + } + + i++ + } } }) } - return { changed, newState } + // Conditions don't work if we don't memcopy the new state, as the object references would otherwise be the same + return { changed, newState: { ...existingState } } } diff --git a/packages/ui/src/forms/buildStateFromSchema/addFieldStatePromise.ts b/packages/ui/src/forms/buildStateFromSchema/addFieldStatePromise.ts index 33ae11190b6..67533c4f6d6 100644 --- a/packages/ui/src/forms/buildStateFromSchema/addFieldStatePromise.ts +++ b/packages/ui/src/forms/buildStateFromSchema/addFieldStatePromise.ts @@ -23,7 +23,7 @@ export type AddFieldStatePromiseArgs = { */ anyParentLocalized?: boolean data: Data - errorPaths: Set<string> + errorPaths: string[] field: NonPresentationalField /** * You can use this to filter down to only `localized` fields that require translation (type: text, textarea, etc.). Another plugin might want to look for only `point` type fields to do some GIS function. With the filter function you can go in like a surgeon. @@ -74,7 +74,7 @@ export const addFieldStatePromise = async (args: AddFieldStatePromiseArgs): Prom id, anyParentLocalized = false, data, - errorPaths: parentErrorPaths, + errorPaths: parentErrorPaths = [], field, filter, forceFullValue = false, @@ -95,7 +95,7 @@ export const addFieldStatePromise = async (args: AddFieldStatePromiseArgs): Prom const validate = operation === 'update' ? field.validate : undefined const fieldState: FormField = { - errorPaths: new Set(), + errorPaths: [], fieldSchema: includeSchema ? field : undefined, initialValue: undefined, passesCondition, @@ -144,7 +144,9 @@ export const addFieldStatePromise = async (args: AddFieldStatePromiseArgs): Prom fieldState.valid = false // TODO: this is unpredictable, need to figure out why // It will sometimes lead to inconsistencies across re-renders - parentErrorPaths.add(`${path}${field.name}`) + if (!parentErrorPaths.includes(`${path}${field.name}`)) { + parentErrorPaths.push(`${path}${field.name}`) + } } else { fieldState.valid = true } diff --git a/packages/ui/src/forms/buildStateFromSchema/index.tsx b/packages/ui/src/forms/buildStateFromSchema/index.tsx index 3908327ded5..74f6166261e 100644 --- a/packages/ui/src/forms/buildStateFromSchema/index.tsx +++ b/packages/ui/src/forms/buildStateFromSchema/index.tsx @@ -40,7 +40,7 @@ export const buildStateFromSchema = async (args: Args): Promise<FormState> => { await iterateFields({ id, data: fullData, - errorPaths: new Set(), + errorPaths: [], fields: fieldSchema, fullData, operation, diff --git a/packages/ui/src/forms/buildStateFromSchema/iterateFields.ts b/packages/ui/src/forms/buildStateFromSchema/iterateFields.ts index 7dbba5ed076..e7455f8d8f0 100644 --- a/packages/ui/src/forms/buildStateFromSchema/iterateFields.ts +++ b/packages/ui/src/forms/buildStateFromSchema/iterateFields.ts @@ -12,7 +12,7 @@ type Args = { */ anyParentLocalized?: boolean data: Data - errorPaths: Set<string> + errorPaths: string[] fields: FieldSchema[] filter?: (args: AddFieldStatePromiseArgs) => boolean /** diff --git a/test/access-control/e2e.spec.ts b/test/access-control/e2e.spec.ts index 7f43984cb3d..4da63e281c3 100644 --- a/test/access-control/e2e.spec.ts +++ b/test/access-control/e2e.spec.ts @@ -9,7 +9,6 @@ import type { ReadOnlyCollection, RestrictedVersion } from './payload-types.js' import { closeNav, - delayNetwork, exactText, initPageConsoleErrorCatch, openDocControls, @@ -60,7 +59,6 @@ describe('access control', () => { const context = await browser.newContext() page = await context.newPage() initPageConsoleErrorCatch(page) - await delayNetwork({ context, page, delay: 'Slow 4G' }) }) test('field without read access should not show', async () => { diff --git a/test/fields/lexical.e2e.spec.ts b/test/fields/lexical.e2e.spec.ts index 7ab19e70392..255b22d6c07 100644 --- a/test/fields/lexical.e2e.spec.ts +++ b/test/fields/lexical.e2e.spec.ts @@ -32,7 +32,7 @@ async function navigateToLexicalFields() { const url: AdminUrlUtil = new AdminUrlUtil(serverURL, 'lexical-fields') await page.goto(url.list) const linkToDoc = page.locator('tbody tr:first-child .cell-title a').first() - await expect(() => expect(linkToDoc).toBeTruthy()).toPass({ timeout: 45000 }) + await expect(() => expect(linkToDoc).toBeTruthy()).toPass({ timeout: POLL_TOPASS_TIMEOUT }) const linkDocHref = await linkToDoc.getAttribute('href') await linkToDoc.click()
f98ef62ad349b607bcd2f63a3ead14800b27611d
2022-07-17 23:16:07
Elliot DeNolf
test: port auth tests to int
false
port auth tests to int
test
diff --git a/src/auth/auth.spec.ts b/src/auth/auth.spec.ts deleted file mode 100644 index cba1200cce3..00000000000 --- a/src/auth/auth.spec.ts +++ /dev/null @@ -1,237 +0,0 @@ -import MongoClient from 'mongodb'; -import getConfig from '../config/load'; -import { email, password, connection } from '../mongoose/testCredentials'; - -require('isomorphic-fetch'); - -const { url: mongoURL, port: mongoPort, name: mongoDBName } = connection; - -const { serverURL: url } = getConfig(); - -let token = null; - -describe('Users REST API', () => { - it('should prevent registering a first user', async () => { - const response = await fetch(`${url}/api/admins/first-register`, { - body: JSON.stringify({ - email: '[email protected]', - password: 'get-out', - }), - headers: { - 'Content-Type': 'application/json', - }, - method: 'post', - }); - - expect(response.status).toBe(403); - }); - - it('should login a user successfully', async () => { - const response = await fetch(`${url}/api/admins/login`, { - body: JSON.stringify({ - email, - password, - }), - headers: { - 'Content-Type': 'application/json', - }, - method: 'post', - }); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.token).toBeDefined(); - - ({ token } = data); - }); - - it('should return a logged in user from /me', async () => { - const response = await fetch(`${url}/api/admins/me`, { - headers: { - Authorization: `JWT ${token}`, - }, - }); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.user.email).toBeDefined(); - }); - - it('should refresh a token and reset its expiration', async () => { - const response = await fetch(`${url}/api/admins/refresh-token`, { - method: 'post', - headers: { - Authorization: `JWT ${token}`, - }, - }); - - const data = await response.json(); - - expect(response.status).toBe(200); - expect(data.refreshedToken).toBeDefined(); - - token = data.refreshedToken; - }); - - it('should allow forgot-password by email', async () => { - // TODO: figure out how to spy on payload instance functions - // const mailSpy = jest.spyOn(payload, 'sendEmail'); - const response = await fetch(`${url}/api/admins/forgot-password`, { - method: 'post', - body: JSON.stringify({ - email, - }), - headers: { - 'Content-Type': 'application/json', - }, - }); - - // is not working - // expect(mailSpy).toHaveBeenCalled(); - - expect(response.status).toBe(200); - }); - - it('should allow a user to be created', async () => { - const response = await fetch(`${url}/api/admins`, { - body: JSON.stringify({ - email: '[email protected]', - password, - roles: ['editor'], - }), - headers: { - Authorization: `JWT ${token}`, - 'Content-Type': 'application/json', - }, - method: 'post', - }); - - const data = await response.json(); - - expect(response.status).toBe(201); - expect(data).toHaveProperty('message'); - expect(data).toHaveProperty('doc'); - - const { doc } = data; - - expect(doc).toHaveProperty('email'); - expect(doc).toHaveProperty('createdAt'); - expect(doc).toHaveProperty('roles'); - }); - - it('should allow verification of a user', async () => { - const emailToVerify = '[email protected]'; - const response = await fetch(`${url}/api/public-users`, { - body: JSON.stringify({ - email: emailToVerify, - password, - roles: ['editor'], - }), - headers: { - Authorization: `JWT ${token}`, - 'Content-Type': 'application/json', - }, - method: 'post', - }); - - expect(response.status).toBe(201); - const client = await MongoClient.connect(`${mongoURL}:${mongoPort}`, { - useUnifiedTopology: true, - }); - - const db = client.db(mongoDBName); - const userResult = await db.collection('public-users').findOne({ email: emailToVerify }); - const { _verified, _verificationToken } = userResult; - - expect(_verified).toBe(false); - expect(_verificationToken).toBeDefined(); - - const verificationResponse = await fetch(`${url}/api/public-users/verify/${_verificationToken}`, { - headers: { - 'Content-Type': 'application/json', - }, - method: 'post', - }); - - expect(verificationResponse.status).toBe(200); - - const afterVerifyResult = await db.collection('public-users').findOne({ email: emailToVerify }); - const { _verified: afterVerified, _verificationToken: afterToken } = afterVerifyResult; - expect(afterVerified).toBe(true); - expect(afterToken).toBeUndefined(); - }); - - describe('Account Locking', () => { - const userEmail = '[email protected]'; - let db; - beforeAll(async () => { - const client = await MongoClient.connect(`${mongoURL}:${mongoPort}`); - db = client.db(mongoDBName); - }); - - it('should lock the user after too many attempts', async () => { - await fetch(`${url}/api/admins`, { - body: JSON.stringify({ - email: userEmail, - password, - }), - headers: { - Authorization: `JWT ${token}`, - 'Content-Type': 'application/json', - }, - method: 'post', - }); - - const tryLogin = () => fetch(`${url}/api/admins/login`, { - body: JSON.stringify({ - email: userEmail, - password: 'bad', - }), - headers: { - Authorization: `JWT ${token}`, - 'Content-Type': 'application/json', - }, - method: 'post', - }); - - await tryLogin(); - await tryLogin(); - await tryLogin(); - await tryLogin(); - await tryLogin(); - - const userResult = await db.collection('admins').findOne({ email: userEmail }); - const { loginAttempts, lockUntil } = userResult; - - expect(loginAttempts).toBe(5); - expect(lockUntil).toBeDefined(); - }); - - it('should unlock account once lockUntil period is over', async () => { - await db.collection('admins').findOneAndUpdate( - { email: userEmail }, - { $set: { lockUntil: Date.now() - (605 * 1000) } }, - ); - - await fetch(`${url}/api/admins/login`, { - body: JSON.stringify({ - email: userEmail, - password, - }), - headers: { - Authorization: `JWT ${token}`, - 'Content-Type': 'application/json', - }, - method: 'post', - }); - - const userResult = await db.collection('admins').findOne({ email: userEmail }); - const { loginAttempts, lockUntil } = userResult; - - expect(loginAttempts).toBe(0); - expect(lockUntil).toBeUndefined(); - }); - }); -}); diff --git a/test/auth/config.ts b/test/auth/config.ts index 8cf17ae0f87..be7065b4e5a 100644 --- a/test/auth/config.ts +++ b/test/auth/config.ts @@ -10,11 +10,31 @@ export default buildConfig({ { slug, auth: { - verify: true, - useAPIKey: true, + tokenExpiration: 7200, // 2 hours + verify: false, maxLoginAttempts: 2, + lockTime: 600 * 1000, // lock time in ms + useAPIKey: true, + depth: 0, + cookies: { + secure: false, + sameSite: 'lax', + domain: undefined, + }, }, - fields: [], + fields: [ + { + name: 'roles', + label: 'Role', + type: 'select', + options: ['admin', 'editor', 'moderator', 'user', 'viewer'], + defaultValue: 'user', + required: true, + saveToJWT: true, + hasMany: true, + }, + + ], }, ], }); diff --git a/test/auth/int.spec.ts b/test/auth/int.spec.ts new file mode 100644 index 00000000000..74fba81cc5c --- /dev/null +++ b/test/auth/int.spec.ts @@ -0,0 +1,290 @@ +import mongoose from 'mongoose'; +import payload from '../../src'; +import { initPayloadTest } from '../helpers/configHelpers'; +import { slug } from './config'; +import { devUser } from '../credentials'; + +require('isomorphic-fetch'); + +let apiUrl; + +const headers = { + 'Content-Type': 'application/json', +}; +const { email, password } = devUser; + +describe('Auth', () => { + beforeAll(async () => { + const { serverURL } = await initPayloadTest({ __dirname, init: { local: false } }); + apiUrl = `${serverURL}/api`; + }); + + afterAll(async () => { + await mongoose.connection.dropDatabase(); + await mongoose.connection.close(); + await payload.mongoMemoryServer.stop(); + }); + + describe('admin user', () => { + beforeAll(async () => { + await fetch(`${apiUrl}/${slug}/first-register`, { + body: JSON.stringify({ + email, + password, + }), + headers, + method: 'post', + }); + }); + + it('should prevent registering a new first user', async () => { + const response = await fetch(`${apiUrl}/${slug}/first-register`, { + body: JSON.stringify({ + email: '[email protected]', + password: 'get-out', + }), + headers, + method: 'post', + }); + + expect(response.status).toBe(403); + }); + + it('should login a user successfully', async () => { + const response = await fetch(`${apiUrl}/${slug}/login`, { + body: JSON.stringify({ + email, + password, + }), + headers, + method: 'post', + }); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data.token).toBeDefined(); + }); + + describe('logged in', () => { + let token: string | undefined; + beforeAll(async () => { + const response = await fetch(`${apiUrl}/${slug}/login`, { + body: JSON.stringify({ + email, + password, + }), + headers, + method: 'post', + }); + + const data = await response.json(); + token = data.token; + }); + + it('should return a logged in user from /me', async () => { + const response = await fetch(`${apiUrl}/${slug}/me`, { + headers: { + ...headers, + Authorization: `JWT ${token}`, + }, + }); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data.user.email).toBeDefined(); + }); + + it('should refresh a token and reset its expiration', async () => { + const response = await fetch(`${apiUrl}/${slug}/refresh-token`, { + method: 'post', + headers: { + Authorization: `JWT ${token}`, + }, + }); + + const data = await response.json(); + + expect(response.status).toBe(200); + expect(data.refreshedToken).toBeDefined(); + }); + + it('should allow a user to be created', async () => { + const response = await fetch(`${apiUrl}/${slug}`, { + body: JSON.stringify({ + email: '[email protected]', + password, + roles: ['editor'], + }), + headers: { + Authorization: `JWT ${token}`, + 'Content-Type': 'application/json', + }, + method: 'post', + }); + + const data = await response.json(); + + expect(response.status).toBe(201); + expect(data).toHaveProperty('message'); + expect(data).toHaveProperty('doc'); + + const { doc } = data; + + expect(doc).toHaveProperty('email'); + expect(doc).toHaveProperty('createdAt'); + expect(doc).toHaveProperty('roles'); + }); + + it.skip('should allow verification of a user', async () => { + const emailToVerify = '[email protected]'; + const response = await fetch(`${apiUrl}/public-users`, { + body: JSON.stringify({ + email: emailToVerify, + password, + roles: ['editor'], + }), + headers: { + Authorization: `JWT ${token}`, + 'Content-Type': 'application/json', + }, + method: 'post', + }); + + expect(response.status).toBe(201); + // const client = await MongoClient.connect(`${mongoURL}:${mongoPort}`, { + // useUnifiedTopology: true, + // }); + + // const db = client.db(mongoDBName); + const { db } = mongoose.connection; + const userResult = await db.collection('public-users').findOne({ email: emailToVerify }); + // @ts-expect-error trust + const { _verified, _verificationToken } = userResult; + + expect(_verified).toBe(false); + expect(_verificationToken).toBeDefined(); + + const verificationResponse = await fetch(`${apiUrl}/public-users/verify/${_verificationToken}`, { + headers: { + 'Content-Type': 'application/json', + }, + method: 'post', + }); + + expect(verificationResponse.status).toBe(200); + + const afterVerifyResult = await db.collection('public-users').findOne({ email: emailToVerify }); + const { _verified: afterVerified, _verificationToken: afterToken } = afterVerifyResult; + expect(afterVerified).toBe(true); + expect(afterToken).toBeUndefined(); + }); + + describe('Account Locking', () => { + const userEmail = '[email protected]'; + + const tryLogin = async () => { + await fetch(`${apiUrl}/${slug}/login`, { + body: JSON.stringify({ + email: userEmail, + password: 'bad', + }), + headers: { + 'Content-Type': 'application/json', + }, + method: 'post', + }); + // expect(loginRes.status).toEqual(401); + }; + + beforeAll(async () => { + const response = await fetch(`${apiUrl}/${slug}/login`, { + body: JSON.stringify({ + email, + password, + }), + headers, + method: 'post', + }); + + const data = await response.json(); + token = data.token; + + // New user to lock + await fetch(`${apiUrl}/${slug}`, { + body: JSON.stringify({ + email: userEmail, + password, + }), + headers: { + 'Content-Type': 'application/json', + Authorization: `JWT ${token}`, + }, + method: 'post', + }); + }); + + it('should lock the user after too many attempts', async () => { + await tryLogin(); + await tryLogin(); + + const userResult = await mongoose.connection.db.collection(slug).findOne<any>({ email: userEmail }); + const { loginAttempts, lockUntil } = userResult; + + expect(loginAttempts).toBe(2); + expect(lockUntil).toBeDefined(); + }); + + it('should unlock account once lockUntil period is over', async () => { + // Lock user + await tryLogin(); + await tryLogin(); + + // set lockUntil + await mongoose.connection.db + .collection(slug) + .findOneAndUpdate({ email: userEmail }, { $set: { lockUntil: Date.now() - 605 * 1000 } }); + + // login + await fetch(`${apiUrl}/${slug}/login`, { + body: JSON.stringify({ + email: userEmail, + password, + }), + headers: { + Authorization: `JWT ${token}`, + 'Content-Type': 'application/json', + }, + method: 'post', + }); + + const userResult = await mongoose.connection.db + .collection(slug) + .findOne<any>({ email: userEmail }); + const { loginAttempts, lockUntil } = userResult; + + expect(loginAttempts).toBe(0); + expect(lockUntil).toBeUndefined(); + }); + }); + }); + + it('should allow forgot-password by email', async () => { + // TODO: Spy on payload sendEmail function + const response = await fetch(`${apiUrl}/${slug}/forgot-password`, { + method: 'post', + body: JSON.stringify({ + email, + }), + headers: { + 'Content-Type': 'application/json', + }, + }); + + // expect(mailSpy).toHaveBeenCalled(); + + expect(response.status).toBe(200); + }); + }); +}); diff --git a/test/auth/payload-types.ts b/test/auth/payload-types.ts index 0315d69a4da..fe69f84827c 100644 --- a/test/auth/payload-types.ts +++ b/test/auth/payload-types.ts @@ -18,10 +18,9 @@ export interface User { email?: string; resetPasswordToken?: string; resetPasswordExpiration?: string; - _verified?: boolean; - _verificationToken?: string; loginAttempts?: number; lockUntil?: string; + roles: ('admin' | 'editor' | 'moderator' | 'user' | 'viewer')[]; createdAt: string; updatedAt: string; }
e116fcfbf57847f1af8afc86ac0ef106d19b1c85
2023-10-13 22:14:45
Jacob Fletcher
docs: updates references of master to main
false
updates references of master to main
docs
diff --git a/docs/admin/components.mdx b/docs/admin/components.mdx index 107f73edc6a..5cee9d99f80 100644 --- a/docs/admin/components.mdx +++ b/docs/admin/components.mdx @@ -129,7 +129,7 @@ To add a _new_ view to the Admin Panel, simply add another key to the `views` ob } ``` -_For more examples regarding how to customize components, look at the following [examples](https://github.com/payloadcms/payload/tree/master/test/admin/components)._ +_For more examples regarding how to customize components, look at the following [examples](https://github.com/payloadcms/payload/tree/main/test/admin/components)._ For help on how to build your own custom view components, see [building a custom view component](#building-a-custom-view-component). @@ -399,12 +399,12 @@ Your custom view components will be given all the props that a React Router `<Ro #### Example -You can find examples of custom views in the [Payload source code `/test/admin/components/views` folder](https://github.com/payloadcms/payload/tree/master/test/admin/components/views). There, you'll find two custom views: +You can find examples of custom views in the [Payload source code `/test/admin/components/views` folder](https://github.com/payloadcms/payload/tree/main/test/admin/components/views). There, you'll find two custom views: 1. A custom view that uses the `DefaultTemplate`, which is the built-in Payload template that displays the sidebar and "eyebrow nav" 1. A custom view that uses the `MinimalTemplate` - which is just a centered template used for things like logging in or out -To see how to pass in your custom views to create custom views of your own, take a look at the `admin.components.views` property of the [Payload test admin config](https://github.com/payloadcms/payload/blob/master/test/admin/config.ts). +To see how to pass in your custom views to create custom views of your own, take a look at the `admin.components.views` property of the [Payload test admin config](https://github.com/payloadcms/payload/blob/main/test/admin/config.ts). ### Fields
304ecd29acad105cef54af8facde110d0c33bc56
2024-11-22 00:39:08
Patrik
docs: removes public demo references (#9408)
false
removes public demo references (#9408)
docs
diff --git a/docs/configuration/collections.mdx b/docs/configuration/collections.mdx index 59f07480604..bd800f524d6 100644 --- a/docs/configuration/collections.mdx +++ b/docs/configuration/collections.mdx @@ -52,7 +52,7 @@ export const Posts: CollectionConfig = { <Banner type="success"> <strong>Reminder:</strong> - For a more complex example, see the [Public Demo](https://github.com/payloadcms/public-demo) source code on GitHub, or the [Templates](https://github.com/payloadcms/payload/tree/main/templates) and [Examples](https://github.com/payloadcms/payload/tree/main/examples) directories in the Payload repository. + For more complex examples, see the [Templates](https://github.com/payloadcms/payload/tree/main/templates) and [Examples](https://github.com/payloadcms/payload/tree/main/examples) directories in the Payload repository. </Banner> The following options are available: diff --git a/docs/configuration/globals.mdx b/docs/configuration/globals.mdx index 9f9cd8c8c2b..f8892c60b73 100644 --- a/docs/configuration/globals.mdx +++ b/docs/configuration/globals.mdx @@ -60,7 +60,7 @@ export const Nav: GlobalConfig = { <Banner type="success"> <strong>Reminder:</strong> - For a more complex example, see the [Public Demo](https://github.com/payloadcms/public-demo) source code on GitHub, or the [Templates](https://github.com/payloadcms/payload/tree/main/templates) and [Examples](https://github.com/payloadcms/payload/tree/main/examples) directories in the Payload repository. + For more complex examples, see the [Templates](https://github.com/payloadcms/payload/tree/main/templates) and [Examples](https://github.com/payloadcms/payload/tree/main/examples) directories in the Payload repository. </Banner> The following options are available: diff --git a/docs/configuration/overview.mdx b/docs/configuration/overview.mdx index 540cd8e47cb..e01656510f8 100644 --- a/docs/configuration/overview.mdx +++ b/docs/configuration/overview.mdx @@ -58,7 +58,7 @@ export default buildConfig({ <Banner type="success"> <strong>Note:</strong> - For a more complex example, see the [Public Demo](https://github.com/payloadcms/public-demo) source code on GitHub, or the [Templates](https://github.com/payloadcms/payload/tree/main/templates) and [Examples](https://github.com/payloadcms/payload/tree/main/examples) directories in the Payload repository. + For more complex examples, see the [Templates](https://github.com/payloadcms/payload/tree/main/templates) and [Examples](https://github.com/payloadcms/payload/tree/main/examples) directories in the Payload repository. </Banner> The following options are available:
d58c3bd3d147ee08eb0f4094c7d75a299af1bac7
2024-02-23 23:49:26
Jarrod Flesch
chore: adds turbo alias paths
false
adds turbo alias paths
chore
diff --git a/next.config.js b/next.config.js index 5edfc405b3c..ee0c11b19dd 100644 --- a/next.config.js +++ b/next.config.js @@ -11,13 +11,19 @@ const nextConfig = { '**/*': ['drizzle-kit', 'drizzle-kit/utils'], }, serverComponentsExternalPackages: ['drizzle-kit', 'drizzle-kit/utils', 'pino', 'pino-pretty'], + turbo: { + resolveAlias: { + '@payloadcms/ui/scss': path.resolve(__dirname, './packages/ui/src/scss/styles.scss'), + 'payload-config': path.resolve(__dirname, process.env.PAYLOAD_CONFIG_PATH), + }, + }, }, reactStrictMode: false, // typescript: { // ignoreBuildErrors: true, // }, + webpack: (config) => { - console.log(process.env.PAYLOAD_CONFIG_PATH) return { ...config, externals: [
727fbeceb4b93936ca08d0ca48ac0d2beb1ce96e
2021-11-29 19:03:20
James
fix: #373
false
#373
fix
diff --git a/src/collections/operations/delete.ts b/src/collections/operations/delete.ts index 091acbe401d..ed442ec26cb 100644 --- a/src/collections/operations/delete.ts +++ b/src/collections/operations/delete.ts @@ -5,11 +5,11 @@ import { PayloadRequest } from '../../express/types'; import sanitizeInternalFields from '../../utilities/sanitizeInternalFields'; import { NotFound, Forbidden, ErrorDeletingFile } from '../../errors'; import executeAccess from '../../auth/executeAccess'; -import fileOrDocExists from '../../uploads/fileOrDocExists'; import { BeforeOperationHook, Collection } from '../config/types'; import { Document, Where } from '../../types'; import { hasWhereAccessResult } from '../../auth/types'; import { FileData } from '../../uploads/types'; +import fileExists from '../../uploads/fileExists'; export type Arguments = { depth?: number @@ -106,7 +106,7 @@ async function deleteQuery(incomingArgs: Arguments): Promise<Document> { const fileToDelete = `${staticPath}/${resultToDelete.filename}`; - if (await fileOrDocExists(Model, staticPath, resultToDelete.filename)) { + if (await fileExists(fileToDelete)) { fs.unlink(fileToDelete, (err) => { if (err) { throw new ErrorDeletingFile(); @@ -116,8 +116,9 @@ async function deleteQuery(incomingArgs: Arguments): Promise<Document> { if (resultToDelete.sizes) { Object.values(resultToDelete.sizes).forEach(async (size: FileData) => { - if (await fileOrDocExists(Model, staticPath, size.filename)) { - fs.unlink(`${staticPath}/${size.filename}`, (err) => { + const sizeToDelete = `${staticPath}/${size.filename}`; + if (await fileExists(sizeToDelete)) { + fs.unlink(sizeToDelete, (err) => { if (err) { throw new ErrorDeletingFile(); } diff --git a/src/uploads/docWithFilenameExists.ts b/src/uploads/docWithFilenameExists.ts new file mode 100644 index 00000000000..209b2ef772e --- /dev/null +++ b/src/uploads/docWithFilenameExists.ts @@ -0,0 +1,10 @@ +import { CollectionModel } from '../collections/config/types'; + +const docWithFilenameExists = async (Model: CollectionModel, path: string, filename: string): Promise<boolean> => { + const doc = await Model.findOne({ filename }); + if (doc) return true; + + return false; +}; + +export default docWithFilenameExists; diff --git a/src/uploads/fileOrDocExists.ts b/src/uploads/fileOrDocExists.ts deleted file mode 100644 index 4bd2d8a61e7..00000000000 --- a/src/uploads/fileOrDocExists.ts +++ /dev/null @@ -1,20 +0,0 @@ -import fs from 'fs'; -import { promisify } from 'util'; -import { CollectionModel } from '../collections/config/types'; - -const stat = promisify(fs.stat); - -const fileOrDocExists = async (Model: CollectionModel, path: string, filename: string): Promise<boolean> => { - try { - const doc = await Model.findOne({ filename }); - if (doc) return true; - - await stat(`${path}/${filename}`); - - return true; - } catch (err) { - return false; - } -}; - -export default fileOrDocExists; diff --git a/src/uploads/getSafeFilename.ts b/src/uploads/getSafeFilename.ts index 298a24f446e..5b31ba3761d 100644 --- a/src/uploads/getSafeFilename.ts +++ b/src/uploads/getSafeFilename.ts @@ -1,6 +1,7 @@ import sanitize from 'sanitize-filename'; import { CollectionModel } from '../collections/config/types'; -import fileOrDocExists from './fileOrDocExists'; +import docWithFilenameExists from './docWithFilenameExists'; +import fileExists from './fileExists'; const incrementName = (name: string) => { const extension = name.split('.').pop(); @@ -24,7 +25,7 @@ async function getSafeFileName(Model: CollectionModel, staticPath: string, desir let modifiedFilename = desiredFilename; // eslint-disable-next-line no-await-in-loop - while (await fileOrDocExists(Model, staticPath, modifiedFilename)) { + while (await docWithFilenameExists(Model, staticPath, modifiedFilename) || await fileExists(`${staticPath}/${modifiedFilename}`)) { modifiedFilename = incrementName(modifiedFilename); } return modifiedFilename;
9f8ac06659e7648117790b1968b140874aa7e4bd
2024-03-25 20:06:52
Alessio Gravili
fix: already-sanitized fields were sanitized twice in buildFieldSchemaMap
false
already-sanitized fields were sanitized twice in buildFieldSchemaMap
fix
diff --git a/packages/next/src/utilities/buildFieldSchemaMap/traverseFields.ts b/packages/next/src/utilities/buildFieldSchemaMap/traverseFields.ts index e63dc75fbd6..2cb94dfb568 100644 --- a/packages/next/src/utilities/buildFieldSchemaMap/traverseFields.ts +++ b/packages/next/src/utilities/buildFieldSchemaMap/traverseFields.ts @@ -1,6 +1,5 @@ import type { Field, SanitizedConfig } from 'payload/types' -import { sanitizeFields } from 'payload/config' import { tabHasName } from 'payload/types' import type { FieldSchemaMap } from './types.js' @@ -21,16 +20,10 @@ export const traverseFields = ({ validRelationships, }: Args) => { fields.map((field) => { - let fieldsToSet switch (field.type) { case 'group': case 'array': - fieldsToSet = sanitizeFields({ - config, - fields: field.fields, - validRelationships, - }) - schemaMap.set(`${schemaPath}.${field.name}`, fieldsToSet) + schemaMap.set(`${schemaPath}.${field.name}`, field.fields) traverseFields({ config, @@ -55,12 +48,8 @@ export const traverseFields = ({ case 'blocks': field.blocks.map((block) => { const blockSchemaPath = `${schemaPath}.${field.name}.${block.slug}` - fieldsToSet = sanitizeFields({ - config, - fields: [...block.fields, { name: 'blockName', type: 'text' }], - validRelationships, - }) - schemaMap.set(blockSchemaPath, fieldsToSet) + + schemaMap.set(blockSchemaPath, block.fields) traverseFields({ config, @@ -88,12 +77,7 @@ export const traverseFields = ({ const tabSchemaPath = tabHasName(tab) ? `${schemaPath}.${tab.name}` : schemaPath if (tabHasName(tab)) { - fieldsToSet = sanitizeFields({ - config, - fields: tab.fields, - validRelationships, - }) - schemaMap.set(tabSchemaPath, fieldsToSet) + schemaMap.set(tabSchemaPath, tab.fields) } traverseFields({ diff --git a/packages/richtext-lexical/src/field/features/blocks/component/BlockContent.tsx b/packages/richtext-lexical/src/field/features/blocks/component/BlockContent.tsx index 1ab5e985905..e53c2269707 100644 --- a/packages/richtext-lexical/src/field/features/blocks/component/BlockContent.tsx +++ b/packages/richtext-lexical/src/field/features/blocks/component/BlockContent.tsx @@ -37,7 +37,9 @@ type Props = { formData: BlockFields formSchema: FieldMap nodeKey: string + path: string reducedBlock: ReducedBlock + schemaPath: string } /** @@ -52,7 +54,9 @@ export const BlockContent: React.FC<Props> = (props) => { formData, formSchema, nodeKey, + path, reducedBlock: { labels }, + schemaPath, } = props const { i18n } = useTranslation() @@ -236,9 +240,9 @@ export const BlockContent: React.FC<Props> = (props) => { fieldMap={Array.isArray(formSchema) ? formSchema : []} forceRender margins="small" - path="" + path={path} readOnly={false} - schemaPath="" + schemaPath={schemaPath} /> </Collapsible> diff --git a/packages/richtext-lexical/src/field/features/blocks/component/index.tsx b/packages/richtext-lexical/src/field/features/blocks/component/index.tsx index 757df914311..3bcf07b568b 100644 --- a/packages/richtext-lexical/src/field/features/blocks/component/index.tsx +++ b/packages/richtext-lexical/src/field/features/blocks/component/index.tsx @@ -42,7 +42,7 @@ export const BlockComponent: React.FC<Props> = (props) => { const config = useConfig() const submitted = useFormSubmitted() const { id } = useDocumentInfo() - const { schemaPath } = useFieldProps() + const { path, schemaPath } = useFieldProps() const { editorConfig, field: parentLexicalRichTextField } = useEditorConfigContext() const [initialState, setInitialState] = useState<FormState | false>(false) @@ -137,7 +137,9 @@ export const BlockComponent: React.FC<Props> = (props) => { formData={formData} formSchema={Array.isArray(fieldMap) ? fieldMap : []} nodeKey={nodeKey} + path={`${path}.feature.blocks.${formData.blockType}`} reducedBlock={reducedBlock} + schemaPath={schemaFieldsPath} /> </Form> )
14400d1cb9e149f32d85f9211c2c9cef798c1495
2024-04-25 05:18:58
James
chore: functional create-first-user
false
functional create-first-user
chore
diff --git a/packages/next/src/routes/rest/buildFormState.ts b/packages/next/src/routes/rest/buildFormState.ts index d88260277ea..61664bdf8c5 100644 --- a/packages/next/src/routes/rest/buildFormState.ts +++ b/packages/next/src/routes/rest/buildFormState.ts @@ -216,6 +216,17 @@ export const buildFormState = async ({ req }: { req: PayloadRequest }) => { result.file = formState.file } + if ( + collectionSlug && + req.payload.collections[collectionSlug]?.config?.auth && + !req.payload.collections[collectionSlug].config.auth.disableLocalStrategy && + formState + ) { + if (formState.password) result.password = formState.password + if (formState.email) result.email = formState.email + if (formState.password) result.password = formState.password + } + return Response.json(result, { headers, status: httpStatus.OK, diff --git a/packages/next/src/views/CreateFirstUser/index.client.tsx b/packages/next/src/views/CreateFirstUser/index.client.tsx index 77643181740..2fa2a1470be 100644 --- a/packages/next/src/views/CreateFirstUser/index.client.tsx +++ b/packages/next/src/views/CreateFirstUser/index.client.tsx @@ -1,6 +1,5 @@ 'use client' import type { FormProps } from '@payloadcms/ui/forms/Form' -import type { FieldMap } from '@payloadcms/ui/utilities/buildComponentMap' import type { FormState } from 'payload/types' import { ConfirmPassword } from '@payloadcms/ui/fields/ConfirmPassword' diff --git a/packages/next/src/views/CreateFirstUser/index.scss b/packages/next/src/views/CreateFirstUser/index.scss index 26ab1e9ed1a..836127681de 100644 --- a/packages/next/src/views/CreateFirstUser/index.scss +++ b/packages/next/src/views/CreateFirstUser/index.scss @@ -1,15 +1,5 @@ .create-first-user { - display: flex; - align-items: center; - flex-wrap: wrap; - min-height: 100vh; - - &__wrap { - width: 100%; - margin: 0 auto var(--base); - - svg { - width: 100%; - } + > form > .field-type { + margin-bottom: var(--base); } } diff --git a/packages/next/src/views/CreateFirstUser/index.tsx b/packages/next/src/views/CreateFirstUser/index.tsx index aff14a7a2e9..834ca3bb7b8 100644 --- a/packages/next/src/views/CreateFirstUser/index.tsx +++ b/packages/next/src/views/CreateFirstUser/index.tsx @@ -54,10 +54,10 @@ export const CreateFirstUserView: React.FC<AdminViewProps> = async ({ initPageRe }) return ( - <React.Fragment> + <div className="create-first-user"> <h1>{req.t('general:welcome')}</h1> <p>{req.t('authentication:beginCreateFirstUser')}</p> <CreateFirstUserClient initialState={formState} userSlug={userSlug} /> - </React.Fragment> + </div> ) }
2bbb02b9c038c7282ad647970c8b9e2100151c03
2024-08-28 00:11:47
Elliot DeNolf
chore(scripts): add package count to publish script [skip ci]
false
add package count to publish script [skip ci]
chore
diff --git a/scripts/release.ts b/scripts/release.ts index ebb09be0cd1..9f2fce8033e 100755 --- a/scripts/release.ts +++ b/scripts/release.ts @@ -38,13 +38,13 @@ const { tag = 'latest', } = args -const logPrefix = dryRun ? chalk.bold.magenta('[dry-run] >') : '' +const LOG_PREFIX = dryRun ? chalk.bold.magenta('[dry-run] >') : '' const cmdRunner = (dryRun: boolean, gitTag: boolean) => (cmd: string, execOpts: ExecSyncOptions) => { const isGitCommand = cmd.startsWith('git') if (dryRun || (isGitCommand && !gitTag)) { - console.log(logPrefix, cmd) + console.log(LOG_PREFIX, cmd) } else { execSync(cmd, execOpts) } @@ -53,7 +53,7 @@ const cmdRunner = const cmdRunnerAsync = (dryRun: boolean) => async (cmd: string, args: string[], options?: execa.Options) => { if (dryRun) { - console.log(logPrefix, cmd, args.join(' ')) + console.log(LOG_PREFIX, cmd, args.join(' ')) return { exitCode: 0 } } else { return await execa(cmd, args, options ?? { stdio: 'inherit' }) @@ -123,7 +123,7 @@ async function main() { } // Preview/Update changelog - header(`${logPrefix}📝 Updating changelog...`) + header(`${LOG_PREFIX}📝 Updating changelog...`) const { changelog: changelogContent, releaseNotes, @@ -170,7 +170,7 @@ async function main() { } // Increment all package versions - header(`${logPrefix}📦 Updating package.json versions...`) + header(`${LOG_PREFIX}📦 Updating package.json versions...`) await Promise.all( packageDetails.map(async (pkg) => { const packageJson = await fse.readJSON(`${pkg.packagePath}/package.json`) @@ -182,7 +182,7 @@ async function main() { ) // Set version in root package.json - header(`${logPrefix}📦 Updating root package.json...`) + header(`${LOG_PREFIX}📦 Updating root package.json...`) const rootPackageJsonPath = path.resolve(dirname, '../package.json') const rootPackageJson = await fse.readJSON(rootPackageJsonPath) rootPackageJson.version = nextReleaseVersion @@ -209,11 +209,19 @@ async function main() { // Publish only payload to get 5 min auth token packageDetails = packageDetails.filter((p) => p.name !== 'payload') - runCmd(`pnpm publish -C packages/payload --no-git-checks --json --tag ${tag}`, execOpts) + runCmd(`pnpm publish -C packages/payload --no-git-checks --json --tag ${tag}`, { + stdio: ['ignore', 'ignore', 'pipe'], + }) const results: PublishResult[] = [] + const totalPackageCount = packageDetails.length + let packageIndex = 1 // payload already published for (const pkg of packageDetails) { - const res = await publishSinglePackage(pkg, { dryRun }) + packageIndex += 1 + const res = await publishSinglePackage(pkg, { + dryRun, + logPrefix: `${packageIndex}/${totalPackageCount}`, + }) results.push(res) } @@ -247,9 +255,16 @@ main().catch((error) => { process.exit(1) }) -async function publishSinglePackage(pkg: PackageDetails, opts?: { dryRun?: boolean }) { - const { dryRun = false } = opts ?? {} - console.log(chalk.bold(`🚀 ${pkg.name} publishing...`)) +async function publishSinglePackage( + pkg: PackageDetails, + opts: { dryRun?: boolean; logPrefix: string }, +) { + const { dryRun = false, logPrefix = '' } = opts + console.log( + chalk.bold( + `${LOG_PREFIX}${logPrefix ? ` ${logPrefix} ` : logPrefix}🚀 ${pkg.name} publishing...`, + ), + ) try { const cmdArgs = ['publish', '-C', pkg.packagePath, '--no-git-checks', '--json', '--tag', tag] @@ -287,7 +302,7 @@ async function publishSinglePackage(pkg: PackageDetails, opts?: { dryRun?: boole } } - console.log(`${logPrefix} ${chalk.green(`✅ ${pkg.name} published`)}`) + console.log(`${LOG_PREFIX} ${chalk.green(`✅ ${pkg.name} published`)}`) return { name: pkg.name, success: true } } catch (err: unknown) { console.error(err)
4be14a12d03951cb464af63a0d161f6bcc64c45b
2022-09-15 01:12:13
Dan Ribbens
chore(release): v1.1.2
false
v1.1.2
chore
diff --git a/CHANGELOG.md b/CHANGELOG.md index f9de73a3d7e..3fa74286c91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## [1.1.2](https://github.com/payloadcms/payload/compare/v1.1.1...v1.1.2) (2022-09-14) + + +### Bug Fixes + +* resize images without local storage ([1496679](https://github.com/payloadcms/payload/commit/14966796ae0d0bcff8cb56b62e3a21c2de2176da)) +* resize images without local storage ([7b756f3](https://github.com/payloadcms/payload/commit/7b756f3421f02d1ff55374a72396e15e9f3e23d7)) + ## [1.1.1](https://github.com/payloadcms/payload/compare/v1.1.0...v1.1.1) (2022-09-13) diff --git a/package.json b/package.json index a7553bd0b26..85cf44a37f9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "1.1.1", + "version": "1.1.2", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "MIT", "author": {
56667cdc8da088d5b956b799181ed4828725312a
2025-01-21 00:44:49
Germán Jabloñski
fix(ui): fixed many bugs in the WhereBuilder relationship select menu (#10553)
false
fixed many bugs in the WhereBuilder relationship select menu (#10553)
fix
diff --git a/packages/ui/src/elements/WhereBuilder/Condition/Relationship/index.tsx b/packages/ui/src/elements/WhereBuilder/Condition/Relationship/index.tsx index 575a665f38e..0cb2c21a0c2 100644 --- a/packages/ui/src/elements/WhereBuilder/Condition/Relationship/index.tsx +++ b/packages/ui/src/elements/WhereBuilder/Condition/Relationship/index.tsx @@ -76,18 +76,17 @@ export const RelationshipField: React.FC<Props> = (props) => { const fieldToSearch = collection?.admin?.useAsTitle || 'id' const pageIndex = nextPageByRelationshipRef.current.get(relationSlug) - const query: { - depth?: number - limit?: number - page?: number - where: Where - } = { + const where: Where = { + and: [], + } + const query = { depth: 0, limit: maxResultsPerRequest, page: pageIndex, - where: { - and: [], + select: { + [fieldToSearch]: true, }, + where, } if (debouncedSearch) { @@ -115,15 +114,13 @@ export const RelationshipField: React.FC<Props> = (props) => { if (data.docs.length > 0) { addOptions(data, relationSlug) - if (!debouncedSearch) { - if (data.nextPage) { - nextPageByRelationshipRef.current.set(relationSlug, data.nextPage) - } else { - partiallyLoadedRelationshipSlugs.current = - partiallyLoadedRelationshipSlugs.current.filter( - (partiallyLoadedRelation) => partiallyLoadedRelation !== relationSlug, - ) - } + if (data.nextPage) { + nextPageByRelationshipRef.current.set(relationSlug, data.nextPage) + } else { + partiallyLoadedRelationshipSlugs.current = + partiallyLoadedRelationshipSlugs.current.filter( + (partiallyLoadedRelation) => partiallyLoadedRelation !== relationSlug, + ) } } } else { @@ -209,7 +206,9 @@ export const RelationshipField: React.FC<Props> = (props) => { }, [hasMany, hasMultipleRelations, value, options]) const handleInputChange = (input: string) => { + dispatchOptions({ type: 'CLEAR', i18n, required: false }) const relationSlug = partiallyLoadedRelationshipSlugs.current[0] + partiallyLoadedRelationshipSlugs.current = relationSlugs nextPageByRelationshipRef.current.set(relationSlug, 1) setSearch(input) } diff --git a/test/admin/collections/With300Documents.ts b/test/admin/collections/With300Documents.ts new file mode 100644 index 00000000000..57e14d7a6a9 --- /dev/null +++ b/test/admin/collections/With300Documents.ts @@ -0,0 +1,21 @@ +import type { CollectionConfig } from 'payload' + +import { with300DocumentsSlug } from '../slugs.js' + +export const with300Documents: CollectionConfig = { + slug: with300DocumentsSlug, + admin: { + useAsTitle: 'text', + }, + fields: [ + { + name: 'text', + type: 'text', + }, + { + name: 'selfRelation', + type: 'relationship', + relationTo: with300DocumentsSlug, + }, + ], +} diff --git a/test/admin/config.ts b/test/admin/config.ts index b08a1060fc2..4c9ba3a3249 100644 --- a/test/admin/config.ts +++ b/test/admin/config.ts @@ -19,6 +19,7 @@ import { CollectionNotInView } from './collections/NotInView.js' import { Posts } from './collections/Posts.js' import { UploadCollection } from './collections/Upload.js' import { Users } from './collections/Users.js' +import { with300Documents } from './collections/With300Documents.js' import { CustomGlobalViews1 } from './globals/CustomViews1.js' import { CustomGlobalViews2 } from './globals/CustomViews2.js' import { Global } from './globals/Global.js' @@ -155,6 +156,7 @@ export default buildConfigWithDefaults({ Geo, DisableDuplicate, BaseListFilter, + with300Documents, ], globals: [ GlobalHidden, diff --git a/test/admin/e2e/list-view/e2e.spec.ts b/test/admin/e2e/list-view/e2e.spec.ts index d7c5ed36281..30bd2290652 100644 --- a/test/admin/e2e/list-view/e2e.spec.ts +++ b/test/admin/e2e/list-view/e2e.spec.ts @@ -16,7 +16,12 @@ import { import { AdminUrlUtil } from '../../../helpers/adminUrlUtil.js' import { initPayloadE2ENoConfig } from '../../../helpers/initPayloadE2ENoConfig.js' import { customAdminRoutes } from '../../shared.js' -import { customViews1CollectionSlug, geoCollectionSlug, postsCollectionSlug } from '../../slugs.js' +import { + customViews1CollectionSlug, + geoCollectionSlug, + postsCollectionSlug, + with300DocumentsSlug, +} from '../../slugs.js' const { beforeAll, beforeEach, describe } = test @@ -48,6 +53,7 @@ describe('List View', () => { let postsUrl: AdminUrlUtil let baseListFiltersUrl: AdminUrlUtil let customViewsUrl: AdminUrlUtil + let with300DocumentsUrl: AdminUrlUtil let serverURL: string let adminRoutes: ReturnType<typeof getRoutes> @@ -65,6 +71,7 @@ describe('List View', () => { geoUrl = new AdminUrlUtil(serverURL, geoCollectionSlug) postsUrl = new AdminUrlUtil(serverURL, postsCollectionSlug) + with300DocumentsUrl = new AdminUrlUtil(serverURL, with300DocumentsSlug) baseListFiltersUrl = new AdminUrlUtil(serverURL, 'base-list-filters') customViewsUrl = new AdminUrlUtil(serverURL, customViews1CollectionSlug) @@ -608,6 +615,35 @@ describe('List View', () => { }) }) + describe('WhereBuilder', () => { + test('should render where builder', async () => { + await page.goto( + `${with300DocumentsUrl.list}?limit=10&page=1&where%5Bor%5D%5B0%5D%5Band%5D%5B0%5D%5BselfRelation%5D%5Bequals%5D=null`, + ) + const valueField = page.locator('.condition__value') + await valueField.click() + await page.keyboard.type('4') + const options = page.getByRole('option') + expect(options).toHaveCount(10) + for (const option of await options.all()) { + expect(option).toHaveText('4') + } + await page.keyboard.press('Backspace') + await page.keyboard.type('5') + expect(options).toHaveCount(10) + for (const option of await options.all()) { + expect(option).toHaveText('5') + } + // await options.last().scrollIntoViewIfNeeded() + await options.first().hover() + // three times because react-select is not very reliable + await page.mouse.wheel(0, 50) + await page.mouse.wheel(0, 50) + await page.mouse.wheel(0, 50) + expect(options).toHaveCount(20) + }) + }) + describe('table columns', () => { test('should hide field column when field.hidden is true', async () => { await page.goto(postsUrl.list) diff --git a/test/admin/payload-types.ts b/test/admin/payload-types.ts index 4c322d9c8ab..448fcf55008 100644 --- a/test/admin/payload-types.ts +++ b/test/admin/payload-types.ts @@ -27,6 +27,7 @@ export interface Config { geo: Geo; 'disable-duplicate': DisableDuplicate; 'base-list-filters': BaseListFilter; + with300documents: With300Document; 'payload-locked-documents': PayloadLockedDocument; 'payload-preferences': PayloadPreference; 'payload-migrations': PayloadMigration; @@ -49,6 +50,7 @@ export interface Config { geo: GeoSelect<false> | GeoSelect<true>; 'disable-duplicate': DisableDuplicateSelect<false> | DisableDuplicateSelect<true>; 'base-list-filters': BaseListFiltersSelect<false> | BaseListFiltersSelect<true>; + with300documents: With300DocumentsSelect<false> | With300DocumentsSelect<true>; 'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>; 'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>; 'payload-migrations': PayloadMigrationsSelect<false> | PayloadMigrationsSelect<true>; @@ -374,6 +376,17 @@ export interface BaseListFilter { updatedAt: string; createdAt: string; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "with300documents". + */ +export interface With300Document { + id: string; + text?: string | null; + selfRelation?: (string | null) | With300Document; + updatedAt: string; + createdAt: string; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "payload-locked-documents". @@ -444,6 +457,10 @@ export interface PayloadLockedDocument { | ({ relationTo: 'base-list-filters'; value: string | BaseListFilter; + } | null) + | ({ + relationTo: 'with300documents'; + value: string | With300Document; } | null); globalSlug?: string | null; user: { @@ -734,6 +751,16 @@ export interface BaseListFiltersSelect<T extends boolean = true> { updatedAt?: T; createdAt?: T; } +/** + * This interface was referenced by `Config`'s JSON-Schema + * via the `definition` "with300documents_select". + */ +export interface With300DocumentsSelect<T extends boolean = true> { + text?: T; + selfRelation?: T; + updatedAt?: T; + createdAt?: T; +} /** * This interface was referenced by `Config`'s JSON-Schema * via the `definition` "payload-locked-documents_select". diff --git a/test/admin/seed.ts b/test/admin/seed.ts index 3dbe062625c..2bbe5f17c74 100644 --- a/test/admin/seed.ts +++ b/test/admin/seed.ts @@ -11,6 +11,7 @@ import { noApiViewCollectionSlug, postsCollectionSlug, usersCollectionSlug, + with300DocumentsSlug, } from './slugs.js' export const seed = async (_payload) => { @@ -117,6 +118,26 @@ export const seed = async (_payload) => { ], false, ) + + // delete all with300Documents + await _payload.delete({ + collection: with300DocumentsSlug, + where: {}, + }) + + // Create 300 documents of with300Documents + const manyDocumentsPromises: Promise<unknown>[] = Array.from({ length: 300 }, (_, i) => { + const index = (i + 1).toString().padStart(3, '0') + return _payload.create({ + collection: with300DocumentsSlug, + data: { + id: index, + text: `document ${index}`, + }, + }) + }) + + await Promise.all([...manyDocumentsPromises]) } export async function clearAndSeedEverything(_payload: Payload) { diff --git a/test/admin/slugs.ts b/test/admin/slugs.ts index d25fa1ca8ea..2370222b239 100644 --- a/test/admin/slugs.ts +++ b/test/admin/slugs.ts @@ -48,3 +48,4 @@ export const globalSlugs = [ hiddenGlobalSlug, noApiViewGlobalSlug, ] +export const with300DocumentsSlug = 'with300documents'
813c46c86d86f8b0a3ba7280d31f24e844c916b6
2022-09-14 08:36:12
Elliot DeNolf
feat: sort select and relationship fields by default
false
sort select and relationship fields by default
feat
diff --git a/src/admin/components/forms/field-types/Relationship/index.tsx b/src/admin/components/forms/field-types/Relationship/index.tsx index 9d070b7d1ef..a04dfc425df 100644 --- a/src/admin/components/forms/field-types/Relationship/index.tsx +++ b/src/admin/components/forms/field-types/Relationship/index.tsx @@ -47,7 +47,7 @@ const Relationship: React.FC<Props> = (props) => { width, description, condition, - isSortable, + isSortable = true, } = {}, } = props; diff --git a/src/admin/components/forms/field-types/Select/index.tsx b/src/admin/components/forms/field-types/Select/index.tsx index 246066eb0a3..9dfcb20f81c 100644 --- a/src/admin/components/forms/field-types/Select/index.tsx +++ b/src/admin/components/forms/field-types/Select/index.tsx @@ -34,7 +34,7 @@ const Select: React.FC<Props> = (props) => { description, isClearable, condition, - isSortable + isSortable = true, } = {}, } = props;
08f4ebaaf8163a520c1d9869e3cae23d97d424c0
2024-04-08 20:52:05
Jacob Fletcher
fix(ui): adds css specificity to select all
false
adds css specificity to select all
fix
diff --git a/packages/ui/src/elements/SelectAll/index.tsx b/packages/ui/src/elements/SelectAll/index.tsx index edd20d35fb1..cc49e87be42 100644 --- a/packages/ui/src/elements/SelectAll/index.tsx +++ b/packages/ui/src/elements/SelectAll/index.tsx @@ -23,7 +23,7 @@ export const SelectAll: React.FC = () => { checked={ selectAll === SelectAllStatus.AllInPage || selectAll === SelectAllStatus.AllAvailable } - className={`${baseClass}__checkbox`} + className={[baseClass, `${baseClass}__checkbox`].join(' ')} id="select-all" name="select-all" onToggle={() => toggleAll()} diff --git a/packages/ui/src/elements/SelectRow/index.tsx b/packages/ui/src/elements/SelectRow/index.tsx index 36aacc5a5c0..1536ac3332d 100644 --- a/packages/ui/src/elements/SelectRow/index.tsx +++ b/packages/ui/src/elements/SelectRow/index.tsx @@ -15,7 +15,7 @@ export const SelectRow: React.FC = () => { return ( <CheckboxInput checked={selected?.[rowData?.id]} - className={`${baseClass}__checkbox`} + className={[baseClass, `${baseClass}__checkbox`].join(' ')} onToggle={() => setSelection(rowData.id)} /> )
911e902da4a7a0a051d3b91a7c7101a70c04597a
2024-03-10 10:30:26
madaxen86
feat: add support for displaying AVIF images (#5227)
false
add support for displaying AVIF images (#5227)
feat
diff --git a/packages/payload/src/uploads/isImage.ts b/packages/payload/src/uploads/isImage.ts index 431a6be3563..01873bb94d7 100644 --- a/packages/payload/src/uploads/isImage.ts +++ b/packages/payload/src/uploads/isImage.ts @@ -1,5 +1,7 @@ export default function isImage(mimeType: string): boolean { return ( - ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp'].indexOf(mimeType) > -1 + ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp', 'image/avif'].indexOf( + mimeType, + ) > -1 ) }
e7d2bdb45a042d69ef3adc40c1b10e065a0620ec
2022-07-17 22:21:42
James
fix: styles empty version diff row for dark mode
false
styles empty version diff row for dark mode
fix
diff --git a/docs/fields/tabs.mdx b/docs/fields/tabs.mdx index 525b9195d50..433881b37d7 100644 --- a/docs/fields/tabs.mdx +++ b/docs/fields/tabs.mdx @@ -2,8 +2,70 @@ title: Tabs Field label: Tabs order: 170 -desc: Tabs field desc here +desc: The Tabs field is a great way to organize complex editing experiences into specific tab-based areas. keywords: tabs, fields, config, configuration, documentation, Content Management System, cms, headless, javascript, node, react, express --- -Coming soon +<Banner > + The Tabs field is presentational-only and only affects the Admin panel. By using it, you can place fields within a nice layout component that separates certain sub-fields by a tabbed interface. +</Banner> + +![Tabs field type used to separate Hero fields from Page Layout](https://payloadcms.com/images/fields/tabs/tabs.jpg) +*Tabs field type used to separate Hero fields from Page Layout* + +### Config + +| Option | Description | +| ---------------- | ----------- | +| **`tabs`** * | Array of tabs to render within this Tabs field. | +| **`admin`** | Admin-specific configuration. See the [default field admin config](/docs/fields/overview#admin-config) for more details. | + +#### Tab-specific Config + +Each tab has its own required `label` and `fields` array. You can also optionally pass a `description` to render within each individual tab. + +| Option | Description | +| ----------------- | ----------- | +| **`label`** * | The label to render on the tab itself. | +| **`fields`** * | The fields to render within this tab. | +| **`description`** | Optionally render a description within this tab to describe the contents of the tab itself. | + +*\* An asterisk denotes that a property is required.* + +### Example + +`collections/ExampleCollection.js` +```js +{ + slug: 'example-collection', + fields: [ + { + type: 'tabs', // required + tabs: [ // required + { + label: 'Tab One Label', // required + description: 'This will appear within the tab above the fields.' + fields: [ // required + { + name: 'someTextField', + type: 'text', + required: true, + }, + ], + }, + { + label: 'Tab Two Label', // required + fields: [ // required + { + name: 'numberField', + type: 'number', + required: true, + }, + ], + } + ] + + } + ] +} +``` diff --git a/src/admin/components/forms/field-types/Tabs/index.scss b/src/admin/components/forms/field-types/Tabs/index.scss index b853a31d81b..252a4634a3a 100644 --- a/src/admin/components/forms/field-types/Tabs/index.scss +++ b/src/admin/components/forms/field-types/Tabs/index.scss @@ -13,9 +13,7 @@ } &--within-collapsible { - margin-left: calc(#{$baseline} * -1); - margin-right: calc(#{$baseline} * -1); - margin-bottom: 0; + margin: 0 calc(#{$baseline} * -1); .tabs-field__tabs, .tabs-field__content-wrap { diff --git a/src/admin/components/views/Version/RenderFieldsToDiff/fields/styles.ts b/src/admin/components/views/Version/RenderFieldsToDiff/fields/styles.ts index 5d4892e0d84..d20e43f6a0c 100644 --- a/src/admin/components/views/Version/RenderFieldsToDiff/fields/styles.ts +++ b/src/admin/components/views/Version/RenderFieldsToDiff/fields/styles.ts @@ -8,6 +8,7 @@ export const diffStyles = { removedColor: 'var(--theme-error-900)', wordAddedBackground: 'var(--theme-success-200)', wordRemovedBackground: 'var(--theme-error-200)', + emptyLineBackground: 'var(--theme-elevation-50)', }, }, }; diff --git a/test/fields/collections/RichText/index.ts b/test/fields/collections/RichText/index.ts index 18be777ebab..c0a5e57e72f 100644 --- a/test/fields/collections/RichText/index.ts +++ b/test/fields/collections/RichText/index.ts @@ -8,6 +8,9 @@ const RichTextFields: CollectionConfig = { name: 'selectHasMany', hasMany: true, type: 'select', + admin: { + description: 'This select field is rendered here to ensure its options dropdown renders above the rich text toolbar.', + }, options: [ { label: 'Value One', @@ -58,7 +61,7 @@ const RichTextFields: CollectionConfig = { }; export const richTextDoc = { - select: ['one', 'five'], + selectHasMany: ['one', 'five'], richText: [ { children: [
c4269d25d3ce5a3f59c2fa42a96b2adf8c995539
2024-11-17 00:35:50
Jacob Fletcher
fix(next): custom default root views (#9247)
false
custom default root views (#9247)
fix
diff --git a/packages/next/src/views/Account/index.tsx b/packages/next/src/views/Account/index.tsx index 961235a2b56..49608f61d85 100644 --- a/packages/next/src/views/Account/index.tsx +++ b/packages/next/src/views/Account/index.tsx @@ -37,11 +37,7 @@ export const Account: React.FC<AdminViewProps> = async ({ } = initPageResult const { - admin: { - components: { views: { Account: CustomAccountComponent } = {} } = {}, - theme, - user: userSlug, - }, + admin: { theme, user: userSlug }, routes: { api }, serverURL, } = config @@ -142,7 +138,8 @@ export const Account: React.FC<AdminViewProps> = async ({ /> <HydrateAuthProvider permissions={permissions} /> <RenderServerComponent - Component={CustomAccountComponent} + Component={config.admin?.components?.views?.Account?.Component} + Fallback={EditView} importMap={payload.importMap} serverProps={{ i18n, @@ -156,7 +153,6 @@ export const Account: React.FC<AdminViewProps> = async ({ user, }} /> - <EditView /> <AccountClient /> </EditDepthProvider> </DocumentInfoProvider> diff --git a/packages/next/src/views/Dashboard/index.tsx b/packages/next/src/views/Dashboard/index.tsx index b342813c437..9171472a3d4 100644 --- a/packages/next/src/views/Dashboard/index.tsx +++ b/packages/next/src/views/Dashboard/index.tsx @@ -31,8 +31,6 @@ export const Dashboard: React.FC<AdminViewProps> = async ({ visibleEntities, } = initPageResult - const CustomDashboardComponent = config.admin.components?.views?.Dashboard - const collections = config.collections.filter( (collection) => permissions?.collections?.[collection.slug]?.read && @@ -115,7 +113,7 @@ export const Dashboard: React.FC<AdminViewProps> = async ({ Link, locale, }} - Component={CustomDashboardComponent} + Component={config.admin?.components?.views?.Dashboard?.Component} Fallback={DefaultDashboard} importMap={payload.importMap} serverProps={{ diff --git a/packages/payload/src/bin/generateImportMap/parsePayloadComponent.ts b/packages/payload/src/bin/generateImportMap/parsePayloadComponent.ts index 5747f0fb019..03964eb7d61 100644 --- a/packages/payload/src/bin/generateImportMap/parsePayloadComponent.ts +++ b/packages/payload/src/bin/generateImportMap/parsePayloadComponent.ts @@ -7,6 +7,7 @@ export function parsePayloadComponent(PayloadComponent: PayloadComponent): { if (!PayloadComponent) { return null } + const pathAndMaybeExport = typeof PayloadComponent === 'string' ? PayloadComponent : PayloadComponent.path
040f3a34d187fff380a8002cf83b4ed693b29cca
2023-10-10 00:57:26
Elliot DeNolf
chore(release): [email protected]
false
chore
diff --git a/packages/payload/package.json b/packages/payload/package.json index 4eb75dd1a77..bf2dbc9dabf 100644 --- a/packages/payload/package.json +++ b/packages/payload/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "2.0.2", + "version": "2.0.3", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "MIT", "main": "./dist/index.js",
cb7fa00a6f43776e03137038a04732c10522bb5d
2024-08-15 02:10:31
Alessio Gravili
fix: use tsx instead of swc as default bin script transpiler, as swc errors when it encounters 'next/cache' (#7681)
false
use tsx instead of swc as default bin script transpiler, as swc errors when it encounters 'next/cache' (#7681)
fix
diff --git a/docs/admin/components.mdx b/docs/admin/components.mdx index ccab841157a..b87003be2b4 100644 --- a/docs/admin/components.mdx +++ b/docs/admin/components.mdx @@ -145,7 +145,7 @@ Instead, we utilize component paths to reference React Components. This method e When constructing the `ClientConfig`, Payload uses the component paths as keys to fetch the corresponding React Component imports from the Import Map. It then substitutes the `PayloadComponent` with a `MappedComponent`. A `MappedComponent` includes the React Component and additional metadata, such as whether it's a server or a client component and which props it should receive. These components are then rendered through the `<RenderComponent />` component within the Payload Admin Panel. -Import maps are regenerated whenever you modify any element related to component paths. This regeneration occurs at startup and whenever Hot Module Replacement (HMR) runs. If the import maps fail to regenerate during HMR, you can restart your application and execute the `payload generate:importmap` command to manually create a new import map. +Import maps are regenerated whenever you modify any element related to component paths. This regeneration occurs at startup and whenever Hot Module Replacement (HMR) runs. If the import maps fail to regenerate during HMR, you can restart your application and execute the `payload generate:importmap` command to manually create a new import map. If you encounter any errors running this command, see the [Troubleshooting](/docs/beta/local-api/outside-nextjs#troubleshooting) section. ### Component paths in external packages diff --git a/docs/local-api/outside-nextjs.mdx b/docs/local-api/outside-nextjs.mdx index 11073a5d926..de24b5279c0 100644 --- a/docs/local-api/outside-nextjs.mdx +++ b/docs/local-api/outside-nextjs.mdx @@ -61,14 +61,27 @@ payload run src/seed.ts The `payload run` command does two things for you: 1. It loads the environment variables the same way Next.js loads them, eliminating the need for additional dependencies like `dotenv`. The usage of `dotenv` is not recommended, as Next.js loads environment variables differently. By using `payload run`, you ensure consistent environment variable handling across your Payload and Next.js setup. -2. It initializes swc, allowing direct execution of TypeScript files without requiring tools like tsx or ts-node. +2. It initializes tsx, allowing direct execution of TypeScript files manually installing tools like tsx or ts-node. ### Troubleshooting -If you encounter import-related errors, try running the script in TSX mode: +If you encounter import-related errors, you have 2 options: + +#### Option 1: enable swc mode by appending `--use-swc` to the `payload` command: + +Example: +```sh +payload run src/seed.ts --use-swc +``` + +Note: Install @swc-node/register in your project first. While swc mode is faster than the default tsx mode, it might break for some imports. + +#### Option 2: use an alternative runtime like bun + +While we do not guarantee support for alternative runtimes, you are free to use them and disable payloads own transpilation by appending the `--disable-transpilation` flag to the `payload` command: ```sh -payload run src/seed.ts --use-tsx +bunx --bun payload run src/seed.ts --disable-transpile ``` -Note: Install tsx in your project first. Be aware that TSX mode is slower than the default swc mode, so only use it if necessary. +You will need to have bun installed on your system for this to work. diff --git a/packages/graphql/bin.js b/packages/graphql/bin.js index e9bec7ed300..177f6550c5a 100755 --- a/packages/graphql/bin.js +++ b/packages/graphql/bin.js @@ -1,21 +1,54 @@ -#!/usr/bin/env node +#!/usr/bin/env node --no-deprecation -import { register } from 'node:module' import path from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' -// Allow disabling SWC for debugging -if (process.env.DISABLE_SWC !== 'true') { +const useSwc = process.argv.includes('--use-swc') +const disableTranspile = process.argv.includes('--disable-transpile') + +if (disableTranspile) { + // Remove --disable-transpile from arguments + process.argv = process.argv.filter((arg) => arg !== '--disable-transpile') + + const start = async () => { + const { bin } = await import('./dist/bin/index.js') + await bin() + } + + void start() +} else { const filename = fileURLToPath(import.meta.url) const dirname = path.dirname(filename) const url = pathToFileURL(dirname).toString() + '/' - register('@swc-node/register/esm', url) -} + if (!useSwc) { + const start = async () => { + // Use tsx + let tsImport = (await import('tsx/esm/api')).tsImport -const start = async () => { - const { bin } = await import('./dist/bin/index.js') - await bin() -} + const { bin } = await tsImport('./dist/bin/index.js', url) + await bin() + } -void start() + void start() + } else if (useSwc) { + const { register } = await import('node:module') + // Remove --use-swc from arguments + process.argv = process.argv.filter((arg) => arg !== '--use-swc') + + try { + register('@swc-node/register/esm', url) + } catch (_) { + console.error( + '@swc-node/register is not installed. Please install @swc-node/register in your project, if you want to use swc in payload run.', + ) + } + + const start = async () => { + const { bin } = await import('./dist/bin/index.js') + await bin() + } + + void start() + } +} diff --git a/packages/graphql/package.json b/packages/graphql/package.json index f1d09a695e8..70203154594 100644 --- a/packages/graphql/package.json +++ b/packages/graphql/package.json @@ -43,7 +43,7 @@ "dependencies": { "graphql-scalars": "1.22.2", "pluralize": "8.0.0", - "@swc-node/register": "1.10.9", + "tsx": "4.17.0", "ts-essentials": "7.0.3" }, "devDependencies": { diff --git a/packages/payload/bin.js b/packages/payload/bin.js index 9ac3b30a402..177f6550c5a 100755 --- a/packages/payload/bin.js +++ b/packages/payload/bin.js @@ -1,18 +1,14 @@ #!/usr/bin/env node --no-deprecation -import { register } from 'node:module' import path from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' -const useTsx = process.argv.includes('--use-tsx') +const useSwc = process.argv.includes('--use-swc') +const disableTranspile = process.argv.includes('--disable-transpile') -// Allow disabling SWC/TSX for debugging -if (process.env.DISABLE_SWC !== 'true' && !useTsx) { - const filename = fileURLToPath(import.meta.url) - const dirname = path.dirname(filename) - const url = pathToFileURL(dirname).toString() + '/' - - register('@swc-node/register/esm', url) +if (disableTranspile) { + // Remove --disable-transpile from arguments + process.argv = process.argv.filter((arg) => arg !== '--disable-transpile') const start = async () => { const { bin } = await import('./dist/bin/index.js') @@ -20,25 +16,39 @@ if (process.env.DISABLE_SWC !== 'true' && !useTsx) { } void start() -} else if (useTsx) { - // Remove --use-tsx from arguments - process.argv = process.argv.filter((arg) => arg !== '--use-tsx') +} else { + const filename = fileURLToPath(import.meta.url) + const dirname = path.dirname(filename) + const url = pathToFileURL(dirname).toString() + '/' + + if (!useSwc) { + const start = async () => { + // Use tsx + let tsImport = (await import('tsx/esm/api')).tsImport + + const { bin } = await tsImport('./dist/bin/index.js', url) + await bin() + } + + void start() + } else if (useSwc) { + const { register } = await import('node:module') + // Remove --use-swc from arguments + process.argv = process.argv.filter((arg) => arg !== '--use-swc') - const start = async () => { - // Use tsx - let tsImport try { - tsImport = (await import('tsx/esm/api')).tsImport + register('@swc-node/register/esm', url) } catch (_) { console.error( - 'tsx is not installed. Please install tsx in your project, if you want to use tsx in payload run.', + '@swc-node/register is not installed. Please install @swc-node/register in your project, if you want to use swc in payload run.', ) - return } - const { bin } = await tsImport('./dist/bin/index.js', import.meta.url) - await bin() - } + const start = async () => { + const { bin } = await import('./dist/bin/index.js') + await bin() + } - void start() + void start() + } } diff --git a/packages/payload/package.json b/packages/payload/package.json index 978c5e79d2c..8cde6d50195 100644 --- a/packages/payload/package.json +++ b/packages/payload/package.json @@ -86,7 +86,7 @@ "dependencies": { "@next/env": "^15.0.0-canary.104", "@payloadcms/translations": "workspace:*", - "@swc-node/register": "1.10.9", + "tsx": "4.17.0", "ajv": "8.14.0", "bson-objectid": "2.0.4", "ci-info": "^4.0.0", diff --git a/packages/payload/src/bin/index.ts b/packages/payload/src/bin/index.ts index 933c2d146b6..227d9bb56fb 100755 --- a/packages/payload/src/bin/index.ts +++ b/packages/payload/src/bin/index.ts @@ -1,4 +1,5 @@ import minimist from 'minimist' +import { pathToFileURL } from 'node:url' import path from 'path' import type { BinScript } from '../config/types.js' @@ -29,7 +30,7 @@ export const bin = async () => { process.argv = [process.argv[0], process.argv[1], ...args._.slice(2)] try { - await import(absoluteScriptPath) + await import(pathToFileURL(absoluteScriptPath).toString()) } catch (error) { console.error(`Error running script: ${absoluteScriptPath}`) console.error(error) @@ -42,7 +43,7 @@ export const bin = async () => { } const configPath = findConfig() - const configPromise = await import(configPath) + const configPromise = await import(pathToFileURL(configPath).toString()) let config = await configPromise if (config.default) config = await config.default @@ -52,7 +53,7 @@ export const bin = async () => { if (userBinScript) { try { - const script: BinScript = await import(userBinScript.scriptPath) + const script: BinScript = await import(pathToFileURL(userBinScript.scriptPath).toString()) await script(config) } catch (err) { console.log(`Could not find associated bin script for the ${userBinScript.key} command`) diff --git a/packages/payload/src/config/find.ts b/packages/payload/src/config/find.ts index e4745ff83e6..1671da8e6e7 100644 --- a/packages/payload/src/config/find.ts +++ b/packages/payload/src/config/find.ts @@ -22,10 +22,7 @@ const getTSConfigPaths = (): { const rootConfigDir = path.resolve(tsConfigDir, tsConfig.compilerOptions.baseUrl || '') const srcPath = tsConfig.compilerOptions?.rootDir || path.resolve(process.cwd(), 'src') const outPath = tsConfig.compilerOptions?.outDir || path.resolve(process.cwd(), 'dist') - let configPath = path.resolve( - rootConfigDir, - tsConfig.compilerOptions?.paths?.['@payload-config']?.[0], - ) + let configPath = tsConfig.compilerOptions?.paths?.['@payload-config']?.[0] if (configPath) { configPath = path.resolve(rootConfigDir, configPath) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index aa62450b8f7..25a0d7f02c5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -549,9 +549,6 @@ importers: packages/graphql: dependencies: - '@swc-node/register': - specifier: 1.10.9 - version: 1.10.9(@swc/[email protected](@swc/[email protected]))(@swc/[email protected])([email protected]) graphql: specifier: ^16.8.1 version: 16.9.0 @@ -564,6 +561,9 @@ importers: ts-essentials: specifier: 7.0.3 version: 7.0.3([email protected]) + tsx: + specifier: 4.17.0 + version: 4.17.0 devDependencies: '@payloadcms/eslint-config': specifier: workspace:* @@ -727,9 +727,6 @@ importers: '@payloadcms/translations': specifier: workspace:* version: link:../translations - '@swc-node/register': - specifier: 1.10.9 - version: 1.10.9(@swc/[email protected](@swc/[email protected]))(@swc/[email protected])([email protected]) ajv: specifier: 8.14.0 version: 8.14.0 @@ -796,6 +793,9 @@ importers: ts-essentials: specifier: 7.0.3 version: 7.0.3([email protected]) + tsx: + specifier: 4.17.0 + version: 4.17.0 uuid: specifier: 10.0.0 version: 10.0.0 @@ -7096,7 +7096,6 @@ packages: [email protected]: resolution: {integrity: sha512-Aj5cQ5uk/6fHdmeW0TiXK42FqUlwx7ytmMLPSaUQPin5HKKKuUPD62MAbN4OEweGBBI7q1BekoEN4gPUEL6MZA==} - cpu: [x64, arm64, wasm32] os: [darwin, linux, win32] [email protected]:
e1a903d03e36a93c3f8d4258a9a4e1bae831ed3d
2022-08-08 04:56:59
James
chore: fixes payload dependency requirement
false
fixes payload dependency requirement
chore
diff --git a/README.md b/README.md index a4b68853114..cc026d8ff85 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ This repository contains the officially supported Payload Cloud Storage plugin. #### Requirements -- Payload version `1.0.16` or higher is required +- Payload version `1.0.19` or higher is required ## Usage
9c77af0d67b7fa0f9e9f0d9d2edd77d64650ee5d
2024-02-13 04:39:01
Jacob Fletcher
chore(next): allows resolved config promise to be thread through initPage (#5071)
false
allows resolved config promise to be thread through initPage (#5071)
chore
diff --git a/packages/next/src/layouts/Admin/index.tsx b/packages/next/src/layouts/Admin/index.tsx index 8b376aeb077..48686fceda3 100644 --- a/packages/next/src/layouts/Admin/index.tsx +++ b/packages/next/src/layouts/Admin/index.tsx @@ -12,15 +12,15 @@ export const metadata = { export const AdminLayout = async ({ children, - config: configPromise, + config, }: { children: React.ReactNode - config: Promise<SanitizedConfig> + config: Promise<SanitizedConfig> | SanitizedConfig }) => { - const { user, permissions, i18n } = await initPage({ configPromise }) + const { user, permissions, i18n } = await initPage({ config }) return ( - <DefaultTemplate config={configPromise} user={user} permissions={permissions} i18n={i18n}> + <DefaultTemplate config={config} user={user} permissions={permissions} i18n={i18n}> {children} </DefaultTemplate> ) diff --git a/packages/next/src/layouts/Document/index.tsx b/packages/next/src/layouts/Document/index.tsx index bcd549910d7..823e17170d9 100644 --- a/packages/next/src/layouts/Document/index.tsx +++ b/packages/next/src/layouts/Document/index.tsx @@ -22,7 +22,7 @@ export const DocumentLayout = async ({ globalSlug?: string }) => { const { config, collectionConfig, globalConfig, i18n } = await initPage({ - configPromise, + config: configPromise, collectionSlug, globalSlug, }) diff --git a/packages/next/src/pages/Account/index.tsx b/packages/next/src/pages/Account/index.tsx index b88cf055338..386fb9ca1ba 100644 --- a/packages/next/src/pages/Account/index.tsx +++ b/packages/next/src/pages/Account/index.tsx @@ -20,7 +20,7 @@ export const Account = async ({ searchParams: { [key: string]: string | string[] | undefined } }) => { const { config, payload, permissions, user, i18n, locale } = await initPage({ - configPromise, + config: configPromise, redirectUnauthenticatedUser: true, }) diff --git a/packages/next/src/pages/CollectionList/index.tsx b/packages/next/src/pages/CollectionList/index.tsx index c434d1ee351..29f8f9af80b 100644 --- a/packages/next/src/pages/CollectionList/index.tsx +++ b/packages/next/src/pages/CollectionList/index.tsx @@ -21,7 +21,7 @@ export const CollectionList = async ({ searchParams: { [key: string]: string | string[] | undefined } }) => { const { config, payload, permissions, user, collectionConfig } = await initPage({ - configPromise, + config: configPromise, redirectUnauthenticatedUser: true, collectionSlug, }) diff --git a/packages/next/src/pages/CreateFirstUser/index.tsx b/packages/next/src/pages/CreateFirstUser/index.tsx index 432866aa89e..b62d763d060 100644 --- a/packages/next/src/pages/CreateFirstUser/index.tsx +++ b/packages/next/src/pages/CreateFirstUser/index.tsx @@ -47,7 +47,7 @@ export const CreateFirstUser: React.FC<{ i18n: { t }, payload, } = await initPage({ - configPromise, + config: configPromise, redirectUnauthenticatedUser: false, }) diff --git a/packages/next/src/pages/Dashboard/index.tsx b/packages/next/src/pages/Dashboard/index.tsx index 9f31961ef25..dbab9140407 100644 --- a/packages/next/src/pages/Dashboard/index.tsx +++ b/packages/next/src/pages/Dashboard/index.tsx @@ -11,7 +11,7 @@ export const Dashboard = async ({ config: Promise<SanitizedConfig> }) => { const { config, user, permissions } = await initPage({ - configPromise, + config: configPromise, redirectUnauthenticatedUser: true, }) diff --git a/packages/next/src/pages/Document/index.tsx b/packages/next/src/pages/Document/index.tsx index 1c3a6e50791..ca3ded2a6e2 100644 --- a/packages/next/src/pages/Document/index.tsx +++ b/packages/next/src/pages/Document/index.tsx @@ -33,7 +33,7 @@ export const Document = async ({ collection?: string global?: string } - config: Promise<SanitizedConfig> + config: Promise<SanitizedConfig> | SanitizedConfig searchParams: { [key: string]: string | string[] | undefined } }) => { const collectionSlug = params.collection @@ -45,7 +45,7 @@ export const Document = async ({ const { config, payload, permissions, user, collectionConfig, globalConfig, locale, i18n } = await initPage({ - configPromise, + config: configPromise, redirectUnauthenticatedUser: true, collectionSlug, globalSlug, diff --git a/packages/next/src/pages/ForgotPassword/index.tsx b/packages/next/src/pages/ForgotPassword/index.tsx index aeb703d611d..03b8d224a25 100644 --- a/packages/next/src/pages/ForgotPassword/index.tsx +++ b/packages/next/src/pages/ForgotPassword/index.tsx @@ -30,7 +30,7 @@ export const generateMetadata = async ({ export const ForgotPassword: React.FC<{ config: Promise<SanitizedConfig> }> = async ({ config: configPromise }) => { - const { config, user, i18n } = await initPage({ configPromise }) + const { config, user, i18n } = await initPage({ config: configPromise }) const { admin: { user: userSlug }, diff --git a/packages/next/src/pages/Login/index.tsx b/packages/next/src/pages/Login/index.tsx index 072f78ece11..bb7d9e5d060 100644 --- a/packages/next/src/pages/Login/index.tsx +++ b/packages/next/src/pages/Login/index.tsx @@ -8,9 +8,10 @@ import { Metadata } from 'next' import { initPage } from '../../utilities/initPage' import { redirect } from 'next/navigation' import { getNextT } from '../../utilities/getNextT' -import './index.scss' import { LoginForm } from './LoginForm' +import './index.scss' + const baseClass = 'login' export const generateMetadata = async ({ @@ -34,7 +35,7 @@ export const Login: React.FC<{ config: Promise<SanitizedConfig> searchParams: { [key: string]: string | string[] | undefined } }> = async ({ config: configPromise, searchParams }) => { - const { config, user } = await initPage({ configPromise }) + const { config, user } = await initPage({ config: configPromise }) const { admin: { components: { afterLogin, beforeLogin } = {}, user: userSlug }, diff --git a/packages/next/src/pages/ResetPassword/index.tsx b/packages/next/src/pages/ResetPassword/index.tsx index 3f8b0d4a1a3..45935231c52 100644 --- a/packages/next/src/pages/ResetPassword/index.tsx +++ b/packages/next/src/pages/ResetPassword/index.tsx @@ -41,7 +41,7 @@ export const ResetPassword: React.FC<{ config: Promise<SanitizedConfig> token: string }> = async ({ config: configPromise, token }) => { - const { config, user, i18n } = await initPage({ configPromise }) + const { config, user, i18n } = await initPage({ config: configPromise }) const { admin: { logoutRoute, user: userSlug }, diff --git a/packages/next/src/pages/Verify/index.tsx b/packages/next/src/pages/Verify/index.tsx index 51d2f4eb807..a395516d754 100644 --- a/packages/next/src/pages/Verify/index.tsx +++ b/packages/next/src/pages/Verify/index.tsx @@ -35,7 +35,7 @@ export const Verify: React.FC<{ config: configPromise, // token }) => { - const { config, user, i18n } = await initPage({ configPromise }) + const { config, user, i18n } = await initPage({ config: configPromise }) const { admin: { user: userSlug }, diff --git a/packages/next/src/utilities/auth.ts b/packages/next/src/utilities/auth.ts index e14a180295e..efd3146c260 100644 --- a/packages/next/src/utilities/auth.ts +++ b/packages/next/src/utilities/auth.ts @@ -10,7 +10,7 @@ export const auth = cache( cookies, }: { headers: any - config: Promise<SanitizedConfig> + config: SanitizedConfig | Promise<SanitizedConfig> cookies: Map<string, string> }) => { const payload = await getPayload({ config }) diff --git a/packages/next/src/utilities/initPage.ts b/packages/next/src/utilities/initPage.ts index 435be683693..725dbd0a0b9 100644 --- a/packages/next/src/utilities/initPage.ts +++ b/packages/next/src/utilities/initPage.ts @@ -16,13 +16,13 @@ import { I18n } from '@payloadcms/translations/types' import { initI18n } from '@payloadcms/translations' export const initPage = async ({ - configPromise, + config: configPromise, redirectUnauthenticatedUser = false, collectionSlug, globalSlug, localeParam, }: { - configPromise: Promise<SanitizedConfig> + config: SanitizedConfig | Promise<SanitizedConfig> redirectUnauthenticatedUser?: boolean collectionSlug?: string globalSlug?: string @@ -57,7 +57,7 @@ export const initPage = async ({ } const payload = await getPayload({ - config: configPromise, + config, }) const i18n = await initI18n({ diff --git a/packages/payload/src/config/types.ts b/packages/payload/src/config/types.ts index f5dc5a281ec..e8335acf0da 100644 --- a/packages/payload/src/config/types.ts +++ b/packages/payload/src/config/types.ts @@ -141,7 +141,7 @@ export type InitOptions = { * The passed config should match the config file, and if it doesn't, there could be mismatches between the admin UI * and the backend functionality */ - config: Promise<SanitizedConfig> + config: Promise<SanitizedConfig> | SanitizedConfig /** * Disable connect to the database on init */ @@ -278,9 +278,7 @@ export type AdminViewProps = { user: User | null | undefined } -export type AdminViewComponent = - | Promise<React.ComponentType<AdminViewProps>> - | React.ComponentType<AdminViewProps> +export type AdminViewComponent = React.ComponentType<AdminViewProps> export type AdminView = AdminViewComponent | AdminViewConfig diff --git a/packages/ui/src/templates/Default/types.ts b/packages/ui/src/templates/Default/types.ts index 08e4569d86e..19e709c767e 100644 --- a/packages/ui/src/templates/Default/types.ts +++ b/packages/ui/src/templates/Default/types.ts @@ -5,7 +5,7 @@ import type React from 'react' export type Props = { children?: React.ReactNode className?: string - config: Promise<SanitizedConfig> + config: Promise<SanitizedConfig> | SanitizedConfig user: User permissions: Permissions i18n: any
e268e25719dd4ebd1a6818dca86d12dc057386ca
2021-02-28 07:54:19
James
feat: simplifies collection update operation
false
simplifies collection update operation
feat
diff --git a/src/collections/operations/update.ts b/src/collections/operations/update.ts index e87fbc95791..f92e5991c2a 100644 --- a/src/collections/operations/update.ts +++ b/src/collections/operations/update.ts @@ -1,11 +1,9 @@ -import deepmerge from 'deepmerge'; import httpStatus from 'http-status'; import path from 'path'; import { UploadedFile } from 'express-fileupload'; import { Where, Document } from '../../types'; import { Collection } from '../config/types'; -import overwriteMerge from '../../utilities/overwriteMerge'; import removeInternalFields from '../../utilities/removeInternalFields'; import executeAccess from '../../auth/executeAccess'; import { NotFound, Forbidden, APIError, FileUploadError } from '../../errors'; @@ -133,9 +131,9 @@ async function update(incomingArgs: Arguments): Promise<Document> { overrideAccess, }); - // ///////////////////////////////////// - // beforeValidate - Collection - // ///////////////////////////////////// + // // ///////////////////////////////////// + // // beforeValidate - Collection + // // ///////////////////////////////////// await collectionConfig.hooks.beforeValidate.reduce(async (priorHook, hook) => { await priorHook; @@ -163,12 +161,6 @@ async function update(incomingArgs: Arguments): Promise<Document> { })) || data; }, Promise.resolve()); - // ///////////////////////////////////// - // Merge updates into existing data - // ///////////////////////////////////// - - data = deepmerge(originalDoc, data, { arrayMerge: overwriteMerge }); - // ///////////////////////////////////// // beforeChange - Fields // ///////////////////////////////////// diff --git a/src/fields/traverseFields.ts b/src/fields/traverseFields.ts index e323c7c5730..3fa55701968 100644 --- a/src/fields/traverseFields.ts +++ b/src/fields/traverseFields.ts @@ -106,10 +106,33 @@ const traverseFields = (args: Arguments): void => { if (field.localized && unflattenLocales) { unflattenLocaleActions.push(() => { - data[field.name] = payload.config.localization.locales.reduce((locales, localeID) => ({ - ...locales, - [localeID]: localeID === locale ? data[field.name] : docWithLocales?.[field.name]?.[localeID], - }), {}); + const localeData = payload.config.localization.locales.reduce((locales, localeID) => { + let valueToSet; + + if (localeID === locale) { + if (data[field.name]) { + valueToSet = data[field.name]; + } else if (docWithLocales?.[field.name]?.[localeID]) { + valueToSet = docWithLocales?.[field.name]?.[localeID]; + } + } else { + valueToSet = docWithLocales?.[field.name]?.[localeID]; + } + + if (valueToSet) { + return { + ...locales, + [localeID]: valueToSet, + }; + } + + return locales; + }, {}); + + // If there are locales with data, set the data + if (Object.keys(localeData).length > 0) { + data[field.name] = localeData; + } }); } diff --git a/src/globals/operations/update.ts b/src/globals/operations/update.ts index 9e69bbe0133..a2be344526e 100644 --- a/src/globals/operations/update.ts +++ b/src/globals/operations/update.ts @@ -1,5 +1,3 @@ -import deepmerge from 'deepmerge'; -import overwriteMerge from '../../utilities/overwriteMerge'; import executeAccess from '../../auth/executeAccess'; import removeInternalFields from '../../utilities/removeInternalFields'; @@ -38,8 +36,6 @@ async function update(args) { if (globalJSON._id) { delete globalJSON._id; } - } else { - globalJSON = { globalType: slug }; } const originalDoc = await this.performFieldOperations(globalConfig, { @@ -96,12 +92,6 @@ async function update(args) { })) || data; }, Promise.resolve()); - // ///////////////////////////////////// - // Merge updates into existing data - // ///////////////////////////////////// - - data = deepmerge(originalDoc, data, { arrayMerge: overwriteMerge }); - // ///////////////////////////////////// // beforeChange - Fields // ///////////////////////////////////// @@ -124,9 +114,10 @@ async function update(args) { global = await Model.findOneAndUpdate( { globalType: slug }, result, - { overwrite: true, new: true }, + { new: true }, ); } else { + result.globalType = slug; global = await Model.create(result); }
8bbe7bcbbebdd6a6eb87d734af69465fbb3c9b99
2025-02-19 16:34:16
Paul
feat(translations): add support for lithuanian (#11243)
false
add support for lithuanian (#11243)
feat
diff --git a/packages/payload/src/exports/i18n/lt.ts b/packages/payload/src/exports/i18n/lt.ts new file mode 100644 index 00000000000..d485d7c516c --- /dev/null +++ b/packages/payload/src/exports/i18n/lt.ts @@ -0,0 +1 @@ +export { lt } from '@payloadcms/translations/languages/lt' diff --git a/packages/plugin-seo/src/translations/index.ts b/packages/plugin-seo/src/translations/index.ts index 4489090a368..dd983f56385 100644 --- a/packages/plugin-seo/src/translations/index.ts +++ b/packages/plugin-seo/src/translations/index.ts @@ -18,6 +18,7 @@ import { hu } from './hu.js' import { it } from './it.js' import { ja } from './ja.js' import { ko } from './ko.js' +import { lt } from './lt.js' import { my } from './my.js' import { nb } from './nb.js' import { nl } from './nl.js' @@ -56,6 +57,7 @@ export const translations = { it, ja, ko, + lt, my, nb, nl, diff --git a/packages/plugin-seo/src/translations/lt.ts b/packages/plugin-seo/src/translations/lt.ts new file mode 100644 index 00000000000..470fa61e9f8 --- /dev/null +++ b/packages/plugin-seo/src/translations/lt.ts @@ -0,0 +1,28 @@ +import type { GenericTranslationsObject } from '@payloadcms/translations' + +export const lt: GenericTranslationsObject = { + $schema: './translation-schema.json', + 'plugin-seo': { + almostThere: 'Beveik baigta', + autoGenerate: 'Automatinis generavimas', + bestPractices: 'geriausios praktikos', + characterCount: '{{current}}/{{minLength}}-{{maxLength}} simbolių, ', + charactersLeftOver: '{{characters}} likusių simbolių', + charactersToGo: '{{characters}} simbolių liko', + charactersTooMany: '{{characters}} per daug simbolių', + checksPassing: '{{current}}/{{max}} tikrinimų sėkmingi', + good: 'Gerai', + imageAutoGenerationTip: 'Automatinis generavimas paims pasirinktą pagrindinį vaizdą.', + lengthTipDescription: + 'Šis tekstas turi būti tarp {{minLength}} ir {{maxLength}} simbolių. Norėdami gauti pagalbos rašant kokybiškus meta aprašus, žiūrėkite ', + lengthTipTitle: + 'Šis tekstas turi būti tarp {{minLength}} ir {{maxLength}} simbolių. Norėdami gauti pagalbos rašant kokybiškus meta pavadinimus, žiūrėkite ', + missing: 'Trūksta', + noImage: 'Nėra vaizdo', + preview: 'Peržiūra', + previewDescription: + 'Tikrųjų paieškos rezultatų gali skirtis priklausomai nuo turinio ir paieškos svarbos.', + tooLong: 'Per ilgas', + tooShort: 'Per trumpas', + }, +} diff --git a/packages/translations/src/exports/all.ts b/packages/translations/src/exports/all.ts index 42153c04f65..79acac81cc9 100644 --- a/packages/translations/src/exports/all.ts +++ b/packages/translations/src/exports/all.ts @@ -18,6 +18,7 @@ import { hu } from '../languages/hu.js' import { it } from '../languages/it.js' import { ja } from '../languages/ja.js' import { ko } from '../languages/ko.js' +import { lt } from '../languages/lt.js' import { my } from '../languages/my.js' import { nb } from '../languages/nb.js' import { nl } from '../languages/nl.js' @@ -56,6 +57,7 @@ export const translations = { it, ja, ko, + lt, my, nb, nl, diff --git a/packages/translations/src/importDateFNSLocale.ts b/packages/translations/src/importDateFNSLocale.ts index 5a1712aaa4d..2556dcaadc1 100644 --- a/packages/translations/src/importDateFNSLocale.ts +++ b/packages/translations/src/importDateFNSLocale.ts @@ -75,6 +75,10 @@ export const importDateFNSLocale = async (locale: string): Promise<Locale> => { case 'ko': result = (await import('date-fns/locale/ko')).ko + break + case 'lt': + result = (await import('date-fns/locale/lt')).lt + break case 'nb': result = (await import('date-fns/locale/nb')).nb diff --git a/packages/translations/src/languages/lt.ts b/packages/translations/src/languages/lt.ts new file mode 100644 index 00000000000..c8856970180 --- /dev/null +++ b/packages/translations/src/languages/lt.ts @@ -0,0 +1,513 @@ +import type { DefaultTranslationsObject, Language } from '../types.js' + +export const ltTranslations: DefaultTranslationsObject = { + authentication: { + account: 'Paskyra', + accountOfCurrentUser: 'Dabartinio vartotojo paskyra', + accountVerified: 'Sąskaita sėkmingai patvirtinta.', + alreadyActivated: 'Jau aktyvuota', + alreadyLoggedIn: 'Jau prisijungęs', + apiKey: 'API raktas', + authenticated: 'Autentifikuotas', + backToLogin: 'Grįžti į prisijungimą', + beginCreateFirstUser: 'Pradėkite, sukurdami savo pirmąjį vartotoją.', + changePassword: 'Keisti slaptažodį', + checkYourEmailForPasswordReset: + 'Jei šis el. pašto adresas yra susijęs su paskyra, netrukus gausite instrukcijas, kaip atstatyti savo slaptažodį. Jei laiško nesimate savo gautiesiųjų dėžutėje, patikrinkite savo šlamšto ar nereikalingų laiškų aplanką.', + confirmGeneration: 'Patvirtinkite generavimą', + confirmPassword: 'Patvirtinkite slaptažodį', + createFirstUser: 'Sukurkite pirmąjį vartotoją', + emailNotValid: 'Pateiktas el. paštas negalioja', + emailOrUsername: 'El. paštas arba vartotojo vardas', + emailSent: 'El. paštas išsiųstas', + emailVerified: 'El. paštas sėkmingai patvirtintas.', + enableAPIKey: 'Įgalinti API raktą', + failedToUnlock: 'Nepavyko atrakinti', + forceUnlock: 'Priverstinis atrakinimas', + forgotPassword: 'Pamiršote slaptažodį', + forgotPasswordEmailInstructions: + 'Prašome įvesti savo el. paštą žemiau. Gausite el. laišką su instrukcijomis, kaip atstatyti savo slaptažodį.', + forgotPasswordQuestion: 'Pamiršote slaptažodį?', + forgotPasswordUsernameInstructions: + 'Prašome įvesti savo vartotojo vardą žemiau. Instrukcijos, kaip atstatyti slaptažodį, bus išsiųstos į el. pašto adresą, susietą su jūsų vartotojo vardu.', + generate: 'Generuoti', + generateNewAPIKey: 'Sukurkite naują API raktą', + generatingNewAPIKeyWillInvalidate: + 'Sugeneruojant naują API raktą, bus <1>anuliuotas</1> ankstesnis raktas. Ar tikrai norite tęsti?', + lockUntil: 'Užrakinti iki', + logBackIn: 'Prisijunkite vėl', + loggedIn: 'Norėdami prisijungti kitu vartotoju, turėtumėte iš pradžių <0>atsijungti</0>.', + loggedInChangePassword: + 'Norėdami pakeisti slaptažodį, eikite į savo <0>paskyrą</0> ir ten redaguokite savo slaptažodį.', + loggedOutInactivity: 'Jūs buvote atjungtas dėl neveiklumo.', + loggedOutSuccessfully: 'Sėkmingai atsijungėte.', + loggingOut: 'Atsijungimas...', + login: 'Prisijungti', + loginAttempts: 'Prisijungimo bandymai', + loginUser: 'Prisijungti vartotojui', + loginWithAnotherUser: + 'Norėdami prisijungti su kitu vartotoju, turėtumėte iš pradžių <0>atsijungti</0>.', + logOut: 'Atsijungti', + logout: 'Atsijungti', + logoutSuccessful: 'Sėkmingai atsijungta.', + logoutUser: 'Atjungti vartotoją', + newAccountCreated: + 'Jums ką tik buvo sukurta nauja paskyra, kad galėtumėte prisijungti prie <a href="{{serverURL}}">{{serverURL}}</a> Prašome paspausti ant šios nuorodos arba įklijuoti apačioje esantį URL į savo naršyklę, kad patvirtintumėte savo el. pašto adresą: <a href="{{verificationURL}}">{{verificationURL}}</a><br> Patvirtinę savo el. pašto adresą, sėkmingai galėsite prisijungti.', + newAPIKeyGenerated: 'Sugeneruotas naujas API raktas.', + newPassword: 'Naujas slaptažodis', + passed: 'Autentifikacija sėkminga', + passwordResetSuccessfully: 'Slaptažodis sėkmingai atnaujintas.', + resetPassword: 'Atstatyti slaptažodį', + resetPasswordExpiration: 'Atstatyti slaptažodžio galiojimo laiką', + resetPasswordToken: 'Slaptažodžio atkūrimo žetonas', + resetYourPassword: 'Atstatykite savo slaptažodį', + stayLoggedIn: 'Likite prisijungę', + successfullyRegisteredFirstUser: 'Sėkmingai užregistruotas pirmas vartotojas.', + successfullyUnlocked: 'Sėkmingai atrakinta', + tokenRefreshSuccessful: 'Žetonų atnaujinimas sėkmingas.', + unableToVerify: 'Negalima patikrinti', + username: 'Vartotojo vardas', + usernameNotValid: 'Pateiktas vartotojo vardas yra netinkamas', + verified: 'Patvirtinta', + verifiedSuccessfully: 'Sėkmingai patvirtinta', + verify: 'Patikrinkite', + verifyUser: 'Patvirtinti vartotoją', + verifyYourEmail: 'Patvirtinkite savo el. paštą', + youAreInactive: + 'Jūs kurį laiką neveikėte ir netrukus būsite automatiškai atjungtas dėl jūsų pačių saugumo. Ar norėtumėte likti prisijungęs?', + youAreReceivingResetPassword: + 'Gavote šį pranešimą, nes jūs (arba kažkas kitas) paprašėte atstatyti slaptažodį savo paskyrai. Norėdami užbaigti procesą, spustelėkite šią nuorodą arba įklijuokite ją į savo naršyklę:', + youDidNotRequestPassword: + 'Jei to neprašėte, prašome ignoruoti šį el. laišką ir jūsų slaptažodis išliks nepakeistas.', + }, + error: { + accountAlreadyActivated: 'Ši paskyra jau aktyvuota.', + autosaving: 'Šio dokumento automatinio išsaugojimo metu kilo problema.', + correctInvalidFields: 'Prašome ištaisyti neteisingus laukus.', + deletingFile: 'Įvyko klaida trinant failą.', + deletingTitle: + 'Įvyko klaida bandant ištrinti {{title}}. Patikrinkite savo ryšį ir bandykite dar kartą.', + emailOrPasswordIncorrect: 'Pateiktas el. pašto adresas arba slaptažodis yra neteisingi.', + followingFieldsInvalid_one: 'Šis laukas yra netinkamas:', + followingFieldsInvalid_other: 'Šie laukai yra neteisingi:', + incorrectCollection: 'Neteisinga kolekcija', + invalidFileType: 'Netinkamas failo tipas', + invalidFileTypeValue: 'Neteisingas failo tipas: {{value}}', + invalidRequestArgs: 'Netinkami argumentai perduoti užklausoje: {{args}}', + loadingDocument: 'Įvyko klaida įkeliant dokumentą, kurio ID yra {{id}}.', + localesNotSaved_one: 'Negalima išsaugoti šios lokalės:', + localesNotSaved_other: 'Šios lokalės negalėjo būti išsaugotos:', + logoutFailed: 'Atsijungimas nepavyko.', + missingEmail: 'Trūksta el. pašto.', + missingIDOfDocument: 'Trūksta dokumento, kurį reikia atnaujinti, ID.', + missingIDOfVersion: 'Trūksta versijos ID.', + missingRequiredData: 'Trūksta reikalingų duomenų.', + noFilesUploaded: 'Neįkelta jokių failų.', + noMatchedField: 'Nerasta atitinkamo lauko „{{label}}“', + notAllowedToAccessPage: 'Jums neleidžiama prieiti prie šio puslapio.', + notAllowedToPerformAction: 'Jums neleidžiama atlikti šio veiksmo.', + notFound: 'Pageidaujamas išteklius nerasta.', + noUser: 'Nėra vartotojo', + previewing: 'Šiam dokumentui peržiūrėti kilo problema.', + problemUploadingFile: 'Failo įkelti nepavyko dėl problemos.', + tokenInvalidOrExpired: 'Žetonas yra neteisingas arba jo galiojimas pasibaigė.', + tokenNotProvided: 'Žetonas nesuteiktas.', + unableToDeleteCount: 'Negalima ištrinti {{count}} iš {{total}} {{label}}.', + unableToReindexCollection: + 'Klaida perindeksuojant rinkinį {{collection}}. Operacija nutraukta.', + unableToUpdateCount: 'Nepavyko atnaujinti {{count}} iš {{total}} {{label}}.', + unauthorized: 'Neleistina, turite būti prisijungęs, kad galėtumėte teikti šį prašymą.', + unauthorizedAdmin: + 'Neleidžiama, šis vartotojas neturi prieigos prie administratoriaus panelės.', + unknown: 'Įvyko nežinoma klaida.', + unPublishingDocument: 'Šio dokumento nepublikuojant kildavo problema.', + unspecific: 'Įvyko klaida.', + userEmailAlreadyRegistered: 'Vartotojas su nurodytu el. paštu jau yra užregistruotas.', + userLocked: 'Šis vartotojas užrakintas dėl per daug nepavykusių prisijungimo bandymų.', + usernameAlreadyRegistered: 'Vartotojas su nurodytu vartotojo vardu jau užregistruotas.', + usernameOrPasswordIncorrect: 'Pateiktas vartotojo vardas arba slaptažodis yra neteisingas.', + valueMustBeUnique: 'Vertė turi būti unikalu.', + verificationTokenInvalid: 'Patvirtinimo kodas yra negaliojantis.', + }, + fields: { + addLabel: 'Pridėkite {{žymė}}', + addLink: 'Pridėti nuorodą', + addNew: 'Pridėti naują', + addNewLabel: 'Pridėti naują {{žymę}}', + addRelationship: 'Pridėti santykį', + addUpload: 'Pridėti Įkelti', + block: 'blokas', + blocks: 'blokai', + blockType: 'Blokas Tipas', + chooseBetweenCustomTextOrDocument: + 'Pasirinkite tarp pasirinkimo įvesti tinkintą tekstą URL arba nuorodos į kitą dokumentą.', + chooseDocumentToLink: 'Pasirinkite dokumentą, prie kurio norite prisegti.', + chooseFromExisting: 'Pasirinkite iš esamų', + chooseLabel: 'Pasirinkite {{žymė}}', + collapseAll: 'Sutraukti viską', + customURL: 'Pasirinktinis URL', + editLabelData: 'Redaguoti {{label}} duomenis', + editLink: 'Redaguoti nuorodą', + editRelationship: 'Redaguoti santykius', + enterURL: 'Įveskite URL', + internalLink: 'Vidinis nuorodos', + itemsAndMore: '{{items}} ir dar {{count}}', + labelRelationship: '{{label}} Santykiai', + latitude: 'Platuma', + linkedTo: 'Susijęs su <0>{{label}}</0>', + linkType: 'Nuorodos tipas', + longitude: 'Ilgumažė', + newLabel: 'Naujas {{žymė}}', + openInNewTab: 'Atidaryti naujame skirtuke', + passwordsDoNotMatch: 'Slaptažodžiai nesutampa.', + relatedDocument: 'Susijęs dokumentas', + relationTo: 'Santykis su', + removeRelationship: 'Pašalinti ryšį', + removeUpload: 'Pašalinti įkėlimą', + saveChanges: 'Išsaugoti pakeitimus', + searchForBlock: 'Ieškokite bloko', + selectExistingLabel: 'Pasirinkite esamą {{žymę}}', + selectFieldsToEdit: 'Pasirinkite laukus, kuriuos norite redaguoti', + showAll: 'Rodyti viską', + swapRelationship: 'Apkeičiamas santykis', + swapUpload: 'Keitimo įkėlimas', + textToDisplay: 'Rodyti tekstą', + toggleBlock: 'Perjungti bloką', + uploadNewLabel: 'Įkelti naują {{label}}', + }, + general: { + aboutToDelete: 'Jūs ketinate ištrinti {{label}} <1>{{title}}</1>. Ar esate tikri?', + aboutToDeleteCount_many: 'Jūs ketinate ištrinti {{count}} {{label}}', + aboutToDeleteCount_one: 'Jūs ketinate ištrinti {{count}} {{label}}', + aboutToDeleteCount_other: 'Jūs ketinate ištrinti {{count}} {{label}}', + addBelow: 'Pridėti žemiau', + addFilter: 'Pridėti filtrą', + adminTheme: 'Admin temos', + all: 'Visi', + allCollections: 'Visos kolekcijos', + and: 'Ir', + anotherUser: 'Kitas vartotojas', + anotherUserTakenOver: 'Kitas naudotojas perėmė šio dokumento redagavimą.', + applyChanges: 'Taikyti pakeitimus', + ascending: 'Kylantis', + automatic: 'Automatinis', + backToDashboard: 'Atgal į informacinę skydelį', + cancel: 'Atšaukti', + changesNotSaved: + 'Jūsų pakeitimai nebuvo išsaugoti. Jei dabar išeisite, prarasite savo pakeitimus.', + clearAll: 'Išvalyti viską', + close: 'Uždaryti', + collapse: 'Susikolimas', + collections: 'Kolekcijos', + columns: 'Stulpeliai', + columnToSort: 'Rūšiuoti stulpelį', + confirm: 'Patvirtinti', + confirmCopy: 'Patvirtinkite kopiją', + confirmDeletion: 'Patvirtinkite šalinimą', + confirmDuplication: 'Patvirtinkite dubliavimą', + confirmReindex: 'Perindeksuoti visas {{kolekcijas}}?', + confirmReindexAll: 'Perindeksuoti visas kolekcijas?', + confirmReindexDescription: + 'Tai pašalins esamus indeksus ir iš naujo indeksuos dokumentus kolekcijose {{collections}}.', + confirmReindexDescriptionAll: + 'Tai pašalins esamas indeksus ir perindeksuos dokumentus visose kolekcijose.', + copied: 'Nukopijuota', + copy: 'Kopijuoti', + copying: 'Kopijavimas', + copyWarning: + 'Jūs ketinate perrašyti {{to}} į {{from}} šildymui {{label}} {{title}}. Ar esate tikri?', + create: 'Sukurti', + created: 'Sukurta', + createdAt: 'Sukurta', + createNew: 'Sukurti naują', + createNewLabel: 'Sukurti naują {{label}}', + creating: 'Kuriant', + creatingNewLabel: 'Kuriamas naujas {{label}}', + currentlyEditing: + 'šiuo metu redaguoja šį dokumentą. Jei perimsite, jie bus užblokuoti ir negalės toliau redaguoti, o taip pat gali prarasti neišsaugotus pakeitimus.', + custom: 'Paprastas', + dark: 'Tamsus', + dashboard: 'Prietaisų skydelis', + delete: 'Ištrinti', + deletedCountSuccessfully: 'Sėkmingai ištrinta {{count}} {{label}}.', + deletedSuccessfully: 'Sėkmingai ištrinta.', + deleting: 'Trinama...', + depth: 'Gylis', + descending: 'Mažėjantis', + deselectAllRows: 'Atžymėkite visas eilutes', + document: 'Dokumentas', + documentLocked: 'Dokumentas užrakintas', + documents: 'Dokumentai', + duplicate: 'Dublikatas', + duplicateWithoutSaving: 'Dubliuoti be įrašytų pakeitimų', + edit: 'Redaguoti', + editAll: 'Redaguoti viską', + editedSince: 'Redaguota nuo', + editing: 'Redagavimas', + editingLabel_many: 'Redaguojama {{count}} {{label}}', + editingLabel_one: 'Redaguojama {{count}} {{label}}', + editingLabel_other: 'Redaguojamas {{count}} {{label}}', + editingTakenOver: 'Redagavimas perimtas', + editLabel: 'Redaguoti {{žymę}}', + email: 'El. paštas', + emailAddress: 'El. pašto adresas', + enterAValue: 'Įveskite reikšmę', + error: 'Klaida', + errors: 'Klaidos', + fallbackToDefaultLocale: 'Grįžkite į numatytąją vietovę', + false: 'Netiesa', + filter: 'Filtruoti', + filters: 'Filtrai', + filterWhere: 'Filtruoti {{label}}, kur', + globals: 'Globalai', + goBack: 'Grįžkite', + isEditing: 'redaguoja', + language: 'Kalba', + lastModified: 'Paskutinį kartą modifikuota', + leaveAnyway: 'Vis tiek išeikite', + leaveWithoutSaving: 'Išeikite neišsaugoję', + light: 'Šviesa', + livePreview: 'Tiesioginė peržiūra', + loading: 'Kraunama', + locale: 'Lokalė', + locales: 'Lokalės', + menu: 'Meniu', + moreOptions: 'Daugiau parinkčių', + moveDown: 'Perkelti žemyn', + moveUp: 'Pakilti', + newPassword: 'Naujas slaptažodis', + next: 'Toliau', + noDateSelected: 'Pasirinktos datos nėra', + noFiltersSet: 'Nenustatyti jokie filtrai', + noLabel: '<Ne {{label}}>', + none: 'Jokios', + noOptions: 'Jokių variantų', + noResults: + 'Nerasta jokių {{label}}. Arba dar nėra sukurtų {{label}}, arba jie neatitinka nurodytų filtrų aukščiau.', + notFound: 'Nerasta', + nothingFound: 'Nieko nerasta', + noUpcomingEventsScheduled: 'Nėra suplanuotų būsimų renginių.', + noValue: 'Nėra vertės', + of: 'apie', + only: 'Tik', + open: 'Atidaryti', + or: 'Arba', + order: 'Užsakyti', + overwriteExistingData: 'Perrašyti esamus lauko duomenis', + pageNotFound: 'Puslapis nerastas', + password: 'Slaptažodis', + payloadSettings: 'Payload nustatymai', + perPage: 'Puslapyje: {{limit}}', + previous: 'Ankstesnis', + reindex: 'Perindeksuoti', + reindexingAll: 'Perindeksuojamos visos {{kolekcijos}}.', + remove: 'Pašalinti', + reset: 'Atstatyti', + resetPreferences: 'Atstatyti nuostatas', + resetPreferencesDescription: 'Tai atstatys visas jūsų nuostatas į numatytąsias reikšmes.', + resettingPreferences: 'Nustatymų atstatymas.', + row: 'Eilutė', + rows: 'Eilutės', + save: 'Išsaugoti', + saving: 'Išsaugoti...', + schedulePublishFor: 'Suplanuokite publikaciją „{{title}}“', + searchBy: 'Ieškokite pagal {{žymę}}', + selectAll: 'Pasirinkite visus {{count}} {{label}}', + selectAllRows: 'Pasirinkite visas eilutes', + selectedCount: '{{count}} {{label}} pasirinkta', + selectValue: 'Pasirinkite reikšmę', + showAllLabel: 'Rodyti visus {{label}}', + sorryNotFound: 'Atsiprašau - nėra nieko, atitinkančio jūsų užklausą.', + sort: 'Rūšiuoti', + sortByLabelDirection: 'Rūšiuoti pagal {{label}} {{direction}}', + stayOnThisPage: 'Likite šiame puslapyje', + submissionSuccessful: 'Pateikimas sėkmingas.', + submit: 'Pateikti', + submitting: 'Pateikiama...', + success: 'Sėkmė', + successfullyCreated: '{{label}} sėkmingai sukurtas.', + successfullyDuplicated: '{{label}} sėkmingai dubliuotas.', + successfullyReindexed: + 'Sėkmingai perindeksuota {{count}} iš {{total}} dokumentų iš {{collections}}', + takeOver: 'Perimti', + thisLanguage: 'Lietuvių', + time: 'Laikas', + timezone: 'Laiko juosta', + titleDeleted: '{{label}} "{{title}}" sėkmingai ištrinta.', + true: 'Tiesa', + unauthorized: 'Neleistinas', + unsavedChanges: 'Turite neišsaugotų pakeitimų. Išsaugokite arba atmestkite prieš tęsdami.', + unsavedChangesDuplicate: 'Jūs turite neišsaugotų pakeitimų. Ar norėtumėte tęsti dubliavimą?', + untitled: 'Neužpavadinamas', + upcomingEvents: 'Artimieji renginiai', + updatedAt: 'Atnaujinta', + updatedCountSuccessfully: '{{count}} {{label}} sėkmingai atnaujinta.', + updatedSuccessfully: 'Sėkmingai atnaujinta.', + updating: 'Atnaujinimas', + uploading: 'Įkeliama', + uploadingBulk: 'Įkeliamas {{current}} iš {{total}}', + user: 'Vartotojas', + username: 'Vartotojo vardas', + users: 'Vartotojai', + value: 'Vertė', + viewReadOnly: 'Peržiūrėti tik skaitymui', + welcome: 'Sveiki', + }, + localization: { + cannotCopySameLocale: 'Negalima kopijuoti į tą pačią vietovę', + copyFrom: 'Kopijuoti iš', + copyFromTo: 'Kopijavimas iš {{from}} į {{to}}', + copyTo: 'Kopijuoti į', + copyToLocale: 'Kopijuoti į vietovę', + localeToPublish: 'Publikuoti lokacijoje', + selectLocaleToCopy: 'Pasirinkite lokalės kopijavimui', + }, + operators: { + contains: 'yra', + equals: 'lygus', + exists: 'egzistuoja', + intersects: 'susikerta', + isGreaterThan: 'yra didesnis nei', + isGreaterThanOrEqualTo: 'yra didesnis arba lygus', + isIn: 'yra', + isLessThan: 'yra mažiau nei', + isLessThanOrEqualTo: 'yra mažiau arba lygu', + isLike: 'yra panašu', + isNotEqualTo: 'nelygu', + isNotIn: 'nėra', + near: 'šalia', + within: 'viduje', + }, + upload: { + addFile: 'Pridėti failą', + addFiles: 'Pridėti failus', + bulkUpload: 'Masinis įkėlimas', + crop: 'Pasėlis', + cropToolDescription: + 'Temkite pasirinktos srities kampus, nubrėžkite naują sritį arba koreguokite žemiau esančias reikšmes.', + dragAndDrop: 'Temkite ir numeskite failą', + dragAndDropHere: 'arba nuvilkite failą čia', + editImage: 'Redaguoti vaizdą', + fileName: 'Failo pavadinimas', + fileSize: 'Failo dydis', + filesToUpload: 'Įkelti failai', + fileToUpload: 'Įkelti failą', + focalPoint: 'Fokuso Taškas', + focalPointDescription: + 'Temkite fokusavimo tašką tiesiogiai peržiūroje arba reguliuokite žemiau esančias reikšmes.', + height: 'Aukštis', + lessInfo: 'Mažiau informacijos', + moreInfo: 'Daugiau informacijos', + pasteURL: 'Įklijuokite URL', + previewSizes: 'Peržiūros dydžiai', + selectCollectionToBrowse: 'Pasirinkite kolekciją, kurią norėtumėte naršyti', + selectFile: 'Pasirinkite failą', + setCropArea: 'Nustatykite pjovimo plotą', + setFocalPoint: 'Nustatyti fokuso tašką', + sizes: 'Dydžiai', + sizesFor: 'Dydžiai skirti {{žymei}}', + width: 'Plotis', + }, + validation: { + emailAddress: 'Įveskite galiojantį el. pašto adresą.', + enterNumber: 'Įveskite galiojantį skaičių.', + fieldHasNo: 'Šiame lauke nėra {{label}}', + greaterThanMax: + '{{value}} yra didesnė nei leidžiama maksimali {{label}} reikšmė, kuri yra {{max}}.', + invalidInput: 'Šis laukas turi netinkamą įvestį.', + invalidSelection: 'Šiame lauke yra netinkamas pasirinkimas.', + invalidSelections: 'Šiame lauke yra šios netinkamos parinktys:', + lessThanMin: + '{{value}} yra mažesnė nei leidžiama minimali {{label}} reikšmė, kuri yra {{min}}.', + limitReached: 'Pasiektas limitas, galima pridėti tik {{max}} daiktus.', + longerThanMin: + 'Ši reikšmė turi būti ilgesnė nei minimalus simbolių skaičius, kuris yra {{minLength}} simboliai.', + notValidDate: '"{{value}}" nėra galiojanti data.', + required: 'Šis laukas yra privalomas.', + requiresAtLeast: 'Šis laukas reikalauja bent {{count}} {{label}}.', + requiresNoMoreThan: 'Šiame laukelyje gali būti ne daugiau kaip {{count}} {{label}}.', + requiresTwoNumbers: 'Šiame lauke reikia įvesti du skaičius.', + shorterThanMax: 'Ši reikšmė turi būti trumpesnė nei maksimalus {{maxLength}} simbolių ilgis.', + timezoneRequired: 'Reikia nustatyti laiko juostą.', + trueOrFalse: 'Šis laukas gali būti lygus tik „true“ ar „false“.', + username: + 'Įveskite galiojantį vartotojo vardą. Galima naudoti raides, skaičius, brūkšnelius, taškus ir pabraukimus.', + validUploadID: 'Šis laukas nėra tinkamas įkėlimo ID.', + }, + version: { + type: 'Įveskite', + aboutToPublishSelection: 'Jūs ketinate išleisti visus {{label}} išrinktame. Ar esate tikri?', + aboutToRestore: + 'Jūs ketinate atkurti šį {{label}} dokumentą į būklę, kurioje jis buvo {{versionDate}}.', + aboutToRestoreGlobal: + 'Jūs ketinate atkurti visuotinę {{label}} būklę, kokia ji buvo {{versionDate}}.', + aboutToRevertToPublished: + 'Jūs ketinate atšaukti šio dokumento pakeitimus ir grįžti prie publikuotos versijos. Ar esate įsitikinęs?', + aboutToUnpublish: 'Jūs ketinate panaikinti šio dokumento publikavimą. Ar esate tikri?', + aboutToUnpublishSelection: + 'Jūs ketinate atšaukti visų {{label}} pasirinkime. Ar esate įsitikinęs?', + autosave: 'Automatinis išsaugojimas', + autosavedSuccessfully: 'Sėkmingai automatiškai išsaugota.', + autosavedVersion: 'Automatiškai išsaugota versija', + changed: 'Pakeistas', + changedFieldsCount_one: '{{count}} pakeistas laukas', + changedFieldsCount_other: '{{count}} pakeisti laukai', + compareVersion: 'Palyginkite versiją su:', + confirmPublish: 'Patvirtinkite publikaciją', + confirmRevertToSaved: 'Patvirtinkite grįžimą į įrašytą', + confirmUnpublish: 'Patvirtinkite nepublikavimą', + confirmVersionRestoration: 'Patvirtinkite versijos atkūrimą', + currentDocumentStatus: 'Dabartinis {{docStatus}} dokumentas', + currentDraft: 'Dabartinis projektas', + currentPublishedVersion: 'Dabartinė publikuota versija', + draft: 'Projektas', + draftSavedSuccessfully: 'Juosmuo sėkmingai išsaugotas.', + lastSavedAgo: 'Paskutinį kartą išsaugota prieš {{distance}}', + modifiedOnly: 'Tik modifikuotas', + noFurtherVersionsFound: 'Nerasta daugiau versijų', + noRowsFound: 'Nerasta {{žymė}}', + noRowsSelected: 'Pasirinkta ne viena {{žymė}}', + preview: 'Peržiūra', + previouslyPublished: 'Ankstesnė publikacija', + problemRestoringVersion: 'Buvo problema atkuriant šią versiją', + publish: 'Paskelbti', + publishAllLocales: 'Publikuokite visus lokalizacijas', + publishChanges: 'Paskelbti pakeitimus', + published: 'Paskelbta', + publishIn: 'Paskelbti {{locale}}', + publishing: 'Leidyba', + restoreAsDraft: 'Atkurti kaip juodraštį', + restoredSuccessfully: 'Sėkmingai atkurtas.', + restoreThisVersion: 'Atkurti šią versiją', + restoring: 'Atkuriamas...', + reverting: 'Grįžtama...', + revertToPublished: 'Grįžti prie publikuotojo', + saveDraft: 'Išsaugoti juodraštį', + scheduledSuccessfully: 'Sėkmingai suplanuota.', + schedulePublish: 'Suplanuokite publikaciją', + selectLocales: 'Pasirinkite lokales, kurias norėtumėte rodyti', + selectVersionToCompare: 'Pasirinkite versiją, kurią norite palyginti', + showingVersionsFor: 'Rodomos versijos:', + showLocales: 'Rodyti lokalizacijas:', + status: 'Būsena', + unpublish: 'Nebepublikuoti', + unpublishing: 'Nebepublikuojama...', + version: 'Versija', + versionCount_many: 'Rasta {{count}} versijų', + versionCount_none: 'Nerasta jokių versijų', + versionCount_one: 'Rasta {{count}} versija', + versionCount_other: 'Rasta {{count}} versijų', + versionCreatedOn: '{{version}} sukurtas:', + versionID: 'Versijos ID', + versions: 'Versijos', + viewingVersion: 'Peržiūrėkite versiją {{entityLabel}} {{documentTitle}}', + viewingVersionGlobal: 'Peržiūrint visuotinę {{entityLabel}} versiją', + viewingVersions: 'Peržiūrint versijas {{entityLabel}} {{documentTitle}}', + viewingVersionsGlobal: 'Peržiūrėti globalaus {{entityLabel}} versijas', + }, +} + +export const lt: Language = { + dateFNSKey: 'lt', + translations: ltTranslations, +} diff --git a/packages/translations/src/types.ts b/packages/translations/src/types.ts index c080234a57a..82a945e7894 100644 --- a/packages/translations/src/types.ts +++ b/packages/translations/src/types.ts @@ -23,6 +23,7 @@ type DateFNSKeys = | 'it' | 'ja' | 'ko' + | 'lt' | 'nb' | 'nl' | 'pl' diff --git a/packages/translations/src/utilities/languages.ts b/packages/translations/src/utilities/languages.ts index fa2550fb255..d7cdde23857 100644 --- a/packages/translations/src/utilities/languages.ts +++ b/packages/translations/src/utilities/languages.ts @@ -21,6 +21,7 @@ export const acceptedLanguages = [ 'it', 'ja', 'ko', + 'lt', 'my', 'nb', 'nl', @@ -85,7 +86,6 @@ export const acceptedLanguages = [ * 'ku-Arab', * 'ky-Cyrl', * 'lb', - * 'lt', * 'lv', * 'mi-Latn', * 'mk',
a46609ef6baa524fb6feb47b531606b1ab7ef58f
2024-12-28 03:11:15
Alessio Gravili
feat(richtext-lexical): more lenient MDX JSON object parser that allows unquoted property keys (#10205)
false
more lenient MDX JSON object parser that allows unquoted property keys (#10205)
feat
diff --git a/eslint.config.js b/eslint.config.js index 355c445d465..fe92040f012 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -19,6 +19,7 @@ export const defaultESLintIgnores = [ '**/build/', '**/node_modules/', '**/temp/', + '**/*.spec.ts', ] /** @typedef {import('eslint').Linter.Config} Config */ diff --git a/packages/richtext-lexical/package.json b/packages/richtext-lexical/package.json index 4e7e29b67db..bf8cab427f0 100644 --- a/packages/richtext-lexical/package.json +++ b/packages/richtext-lexical/package.json @@ -362,6 +362,7 @@ "bson-objectid": "2.0.4", "dequal": "2.0.3", "escape-html": "1.0.3", + "json5": "^2.2.3", "lexical": "0.20.0", "mdast-util-from-markdown": "2.0.2", "mdast-util-mdx-jsx": "3.1.3", diff --git a/packages/richtext-lexical/src/utilities/jsx/extractPropsFromJSXPropsString.ts b/packages/richtext-lexical/src/utilities/jsx/extractPropsFromJSXPropsString.ts index 52d23e9772d..bdf8544b501 100644 --- a/packages/richtext-lexical/src/utilities/jsx/extractPropsFromJSXPropsString.ts +++ b/packages/richtext-lexical/src/utilities/jsx/extractPropsFromJSXPropsString.ts @@ -1,3 +1,7 @@ +import JSON5Import from 'json5' + +const JSON5 = ('default' in JSON5Import ? JSON5Import.default : JSON5Import) as typeof JSON5Import + /** * Turns a JSX props string into an object. * @@ -78,7 +82,7 @@ function handleArray(propsString: string, startIndex: number): { newIndex: numbe i++ } - return { newIndex: i, value: JSON.parse(`[${value}]`) } + return { newIndex: i, value: JSON5.parse(`[${value}]`) } } function handleQuotedString( @@ -116,10 +120,10 @@ function handleObject(propsString: string, startIndex: number): { newIndex: numb function parseObject(objString: string): Record<string, any> { if (objString[0] !== '{') { - return JSON.parse(objString) + return JSON5.parse(objString) } - const result = JSON.parse(objString.replace(/(\w+):/g, '"$1":')) + const result = JSON5.parse(objString.replace(/(\w+):/g, '"$1":')) return result } diff --git a/packages/richtext-lexical/src/utilities/jsx/jsx.spec.ts b/packages/richtext-lexical/src/utilities/jsx/jsx.spec.ts index decbf1d55d6..6d635e013ad 100644 --- a/packages/richtext-lexical/src/utilities/jsx/jsx.spec.ts +++ b/packages/richtext-lexical/src/utilities/jsx/jsx.spec.ts @@ -3,7 +3,11 @@ import { propsToJSXString } from './jsx.js' describe('jsx', () => { describe('prop string to object', () => { - const INPUT_AND_OUTPUT = [ + const INPUT_AND_OUTPUT: { + input: string + inputFromOutput?: string + output: Record<string, any> + }[] = [ { input: 'key="value"', output: { @@ -112,6 +116,15 @@ describe('jsx', () => { update: true, }, }, + { + // Test if unquoted property keys in objects within arrays are supprted. This is + // supported through the more lenient json5 parser, instead of using JSON.parse() + input: 'key={[1, 2, { hello: "there" }]}', + inputFromOutput: 'key={[1, 2, { "hello": "there" }]}', + output: { + key: [1, 2, { hello: 'there' }], + }, + }, ] for (const { input, output } of INPUT_AND_OUTPUT) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index efca83ac877..4b9622df642 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -45,7 +45,7 @@ importers: version: 1.48.1 '@sentry/nextjs': specifier: ^8.33.1 - version: 8.37.1(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))) + version: 8.37.1(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))([email protected])) '@sentry/node': specifier: ^8.33.1 version: 8.37.1 @@ -147,7 +147,7 @@ importers: version: 9.5.0(@aws-sdk/[email protected](@aws-sdk/[email protected](@aws-sdk/[email protected]))) next: specifier: 15.0.3 - version: 15.0.3(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) + version: 15.0.3(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) open: specifier: ^10.1.0 version: 10.1.0 @@ -964,7 +964,7 @@ importers: version: link:../payload ts-jest: specifier: ^29.1.0 - version: 29.2.5(@babel/[email protected])(@jest/[email protected])(@jest/[email protected])([email protected](@babel/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected]) + version: 29.2.5(@babel/[email protected])(@jest/[email protected])(@jest/[email protected])([email protected](@babel/[email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected]) packages/plugin-cloud-storage: dependencies: @@ -1087,7 +1087,7 @@ importers: dependencies: '@sentry/nextjs': specifier: ^8.33.1 - version: 8.37.1(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))) + version: 8.37.1(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))([email protected])) '@sentry/types': specifier: ^8.33.1 version: 8.37.1 @@ -1244,6 +1244,9 @@ importers: escape-html: specifier: 1.0.3 version: 1.0.3 + json5: + specifier: ^2.2.3 + version: 2.2.3 lexical: specifier: 0.20.0 version: 0.20.0 @@ -1434,7 +1437,7 @@ importers: version: link:../plugin-cloud-storage uploadthing: specifier: 7.3.0 - version: 7.3.0([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])) + version: 7.3.0([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])) devDependencies: payload: specifier: workspace:* @@ -1708,7 +1711,7 @@ importers: version: link:../packages/ui '@sentry/nextjs': specifier: ^8.33.1 - version: 8.37.1(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))) + version: 8.37.1(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))([email protected])) '@sentry/react': specifier: ^7.77.0 version: 7.119.2([email protected]) @@ -1753,7 +1756,7 @@ importers: version: 8.8.3(@aws-sdk/[email protected](@aws-sdk/[email protected](@aws-sdk/[email protected])))([email protected]) next: specifier: 15.0.3 - version: 15.0.3(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) + version: 15.0.3(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) nodemailer: specifier: 6.9.10 version: 6.9.10 @@ -7854,6 +7857,7 @@ packages: [email protected]: resolution: {integrity: sha512-T9eIRCs6b0J1SHKYIvD8+KCJMcWZ900iZyxdnSCdqxN12Z1ijzT+jY5nrk72Jw4B0HGzms2NgpryArlJqvc3Lw==} + cpu: [x64, arm64, wasm32] os: [darwin, linux, win32] [email protected]: @@ -13684,7 +13688,7 @@ snapshots: '@sentry/utils': 7.119.2 localforage: 1.10.0 - '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))': + '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))([email protected]))': dependencies: '@opentelemetry/api': 1.9.0 '@opentelemetry/instrumentation-http': 0.53.0(@opentelemetry/[email protected]) @@ -13698,9 +13702,9 @@ snapshots: '@sentry/types': 8.37.1 '@sentry/utils': 8.37.1 '@sentry/vercel-edge': 8.37.1 - '@sentry/webpack-plugin': 2.22.6([email protected](@swc/[email protected](@swc/[email protected]))) + '@sentry/webpack-plugin': 2.22.6([email protected](@swc/[email protected](@swc/[email protected]))([email protected])) chalk: 3.0.0 - next: 15.0.3(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) + next: 15.0.3(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) resolve: 1.22.8 rollup: 3.29.5 stacktrace-parser: 0.1.10 @@ -13713,7 +13717,7 @@ snapshots: - supports-color - webpack - '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected])))': + '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))([email protected]))': dependencies: '@opentelemetry/api': 1.9.0 '@opentelemetry/instrumentation-http': 0.53.0(@opentelemetry/[email protected]) @@ -13727,9 +13731,9 @@ snapshots: '@sentry/types': 8.37.1 '@sentry/utils': 8.37.1 '@sentry/vercel-edge': 8.37.1 - '@sentry/webpack-plugin': 2.22.6([email protected](@swc/[email protected](@swc/[email protected]))) + '@sentry/webpack-plugin': 2.22.6([email protected](@swc/[email protected](@swc/[email protected]))([email protected])) chalk: 3.0.0 - next: 15.0.4(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) + next: 15.0.4(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) resolve: 1.22.8 rollup: 3.29.5 stacktrace-parser: 0.1.10 @@ -13837,12 +13841,12 @@ snapshots: '@sentry/types': 8.37.1 '@sentry/utils': 8.37.1 - '@sentry/[email protected]([email protected](@swc/[email protected](@swc/[email protected])))': + '@sentry/[email protected]([email protected](@swc/[email protected](@swc/[email protected]))([email protected]))': dependencies: '@sentry/bundler-plugin-core': 2.22.6 unplugin: 1.0.1 uuid: 9.0.0 - webpack: 5.96.1(@swc/[email protected](@swc/[email protected])) + webpack: 5.96.1(@swc/[email protected](@swc/[email protected]))([email protected]) transitivePeerDependencies: - encoding - supports-color @@ -18460,36 +18464,7 @@ snapshots: - '@babel/core' - babel-plugin-macros - [email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]): - dependencies: - '@next/env': 15.0.3 - '@swc/counter': 0.1.3 - '@swc/helpers': 0.5.13 - busboy: 1.6.0 - caniuse-lite: 1.0.30001678 - postcss: 8.4.31 - react: 19.0.0 - react-dom: 19.0.0([email protected]) - styled-jsx: 5.1.6(@babel/[email protected])([email protected])([email protected]) - optionalDependencies: - '@next/swc-darwin-arm64': 15.0.3 - '@next/swc-darwin-x64': 15.0.3 - '@next/swc-linux-arm64-gnu': 15.0.3 - '@next/swc-linux-arm64-musl': 15.0.3 - '@next/swc-linux-x64-gnu': 15.0.3 - '@next/swc-linux-x64-musl': 15.0.3 - '@next/swc-win32-arm64-msvc': 15.0.3 - '@next/swc-win32-x64-msvc': 15.0.3 - '@opentelemetry/api': 1.9.0 - '@playwright/test': 1.48.1 - babel-plugin-react-compiler: 19.0.0-beta-df7b47d-20241124 - sass: 1.77.4 - sharp: 0.33.5 - transitivePeerDependencies: - - '@babel/core' - - babel-plugin-macros - - [email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]): + [email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]): dependencies: '@next/env': 15.0.4 '@swc/counter': 0.1.3 @@ -19920,16 +19895,17 @@ snapshots: ansi-escapes: 4.3.2 supports-hyperlinks: 2.3.0 - [email protected](@swc/[email protected](@swc/[email protected]))([email protected](@swc/[email protected](@swc/[email protected]))): + [email protected](@swc/[email protected](@swc/[email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))([email protected])): dependencies: '@jridgewell/trace-mapping': 0.3.25 jest-worker: 27.5.1 schema-utils: 3.3.0 serialize-javascript: 6.0.2 terser: 5.36.0 - webpack: 5.96.1(@swc/[email protected](@swc/[email protected])) + webpack: 5.96.1(@swc/[email protected](@swc/[email protected]))([email protected]) optionalDependencies: '@swc/core': 1.9.3(@swc/[email protected]) + esbuild: 0.19.12 [email protected]: dependencies: @@ -20025,7 +20001,7 @@ snapshots: optionalDependencies: typescript: 5.7.2 - [email protected](@babel/[email protected])(@jest/[email protected])(@jest/[email protected])([email protected](@babel/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected]): + [email protected](@babel/[email protected])(@jest/[email protected])(@jest/[email protected])([email protected](@babel/[email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected]): dependencies: bs-logger: 0.2.6 ejs: 3.1.10 @@ -20043,6 +20019,7 @@ snapshots: '@jest/transform': 29.7.0 '@jest/types': 29.6.3 babel-jest: 29.7.0(@babel/[email protected]) + esbuild: 0.19.12 [email protected]: {} @@ -20234,14 +20211,14 @@ snapshots: escalade: 3.2.0 picocolors: 1.1.1 - [email protected]([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])): + [email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])): dependencies: '@effect/platform': 0.69.8([email protected]) '@uploadthing/mime-types': 0.3.2 '@uploadthing/shared': 7.1.1 effect: 3.10.3 optionalDependencies: - next: 15.0.4(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) + next: 15.0.4(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]) [email protected]: dependencies: @@ -20344,7 +20321,7 @@ snapshots: [email protected]: {} - [email protected](@swc/[email protected](@swc/[email protected])): + [email protected](@swc/[email protected](@swc/[email protected]))([email protected]): dependencies: '@types/eslint-scope': 3.7.7 '@types/estree': 1.0.6 @@ -20366,7 +20343,7 @@ snapshots: neo-async: 2.6.2 schema-utils: 3.3.0 tapable: 2.2.1 - terser-webpack-plugin: 5.3.10(@swc/[email protected](@swc/[email protected]))([email protected](@swc/[email protected](@swc/[email protected]))) + terser-webpack-plugin: 5.3.10(@swc/[email protected](@swc/[email protected]))([email protected])([email protected](@swc/[email protected](@swc/[email protected]))([email protected])) watchpack: 2.4.2 webpack-sources: 3.2.3 transitivePeerDependencies:
8b715a81278c8fce579014588eb0a06a6077c9f4
2023-09-22 05:35:57
Alessio Gravili
chore: revert setting default db to postgres
false
revert setting default db to postgres
chore
diff --git a/test/buildConfigWithDefaults.ts b/test/buildConfigWithDefaults.ts index 135617577ba..afee7a37d8d 100644 --- a/test/buildConfigWithDefaults.ts +++ b/test/buildConfigWithDefaults.ts @@ -9,7 +9,7 @@ import { postgresAdapter } from '../packages/db-postgres/src/index' import { buildConfig as buildPayloadConfig } from '../packages/payload/src/config/build' import { createSlate } from '../packages/richtext-slate/src' -process.env.PAYLOAD_DATABASE = 'postgres' +// process.env.PAYLOAD_DATABASE = 'postgres' const databaseAdapters = { mongoose: mongooseAdapter({
ea80fd68b14139cb01259a47ea597d33526d0c76
2021-06-29 19:13:18
Dan Ribbens
fix: changes scss imports to allow vars imports to payload projects
false
changes scss imports to allow vars imports to payload projects
fix
diff --git a/scss/vars.scss b/scss/vars.scss index 28fe755c446..e3fad15b306 100644 --- a/scss/vars.scss +++ b/scss/vars.scss @@ -1 +1,13 @@ @import '../dist/admin/scss/vars'; +@import '../dist/admin/scss/z-index'; + +////////////////////////////// +// IMPORT OVERRIDES +////////////////////////////// + +@import '~payload-scss-overrides'; + +@import '../dist/admin/scss/type'; +@import '../dist/admin/scss/queries'; +@import '../dist/admin/scss/resets'; +@import '../dist/admin/scss/svg';
f5fb095df4de32f38994b4ba03d359e91011a9ad
2024-05-07 19:09:11
Alessio Gravili
feat(richtext-lexical): improve draggable block indicator style and animations
false
improve draggable block indicator style and animations
feat
diff --git a/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/getNodeCloseToPoint.ts b/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/getNodeCloseToPoint.ts index b625e1b64ec..09811d8b163 100644 --- a/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/getNodeCloseToPoint.ts +++ b/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/getNodeCloseToPoint.ts @@ -15,7 +15,7 @@ const Indeterminate = 0 type Props = { anchorElem: HTMLElement - cache_treshold?: number + cache_threshold?: number editor: LexicalEditor /** fuzzy makes the search not exact. If no exact match found, find the closes node instead of returning null */ fuzzy?: boolean @@ -51,7 +51,7 @@ function isPointClose(previous: Point, current: Point, threshold: number = 20): export function getNodeCloseToPoint(props: Props): Output { const { anchorElem, - cache_treshold = 20, + cache_threshold = 20, editor, fuzzy = false, horizontalOffset = 0, @@ -63,13 +63,13 @@ export function getNodeCloseToPoint(props: Props): Output { // Use cache if ( - cache_treshold > 0 && + cache_threshold > 0 && cache.props && cache.result && cache.props.fuzzy === props.fuzzy && cache.props.horizontalOffset === props.horizontalOffset && cache.props.useEdgeAsDefault === props.useEdgeAsDefault && - isPointClose(cache.props.point, props.point, cache_treshold) + isPointClose(cache.props.point, props.point, cache_threshold) ) { if (verbose) { //console.log('Returning cached result') diff --git a/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/index.scss b/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/index.scss index 59c4f18ef29..4cc2862214f 100644 --- a/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/index.scss +++ b/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/index.scss @@ -53,3 +53,11 @@ transition: none; } } + + +.rich-text-lexical { + .ContentEditable__root > * { + will-change: margin-top, margin-bottom; + transition: margin-top 0.08s, margin-bottom 0.08s; + } +} diff --git a/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/index.tsx b/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/index.tsx index 56b04e9647d..0bd6f1313fe 100644 --- a/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/index.tsx +++ b/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/index.tsx @@ -55,8 +55,11 @@ function hideTargetLine( targetLineElem.style.opacity = '0' } if (lastTargetBlockElem) { - lastTargetBlockElem.style.opacity = '1' - lastTargetBlockElem.style.transform = 'translate(0, 0)' + lastTargetBlockElem.style.opacity = '' + lastTargetBlockElem.style.transform = '' + // Delete marginBottom and marginTop values we set + lastTargetBlockElem.style.marginBottom = '' + lastTargetBlockElem.style.marginTop = '' //lastTargetBlockElem.style.border = 'none' } } @@ -139,7 +142,7 @@ function useDraggableBlockMenu( isFoundNodeEmptyParagraph, } = getNodeCloseToPoint({ anchorElem, - cache_treshold: 0, + cache_threshold: 0, editor, horizontalOffset: -distanceFromScrollerElem, point: new Point(event.x, event.y), diff --git a/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/setTargetLine.ts b/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/setTargetLine.ts index d60e28087d5..ba4a176ea36 100644 --- a/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/setTargetLine.ts +++ b/packages/richtext-lexical/src/field/lexical/plugins/handles/DraggableBlockPlugin/setTargetLine.ts @@ -36,20 +36,39 @@ export function setTargetLine( lineTop += targetBlockElemHeight / 2 } - const top = lineTop - anchorTop - TARGET_LINE_HALF_HEIGHT + const targetElemTranslate = 0 + let targetElemTranslate2 = 0 + + if (!isFoundNodeEmptyParagraph) { + if (isBelow) { + targetElemTranslate2 = -TARGET_LINE_HALF_HEIGHT + } else { + targetElemTranslate2 = TARGET_LINE_HALF_HEIGHT + } + } + + let top = lineTop - anchorTop + targetElemTranslate2 + if (!isBelow) { + top -= TARGET_LINE_HALF_HEIGHT * 2 + } const left = TEXT_BOX_HORIZONTAL_PADDING - SPACE targetLineElem.style.transform = `translate(${left}px, ${top}px)` targetLineElem.style.width = `${anchorWidth - (TEXT_BOX_HORIZONTAL_PADDING - SPACE) * 2}px` targetLineElem.style.opacity = '.4' - targetBlockElem.style.opacity = '0.4' + /** + * Move around element below or above the line (= the target / targetBlockElem) + */ + //targetBlockElem.style.opacity = '0.4' if (!isFoundNodeEmptyParagraph) { // move lastTargetBlockElem down 50px to make space for targetLineElem (which is 50px height) + targetBlockElem.style.transform = `translate(0, ${targetElemTranslate}px)` if (isBelow) { - targetBlockElem.style.transform = `translate(0, ${-TARGET_LINE_HALF_HEIGHT / 1.9}px)` + // add to existing marginBottom plus the height of targetLineElem + targetBlockElem.style.marginBottom = TARGET_LINE_HALF_HEIGHT * 2 + 'px' } else { - targetBlockElem.style.transform = `translate(0, ${TARGET_LINE_HALF_HEIGHT / 1.9}px)` + targetBlockElem.style.marginTop = TARGET_LINE_HALF_HEIGHT * 2 + 'px' } } @@ -59,8 +78,12 @@ export function setTargetLine( } if (lastTargetBlockElem && lastTargetBlockElem !== targetBlockElem) { - lastTargetBlockElem.style.opacity = '1' - lastTargetBlockElem.style.transform = 'translate(0, 0)' + lastTargetBlockElem.style.opacity = '' + lastTargetBlockElem.style.transform = '' + + // Delete marginBottom and marginTop values we set + lastTargetBlockElem.style.marginBottom = '' + lastTargetBlockElem.style.marginTop = '' //lastTargetBlockElem.style.border = 'none' } }
4fb8b0fa28637efe9c8d04eecb2486e073c0a3f6
2023-04-24 22:28:49
Jessica Boezwinkle
chore: updates richText docs
false
updates richText docs
chore
diff --git a/docs/fields/rich-text.mdx b/docs/fields/rich-text.mdx index c23497df881..6d3f210707f 100644 --- a/docs/fields/rich-text.mdx +++ b/docs/fields/rich-text.mdx @@ -55,6 +55,7 @@ The default `elements` available in Payload are: - `h4` - `h5` - `h6` +- `blockquote` - `link` - `ol` - `ul` @@ -154,6 +155,7 @@ const ExampleCollection: CollectionConfig = { 'h3', 'h4', 'link', + 'blockquote', { name: 'cta', Button: CustomCallToActionButton,
5cc0e74471076ce596f64ed8ecfb3c1b0d247efc
2025-03-06 00:29:49
Sasha
fix(storage-*): client uploads with `disablePayloadAccessControl: true` (#11530)
false
client uploads with `disablePayloadAccessControl: true` (#11530)
fix
diff --git a/packages/plugin-cloud-storage/src/plugin.ts b/packages/plugin-cloud-storage/src/plugin.ts index a7d4f7e80fb..ae789cc9367 100644 --- a/packages/plugin-cloud-storage/src/plugin.ts +++ b/packages/plugin-cloud-storage/src/plugin.ts @@ -60,6 +60,17 @@ export const cloudStoragePlugin = if (!options.disablePayloadAccessControl) { handlers.push(adapter.staticHandler) + // Else if disablePayloadAccessControl: true and clientUploads is used + // Build the "proxied" handler that responses only when the file was requested by client upload in addDataAndFileToRequest + } else if (adapter.clientUploads) { + handlers.push((req, args) => { + if ('clientUploadContext' in args.params) { + return adapter.staticHandler(req, args) + } + + // Otherwise still skip staticHandler + return null + }) } return { diff --git a/packages/plugin-cloud-storage/src/types.ts b/packages/plugin-cloud-storage/src/types.ts index a46de6c5369..a1e1da9aee1 100644 --- a/packages/plugin-cloud-storage/src/types.ts +++ b/packages/plugin-cloud-storage/src/types.ts @@ -63,6 +63,7 @@ export type StaticHandler = ( ) => Promise<Response> | Response export interface GeneratedAdapter { + clientUploads?: ClientUploadsConfig /** * Additional fields to be injected into the base collection and image sizes */ diff --git a/packages/storage-azure/src/index.ts b/packages/storage-azure/src/index.ts index dd965c450e7..99788b1be28 100644 --- a/packages/storage-azure/src/index.ts +++ b/packages/storage-azure/src/index.ts @@ -134,7 +134,13 @@ export const azureStorage: AzureStoragePlugin = function azureStorageInternal( getStorageClient: () => ContainerClient, - { allowContainerCreate, baseURL, connectionString, containerName }: AzureStorageOptions, + { + allowContainerCreate, + baseURL, + clientUploads, + connectionString, + containerName, + }: AzureStorageOptions, ): Adapter { const createContainerIfNotExists = () => { void getStorageClientFunc({ connectionString, containerName }).createIfNotExists({ @@ -145,6 +151,7 @@ function azureStorageInternal( return ({ collection, prefix }): GeneratedAdapter => { return { name: 'azure', + clientUploads, generateURL: getGenerateURL({ baseURL, containerName }), handleDelete: getHandleDelete({ collection, getStorageClient }), handleUpload: getHandleUpload({ diff --git a/packages/storage-gcs/src/index.ts b/packages/storage-gcs/src/index.ts index b64507755be..c6f3b1a26fe 100644 --- a/packages/storage-gcs/src/index.ts +++ b/packages/storage-gcs/src/index.ts @@ -128,11 +128,12 @@ export const gcsStorage: GcsStoragePlugin = function gcsStorageInternal( getStorageClient: () => Storage, - { acl, bucket }: GcsStorageOptions, + { acl, bucket, clientUploads }: GcsStorageOptions, ): Adapter { return ({ collection, prefix }): GeneratedAdapter => { return { name: 'gcs', + clientUploads, generateURL: getGenerateURL({ bucket, getStorageClient }), handleDelete: getHandleDelete({ bucket, getStorageClient }), handleUpload: getHandleUpload({ diff --git a/packages/storage-s3/src/index.ts b/packages/storage-s3/src/index.ts index e5d9baa3e47..b05942a2593 100644 --- a/packages/storage-s3/src/index.ts +++ b/packages/storage-s3/src/index.ts @@ -142,11 +142,12 @@ export const s3Storage: S3StoragePlugin = function s3StorageInternal( getStorageClient: () => AWS.S3, - { acl, bucket, config = {} }: S3StorageOptions, + { acl, bucket, clientUploads, config = {} }: S3StorageOptions, ): Adapter { return ({ collection, prefix }): GeneratedAdapter => { return { name: 's3', + clientUploads, generateURL: getGenerateURL({ bucket, config }), handleDelete: getHandleDelete({ bucket, getStorageClient }), handleUpload: getHandleUpload({ diff --git a/packages/storage-uploadthing/src/index.ts b/packages/storage-uploadthing/src/index.ts index 96c7186c91e..b47b4992888 100644 --- a/packages/storage-uploadthing/src/index.ts +++ b/packages/storage-uploadthing/src/index.ts @@ -141,6 +141,7 @@ function uploadthingInternal(options: UploadthingStorageOptions): Adapter { return (): GeneratedAdapter => { const { + clientUploads, options: { acl = 'public-read', ...utOptions }, } = options @@ -148,6 +149,7 @@ function uploadthingInternal(options: UploadthingStorageOptions): Adapter { return { name: 'uploadthing', + clientUploads, fields, generateURL, handleDelete: getHandleDelete({ utApi }), diff --git a/packages/storage-vercel-blob/src/index.ts b/packages/storage-vercel-blob/src/index.ts index dc8c4ebf7b5..a2480c69726 100644 --- a/packages/storage-vercel-blob/src/index.ts +++ b/packages/storage-vercel-blob/src/index.ts @@ -172,7 +172,7 @@ function vercelBlobStorageInternal( options: { baseUrl: string } & VercelBlobStorageOptions, ): Adapter { return ({ collection, prefix }): GeneratedAdapter => { - const { access, addRandomSuffix, baseUrl, cacheControlMaxAge, token } = options + const { access, addRandomSuffix, baseUrl, cacheControlMaxAge, clientUploads, token } = options if (!token) { throw new Error('Vercel Blob storage token is required') @@ -180,6 +180,7 @@ function vercelBlobStorageInternal( return { name: 'vercel-blob', + clientUploads, generateURL: getGenerateUrl({ baseUrl, prefix }), handleDelete: getHandleDelete({ baseUrl, prefix, token }), handleUpload: getHandleUpload({
580520f10064eda282b11553eb88edfc7a2a8674
2024-03-15 06:52:30
Alessio Gravili
chore: add back relaxed eslint rules for tests
false
add back relaxed eslint rules for tests
chore
diff --git a/test/.eslintrc.cjs b/test/.eslintrc.cjs index 39a96642f1a..91d9879c384 100644 --- a/test/.eslintrc.cjs +++ b/test/.eslintrc.cjs @@ -5,4 +5,65 @@ module.exports = { project: ['./tsconfig.eslint.json'], tsconfigRootDir: __dirname, }, + overrides: [ + { + extends: ['plugin:@typescript-eslint/disable-type-checked'], + files: [ + '*.js', + '*.cjs', + 'playwright.config.ts', + 'playwright.bail.config.ts', + 'bin-cks.cjs', + 'bin-esm.mjs', + 'esm-loader.mjs', + 'esm-loader-playwright.mjs', + '*.json', + '*.md', + '*.yml', + '*.yaml', + ], + }, + { + files: ['config.ts'], + rules: { + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-use-before-define': 'off', + // turn the @typescript-eslint/unbound-method rule off *only* for test files. See https://typescript-eslint.io/rules/unbound-method/#when-not-to-use-it + '@typescript-eslint/unbound-method': 'off', + 'no-console': 'off', + 'perfectionist/sort-objects': 'off', + }, + }, + { + files: ['**/int.spec.ts'], + rules: { + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-use-before-define': 'off', + 'jest/prefer-strict-equal': 'off', + }, + }, + { + extends: ['plugin:playwright/playwright-test'], + files: ['**/e2e.spec.ts'], + rules: { + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-use-before-define': 'off', + 'jest/consistent-test-it': 'off', + 'jest/expect-expect': 'off', + 'jest/no-test-callback': 'off', + 'jest/prefer-strict-equal': 'off', + 'jest/require-top-level-describe': 'off', + 'jest-dom/prefer-to-have-attribute': 'off', + }, + }, + { + files: ['*.e2e.ts'], + rules: { + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-use-before-define': 'off', + 'jest/expect-expect': 'off', + }, + }, + ], }
81522b33e69297aadbe727efc923172a46c1e7bc
2024-03-18 20:06:13
James
chore: removes setOnSave from DocumentInfo, refreshes cookie when saving user
false
removes setOnSave from DocumentInfo, refreshes cookie when saving user
chore
diff --git a/packages/next/src/views/Edit/Default/index.tsx b/packages/next/src/views/Edit/Default/index.tsx index d9d5ae08dfc..1e5000ceae7 100644 --- a/packages/next/src/views/Edit/Default/index.tsx +++ b/packages/next/src/views/Edit/Default/index.tsx @@ -8,13 +8,17 @@ import { FormLoadingOverlayToggle, OperationProvider, getFormState, + useAuth, useComponentMap, useConfig, useDocumentEvents, useDocumentInfo, useEditDepth, + useFormQueryParams, } from '@payloadcms/ui' import { Upload } from '@payloadcms/ui/elements' +import { useRouter } from 'next/navigation.js' +import { useSearchParams } from 'next/navigation.js' import React, { Fragment, useCallback } from 'react' import { LeaveWithoutSaving } from '../../../elements/LeaveWithoutSaving/index.js' @@ -42,26 +46,33 @@ export const DefaultEditView: React.FC = () => { disableActions, disableLeaveWithoutSaving, docPermissions, + getDocPermissions, getDocPreferences, + getVersions, globalSlug, hasSavePermission, initialData: data, initialState, - onSave: onSaveFromContext, + isEditing, } = useDocumentInfo() + const { refreshCookieAsync, user } = useAuth() const config = useConfig() + const router = useRouter() + const { dispatchFormQueryParams } = useFormQueryParams() + const { getComponentMap, getFieldMap } = useComponentMap() + const params = useSearchParams() + const depth = useEditDepth() + const { reportUpdate } = useDocumentEvents() const { collections, globals, - routes: { api: apiRoute }, + routes: { admin: adminRoute, api: apiRoute }, serverURL, } = config - const { getComponentMap, getFieldMap } = useComponentMap() - - const depth = useEditDepth() + const locale = params.get('locale') const componentMap = getComponentMap({ collectionSlug, globalSlug }) @@ -77,8 +88,6 @@ export const DefaultEditView: React.FC = () => { globalSlug: globalConfig?.slug, }) - const { reportUpdate } = useDocumentEvents() - const operation = id ? 'update' : 'create' const auth = collectionConfig ? collectionConfig.auth : undefined @@ -99,23 +108,43 @@ export const DefaultEditView: React.FC = () => { updatedAt: json?.result?.updatedAt || new Date().toISOString(), }) - // if (auth && id === user.id) { - // await refreshCookieAsync() - // } + // If we're editing the doc of the logged in user, + // Refresh the cookie to get new permissions + if (collectionSlug === user?.collection && id === user.id) { + void refreshCookieAsync() + } + + void getVersions() + void getDocPermissions() - if (typeof onSaveFromContext === 'function') { - void onSaveFromContext({ - ...json, - operation: id ? 'update' : 'create', + if (!isEditing) { + // Redirect to the same locale if it's been set + const redirectRoute = `${adminRoute}/collections/${collectionSlug}/${json?.doc?.id}${locale ? `?locale=${locale}` : ''}` + router.push(redirectRoute) + } else { + dispatchFormQueryParams({ + type: 'SET', + params: { + uploadEdits: null, + }, }) } }, [ - id, - onSaveFromContext, - // refreshCookieAsync, reportUpdate, + id, entitySlug, + collectionSlug, + user?.collection, + user.id, + getVersions, + getDocPermissions, + isEditing, + refreshCookieAsync, + adminRoute, + locale, + router, + dispatchFormQueryParams, ], ) diff --git a/packages/next/src/views/Edit/index.client.tsx b/packages/next/src/views/Edit/index.client.tsx index d644688b5f8..386fa914e58 100644 --- a/packages/next/src/views/Edit/index.client.tsx +++ b/packages/next/src/views/Edit/index.client.tsx @@ -1,73 +1,18 @@ 'use client' -import { - LoadingOverlay, - SetViewActions, - useComponentMap, - useConfig, - useDocumentInfo, - useFormQueryParams, -} from '@payloadcms/ui' -import { useRouter } from 'next/navigation.js' -import { useSearchParams } from 'next/navigation.js' -import React, { Fragment, useEffect } from 'react' -import { useCallback } from 'react' +import { LoadingOverlay, SetViewActions, useComponentMap, useDocumentInfo } from '@payloadcms/ui' +import React, { Fragment } from 'react' export const EditViewClient: React.FC = () => { - const { collectionSlug, getDocPermissions, getVersions, globalSlug, isEditing, setOnSave } = - useDocumentInfo() - - const { - routes: { admin: adminRoute }, - } = useConfig() - - const router = useRouter() - const { dispatchFormQueryParams } = useFormQueryParams() + const { collectionSlug, globalSlug } = useDocumentInfo() const { getComponentMap } = useComponentMap() - const params = useSearchParams() - - const locale = params.get('locale') const { Edit, actionsMap } = getComponentMap({ collectionSlug, globalSlug, }) - const onSave = useCallback( - (json: { doc }) => { - void getVersions() - void getDocPermissions() - - if (!isEditing) { - // Redirect to the same locale if it's been set - const redirectRoute = `${adminRoute}/collections/${collectionSlug}/${json?.doc?.id}${locale ? `?locale=${locale}` : ''}` - router.push(redirectRoute) - } else { - dispatchFormQueryParams({ - type: 'SET', - params: { - uploadEdits: null, - }, - }) - } - }, - [ - adminRoute, - collectionSlug, - dispatchFormQueryParams, - getDocPermissions, - getVersions, - isEditing, - router, - locale, - ], - ) - - useEffect(() => { - void setOnSave(() => onSave) - }, [setOnSave, onSave]) - // Allow the `DocumentInfoProvider` to hydrate if (!Edit || (!collectionSlug && !globalSlug)) { return <LoadingOverlay /> diff --git a/packages/ui/src/providers/DocumentInfo/index.tsx b/packages/ui/src/providers/DocumentInfo/index.tsx index 4c6329312f5..e091b092700 100644 --- a/packages/ui/src/providers/DocumentInfo/index.tsx +++ b/packages/ui/src/providers/DocumentInfo/index.tsx @@ -26,7 +26,6 @@ export const DocumentInfoProvider: React.FC< } > = ({ children, ...props }) => { const [documentTitle, setDocumentTitle] = useState(props.title) - const [onSave, setOnSave] = useState(() => props.onSave) const { id, collectionSlug, globalSlug } = props @@ -301,11 +300,11 @@ export const DocumentInfoProvider: React.FC< getDocPreferences, getVersions, hasSavePermission, - onSave, + isEditingUser: Boolean(props.isEditingUser), + onSave: props.onSave, publishedDoc, setDocFieldPreferences, setDocumentTitle, - setOnSave, title: documentTitle, unpublishedVersions, versions, diff --git a/packages/ui/src/providers/DocumentInfo/types.ts b/packages/ui/src/providers/DocumentInfo/types.ts index 2d1af21a0ad..fdca66ce206 100644 --- a/packages/ui/src/providers/DocumentInfo/types.ts +++ b/packages/ui/src/providers/DocumentInfo/types.ts @@ -52,5 +52,4 @@ export type DocumentInfoContext = DocumentInfo & { fieldPreferences: Partial<InsideFieldsPreferences> & { [key: string]: unknown }, ) => void setDocumentTitle: (title: string) => void - setOnSave: (data: Data) => Promise<void> | void }
5b36bd7b43974df9fe6d0362fb9911f07588c7f9
2021-10-22 05:05:22
James
chore: dependencies
false
dependencies
chore
diff --git a/yarn.lock b/yarn.lock index bb23f426492..c5250891325 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1157,24 +1157,6 @@ resolved "https://registry.npmjs.org/@faceless-ui/window-info/-/window-info-1.2.9.tgz#313c36c7180e6d15d2e49269f04a90b9192ac2ab" integrity sha512-wGJk77HP2hJ9gsV/Pgqx7bK4FnGrmrmQyBgSB6s7yPPG9/iaPuDugl2kaE4Fi26EX9FdSIumyyveI4CSSgghkg== -"@fluentui/dom-utilities@^1.1.2": - version "1.1.2" - resolved "https://registry.npmjs.org/@fluentui/dom-utilities/-/dom-utilities-1.1.2.tgz#1a53e51e1ab1d40696ae7d355a970c68d496845f" - integrity sha512-XqPS7l3YoMwxdNlaYF6S2Mp0K3FmVIOIy2K3YkMc+eRxu9wFK6emr2Q/3rBhtG5u/On37NExRT7/5CTLnoi9gw== - dependencies: - "@uifabric/set-version" "^7.0.24" - tslib "^1.10.0" - -"@fluentui/theme@^1.7.4": - version "1.7.4" - resolved "https://registry.npmjs.org/@fluentui/theme/-/theme-1.7.4.tgz#8582bab5a7445585c631d05d44b5ebb56f18b6ba" - integrity sha512-o4eo7lstLxxXl1g2RR9yz18Yt8yjQO/LbQuZjsiAfv/4Bf0CRnb+3j1F7gxIdBWAchKj9gzaMpIFijfI98pvYQ== - dependencies: - "@uifabric/merge-styles" "^7.19.2" - "@uifabric/set-version" "^7.0.24" - "@uifabric/utilities" "^7.33.5" - tslib "^1.10.0" - "@gar/promisify@^1.0.1": version "1.1.2" resolved "https://registry.npmjs.org/@gar/promisify/-/promisify-1.1.2.tgz#30aa825f11d438671d585bd44e7fd564535fc210" @@ -1413,11 +1395,6 @@ "@types/yargs" "^16.0.0" chalk "^4.0.0" -"@microsoft/load-themed-styles@^1.10.26": - version "1.10.224" - resolved "https://registry.npmjs.org/@microsoft/load-themed-styles/-/load-themed-styles-1.10.224.tgz#415e0c2c64cc20bfa0014267cb1482dff5eaa4e9" - integrity sha512-ZtYKEVYwDg49UlqyuxsboE3TJ6IxGv1Igoqu0Q5oxuxTcIAIOLqyRadUiU3SHoPq0K+9ZWXWM7tUgfsVB7QXqA== - "@nicolo-ribaudo/[email protected]": version "2.1.8-no-fsevents.3" resolved "https://registry.npmjs.org/@nicolo-ribaudo/chokidar-2/-/chokidar-2-2.1.8-no-fsevents.3.tgz#323d72dd25103d0c4fbdce89dadf574a787b1f9b" @@ -1573,31 +1550,6 @@ resolved "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.21.tgz#5de5a2385a35309427f6011992b544514d559aa1" integrity sha512-a5Sab1C4/icpTZVzZc5Ghpz88yQtGOyNqYXcZgOssB2uuAr+wF/MvN6bgtW32q7HHrvBki+BsZ0OuNv6EV3K9g== -"@popperjs/core@^2.9.0": - version "2.10.2" - resolved "https://registry.npmjs.org/@popperjs/core/-/core-2.10.2.tgz#0798c03351f0dea1a5a4cabddf26a55a7cbee590" - integrity sha512-IXf3XA7+XyN7CP9gGh/XB0UxVMlvARGEgGXLubFICsUMGz6Q+DU+i4gGlpOxTjKvXjkJDJC8YdqdKkDj9qZHEQ== - -"@react-dnd/asap@^4.0.0": - version "4.0.0" - resolved "https://registry.npmjs.org/@react-dnd/asap/-/asap-4.0.0.tgz#b300eeed83e9801f51bd66b0337c9a6f04548651" - integrity sha512-0XhqJSc6pPoNnf8DhdsPHtUhRzZALVzYMTzRwV4VI6DJNJ/5xxfL9OQUwb8IH5/2x7lSf7nAZrnzUD+16VyOVQ== - -"@react-dnd/invariant@^2.0.0": - version "2.0.0" - resolved "https://registry.npmjs.org/@react-dnd/invariant/-/invariant-2.0.0.tgz#09d2e81cd39e0e767d7da62df9325860f24e517e" - integrity sha512-xL4RCQBCBDJ+GRwKTFhGUW8GXa4yoDfJrPbLblc3U09ciS+9ZJXJ3Qrcs/x2IODOdIE5kQxvMmE2UKyqUictUw== - -"@react-dnd/shallowequal@^2.0.0": - version "2.0.0" - resolved "https://registry.npmjs.org/@react-dnd/shallowequal/-/shallowequal-2.0.0.tgz#a3031eb54129f2c66b2753f8404266ec7bf67f0a" - integrity sha512-Pc/AFTdwZwEKJxFJvlxrSmGe/di+aAOBn60sremrpLo6VI/6cmiUYNNwlI5KNYttg7uypzA3ILPMPgxB2GYZEg== - -"@react-hook/merged-ref@^1.3.0": - version "1.3.2" - resolved "https://registry.npmjs.org/@react-hook/merged-ref/-/merged-ref-1.3.2.tgz#919b387a5f79ed67f2578f2015ab7b7d337787d2" - integrity sha512-cQ9Y8m4zlrw/qotReo33E+3Sy9FVqMZb5JwUlb3wj3IJJ1cNJtxcgfWF6rS2NZQrfBJ2nAnckUdPJjMyIJTNZg== - "@release-it/conventional-changelog@^2.0.0": version "2.0.1" resolved "https://registry.npmjs.org/@release-it/conventional-changelog/-/conventional-changelog-2.0.1.tgz#bdd52ad3ecc0d6e39d637592d6ea2bd6d28e5ecb" @@ -1700,13 +1652,6 @@ "@babel/runtime" "^7.12.5" "@testing-library/dom" "^7.28.1" -"@tippyjs/react@^4.0.2": - version "4.2.5" - resolved "https://registry.npmjs.org/@tippyjs/react/-/react-4.2.5.tgz#9b5837db93a1cac953962404df906aef1a18e80d" - integrity sha512-YBLgy+1zznBNbx4JOoOdFXWMLXjBh9hLPwRtq3s8RRdrez2l3tPBRt2m2909wZd9S1KUeKjOOYYsnitccI9I3A== - dependencies: - tippy.js "^6.3.1" - "@tootallnate/once@1": version "1.1.2" resolved "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz#ccb91445360179a04e7fe6aff78c00ffc1eeaf82" @@ -1843,11 +1788,6 @@ dependencies: "@types/node" "*" -"@types/escape-html@^1.0.0": - version "1.0.1" - resolved "https://registry.npmjs.org/@types/escape-html/-/escape-html-1.0.1.tgz#b19b4646915f0ae2c306bf984dc0a59c5cfc97ba" - integrity sha512-4mI1FuUUZiuT95fSVqvZxp/ssQK9zsa86S43h9x3zPOSU9BBJ+BfDkXwuaU7BfsD+e7U0/cUUfJFk3iW2M4okA== - "@types/eslint-scope@^3.7.0": version "3.7.1" resolved "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.1.tgz#8dc390a7b4f9dd9f1284629efce982e41612116e" @@ -1933,7 +1873,7 @@ resolved "https://registry.npmjs.org/@types/history/-/history-4.7.9.tgz#1cfb6d60ef3822c589f18e70f8b12f9a28ce8724" integrity sha512-MUc6zSmU3tEVnkQ78q0peeEjKWPUADMlC/t++2bI8WnAG2tvYRPIgHG8lWkXwqc8MsUF6Z2MOf+Mh5sazOmhiQ== -"@types/hoist-non-react-statics@^3.3.0", "@types/hoist-non-react-statics@^3.3.1": +"@types/hoist-non-react-statics@^3.3.0": version "3.3.1" resolved "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz#1124aafe5118cb591977aeb1ceaaed1070eb039f" integrity sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA== @@ -2026,11 +1966,6 @@ resolved "https://registry.npmjs.org/@types/joi/-/joi-14.3.4.tgz#eed1e14cbb07716079c814138831a520a725a1e0" integrity sha512-1TQNDJvIKlgYXGNIABfgFp9y0FziDpuGrd799Q5RcnsDu+krD+eeW/0Fs5PHARvWWFelOhIG2OPCo6KbadBM4A== -"@types/[email protected]": - version "2.2.6" - resolved "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-2.2.6.tgz#f1a1cb35aff47bc5cfb05cb0c441ca91e914c26f" - integrity sha512-+oY0FDTO2GYKEV0YPvSshGq9t7YozVkgvXLty7zogQNuCxBhT9/3INX9Q7H1aRZ4SUDRXAKlJuA4EA5nTt7SNw== - "@types/json-schema@*", "@types/json-schema@^7.0.3", "@types/json-schema@^7.0.5", "@types/json-schema@^7.0.7", "@types/json-schema@^7.0.8": version "7.0.9" resolved "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.9.tgz#97edc9037ea0c38585320b28964dde3b39e4660d" @@ -2060,13 +1995,6 @@ resolved "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.175.tgz#b78dfa959192b01fae0ad90e166478769b215f45" integrity sha512-XmdEOrKQ8a1Y/yxQFOMbC47G/V2VDO1GvMRnl4O75M4GW/abC5tnfzadQYkqEveqRM1dEJGFFegfPNA2vvx2iw== -"@types/mdast@^3.0.0": - version "3.0.10" - resolved "https://registry.npmjs.org/@types/mdast/-/mdast-3.0.10.tgz#4724244a82a4598884cbbe9bcfd73dff927ee8af" - integrity sha512-W864tg/Osz1+9f4lrGTZpCSO5/z4608eUp19tbozkq2HJK6i3z1kT0H9tlADXuYIb1YYOBByU4Jsqkk75q48qA== - dependencies: - "@types/unist" "*" - "@types/method-override@^0.0.31": version "0.0.31" resolved "https://registry.npmjs.org/@types/method-override/-/method-override-0.0.31.tgz#ec12b738c1b2a74a5d3d8af73c7d4952ad9c14d2" @@ -2448,11 +2376,6 @@ dependencies: source-map "^0.6.1" -"@types/unist@*", "@types/unist@^2.0.0", "@types/unist@^2.0.2": - version "2.0.6" - resolved "https://registry.npmjs.org/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d" - integrity sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ== - "@types/uuid@^8.3.0": version "8.3.1" resolved "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.1.tgz#1a32969cf8f0364b3d8c8af9cc3555b7805df14f" @@ -2690,71 +2613,6 @@ "@typescript-eslint/types" "4.33.0" eslint-visitor-keys "^2.0.0" -"@udecode/slate-plugins-core@^0.71.11": - version "0.71.11" - resolved "https://registry.npmjs.org/@udecode/slate-plugins-core/-/slate-plugins-core-0.71.11.tgz#6e8e7c4af4e484b990031a4762165f28c45163cb" - integrity sha512-JbMbwl8V7fwK4JPbkhspDeBJ8+pk1QGw5l0IDREBCFaviqBg5shYs1ij6jnN7xKEQ+bIc0ogqxJ8B8zhq9pC5w== - -"@udecode/slate-plugins@^0.71.9": - version "0.71.11" - resolved "https://registry.npmjs.org/@udecode/slate-plugins/-/slate-plugins-0.71.11.tgz#6cafecdb524e331ad6d2306ea85a6f93075480a4" - integrity sha512-aodKa+b08aHrX7pGzijzt85JwvLfK7MWu84OieCOSBFWxPniZ1PLwNlSuFJYqVC25g6O8jJdjzIoQQtS/aEBBg== - dependencies: - "@react-hook/merged-ref" "^1.3.0" - "@tippyjs/react" "^4.0.2" - "@udecode/slate-plugins-core" "^0.71.11" - "@uifabric/styling" "^7.12.11" - "@uifabric/utilities" "^7.19.0" - image-extensions "^1.1.0" - is-hotkey "^0.1.6" - lodash "^4.17.15" - prismjs "^1.20.0" - react-dnd "^11.1.3" - react-dnd-html5-backend "^11.1.3" - react-use "^15.1.0" - remark-parse "^9.0.0" - remark-slate "^1.4.0" - unified "^9.1.0" - utility-types "^3.10.0" - -"@uifabric/merge-styles@^7.19.2": - version "7.19.2" - resolved "https://registry.npmjs.org/@uifabric/merge-styles/-/merge-styles-7.19.2.tgz#e020adc2f9b238f0feb855274dfeedaf6d5822a7" - integrity sha512-kTlhwglDqwVgIaJq+0yXgzi65plGhmFcPrfme/rXUGMJZoU+qlGT5jXj5d3kuI59p6VB8jWEg9DAxHozhYeu0g== - dependencies: - "@uifabric/set-version" "^7.0.24" - tslib "^1.10.0" - -"@uifabric/set-version@^7.0.24": - version "7.0.24" - resolved "https://registry.npmjs.org/@uifabric/set-version/-/set-version-7.0.24.tgz#8c67d8f1d67c1636a170efa8b622132da2d294a9" - integrity sha512-t0Pt21dRqdC707/ConVJC0WvcQ/KF7tKLU8AZY7YdjgJpMHi1c0C427DB4jfUY19I92f60LOQyhJ4efH+KpFEg== - dependencies: - tslib "^1.10.0" - -"@uifabric/styling@^7.12.11": - version "7.19.1" - resolved "https://registry.npmjs.org/@uifabric/styling/-/styling-7.19.1.tgz#a89e4762050f7f7ca65111c1121f7a276daf4153" - integrity sha512-1yvfVJ9HSB7TVUKocjs/ij3bsVHtfBRbhnhDtdMS9Fw13abf1IBOpwx8LPMGMt1nbeAmWbzlBI+Deoyij9lstA== - dependencies: - "@fluentui/theme" "^1.7.4" - "@microsoft/load-themed-styles" "^1.10.26" - "@uifabric/merge-styles" "^7.19.2" - "@uifabric/set-version" "^7.0.24" - "@uifabric/utilities" "^7.33.5" - tslib "^1.10.0" - -"@uifabric/utilities@^7.19.0", "@uifabric/utilities@^7.33.5": - version "7.33.5" - resolved "https://registry.npmjs.org/@uifabric/utilities/-/utilities-7.33.5.tgz#4e7ed4bab725c054005e9ac37b0f01d743089be4" - integrity sha512-I+Oi0deD/xltSluFY8l2EVd/J4mvOaMljxKO2knSD9/KoGDlo/o5GN4gbnVo8nIt76HWHLAk3KtlJKJm6BhbIQ== - dependencies: - "@fluentui/dom-utilities" "^1.1.2" - "@uifabric/merge-styles" "^7.19.2" - "@uifabric/set-version" "^7.0.24" - prop-types "^15.7.2" - tslib "^1.10.0" - "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.1.tgz#2bfd767eae1a6996f432ff7e8d7fc75679c0b6a7" @@ -2893,11 +2751,6 @@ resolved "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.6.0.tgz#2c275aa05c895eccebbfc34cfb223c6e8bd591a2" integrity sha512-ZkVeqEmRpBV2GHvjjUZqEai2PpUbuq8Bqd//vEYsp63J8WyexI8ppCqVS3Zs0QADf6aWuPdU+0XsPI647PVlQA== -"@xobotyi/[email protected]": - version "1.9.5" - resolved "https://registry.npmjs.org/@xobotyi/scrollbar-width/-/scrollbar-width-1.9.5.tgz#80224a6919272f405b87913ca13b92929bdf3c4d" - integrity sha512-N8tkAACJx2ww8vFMneJmaAgmjAG1tnVBZJRLRcx061tmsLRZHSEZSLuGWnwPtunsSLvSqXQ2wfp7Mgqg1I+2dQ== - "@xtuc/ieee754@^1.2.0": version "1.2.0" resolved "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz#eef014a3145ae477a1cbc00cd1e552336dceb790" @@ -3451,11 +3304,6 @@ babel-preset-jest@^26.6.2: babel-plugin-jest-hoist "^26.6.2" babel-preset-current-node-syntax "^1.0.0" -bail@^1.0.0: - version "1.0.5" - resolved "https://registry.npmjs.org/bail/-/bail-1.0.5.tgz#b6fa133404a392cbc1f8c4bf63f5953351e7a776" - integrity sha512-xFbRxM1tahm08yHBP16MMjVUAvDaBMD38zsM9EMAUN61omwLmKlOpB/Zku5QkjZ8TZ4vn53pj+t518cH0S03RQ== - balanced-match@^1.0.0: version "1.0.2" resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" @@ -3876,21 +3724,6 @@ char-regex@^1.0.2: resolved "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf" integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw== -character-entities-legacy@^1.0.0: - version "1.1.4" - resolved "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-1.1.4.tgz#94bc1845dce70a5bb9d2ecc748725661293d8fc1" - integrity sha512-3Xnr+7ZFS1uxeiUDvV02wQ+QDbc55o97tIV5zHScSPJpcLm/r0DFPcoY3tYRp+VZukxuMeKgXYmsXQHO05zQeA== - -character-entities@^1.0.0: - version "1.2.4" - resolved "https://registry.npmjs.org/character-entities/-/character-entities-1.2.4.tgz#e12c3939b7eaf4e5b15e7ad4c5e28e1d48c5b16b" - integrity sha512-iBMyeEHxfVnIakwOuDXpVkc54HijNgCyQB2w0VfGQThle6NXn50zU6V/u+LDhxHcDUPojn6Kpga3PTAD8W1bQw== - -character-reference-invalid@^1.0.0: - version "1.1.4" - resolved "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-1.1.4.tgz#083329cda0eae272ab3dbbf37e9a382c13af1560" - integrity sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg== - chardet@^0.7.0: version "0.7.0" resolved "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e" @@ -4424,13 +4257,6 @@ copy-descriptor@^0.1.0: resolved "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= -copy-to-clipboard@^3.2.0: - version "3.3.1" - resolved "https://registry.npmjs.org/copy-to-clipboard/-/copy-to-clipboard-3.3.1.tgz#115aa1a9998ffab6196f93076ad6da3b913662ae" - integrity sha512-i13qo6kIHTTpCm8/Wup+0b1mVWETvu2kIMzKoK8FpkLkFxlt0znUAHcMzox+T8sPlqtZXq3CulEjQHsYiGFJUw== - dependencies: - toggle-selection "^1.0.6" - copyfiles@^2.4.0: version "2.4.1" resolved "https://registry.npmjs.org/copyfiles/-/copyfiles-2.4.1.tgz#d2dcff60aaad1015f09d0b66e7f0f1c5cd3c5da5" @@ -4578,14 +4404,6 @@ css-has-pseudo@^0.10.0: postcss "^7.0.6" postcss-selector-parser "^5.0.0-rc.4" -css-in-js-utils@^2.0.0: - version "2.0.1" - resolved "https://registry.npmjs.org/css-in-js-utils/-/css-in-js-utils-2.0.1.tgz#3b472b398787291b47cfe3e44fecfdd9e914ba99" - integrity sha512-PJF0SpJT+WdbVVt0AOYp9C8GnuruRlL/UFW7932nLWmFLQTaWEzTBQEx7/hn4BuV+WON75iAViSUJLiU3PKbpA== - dependencies: - hyphenate-style-name "^1.0.2" - isobject "^3.0.1" - css-loader@^5.0.1: version "5.2.7" resolved "https://registry.npmjs.org/css-loader/-/css-loader-5.2.7.tgz#9b9f111edf6fb2be5dc62525644cbc9c232064ae" @@ -4807,7 +4625,7 @@ csstype@^2.5.7: resolved "https://registry.npmjs.org/csstype/-/csstype-2.6.18.tgz#980a8b53085f34af313410af064f2bd241784218" integrity sha512-RSU6Hyeg14am3Ah4VZEmeX8H7kLwEEirXe6aU2IPfKNvhXwTflK5HQRDNI0ypQXoqmm+QPyG2IaPuQE5zMwSIQ== -csstype@^3.0.2, csstype@^3.0.6: +csstype@^3.0.2: version "3.0.9" resolved "https://registry.npmjs.org/csstype/-/csstype-3.0.9.tgz#6410af31b26bd0520933d02cbc64fce9ce3fbf0b" integrity sha512-rpw6JPxK6Rfg1zLOYCSwle2GFOOsnjmDYDaBwEcwoOg4qlsIVCN789VkBZDJAGi4T07gI4YSutR43t9Zz4Lzuw== @@ -4867,7 +4685,7 @@ [email protected]: dependencies: ms "2.0.0" -debug@4, [email protected], [email protected], debug@^4.0.0, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1, debug@^4.2.0, debug@^4.3.1, debug@^4.3.2: +debug@4, [email protected], [email protected], debug@^4.0.1, debug@^4.1.0, debug@^4.1.1, debug@^4.2.0, debug@^4.3.1, debug@^4.3.2: version "4.3.2" resolved "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== @@ -5101,15 +4919,6 @@ direction@^1.0.3: resolved "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz#2b86fb686967e987088caf8b89059370d4837442" integrity sha512-GYqKi1aH7PJXxdhTeZBFrg8vUBeKXi+cNprXsC1kpJcbcVnV9wBsrOu1cQEdG0WeQwlfHiy3XvnKfIrJ2R0NzQ== -dnd-core@^11.1.3: - version "11.1.3" - resolved "https://registry.npmjs.org/dnd-core/-/dnd-core-11.1.3.tgz#f92099ba7245e49729d2433157031a6267afcc98" - integrity sha512-QugF55dNW+h+vzxVJ/LSJeTeUw9MCJ2cllhmVThVPEtF16ooBkxj0WBE5RB+AceFxMFo1rO6bJKXtqKl+JNnyA== - dependencies: - "@react-dnd/asap" "^4.0.0" - "@react-dnd/invariant" "^2.0.0" - redux "^4.0.4" - doctrine@^2.1.0: version "2.1.0" resolved "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" @@ -5324,13 +5133,6 @@ error-ex@^1.3.1: dependencies: is-arrayish "^0.2.1" -error-stack-parser@^2.0.6: - version "2.0.6" - resolved "https://registry.npmjs.org/error-stack-parser/-/error-stack-parser-2.0.6.tgz#5a99a707bd7a4c58a797902d48d82803ede6aad8" - integrity sha512-d51brTeqC+BHlwF0BhPtcYgF5nlzf9ZZ0ZIUQNZpc9ZB9qw5IJ2diTrBY9jlCJkTLITYPjmiX6OWCwH+fuyNgQ== - dependencies: - stackframe "^1.1.1" - es-abstract@^1.17.2, es-abstract@^1.18.5, es-abstract@^1.19.0, es-abstract@^1.19.1: version "1.19.1" resolved "https://registry.npmjs.org/es-abstract/-/es-abstract-1.19.1.tgz#d4885796876916959de78edaa0df456627115ec3" @@ -5395,7 +5197,7 @@ escape-goat@^2.0.0: resolved "https://registry.npmjs.org/escape-goat/-/escape-goat-2.1.1.tgz#1b2dc77003676c457ec760b2dc68edb648188675" integrity sha512-8/uIhbG12Csjy2JEW7D9pHbreaVaS/OpN3ycnyvElTdwM5n6GY6W6e2IPemfvGZeUMqZ9A/3GqIZMgKnBhAw/Q== -escape-html@^1.0.3, escape-html@~1.0.3: +escape-html@~1.0.3: version "1.0.3" resolved "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" integrity sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg= @@ -5807,7 +5609,7 @@ extend-shallow@^3.0.0, extend-shallow@^3.0.2: assign-symbols "^1.0.0" is-extendable "^1.0.1" -extend@^3.0.0, extend@~3.0.2: +extend@~3.0.2: version "3.0.2" resolved "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== @@ -5855,7 +5657,7 @@ extsprintf@^1.2.0: resolved "https://registry.npmjs.org/falsey/-/falsey-1.0.0.tgz#71bdd775c24edad9f2f5c015ce8be24400bb5d7d" integrity sha512-zMDNZ/Ipd8MY0+346CPvhzP1AsiVyNfTOayJza4reAIWf72xbkuFUDcJNxSAsQE1b9Bu0wijKb8Ngnh/a7fI5w== -fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: +fast-deep-equal@^3.1.1: version "3.1.3" resolved "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== @@ -5891,21 +5693,11 @@ fast-safe-stringify@^2.0.7, fast-safe-stringify@^2.0.8: resolved "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz#c406a83b6e70d9e35ce3b30a81141df30aeba884" integrity sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA== -fast-shallow-equal@^1.0.0: - version "1.0.0" - resolved "https://registry.npmjs.org/fast-shallow-equal/-/fast-shallow-equal-1.0.0.tgz#d4dcaf6472440dcefa6f88b98e3251e27f25628b" - integrity sha512-HPtaa38cPgWvaCFmRNhlc6NG7pv6NUHqjPgVAkWGoB9mQMwYB27/K0CvOM5Czy+qpT3e8XJ6Q4aPAnzpNpzNaw== - fastest-levenshtein@^1.0.12: version "1.0.12" resolved "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.12.tgz#9990f7d3a88cc5a9ffd1f1745745251700d497e2" integrity sha512-On2N+BpYJ15xIC974QNVuYGMOlEVt4s0EOI3wwMqOmK1fdDY+FN/zltPV8vosq4ad4c/gJ1KHScUn/6AWIgiow== -fastest-stable-stringify@^2.0.2: - version "2.0.2" - resolved "https://registry.npmjs.org/fastest-stable-stringify/-/fastest-stable-stringify-2.0.2.tgz#3757a6774f6ec8de40c4e86ec28ea02417214c76" - integrity sha512-bijHueCGd0LqqNK9b5oCMHc0MluJAx0cwqASgbWMvkO01lCYgIhacVRLcaDz3QnyYIRNJRDwMb41VuT6pHJ91Q== - fastify-warning@^0.2.0: version "0.2.0" resolved "https://registry.npmjs.org/fastify-warning/-/fastify-warning-0.2.0.tgz#e717776026a4493dc9a2befa44db6d17f618008f" @@ -6829,11 +6621,6 @@ human-signals@^2.1.0: resolved "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0" integrity sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw== -hyphenate-style-name@^1.0.2: - version "1.0.4" - resolved "https://registry.npmjs.org/hyphenate-style-name/-/hyphenate-style-name-1.0.4.tgz#691879af8e220aea5750e8827db4ef62a54e361d" - integrity sha512-ygGZLjmXfPHj+ZWh6LwbC37l43MhfztxetbFCoYTM2VjkIUpeHgSNn7QIyVFj7YQ1Wl9Cbw5sholVJPzWvC2MQ== - [email protected], iconv-lite@^0.4.24, iconv-lite@^0.4.4: version "0.4.24" resolved "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" @@ -6866,11 +6653,6 @@ ignore@^5.1.4, ignore@^5.1.8: resolved "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57" integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw== -image-extensions@^1.1.0: - version "1.1.0" - resolved "https://registry.npmjs.org/image-extensions/-/image-extensions-1.1.0.tgz#b8e6bf6039df0056e333502a00b6637a3105d894" - integrity sha1-uOa/YDnfAFbjM1AqALZjejEF2JQ= - immer@^9.0.6: version "9.0.6" resolved "https://registry.npmjs.org/immer/-/immer-9.0.6.tgz#7a96bf2674d06c8143e327cbf73539388ddf1a73" @@ -6967,13 +6749,6 @@ ini@^1.3.2, ini@~1.3.0: resolved "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== -inline-style-prefixer@^6.0.0: - version "6.0.1" - resolved "https://registry.npmjs.org/inline-style-prefixer/-/inline-style-prefixer-6.0.1.tgz#c5c0e43ba8831707afc5f5bbfd97edf45c1fa7ae" - integrity sha512-AsqazZ8KcRzJ9YPN1wMH2aNM7lkWQ8tSPrW5uDk1ziYwiAPWSZnUsC7lfZq+BDqLqz0B4Pho5wscWcJzVvRzDQ== - dependencies: - css-in-js-utils "^2.0.0" - [email protected]: version "8.1.5" resolved "https://registry.npmjs.org/inquirer/-/inquirer-8.1.5.tgz#2dc5159203c826d654915b5fe6990fd17f54a150" @@ -7056,19 +6831,6 @@ is-accessor-descriptor@^1.0.0: dependencies: kind-of "^6.0.0" -is-alphabetical@^1.0.0: - version "1.0.4" - resolved "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-1.0.4.tgz#9e7d6b94916be22153745d184c298cbf986a686d" - integrity sha512-DwzsA04LQ10FHTZuL0/grVDk4rFoVH1pjAToYwBrHSxcrBIGQuXrQMtD5U1b0U2XVgKZCTLLP8u2Qxqhy3l2Vg== - -is-alphanumerical@^1.0.0: - version "1.0.4" - resolved "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-1.0.4.tgz#7eb9a2431f855f6b1ef1a78e326df515696c4dbf" - integrity sha512-UzoZUr+XfVz3t3v4KyGEniVL9BDRoQtY7tOyrRybkVNjDFWyo1yhXNGrrBTQxp3ib9BLAWs7k2YKBQsFRkZG9A== - dependencies: - is-alphabetical "^1.0.0" - is-decimal "^1.0.0" - is-arguments@^1.0.4, is-arguments@^1.1.0: version "1.1.1" resolved "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz#15b3f88fda01f2a97fec84ca761a560f123efa9b" @@ -7114,11 +6876,6 @@ is-buffer@^1.1.5, is-buffer@^1.1.6: resolved "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== -is-buffer@^2.0.0: - version "2.0.5" - resolved "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz#ebc252e400d22ff8d77fa09888821a24a658c191" - integrity sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ== - is-callable@^1.1.4, is-callable@^1.2.4: version "1.2.4" resolved "https://registry.npmjs.org/is-callable/-/is-callable-1.2.4.tgz#47301d58dd0259407865547853df6d61fe471945" @@ -7178,11 +6935,6 @@ is-date-object@^1.0.1, is-date-object@^1.0.2: dependencies: has-tostringtag "^1.0.0" -is-decimal@^1.0.0: - version "1.0.4" - resolved "https://registry.npmjs.org/is-decimal/-/is-decimal-1.0.4.tgz#65a3a5958a1c5b63a706e1b333d7cd9f630d3fa5" - integrity sha512-RGdriMmQQvZ2aqaQq3awNA6dCGtKpiDFcOzrTWrDAT2MiWrKQVPmxLGHl7Y2nNu6led0kEyoX0enY0qXYsv9zw== - is-descriptor@^0.1.0: version "0.1.6" resolved "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" @@ -7257,11 +7009,6 @@ is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3, is-glob@~4.0.1: dependencies: is-extglob "^2.1.1" -is-hexadecimal@^1.0.0: - version "1.0.4" - resolved "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-1.0.4.tgz#cc35c97588da4bd49a8eedd6bc4082d44dcb23a7" - integrity sha512-gyPJuv83bHMpocVYoqof5VDiZveEoGoFL8m3BXNb2VW8Xs+rz9kqO8LOQ5DH6EsuvilT1ApazU0pyl+ytbPtlw== - is-hotkey@^0.1.6: version "0.1.8" resolved "https://registry.npmjs.org/is-hotkey/-/is-hotkey-0.1.8.tgz#6b1f4b2d0e5639934e20c05ed24d623a21d36d25" @@ -7334,11 +7081,6 @@ is-plain-obj@^1.1.0: resolved "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz#71a50c8429dfca773c92a390a4a03b39fcd51d3e" integrity sha1-caUMhCnfync8kqOQpKA7OfzVHT4= -is-plain-obj@^2.0.0: - version "2.1.0" - resolved "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz#45e42e37fccf1f40da8e5f76ee21515840c09287" - integrity sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA== - is-plain-object@^2.0.3, is-plain-object@^2.0.4: version "2.0.4" resolved "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" @@ -7981,11 +7723,6 @@ js-base64@^2.1.8: resolved "https://registry.npmjs.org/js-base64/-/js-base64-2.6.4.tgz#f4e686c5de1ea1f867dbcad3d46d969428df98c4" integrity sha512-pZe//GGmwJndub7ZghVHz7vjb2LgC1m8B07Au3eYqeqv9emhESByMXxaEgkUkEqJe87oBbSniGYoQNIBklc7IQ== -js-cookie@^2.2.1: - version "2.2.1" - resolved "https://registry.npmjs.org/js-cookie/-/js-cookie-2.2.1.tgz#69e106dc5d5806894562902aa5baec3744e9b2b8" - integrity sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ== - "js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" @@ -8498,22 +8235,6 @@ md5-file@^5.0.0: resolved "https://registry.npmjs.org/md5-file/-/md5-file-5.0.0.tgz#e519f631feca9c39e7f9ea1780b63c4745012e20" integrity sha512-xbEFXCYVWrSx/gEKS1VPlg84h/4L20znVIulKw6kMfmBUAZNAnF00eczz9ICMl+/hjQGo5KSXRxbL/47X3rmMw== -mdast-util-from-markdown@^0.8.0: - version "0.8.5" - resolved "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-0.8.5.tgz#d1ef2ca42bc377ecb0463a987910dae89bd9a28c" - integrity sha512-2hkTXtYYnr+NubD/g6KGBS/0mFmBcifAsI0yIWRiRo0PjVs6SSOSOdtzbp6kSGnShDN6G5aWZpKQ2lWRy27mWQ== - dependencies: - "@types/mdast" "^3.0.0" - mdast-util-to-string "^2.0.0" - micromark "~2.11.0" - parse-entities "^2.0.0" - unist-util-stringify-position "^2.0.0" - -mdast-util-to-string@^2.0.0: - version "2.0.0" - resolved "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-2.0.0.tgz#b8cfe6a713e1091cb5b728fc48885a4767f8b97b" - integrity sha512-AW4DRS3QbBayY/jJmD8437V1Gombjf8RSOUCMFBuo5iHi58AGEgVCKQ+ezHkZZDpAQS75hcBMpLqjpJTjtUL7w== - [email protected]: version "2.0.14" resolved "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.14.tgz#7113fc4281917d63ce29b43446f701e68c25ba50" @@ -8624,14 +8345,6 @@ micro-memoize@^4.0.9: resolved "https://registry.npmjs.org/micro-memoize/-/micro-memoize-4.0.9.tgz#b44a38c9dffbee1cefc2fd139bc8947952268b62" integrity sha512-Z2uZi/IUMGQDCXASdujXRqrXXEwSY0XffUrAOllhqzQI3wpUyZbiZTiE2JuYC0HSG2G7DbCS5jZmsEKEGZuemg== -micromark@~2.11.0: - version "2.11.4" - resolved "https://registry.npmjs.org/micromark/-/micromark-2.11.4.tgz#d13436138eea826383e822449c9a5c50ee44665a" - integrity sha512-+WoovN/ppKolQOFIAajxi7Lu9kInbPxFuTBVEavFcL8eAfVstoc5MocPmqBeAdBOJV00uaVjegzH4+MA0DN/uA== - dependencies: - debug "^4.0.0" - parse-entities "^2.0.0" - micromatch@^3.1.4: version "3.1.10" resolved "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" @@ -8995,20 +8708,6 @@ nan@^2.13.2: resolved "https://registry.npmjs.org/nan/-/nan-2.15.0.tgz#3f34a473ff18e15c1b5626b62903b5ad6e665fee" integrity sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ== -nano-css@^5.2.1: - version "5.3.4" - resolved "https://registry.npmjs.org/nano-css/-/nano-css-5.3.4.tgz#40af6a83a76f84204f346e8ccaa9169cdae9167b" - integrity sha512-wfcviJB6NOxDIDfr7RFn/GlaN7I/Bhe4d39ZRCJ3xvZX60LVe2qZ+rDqM49nm4YT81gAjzS+ZklhKP/Gnfnubg== - dependencies: - css-tree "^1.1.2" - csstype "^3.0.6" - fastest-stable-stringify "^2.0.2" - inline-style-prefixer "^6.0.0" - rtl-css-js "^1.14.0" - sourcemap-codec "^1.4.8" - stacktrace-js "^2.0.2" - stylis "^4.0.6" - nanoid@^3.1.28: version "3.1.29" resolved "https://registry.npmjs.org/nanoid/-/nanoid-3.1.29.tgz#214fb2d7a33e1a5bef4757b779dfaeb6a4e5aeb4" @@ -9657,18 +9356,6 @@ parent-module@^1.0.0: dependencies: callsites "^3.0.0" -parse-entities@^2.0.0: - version "2.0.0" - resolved "https://registry.npmjs.org/parse-entities/-/parse-entities-2.0.0.tgz#53c6eb5b9314a1f4ec99fa0fdf7ce01ecda0cbe8" - integrity sha512-kkywGpCcRYhqQIchaWqZ875wzpS/bMKhz5HnN3p7wveJTkTtyAB/AlnS0f8DFSqYW1T82t6yEAkEcB+A1I3MbQ== - dependencies: - character-entities "^1.0.0" - character-entities-legacy "^1.0.0" - character-reference-invalid "^1.0.0" - is-alphanumerical "^1.0.0" - is-decimal "^1.0.0" - is-hexadecimal "^1.0.0" - [email protected], parse-json@^5.0.0: version "5.2.0" resolved "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz#c76fc66dee54231c962b22bcc8a72cf2f99753cd" @@ -10643,7 +10330,7 @@ pretty-format@^27.0.0, pretty-format@^27.2.5: ansi-styles "^5.0.0" react-is "^17.0.1" -prismjs@^1.20.0, prismjs@^1.21.0: +prismjs@^1.21.0: version "1.25.0" resolved "https://registry.npmjs.org/prismjs/-/prismjs-1.25.0.tgz#6f822df1bdad965734b310b315a23315cf999756" integrity sha512-WCjJHl1KEWbnkQom1+SzftbtXMKQoezOCYs5rECqMN+jP+apI7ftoflyqigqzopSO3hMhTEb0mFClA8lkolgEg== @@ -10885,23 +10572,6 @@ react-datepicker@^3.3.0: react-onclickoutside "^6.10.0" react-popper "^1.3.8" -react-dnd-html5-backend@^11.1.3: - version "11.1.3" - resolved "https://registry.npmjs.org/react-dnd-html5-backend/-/react-dnd-html5-backend-11.1.3.tgz#2749f04f416ec230ea193f5c1fbea2de7dffb8f7" - integrity sha512-/1FjNlJbW/ivkUxlxQd7o3trA5DE33QiRZgxent3zKme8DwF4Nbw3OFVhTRFGaYhHFNL1rZt6Rdj1D78BjnNLw== - dependencies: - dnd-core "^11.1.3" - -react-dnd@^11.1.3: - version "11.1.3" - resolved "https://registry.npmjs.org/react-dnd/-/react-dnd-11.1.3.tgz#f9844f5699ccc55dfc81462c2c19f726e670c1af" - integrity sha512-8rtzzT8iwHgdSC89VktwhqdKKtfXaAyC4wiqp0SywpHG12TTLvfOoL6xNEIUWXwIEWu+CFfDn4GZJyynCEuHIQ== - dependencies: - "@react-dnd/shallowequal" "^2.0.0" - "@types/hoist-non-react-statics" "^3.3.1" - dnd-core "^11.1.3" - hoist-non-react-statics "^3.3.0" - react-dom@^17.0.1: version "17.0.2" resolved "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz#ecffb6845e3ad8dbfcdc498f0d0a939736502c23" @@ -11050,31 +10720,6 @@ react-transition-group@^4.3.0, react-transition-group@^4.4.1: loose-envify "^1.4.0" prop-types "^15.6.2" -react-universal-interface@^0.6.2: - version "0.6.2" - resolved "https://registry.npmjs.org/react-universal-interface/-/react-universal-interface-0.6.2.tgz#5e8d438a01729a4dbbcbeeceb0b86be146fe2b3b" - integrity sha512-dg8yXdcQmvgR13RIlZbTRQOoUrDciFVoSBZILwjE2LFISxZZ8loVJKAkuzswl5js8BHda79bIb2b84ehU8IjXw== - -react-use@^15.1.0: - version "15.3.8" - resolved "https://registry.npmjs.org/react-use/-/react-use-15.3.8.tgz#ca839ac7fb3d696e5ccbeabbc8dadc2698969d30" - integrity sha512-GeGcrmGuUvZrY5wER3Lnph9DSYhZt5nEjped4eKDq8BRGr2CnLf9bDQWG9RFc7oCPphnscUUdOovzq0E5F2c6Q== - dependencies: - "@types/js-cookie" "2.2.6" - "@xobotyi/scrollbar-width" "1.9.5" - copy-to-clipboard "^3.2.0" - fast-deep-equal "^3.1.3" - fast-shallow-equal "^1.0.0" - js-cookie "^2.2.1" - nano-css "^5.2.1" - react-universal-interface "^0.6.2" - resize-observer-polyfill "^1.5.1" - screenfull "^5.0.0" - set-harmonic-interval "^1.0.1" - throttle-debounce "^2.1.0" - ts-easing "^0.2.0" - tslib "^2.0.0" - react@^17.0.1: version "17.0.2" resolved "https://registry.npmjs.org/react/-/react-17.0.2.tgz#d0b5cc516d29eb3eee383f75b62864cfb6800037" @@ -11320,21 +10965,6 @@ release-it@^14.2.2: yaml "1.10.2" yargs-parser "20.2.9" -remark-parse@^9.0.0: - version "9.0.0" - resolved "https://registry.npmjs.org/remark-parse/-/remark-parse-9.0.0.tgz#4d20a299665880e4f4af5d90b7c7b8a935853640" - integrity sha512-geKatMwSzEXKHuzBNU1z676sGcDcFoChMK38TgdHJNAYfFtsfHDQG7MoJAjs6sgYMqyLduCYWDIWZIxiPeafEw== - dependencies: - mdast-util-from-markdown "^0.8.0" - -remark-slate@^1.4.0: - version "1.8.0" - resolved "https://registry.npmjs.org/remark-slate/-/remark-slate-1.8.0.tgz#f0e97fe7d96bd82d896b777fa3064008f75aa144" - integrity sha512-KYZCehGs4gTaEt5i0TQqSYnYTO3/EFZ4K3x9i4dVydEximrBZoRcIJcF4+cAnF5glJYaBQhdNvhHk3vINgP9vg== - dependencies: - "@types/escape-html" "^1.0.0" - escape-html "^1.0.3" - remove-trailing-separator@^1.0.1: version "1.1.0" resolved "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" @@ -11407,11 +11037,6 @@ requireindex@^1.2.0: resolved "https://registry.npmjs.org/requireindex/-/requireindex-1.2.0.tgz#3463cdb22ee151902635aa6c9535d4de9c2ef1ef" integrity sha512-L9jEkOi3ASd9PYit2cwRfyppc9NoABujTP8/5gFcbERmo5jUoAKovIC3fsF17pkTnGsrByysqX+Kxd2OTNI1ww== -resize-observer-polyfill@^1.5.1: - version "1.5.1" - resolved "https://registry.npmjs.org/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz#0e9020dd3d21024458d4ebd27e23e40269810464" - integrity sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg== - resolve-alpn@^1.0.0: version "1.2.1" resolved "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9" @@ -11536,13 +11161,6 @@ rsvp@^4.8.4: resolved "https://registry.npmjs.org/rsvp/-/rsvp-4.8.5.tgz#c8f155311d167f68f21e168df71ec5b083113734" integrity sha512-nfMOlASu9OnRJo1mbEk2cz0D56a1MBNrJ7orjRZQG10XDyuvwksKbuXNp6qa+kbn839HwjwhBzhFmdsaEAfauA== -rtl-css-js@^1.14.0: - version "1.14.2" - resolved "https://registry.npmjs.org/rtl-css-js/-/rtl-css-js-1.14.2.tgz#fb2168433af9cdabee8a1613f4e2cbd1148acf6f" - integrity sha512-t6Wc/wpqm8s3kuXAV6tL/T7VS6n0XszzX58CgCsLj3O2xi9ITSLfzYhtl+GKyxCi/3QEqVctOJQwCiDzb2vteQ== - dependencies: - "@babel/runtime" "^7.1.2" - run-async@^2.4.0: version "2.4.1" resolved "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz#8440eccf99ea3e70bd409d49aab88e10c189a455" @@ -11691,11 +11309,6 @@ scmp@^2.1.0: resolved "https://registry.npmjs.org/scmp/-/scmp-2.1.0.tgz#37b8e197c425bdeb570ab91cc356b311a11f9c9a" integrity sha512-o/mRQGk9Rcer/jEEw/yw4mwo3EU/NvYvp577/Btqrym9Qy5/MdWGBqipbALgd2lrdWTJ5/gqDusxfnQBxOxT2Q== -screenfull@^5.0.0: - version "5.1.0" - resolved "https://registry.npmjs.org/screenfull/-/screenfull-5.1.0.tgz#85c13c70f4ead4c1b8a935c70010dfdcd2c0e5c8" - integrity sha512-dYaNuOdzr+kc6J6CFcBrzkLCfyGcMg+gWkJ8us93IQ7y1cevhQAugFsaCdMHb6lw8KV3xPzSxzH7zM1dQap9mA== - scroll-into-view-if-needed@^2.2.20: version "2.2.28" resolved "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-2.2.28.tgz#5a15b2f58a52642c88c8eca584644e01703d645a" @@ -11788,11 +11401,6 @@ set-blocking@^2.0.0, set-blocking@~2.0.0: resolved "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= -set-harmonic-interval@^1.0.1: - version "1.0.1" - resolved "https://registry.npmjs.org/set-harmonic-interval/-/set-harmonic-interval-1.0.1.tgz#e1773705539cdfb80ce1c3d99e7f298bb3995249" - integrity sha512-AhICkFV84tBP1aWqPwLZqFvAwqEoVA9kxNMniGEUvzOlm4vLmOFLiTT3UZ6bziJTy4bOVpzWGTfSCbmaayGx8g== - set-value@^2.0.0, set-value@^2.0.1: version "2.0.1" resolved "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b" @@ -12074,11 +11682,6 @@ source-map-url@^0.4.0: resolved "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.1.tgz#0af66605a745a5a2f91cf1bbf8a7afbc283dec56" integrity sha512-cPiFOTLUKvJFIg4SKVScy4ilPPW6rFgMgfuZJPNoDuMs3nC1HbMUycBoJw77xFIp6z1UJQJOfx6C9GMH80DiTw== [email protected]: - version "0.5.6" - resolved "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz#75ce38f52bf0733c5a7f0c118d81334a2bb5f412" - integrity sha1-dc449SvwczxafwwRjYEzSiu19BI= - source-map@^0.4.2: version "0.4.4" resolved "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" @@ -12101,11 +11704,6 @@ source-map@^0.7.3, source-map@~0.7.2: resolved "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz#5302f8169031735226544092e64981f751750383" integrity sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ== -sourcemap-codec@^1.4.8: - version "1.4.8" - resolved "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz#ea804bd94857402e6992d05a38ef1ae35a9ab4c4" - integrity sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA== - sparse-bitfield@^3.0.3: version "3.0.3" resolved "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz#ff4ae6e68656056ba4b3e792ab3334d38273ca11" @@ -12197,13 +11795,6 @@ stable@^0.1.8: resolved "https://registry.npmjs.org/stable/-/stable-0.1.8.tgz#836eb3c8382fe2936feaf544631017ce7d47a3cf" integrity sha512-ji9qxRnOVfcuLDySj9qzhGSEFVobyt1kIOSkj1qZzYLzq7Tos/oUUWvotUPQLlrsidqsK6tBH89Bc9kL5zHA6w== -stack-generator@^2.0.5: - version "2.0.5" - resolved "https://registry.npmjs.org/stack-generator/-/stack-generator-2.0.5.tgz#fb00e5b4ee97de603e0773ea78ce944d81596c36" - integrity sha512-/t1ebrbHkrLrDuNMdeAcsvynWgoH/i4o8EGGfX7dEYDoTXOYVAkEpFdtshlvabzc6JlJ8Kf9YdFEoz7JkzGN9Q== - dependencies: - stackframe "^1.1.1" - stack-utils@^2.0.2: version "2.0.5" resolved "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.5.tgz#d25265fca995154659dbbfba3b49254778d2fdd5" @@ -12211,28 +11802,6 @@ stack-utils@^2.0.2: dependencies: escape-string-regexp "^2.0.0" -stackframe@^1.1.1: - version "1.2.0" - resolved "https://registry.npmjs.org/stackframe/-/stackframe-1.2.0.tgz#52429492d63c62eb989804c11552e3d22e779303" - integrity sha512-GrdeshiRmS1YLMYgzF16olf2jJ/IzxXY9lhKOskuVziubpTYcYqyOwYeJKzQkwy7uN0fYSsbsC4RQaXf9LCrYA== - -stacktrace-gps@^3.0.4: - version "3.0.4" - resolved "https://registry.npmjs.org/stacktrace-gps/-/stacktrace-gps-3.0.4.tgz#7688dc2fc09ffb3a13165ebe0dbcaf41bcf0c69a" - integrity sha512-qIr8x41yZVSldqdqe6jciXEaSCKw1U8XTXpjDuy0ki/apyTn/r3w9hDAAQOhZdxvsC93H+WwwEu5cq5VemzYeg== - dependencies: - source-map "0.5.6" - stackframe "^1.1.1" - -stacktrace-js@^2.0.2: - version "2.0.2" - resolved "https://registry.npmjs.org/stacktrace-js/-/stacktrace-js-2.0.2.tgz#4ca93ea9f494752d55709a081d400fdaebee897b" - integrity sha512-Je5vBeY4S1r/RnLydLl0TBTi3F2qdfWmYsGvtfZgEI+SCprPppaIhQf5nGcal4gI4cGpCV/duLcAzT1np6sQqg== - dependencies: - error-stack-parser "^2.0.6" - stack-generator "^2.0.5" - stacktrace-gps "^3.0.4" - static-extend@^0.1.1: version "0.1.2" resolved "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6" @@ -12444,11 +12013,6 @@ stylehacks@^4.0.0: postcss "^7.0.0" postcss-selector-parser "^3.0.0" -stylis@^4.0.6: - version "4.0.10" - resolved "https://registry.npmjs.org/stylis/-/stylis-4.0.10.tgz#446512d1097197ab3f02fb3c258358c3f7a14240" - integrity sha512-m3k+dk7QeJw660eIKRRn3xPF6uuvHs/FFzjX3HQ5ove0qYsiygoAhwn5a3IYKaZPo5LrYD0rfVmtv1gNY1uYwg== - supports-color@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" @@ -12633,11 +12197,6 @@ throat@^5.0.0: resolved "https://registry.npmjs.org/throat/-/throat-5.0.0.tgz#c5199235803aad18754a667d659b5e72ce16764b" integrity sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA== -throttle-debounce@^2.1.0: - version "2.3.0" - resolved "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-2.3.0.tgz#fd31865e66502071e411817e241465b3e9c372e2" - integrity sha512-H7oLPV0P7+jgvrk+6mwwwBDmxTaxnu9HMXmloNLXwnNO0ZxZ31Orah2n8lU1eMPvsaowP2CX+USCgyovXfdOFQ== - through2@^2.0.0, through2@^2.0.1: version "2.0.5" resolved "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd" @@ -12678,13 +12237,6 @@ tiny-warning@^1.0.0, tiny-warning@^1.0.3: resolved "https://registry.npmjs.org/tiny-warning/-/tiny-warning-1.0.3.tgz#94a30db453df4c643d0fd566060d60a875d84754" integrity sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA== -tippy.js@^6.3.1: - version "6.3.2" - resolved "https://registry.npmjs.org/tippy.js/-/tippy.js-6.3.2.tgz#c03a0b88f170dffeba42f569771801dddc1f6340" - integrity sha512-35XVQI7Zl/jHZ51+8eHu/vVRXBjWYGobPm5G9FxOchj4r5dWhghKGS0nm0ARUKZTF96V7pPn7EbXS191NTwldw== - dependencies: - "@popperjs/core" "^2.9.0" - tmp@^0.0.33: version "0.0.33" resolved "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" @@ -12746,11 +12298,6 @@ to-regex@^3.0.1, to-regex@^3.0.2: regex-not "^1.0.2" safe-regex "^1.1.0" -toggle-selection@^1.0.6: - version "1.0.6" - resolved "https://registry.npmjs.org/toggle-selection/-/toggle-selection-1.0.6.tgz#6e45b1263f2017fa0acc7d89d78b15b8bf77da32" - integrity sha1-bkWxJj8gF/oKzH2J14sVuL932jI= - [email protected]: version "1.0.0" resolved "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz#7e1be3470f1e77948bc43d94a3c8f4d7752ba553" @@ -12802,11 +12349,6 @@ trim-newlines@^3.0.0: resolved "https://registry.npmjs.org/trim-newlines/-/trim-newlines-3.0.1.tgz#260a5d962d8b752425b32f3a7db0dcacd176c144" integrity sha512-c1PTsA3tYrIsLGkJkzHF+w9F2EyxfXGo4UyJc4pFL++FMjnq0HJS69T3M7d//gKrFKwy429bouPescbjecU+Zw== -trough@^1.0.0: - version "1.0.5" - resolved "https://registry.npmjs.org/trough/-/trough-1.0.5.tgz#b8b639cefad7d0bb2abd37d433ff8293efa5f406" - integrity sha512-rvuRbTarPXmMb79SmzEp8aqXNKcK+y0XaB298IXueQ8I2PsrATcPBCSPyK/dDNa2iWOhKlfNnOjdAOTBU/nkFA== - "true-case-path@^1.0.2": version "1.0.3" resolved "https://registry.npmjs.org/true-case-path/-/true-case-path-1.0.3.tgz#f813b5a8c86b40da59606722b144e3225799f47d" @@ -12821,11 +12363,6 @@ truncate-utf8-bytes@^1.0.0: dependencies: utf8-byte-length "^1.0.1" -ts-easing@^0.2.0: - version "0.2.0" - resolved "https://registry.npmjs.org/ts-easing/-/ts-easing-0.2.0.tgz#c8a8a35025105566588d87dbda05dd7fbfa5a4ec" - integrity sha512-Z86EW+fFFh/IFB1fqQ3/+7Zpf9t2ebOAxNI/V6Wo7r5gqiqtxmgTlQ1qbqQcjLKYeSHPTsEmvlJUDg/EuL0uHQ== - ts-essentials@^7.0.1: version "7.0.3" resolved "https://registry.npmjs.org/ts-essentials/-/ts-essentials-7.0.3.tgz#686fd155a02133eedcc5362dc8b5056cde3e5a38" @@ -12841,12 +12378,12 @@ tsconfig-paths@^3.11.0: minimist "^1.2.0" strip-bom "^3.0.0" -tslib@^1.10.0, tslib@^1.8.1, tslib@^1.9.0: +tslib@^1.8.1, tslib@^1.9.0: version "1.14.1" resolved "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== -tslib@^2.0.0, tslib@^2.0.3, tslib@^2.3.0, tslib@^2.3.1, tslib@~2.3.0: +tslib@^2.0.3, tslib@^2.3.0, tslib@^2.3.1, tslib@~2.3.0: version "2.3.1" resolved "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== @@ -12992,18 +12529,6 @@ unicode-property-aliases-ecmascript@^2.0.0: resolved "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.0.0.tgz#0a36cb9a585c4f6abd51ad1deddb285c165297c8" integrity sha512-5Zfuy9q/DFr4tfO7ZPeVXb1aPoeQSdeFMLpYuFebehDAhbuevLs5yxSZmIFN1tP5F9Wl4IpJrYojg85/zgyZHQ== -unified@^9.1.0: - version "9.2.2" - resolved "https://registry.npmjs.org/unified/-/unified-9.2.2.tgz#67649a1abfc3ab85d2969502902775eb03146975" - integrity sha512-Sg7j110mtefBD+qunSLO1lqOEKdrwBFBrR6Qd8f4uwkhWNlbkaqwHse6e7QvD3AP/MNoJdEDLaf8OxYyoWgorQ== - dependencies: - bail "^1.0.0" - extend "^3.0.0" - is-buffer "^2.0.0" - is-plain-obj "^2.0.0" - trough "^1.0.0" - vfile "^4.0.0" - union-value@^1.0.0: version "1.0.1" resolved "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847" @@ -13045,13 +12570,6 @@ unique-string@^2.0.0: dependencies: crypto-random-string "^2.0.0" -unist-util-stringify-position@^2.0.0: - version "2.0.3" - resolved "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-2.0.3.tgz#cce3bfa1cdf85ba7375d1d5b17bdc4cada9bd9da" - integrity sha512-3faScn5I+hy9VleOq/qNbAd6pAx7iH5jYBMS9I1HgQVijz/4mv5Bvw5iw1sC/90CODiKo81G/ps8AJrISn687g== - dependencies: - "@types/unist" "^2.0.2" - universal-user-agent@^6.0.0: version "6.0.0" resolved "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee" @@ -13173,11 +12691,6 @@ utila@~0.4: resolved "https://registry.npmjs.org/utila/-/utila-0.4.0.tgz#8a16a05d445657a3aea5eecc5b12a4fa5379772c" integrity sha1-ihagXURWV6Oupe7MWxKk+lN5dyw= -utility-types@^3.10.0: - version "3.10.0" - resolved "https://registry.npmjs.org/utility-types/-/utility-types-3.10.0.tgz#ea4148f9a741015f05ed74fd615e1d20e6bed82b" - integrity sha512-O11mqxmi7wMKCo6HKFt5AhO4BwY3VV68YU07tgxfz8zJTIxr4BpsezN49Ffwy9j3ZpwwJp4fkRwjRzq3uWE6Rg== - [email protected]: version "1.0.1" resolved "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" @@ -13246,24 +12759,6 @@ [email protected]: core-util-is "1.0.2" extsprintf "^1.2.0" -vfile-message@^2.0.0: - version "2.0.4" - resolved "https://registry.npmjs.org/vfile-message/-/vfile-message-2.0.4.tgz#5b43b88171d409eae58477d13f23dd41d52c371a" - integrity sha512-DjssxRGkMvifUOJre00juHoP9DPWuzjxKuMDrhNbk2TdaYYBNMStsNhEOt3idrtI12VQYM/1+iM0KOzXi4pxwQ== - dependencies: - "@types/unist" "^2.0.0" - unist-util-stringify-position "^2.0.0" - -vfile@^4.0.0: - version "4.2.1" - resolved "https://registry.npmjs.org/vfile/-/vfile-4.2.1.tgz#03f1dce28fc625c625bc6514350fbdb00fa9e624" - integrity sha512-O6AE4OskCG5S1emQ/4gl8zK586RqA3srz3nfK/Viy0UPToBc5Trp9BVFb1u0CjsKrAWwnpr4ifM/KBXPWwJbCA== - dependencies: - "@types/unist" "^2.0.0" - is-buffer "^2.0.0" - unist-util-stringify-position "^2.0.0" - vfile-message "^2.0.0" - w3c-hr-time@^1.0.2: version "1.0.2" resolved "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz#0a89cdf5cc15822df9c360543676963e0cc308cd"
d22cb1dfa7e01714d90168a759c649779d2206d5
2024-03-12 03:03:49
Dan Ribbens
chore(release): v3.0.0-alpha.46 [skip ci]
false
v3.0.0-alpha.46 [skip ci]
chore
diff --git a/package.json b/package.json index afa3c2b21d4..fd494bfe93f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "payload-monorepo", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "private": true, "type": "module", "workspaces:": [ diff --git a/packages/db-mongodb/package.json b/packages/db-mongodb/package.json index 0c25c1e75b4..457b14f918c 100644 --- a/packages/db-mongodb/package.json +++ b/packages/db-mongodb/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/db-mongodb", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "description": "The officially supported MongoDB database adapter for Payload - Update 2", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/db-postgres/package.json b/packages/db-postgres/package.json index 6b3b758837c..c0a5aa497e7 100644 --- a/packages/db-postgres/package.json +++ b/packages/db-postgres/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/db-postgres", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "description": "The officially supported Postgres database adapter for Payload", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/graphql/package.json b/packages/graphql/package.json index be621398eb8..fa7290ce87f 100644 --- a/packages/graphql/package.json +++ b/packages/graphql/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/graphql", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "main": "./src/index.ts", "types": "./src/index.d.ts", "type": "module", diff --git a/packages/next/package.json b/packages/next/package.json index c08ca5810b8..740be295c7f 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/next", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "main": "./src/index.ts", "types": "./src/index.d.ts", "type": "module", diff --git a/packages/payload/package.json b/packages/payload/package.json index 45a2ca87d40..7ad5a95ae12 100644 --- a/packages/payload/package.json +++ b/packages/payload/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "MIT", "main": "./src/index.js", diff --git a/packages/plugin-cloud-storage/package.json b/packages/plugin-cloud-storage/package.json index 6ac545fe02d..98e22a82226 100644 --- a/packages/plugin-cloud-storage/package.json +++ b/packages/plugin-cloud-storage/package.json @@ -1,7 +1,7 @@ { "name": "@payloadcms/plugin-cloud-storage", "description": "The official cloud storage plugin for Payload CMS", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "main": "dist/index.js", "types": "dist/index.d.ts", "type": "module", diff --git a/packages/plugin-cloud/package.json b/packages/plugin-cloud/package.json index bd2f8c08e00..04fb7862cd5 100644 --- a/packages/plugin-cloud/package.json +++ b/packages/plugin-cloud/package.json @@ -1,7 +1,7 @@ { "name": "@payloadcms/plugin-cloud", "description": "The official Payload Cloud plugin", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "main": "dist/index.js", "types": "dist/index.d.ts", "license": "MIT", diff --git a/packages/plugin-nested-docs/package.json b/packages/plugin-nested-docs/package.json index 5c1ba9afbba..5510d52c8f9 100644 --- a/packages/plugin-nested-docs/package.json +++ b/packages/plugin-nested-docs/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/plugin-nested-docs", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "description": "The official Nested Docs plugin for Payload", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/plugin-redirects/package.json b/packages/plugin-redirects/package.json index dc87f98fbee..2f9ac372b02 100644 --- a/packages/plugin-redirects/package.json +++ b/packages/plugin-redirects/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/plugin-redirects", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "homepage:": "https://payloadcms.com", "repository": "[email protected]:payloadcms/plugin-redirects.git", "description": "Redirects plugin for Payload", diff --git a/packages/plugin-search/package.json b/packages/plugin-search/package.json index 00e5da19954..0d9ae5fafc5 100644 --- a/packages/plugin-search/package.json +++ b/packages/plugin-search/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/plugin-search", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "homepage:": "https://payloadcms.com", "repository": "[email protected]:payloadcms/plugin-search.git", "description": "Search plugin for Payload", diff --git a/packages/plugin-seo/package.json b/packages/plugin-seo/package.json index f20a4f915a2..cb55de2cef0 100644 --- a/packages/plugin-seo/package.json +++ b/packages/plugin-seo/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/plugin-seo", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "homepage:": "https://payloadcms.com", "repository": "[email protected]:payloadcms/plugin-seo.git", "description": "SEO plugin for Payload", diff --git a/packages/richtext-lexical/package.json b/packages/richtext-lexical/package.json index 69098806632..b76e80fa9eb 100644 --- a/packages/richtext-lexical/package.json +++ b/packages/richtext-lexical/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/richtext-lexical", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "description": "The officially supported Lexical richtext adapter for Payload", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/richtext-slate/package.json b/packages/richtext-slate/package.json index 7f9d8fac841..b6825113c45 100644 --- a/packages/richtext-slate/package.json +++ b/packages/richtext-slate/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/richtext-slate", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "description": "The officially supported Slate richtext adapter for Payload", "repository": "https://github.com/payloadcms/payload", "license": "MIT", diff --git a/packages/translations/package.json b/packages/translations/package.json index 96cd410ba03..9b797487a6e 100644 --- a/packages/translations/package.json +++ b/packages/translations/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/translations", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "main": "./dist/exports/index.ts", "types": "./dist/types.d.ts", "type": "module", diff --git a/packages/ui/package.json b/packages/ui/package.json index d977f477866..c62179aadd5 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,6 +1,6 @@ { "name": "@payloadcms/ui", - "version": "3.0.0-alpha.45", + "version": "3.0.0-alpha.46", "main": "./src/index.ts", "types": "./dist/index.d.ts", "type": "module",
1ed5fd551e341bd28d78359b81e0bcef0f89bdbd
2021-12-01 00:10:06
Jacob Fletcher
fix: type errors
false
type errors
fix
diff --git a/packages/plugin-seo/fields/MetaDescription.tsx b/packages/plugin-seo/fields/MetaDescription.tsx index e58061bc397..0105ec81032 100644 --- a/packages/plugin-seo/fields/MetaDescription.tsx +++ b/packages/plugin-seo/fields/MetaDescription.tsx @@ -96,6 +96,7 @@ export const MetaDescription: React.FC<TextFieldType> = (props) => { }} > <TextareaInput + path={name} name={name} onChange={setValue} value={value} diff --git a/packages/plugin-seo/fields/MetaImage.tsx b/packages/plugin-seo/fields/MetaImage.tsx index c0bc619040e..270d74b6c21 100644 --- a/packages/plugin-seo/fields/MetaImage.tsx +++ b/packages/plugin-seo/fields/MetaImage.tsx @@ -94,6 +94,7 @@ export const MetaImage: React.FC<UploadFieldType> = (props) => { }} > <UploadInput + path={name} fieldTypes={fieldTypes} name={name} relationTo={relationTo} diff --git a/packages/plugin-seo/fields/MetaTitle.tsx b/packages/plugin-seo/fields/MetaTitle.tsx index 301ab821895..5fc401acb31 100644 --- a/packages/plugin-seo/fields/MetaTitle.tsx +++ b/packages/plugin-seo/fields/MetaTitle.tsx @@ -97,6 +97,7 @@ export const MetaTitle: React.FC<TextFieldType> = (props) => { }} > <TextInputField + path={name} name={name} onChange={setValue} value={value}
7679e3f0aa351832ca933a3978d5931c47375e8b
2023-10-09 17:37:32
Alessio Gravili
fix: richtext adapter types (#3497)
false
richtext adapter types (#3497)
fix
diff --git a/packages/payload/src/admin/components/forms/field-types/RichText/types.ts b/packages/payload/src/admin/components/forms/field-types/RichText/types.ts index a959304bc27..41c81a18191 100644 --- a/packages/payload/src/admin/components/forms/field-types/RichText/types.ts +++ b/packages/payload/src/admin/components/forms/field-types/RichText/types.ts @@ -2,14 +2,14 @@ import type { PayloadRequest } from '../../../../../express/types' import type { RichTextField, Validate } from '../../../../../fields/config/types' import type { CellComponentProps } from '../../../views/collections/List/Cell/types' -export type RichTextFieldProps<AdapterProps = unknown> = Omit< +export type RichTextFieldProps<AdapterProps = object> = Omit< RichTextField<AdapterProps>, 'type' > & { path?: string } -export type RichTextAdapter<AdapterProps = unknown> = { +export type RichTextAdapter<AdapterProps = object> = { CellComponent: React.FC<CellComponentProps<RichTextField<AdapterProps>>> FieldComponent: React.FC<RichTextFieldProps<AdapterProps>> afterReadPromise?: (data: { diff --git a/packages/payload/src/fields/config/types.ts b/packages/payload/src/fields/config/types.ts index 96da3e8fbe8..120464d7536 100644 --- a/packages/payload/src/fields/config/types.ts +++ b/packages/payload/src/fields/config/types.ts @@ -398,7 +398,7 @@ export type RelationshipValue = | ValueWithRelation[] | (number | string) -export type RichTextField<AdapterProps = unknown> = FieldBase & { +export type RichTextField<AdapterProps = object> = FieldBase & { admin?: Admin editor?: RichTextAdapter<AdapterProps> type: 'richText'
680863702e67d69dc4ec8d6a48b0e1402164cc97
2021-01-06 01:21:19
James
fix: removes prod devtool
false
removes prod devtool
fix
diff --git a/src/bin/build.ts b/src/bin/build.ts index c14834ebda0..36811ff74d9 100755 --- a/src/bin/build.ts +++ b/src/bin/build.ts @@ -22,10 +22,15 @@ export const build = (): void => { webpack(webpackProdConfig, (err, stats) => { // Stats Object if (err || stats.hasErrors()) { // Handle errors here - console.error(stats.toString({ - chunks: false, - colors: true, - })); + + if (stats) { + console.error(stats.toString({ + chunks: false, + colors: true, + })); + } else { + console.error(err.message); + } } }); } catch (err) { diff --git a/src/webpack/getProdConfig.ts b/src/webpack/getProdConfig.ts index 8ad3d85910d..de0abffc8ce 100644 --- a/src/webpack/getProdConfig.ts +++ b/src/webpack/getProdConfig.ts @@ -19,7 +19,6 @@ export default (payloadConfig: Config): Configuration => { chunkFilename: '[name].[chunkhash].js', }, mode: 'production', - devtool: 'none', stats: 'errors-only', optimization: { minimizer: [new TerserJSPlugin({}), new CssMinimizerPlugin()],
1fdff92525d9e565dde175fcece063b60dc08e07
2023-10-16 21:40:30
Elliot DeNolf
chore(script): use semver to validate and show next version
false
use semver to validate and show next version
chore
diff --git a/package.json b/package.json index 48f8ae3046d..d81d0a0504d 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ "@types/prompts": "^2.4.5", "@types/qs": "6.9.7", "@types/react": "18.2.15", + "@types/semver": "^7.5.3", "@types/shelljs": "0.8.12", "@types/testing-library__jest-dom": "5.14.8", "chalk": "^5.3.0", @@ -74,6 +75,7 @@ "prompts": "2.4.2", "qs": "6.11.2", "rimraf": "3.0.2", + "semver": "^7.5.4", "shelljs": "0.8.5", "simple-git": "^3.20.0", "slash": "3.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9e5074e64a3..357b37e59fd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -60,6 +60,9 @@ importers: '@types/react': specifier: 18.2.15 version: 18.2.15 + '@types/semver': + specifier: ^7.5.3 + version: 7.5.3 '@types/shelljs': specifier: 0.8.12 version: 0.8.12 @@ -141,6 +144,9 @@ importers: rimraf: specifier: 3.0.2 version: 3.0.2 + semver: + specifier: ^7.5.4 + version: 7.5.4 shelljs: specifier: 0.8.5 version: 0.8.5 @@ -5795,6 +5801,10 @@ packages: resolution: {integrity: sha512-7aqorHYgdNO4DM36stTiGO3DvKoex9TQRwsJU6vMaFGyqpBA1MNZkz+PG3gaNUPpTAOYhT1WR7M1JyA3fbS9Cw==} dev: false + /@types/[email protected]: + resolution: {integrity: sha512-OxepLK9EuNEIPxWNME+C6WwbRAOOI2o2BaQEGzz5Lu2e4Z5eDnEo+/aVEDMIXywoJitJ7xWd641wrGLZdtwRyw==} + dev: true + /@types/[email protected]: resolution: {integrity: sha512-Cwo8LE/0rnvX7kIIa3QHCkcuF21c05Ayb0ZfxPiv0W8VRiZiNW/WuRupHKpqqGVGf7SUA44QSOUKaEd9lIrd/Q==} dependencies: diff --git a/scripts/release.ts b/scripts/release.ts index e07a5fee9d2..a15fd83385e 100755 --- a/scripts/release.ts +++ b/scripts/release.ts @@ -5,6 +5,7 @@ import prompts from 'prompts' import minimist from 'minimist' import chalkTemplate from 'chalk-template' import { PackageDetails, getPackageDetails, showPackageDetails } from './lib/getPackageDetails' +import semver from 'semver' const execOpts: ExecSyncOptions = { stdio: 'inherit' } const args = minimist(process.argv.slice(2)) @@ -12,6 +13,10 @@ const args = minimist(process.argv.slice(2)) async function main() { const { tag = 'latest', bump = 'patch' } = args + if (!semver.RELEASE_TYPES.includes(bump)) { + abort(`Invalid bump type: ${bump}.\n\nMust be one of: ${semver.RELEASE_TYPES.join(', ')}`) + } + const packageDetails = await getPackageDetails() showPackageDetails(packageDetails) @@ -58,7 +63,7 @@ async function main() { ${packagesToRelease .map((p) => { const { shortName, version } = packageMap[p] - return ` ${shortName.padEnd(24)} ${version}` + return ` ${shortName.padEnd(24)} ${version} -> ${semver.inc(version, bump)}` }) .join('\n')} `)
1a9c63bf2629f9c8bc1e060a3028e331ae88b0d8
2024-06-25 20:24:59
Alessio Gravili
docs(richtext-lexical): docs for building custom lexical features (#6862)
false
docs for building custom lexical features (#6862)
docs
diff --git a/docs/fields/rich-text.mdx b/docs/fields/rich-text.mdx index 99b386b3c4b..f3825433065 100644 --- a/docs/fields/rich-text.mdx +++ b/docs/fields/rich-text.mdx @@ -26,7 +26,8 @@ Right now, Payload is officially supporting two rich text editors: 2. [Lexical](/docs/rich-text/lexical) - beta, where things will be moving <Banner type="success"> - <strong>Consistent with Payload's goal of making you learn as little of Payload as possible, customizing + <strong> + Consistent with Payload's goal of making you learn as little of Payload as possible, customizing and using the Rich Text Editor does not involve learning how to develop for a <em>Payload</em>{' '} rich text editor. </strong> diff --git a/docs/lexical/building-custom-features.mdx b/docs/lexical/building-custom-features.mdx new file mode 100644 index 00000000000..71916ee20d7 --- /dev/null +++ b/docs/lexical/building-custom-features.mdx @@ -0,0 +1,620 @@ +--- +title: Lexical Building Custom Features +label: Custom Features +order: 40 +desc: Building custom lexical features +keywords: lexical, rich text, editor, headless cms, feature, features +--- + +Before you begin building custom features for Lexical, it is crucial to familiarize yourself with the [Lexical docs](https://lexical.dev/docs/intro), particularly the "Concepts" section. This foundation is necessary for understanding Lexical's core principles, such as nodes, editor state, and commands. + +Lexical features are designed to be modular, meaning each piece of functionality is encapsulated within just two specific interfaces: one for server-side code and one for client-side code. + +By convention, these are named feature.server.ts for server-side functionality and feature.client.ts for client-side functionality. The primary functionality is housed within feature.server.ts, which users will import into their projects. The client-side feature, although defined separately, is integrated and rendered server-side through the server feature. That way, we still maintain a clear boundary between server and client code, while also centralizing the code needed for a feature in basically one place. This approach is beneficial for managing all the bits and pieces which make up your feature as a whole, such as toolbar entries, buttons, or new nodes, allowing each feature to be neatly contained and managed independently. + + +## Server Feature + +In order to get started with a new feature, you should start with the server feature which is the entry-point of your feature. + +**Example myFeature/feature.server.ts:** + +```ts +import { createServerFeature } from '@payloadcms/richtext-lexical'; + +export const MyFeature = createServerFeature({ + feature: { + }, + key: 'myFeature', +}) +``` + +`createServerFeature` is a helper function which lets you create new features without boilerplate code. + +Now, the feature is ready to be used in the editor: + +```ts +import { MyFeature } from './myFeature/feature.server'; +import { lexicalEditor } from '@payloadcms/richtext-lexical'; + +//... + { + name: 'richText', + type: 'richText', + editor: lexicalEditor({ + features: [ + MyFeature(), + ], + }), + }, +``` + +By default, this server feature does nothing - you haven't added any functionality yet. Depending on what you want your +feature to do, the ServerFeature type exposes various properties you can set to inject custom functionality into the lexical editor. + +Here is an example: + +```ts +import { createServerFeature, createNode } from '@payloadcms/richtext-lexical'; +import { MyClientFeature } from './feature.client.ts'; +import { MyMarkdownTransformer } from './feature.client.ts'; + +export const MyFeature = createServerFeature({ + feature: { + // This allows you to connect the Client Feature. More on that below + ClientFeature: MyClientFeature, + // This allows you to add i18n translations scoped to your feature. + // This specific translation will be available under "lexical:myFeature:label" - myFeature + // being your feature key. + i18n: { + en: { + label: 'My Feature', + }, + de: { + label: 'Mein Feature', + }, + }, + // Markdown Transformers in the server feature are used when converting the + // editor from or to markdown + markdownTransformers: [MyMarkdownTransformer], + nodes: [ + // Use the createNode helper function to more easily create nodes with proper typing + createNode({ + converters: { + html: { + converter: () => { + return `<hr/>` + }, + nodeTypes: [MyNode.getType()], + }, + }, + // Here you can add your actual node. On the server, they will be + // used to initialize a headless editor which can be used to perform + // operations on the editor, like markdown / html conversion. + node: MyNode, + }), + ], + }, + key: 'myFeature', +}) +``` + +### Feature load order + +Server features can also accept a function as the `feature` property (useful for sanitizing props, as mentioned below). This function will be called when the feature is loaded during the payload sanitization process: + +```ts +import { createServerFeature } from '@payloadcms/richtext-lexical'; + +createServerFeature({ + //... + feature: async ({ config, isRoot, props, resolvedFeatures, unSanitizedEditorConfig, featureProviderMap }) => { + + return { + //Actual server feature here... + } + } +}) +``` + +"Loading" here means the process of calling this `feature` function. By default, features are called in the order in which they are added to the editor. +However, sometimes you might want to load a feature after another feature has been loaded, or require a different feature to be loaded, throwing an error if this is not the case. + +Within lexical, one example where this is done are our list features. Both `UnorderedListFeature` and `OrderedListFeature` register the same `ListItem` node. Within `UnorderedListFeature` we register it normally, but within `OrderedListFeature` we want to only register the `ListItem` node if the `UnorderedListFeature` is not present - otherwise, we would have two features registering the same node. + +Here is how we do it: + +```ts +import { createServerFeature, createNode } from '@payloadcms/richtext-lexical'; + +export const OrderedListFeature = createServerFeature({ + feature: ({ featureProviderMap }) => { + return { + // ... + nodes: featureProviderMap.has('unorderedList') + ? [] + : [ + createNode({ + // ... + }), + ], + } + }, + key: 'orderedList', +}) +``` + +`featureProviderMap` will always be available and contain all the features, even yet-to-be-loaded ones, so we can check if a feature is loaded by checking if its `key` present in the map. + +If you wanted to make sure a feature is loaded before another feature, you can use the `dependenciesPriority` property: + +```ts +import { createServerFeature } from '@payloadcms/richtext-lexical'; + +export const MyFeature = createServerFeature({ + feature: ({ featureProviderMap }) => { + return { + // ... + } + }, + key: 'myFeature', + dependenciesPriority: ['otherFeature'], +}) +``` + +| Option | Description | +|----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **`dependenciesSoft`** | Keys of soft-dependencies needed for this feature. These are optional. Payload will attempt to load them before this feature, but doesn't throw an error if that's not possible. | +| **`dependencies`** | Keys of dependencies needed for this feature. These dependencies do not have to be loaded first, but they have to exist, otherwise an error will be thrown. | +| **`dependenciesPriority`** | Keys of priority dependencies needed for this feature. These dependencies have to be loaded first AND have to exist, otherwise an error will be thrown. They will be available in the `feature` property. | + +## Client Feature + +Most of the functionality which the user actually sees and interacts with, like toolbar items and React components for nodes, resides on the client-side. + +To set up your client-side feature, follow these three steps: + +1. **Create a Separate File**: Start by creating a new file specifically for your client feature, such as `myFeature/feature.client.ts`. It's important to keep client and server features in separate files to maintain a clean boundary between server and client code. +2. **'use client'**: Mark that file with a 'use client' directive at the top of the file +3. **Register the Client Feature**: Register the client feature within your server feature, by passing it to the `ClientFeature` prop. This is needed because the server feature is the sole entry-point of your feature. This also means you are not able to create a client feature without a server feature, as you will not be able to register it otherwise. + +**Example myFeature/feature.client.ts:** + +```ts +'use client' + +import { createClientFeature } from '@payloadcms/richtext-lexical/client'; + +export const MyClientFeature = createClientFeature({ + +}) +``` + +Explore the APIs available through ClientFeature to add the specific functionality you need. Remember, do not import directly from `'@payloadcms/richtext-lexical'` when working on the client-side, as it will cause errors with webpack or turbopack. Instead, use `'@payloadcms/richtext-lexical/client'` for all client-side imports. Type-imports are excluded from this rule and can always be imported. + +### Nodes + +Add nodes to the `nodes` array in **both** your client & server feature. On the server side, nodes are utilized for backend operations like HTML conversion in a headless editor. On the client side, these nodes are integral to how content is displayed and managed in the editor, influencing how they are rendered, behave, and saved in the database. + +Example: + +**myFeature/feature.client.ts:** + +```ts +'use client' + +import { createClientFeature } from '@payloadcms/richtext-lexical/client'; +import { MyNode } from './nodes/MyNode'; + +export const MyClientFeature = createClientFeature({ + nodes: [MyNode] +}) +``` + +**myFeature/nodes/MyNode.tsx:** + +Here is a basic DecoratorNode example: + +```ts +import type { + DOMConversionMap, + DOMConversionOutput, + DOMExportOutput, + EditorConfig, + LexicalNode, + SerializedLexicalNode, +} from 'lexical' + +import { $applyNodeReplacement, DecoratorNode } from 'lexical' + +// SerializedLexicalNode is the default lexical node. +// By setting your SerializedMyNode type to SerializedLexicalNode, +// you are basically saying that this node does not save any additional data. +// If you want your node to save data, feel free to extend it +export type SerializedMyNode = SerializedLexicalNode + +// Lazy-import the React component to your node here +const MyNodeComponent = React.lazy(() => + import('../component/index.js').then((module) => ({ + default: module.MyNodeComponent, + })), +) + +/** + * This node is a DecoratorNode. DecoratorNodes allow you to render React components in the editor. + * + * They need both createDom and decorate functions. createDom => outside of the html. decorate => React Component inside of the html. + * + * If we used DecoratorBlockNode instead, we would only need a decorate method + */ +export class MyNode extends DecoratorNode<React.ReactElement> { + static clone(node: MyNode): MyNode { + return new MyNode(node.__key) + } + + static getType(): string { + return 'myNode' + } + + /** + * Defines what happens if you copy a div element from another page and paste it into the lexical editor + * + * This also determines the behavior of lexical's internal HTML -> Lexical converter + */ + static importDOM(): DOMConversionMap | null { + return { + div: () => ({ + conversion: $yourConversionMethod, + priority: 0, + }), + } + } + + /** + * The data for this node is stored serialized as JSON. This is the "load function" of that node: it takes the saved data and converts it into a node. + */ + static importJSON(serializedNode: SerializedMyNode): MyNode { + return $createMyNode() + } + + /** + * Determines how the hr element is rendered in the lexical editor. This is only the "initial" / "outer" HTML element. + */ + createDOM(config: EditorConfig): HTMLElement { + const element = document.createElement('div') + return element + } + + /** + * Allows you to render a React component within whatever createDOM returns. + */ + decorate(): React.ReactElement { + return <MyNodeComponent nodeKey={this.__key} /> + } + + /** + * Opposite of importDOM, this function defines what happens when you copy a div element from the lexical editor and paste it into another page. + * + * This also determines the behavior of lexical's internal Lexical -> HTML converter + */ + exportDOM(): DOMExportOutput { + return { element: document.createElement('div') } + } + /** + * Opposite of importJSON. This determines what data is saved in the database / in the lexical editor state. + */ + exportJSON(): SerializedLexicalNode { + return { + type: 'myNode', + version: 1, + } + } + + getTextContent(): string { + return '\n' + } + + isInline(): false { + return false + } + + updateDOM(): boolean { + return false + } +} + +// This is used in the importDOM method. Totally optional if you do not want your node to be created automatically when copy & pasting certain dom elements +// into your editor. +function $yourConversionMethod(): DOMConversionOutput { + return { node: $createMyNode() } +} + +// This is a utility method to create a new MyNode. Utility methods prefixed with $ make it explicit that this should only be used within lexical +export function $createMyNode(): MyNode { + return $applyNodeReplacement(new MyNode()) +} + +// This is just a utility method you can use to check if a node is a MyNode. This also ensures correct typing. +export function $isMyNode( + node: LexicalNode | null | undefined, +): node is MyNode { + return node instanceof MyNode +} +``` + +Please do not add any 'use client' directives to your nodes, as the node class can be used on the server. + +### Plugins + +One small part of a feature are plugins. The name stems from the lexical playground plugins and is just a small part of a lexical feature. +Plugins are simply react components which are added to the editor, within all the lexical context providers. They can be used to add any functionality +to the editor, by utilizing the lexical API. + +Most commonly, they are used to register [lexical listeners](https://lexical.dev/docs/concepts/listeners), [node transforms](https://lexical.dev/docs/concepts/transforms) or [commands](https://lexical.dev/docs/concepts/commands). +For example, you could add a drawer to your plugin and register a command which opens it. That command can then be called from anywhere within lexical, e.g. from within your custom lexical node. + +To add a plugin, simply add it to the `plugins` array in your client feature: + +```ts +'use client' + +import { createClientFeature } from '@payloadcms/richtext-lexical/client'; +import { MyPlugin } from './plugin'; + +export const MyClientFeature = createClientFeature({ + plugins: [MyPlugin] +}) +``` + +Example plugin.tsx: + +```ts +'use client' +import type { + LexicalCommand, +} from 'lexical' + +import { + createCommand, + $getSelection, + $isRangeSelection, + COMMAND_PRIORITY_EDITOR +} from 'lexical' + +import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext.js' +import { $insertNodeToNearestRoot } from '@lexical/utils' +import { useEffect } from 'react' + +import type { PluginComponent } from '@payloadcms/richtext-lexical' // type imports can be imported from @payloadcms/richtext-lexical - even on the client + +import { + $createMyNode, +} from '../nodes/MyNode' +import './index.scss' + +export const INSERT_MYNODE_COMMAND: LexicalCommand<void> = createCommand( + 'INSERT_MYNODE_COMMAND', +) + +/** + * Plugin which registers a lexical command to insert a new MyNode into the editor + */ +export const MyNodePlugin: PluginComponent= () => { + // The useLexicalComposerContext hook can be used to access the lexical editor instance + const [editor] = useLexicalComposerContext() + + useEffect(() => { + return editor.registerCommand( + INSERT_MYNODE_COMMAND, + (type) => { + const selection = $getSelection() + + if (!$isRangeSelection(selection)) { + return false + } + + const focusNode = selection.focus.getNode() + + if (focusNode !== null) { + const newMyNode = $createMyNode() + $insertNodeToNearestRoot(newMyNode) + } + + return true + }, + COMMAND_PRIORITY_EDITOR, + ) + }, [editor]) + + return null +} +``` + +In this example, we register a lexical command which simply inserts a new MyNode into the editor. This command can be called from anywhere within lexical, e.g. from within a custom node. + +### Toolbar items + +Custom nodes and features on its own are pointless, if they can not be added to the editor. You will need to hook in one of our interfaces which allow the user to interact with the editor: + +- Fixed toolbar which stays fixed at the top of the editor +- Inline, floating toolbar which appears when selecting text +- Slash menu which appears when typing `/` in the editor +- Markdown transformers which are triggered when a certain text pattern is typed in the editor +- Or any other interfaces which can be added via your own plugins. Our toolbars are a prime example of this - they are just plugins. + +In order to add a toolbar item to either the floating or the inline toolbar, you can add a ToolbarGroup with a ToolbarItem to the `toolbarFixed` or `toolbarInline` props of your client feature: + +```ts +'use client' + +import { createClientFeature, toolbarAddDropdownGroupWithItems } from '@payloadcms/richtext-lexical/client'; +import { IconComponent } from './icon'; +import { $isHorizontalRuleNode } from './nodes/MyNode'; +import { INSERT_MYNODE_COMMAND } from './plugin'; +import { $isNodeSelection } from 'lexical' + +export const MyClientFeature = createClientFeature({ + toolbarFixed: { + groups: [ + toolbarAddDropdownGroupWithItems([ + { + ChildComponent: IconComponent, + isActive: ({ selection }) => { + if (!$isNodeSelection(selection) || !selection.getNodes().length) { + return false + } + + const firstNode = selection.getNodes()[0] + return $isHorizontalRuleNode(firstNode) + }, + key: 'myNode', + label: ({ i18n }) => { + return i18n.t('lexical:myFeature:label') + }, + onSelect: ({ editor }) => { + editor.dispatchCommand(INSERT_MYNODE_COMMAND, undefined) + }, + }, + ]), + ], + }, +}) +``` + +You will have to provide a toolbar group first, and then the items for that toolbar group. +We already export all the default toolbar groups (like `toolbarAddDropdownGroupWithItems`, so you can use them as a base for your own toolbar items. + +If a toolbar with the same key is declared twice, all its items will be merged together into one group. + +A `ToolbarItem` various props you can use to customize its behavior: + +| Option | Description | +|----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **`ChildComponent`** | A React component which is rendered within your toolbar item's default button component. Usually, you want this to be an icon. | +| **`Component`** | A React component which is rendered in place of the toolbar item's default button component, thus completely replacing it. The `ChildComponent` and `onSelect` properties will be ignored. | +| **`label`** | The label will be displayed in your toolbar item, if it's within a dropdown group. In order to make use of i18n, this can be a function. | +| **`key`** | Each toolbar item needs to have a unique key. | +| **`onSelect`** | A function which is called when the toolbar item is clicked. | +| **`isEnabled`** | This is optional and controls if the toolbar item is clickable or not. If `false` is returned here, it will be grayed out and unclickable. | +| **`isActive`** | This is optional and controls if the toolbar item is highlighted or not | + +The API for adding an item to the floating inline toolbar (`toolbarInline`) is identical. If you wanted to add an item to both the fixed and inline toolbar, you can extract it into its own variable +(typed as `ToolbarGroup[]`) and add it to both the `toolbarFixed` and `toolbarInline` props. + +### Slash Menu items + +The API for adding items to the slash menu is similar. There are slash menu groups, and each slash menu groups has items. Here is an example: + +```ts +'use client' + +import { createClientFeature, slashMenuBasicGroupWithItems } from '@payloadcms/richtext-lexical/client'; +import { INSERT_MYNODE_COMMAND } from './plugin'; +import { IconComponent } from './icon'; + +export const MyClientFeature = createClientFeature({ + slashMenu: { + groups: [ + slashMenuBasicGroupWithItems([ + { + Icon: IconComponent, + key: 'myNode', + keywords: ['myNode', 'myFeature', 'someOtherKeyword'], + label: ({ i18n }) => { + return i18n.t('lexical:myFeature:label') + }, + onSelect: ({ editor }) => { + editor.dispatchCommand(INSERT_MYNODE_COMMAND, undefined) + }, + }, + ]), + ], + }, +}) +``` + +| Option | Description | +|----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **`Icon`** | The icon which is rendered in your slash menu item. | +| **`label`** | The label will be displayed in your slash menu item. In order to make use of i18n, this can be a function. | +| **`key`** | Each slash menu item needs to have a unique key. The key will be matched when typing, displayed if no `label` property is set, and used for classNames. | +| **`onSelect`** | A function which is called when the slash menu item is selected. | +| **`keywords`** | Keywords are used in order to match the item for different texts typed after the '/'. E.g. you might want to show a horizontal rule item if you type both /hr, /separator, /horizontal etc. Additionally to the keywords, the label and key will be used to match the correct slash menu item. | + +## Props + +In order to accept props in your feature, you should first type them as a generic. + +Server Feature: + +```ts +createServerFeature<UnSanitizedProps, SanitizedProps, UnSanitizedClientProps>({ + //... +}) +``` + +Client Feature: + +```ts +createClientFeature<UnSanitizedClientProps, SanitizedClientProps>({ + //... +}) +``` + +The unSanitized props are what the user will pass to the feature when they call its provider function and add it to their editor config. You then have an option to sanitize those props. +To sanitize those in the server feature, you can pass a function to `feature` instead of an object: + +```ts +createServerFeature<UnSanitizedProps, SanitizedProps, UnSanitizedClientProps>({ + //... + feature: async ({ config, isRoot, props, resolvedFeatures, unSanitizedEditorConfig, featureProviderMap }) => { + const sanitizedProps = doSomethingWithProps(props) + + return { + sanitizedServerFeatureProps: sanitizedProps, + //Actual server feature here... + } + } +}) +``` + +Keep in mind that any sanitized props then have to returned in the `sanitizedServerFeatureProps` property. + +In the client feature, it works in a similar way: + +```ts +createClientFeature<UnSanitizedClientProps, SanitizedClientProps>( + ({ clientFunctions, featureProviderMap, props, resolvedFeatures, unSanitizedEditorConfig }) => { + const sanitizedProps = doSomethingWithProps(props) + return { + sanitizedClientFeatureProps: sanitizedProps, + //Actual client feature here... + } + }, +) +``` + +### Bringing props from the server to the client + +By default, the client feature will never receive any props from the server feature. In order to pass props from the server to the client, you can need to return those props in the server feature: + +```ts +type UnSanitizedClientProps = { + test: string +} + +createServerFeature<UnSanitizedProps, SanitizedProps, UnSanitizedClientProps>({ + //... + feature: { + clientFeatureProps: { + test: 'myValue' + } + } +}) +``` + +The reason the client feature does not have the same props available as the server by default is because all client props need to be serializable. You can totally accept things like functions or Maps as props in your server feature, but you will not be able to send those to the client. In the end, those props are sent from the server to the client over the network, so they need to be serializable. + +## More information + +Take a look at the [features we've already built](https://github.com/payloadcms/payload/tree/beta/packages/richtext-lexical/src/features) - understanding how they work will help you understand how to create your own. There is no difference between the features included by default and the ones you create yourself - since those features are all isolated from the "core", you have access to the same APIs, whether the feature is part of payload or not! diff --git a/docs/lexical/converters.mdx b/docs/lexical/converters.mdx index 212e8186c4d..17689c3fe4e 100644 --- a/docs/lexical/converters.mdx +++ b/docs/lexical/converters.mdx @@ -6,7 +6,6 @@ desc: Conversion between lexical, markdown and html keywords: lexical, rich text, editor, headless cms, convert, html, mdx, markdown, md, conversion, export --- - ## Lexical => HTML Lexical saves data in JSON, but can also generate its HTML representation via two main methods: @@ -21,7 +20,7 @@ The editor comes with built-in HTML serializers, simplifying the process of conv To add HTML generation directly within the collection, follow the example below: ```ts -import type { CollectionConfig } from 'payload/types' +import type { CollectionConfig } from 'payload' import { HTMLConverterFeature, lexicalEditor, lexicalHTML } from '@payloadcms/richtext-lexical' @@ -66,6 +65,8 @@ async function lexicalToHTML( return await convertLexicalToHTML({ converters: consolidateHTMLConverters({ editorConfig }), data: editorData, + payload, // if you have payload but no req available, pass it in here to enable server-only functionality (e.g. proper conversion of upload nodes) + req, // if you have req available, pass it in here to enable server-only functionality (e.g. proper conversion of upload nodes). No need to pass in payload if req is passed in. }) } ``` @@ -95,19 +96,33 @@ HTML Converters are typed as `HTMLConverter`, which contains the node type it sh import type { HTMLConverter } from '@payloadcms/richtext-lexical' const UploadHTMLConverter: HTMLConverter<SerializedUploadNode> = { - converter: async ({ node, payload }) => { - const uploadDocument = await payload.findByID({ - id: node.value.id, - collection: node.relationTo, - }) - const url = (payload?.config?.serverURL || '') + uploadDocument?.url - - if (!(uploadDocument?.mimeType as string)?.startsWith('image')) { + converter: async ({ node, req }) => { + const uploadDocument: { + value?: any + } = {} + if(req) { + await populate({ + id, + collectionSlug: node.relationTo, + currentDepth: 0, + data: uploadDocument, + depth: 1, + draft: false, + key: 'value', + overrideAccess: false, + req, + showHiddenFields: false, + }) + } + + const url = (req?.payload?.config?.serverURL || '') + uploadDocument?.value?.url + + if (!(uploadDocument?.value?.mimeType as string)?.startsWith('image')) { // Only images can be serialized as HTML return `` } - return `<img src="${url}" alt="${uploadDocument?.filename}" width="${uploadDocument?.width}" height="${uploadDocument?.height}"/>` + return `<img src="${url}" alt="${uploadDocument?.value?.filename}" width="${uploadDocument?.value?.width}" height="${uploadDocument?.value?.height}"/>` }, nodeTypes: [UploadNode.getType()], // This is the type of the lexical node that this converter can handle. Instead of hardcoding 'upload' we can get the node type directly from the UploadNode, since it's static. } @@ -200,7 +215,7 @@ yourEditorConfig.features = [ If you have access to the sanitized collection config, you can get access to the lexical sanitized editor config & features, as every lexical richText field returns it. Here is an example how you can get it from another field's afterRead hook: ```ts -import type { CollectionConfig, RichTextField } from 'payload/types' +import type { CollectionConfig, RichTextField } from 'payload' import { createHeadlessEditor } from '@lexical/headless' import type { LexicalRichTextAdapter, SanitizedServerEditorConfig } from '@payloadcms/richtext-lexical' import { diff --git a/docs/lexical/migration.mdx b/docs/lexical/migration.mdx index 7f347694327..33f81c233b0 100644 --- a/docs/lexical/migration.mdx +++ b/docs/lexical/migration.mdx @@ -17,7 +17,7 @@ One way to handle this is to just give your lexical editor the ability to read t Simply add the `SlateToLexicalFeature` to your editor: ```ts -import type { CollectionConfig } from 'payload/types' +import type { CollectionConfig } from 'payload' import { SlateToLexicalFeature, lexicalEditor } from '@payloadcms/richtext-lexical' @@ -49,7 +49,7 @@ The easy way to solve this: Just save the document! This overrides the slate dat The method described above does not solve the issue for all documents, though. If you want to convert all your documents to lexical, you can use a migration script. Here's a simple example: ```ts -import type { Payload } from 'payload' +import type { Payload, YourDocumentType } from 'payload' import type { YourDocumentType } from 'payload/generated-types' import { @@ -146,7 +146,7 @@ When using a migration script, you can add your custom converters to the `conver When using the `SlateToLexicalFeature`, you can add your custom converters to the `converters` property of the `SlateToLexicalFeature` props: ```ts -import type { CollectionConfig } from 'payload/types' +import type { CollectionConfig } from 'payload' import { SlateToLexicalFeature, diff --git a/docs/lexical/overview.mdx b/docs/lexical/overview.mdx index f4d03d4268f..bdda5123e7d 100644 --- a/docs/lexical/overview.mdx +++ b/docs/lexical/overview.mdx @@ -32,7 +32,7 @@ npm install @payloadcms/richtext-lexical Once you have it installed, you can pass it to your top-level Payload config as follows: ```ts -import { buildConfig } from 'payload/config' +import { buildConfig } from 'payload' import { lexicalEditor } from '@payloadcms/richtext-lexical' export default buildConfig({ @@ -47,7 +47,7 @@ export default buildConfig({ You can also override Lexical settings on a field-by-field basis as follows: ```ts -import type { CollectionConfig } from 'payload/types' +import type { CollectionConfig } from 'payload' import { lexicalEditor } from '@payloadcms/richtext-lexical' export const Pages: CollectionConfig = { @@ -168,12 +168,4 @@ Notice how even the toolbars are features? That's how extensible our lexical edi ## Creating your own, custom Feature -Creating your own custom feature requires deep knowledge of the Lexical editor. We recommend you take a look at the [Lexical documentation](https://lexical.dev/docs/intro) first - especially the "concepts" section. - -Next, take a look at the [features we've already built](https://github.com/payloadcms/payload/tree/main/packages/richtext-lexical/src/field/features) - understanding how they work will help you understand how to create your own. There is no difference between the features included by default and the ones you create yourself - since those features are all isolated from the "core", you have access to the same APIs, whether the feature is part of payload or not! - -## Coming Soon - -Lots more documentation will be coming soon, which will show in detail how to create your own custom features within Lexical. - -For now, take a look at the TypeScript interfaces and let us know if you need a hand. Much more will be coming from the Payload team on this topic soon. +You can find more information about creating your own feature in our [building custom feature docs](lexical/building-custom-features). diff --git a/packages/richtext-lexical/src/features/lists/orderedList/feature.server.ts b/packages/richtext-lexical/src/features/lists/orderedList/feature.server.ts index 6dd3eb93330..29611b0040f 100644 --- a/packages/richtext-lexical/src/features/lists/orderedList/feature.server.ts +++ b/packages/richtext-lexical/src/features/lists/orderedList/feature.server.ts @@ -1,7 +1,5 @@ import { ListItemNode, ListNode } from '@lexical/list' -import type { FeatureProviderProviderServer } from '../../types.js' - // eslint-disable-next-line payload/no-imports-from-exports-dir import { OrderedListFeatureClient } from '../../../exports/client/index.js' import { createServerFeature } from '../../../utilities/createServerFeature.js' diff --git a/packages/richtext-lexical/src/features/toolbars/types.ts b/packages/richtext-lexical/src/features/toolbars/types.ts index ecd2d6b4f38..508f76f17f4 100644 --- a/packages/richtext-lexical/src/features/toolbars/types.ts +++ b/packages/richtext-lexical/src/features/toolbars/types.ts @@ -20,8 +20,9 @@ export type ToolbarGroup = } export type ToolbarGroupItem = { + /** A React component which is rendered within your toolbar item's default button component. Usually, you want this to be an icon. */ ChildComponent?: React.FC - /** Use component to ignore the children and onClick properties. It does not use the default, pre-defined format Button component */ + /** A React component which is rendered in place of the toolbar item's default button component, thus completely replacing it. The `ChildComponent` and `onSelect` properties will be ignored. */ Component?: React.FC<{ active?: boolean anchorElem: HTMLElement @@ -29,6 +30,7 @@ export type ToolbarGroupItem = { enabled?: boolean item: ToolbarGroupItem }> + /** This is optional and controls if the toolbar item is highlighted or not. */ isActive?: ({ editor, editorConfigContext, @@ -38,6 +40,7 @@ export type ToolbarGroupItem = { editorConfigContext: EditorConfigContextType selection: BaseSelection }) => boolean + /** This is optional and controls if the toolbar item is clickable or not. If `false` is returned here, it will be grayed out and unclickable. */ isEnabled?: ({ editor, editorConfigContext, @@ -47,9 +50,11 @@ export type ToolbarGroupItem = { editorConfigContext: EditorConfigContextType selection: BaseSelection }) => boolean + /** Each toolbar item needs to have a unique key. */ key: string - /** The label is displayed as text if the item is part of a dropdown group */ + /** The label will be displayed in your toolbar item, if it's within a dropdown group. In order to make use of i18n, this can be a function. */ label?: (({ i18n }: { i18n: I18nClient<{}, string> }) => string) | string + /** Each toolbar item needs to have a unique key. */ onSelect?: ({ editor, isActive }: { editor: LexicalEditor; isActive: boolean }) => void order?: number } diff --git a/packages/richtext-lexical/src/features/types.ts b/packages/richtext-lexical/src/features/types.ts index 7aae0d85291..e456daf432c 100644 --- a/packages/richtext-lexical/src/features/types.ts +++ b/packages/richtext-lexical/src/features/types.ts @@ -92,11 +92,11 @@ export type FeatureProviderServer< ServerFeatureProps = UnSanitizedServerFeatureProps, ClientFeatureProps = undefined, > = { - /** Keys of dependencies needed for this feature. These dependencies do not have to be loaded first */ + /** Keys of dependencies needed for this feature. These dependencies do not have to be loaded first, but they have to exist, otherwise an error will be thrown. */ dependencies?: string[] - /** Keys of priority dependencies needed for this feature. These dependencies have to be loaded first and are available in the `feature` property*/ + /** Keys of priority dependencies needed for this feature. These dependencies have to be loaded first AND have to exist, otherwise an error will be thrown. They will be available in the `feature` property. */ dependenciesPriority?: string[] - /** Keys of soft-dependencies needed for this feature. The FeatureProviders dependencies are optional, but are considered as last-priority in the loading process */ + /** Keys of soft-dependencies needed for this feature. These are optional. Payload will attempt to load them before this feature, but doesn't throw an error if that's not possible. */ dependenciesSoft?: string[] /** diff --git a/packages/richtext-lexical/src/lexical/plugins/SlashMenu/LexicalTypeaheadMenuPlugin/types.ts b/packages/richtext-lexical/src/lexical/plugins/SlashMenu/LexicalTypeaheadMenuPlugin/types.ts index 2a0b5eac7fe..674ba545bda 100644 --- a/packages/richtext-lexical/src/lexical/plugins/SlashMenu/LexicalTypeaheadMenuPlugin/types.ts +++ b/packages/richtext-lexical/src/lexical/plugins/SlashMenu/LexicalTypeaheadMenuPlugin/types.ts @@ -1,27 +1,29 @@ -import type { I18n, I18nClient } from '@payloadcms/translations' +import type { I18nClient } from '@payloadcms/translations' import type { LexicalEditor } from 'lexical' import type { MutableRefObject } from 'react' import type React from 'react' export type SlashMenuItem = { - // Icon for display + /** The icon which is rendered in your slash menu item. */ Icon: React.FC - - // Used for class names and, if label is not provided, for display. + /** Each slash menu item needs to have a unique key. The key will be matched when typing, displayed if no `label` property is set, and used for classNames. */ key: string - // TBD - keyboardShortcut?: string - // For extra searching. + /** + * Keywords are used in order to match the item for different texts typed after the '/'. + * E.g. you might want to show a horizontal rule item if you type both /hr, /separator, /horizontal etc. + * Additionally to the keywords, the label and key will be used to match the correct slash menu item. + */ keywords?: Array<string> + /** The label will be displayed in your slash menu item. In order to make use of i18n, this can be a function. */ label?: (({ i18n }: { i18n: I18nClient<{}, string> }) => string) | string - // What happens when you select this item? + /** A function which is called when the slash menu item is selected. */ onSelect: ({ editor, queryString }: { editor: LexicalEditor; queryString: string }) => void } export type SlashMenuGroup = { items: Array<SlashMenuItem> - key: string // Used for class names and, if label is not provided, for display. + key: string label?: (({ i18n }: { i18n: I18nClient<{}, string> }) => string) | string }
0bc103658a1f4199fc1002df5dd831b34947b322
2024-04-11 05:59:57
Elliot DeNolf
chore(cpa): improve move message
false
improve move message
chore
diff --git a/packages/create-payload-app/src/utils/messages.ts b/packages/create-payload-app/src/utils/messages.ts index 347dd952936..79dc5552b04 100644 --- a/packages/create-payload-app/src/utils/messages.ts +++ b/packages/create-payload-app/src/utils/messages.ts @@ -86,7 +86,7 @@ export function successfulNextInit(): string { } export function moveMessage(args: { nextAppDir: string; projectDir: string }): string { - const relativePath = path.relative(process.cwd(), args.nextAppDir) + const relativeAppDir = path.relative(process.cwd(), args.nextAppDir) return ` ${header('Next Steps:')} @@ -94,7 +94,10 @@ Payload does not support a top-level layout.tsx file in the app directory. ${chalk.bold('To continue:')} -Move all files from ./${relativePath} to a named directory such as ./${relativePath}/${chalk.bold('(app)')} +- Create a new directory in ./${relativeAppDir} such as ./${relativeAppDir}/${chalk.bold('(app)')} +- Move all files from ./${relativeAppDir} into that directory + +It is recommended to do this from your IDE if your app has existing file references. Once moved, rerun the create-payload-app command again. `
c7bb694249927734cc6632505691a6014d1524db
2025-03-11 21:15:13
Alessio Gravili
perf: 50% faster compilation speed by skipping bundling of server-only packages during dev (#11594)
false
50% faster compilation speed by skipping bundling of server-only packages during dev (#11594)
perf
diff --git a/next.config.mjs b/next.config.mjs index 07ee2369321..a7d7748fa54 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -12,54 +12,57 @@ const withBundleAnalyzer = bundleAnalyzer({ }) const config = withBundleAnalyzer( - withPayload({ - eslint: { - ignoreDuringBuilds: true, - }, - typescript: { - ignoreBuildErrors: true, - }, - experimental: { - fullySpecified: true, - serverActions: { - bodySizeLimit: '5mb', + withPayload( + { + eslint: { + ignoreDuringBuilds: true, }, - }, - env: { - PAYLOAD_CORE_DEV: 'true', - ROOT_DIR: path.resolve(dirname), - // @todo remove in 4.0 - will behave like this by default in 4.0 - PAYLOAD_DO_NOT_SANITIZE_LOCALIZED_PROPERTY: 'true', - }, - async redirects() { - return [ - { - destination: '/admin', - permanent: false, - source: '/', + typescript: { + ignoreBuildErrors: true, + }, + experimental: { + fullySpecified: true, + serverActions: { + bodySizeLimit: '5mb', }, - ] - }, - images: { - domains: ['localhost'], - }, - webpack: (webpackConfig) => { - webpackConfig.resolve.extensionAlias = { - '.cjs': ['.cts', '.cjs'], - '.js': ['.ts', '.tsx', '.js', '.jsx'], - '.mjs': ['.mts', '.mjs'], - } + }, + env: { + PAYLOAD_CORE_DEV: 'true', + ROOT_DIR: path.resolve(dirname), + // @todo remove in 4.0 - will behave like this by default in 4.0 + PAYLOAD_DO_NOT_SANITIZE_LOCALIZED_PROPERTY: 'true', + }, + async redirects() { + return [ + { + destination: '/admin', + permanent: false, + source: '/', + }, + ] + }, + images: { + domains: ['localhost'], + }, + webpack: (webpackConfig) => { + webpackConfig.resolve.extensionAlias = { + '.cjs': ['.cts', '.cjs'], + '.js': ['.ts', '.tsx', '.js', '.jsx'], + '.mjs': ['.mts', '.mjs'], + } - // Ignore sentry warnings when not wrapped with withSentryConfig - webpackConfig.ignoreWarnings = [ - ...(webpackConfig.ignoreWarnings ?? []), - { file: /esm\/platform\/node\/instrumentation.js/ }, - { module: /esm\/platform\/node\/instrumentation.js/ }, - ] + // Ignore sentry warnings when not wrapped with withSentryConfig + webpackConfig.ignoreWarnings = [ + ...(webpackConfig.ignoreWarnings ?? []), + { file: /esm\/platform\/node\/instrumentation.js/ }, + { module: /esm\/platform\/node\/instrumentation.js/ }, + ] - return webpackConfig + return webpackConfig + }, }, - }), + { devBundleServerPackages: false }, + ), ) export default process.env.NEXT_PUBLIC_SENTRY_DSN diff --git a/packages/next/src/withPayload.js b/packages/next/src/withPayload.js index fff14cabe1f..8fa8b23c8cd 100644 --- a/packages/next/src/withPayload.js +++ b/packages/next/src/withPayload.js @@ -1,9 +1,11 @@ /** * @param {import('next').NextConfig} nextConfig + * @param {Object} [options] - Optional configuration options + * @param {boolean} [options.devBundleServerPackages] - Whether to bundle server packages in development mode. @default true * * @returns {import('next').NextConfig} * */ -export const withPayload = (nextConfig = {}) => { +export const withPayload = (nextConfig = {}, options = {}) => { const env = nextConfig?.env || {} if (nextConfig.experimental?.staleTimes?.dynamic) { @@ -99,6 +101,32 @@ export const withPayload = (nextConfig = {}) => { 'libsql', 'pino-pretty', 'graphql', + // Do not bundle server-only packages during dev to improve compile speed + ...(process.env.npm_lifecycle_event === 'dev' && options.devBundleServerPackages === false + ? [ + 'payload', + '@payloadcms/db-mongodb', + '@payloadcms/db-postgres', + '@payloadcms/db-sqlite', + '@payloadcms/db-vercel-postgres', + '@payloadcms/drizzle', + '@payloadcms/email-nodemailer', + '@payloadcms/email-resend', + '@payloadcms/graphql', + '@payloadcms/payload-cloud', + '@payloadcms/plugin-cloud-storage', + '@payloadcms/plugin-redirects', + '@payloadcms/plugin-sentry', + '@payloadcms/plugin-stripe', + // TODO: Add the following packages, excluding their /client subpath exports, once Next.js supports it + // @payloadcms/richtext-lexical + //'@payloadcms/storage-azure', + //'@payloadcms/storage-gcs', + //'@payloadcms/storage-s3', + //'@payloadcms/storage-uploadthing', + //'@payloadcms/storage-vercel-blob', + ] + : []), ], webpack: (webpackConfig, webpackOptions) => { const incomingWebpackConfig = diff --git a/packages/payload-cloud/src/utilities/refreshSession.ts b/packages/payload-cloud/src/utilities/refreshSession.ts index a12ad42e218..8fc41069dd0 100644 --- a/packages/payload-cloud/src/utilities/refreshSession.ts +++ b/packages/payload-cloud/src/utilities/refreshSession.ts @@ -1,12 +1,12 @@ import { CognitoIdentityClient } from '@aws-sdk/client-cognito-identity' -import * as AWS from '@aws-sdk/client-s3' +import { S3 } from '@aws-sdk/client-s3' import { fromCognitoIdentityPool } from '@aws-sdk/credential-providers' import { authAsCognitoUser } from './authAsCognitoUser.js' export type GetStorageClient = () => Promise<{ identityID: string - storageClient: AWS.S3 + storageClient: S3 }> export const refreshSession = async () => { @@ -33,7 +33,7 @@ export const refreshSession = async () => { // @ts-expect-error - Incorrect AWS types const identityID = credentials.identityId - const storageClient = new AWS.S3({ + const storageClient = new S3({ credentials, region: process.env.PAYLOAD_CLOUD_BUCKET_REGION, }) diff --git a/templates/_template/next.config.mjs b/templates/_template/next.config.mjs index 7ec4bd83665..de1c37d9ddc 100644 --- a/templates/_template/next.config.mjs +++ b/templates/_template/next.config.mjs @@ -5,4 +5,4 @@ const nextConfig = { // Your Next.js config here } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/templates/blank/next.config.mjs b/templates/blank/next.config.mjs index 7ec4bd83665..de1c37d9ddc 100644 --- a/templates/blank/next.config.mjs +++ b/templates/blank/next.config.mjs @@ -5,4 +5,4 @@ const nextConfig = { // Your Next.js config here } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/templates/plugin/dev/next.config.mjs b/templates/plugin/dev/next.config.mjs index eb65f30932d..c2a76732df2 100644 --- a/templates/plugin/dev/next.config.mjs +++ b/templates/plugin/dev/next.config.mjs @@ -18,4 +18,4 @@ const nextConfig = { // transpilePackages: ['../src'], } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/templates/website/next.config.js b/templates/website/next.config.js index 25f37e4f454..bcfc4c118ae 100644 --- a/templates/website/next.config.js +++ b/templates/website/next.config.js @@ -24,4 +24,4 @@ const nextConfig = { redirects, } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/templates/with-payload-cloud/next.config.mjs b/templates/with-payload-cloud/next.config.mjs index 7ec4bd83665..de1c37d9ddc 100644 --- a/templates/with-payload-cloud/next.config.mjs +++ b/templates/with-payload-cloud/next.config.mjs @@ -5,4 +5,4 @@ const nextConfig = { // Your Next.js config here } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/templates/with-postgres/next.config.mjs b/templates/with-postgres/next.config.mjs index 7ec4bd83665..de1c37d9ddc 100644 --- a/templates/with-postgres/next.config.mjs +++ b/templates/with-postgres/next.config.mjs @@ -5,4 +5,4 @@ const nextConfig = { // Your Next.js config here } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/templates/with-vercel-mongodb/next.config.mjs b/templates/with-vercel-mongodb/next.config.mjs index 7ec4bd83665..de1c37d9ddc 100644 --- a/templates/with-vercel-mongodb/next.config.mjs +++ b/templates/with-vercel-mongodb/next.config.mjs @@ -5,4 +5,4 @@ const nextConfig = { // Your Next.js config here } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/templates/with-vercel-postgres/next.config.mjs b/templates/with-vercel-postgres/next.config.mjs index 7ec4bd83665..de1c37d9ddc 100644 --- a/templates/with-vercel-postgres/next.config.mjs +++ b/templates/with-vercel-postgres/next.config.mjs @@ -5,4 +5,4 @@ const nextConfig = { // Your Next.js config here } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/templates/with-vercel-website/next.config.js b/templates/with-vercel-website/next.config.js index 25f37e4f454..bcfc4c118ae 100644 --- a/templates/with-vercel-website/next.config.js +++ b/templates/with-vercel-website/next.config.js @@ -24,4 +24,4 @@ const nextConfig = { redirects, } -export default withPayload(nextConfig) +export default withPayload(nextConfig, { devBundleServerPackages: false }) diff --git a/test/next.config.mjs b/test/next.config.mjs index 49b14a2c13d..5abc7ab8d34 100644 --- a/test/next.config.mjs +++ b/test/next.config.mjs @@ -12,45 +12,48 @@ const withBundleAnalyzer = bundleAnalyzer({ }) export default withBundleAnalyzer( - withPayload({ - eslint: { - ignoreDuringBuilds: true, - }, - typescript: { - ignoreBuildErrors: true, - }, - experimental: { - fullySpecified: true, - serverActions: { - bodySizeLimit: '5mb', + withPayload( + { + eslint: { + ignoreDuringBuilds: true, }, - }, - env: { - PAYLOAD_CORE_DEV: 'true', - ROOT_DIR: path.resolve(dirname), - // @todo remove in 4.0 - will behave like this by default in 4.0 - PAYLOAD_DO_NOT_SANITIZE_LOCALIZED_PROPERTY: 'true', - }, - async redirects() { - return [ - { - destination: '/admin', - permanent: true, - source: '/', + typescript: { + ignoreBuildErrors: true, + }, + experimental: { + fullySpecified: true, + serverActions: { + bodySizeLimit: '5mb', }, - ] - }, - images: { - domains: ['localhost'], - }, - webpack: (webpackConfig) => { - webpackConfig.resolve.extensionAlias = { - '.cjs': ['.cts', '.cjs'], - '.js': ['.ts', '.tsx', '.js', '.jsx'], - '.mjs': ['.mts', '.mjs'], - } + }, + env: { + PAYLOAD_CORE_DEV: 'true', + ROOT_DIR: path.resolve(dirname), + // @todo remove in 4.0 - will behave like this by default in 4.0 + PAYLOAD_DO_NOT_SANITIZE_LOCALIZED_PROPERTY: 'true', + }, + async redirects() { + return [ + { + destination: '/admin', + permanent: true, + source: '/', + }, + ] + }, + images: { + domains: ['localhost'], + }, + webpack: (webpackConfig) => { + webpackConfig.resolve.extensionAlias = { + '.cjs': ['.cts', '.cjs'], + '.js': ['.ts', '.tsx', '.js', '.jsx'], + '.mjs': ['.mts', '.mjs'], + } - return webpackConfig + return webpackConfig + }, }, - }), + { devBundleServerPackages: false }, + ), )
3248740f04e631ce289eadb5bf899824a8a478a2
2020-12-29 04:10:21
James
docs: progress to collection config
false
progress to collection config
docs
diff --git a/docs/Admin/components.mdx b/docs/Admin/components.mdx index 48a8a9bec54..f3d74bb372a 100644 --- a/docs/Admin/components.mdx +++ b/docs/Admin/components.mdx @@ -5,3 +5,8 @@ order: 20 --- Talk about how to build custom components. Show a list of all components that can be swapped out. + + +### Collections + +Talk about Collection-based components here. diff --git a/docs/Configuration/collections.mdx b/docs/Configuration/collections.mdx index dd102490785..c19999e2d1f 100644 --- a/docs/Configuration/collections.mdx +++ b/docs/Configuration/collections.mdx @@ -4,7 +4,7 @@ label: Collections order: 20 --- -Payload Collections are defined through configs of their own, and you can define as many as your application needs. Each Collection will map one-to-one with a MongoDB collection automatically based on fields that you define. +Payload Collections are defined through configs of their own, and you can define as many as your application needs. Each Collection will scaffold a MongoDB collection automatically based on fields that you define. It's often best practice to write your Collections in separate files and then import them into the main Payload config. @@ -14,10 +14,13 @@ It's often best practice to write your Collections in separate files and then im | ---------------- | -------------| | `slug` | Unique, URL-friendly string that will act as a global identifier for this collection. | | `labels` | Singular and plural labels for use in identifying this collection throughout Payload. | -| `fields` | Array of field types that will determine the structure and functionality of the data stored within this collection. | +| `fields` | Array of field types that will determine the structure and functionality of the data stored within this collection. [Click here](/docs/fields/overview) for a full list of field types as well as how to configure them. | | `admin` | Admin-specific configuration. See below for [more detail](/docs/collections#admin). | | `preview` | Function to generate preview URLS within the Admin panel that can point to your app. [More](/docs/collections#preview). | -| `hooks` | +| `hooks` | Entry points to "tie in" to collection actions at specific points. [More](/docs/hooks/config#collection-hooks) | +| `access` | Provide access control functions to define exactly who should be able to do what with documents in this collection. [More](/docs/access-control/config/#collections) | +| `auth` | Specify options if you would like this collection to feature authentication. For more, consult the [Authentication](/docs/authentication/config) documentation. | +| `upload` | Specify options if you would like this collection to support file uploads. For more, consult the [Uploads](/docs/uploads/config) documentation. | #### Simple example @@ -44,11 +47,24 @@ const Order = { } ``` -#### Full examples +#### More collection config examples You can find an assortment of [example collection configs](https://github.com/payloadcms/payload/blob/master/demo/collections) in the Payload source code on GitHub. ### Admin options +You can customize the way that the Admin panel behaves on a collection-by-collection basis by defining the `admin` property on a collection's config. + +#### Admin Collection Options + +| Option | Description | +| ---------------------------- | -------------| +| `useAsTitle` | Specify a top-level field to use for a document title throughout the Admin panel. If no field is defined, the ID of the document is used as the title. | +| `defaultColumns` | Array of field names that correspond to which columns to show by default in this collection's List view. | +| `disableDuplicate ` | Disables the "Duplicate" button while editing documents within this collection. | +| `enableRichTextRelationship` | The [Rich Text](/docs/fields/rich-text) field features a `Relationship` element which allows for users to automatically reference related documents within their rich text. Set this field to `true` to enable the collection to be selected within it. | +| `components` | Swap in your own React components to be used within this collection. [More](/docs/admin/components#collections) | ### Preview + +The Admin panel features a `` diff --git a/docs/Fields/richText.mdx b/docs/Fields/richText.mdx new file mode 100644 index 00000000000..78b36cc785c --- /dev/null +++ b/docs/Fields/richText.mdx @@ -0,0 +1,7 @@ +--- +title: Rich Text Field +label: Rich Text +order: 20 +--- + +get out
aee76cb793e0ad1ea7fa7f035efe814c2c7fba91
2024-09-17 00:57:39
Jacob Fletcher
fix(plugin-seo): threads entity slug and document config through generation fn args (#8238)
false
threads entity slug and document config through generation fn args (#8238)
fix
diff --git a/docs/plugins/seo.mdx b/docs/plugins/seo.mdx index 1a00a689a16..b42f088e8a2 100644 --- a/docs/plugins/seo.mdx +++ b/docs/plugins/seo.mdx @@ -119,11 +119,33 @@ A function that allows you to return any meta title, including from document's c { // ... seoPlugin({ - generateTitle: ({ ...docInfo, doc, locale, req }) => `Website.com — ${doc?.title}`, + generateTitle: ({ doc }) => `Website.com — ${doc?.title}`, }) } ``` +All "generate" functions receive the following arguments: + +| Argument | Description | +| --- | --- | +| **`collectionConfig`** | The configuration of the collection. | +| **`collectionSlug`** | The slug of the collection. | +| **`doc`** | The data of the current document. | +| **`docPermissions`** | The permissions of the document. | +| **`globalConfig`** | The configuration of the global. | +| **`globalSlug`** | The slug of the global. | +| **`hasPublishPermission`** | Whether the user has permission to publish the document. | +| **`hasSavePermission`** | Whether the user has permission to save the document. | +| **`id`** | The ID of the document. | +| **`initialData`** | The initial data of the document. | +| **`initialState`** | The initial state of the document. | +| **`locale`** | The locale of the document. | +| **`preferencesKey`** | The preferences key of the document. | +| **`publishedDoc`** | The published document. | +| **`req`** | The Payload request object containing `user`, `payload`, `i18n`, etc. | +| **`title`** | The title of the document. | +| **`versionsCount`** | The number of versions of the document. | + ##### `generateDescription` A function that allows you to return any meta description, including from document's content. @@ -133,11 +155,13 @@ A function that allows you to return any meta description, including from docume { // ... seoPlugin({ - generateDescription: ({ ...docInfo, doc, locale, req }) => doc?.excerpt, + generateDescription: ({ doc }) => doc?.excerpt, }) } ``` +For a full list of arguments, see the [`generateTitle`](#generateTitle) function. + ##### `generateImage` A function that allows you to return any meta image, including from document's content. @@ -147,11 +171,13 @@ A function that allows you to return any meta image, including from document's c { // ... seoPlugin({ - generateImage: ({ ...docInfo, doc, locale, req }) => doc?.featuredImage, + generateImage: ({ doc }) => doc?.featuredImage, }) } ``` +For a full list of arguments, see the [`generateTitle`](#generateTitle) function. + ##### `generateURL` A function called by the search preview component to display the actual URL of your page. @@ -161,12 +187,14 @@ A function called by the search preview component to display the actual URL of y { // ... seoPlugin({ - generateURL: ({ ...docInfo, doc, locale, req }) => - `https://yoursite.com/${collection?.slug}/${doc?.slug}`, + generateURL: ({ doc, collectionSlug }) => + `https://yoursite.com/${collectionSlug}/${doc?.slug}`, }) } ``` +For a full list of arguments, see the [`generateTitle`](#generateTitle) function. + #### `interfaceName` Rename the meta group interface name that is generated for TypeScript and GraphQL. diff --git a/packages/plugin-seo/src/fields/MetaDescription/MetaDescriptionComponent.tsx b/packages/plugin-seo/src/fields/MetaDescription/MetaDescriptionComponent.tsx index 9cf4a922d34..20c4843391b 100644 --- a/packages/plugin-seo/src/fields/MetaDescription/MetaDescriptionComponent.tsx +++ b/packages/plugin-seo/src/fields/MetaDescription/MetaDescriptionComponent.tsx @@ -61,16 +61,20 @@ export const MetaDescriptionComponent: React.FC<MetaDescriptionProps> = (props) const genDescriptionResponse = await fetch('/api/plugin-seo/generate-description', { body: JSON.stringify({ id: docInfo.id, - slug: docInfo.slug, + collectionSlug: docInfo.collectionSlug, doc: getData(), docPermissions: docInfo.docPermissions, + globalSlug: docInfo.globalSlug, hasPublishPermission: docInfo.hasPublishPermission, hasSavePermission: docInfo.hasSavePermission, initialData: docInfo.initialData, initialState: docInfo.initialState, locale: typeof locale === 'object' ? locale?.code : locale, title: docInfo.title, - } satisfies Omit<Parameters<GenerateDescription>[0], 'req'>), + } satisfies Omit< + Parameters<GenerateDescription>[0], + 'collectionConfig' | 'globalConfig' | 'req' + >), credentials: 'include', headers: { 'Content-Type': 'application/json', diff --git a/packages/plugin-seo/src/fields/MetaImage/MetaImageComponent.tsx b/packages/plugin-seo/src/fields/MetaImage/MetaImageComponent.tsx index ab85eb5414a..830507ce4b6 100644 --- a/packages/plugin-seo/src/fields/MetaImage/MetaImageComponent.tsx +++ b/packages/plugin-seo/src/fields/MetaImage/MetaImageComponent.tsx @@ -58,16 +58,17 @@ export const MetaImageComponent: React.FC<MetaImageProps> = (props) => { const genImageResponse = await fetch('/api/plugin-seo/generate-image', { body: JSON.stringify({ id: docInfo.id, - slug: docInfo.slug, + collectionSlug: docInfo.collectionSlug, doc: getData(), docPermissions: docInfo.docPermissions, + globalSlug: docInfo.globalSlug, hasPublishPermission: docInfo.hasPublishPermission, hasSavePermission: docInfo.hasSavePermission, initialData: docInfo.initialData, initialState: docInfo.initialState, locale: typeof locale === 'object' ? locale?.code : locale, title: docInfo.title, - } satisfies Omit<Parameters<GenerateImage>[0], 'req'>), + } satisfies Omit<Parameters<GenerateImage>[0], 'collectionConfig' | 'globalConfig' | 'req'>), credentials: 'include', headers: { 'Content-Type': 'application/json', diff --git a/packages/plugin-seo/src/fields/MetaTitle/MetaTitleComponent.tsx b/packages/plugin-seo/src/fields/MetaTitle/MetaTitleComponent.tsx index 357145ba6bc..a2c65302e55 100644 --- a/packages/plugin-seo/src/fields/MetaTitle/MetaTitleComponent.tsx +++ b/packages/plugin-seo/src/fields/MetaTitle/MetaTitleComponent.tsx @@ -62,16 +62,17 @@ export const MetaTitleComponent: React.FC<MetaTitleProps> = (props) => { const genTitleResponse = await fetch('/api/plugin-seo/generate-title', { body: JSON.stringify({ id: docInfo.id, - slug: docInfo.slug, + collectionSlug: docInfo.collectionSlug, doc: getData(), docPermissions: docInfo.docPermissions, + globalSlug: docInfo.globalSlug, hasPublishPermission: docInfo.hasPublishPermission, hasSavePermission: docInfo.hasSavePermission, initialData: docInfo.initialData, initialState: docInfo.initialState, locale: typeof locale === 'object' ? locale?.code : locale, title: docInfo.title, - } satisfies Omit<Parameters<GenerateTitle>[0], 'req'>), + } satisfies Omit<Parameters<GenerateTitle>[0], 'collectionConfig' | 'globalConfig' | 'req'>), credentials: 'include', headers: { 'Content-Type': 'application/json', diff --git a/packages/plugin-seo/src/fields/Preview/PreviewComponent.tsx b/packages/plugin-seo/src/fields/Preview/PreviewComponent.tsx index 62afc9de30e..d5f826b3a48 100644 --- a/packages/plugin-seo/src/fields/Preview/PreviewComponent.tsx +++ b/packages/plugin-seo/src/fields/Preview/PreviewComponent.tsx @@ -49,15 +49,17 @@ export const PreviewComponent: React.FC<PreviewProps> = (props) => { const genURLResponse = await fetch('/api/plugin-seo/generate-url', { body: JSON.stringify({ id: docInfo.id, + collectionSlug: docInfo.collectionSlug, doc: getData(), docPermissions: docInfo.docPermissions, + globalSlug: docInfo.globalSlug, hasPublishPermission: docInfo.hasPublishPermission, hasSavePermission: docInfo.hasSavePermission, initialData: docInfo.initialData, initialState: docInfo.initialState, locale: typeof locale === 'object' ? locale?.code : locale, title: docInfo.title, - } satisfies Omit<Parameters<GenerateURL>[0], 'req'>), + } satisfies Omit<Parameters<GenerateURL>[0], 'collectionConfig' | 'globalConfig' | 'req'>), credentials: 'include', headers: { 'Content-Type': 'application/json', diff --git a/packages/plugin-seo/src/index.tsx b/packages/plugin-seo/src/index.tsx index ffafe29acf1..389ac63ca05 100644 --- a/packages/plugin-seo/src/index.tsx +++ b/packages/plugin-seo/src/index.tsx @@ -132,7 +132,10 @@ export const seoPlugin = ...(config.endpoints ?? []), { handler: async (req) => { - const data = await req.json() + const data: Omit< + Parameters<GenerateTitle>[0], + 'collectionConfig' | 'globalConfig' | 'req' + > = await req.json() if (data) { req.data = data @@ -140,9 +143,15 @@ export const seoPlugin = const result = pluginConfig.generateTitle ? await pluginConfig.generateTitle({ - ...req.data, + ...data, + collectionConfig: req.data.collectionSlug + ? config.collections?.find((c) => c.slug === req.data.collectionSlug) + : null, + globalConfig: req.data.globalSlug + ? config.globals?.find((g) => g.slug === req.data.globalSlug) + : null, req, - } as unknown as Parameters<GenerateTitle>[0]) + } satisfies Parameters<GenerateTitle>[0]) : '' return new Response(JSON.stringify({ result }), { status: 200 }) }, @@ -151,7 +160,10 @@ export const seoPlugin = }, { handler: async (req) => { - const data = await req.json() + const data: Omit< + Parameters<GenerateTitle>[0], + 'collectionConfig' | 'globalConfig' | 'req' + > = await req.json() if (data) { req.data = data @@ -159,9 +171,15 @@ export const seoPlugin = const result = pluginConfig.generateDescription ? await pluginConfig.generateDescription({ - ...req.data, + ...data, + collectionConfig: req.data.collectionSlug + ? config.collections?.find((c) => c.slug === req.data.collectionSlug) + : null, + globalConfig: req.data.globalSlug + ? config.globals?.find((g) => g.slug === req.data.globalSlug) + : null, req, - } as unknown as Parameters<GenerateDescription>[0]) + } satisfies Parameters<GenerateDescription>[0]) : '' return new Response(JSON.stringify({ result }), { status: 200 }) }, @@ -170,7 +188,10 @@ export const seoPlugin = }, { handler: async (req) => { - const data = await req.json() + const data: Omit< + Parameters<GenerateTitle>[0], + 'collectionConfig' | 'globalConfig' | 'req' + > = await req.json() if (data) { req.data = data @@ -178,9 +199,15 @@ export const seoPlugin = const result = pluginConfig.generateURL ? await pluginConfig.generateURL({ - ...req.data, + ...data, + collectionConfig: req.data.collectionSlug + ? config.collections?.find((c) => c.slug === req.data.collectionSlug) + : null, + globalConfig: req.data.globalSlug + ? config.globals?.find((g) => g.slug === req.data.globalSlug) + : null, req, - } as unknown as Parameters<GenerateURL>[0]) + } satisfies Parameters<GenerateURL>[0]) : '' return new Response(JSON.stringify({ result }), { status: 200 }) }, @@ -189,7 +216,10 @@ export const seoPlugin = }, { handler: async (req) => { - const data = await req.json() + const data: Omit< + Parameters<GenerateTitle>[0], + 'collectionConfig' | 'globalConfig' | 'req' + > = await req.json() if (data) { req.data = data @@ -197,9 +227,15 @@ export const seoPlugin = const result = pluginConfig.generateImage ? await pluginConfig.generateImage({ - ...req.data, + ...data, + collectionConfig: req.data.collectionSlug + ? config.collections?.find((c) => c.slug === req.data.collectionSlug) + : null, + globalConfig: req.data.globalSlug + ? config.globals?.find((g) => g.slug === req.data.globalSlug) + : null, req, - } as unknown as Parameters<GenerateImage>[0]) + } as Parameters<GenerateImage>[0]) : '' return new Response(result, { status: 200 }) }, diff --git a/packages/plugin-seo/src/types.ts b/packages/plugin-seo/src/types.ts index e69bc182d1a..f160557b3ed 100644 --- a/packages/plugin-seo/src/types.ts +++ b/packages/plugin-seo/src/types.ts @@ -1,9 +1,19 @@ import type { DocumentInfoContext } from '@payloadcms/ui' -import type { Field, PayloadRequest, TextareaField, TextField, UploadField } from 'payload' +import type { + CollectionConfig, + Field, + GlobalConfig, + PayloadRequest, + TextareaField, + TextField, + UploadField, +} from 'payload' export type PartialDocumentInfoContext = Pick< DocumentInfoContext, + | 'collectionSlug' | 'docPermissions' + | 'globalSlug' | 'hasPublishPermission' | 'hasSavePermission' | 'id' @@ -11,29 +21,48 @@ export type PartialDocumentInfoContext = Pick< | 'initialState' | 'preferencesKey' | 'publishedDoc' - | 'slug' | 'title' | 'versionsCount' > export type GenerateTitle<T = any> = ( - args: { doc: T; locale?: string; req: PayloadRequest } & PartialDocumentInfoContext, + args: { + collectionConfig?: CollectionConfig + doc: T + globalConfig?: GlobalConfig + locale?: string + req: PayloadRequest + } & PartialDocumentInfoContext, ) => Promise<string> | string export type GenerateDescription<T = any> = ( args: { + collectionConfig?: CollectionConfig doc: T + globalConfig?: GlobalConfig locale?: string req: PayloadRequest } & PartialDocumentInfoContext, ) => Promise<string> | string export type GenerateImage<T = any> = ( - args: { doc: T; locale?: string; req: PayloadRequest } & PartialDocumentInfoContext, + args: { + collectionConfig?: CollectionConfig + doc: T + globalConfig?: GlobalConfig + locale?: string + req: PayloadRequest + } & PartialDocumentInfoContext, ) => Promise<string> | string export type GenerateURL<T = any> = ( - args: { doc: T; locale?: string; req: PayloadRequest } & PartialDocumentInfoContext, + args: { + collectionConfig?: CollectionConfig + doc: T + globalConfig?: GlobalConfig + locale?: string + req: PayloadRequest + } & PartialDocumentInfoContext, ) => Promise<string> | string export type SEOPluginConfig = { diff --git a/packages/ui/src/providers/DocumentInfo/types.ts b/packages/ui/src/providers/DocumentInfo/types.ts index e0787b678eb..088688f1bd4 100644 --- a/packages/ui/src/providers/DocumentInfo/types.ts +++ b/packages/ui/src/providers/DocumentInfo/types.ts @@ -71,7 +71,6 @@ export type DocumentInfoContext = { fieldPreferences: { [key: string]: unknown } & Partial<InsideFieldsPreferences>, ) => void setDocumentTitle: (title: string) => void - slug?: string title: string unpublishedVersions?: PaginatedDocs<TypeWithVersion<any>> versions?: PaginatedDocs<TypeWithVersion<any>>
e12e720a9946c56e8f4f03158d80744ae291784f
2024-03-08 21:54:25
James
chore: imports translations in a safer manner
false
imports translations in a safer manner
chore
diff --git a/packages/payload/src/bin/register/register.ts b/packages/payload/src/bin/register/register.ts index c36ad1349d3..5b2b9d77b56 100644 --- a/packages/payload/src/bin/register/register.ts +++ b/packages/payload/src/bin/register/register.ts @@ -90,17 +90,7 @@ export function compile( return injectInlineSourceMap({ code: outputText, filename, map: sourceMapText }) } - let swcRegisterConfig: Options - if (process.env.SWCRC) { - // when SWCRC environment variable is set to true it will use swcrc file - swcRegisterConfig = { - swc: { - swcrc: true, - }, - } - } else { - swcRegisterConfig = tsCompilerOptionsToSwcConfig(options, filename) - } + const swcRegisterConfig: Options = tsCompilerOptionsToSwcConfig(options, filename) if (async) { return transform(sourcecode, filename, swcRegisterConfig).then(({ code, map }) => { @@ -116,7 +106,6 @@ export function register(options: Partial<ts.CompilerOptions> = {}, hookOpts = { const locatedConfig = getTsconfig() const tsconfig = locatedConfig.config.compilerOptions as unknown as ts.CompilerOptions options = tsconfig - // options.module = ts.ModuleKind.CommonJS installSourceMapSupport() return addHook((code, filename) => compile(code, filename, options), { exts: DEFAULT_EXTENSIONS, diff --git a/packages/translations/src/_generatedFiles_/api/index.ts b/packages/translations/src/_generatedFiles_/api/index.ts index 7ab7ae98b26..fb2376ff6ee 100644 --- a/packages/translations/src/_generatedFiles_/api/index.ts +++ b/packages/translations/src/_generatedFiles_/api/index.ts @@ -1,33 +1,33 @@ -import ar from './ar.json' assert { type: 'json' } -import az from './az.json' assert { type: 'json' } -import bg from './bg.json' assert { type: 'json' } -import cs from './cs.json' assert { type: 'json' } -import de from './de.json' assert { type: 'json' } -import en from './en.json' assert { type: 'json' } -import es from './es.json' assert { type: 'json' } -import fa from './fa.json' assert { type: 'json' } -import fr from './fr.json' assert { type: 'json' } -import hr from './hr.json' assert { type: 'json' } -import hu from './hu.json' assert { type: 'json' } -import it from './it.json' assert { type: 'json' } -import ja from './ja.json' assert { type: 'json' } -import ko from './ko.json' assert { type: 'json' } -import my from './my.json' assert { type: 'json' } -import nb from './nb.json' assert { type: 'json' } -import nl from './nl.json' assert { type: 'json' } -import pl from './pl.json' assert { type: 'json' } -import pt from './pt.json' assert { type: 'json' } -import ro from './ro.json' assert { type: 'json' } -import rs from './rs.json' assert { type: 'json' } -import rsLatin from './rs-latin.json' assert { type: 'json' } -import ru from './ru.json' assert { type: 'json' } -import sv from './sv.json' assert { type: 'json' } -import th from './th.json' assert { type: 'json' } -import tr from './tr.json' assert { type: 'json' } -import ua from './ua.json' assert { type: 'json' } -import vi from './vi.json' assert { type: 'json' } -import zh from './zh.json' assert { type: 'json' } -import zhTw from './zh-tw.json' assert { type: 'json' } +const { default: ar } = await import('./ar.json', { assert: { type: 'json' } }) +const { default: az } = await import('./az.json', { assert: { type: 'json' } }) +const { default: bg } = await import('./bg.json', { assert: { type: 'json' } }) +const { default: cs } = await import('./cs.json', { assert: { type: 'json' } }) +const { default: de } = await import('./de.json', { assert: { type: 'json' } }) +const { default: en } = await import('./en.json', { assert: { type: 'json' } }) +const { default: es } = await import('./es.json', { assert: { type: 'json' } }) +const { default: fa } = await import('./fa.json', { assert: { type: 'json' } }) +const { default: fr } = await import('./fr.json', { assert: { type: 'json' } }) +const { default: hr } = await import('./hr.json', { assert: { type: 'json' } }) +const { default: hu } = await import('./hu.json', { assert: { type: 'json' } }) +const { default: it } = await import('./it.json', { assert: { type: 'json' } }) +const { default: ja } = await import('./ja.json', { assert: { type: 'json' } }) +const { default: ko } = await import('./ko.json', { assert: { type: 'json' } }) +const { default: my } = await import('./my.json', { assert: { type: 'json' } }) +const { default: nb } = await import('./nb.json', { assert: { type: 'json' } }) +const { default: nl } = await import('./nl.json', { assert: { type: 'json' } }) +const { default: pl } = await import('./pl.json', { assert: { type: 'json' } }) +const { default: pt } = await import('./pt.json', { assert: { type: 'json' } }) +const { default: ro } = await import('./ro.json', { assert: { type: 'json' } }) +const { default: rs } = await import('./rs.json', { assert: { type: 'json' } }) +const { default: rsLatin } = await import('./rs-latin.json', { assert: { type: 'json' } }) +const { default: ru } = await import('./ru.json', { assert: { type: 'json' } }) +const { default: sv } = await import('./sv.json', { assert: { type: 'json' } }) +const { default: th } = await import('./th.json', { assert: { type: 'json' } }) +const { default: tr } = await import('./tr.json', { assert: { type: 'json' } }) +const { default: ua } = await import('./ua.json', { assert: { type: 'json' } }) +const { default: vi } = await import('./vi.json', { assert: { type: 'json' } }) +const { default: zh } = await import('./zh.json', { assert: { type: 'json' } }) +const { default: zhTw } = await import('./zh-tw.json', { assert: { type: 'json' } }) export const translations = { ar, diff --git a/packages/translations/src/_generatedFiles_/client/index.ts b/packages/translations/src/_generatedFiles_/client/index.ts index 7ab7ae98b26..fb2376ff6ee 100644 --- a/packages/translations/src/_generatedFiles_/client/index.ts +++ b/packages/translations/src/_generatedFiles_/client/index.ts @@ -1,33 +1,33 @@ -import ar from './ar.json' assert { type: 'json' } -import az from './az.json' assert { type: 'json' } -import bg from './bg.json' assert { type: 'json' } -import cs from './cs.json' assert { type: 'json' } -import de from './de.json' assert { type: 'json' } -import en from './en.json' assert { type: 'json' } -import es from './es.json' assert { type: 'json' } -import fa from './fa.json' assert { type: 'json' } -import fr from './fr.json' assert { type: 'json' } -import hr from './hr.json' assert { type: 'json' } -import hu from './hu.json' assert { type: 'json' } -import it from './it.json' assert { type: 'json' } -import ja from './ja.json' assert { type: 'json' } -import ko from './ko.json' assert { type: 'json' } -import my from './my.json' assert { type: 'json' } -import nb from './nb.json' assert { type: 'json' } -import nl from './nl.json' assert { type: 'json' } -import pl from './pl.json' assert { type: 'json' } -import pt from './pt.json' assert { type: 'json' } -import ro from './ro.json' assert { type: 'json' } -import rs from './rs.json' assert { type: 'json' } -import rsLatin from './rs-latin.json' assert { type: 'json' } -import ru from './ru.json' assert { type: 'json' } -import sv from './sv.json' assert { type: 'json' } -import th from './th.json' assert { type: 'json' } -import tr from './tr.json' assert { type: 'json' } -import ua from './ua.json' assert { type: 'json' } -import vi from './vi.json' assert { type: 'json' } -import zh from './zh.json' assert { type: 'json' } -import zhTw from './zh-tw.json' assert { type: 'json' } +const { default: ar } = await import('./ar.json', { assert: { type: 'json' } }) +const { default: az } = await import('./az.json', { assert: { type: 'json' } }) +const { default: bg } = await import('./bg.json', { assert: { type: 'json' } }) +const { default: cs } = await import('./cs.json', { assert: { type: 'json' } }) +const { default: de } = await import('./de.json', { assert: { type: 'json' } }) +const { default: en } = await import('./en.json', { assert: { type: 'json' } }) +const { default: es } = await import('./es.json', { assert: { type: 'json' } }) +const { default: fa } = await import('./fa.json', { assert: { type: 'json' } }) +const { default: fr } = await import('./fr.json', { assert: { type: 'json' } }) +const { default: hr } = await import('./hr.json', { assert: { type: 'json' } }) +const { default: hu } = await import('./hu.json', { assert: { type: 'json' } }) +const { default: it } = await import('./it.json', { assert: { type: 'json' } }) +const { default: ja } = await import('./ja.json', { assert: { type: 'json' } }) +const { default: ko } = await import('./ko.json', { assert: { type: 'json' } }) +const { default: my } = await import('./my.json', { assert: { type: 'json' } }) +const { default: nb } = await import('./nb.json', { assert: { type: 'json' } }) +const { default: nl } = await import('./nl.json', { assert: { type: 'json' } }) +const { default: pl } = await import('./pl.json', { assert: { type: 'json' } }) +const { default: pt } = await import('./pt.json', { assert: { type: 'json' } }) +const { default: ro } = await import('./ro.json', { assert: { type: 'json' } }) +const { default: rs } = await import('./rs.json', { assert: { type: 'json' } }) +const { default: rsLatin } = await import('./rs-latin.json', { assert: { type: 'json' } }) +const { default: ru } = await import('./ru.json', { assert: { type: 'json' } }) +const { default: sv } = await import('./sv.json', { assert: { type: 'json' } }) +const { default: th } = await import('./th.json', { assert: { type: 'json' } }) +const { default: tr } = await import('./tr.json', { assert: { type: 'json' } }) +const { default: ua } = await import('./ua.json', { assert: { type: 'json' } }) +const { default: vi } = await import('./vi.json', { assert: { type: 'json' } }) +const { default: zh } = await import('./zh.json', { assert: { type: 'json' } }) +const { default: zhTw } = await import('./zh-tw.json', { assert: { type: 'json' } }) export const translations = { ar, diff --git a/packages/translations/src/all/index.ts b/packages/translations/src/all/index.ts index 7ab7ae98b26..fb2376ff6ee 100644 --- a/packages/translations/src/all/index.ts +++ b/packages/translations/src/all/index.ts @@ -1,33 +1,33 @@ -import ar from './ar.json' assert { type: 'json' } -import az from './az.json' assert { type: 'json' } -import bg from './bg.json' assert { type: 'json' } -import cs from './cs.json' assert { type: 'json' } -import de from './de.json' assert { type: 'json' } -import en from './en.json' assert { type: 'json' } -import es from './es.json' assert { type: 'json' } -import fa from './fa.json' assert { type: 'json' } -import fr from './fr.json' assert { type: 'json' } -import hr from './hr.json' assert { type: 'json' } -import hu from './hu.json' assert { type: 'json' } -import it from './it.json' assert { type: 'json' } -import ja from './ja.json' assert { type: 'json' } -import ko from './ko.json' assert { type: 'json' } -import my from './my.json' assert { type: 'json' } -import nb from './nb.json' assert { type: 'json' } -import nl from './nl.json' assert { type: 'json' } -import pl from './pl.json' assert { type: 'json' } -import pt from './pt.json' assert { type: 'json' } -import ro from './ro.json' assert { type: 'json' } -import rs from './rs.json' assert { type: 'json' } -import rsLatin from './rs-latin.json' assert { type: 'json' } -import ru from './ru.json' assert { type: 'json' } -import sv from './sv.json' assert { type: 'json' } -import th from './th.json' assert { type: 'json' } -import tr from './tr.json' assert { type: 'json' } -import ua from './ua.json' assert { type: 'json' } -import vi from './vi.json' assert { type: 'json' } -import zh from './zh.json' assert { type: 'json' } -import zhTw from './zh-tw.json' assert { type: 'json' } +const { default: ar } = await import('./ar.json', { assert: { type: 'json' } }) +const { default: az } = await import('./az.json', { assert: { type: 'json' } }) +const { default: bg } = await import('./bg.json', { assert: { type: 'json' } }) +const { default: cs } = await import('./cs.json', { assert: { type: 'json' } }) +const { default: de } = await import('./de.json', { assert: { type: 'json' } }) +const { default: en } = await import('./en.json', { assert: { type: 'json' } }) +const { default: es } = await import('./es.json', { assert: { type: 'json' } }) +const { default: fa } = await import('./fa.json', { assert: { type: 'json' } }) +const { default: fr } = await import('./fr.json', { assert: { type: 'json' } }) +const { default: hr } = await import('./hr.json', { assert: { type: 'json' } }) +const { default: hu } = await import('./hu.json', { assert: { type: 'json' } }) +const { default: it } = await import('./it.json', { assert: { type: 'json' } }) +const { default: ja } = await import('./ja.json', { assert: { type: 'json' } }) +const { default: ko } = await import('./ko.json', { assert: { type: 'json' } }) +const { default: my } = await import('./my.json', { assert: { type: 'json' } }) +const { default: nb } = await import('./nb.json', { assert: { type: 'json' } }) +const { default: nl } = await import('./nl.json', { assert: { type: 'json' } }) +const { default: pl } = await import('./pl.json', { assert: { type: 'json' } }) +const { default: pt } = await import('./pt.json', { assert: { type: 'json' } }) +const { default: ro } = await import('./ro.json', { assert: { type: 'json' } }) +const { default: rs } = await import('./rs.json', { assert: { type: 'json' } }) +const { default: rsLatin } = await import('./rs-latin.json', { assert: { type: 'json' } }) +const { default: ru } = await import('./ru.json', { assert: { type: 'json' } }) +const { default: sv } = await import('./sv.json', { assert: { type: 'json' } }) +const { default: th } = await import('./th.json', { assert: { type: 'json' } }) +const { default: tr } = await import('./tr.json', { assert: { type: 'json' } }) +const { default: ua } = await import('./ua.json', { assert: { type: 'json' } }) +const { default: vi } = await import('./vi.json', { assert: { type: 'json' } }) +const { default: zh } = await import('./zh.json', { assert: { type: 'json' } }) +const { default: zhTw } = await import('./zh-tw.json', { assert: { type: 'json' } }) export const translations = { ar,
192964417dbc774232f742b9c45ba0b6342a6c41
2025-03-03 09:35:25
Alessio Gravili
chore: temporarily disables flaky "should execute a custom script" test (#11487)
false
temporarily disables flaky "should execute a custom script" test (#11487)
chore
diff --git a/test/config/int.spec.ts b/test/config/int.spec.ts index c3a843cc000..0b6b568878c 100644 --- a/test/config/int.spec.ts +++ b/test/config/int.spec.ts @@ -129,7 +129,7 @@ describe('Config', () => { } } - it('should execute a custom script', () => { + it.skip('should execute a custom script', () => { deleteTestFile() executeCLI('start-server') expect(JSON.parse(readFileSync(testFilePath, 'utf-8')).docs).toHaveLength(1)
ee62c2a722bb0cee9b9b7db3b1e83c7a8415112b
2023-02-09 22:42:12
Elliot DeNolf
chore: additional webpack mock for dev
false
additional webpack mock for dev
chore
diff --git a/src/adapters/s3/mock.js b/src/adapters/s3/mock.js index c380fe1d7c7..217b6408624 100644 --- a/src/adapters/s3/mock.js +++ b/src/adapters/s3/mock.js @@ -1,4 +1,5 @@ exports.S3 = () => null +exports.Upload = () => null exports.HeadObjectCommand = () => null exports.PutObjectCommand = () => null
96844a5185273d6079e9a1be5062ae1fb83bacf6
2023-09-29 21:56:50
Elliot DeNolf
ci: add builds for bundlers and plugins
false
add builds for bundlers and plugins
ci
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1af75830684..f3af81f82a6 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -165,6 +165,8 @@ jobs: - name: Generate GraphQL schema file run: pnpm dev:generate-graphql-schema graphql-schema-gen +# DB Adapters + build-db-mongodb: runs-on: ubuntu-latest needs: core-build @@ -214,3 +216,82 @@ jobs: - name: Build db-postgres run: pnpm turbo run build --filter=db-postgres + +# Bundlers + + build-bundler-webpack: + runs-on: ubuntu-latest + needs: core-build + + steps: + - name: Use Node.js 18 + uses: actions/setup-node@v3 + with: + node-version: 18 + + - name: Install pnpm + uses: pnpm/action-setup@v2 + with: + version: 8 + run_install: false + + - name: Restore build + uses: actions/cache@v3 + with: + path: ./* + key: ${{ github.sha }}-${{ github.run_number }} + + - name: Build bundler-webpack + run: pnpm turbo run build --filter=bundler-webpack + + build-bundler-vite: + runs-on: ubuntu-latest + needs: core-build + + steps: + - name: Use Node.js 18 + uses: actions/setup-node@v3 + with: + node-version: 18 + + - name: Install pnpm + uses: pnpm/action-setup@v2 + with: + version: 8 + run_install: false + + - name: Restore build + uses: actions/cache@v3 + with: + path: ./* + key: ${{ github.sha }}-${{ github.run_number }} + + - name: Build bundler-vite + run: pnpm turbo run build --filter=bundler-vite + +# Other Plugins + + build-plugin-richtext-slate: + runs-on: ubuntu-latest + needs: core-build + + steps: + - name: Use Node.js 18 + uses: actions/setup-node@v3 + with: + node-version: 18 + + - name: Install pnpm + uses: pnpm/action-setup@v2 + with: + version: 8 + run_install: false + + - name: Restore build + uses: actions/cache@v3 + with: + path: ./* + key: ${{ github.sha }}-${{ github.run_number }} + + - name: Build richtext-slate + run: pnpm turbo run build --filter=richtext-slate
dd8c1d7a9ec495195fe67f54e63d7c04a379825c
2022-05-17 04:59:03
Dan Ribbens
chore(release): v0.17.0
false
v0.17.0
chore
diff --git a/CHANGELOG.md b/CHANGELOG.md index c20165aee38..23d249d64b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +# [0.17.0](https://github.com/payloadcms/payload/compare/v0.16.4...v0.17.0) (2022-05-16) + + +### Bug Fixes + +* apply field condition to custom components ([#560](https://github.com/payloadcms/payload/issues/560)) ([1dfe2b8](https://github.com/payloadcms/payload/commit/1dfe2b892947411ff5295f5818befe28c4972915)) +* prevent changing order of readOnly arrays ([#563](https://github.com/payloadcms/payload/issues/563)) ([16b7edb](https://github.com/payloadcms/payload/commit/16b7edbc9782dcfb3bef77f1ff312e041d66922c)) + ## [0.16.4](https://github.com/payloadcms/payload/compare/v0.16.3...v0.16.4) (2022-05-06) diff --git a/package.json b/package.json index 86b972fab33..cab85b02119 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "0.16.4", + "version": "0.17.0", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "SEE LICENSE IN license.md", "author": {
14cbf2f079f782fae48fb38875bd0058e1a70672
2022-10-18 23:40:27
Hung Vu
docs: correction to demo code of radio field (#1266)
false
correction to demo code of radio field (#1266)
docs
diff --git a/docs/fields/radio.mdx b/docs/fields/radio.mdx index 1918016bd7d..b3f85304c79 100644 --- a/docs/fields/radio.mdx +++ b/docs/fields/radio.mdx @@ -23,7 +23,7 @@ keywords: radio, fields, config, configuration, documentation, Content Managemen | **`hooks`** | Provide field-based hooks to control logic for this field. [More](/docs/fields/overview#field-level-hooks) | | **`access`** | Provide field-based access control to denote what users can see and do with this field's data. [More](/docs/fields/overview#field-level-access-control) | | **`hidden`** | Restrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API or the Admin panel. | -| **`defaultValue`** | Provide data to be used for this field's default value. [More](/docs/fields/overview#default-values) | +| **`defaultValue`** | Provide data to be used for this field's default value. The default value must exist within provided values in `options`. [More](/docs/fields/overview#default-values) | | **`localized`** | Enable localization for this field. Requires [localization to be enabled](/docs/configuration/localization) in the Base config. | | **`required`** | Require this field to have a value. | | **`admin`** | Admin-specific configuration. See below for [more detail](#admin-config). | @@ -41,7 +41,7 @@ In addition to the default [field admin config](/docs/fields/overview#admin-conf **`layout`** -The `layout` property allows for the radio group to be styled as a horizonally or vertically distributed list. +The `layout` property allows for the radio group to be styled as a horizonally or vertically distributed list. The default value is `horizontal`. ### Example @@ -65,7 +65,7 @@ const ExampleCollection: CollectionConfig = { value: 'dark_gray', }, ], - defaultValue: 'option_1', + defaultValue: 'mint', // The first value in options. admin: { layout: 'horizontal', }
3a86822f0ad2be140d9198eee212ed5e7b6ef547
2024-08-16 21:34:32
Paul
fix(ui): ensure that aborting Autosave always has a valid reason for the controller - fixes uncaught error (#7723)
false
ensure that aborting Autosave always has a valid reason for the controller - fixes uncaught error (#7723)
fix
diff --git a/packages/ui/src/elements/Autosave/index.tsx b/packages/ui/src/elements/Autosave/index.tsx index f2aed23779a..d06e50b142f 100644 --- a/packages/ui/src/elements/Autosave/index.tsx +++ b/packages/ui/src/elements/Autosave/index.tsx @@ -224,7 +224,7 @@ export const Autosave: React.FC<Props> = ({ if (autosaveTimeout) clearTimeout(autosaveTimeout) if (abortController.signal) { try { - abortController.abort() + abortController.abort('Autosave closed early.') } catch (error) { // swallow error }
cc9f9dd704ffd2602791b31cbcce5ac3093877a4
2022-08-18 23:47:31
Jacob Fletcher
feat: opens stripe rest
false
opens stripe rest
feat
diff --git a/packages/plugin-stripe/README.md b/packages/plugin-stripe/README.md index d7c2e3cc831..ec75b9f8ef0 100644 --- a/packages/plugin-stripe/README.md +++ b/packages/plugin-stripe/README.md @@ -5,9 +5,9 @@ A plugin for [Payload CMS](https://github.com/payloadcms/payload) to manage a [Stripe](https://stripe.com/) account through Payload. Core features: - - Provides a layer of Payload access control over your Stripe account - - Opens custom routes to interface with the Stripe API - - Allows two-way data sync from Stripe to Payload + - Layers your Stripe account with Payload access control + - Opens custom routes to interface with the Stripe REST API + - Handles Stripe webhooks to allow for a two-way data sync ## Installation @@ -56,17 +56,20 @@ The following routes are automatically opened to allow you to interact with the >NOTE: the `/api` part of these routes may be different based on the settings defined in your Payload config. -- `GET /api/stripe/products` +- `POST /api/stripe/rest` - Returns every product available in your account by calling [`stripe.products.list`](https://stripe.com/docs/api/products/list). + Calls the given [Stripe REST API](https://stripe.com/docs/api) method and returns the result. -- `GET /api/stripe/subscriptions/:id` - - Returns a customer's subscriptions by calling [`stripe.subscriptions.retrieve(id)`](https://stripe.com/docs/api/subscriptions/list). - -- `POST /api/stripe/subscriptions/update-payment` - - Returns an http status code. Updates a subscription's payment method by calling [`stripe.subscriptions.update(id)`](https://stripe.com/docs/api/subscriptions/update). Send the subscription ID through the body of your request. + ``` + const res = await fetch(`/api/stripe/rest`, { + body: JSON.stringify({ + stripeMethod: "stripe.subscriptions.list', + stripeMethodArgs: { + customer: "abc" + } + }) + }) + ``` - `POST /api/stripe/webhooks` @@ -113,6 +116,21 @@ import { } from '@payloadcms/plugin-stripe/dist/types'; ``` +### Development + +This plugin can be developed locally using any Stripe account that you have access to. Then: + +```bash +git clone [email protected]:payloadcms/plugin-stripe.git \ + cd plugin-stripe && yarn \ + cd demo && yarn \ + cp .env.example .env \ + vim .env \ # add your Stripe creds to this file + yarn dev +``` + +Now you have a running Payload server with this plugin installed, so you can authenticate and begin hitting the routes. To do this, open [Postman](https://www.postman.com/) and import [our config](https://github.com/payloadcms/plugin-stripe/blob/main/src/payload-stripe-plugin.postman_collection.json). First, login to retrieve your Payload access token. This token is automatically attached to the header of all other requests. + ## Screenshots <!-- ![screenshot 1](https://github.com/@payloadcms/plugin-stripe/blob/main/images/screenshot-1.jpg?raw=true) --> diff --git a/packages/plugin-stripe/demo/package.json b/packages/plugin-stripe/demo/package.json index e67053ee585..0792fcbbc07 100644 --- a/packages/plugin-stripe/demo/package.json +++ b/packages/plugin-stripe/demo/package.json @@ -13,9 +13,9 @@ "generate:types": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:types" }, "dependencies": { - "payload": "^1.0.9", "dotenv": "^8.2.0", - "express": "^4.17.1" + "express": "^4.17.1", + "payload": "^1.0.25" }, "devDependencies": { "@types/express": "^4.17.9", diff --git a/packages/plugin-stripe/demo/yarn.lock b/packages/plugin-stripe/demo/yarn.lock index 0f45b9fd3df..ae916fc0603 100644 --- a/packages/plugin-stripe/demo/yarn.lock +++ b/packages/plugin-stripe/demo/yarn.lock @@ -2534,9 +2534,9 @@ bson-objectid@^2.0.1: integrity sha512-WYwVtY9yqk179EPMNuF3vcxufdrGLEo2XwqdRVbfLVe9X6jLt7WKZQgP+ObOcprakBGbHxzl76tgTaieqsH29g== bson@^4.6.5: - version "4.6.5" - resolved "https://registry.yarnpkg.com/bson/-/bson-4.6.5.tgz#1a410148c20eef4e40d484878a037a7036e840fb" - integrity sha512-uqrgcjyOaZsHfz7ea8zLRCLe1u+QGUSzMZmvXqO24CDW7DWoW1qiN9folSwa7hSneTSgM2ykDIzF5kcQQ8cwNw== + version "4.7.0" + resolved "https://registry.yarnpkg.com/bson/-/bson-4.7.0.tgz#7874a60091ffc7a45c5dd2973b5cad7cded9718a" + integrity sha512-VrlEE4vuiO1WTpfof4VmaVolCVYkYTgB9iWgYNOrVlnifpME/06fhFRmONgBhClD5pFC1t9ZWqFUQEQAzY43bA== dependencies: buffer "^5.6.0" @@ -3242,9 +3242,9 @@ dataloader@^2.1.0: integrity sha512-qTcEYLen3r7ojZNgVUaRggOI+KM7jrKxXeSHhogh/TWxYMeONEMqY+hmkobiYQozsGIyg9OYVzO4ZIfoB4I0pQ== date-fns@^2.0.1, date-fns@^2.14.0: - version "2.29.1" - resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.29.1.tgz#9667c2615525e552b5135a3116b95b1961456e60" - integrity sha512-dlLD5rKaKxpFdnjrs+5azHDFOPEu4ANy/LTh04A1DTzMM7qoajmKCBc8pkKRFT41CNzw+4gQh79X5C+Jq27HAw== + version "2.29.2" + resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.29.2.tgz#0d4b3d0f3dff0f920820a070920f0d9662c51931" + integrity sha512-0VNbwmWJDS/G3ySwFSJA3ayhbURMTJLtwM2DTxf9CWondCnh6DTNlO9JgRSq6ibf4eD0lfMJNBxUdEAHHix+bA== dateformat@^4.5.1: version "4.6.3" @@ -3531,9 +3531,9 @@ [email protected]: integrity sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow== electron-to-chromium@^1.4.202: - version "1.4.222" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.222.tgz#2ba24bef613fc1985dbffea85df8f62f2dec6448" - integrity sha512-gEM2awN5HZknWdLbngk4uQCVfhucFAfFzuchP3wM3NN6eow1eDU0dFy2kts43FB20ZfhVFF0jmFSTb1h5OhyIg== + version "1.4.224" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.224.tgz#ecf2eed395cfedcbbe634658ccc4b457f7b254c3" + integrity sha512-dOujC5Yzj0nOVE23iD5HKqrRSDj2SD7RazpZS/b/WX85MtO6/LzKDF4TlYZTBteB+7fvSg5JpWh0sN7fImNF8w== emittery@^0.7.1: version "0.7.2" @@ -6628,10 +6628,10 @@ [email protected]: resolved "https://registry.yarnpkg.com/pause/-/pause-0.0.1.tgz#1d408b3fdb76923b9543d96fb4c9dfd535d9cb5d" integrity sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg== -payload@^1.0.9: - version "1.0.24" - resolved "https://registry.yarnpkg.com/payload/-/payload-1.0.24.tgz#1a5bc168ca34d2d387f7e3a288da465aff7c62ae" - integrity sha512-SGRg45ixrfOh8UF9pqnUvMf/uUOGpeahJx4mcpQ5uq4CE5OzIAgq5tRiJeR9DwydlDyE63oI7ohqJV16wzTeQw== +payload@^1.0.25: + version "1.0.25" + resolved "https://registry.yarnpkg.com/payload/-/payload-1.0.25.tgz#6fc6f8234deecca66040f517a46cd1635731f83f" + integrity sha512-QlYnKCpeUBjIaWjbxyYov5s10003qaJzI49UxDF67EgPK7AfSLWPfmGbvbOMbxTgu0CuF1yCYc+dObpnzVri8g== dependencies: "@babel/cli" "^7.12.8" "@babel/core" "^7.11.6" diff --git a/packages/plugin-stripe/package.json b/packages/plugin-stripe/package.json index 6a9a04c3548..b0bf04512df 100644 --- a/packages/plugin-stripe/package.json +++ b/packages/plugin-stripe/package.json @@ -20,14 +20,23 @@ ], "author": "[email protected]", "license": "MIT", + "peerDependencies": { + "payload": "^0.18.5 || ^1.0.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + }, + "dependencies": { + "lodash.get": "^4.4.2", + "stripe": "^10.2.0" + }, "devDependencies": { + "@types/lodash.get": "^4.4.7", + "@types/react": "^18.0.8", + "@types/react-dom": "^18.0.3", "payload": "^1.0.9", + "react": "^18.0.0", "typescript": "^4.5.5" }, "files": [ "dist" - ], - "dependencies": { - "stripe": "^10.2.0" - } + ] } diff --git a/packages/plugin-stripe/src/index.ts b/packages/plugin-stripe/src/index.ts index 69eece024e5..19ba68af8b5 100644 --- a/packages/plugin-stripe/src/index.ts +++ b/packages/plugin-stripe/src/index.ts @@ -1,44 +1,29 @@ import { Config } from 'payload/config'; -import { getAllProducts } from './routes/getAllProducts'; -import { getStripeSubscriptions } from './routes/getSubscriptions'; -import { updateStripePayment } from './routes/updatePayment'; -import webhooks from './routes/webhooks'; +import { PayloadRequest } from 'payload/dist/types'; +import { stripeREST } from './routes/rest'; +import { stripeWebhooks } from './routes/webhooks'; import { StripeConfig } from './types'; const stripe = (stripeConfig: StripeConfig) => (config: Config): Config => { return ({ ...config, - // endpoints: [ - // ...config?.endpoints || [], - // { - // path: '/stripe/webhooks', - // method: 'post', - // handler: (req, res) => { - // webhooks(req, res, stripeConfig) - // } - // }, - // { - // path: '/stripe/subscriptions/update-payment', - // method: 'post', - // handler: (req, res) => { - // updateStripePayment(req, res, stripeConfig) - // } - // }, - // { - // path: '/stripe/subscriptions/:id', - // method: 'get', - // handler: (req, res) => { - // getStripeSubscriptions(req, res, stripeConfig) - // } - // }, - // { - // path: '/stripe/products', - // method: 'get', - // handler: (req, res) => { - // getAllProducts(req, res, stripeConfig) - // } - // }, - // ] + endpoints: [ + ...config?.endpoints || [], + { + path: '/stripe/webhooks', + method: 'post', + handler: (req: PayloadRequest, res: any, next: any) => { + stripeWebhooks(req, res, next, stripeConfig) + } + }, + { + path: '/stripe/rest', + method: 'post', + handler: (req: PayloadRequest, res: any, next: any) => { + stripeREST(req, res, next, stripeConfig) + } + }, + ] }) }; diff --git a/packages/plugin-stripe/src/payload-stripe-plugin.postman_collection.json b/packages/plugin-stripe/src/payload-stripe-plugin.postman_collection.json new file mode 100644 index 00000000000..f1148e8cfd1 --- /dev/null +++ b/packages/plugin-stripe/src/payload-stripe-plugin.postman_collection.json @@ -0,0 +1,119 @@ +{ + "info": { + "_postman_id": "130686e1-ddd9-40f1-b031-68ec1a6413ee", + "name": "Payload Stripe Plugin", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "4309346" + }, + "item": [ + { + "name": "Get All Products", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + }, + { + "key": "Authorization", + "value": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImphY29ic2ZsZXRjaEBnbWFpbC5jb20iLCJpZCI6IjYyMGYyMGUxM2Y2NmNkNmYyYWI1MDVjOCIsImNvbGxlY3Rpb24iOiJ1c2VycyIsImlhdCI6MTY2MDgzNTE3MCwiZXhwIjoxNjYwODQyMzcwfQ.46HcrF-SSlOsEbYtdzzUTWZm2J5_30y6LC1FiMoVCPg", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"stripeMethod\": \"subscriptions.list\",\n \"stripeArgs\": {\n \"customer\": \"cus_MGgt3Tuj3D66f2\"\n }\n}" + }, + "url": { + "raw": "localhost:3000/api/stripe/rest", + "host": [ + "localhost" + ], + "port": "3000", + "path": [ + "api", + "stripe", + "rest" + ] + } + }, + "response": [] + }, + { + "name": "Login", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "let jsonData = pm.response.json();", + "pm.environment.set(\"PAYLOAD_API_TOKEN\", jsonData.token);" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"email\": \"[email protected]\",\n\t\"password\": \"test\"\n}" + }, + "url": { + "raw": "localhost:3000/api/users/login", + "host": [ + "localhost" + ], + "port": "3000", + "path": [ + "api", + "users", + "login" + ] + }, + "description": "\t" + }, + "response": [] + }, + { + "name": "Refresh Token", + "protocolProfileBehavior": { + "disabledSystemHeaders": {} + }, + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImphY29ic2ZsZXRjaEBnbWFpbC5jb20iLCJpZCI6IjYwODJlZjUxMzg5ZmM2MmYzNWI2MmM2ZiIsImNvbGxlY3Rpb24iOiJ1c2VycyIsImZpcnN0TmFtZSI6IkphY29iIiwibGFzdE5hbWUiOiJGbGV0Y2hlciIsIm9yZ2FuaXphdGlvbiI6IjYwN2RiNGNmYjYzMGIyNWI5YzkzNmMzNSIsImlhdCI6MTYzMTExMDk3NSwiZXhwIjoxNjMyOTI1Mzc1fQ.OL9l8jFNaCZCU-ZDQpH-EJauaRM-5JT4_Y3J_-aC-aY\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "localhost:3000/api/users/refresh-token", + "host": [ + "localhost" + ], + "port": "3000", + "path": [ + "api", + "users", + "refresh-token" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/packages/plugin-stripe/src/routes/getAllProducts.ts b/packages/plugin-stripe/src/routes/getAllProducts.ts deleted file mode 100644 index 5929b257ca9..00000000000 --- a/packages/plugin-stripe/src/routes/getAllProducts.ts +++ /dev/null @@ -1,38 +0,0 @@ -import payload from 'payload'; -import { PayloadRequest } from 'payload/dist/types'; -import { Forbidden } from 'payload/errors'; -import Stripe from 'stripe'; -import { StripeConfig } from '../types'; - -export const getAllProducts = async ( - req: PayloadRequest, - res: any, - next: any, - stripeConfig: StripeConfig -) => { - const { stripeSecretKey } = stripeConfig; - - const stripe = new Stripe(stripeSecretKey, { apiVersion: '2022-08-01' }); - - try { - const { user } = req; - - if (!user) { - throw new Forbidden(); - } - - const products = await stripe.products.list(({ - limit: 20, - })); - - if (!products?.data) { - return res.status(404); - } - - return res.json({ - products - }); - } catch (err) { - return next(err); - } -}; diff --git a/packages/plugin-stripe/src/routes/getSubscriptions.ts b/packages/plugin-stripe/src/routes/getSubscriptions.ts deleted file mode 100644 index eb2167a2b0f..00000000000 --- a/packages/plugin-stripe/src/routes/getSubscriptions.ts +++ /dev/null @@ -1,50 +0,0 @@ -import payload from 'payload'; -import { PayloadRequest } from 'payload/dist/types'; -import { Forbidden } from 'payload/errors'; -import Stripe from 'stripe'; -import { StripeConfig } from '../types'; - -export const getStripeSubscriptions = async ( - req: PayloadRequest, - res: any, - next: any, - stripeConfig: StripeConfig -) => { - const { stripeSecretKey } = stripeConfig; - - const stripe = new Stripe(stripeSecretKey, { apiVersion: '2022-08-01' }); - - try { - const { params: { id }, user } = req; - - if (!user) { - throw new Forbidden(); - } - - const subscription = await stripe.subscriptions.retrieve(id); - - if (!subscription?.items?.data?.[0]?.plan?.id) { - return res.status(404); - } - - const paymentMethod = await stripe.paymentMethods.retrieve(subscription.default_payment_method as string); - - const invoices = await stripe.invoices.list({ - subscription: id, - limit: 20, - }); - - return res.json({ - paymentMethod: { - brand: paymentMethod?.card?.brand, - last4: paymentMethod?.card?.last4, - }, - invoices: invoices.data.map(({ amount_due: amount, created }) => ({ - amount, - created, - })), - }); - } catch (err) { - return next(err); - } -}; diff --git a/packages/plugin-stripe/src/routes/rest.ts b/packages/plugin-stripe/src/routes/rest.ts new file mode 100644 index 00000000000..72f9659eaa4 --- /dev/null +++ b/packages/plugin-stripe/src/routes/rest.ts @@ -0,0 +1,56 @@ +import { PayloadRequest } from 'payload/dist/types'; +import { Forbidden } from 'payload/errors'; +import Stripe from 'stripe'; +import { StripeConfig } from '../types'; +import lodashGet from 'lodash.get'; + +export const stripeREST = async ( + req: PayloadRequest, + res: Response, + next: any, + stripeConfig: StripeConfig +) => { + const { stripeSecretKey } = stripeConfig; + + const stripe = new Stripe(stripeSecretKey, { apiVersion: '2022-08-01' }); + + try { + const { + body: { + stripeMethod, // 'subscriptions.list', + stripeArgs // 'cus_MGgt3Tuj3D66f2' + }, + user + } = req; + + if (!user) { + throw new Forbidden(); + } + + if (typeof stripeMethod === 'string') { + const foundMethod = lodashGet(stripe, stripeMethod); // NOTE: convert dot notation + + if (typeof foundMethod === 'function') { + + const stripeResponse = await foundMethod.apply(stripe, stripeArgs); + + // const stripeResponse = await stripe.subscriptions.list(stripeArgs); + + if (!stripeResponse?.data) { + return res.status(404); + } + + return res.json(stripeResponse); + } else { + console.warn(`The provide Stripe method of '${stripeMethod}' is not a part of the Stripe API.`); + return next(); + } + } else { + console.warn('You must provide a Stripe method to call.'); + return next(); + } + + } catch (err) { + return next(err); + } +}; diff --git a/packages/plugin-stripe/src/routes/updatePayment.ts b/packages/plugin-stripe/src/routes/updatePayment.ts deleted file mode 100644 index ee6c8864a4b..00000000000 --- a/packages/plugin-stripe/src/routes/updatePayment.ts +++ /dev/null @@ -1,36 +0,0 @@ -import payload from 'payload'; -import { PayloadRequest } from 'payload/dist/types'; -import { Forbidden } from 'payload/errors'; -import Stripe from 'stripe'; -import { StripeConfig } from '../types'; - -export const updateStripePayment = async ( - req: PayloadRequest, - res: any, - next: any, - stripeConfig: StripeConfig -) => { - const { stripeSecretKey } = stripeConfig; - - const stripe = new Stripe(stripeSecretKey, { apiVersion: '2022-08-01' }); - - try { - const { body: { subscriptionID, paymentMethodID }, user } = req; - - if (!user) { - throw new Forbidden(); - } - - await stripe.paymentMethods.attach(paymentMethodID, { - customer: user.stripeCustomerID as string, // TODO: remove type assertion - }); - - await stripe.subscriptions.update(subscriptionID, { - default_payment_method: paymentMethodID, - }); - - return res.sendStatus(200); - } catch (err) { - return next(err); - } -}; diff --git a/packages/plugin-stripe/src/routes/webhooks.ts b/packages/plugin-stripe/src/routes/webhooks.ts index f58fc56cc08..0128d9e26a1 100644 --- a/packages/plugin-stripe/src/routes/webhooks.ts +++ b/packages/plugin-stripe/src/routes/webhooks.ts @@ -2,7 +2,7 @@ import Stripe from 'stripe'; import { PayloadRequest } from 'payload/dist/types'; import { StripeConfig } from '../types'; -const webhooks = ( +export const stripeWebhooks = ( req: PayloadRequest, res: any, next: any, @@ -37,5 +37,3 @@ const webhooks = ( res.json({ received: true }); }; - -export default webhooks; diff --git a/packages/plugin-stripe/yarn.lock b/packages/plugin-stripe/yarn.lock index fb4a95ca09a..35146dfa60b 100644 --- a/packages/plugin-stripe/yarn.lock +++ b/packages/plugin-stripe/yarn.lock @@ -1725,7 +1725,14 @@ resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.11.tgz#d421b6c527a3037f7c84433fd2c4229e016863d3" integrity sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ== -"@types/lodash@^4.14.149", "@types/lodash@^4.14.182": +"@types/lodash.get@^4.4.7": + version "4.4.7" + resolved "https://registry.yarnpkg.com/@types/lodash.get/-/lodash.get-4.4.7.tgz#1ea63d8b94709f6bc9e231f252b31440abe312cf" + integrity sha512-af34Mj+KdDeuzsJBxc/XeTtOx0SZHZNLd+hdrn+PcKGQs0EG2TJTzQAOTCZTgDJCArahlCzLWSy8c2w59JRz7Q== + dependencies: + "@types/lodash" "*" + +"@types/lodash@*", "@types/lodash@^4.14.149", "@types/lodash@^4.14.182": version "4.14.183" resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.183.tgz#1173e843e858cff5b997c234df2789a4a54c2374" integrity sha512-UXavyuxzXKMqJPEpFPri6Ku5F9af6ZJXUneHhvQJxavrEjuHkFp2YnDWHcxJiG7hk8ZkWqjcyNeW1s/smZv5cw== @@ -1760,6 +1767,13 @@ resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.5.tgz#5f19d2b85a98e9558036f6a3cacc8819420f05cf" integrity sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w== +"@types/react-dom@^18.0.3": + version "18.0.6" + resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-18.0.6.tgz#36652900024842b74607a17786b6662dd1e103a1" + integrity sha512-/5OFZgfIPSwy+YuIBP/FgJnQnsxhZhjjrnxudMddeblOouIodEQ75X14Rr4wGSG/bknL+Omy9iWlLo1u/9GzAA== + dependencies: + "@types/react" "*" + "@types/react-redux@^7.1.20": version "7.1.24" resolved "https://registry.yarnpkg.com/@types/react-redux/-/react-redux-7.1.24.tgz#6caaff1603aba17b27d20f8ad073e4c077e975c0" @@ -1770,7 +1784,7 @@ hoist-non-react-statics "^3.3.0" redux "^4.0.0" -"@types/react@*": +"@types/react@*", "@types/react@^18.0.8": version "18.0.17" resolved "https://registry.yarnpkg.com/@types/react/-/react-18.0.17.tgz#4583d9c322d67efe4b39a935d223edcc7050ccf4" integrity sha512-38ETy4tL+rn4uQQi7mB81G7V1g0u2ryquNmsVIOKUAEIDK+3CUjZ6rSRpdvS99dNBnkLFL83qfmtLacGOTIhwQ== @@ -3163,9 +3177,9 @@ dataloader@^2.1.0: integrity sha512-qTcEYLen3r7ojZNgVUaRggOI+KM7jrKxXeSHhogh/TWxYMeONEMqY+hmkobiYQozsGIyg9OYVzO4ZIfoB4I0pQ== date-fns@^2.0.1, date-fns@^2.14.0: - version "2.29.1" - resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.29.1.tgz#9667c2615525e552b5135a3116b95b1961456e60" - integrity sha512-dlLD5rKaKxpFdnjrs+5azHDFOPEu4ANy/LTh04A1DTzMM7qoajmKCBc8pkKRFT41CNzw+4gQh79X5C+Jq27HAw== + version "2.29.2" + resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.29.2.tgz#0d4b3d0f3dff0f920820a070920f0d9662c51931" + integrity sha512-0VNbwmWJDS/G3ySwFSJA3ayhbURMTJLtwM2DTxf9CWondCnh6DTNlO9JgRSq6ibf4eD0lfMJNBxUdEAHHix+bA== dateformat@^4.5.1: version "4.6.3" @@ -3452,9 +3466,9 @@ [email protected]: integrity sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow== electron-to-chromium@^1.4.202: - version "1.4.222" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.222.tgz#2ba24bef613fc1985dbffea85df8f62f2dec6448" - integrity sha512-gEM2awN5HZknWdLbngk4uQCVfhucFAfFzuchP3wM3NN6eow1eDU0dFy2kts43FB20ZfhVFF0jmFSTb1h5OhyIg== + version "1.4.224" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.224.tgz#ecf2eed395cfedcbbe634658ccc4b457f7b254c3" + integrity sha512-dOujC5Yzj0nOVE23iD5HKqrRSDj2SD7RazpZS/b/WX85MtO6/LzKDF4TlYZTBteB+7fvSg5JpWh0sN7fImNF8w== emittery@^0.7.1: version "0.7.2" @@ -6517,9 +6531,9 @@ [email protected]: integrity sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg== payload@^1.0.9: - version "1.0.24" - resolved "https://registry.yarnpkg.com/payload/-/payload-1.0.24.tgz#1a5bc168ca34d2d387f7e3a288da465aff7c62ae" - integrity sha512-SGRg45ixrfOh8UF9pqnUvMf/uUOGpeahJx4mcpQ5uq4CE5OzIAgq5tRiJeR9DwydlDyE63oI7ohqJV16wzTeQw== + version "1.0.25" + resolved "https://registry.yarnpkg.com/payload/-/payload-1.0.25.tgz#6fc6f8234deecca66040f517a46cd1635731f83f" + integrity sha512-QlYnKCpeUBjIaWjbxyYov5s10003qaJzI49UxDF67EgPK7AfSLWPfmGbvbOMbxTgu0CuF1yCYc+dObpnzVri8g== dependencies: "@babel/cli" "^7.12.8" "@babel/core" "^7.11.6"
3a98c6ad531c86ec7a3a4163650068a157d56746
2022-07-17 04:15:15
James
feat: ensures groups within blocks render properly
false
ensures groups within blocks render properly
feat
diff --git a/package.json b/package.json index 1c34377d175..7119a118365 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "payload", - "version": "0.20.5-beta.0", + "version": "0.20.7-beta.0", "description": "Node, React and MongoDB Headless CMS and Application Framework", "license": "MIT", "author": { diff --git a/src/admin/components/forms/field-types/Array/Array.tsx b/src/admin/components/forms/field-types/Array/Array.tsx index a65340c6b12..1226335c2ca 100644 --- a/src/admin/components/forms/field-types/Array/Array.tsx +++ b/src/admin/components/forms/field-types/Array/Array.tsx @@ -286,6 +286,7 @@ const ArrayFieldType: React.FC<Props> = (props) => { value={row.id} /> <RenderFields + className={`${baseClass}__fields`} forceRender readOnly={readOnly} fieldTypes={fieldTypes} diff --git a/src/admin/components/forms/field-types/Array/index.scss b/src/admin/components/forms/field-types/Array/index.scss index 3b56605cc7a..df882647c57 100644 --- a/src/admin/components/forms/field-types/Array/index.scss +++ b/src/admin/components/forms/field-types/Array/index.scss @@ -55,7 +55,7 @@ } } - .field-type:last-child { + &__fields>.field-type:last-child { margin-bottom: 0; } } diff --git a/src/admin/components/forms/field-types/Blocks/Blocks.tsx b/src/admin/components/forms/field-types/Blocks/Blocks.tsx index 100e18d69c0..89f1028241d 100644 --- a/src/admin/components/forms/field-types/Blocks/Blocks.tsx +++ b/src/admin/components/forms/field-types/Blocks/Blocks.tsx @@ -336,6 +336,7 @@ const Blocks: React.FC<Props> = (props) => { value={row.id} /> <RenderFields + className={`${baseClass}__fields`} forceRender readOnly={readOnly} fieldTypes={fieldTypes} diff --git a/src/admin/components/forms/field-types/Blocks/index.scss b/src/admin/components/forms/field-types/Blocks/index.scss index 5a734159048..8b6c45c3f5a 100644 --- a/src/admin/components/forms/field-types/Blocks/index.scss +++ b/src/admin/components/forms/field-types/Blocks/index.scss @@ -74,7 +74,7 @@ } } - .field-type:last-child { + &__fields>.field-type:last-child { margin-bottom: 0; } } diff --git a/src/admin/components/forms/field-types/Group/index.scss b/src/admin/components/forms/field-types/Group/index.scss index f121fc9e15c..5751390ae46 100644 --- a/src/admin/components/forms/field-types/Group/index.scss +++ b/src/admin/components/forms/field-types/Group/index.scss @@ -29,6 +29,18 @@ border-bottom: 0; } + &--within-tab:first-child { + margin-top: 0; + border-top: 0; + padding-top: 0; + } + + &--within-tab:last-child { + margin-bottom: 0; + border-bottom: 0; + padding-bottom: 0; + } + &--gutter { border-left: 1px solid var(--theme-elevation-100); padding: 0 0 0 $baseline; diff --git a/src/admin/components/forms/field-types/Group/index.tsx b/src/admin/components/forms/field-types/Group/index.tsx index c4fd70f0734..665bd03ca0a 100644 --- a/src/admin/components/forms/field-types/Group/index.tsx +++ b/src/admin/components/forms/field-types/Group/index.tsx @@ -8,6 +8,7 @@ import { useCollapsible } from '../../../elements/Collapsible/provider'; import './index.scss'; import { GroupProvider, useGroup } from './provider'; +import { useTabs } from '../Tabs/provider'; const baseClass = 'group-field'; @@ -31,6 +32,7 @@ const Group: React.FC<Props> = (props) => { const isWithinCollapsible = useCollapsible(); const isWithinGroup = useGroup(); + const isWithinTab = useTabs(); const path = pathFromProps || name; @@ -42,6 +44,7 @@ const Group: React.FC<Props> = (props) => { baseClass, isWithinCollapsible && `${baseClass}--within-collapsible`, isWithinGroup && `${baseClass}--within-group`, + isWithinTab && `${baseClass}--within-tab`, (!hideGutter && isWithinGroup) && `${baseClass}--gutter`, className, ].filter(Boolean).join(' ')} diff --git a/src/admin/components/forms/field-types/Tabs/index.tsx b/src/admin/components/forms/field-types/Tabs/index.tsx index 4a5da62b3b3..d6c3a0eff7c 100644 --- a/src/admin/components/forms/field-types/Tabs/index.tsx +++ b/src/admin/components/forms/field-types/Tabs/index.tsx @@ -6,6 +6,7 @@ import { fieldAffectsData } from '../../../../../fields/config/types'; import FieldDescription from '../../FieldDescription'; import toKebabCase from '../../../../../utilities/toKebabCase'; import { useCollapsible } from '../../../elements/Collapsible/provider'; +import { TabsProvider } from './provider'; import './index.scss'; @@ -35,25 +36,26 @@ const TabsField: React.FC<Props> = (props) => { isWithinCollapsible && `${baseClass}--within-collapsible`, ].filter(Boolean).join(' ')} > - <div className={`${baseClass}__tabs`}> - {tabs.map((tab, i) => { - return ( - <button - key={i} - type="button" - className={[ - `${baseClass}__tab-button`, - active === i && `${baseClass}__tab-button--active`, - ].filter(Boolean).join(' ')} - onClick={() => setActive(i)} - > - {tab.label} - </button> - ); - })} - </div> - <div className={`${baseClass}__content-wrap`}> - {activeTab && ( + <TabsProvider> + <div className={`${baseClass}__tabs`}> + {tabs.map((tab, i) => { + return ( + <button + key={i} + type="button" + className={[ + `${baseClass}__tab-button`, + active === i && `${baseClass}__tab-button--active`, + ].filter(Boolean).join(' ')} + onClick={() => setActive(i)} + > + {tab.label} + </button> + ); + })} + </div> + <div className={`${baseClass}__content-wrap`}> + {activeTab && ( <div className={[ `${baseClass}__tab`, `${baseClass}__tab-${toKebabCase(activeTab.label)}`, @@ -74,8 +76,9 @@ const TabsField: React.FC<Props> = (props) => { }))} /> </div> - )} - </div> + )} + </div> + </TabsProvider> </div> ); }; diff --git a/src/admin/components/forms/field-types/Tabs/provider.tsx b/src/admin/components/forms/field-types/Tabs/provider.tsx new file mode 100644 index 00000000000..4f5e5786e30 --- /dev/null +++ b/src/admin/components/forms/field-types/Tabs/provider.tsx @@ -0,0 +1,17 @@ +import React, { + createContext, useContext, +} from 'react'; + +const Context = createContext(false); + +export const TabsProvider: React.FC<{ children?: React.ReactNode, withinTab?: boolean }> = ({ children, withinTab = true }) => { + return ( + <Context.Provider value={withinTab}> + {children} + </Context.Provider> + ); +}; + +export const useTabs = (): boolean => useContext(Context); + +export default Context; diff --git a/src/admin/scss/styles.scss b/src/admin/scss/styles.scss index c163b874293..65aa3d3e959 100644 --- a/src/admin/scss/styles.scss +++ b/src/admin/scss/styles.scss @@ -1,4 +1,5 @@ @import 'vars'; +@import 'z-index'; ////////////////////////////// // IMPORT OVERRIDES diff --git a/src/admin/scss/vars.scss b/src/admin/scss/vars.scss index 54d4f257cfc..3fd3813ad51 100644 --- a/src/admin/scss/vars.scss +++ b/src/admin/scss/vars.scss @@ -22,14 +22,14 @@ $baseline : math.div($baseline-px, $baseline-body-size)+rem; } ////////////////////////////// -// FONTS (LEGACY - DO NOT USE. PREFER CSS VARIABLES) +// FONTS (DEPRECATED. DO NOT USE. PREFER CSS VARIABLES) ////////////////////////////// $font-body : 'Suisse Intl' !default; $font-mono : monospace !default; ////////////////////////////// -// COLORS (LEGACY - DO NOT USE. PREFER CSS VARIABLES) +// COLORS (DEPRECATED. DO NOT USE. PREFER CSS VARIABLES) ////////////////////////////// $color-dark-gray : #333333 !default; diff --git a/src/admin/scss/z-index.scss b/src/admin/scss/z-index.scss new file mode 100644 index 00000000000..50c79d53c9a --- /dev/null +++ b/src/admin/scss/z-index.scss @@ -0,0 +1,9 @@ +///////////////////////////// +// Z-INDEX CHART (DEPRECATED. DO NOT USE. PREFER CSS VARIABLES) +///////////////////////////// + +$z-page: 20; +$z-page-content: 30; +$z-nav: 40; +$z-modal: 50; +$z-status: 60; diff --git a/test/fields/collections/Blocks/index.ts b/test/fields/collections/Blocks/index.ts index d14e8002de0..0d02f7d5099 100644 --- a/test/fields/collections/Blocks/index.ts +++ b/test/fields/collections/Blocks/index.ts @@ -1,59 +1,55 @@ import type { CollectionConfig } from '../../../../src/collections/config/types'; +import { Field } from '../../../../src/fields/config/types'; -const BlockFields: CollectionConfig = { - slug: 'block-fields', - fields: [ +export const blocksField: Field = { + name: 'blocks', + type: 'blocks', + required: true, + blocks: [ { - name: 'blocks', - type: 'blocks', - required: true, - blocks: [ + slug: 'text', + fields: [ { - slug: 'text', - fields: [ - { - name: 'text', - type: 'text', - required: true, - }, - ], + name: 'text', + type: 'text', + required: true, }, + ], + }, + { + slug: 'number', + fields: [ { - slug: 'number', - fields: [ - { - name: 'number', - type: 'number', - required: true, - }, - ], + name: 'number', + type: 'number', + required: true, }, + ], + }, + { + slug: 'subBlocks', + fields: [ { - slug: 'subBlocks', - fields: [ + name: 'subBlocks', + type: 'blocks', + blocks: [ { - name: 'subBlocks', - type: 'blocks', - blocks: [ + slug: 'text', + fields: [ { - slug: 'text', - fields: [ - { - name: 'text', - type: 'text', - required: true, - }, - ], + name: 'text', + type: 'text', + required: true, }, + ], + }, + { + slug: 'number', + fields: [ { - slug: 'number', - fields: [ - { - name: 'number', - type: 'number', - required: true, - }, - ], + name: 'number', + type: 'number', + required: true, }, ], }, @@ -64,35 +60,44 @@ const BlockFields: CollectionConfig = { ], }; -export const blocksDoc = { - blocks: [ - { - blockName: 'First block', - blockType: 'text', - text: 'first block', - }, - { - blockName: 'Second block', - blockType: 'number', - number: 342, - }, - { - blockName: 'Sub-block demonstration', - blockType: 'subBlocks', - subBlocks: [ - { - blockName: 'First sub block', - blockType: 'number', - number: 123, - }, - { - blockName: 'Second sub block', - blockType: 'text', - text: 'second sub block', - }, - ], - }, +const BlockFields: CollectionConfig = { + slug: 'block-fields', + fields: [ + blocksField, ], }; +export const blocksFieldSeedData = [ + { + blockName: 'First block', + blockType: 'text', + text: 'first block', + }, + { + blockName: 'Second block', + blockType: 'number', + number: 342, + }, + { + blockName: 'Sub-block demonstration', + blockType: 'subBlocks', + subBlocks: [ + { + blockName: 'First sub block', + blockType: 'number', + number: 123, + }, + { + blockName: 'Second sub block', + blockType: 'text', + text: 'second sub block', + }, + ], + }, +]; + +export const blocksDoc = { + blocks: blocksFieldSeedData, +}; + export default BlockFields; diff --git a/test/fields/collections/Tabs/index.ts b/test/fields/collections/Tabs/index.ts index a3803605042..070cfcf4622 100644 --- a/test/fields/collections/Tabs/index.ts +++ b/test/fields/collections/Tabs/index.ts @@ -1,4 +1,5 @@ import type { CollectionConfig } from '../../../../src/collections/config/types'; +import { blocksField, blocksFieldSeedData } from '../Blocks'; const TabsFields: CollectionConfig = { slug: 'tabs-fields', @@ -8,8 +9,8 @@ const TabsFields: CollectionConfig = { type: 'tabs', tabs: [ { - label: 'Tab One', - description: 'Here is a description for tab one', + label: 'Tab with Array', + description: 'This tab has an array.', fields: [ { name: 'array', @@ -30,24 +31,27 @@ const TabsFields: CollectionConfig = { ], }, { - label: 'Tab Two', - description: 'Description for tab two', + label: 'Tab with Blocks', + description: 'Blocks are rendered here to ensure they populate and render correctly.', fields: [ - { - name: 'text', - type: 'text', - required: true, - }, + blocksField, ], }, { - label: 'Tab Three', - description: 'Description for tab three', + label: 'Tab with Group', + description: 'This tab has a group, which should not render its top border or margin.', fields: [ { - name: 'number', - type: 'number', - required: true, + name: 'group', + type: 'group', + label: 'Group', + fields: [ + { + name: 'number', + type: 'number', + required: true, + }, + ], }, ], }, @@ -100,8 +104,10 @@ export const tabsDoc = { text: 'Here is some data for the third row', }, ], - text: 'This text will show up in the second tab input', - number: 12, + blocks: blocksFieldSeedData, + group: { + number: 12, + }, textarea: 'Here is some text that goes in a textarea', anotherText: 'Super tired of writing this text', };
efce1549d0de8d199126bdca65dd33f285c366c2
2025-03-04 00:01:26
Germán Jabloñski
chore(plugin-search): enable TypeScript strict mode (#11508)
false
enable TypeScript strict mode (#11508)
chore
diff --git a/packages/plugin-search/src/Search/index.ts b/packages/plugin-search/src/Search/index.ts index 425259909a4..9941cb68fcf 100644 --- a/packages/plugin-search/src/Search/index.ts +++ b/packages/plugin-search/src/Search/index.ts @@ -1,13 +1,13 @@ import type { CollectionConfig, Field } from 'payload' -import type { SearchPluginConfigWithLocales } from '../types.js' +import type { SanitizedSearchPluginConfig } from '../types.js' import type { ReindexButtonServerProps } from './ui/ReindexButton/types.js' import { generateReindexHandler } from '../utilities/generateReindexHandler.js' // all settings can be overridden by the config export const generateSearchCollection = ( - pluginConfig: SearchPluginConfigWithLocales, + pluginConfig: SanitizedSearchPluginConfig, ): CollectionConfig => { const searchSlug = pluginConfig?.searchOverrides?.slug || 'search' const searchCollections = pluginConfig?.collections || [] @@ -55,6 +55,10 @@ export const generateSearchCollection = ( }, ] + if (!collectionLabels) { + throw new Error('collectionLabels is required') + } + const newConfig: CollectionConfig = { ...(pluginConfig?.searchOverrides || {}), slug: searchSlug, diff --git a/packages/plugin-search/src/Search/ui/ReindexButton/index.client.tsx b/packages/plugin-search/src/Search/ui/ReindexButton/index.client.tsx index ef46bf14e52..2c4f1a9d7c6 100644 --- a/packages/plugin-search/src/Search/ui/ReindexButton/index.client.tsx +++ b/packages/plugin-search/src/Search/ui/ReindexButton/index.client.tsx @@ -89,7 +89,7 @@ export const ReindexButtonClient: React.FC<ReindexButtonProps> = ({ if (typeof label === 'string') { return label } else { - return Object.hasOwn(label, locale.code) ? label[locale.code] : slug + return label && Object.hasOwn(label, locale.code) ? label[locale.code] : slug } }, [collectionLabels, locale.code], @@ -97,7 +97,10 @@ export const ReindexButtonClient: React.FC<ReindexButtonProps> = ({ const pluralizedLabels = useMemo(() => { return searchCollections.reduce<Record<string, string>>((acc, slug) => { - acc[slug] = getPluralizedLabel(slug) + const label = getPluralizedLabel(slug) + if (label) { + acc[slug] = label + } return acc }, {}) }, [searchCollections, getPluralizedLabel]) @@ -111,9 +114,6 @@ export const ReindexButtonClient: React.FC<ReindexButtonProps> = ({ const modalDescription = selectedAll ? t('general:confirmReindexDescriptionAll') : t('general:confirmReindexDescription', { collections: selectedLabels }) - const loadingText = selectedAll - ? t('general:reindexingAll', { collections: t('general:collections') }) - : t('general:reindexingAll', { collections: selectedLabels }) return ( <div> diff --git a/packages/plugin-search/src/Search/ui/ReindexButton/index.tsx b/packages/plugin-search/src/Search/ui/ReindexButton/index.tsx index 03327ca4dbe..6f08a481fb5 100644 --- a/packages/plugin-search/src/Search/ui/ReindexButton/index.tsx +++ b/packages/plugin-search/src/Search/ui/ReindexButton/index.tsx @@ -12,6 +12,7 @@ export const ReindexButton: SearchReindexButtonServerComponent = (props) => { const pluralLabel = labels?.plural if (typeof pluralLabel === 'function') { + // @ts-expect-error - I don't know why it gives an error. pluralLabel and i18n.t should both resolve to TFunction<DefaultTranslationKeys> return [collection, pluralLabel({ t: i18n.t })] } diff --git a/packages/plugin-search/src/index.ts b/packages/plugin-search/src/index.ts index a43939d1c62..05a4939dc1e 100644 --- a/packages/plugin-search/src/index.ts +++ b/packages/plugin-search/src/index.ts @@ -1,6 +1,6 @@ import type { CollectionAfterChangeHook, CollectionAfterDeleteHook, Config } from 'payload' -import type { SearchPluginConfig, SearchPluginConfigWithLocales } from './types.js' +import type { SanitizedSearchPluginConfig, SearchPluginConfig } from './types.js' import { deleteFromSearch } from './Search/hooks/deleteFromSearch.js' import { syncWithSearch } from './Search/hooks/syncWithSearch.js' @@ -35,7 +35,7 @@ export const searchPlugin = .map((collection) => [collection.slug, collection.labels]), ) - const pluginConfig: SearchPluginConfigWithLocales = { + const pluginConfig: SanitizedSearchPluginConfig = { // write any config defaults here deleteDrafts: true, labels, diff --git a/packages/plugin-search/src/types.ts b/packages/plugin-search/src/types.ts index 48bdf0749ef..4b0e4c1f36b 100644 --- a/packages/plugin-search/src/types.ts +++ b/packages/plugin-search/src/types.ts @@ -77,6 +77,11 @@ export type SearchPluginConfigWithLocales = { locales?: string[] } & SearchPluginConfig +export type SanitizedSearchPluginConfig = { + reindexBatchSize: number + syncDrafts: boolean +} & SearchPluginConfigWithLocales + export type SyncWithSearchArgs = { collection: string pluginConfig: SearchPluginConfig diff --git a/packages/plugin-search/src/utilities/generateReindexHandler.ts b/packages/plugin-search/src/utilities/generateReindexHandler.ts index c7733730146..b14184228c4 100644 --- a/packages/plugin-search/src/utilities/generateReindexHandler.ts +++ b/packages/plugin-search/src/utilities/generateReindexHandler.ts @@ -9,7 +9,7 @@ import { killTransaction, } from 'payload' -import type { SearchPluginConfigWithLocales } from '../types.js' +import type { SanitizedSearchPluginConfig } from '../types.js' import { syncDocAsSearchIndex } from './syncDocAsSearchIndex.js' @@ -19,19 +19,29 @@ type ValidationResult = { } export const generateReindexHandler = - (pluginConfig: SearchPluginConfigWithLocales): PayloadHandler => + (pluginConfig: SanitizedSearchPluginConfig): PayloadHandler => async (req) => { addLocalesToRequestFromData(req) + if (!req.json) { + return new Response('Req.json is undefined', { status: 400 }) + } const { collections = [] } = (await req.json()) as { collections: string[] } const t = req.t const searchSlug = pluginConfig?.searchOverrides?.slug || 'search' const searchCollections = pluginConfig?.collections || [] - const reindexLocales = pluginConfig?.locales?.length ? pluginConfig.locales : [req.locale] + const reindexLocales = pluginConfig?.locales?.length + ? pluginConfig.locales + : req.locale + ? [req.locale] + : [] const validatePermissions = async (): Promise<ValidationResult> => { const accessResults = await getAccessResults({ req }) - const searchAccessResults = accessResults.collections[searchSlug] + const searchAccessResults = accessResults.collections?.[searchSlug] + if (!searchAccessResults) { + return { isValid: false, message: t('error:notAllowedToPerformAction') } + } const permissions = [searchAccessResults.delete, searchAccessResults.update] // plugin doesn't allow create by default: diff --git a/packages/plugin-search/src/utilities/syncDocAsSearchIndex.ts b/packages/plugin-search/src/utilities/syncDocAsSearchIndex.ts index bb8734439f1..2f2159815f9 100644 --- a/packages/plugin-search/src/utilities/syncDocAsSearchIndex.ts +++ b/packages/plugin-search/src/utilities/syncDocAsSearchIndex.ts @@ -56,7 +56,7 @@ export const syncDocAsSearchIndex = async ({ `Error gathering default priority for ${searchSlug} documents related to ${collection}`, ) } - } else { + } else if (priority !== undefined) { defaultPriority = priority } } diff --git a/packages/plugin-search/tsconfig.json b/packages/plugin-search/tsconfig.json index 1d4d43b8fce..fb211828647 100644 --- a/packages/plugin-search/tsconfig.json +++ b/packages/plugin-search/tsconfig.json @@ -1,8 +1,4 @@ { "extends": "../../tsconfig.base.json", - "compilerOptions": { - /* TODO: remove the following lines */ - "strict": false, - }, "references": [{ "path": "../payload" }, { "path": "../ui" }, { "path": "../next" }] }
6a162776f2440a09425ed72078a307fa52ef6de6
2024-04-15 21:23:12
Paul
chore: export react toastify from UI (#5828)
false
export react toastify from UI (#5828)
chore
diff --git a/packages/ui/src/exports/elements.ts b/packages/ui/src/exports/elements.ts index d3b2b4ef5bf..f53972274de 100644 --- a/packages/ui/src/exports/elements.ts +++ b/packages/ui/src/exports/elements.ts @@ -46,9 +46,11 @@ export { Tooltip } from '../elements/Tooltip/index.js' export { Translation } from '../elements/Translation/index.js' export { UnpublishMany } from '../elements/UnpublishMany/index.js' export { Upload } from '../elements/Upload/index.js' -export { BlocksDrawer } from '../fields/Blocks/BlocksDrawer/index.js' import * as facelessUIImport from '@faceless-ui/modal' const { Modal } = facelessUIImport && 'Modal' in facelessUIImport ? facelessUIImport : { Modal: undefined } export { Modal } -export { SetViewActions } from '../providers/Actions/SetViewActions/index.js' +import * as reactToastifyImport from 'react-toastify' +const { toast } = + reactToastifyImport && 'toast' in reactToastifyImport ? reactToastifyImport : { toast: undefined } +export { toast } diff --git a/packages/ui/src/exports/fields.ts b/packages/ui/src/exports/fields.ts new file mode 100644 index 00000000000..79921ad0794 --- /dev/null +++ b/packages/ui/src/exports/fields.ts @@ -0,0 +1 @@ +export { BlocksDrawer } from '../fields/Blocks/BlocksDrawer/index.js' diff --git a/packages/ui/src/exports/providers.ts b/packages/ui/src/exports/providers.ts new file mode 100644 index 00000000000..513c383c5f1 --- /dev/null +++ b/packages/ui/src/exports/providers.ts @@ -0,0 +1 @@ +export { SetViewActions } from '../providers/Actions/SetViewActions/index.js'
c6c5cabfbb7eb954eea51170a6af7582b1f9b84b
2023-12-13 20:44:14
Alessio Gravili
feat(plugin-form-builder): Lexical support (#4487)
false
Lexical support (#4487)
feat
diff --git a/packages/plugin-form-builder/package.json b/packages/plugin-form-builder/package.json index bcae555540c..d13b31696f8 100644 --- a/packages/plugin-form-builder/package.json +++ b/packages/plugin-form-builder/package.json @@ -25,16 +25,16 @@ "escape-html": "^1.0.3" }, "devDependencies": { - "@types/escape-html": "^1.0.1", + "@types/escape-html": "^1.0.4", "@payloadcms/eslint-config": "workspace:*", - "@types/express": "^4.17.9", - "@types/react": "18.0.21", + "@types/express": "^4.17.21", + "@types/react": "18.2.15", "copyfiles": "^2.4.1", "cross-env": "^7.0.3", - "nodemon": "^2.0.6", - "payload": "^1.3.0", + "nodemon": "^3.0.2", + "payload": "workspace:*", "react": "^18.0.0", - "ts-node": "^9.1.1" + "ts-node": "10.9.1" }, "files": [ "dist", diff --git a/packages/plugin-form-builder/src/collections/FormSubmissions/hooks/sendEmail.ts b/packages/plugin-form-builder/src/collections/FormSubmissions/hooks/sendEmail.ts index 3a19c77bb1b..3eb0b8efe7e 100644 --- a/packages/plugin-form-builder/src/collections/FormSubmissions/hooks/sendEmail.ts +++ b/packages/plugin-form-builder/src/collections/FormSubmissions/hooks/sendEmail.ts @@ -1,7 +1,8 @@ import type { Email, FormattedEmail, PluginConfig } from '../../../types' +import { serializeLexical } from '../../../utilities/lexical/serializeLexical' import { replaceDoubleCurlys } from '../../../utilities/replaceDoubleCurlys' -import { serialize } from '../../../utilities/serializeRichText' +import { serializeSlate } from '../../../utilities/slate/serializeSlate' const sendEmail = async (beforeChangeData: any, formConfig: PluginConfig): Promise<any> => { const { data, operation } = beforeChangeData @@ -26,8 +27,8 @@ const sendEmail = async (beforeChangeData: any, formConfig: PluginConfig): Promi const { emails } = form if (emails && emails.length) { - const formattedEmails: FormattedEmail[] = emails.map( - (email: Email): FormattedEmail | null => { + const formattedEmails: FormattedEmail[] = await Promise.all( + emails.map(async (email: Email): Promise<FormattedEmail | null> => { const { bcc: emailBCC, cc: emailCC, @@ -44,16 +45,22 @@ const sendEmail = async (beforeChangeData: any, formConfig: PluginConfig): Promi const from = replaceDoubleCurlys(emailFrom, submissionData) const replyTo = replaceDoubleCurlys(emailReplyTo || emailFrom, submissionData) + const isLexical = message && !Array.isArray(message) && 'root' in message + + const serializedMessage = isLexical + ? await serializeLexical(message, submissionData) + : serializeSlate(message, submissionData) + return { bcc, cc, from, - html: `<div>${serialize(message, submissionData)}</div>`, + html: `<div>${serializedMessage}</div>`, replyTo, subject: replaceDoubleCurlys(subject, submissionData), to, } - }, + }), ) let emailsToSend = formattedEmails @@ -72,7 +79,9 @@ const sendEmail = async (beforeChangeData: any, formConfig: PluginConfig): Promi return emailPromise } catch (err: unknown) { payload.logger.error({ - err: `Error while sending email to address: ${to}. Email not sent: ${err}`, + err: `Error while sending email to address: ${to}. Email not sent: ${JSON.stringify( + err, + )}`, }) } }), diff --git a/packages/plugin-form-builder/src/collections/Forms/DynamicPriceSelector.tsx b/packages/plugin-form-builder/src/collections/Forms/DynamicPriceSelector.tsx index d6305b0ae51..79da6fd5296 100644 --- a/packages/plugin-form-builder/src/collections/Forms/DynamicPriceSelector.tsx +++ b/packages/plugin-form-builder/src/collections/Forms/DynamicPriceSelector.tsx @@ -49,8 +49,10 @@ export const DynamicPriceSelector: React.FC<TextFieldType> = (props) => { return <Text {...props} /> } - const localLabels = typeof label === 'object' ? label : { [locale]: label } - const labelValue = localLabels[locale] || localLabels['en'] || '' + const localeCode = typeof locale === 'object' && 'code' in locale ? locale.code : locale + + const localLabels = typeof label === 'object' ? label : { [localeCode]: label } + const labelValue = localLabels[localeCode] || localLabels['en'] || '' if (valueType === 'valueOfField' && !isNumberField) { return ( diff --git a/packages/plugin-form-builder/src/utilities/lexical/converters/heading.ts b/packages/plugin-form-builder/src/utilities/lexical/converters/heading.ts new file mode 100644 index 00000000000..15c280b62ea --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/converters/heading.ts @@ -0,0 +1,19 @@ +import type { HTMLConverter } from '../types' + +import { convertLexicalNodesToHTML } from '../serializeLexical' + +export const HeadingHTMLConverter: HTMLConverter<any> = { + async converter({ converters, node, parent }) { + const childrenText = await convertLexicalNodesToHTML({ + converters, + lexicalNodes: node.children, + parent: { + ...node, + parent, + }, + }) + + return '<' + node?.tag + '>' + childrenText + '</' + node?.tag + '>' + }, + nodeTypes: ['heading'], +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/converters/linebreak.ts b/packages/plugin-form-builder/src/utilities/lexical/converters/linebreak.ts new file mode 100644 index 00000000000..300ae670449 --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/converters/linebreak.ts @@ -0,0 +1,8 @@ +import type { HTMLConverter } from '../types' + +export const LinebreakHTMLConverter: HTMLConverter<any> = { + converter() { + return `<br>` + }, + nodeTypes: ['linebreak'], +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/converters/link.ts b/packages/plugin-form-builder/src/utilities/lexical/converters/link.ts new file mode 100644 index 00000000000..d84c30a33ae --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/converters/link.ts @@ -0,0 +1,24 @@ +import type { HTMLConverter } from '../types' + +import { convertLexicalNodesToHTML } from '../serializeLexical' + +export const LinkHTMLConverter: HTMLConverter<any> = { + async converter({ converters, node, parent }) { + const childrenText = await convertLexicalNodesToHTML({ + converters, + lexicalNodes: node.children, + parent: { + ...node, + parent, + }, + }) + + const rel: string = node.fields.newTab ? ' rel="noopener noreferrer"' : '' + + const href: string = + node.fields.linkType === 'custom' ? node.fields.url : node.fields.doc?.value?.id + + return `<a href="${href}"${rel}>${childrenText}</a>` + }, + nodeTypes: ['link'], +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/converters/list.ts b/packages/plugin-form-builder/src/utilities/lexical/converters/list.ts new file mode 100644 index 00000000000..224d1dc3360 --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/converters/list.ts @@ -0,0 +1,49 @@ +import type { HTMLConverter } from '../types' + +import { convertLexicalNodesToHTML } from '../serializeLexical' + +export const ListHTMLConverter: HTMLConverter<any> = { + converter: async ({ converters, node, parent }) => { + const childrenText = await convertLexicalNodesToHTML({ + converters, + lexicalNodes: node.children, + parent: { + ...node, + parent, + }, + }) + + return `<${node?.tag} class="${node?.listType}">${childrenText}</${node?.tag}>` + }, + nodeTypes: ['list'], +} + +export const ListItemHTMLConverter: HTMLConverter<any> = { + converter: async ({ converters, node, parent }) => { + const childrenText = await convertLexicalNodesToHTML({ + converters, + lexicalNodes: node.children, + parent: { + ...node, + parent, + }, + }) + + if ('listType' in parent && parent?.listType === 'check') { + return `<li aria-checked=${node.checked ? 'true' : 'false'} class="${ + 'list-item-checkbox' + node.checked + ? 'list-item-checkbox-checked' + : 'list-item-checkbox-unchecked' + }" + role="checkbox" + tabIndex=${-1} + value=${node?.value} + > + {serializedChildren} + </li>` + } else { + return `<li value=${node?.value}>${childrenText}</li>` + } + }, + nodeTypes: ['listitem'], +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/converters/paragraph.ts b/packages/plugin-form-builder/src/utilities/lexical/converters/paragraph.ts new file mode 100644 index 00000000000..a4e7d4e767b --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/converters/paragraph.ts @@ -0,0 +1,18 @@ +import type { HTMLConverter } from '../types' + +import { convertLexicalNodesToHTML } from '../serializeLexical' + +export const ParagraphHTMLConverter: HTMLConverter<any> = { + async converter({ converters, node, parent }) { + const childrenText = await convertLexicalNodesToHTML({ + converters, + lexicalNodes: node.children, + parent: { + ...node, + parent, + }, + }) + return `<p>${childrenText}</p>` + }, + nodeTypes: ['paragraph'], +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/converters/quote.ts b/packages/plugin-form-builder/src/utilities/lexical/converters/quote.ts new file mode 100644 index 00000000000..890ad831262 --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/converters/quote.ts @@ -0,0 +1,19 @@ +import type { HTMLConverter } from '../types' + +import { convertLexicalNodesToHTML } from '../serializeLexical' + +export const QuoteHTMLConverter: HTMLConverter<any> = { + async converter({ converters, node, parent }) { + const childrenText = await convertLexicalNodesToHTML({ + converters, + lexicalNodes: node.children, + parent: { + ...node, + parent, + }, + }) + + return `<blockquote>${childrenText}</blockquote>` + }, + nodeTypes: ['quote'], +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/converters/text.ts b/packages/plugin-form-builder/src/utilities/lexical/converters/text.ts new file mode 100644 index 00000000000..378ab65dabc --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/converters/text.ts @@ -0,0 +1,34 @@ +import type { HTMLConverter } from '../types' + +import { NodeFormat } from '../nodeFormat' + +export const TextHTMLConverter: HTMLConverter<any> = { + converter({ node }) { + let text = node.text + + if (node.format & NodeFormat.IS_BOLD) { + text = `<strong>${text}</strong>` + } + if (node.format & NodeFormat.IS_ITALIC) { + text = `<em>${text}</em>` + } + if (node.format & NodeFormat.IS_STRIKETHROUGH) { + text = `<span style="text-decoration: line-through">${text}</span>` + } + if (node.format & NodeFormat.IS_UNDERLINE) { + text = `<span style="text-decoration: underline">${text}</span>` + } + if (node.format & NodeFormat.IS_CODE) { + text = `<code>${text}</code>` + } + if (node.format & NodeFormat.IS_SUBSCRIPT) { + text = `<sub>${text}</sub>` + } + if (node.format & NodeFormat.IS_SUPERSCRIPT) { + text = `<sup>${text}</sup>` + } + + return text + }, + nodeTypes: ['text'], +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/defaultConverters.ts b/packages/plugin-form-builder/src/utilities/lexical/defaultConverters.ts new file mode 100644 index 00000000000..399a9544c4a --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/defaultConverters.ts @@ -0,0 +1,20 @@ +import type { HTMLConverter } from './types' + +import { HeadingHTMLConverter } from './converters/heading' +import { LinebreakHTMLConverter } from './converters/linebreak' +import { LinkHTMLConverter } from './converters/link' +import { ListHTMLConverter, ListItemHTMLConverter } from './converters/list' +import { ParagraphHTMLConverter } from './converters/paragraph' +import { QuoteHTMLConverter } from './converters/quote' +import { TextHTMLConverter } from './converters/text' + +export const defaultHTMLConverters: HTMLConverter[] = [ + ParagraphHTMLConverter, + TextHTMLConverter, + LinebreakHTMLConverter, + LinkHTMLConverter, + HeadingHTMLConverter, + QuoteHTMLConverter, + ListHTMLConverter, + ListItemHTMLConverter, +] diff --git a/packages/plugin-form-builder/src/utilities/lexical/nodeFormat.ts b/packages/plugin-form-builder/src/utilities/lexical/nodeFormat.ts new file mode 100644 index 00000000000..57070314793 --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/nodeFormat.ts @@ -0,0 +1,113 @@ +/* eslint-disable perfectionist/sort-objects */ +/* eslint-disable regexp/no-obscure-range */ +/* eslint-disable @typescript-eslint/no-redundant-type-constituents */ +//This copy-and-pasted from lexical here: https://github.com/facebook/lexical/blob/c2ceee223f46543d12c574e62155e619f9a18a5d/packages/lexical/src/LexicalConstants.ts + +// DOM +export const NodeFormat = { + DOM_ELEMENT_TYPE: 1, + DOM_TEXT_TYPE: 3, + // Reconciling + NO_DIRTY_NODES: 0, + HAS_DIRTY_NODES: 1, + FULL_RECONCILE: 2, + // Text node modes + IS_NORMAL: 0, + IS_TOKEN: 1, + IS_SEGMENTED: 2, + IS_INERT: 3, + // Text node formatting + IS_BOLD: 1, + IS_ITALIC: 1 << 1, + IS_STRIKETHROUGH: 1 << 2, + IS_UNDERLINE: 1 << 3, + IS_CODE: 1 << 4, + IS_SUBSCRIPT: 1 << 5, + IS_SUPERSCRIPT: 1 << 6, + IS_HIGHLIGHT: 1 << 7, + // Text node details + IS_DIRECTIONLESS: 1, + IS_UNMERGEABLE: 1 << 1, + // Element node formatting + IS_ALIGN_LEFT: 1, + IS_ALIGN_CENTER: 2, + IS_ALIGN_RIGHT: 3, + IS_ALIGN_JUSTIFY: 4, + IS_ALIGN_START: 5, + IS_ALIGN_END: 6, +} as const + +export const IS_ALL_FORMATTING = + NodeFormat.IS_BOLD | + NodeFormat.IS_ITALIC | + NodeFormat.IS_STRIKETHROUGH | + NodeFormat.IS_UNDERLINE | + NodeFormat.IS_CODE | + NodeFormat.IS_SUBSCRIPT | + NodeFormat.IS_SUPERSCRIPT | + NodeFormat.IS_HIGHLIGHT + +// Reconciliation +export const NON_BREAKING_SPACE = '\u00A0' + +export const DOUBLE_LINE_BREAK = '\n\n' + +// For FF, we need to use a non-breaking space, or it gets composition +// in a stuck state. + +const RTL = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC' +const LTR = + 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6' + + '\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C' + + '\uFE00-\uFE6F\uFEFD-\uFFFF' + +// eslint-disable-next-line no-misleading-character-class +export const RTL_REGEX = new RegExp('^[^' + LTR + ']*[' + RTL + ']') +// eslint-disable-next-line no-misleading-character-class +export const LTR_REGEX = new RegExp('^[^' + RTL + ']*[' + LTR + ']') + +export const TEXT_TYPE_TO_FORMAT: Record<any | string, number> = { + bold: NodeFormat.IS_BOLD, + code: NodeFormat.IS_CODE, + highlight: NodeFormat.IS_HIGHLIGHT, + italic: NodeFormat.IS_ITALIC, + strikethrough: NodeFormat.IS_STRIKETHROUGH, + subscript: NodeFormat.IS_SUBSCRIPT, + superscript: NodeFormat.IS_SUPERSCRIPT, + underline: NodeFormat.IS_UNDERLINE, +} + +export const DETAIL_TYPE_TO_DETAIL: Record<any | string, number> = { + directionless: NodeFormat.IS_DIRECTIONLESS, + unmergeable: NodeFormat.IS_UNMERGEABLE, +} + +export const ELEMENT_TYPE_TO_FORMAT: Record<Exclude<any, ''>, number> = { + center: NodeFormat.IS_ALIGN_CENTER, + end: NodeFormat.IS_ALIGN_END, + justify: NodeFormat.IS_ALIGN_JUSTIFY, + left: NodeFormat.IS_ALIGN_LEFT, + right: NodeFormat.IS_ALIGN_RIGHT, + start: NodeFormat.IS_ALIGN_START, +} + +export const ELEMENT_FORMAT_TO_TYPE: Record<number, any> = { + [NodeFormat.IS_ALIGN_CENTER]: 'center', + [NodeFormat.IS_ALIGN_END]: 'end', + [NodeFormat.IS_ALIGN_JUSTIFY]: 'justify', + [NodeFormat.IS_ALIGN_LEFT]: 'left', + [NodeFormat.IS_ALIGN_RIGHT]: 'right', + [NodeFormat.IS_ALIGN_START]: 'start', +} + +export const TEXT_MODE_TO_TYPE: Record<any, 0 | 1 | 2> = { + normal: NodeFormat.IS_NORMAL, + segmented: NodeFormat.IS_SEGMENTED, + token: NodeFormat.IS_TOKEN, +} + +export const TEXT_TYPE_TO_MODE: Record<number, any> = { + [NodeFormat.IS_NORMAL]: 'normal', + [NodeFormat.IS_SEGMENTED]: 'segmented', + [NodeFormat.IS_TOKEN]: 'token', +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/serializeLexical.ts b/packages/plugin-form-builder/src/utilities/lexical/serializeLexical.ts new file mode 100644 index 00000000000..9b3f1c99c01 --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/serializeLexical.ts @@ -0,0 +1,50 @@ +import type { HTMLConverter, SerializedLexicalNodeWithParent } from './types' + +import { defaultHTMLConverters } from './defaultConverters' + +export async function serializeLexical(data?: any, submissionData?: any): Promise<string> { + const converters: HTMLConverter[] = defaultHTMLConverters + + if (data?.root?.children?.length) { + return await convertLexicalNodesToHTML({ + converters, + lexicalNodes: data?.root?.children, + parent: data?.root, + }) + } + return '' +} + +export async function convertLexicalNodesToHTML({ + converters, + lexicalNodes, + parent, +}: { + converters: HTMLConverter[] + lexicalNodes: any[] + parent: SerializedLexicalNodeWithParent +}): Promise<string> { + const unknownConverter = converters.find((converter) => converter.nodeTypes.includes('unknown')) + + const htmlArray = await Promise.all( + lexicalNodes.map(async (node, i) => { + const converterForNode = converters.find((converter) => + converter.nodeTypes.includes(node.type), + ) + if (!converterForNode) { + if (unknownConverter) { + return unknownConverter.converter({ childIndex: i, converters, node, parent }) + } + return '<span>unknown node</span>' + } + return converterForNode.converter({ + childIndex: i, + converters, + node, + parent, + }) + }), + ) + + return htmlArray.join('') || '' +} diff --git a/packages/plugin-form-builder/src/utilities/lexical/types.ts b/packages/plugin-form-builder/src/utilities/lexical/types.ts new file mode 100644 index 00000000000..515c781f083 --- /dev/null +++ b/packages/plugin-form-builder/src/utilities/lexical/types.ts @@ -0,0 +1,18 @@ +export type HTMLConverter<T = any> = { + converter: ({ + childIndex, + converters, + node, + parent, + }: { + childIndex: number + converters: HTMLConverter[] + node: T + parent: SerializedLexicalNodeWithParent + }) => Promise<string> | string + nodeTypes: string[] +} + +export type SerializedLexicalNodeWithParent = any & { + parent?: any +} diff --git a/packages/plugin-form-builder/src/utilities/serializeRichText.ts b/packages/plugin-form-builder/src/utilities/slate/serializeSlate.ts similarity index 57% rename from packages/plugin-form-builder/src/utilities/serializeRichText.ts rename to packages/plugin-form-builder/src/utilities/slate/serializeSlate.ts index 7b254c82b37..b4192ad486d 100644 --- a/packages/plugin-form-builder/src/utilities/serializeRichText.ts +++ b/packages/plugin-form-builder/src/utilities/slate/serializeSlate.ts @@ -1,6 +1,6 @@ import escapeHTML from 'escape-html' -import { replaceDoubleCurlys } from './replaceDoubleCurlys' +import { replaceDoubleCurlys } from '../replaceDoubleCurlys' interface Node { bold?: boolean @@ -16,7 +16,7 @@ const isTextNode = (node: Node): node is Node & { text: string } => { return 'text' in node } -export const serialize = (children?: Node[], submissionData?: any): string | undefined => +export const serializeSlate = (children?: Node[], submissionData?: any): string | undefined => children ?.map((node: Node) => { if (isTextNode(node)) { @@ -57,56 +57,80 @@ export const serialize = (children?: Node[], submissionData?: any): string | und case 'h1': return ` <h1> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </h1> + ` + case 'h2': + return ` + <h2> + ${serializeSlate(node.children, submissionData)} + </h2> + ` + case 'h3': + return ` + <h3> + ${serializeSlate(node.children, submissionData)} + </h3> + ` + case 'h4': + return ` + <h4> + ${serializeSlate(node.children, submissionData)} + </h4> + ` + case 'h5': + return ` + <h5> + ${serializeSlate(node.children, submissionData)} + </h5> ` case 'h6': return ` <h6> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </h6> ` case 'quote': return ` <blockquote> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </blockquote> ` case 'ul': return ` <ul> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </ul> ` case 'ol': return ` <ol> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </ol> ` case 'li': return ` <li> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </li> ` case 'indent': return ` <p style="padding-left: 20px"> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </p> ` case 'link': return ` <a href={${escapeHTML(node.url)}}> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </a> ` default: return ` <p> - ${serialize(node.children, submissionData)} + ${serializeSlate(node.children, submissionData)} </p> ` } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3cb955bc189..14bad6a3ae4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1151,14 +1151,14 @@ importers: specifier: workspace:* version: link:../eslint-config-payload '@types/escape-html': - specifier: ^1.0.1 - version: 1.0.3 + specifier: ^1.0.4 + version: 1.0.4 '@types/express': - specifier: ^4.17.9 - version: 4.17.17 + specifier: ^4.17.21 + version: 4.17.21 '@types/react': - specifier: 18.0.21 - version: 18.0.21 + specifier: 18.2.15 + version: 18.2.15 copyfiles: specifier: ^2.4.1 version: 2.4.1 @@ -1166,17 +1166,17 @@ importers: specifier: ^7.0.3 version: 7.0.3 nodemon: - specifier: ^2.0.6 - version: 2.0.22 + specifier: ^3.0.2 + version: 3.0.2 payload: - specifier: ^1.3.0 - version: 1.15.8(@types/[email protected])([email protected]) + specifier: workspace:* + version: link:../payload react: specifier: ^18.0.0 version: 18.2.0 ts-node: - specifier: ^9.1.1 - version: 9.1.1([email protected]) + specifier: 10.9.1 + version: 10.9.1(@swc/[email protected])(@types/[email protected])([email protected]) packages/plugin-nested-docs: devDependencies: @@ -5754,7 +5754,7 @@ packages: /@types/[email protected]: resolution: {integrity: sha512-P63Zd/JUGq+PdrM1lv0Wv5SBYeA2+CORvbrXbngriYY0jzLUWfQMQQxOhjONEz/wlHOAxOdY7CY65rgQdTjq2w==} dependencies: - '@types/node': 16.18.58 + '@types/node': 20.6.2 dev: true /@types/[email protected]: @@ -5810,8 +5810,8 @@ packages: resolution: {integrity: sha512-E9ZPeZwh81/gDPVH4XpvcS4ewH/Ub4XJeM5xYAUP0BexGORIyCRYzSivlGOuGbVc4MH3//+z3h4CbrnMZMeUdA==} dev: true - /@types/[email protected]: - resolution: {integrity: sha512-QbNxKa2IX2y/9eGiy4w8rrwk//ERHXA6zwYVRA3+ayA/D3pkz+/bLL4b5uSLA0L0kPuNX1Jbv9HyPzv9T4zbJQ==} + /@types/[email protected]: + resolution: {integrity: sha512-qZ72SFTgUAZ5a7Tj6kf2SHLetiH5S6f8G5frB2SPQ3EyF02kxdyBFf4Tz4banE3xCgGnKgWLt//a6VuYHKYJTg==} dev: true /@types/[email protected]: @@ -5860,6 +5860,15 @@ packages: '@types/serve-static': 1.15.2 dev: true + /@types/[email protected]: + resolution: {integrity: sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==} + dependencies: + '@types/body-parser': 1.19.2 + '@types/express-serve-static-core': 4.17.35 + '@types/qs': 6.9.7 + '@types/serve-static': 1.15.2 + dev: true + /@types/[email protected]: resolution: {integrity: sha512-y1sAp2P5sCfqaUDWS7TSB/xemrHGpw9dsjiLE4lC+7bxDC8024Rzl7EdgDVM6wDpJ26H1tWuHRwxLFz1MD95Uw==} dependencies: @@ -6150,7 +6159,7 @@ packages: /@types/[email protected]: resolution: {integrity: sha512-o5D19Jy2XPFoX2rKApykY15et3Apgax00RRLf0RUotPDUsYrQa7x4howLYr9El2mlUApHmCMv5CZ1IXqKFQ2+g==} dependencies: - '@types/express': 4.17.17 + '@types/express': 4.17.21 '@types/passport': 1.0.12 dev: true @@ -6294,7 +6303,7 @@ packages: resolution: {integrity: sha512-Cwo8LE/0rnvX7kIIa3QHCkcuF21c05Ayb0ZfxPiv0W8VRiZiNW/WuRupHKpqqGVGf7SUA44QSOUKaEd9lIrd/Q==} dependencies: '@types/mime': 1.3.2 - '@types/node': 16.18.58 + '@types/node': 20.6.2 dev: true /@types/[email protected]: @@ -6302,7 +6311,7 @@ packages: dependencies: '@types/http-errors': 2.0.2 '@types/mime': 2.0.3 - '@types/node': 16.18.58 + '@types/node': 20.6.2 dev: true /@types/[email protected]: @@ -10803,7 +10812,7 @@ packages: /[email protected]: resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==} dependencies: - get-intrinsic: 1.2.1 + get-intrinsic: 1.2.2 /[email protected]: resolution: {integrity: sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==} @@ -10988,7 +10997,7 @@ packages: /[email protected]: resolution: {integrity: sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==} dependencies: - get-intrinsic: 1.2.1 + get-intrinsic: 1.2.2 /[email protected]: resolution: {integrity: sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==} @@ -16533,8 +16542,8 @@ packages: /[email protected]: resolution: {integrity: sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==} dependencies: - call-bind: 1.0.2 - get-intrinsic: 1.2.1 + call-bind: 1.0.5 + get-intrinsic: 1.2.2 object-inspect: 1.12.3 /[email protected]: @@ -17480,6 +17489,38 @@ packages: yargs-parser: 21.1.1 dev: true + /[email protected](@swc/[email protected])(@types/[email protected])([email protected]): + resolution: {integrity: sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==} + hasBin: true + peerDependencies: + '@swc/core': '>=1.2.50' + '@swc/wasm': '>=1.2.50' + '@types/node': '*' + typescript: '>=2.7' + peerDependenciesMeta: + '@swc/core': + optional: true + '@swc/wasm': + optional: true + dependencies: + '@cspotcode/source-map-support': 0.8.1 + '@swc/core': 1.3.76 + '@tsconfig/node10': 1.0.9 + '@tsconfig/node12': 1.0.11 + '@tsconfig/node14': 1.0.3 + '@tsconfig/node16': 1.0.4 + '@types/node': 16.18.58 + acorn: 8.10.0 + acorn-walk: 8.2.0 + arg: 4.1.3 + create-require: 1.1.1 + diff: 4.0.2 + make-error: 1.3.6 + typescript: 5.2.2 + v8-compile-cache-lib: 3.0.1 + yn: 3.1.1 + dev: true + /[email protected](@swc/[email protected])(@types/[email protected])([email protected]): resolution: {integrity: sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==} hasBin: true diff --git a/tsconfig.json b/tsconfig.json index 1f6831d328b..2fcd0d6a095 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -38,6 +38,9 @@ { "path": "./packages/richtext-lexical" }, { "path": "./packages/payload" }, { "path": "./packages/plugin-nested-docs" }, + { "path": "./packages/plugin-form-builder" }, + { "path": "./packages/plugin-cloud-storage" }, + { "path": "./packages/plugin-cloud" }, { "path": "./packages/live-preview" }, { "path": "./packages/live-preview-react" } ]
b1734b0d38ef653fb48f4c362d8e50bea76a3964
2025-02-14 19:36:46
Sasha
fix(ui): hide array field "add" button if `admin.readOnly: true` is set (#11184)
false
hide array field "add" button if `admin.readOnly: true` is set (#11184)
fix
diff --git a/packages/ui/src/fields/Array/index.tsx b/packages/ui/src/fields/Array/index.tsx index f4c0eaa228a..6ad79c062a6 100644 --- a/packages/ui/src/fields/Array/index.tsx +++ b/packages/ui/src/fields/Array/index.tsx @@ -336,11 +336,10 @@ export const ArrayFieldComponent: ArrayFieldClientComponent = (props) => { )} </DraggableSortable> )} - {!hasMaxRows && ( + {!hasMaxRows && !readOnly && ( <Button buttonStyle="icon-label" className={`${baseClass}__add-row`} - disabled={readOnly} icon="plus" iconPosition="left" iconStyle="with-border" diff --git a/test/fields/collections/Array/e2e.spec.ts b/test/fields/collections/Array/e2e.spec.ts index 2db8a5ebd80..01572933c07 100644 --- a/test/fields/collections/Array/e2e.spec.ts +++ b/test/fields/collections/Array/e2e.spec.ts @@ -71,6 +71,7 @@ describe('Array', () => { await page.goto(url.create) const field = page.locator('#field-readOnly__0__text') await expect(field).toBeDisabled() + await expect(page.locator('#field-readOnly .array-field__add-row')).toBeHidden() }) test('should have defaultValue', async () => {
a42e84bbb2cfeab3e423ba66a089cd6cf3fa540e
2023-10-11 00:40:22
Elliot DeNolf
chore(eslint): prepare config for publishing
false
prepare config for publishing
chore
diff --git a/packages/eslint-config-payload/eslint-config/configs/jest/index.cjs b/packages/eslint-config-payload/eslint-config/configs/jest/index.js similarity index 55% rename from packages/eslint-config-payload/eslint-config/configs/jest/index.cjs rename to packages/eslint-config-payload/eslint-config/configs/jest/index.js index 2dbaeaf296e..6c2adcc5ad3 100644 --- a/packages/eslint-config-payload/eslint-config/configs/jest/index.cjs +++ b/packages/eslint-config-payload/eslint-config/configs/jest/index.js @@ -3,6 +3,6 @@ module.exports = { jest: true, }, plugins: ['jest', 'jest-dom'], - extends: ['./rules/jest.cjs', './rules/jest-dom.cjs'].map(require.resolve), + extends: ['./rules/jest.js', './rules/jest-dom.js'].map(require.resolve), rules: {}, } diff --git a/packages/eslint-config-payload/eslint-config/configs/jest/rules/jest-dom.cjs b/packages/eslint-config-payload/eslint-config/configs/jest/rules/jest-dom.js similarity index 100% rename from packages/eslint-config-payload/eslint-config/configs/jest/rules/jest-dom.cjs rename to packages/eslint-config-payload/eslint-config/configs/jest/rules/jest-dom.js diff --git a/packages/eslint-config-payload/eslint-config/configs/jest/rules/jest.cjs b/packages/eslint-config-payload/eslint-config/configs/jest/rules/jest.js similarity index 100% rename from packages/eslint-config-payload/eslint-config/configs/jest/rules/jest.cjs rename to packages/eslint-config-payload/eslint-config/configs/jest/rules/jest.js diff --git a/packages/eslint-config-payload/eslint-config/configs/react/index.cjs b/packages/eslint-config-payload/eslint-config/configs/react/index.js similarity index 75% rename from packages/eslint-config-payload/eslint-config/configs/react/index.cjs rename to packages/eslint-config-payload/eslint-config/configs/react/index.js index 3db9df807c5..9dca50e92b5 100644 --- a/packages/eslint-config-payload/eslint-config/configs/react/index.cjs +++ b/packages/eslint-config-payload/eslint-config/configs/react/index.js @@ -13,6 +13,6 @@ module.exports = { jsx: true, }, }, - extends: ['./rules/react-a11y.cjs', './rules/react.cjs'].map(require.resolve), + extends: ['./rules/react-a11y.js', './rules/react.js'].map(require.resolve), rules: {}, } diff --git a/packages/eslint-config-payload/eslint-config/configs/react/rules/react-a11y.cjs b/packages/eslint-config-payload/eslint-config/configs/react/rules/react-a11y.js similarity index 100% rename from packages/eslint-config-payload/eslint-config/configs/react/rules/react-a11y.cjs rename to packages/eslint-config-payload/eslint-config/configs/react/rules/react-a11y.js diff --git a/packages/eslint-config-payload/eslint-config/configs/react/rules/react.cjs b/packages/eslint-config-payload/eslint-config/configs/react/rules/react.js similarity index 100% rename from packages/eslint-config-payload/eslint-config/configs/react/rules/react.cjs rename to packages/eslint-config-payload/eslint-config/configs/react/rules/react.js diff --git a/packages/eslint-config-payload/eslint-config/index.cjs b/packages/eslint-config-payload/eslint-config/index.js similarity index 96% rename from packages/eslint-config-payload/eslint-config/index.cjs rename to packages/eslint-config-payload/eslint-config/index.js index 2f739796ff4..58c298519e2 100644 --- a/packages/eslint-config-payload/eslint-config/index.cjs +++ b/packages/eslint-config-payload/eslint-config/index.js @@ -11,8 +11,8 @@ module.exports = { 'plugin:regexp/recommended', 'plugin:react/recommended', 'plugin:react-hooks/recommended', - './configs/jest/index.cjs', - './configs/react/index.cjs', + './configs/jest/index.js', + './configs/react/index.js', 'prettier', ], parser: '@typescript-eslint/parser', diff --git a/packages/eslint-config-payload/index.js b/packages/eslint-config-payload/index.js index 55f3d9d2e8a..c616e631fce 100644 --- a/packages/eslint-config-payload/index.js +++ b/packages/eslint-config-payload/index.js @@ -1,4 +1,4 @@ module.exports = { root: true, - extends: ['./eslint-config/index.cjs'], + extends: ['./eslint-config/index.js'], } diff --git a/packages/eslint-config-payload/package.json b/packages/eslint-config-payload/package.json index cb00f213384..98cd5b0474a 100644 --- a/packages/eslint-config-payload/package.json +++ b/packages/eslint-config-payload/package.json @@ -1,7 +1,6 @@ { "name": "@payloadcms/eslint-config", "version": "0.0.1", - "private": true, "description": "Payload styles for ESLint and Prettier", "license": "MIT", "author": {
71a15b5e6d1a7bfd2f7a22efaba571607765ab7b
2021-03-14 00:25:01
James
docs: clarity around afterRead S3 hook
false
clarity around afterRead S3 hook
docs
diff --git a/docs/production/deployment.mdx b/docs/production/deployment.mdx index bd2b2cd9d01..3d7eb6f1217 100644 --- a/docs/production/deployment.mdx +++ b/docs/production/deployment.mdx @@ -108,7 +108,7 @@ But, if you do, and you still want to use an ephemeral filesystem provider, you **To automatically send uploaded files to S3 or similar, you could:** - Write an asynchronous `beforeChange` hook for all Collections that support Uploads, which takes any uploaded `file` from the Express `req` and sends it to an S3 bucket -- Write an `afterRead` hook for the `filename` field that automatically adjusts the `filename` stored to add its full S3 URL +- Write an `afterRead` hook to save a `s3URL` field that automatically takes the `filename` stored and formats a full S3 URL - Write an `afterDelete` hook that automatically deletes files from the S3 bucket With the above configuration, deploying to Heroku or similar becomes no problem.
e796ff233027cc044d551b48140bfbbc4ccd9132
2024-11-19 02:01:45
Elliot DeNolf
chore(templates): add back payload cloud to plugins array
false
add back payload cloud to plugins array
chore
diff --git a/templates/blank/src/payload.config.ts b/templates/blank/src/payload.config.ts index da48011c9fb..19b9a86a931 100644 --- a/templates/blank/src/payload.config.ts +++ b/templates/blank/src/payload.config.ts @@ -1,5 +1,6 @@ // storage-adapter-import-placeholder import { mongooseAdapter } from '@payloadcms/db-mongodb' // database-adapter-import +import { payloadCloudPlugin } from '@payloadcms/payload-cloud' import { lexicalEditor } from '@payloadcms/richtext-lexical' import path from 'path' import { buildConfig } from 'payload' @@ -32,6 +33,7 @@ export default buildConfig({ // database-adapter-config-end sharp, plugins: [ + payloadCloudPlugin(), // storage-adapter-placeholder ], })
1123909960bcfd7168ccb2db014fde77f946bc6c
2023-05-09 23:09:12
Elliot DeNolf
fix: revert template serverURL back to localhost
false
revert template serverURL back to localhost
fix
diff --git a/src/templates/blank/src/payload.config.ts b/src/templates/blank/src/payload.config.ts index 8c230a0c375..f7ec15072a1 100644 --- a/src/templates/blank/src/payload.config.ts +++ b/src/templates/blank/src/payload.config.ts @@ -4,7 +4,7 @@ import path from 'path'; import Users from './collections/Users'; export default buildConfig({ - serverURL: 'http://127.0.0.1:3000', + serverURL: 'http://localhost:3000', admin: { user: Users.slug, }, diff --git a/src/templates/blog/src/payload.config.ts b/src/templates/blog/src/payload.config.ts index 49ffb165e42..4b53ccfe5c9 100644 --- a/src/templates/blog/src/payload.config.ts +++ b/src/templates/blog/src/payload.config.ts @@ -7,7 +7,7 @@ import Users from './collections/Users'; import Media from './collections/Media'; export default buildConfig({ - serverURL: 'http://127.0.0.1:3000', + serverURL: 'http://localhost:3000', admin: { user: Users.slug, }, diff --git a/src/templates/todo/src/payload.config.ts b/src/templates/todo/src/payload.config.ts index ebd274ed10b..4e187be52bd 100644 --- a/src/templates/todo/src/payload.config.ts +++ b/src/templates/todo/src/payload.config.ts @@ -4,7 +4,7 @@ import TodoLists from './collections/TodoLists'; import Users from './collections/Users'; export default buildConfig({ - serverURL: 'http://127.0.0.1:3000', + serverURL: 'http://localhost:3000', admin: { user: Users.slug, },