From 142616e6adef79f45e661436421dd9968d011e28 Mon Sep 17 00:00:00 2001 From: Elliot DeNolf Date: Thu, 29 Aug 2024 10:15:36 -0400 Subject: [PATCH] chore(eslint): curly [skip-lint] (#7959) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Now enforcing curly brackets on all if statements. Includes auto-fixer. ```ts // ❌ Bad if (foo) foo++; // ✅ Good if (foo) { foo++; } ``` Note: this did not lint the `drizzle` package or any `db-*` packages. This will be done in the future. --- eslint.config.js | 1 + .../create-payload-app/src/lib/init-next.ts | 4 +- .../src/lib/parse-project-name.ts | 12 ++- .../src/lib/parse-template.ts | 4 +- .../create-payload-app/src/lib/select-db.ts | 8 +- .../src/lib/update-payload-in-project.ts | 4 +- .../src/lib/write-env-file.ts | 4 +- packages/email-nodemailer/src/index.ts | 4 +- packages/eslint-config/index.mjs | 1 + .../src/resolvers/auth/resetPassword.ts | 8 +- .../graphql/src/resolvers/auth/verifyEmail.ts | 8 +- .../src/resolvers/collections/delete.ts | 8 +- .../graphql/src/resolvers/collections/find.ts | 8 +- .../src/resolvers/collections/findByID.ts | 8 +- .../src/resolvers/collections/findVersions.ts | 8 +- .../src/resolvers/collections/update.ts | 8 +- .../graphql/src/resolvers/globals/findOne.ts | 8 +- .../src/resolvers/globals/findVersionByID.ts | 8 +- .../graphql/src/resolvers/globals/update.ts | 8 +- .../src/schema/buildMutationInputType.ts | 32 ++++++-- .../graphql/src/schema/buildObjectType.ts | 16 +++- .../graphql/src/schema/buildPoliciesType.ts | 4 +- .../graphql/src/schema/initCollections.ts | 4 +- packages/graphql/src/schema/initGlobals.ts | 4 +- packages/graphql/src/schema/withOperators.ts | 4 +- packages/next/babel.config.cjs | 5 +- .../elements/DocumentHeader/Tabs/index.tsx | 10 ++- .../Tabs/tabs/VersionsPill/index.tsx | 3 +- .../src/elements/LeaveWithoutSaving/index.tsx | 7 +- .../LeaveWithoutSaving/usePreventLeave.tsx | 4 +- .../next/src/fetchAPI-multipart/handlers.ts | 4 +- .../src/fetchAPI-multipart/processNested.ts | 8 +- .../src/fetchAPI-multipart/uploadTimer.ts | 4 +- .../next/src/fetchAPI-multipart/utilities.ts | 39 +++++++--- .../src/routes/rest/collections/updateByID.ts | 8 +- .../src/routes/rest/files/checkFileAccess.ts | 4 +- .../next/src/routes/rest/files/getFile.ts | 8 +- .../next/src/routes/rest/globals/update.ts | 8 +- packages/next/src/routes/rest/index.ts | 56 ++++++++++---- .../rest/utilities/sanitizeCollectionID.ts | 8 +- .../src/templates/Default/Wrapper/index.scss | 1 - .../next/src/utilities/addLocalesToRequest.ts | 8 +- .../src/utilities/createPayloadRequest.ts | 12 ++- .../utilities/initPage/handleAuthRedirect.ts | 4 +- packages/next/src/utilities/initPage/index.ts | 4 +- packages/next/src/utilities/timestamp.ts | 4 +- packages/next/src/views/Account/index.tsx | 26 ++++--- .../Edit/Default/SetDocumentStepNav/index.tsx | 4 +- .../next/src/views/Edit/Default/index.tsx | 8 +- .../src/views/LivePreview/Context/index.tsx | 4 +- .../src/views/LivePreview/Device/index.tsx | 7 +- .../LivePreview/Toolbar/SizeInput/index.tsx | 11 ++- .../next/src/views/Login/LoginForm/index.tsx | 8 +- .../src/views/Root/isPathMatchingRoute.ts | 8 +- packages/next/src/views/Verify/index.tsx | 4 +- .../fields/Iterable/index.tsx | 4 +- .../fields/Select/index.tsx | 4 +- .../RenderFieldsToDiff/fields/Text/index.tsx | 12 ++- .../Version/RenderFieldsToDiff/index.tsx | 8 +- .../views/Version/SelectComparison/index.tsx | 4 +- .../src/views/Version/SelectLocales/index.tsx | 4 +- .../views/Versions/cells/CreatedAt/index.tsx | 6 +- packages/payload/src/auth/executeAccess.ts | 8 +- packages/payload/src/auth/getAuthFields.ts | 4 +- packages/payload/src/auth/isLocked.ts | 4 +- packages/payload/src/auth/operations/auth.ts | 4 +- .../src/auth/operations/forgotPassword.ts | 8 +- packages/payload/src/auth/operations/login.ts | 8 +- .../payload/src/auth/operations/logout.ts | 7 +- packages/payload/src/auth/operations/me.ts | 8 +- .../payload/src/auth/operations/refresh.ts | 8 +- .../src/auth/operations/registerFirstUser.ts | 8 +- .../src/auth/operations/resetPassword.ts | 8 +- .../payload/src/auth/operations/unlock.ts | 4 +- .../src/auth/operations/verifyEmail.ts | 11 ++- .../src/auth/strategies/local/authenticate.ts | 4 +- .../src/auth/strategies/local/register.ts | 4 +- .../strategies/local/resetLoginAttempts.ts | 4 +- packages/payload/src/bin/generateTypes.ts | 8 +- packages/payload/src/bin/index.ts | 4 +- .../src/collections/config/sanitize.ts | 16 +++- .../payload/src/collections/dataloader.ts | 4 +- .../src/collections/operations/create.ts | 4 +- .../src/collections/operations/delete.ts | 4 +- .../src/collections/operations/deleteByID.ts | 12 ++- .../src/collections/operations/duplicate.ts | 12 ++- .../src/collections/operations/findByID.ts | 8 +- .../collections/operations/findVersionByID.ts | 12 ++- .../collections/operations/restoreVersion.ts | 8 +- .../src/collections/operations/update.ts | 4 +- .../src/collections/operations/updateByID.ts | 12 ++- packages/payload/src/config/find.ts | 12 ++- packages/payload/src/config/sanitize.ts | 8 +- .../payload/src/database/combineQueries.ts | 12 ++- .../payload/src/database/getLocalizedPaths.ts | 4 +- .../database/migrations/readMigrationFiles.ts | 4 +- .../payload/src/fields/config/sanitize.ts | 16 +++- .../src/fields/hooks/afterRead/index.ts | 4 +- .../src/fields/hooks/afterRead/promise.ts | 8 +- .../hooks/beforeChange/getExistingRowDoc.ts | 8 +- .../src/fields/hooks/beforeChange/promise.ts | 22 ++++-- .../fields/hooks/beforeValidate/promise.ts | 28 +++++-- packages/payload/src/fields/validations.ts | 76 ++++++++++++++----- .../payload/src/globals/config/sanitize.ts | 56 ++++++++++---- .../src/globals/operations/docAccess.ts | 4 +- .../src/globals/operations/findVersionByID.ts | 16 +++- .../src/globals/operations/restoreVersion.ts | 4 +- .../payload/src/globals/operations/update.ts | 4 +- packages/payload/src/index.ts | 12 ++- .../src/preferences/operations/findOne.ts | 4 +- packages/payload/src/uploads/cropImage.ts | 4 +- .../src/uploads/deleteAssociatedFiles.ts | 4 +- .../src/uploads/docWithFilenameExists.ts | 4 +- .../payload/src/uploads/formatFilesize.ts | 4 +- .../payload/src/uploads/generateFileData.ts | 16 +++- packages/payload/src/uploads/getBaseFields.ts | 8 +- .../payload/src/uploads/getExternalFile.ts | 4 +- packages/payload/src/uploads/imageResizer.ts | 44 ++++++++--- .../src/uploads/optionallyAppendMetadata.ts | 4 +- .../src/utilities/configToJSONSchema.ts | 16 +++- .../createArrayFromCommaDelineated.ts | 4 +- .../payload/src/utilities/createLocalReq.ts | 40 +++++++--- .../payload/src/utilities/deepCopyObject.ts | 20 +++-- .../utilities/dependencies/versionUtils.ts | 32 ++++++-- .../src/utilities/getEntityPolicies.ts | 12 ++- .../src/utilities/getObjectDotNotation.ts | 4 +- .../payload/src/utilities/getSiblingData.ts | 4 +- packages/payload/src/utilities/isValidID.ts | 4 +- .../src/utilities/reduceFieldsToValues.ts | 4 +- packages/payload/src/utilities/timestamp.ts | 4 +- .../src/versions/drafts/getQueryDraftsSort.ts | 4 +- packages/payload/src/versions/saveVersion.ts | 21 +++-- .../src/adapters/azure/index.ts | 4 +- .../src/adapters/gcs/index.ts | 4 +- .../src/adapters/s3/index.ts | 4 +- .../src/hooks/afterDelete.ts | 4 +- packages/plugin-cloud-storage/src/plugin.ts | 8 +- packages/plugin-cloud/src/email.ts | 7 +- .../plugin-cloud/src/hooks/uploadCache.ts | 8 +- .../src/collections/FormSubmissions/index.ts | 4 +- .../src/collections/Forms/index.ts | 4 +- .../src/utilities/replaceDoubleCurlys.ts | 4 +- .../src/hooks/resaveChildren.ts | 4 +- .../src/utilities/populateBreadcrumbs.ts | 2 +- .../src/hooks/beforeChange.ts | 4 +- packages/plugin-sentry/src/plugin.ts | 4 +- packages/plugin-sentry/src/startSentry.ts | 4 +- .../MetaDescriptionComponent.tsx | 4 +- .../fields/MetaImage/MetaImageComponent.tsx | 4 +- .../fields/MetaTitle/MetaTitleComponent.tsx | 4 +- .../src/fields/Overview/OverviewComponent.tsx | 6 +- .../src/hooks/createNewInStripe.ts | 23 ++++-- .../src/hooks/deleteFromStripe.ts | 13 +++- .../src/hooks/syncExistingWithStripe.ts | 13 +++- .../src/webhooks/handleCreatedOrUpdated.ts | 43 +++++++---- .../src/webhooks/handleDeleted.ts | 24 ++++-- packages/plugin-stripe/src/webhooks/index.ts | 3 +- packages/richtext-lexical/babel.config.cjs | 5 +- .../features/converters/html/field/index.ts | 3 +- .../client/plugins/TablePlugin/index.scss | 12 ++- .../link/client/plugins/autoLink/index.tsx | 4 +- .../src/features/link/nodes/LinkNode.ts | 2 +- .../shared/ToolbarDropdown/DropDown.tsx | 12 ++- .../features/upload/server/feature.server.ts | 4 +- .../src/lexical/LexicalEditor.tsx | 4 +- .../LexicalMenu.tsx | 4 +- .../utils/doesLineHeightAffectElement.ts | 4 +- .../richtext-lexical/src/lexical/utils/url.ts | 24 ++++-- .../richtext-slate/src/data/validation.ts | 4 +- .../richtext-slate/src/field/RichText.tsx | 8 +- .../src/field/createFeatureMap.ts | 16 +++- .../src/field/elements/isActive.tsx | 4 +- .../elements/isLastSelectedElementEmpty.ts | 4 +- .../src/field/elements/isListActive.ts | 8 +- .../src/field/elements/link/Element/index.tsx | 8 +- .../src/field/elements/toggleList.tsx | 8 +- .../src/generateComponentMap.tsx | 3 +- packages/storage-azure/src/staticHandler.ts | 2 +- .../src/utils/getStorageClient.ts | 4 +- packages/storage-gcs/src/index.ts | 4 +- packages/storage-s3/src/index.ts | 4 +- .../storage-uploadthing/src/staticHandler.ts | 4 +- .../scripts/translateNewKeys/sortKeys.ts | 4 +- .../translations/src/importDateFNSLocale.ts | 4 +- packages/translations/src/utilities/init.ts | 4 +- packages/ui/babel.config.cjs | 5 +- packages/ui/src/elements/Autosave/index.tsx | 7 +- packages/ui/src/elements/Banner/index.tsx | 8 +- .../elements/BulkUpload/ActionsBar/index.scss | 8 +- .../elements/BulkUpload/ActionsBar/index.tsx | 14 +++- .../BulkUpload/AddFilesView/index.scss | 2 +- .../elements/BulkUpload/EditForm/index.tsx | 8 +- .../BulkUpload/FileSidebar/index.scss | 18 ++--- .../BulkUpload/FormsManager/index.tsx | 4 +- packages/ui/src/elements/BulkUpload/index.tsx | 4 +- packages/ui/src/elements/Button/index.tsx | 15 +++- .../ui/src/elements/Collapsible/index.tsx | 4 +- .../ui/src/elements/ColumnSelector/index.tsx | 8 +- .../ui/src/elements/DatePicker/DatePicker.tsx | 20 +++-- .../src/elements/DraggableSortable/index.tsx | 4 +- packages/ui/src/elements/Drawer/index.tsx | 4 +- packages/ui/src/elements/Dropzone/index.scss | 2 +- packages/ui/src/elements/EditUpload/index.tsx | 23 ++++-- packages/ui/src/elements/ErrorPill/index.tsx | 4 +- .../ui/src/elements/FieldSelect/index.tsx | 4 +- .../src/elements/ListDrawer/DrawerContent.tsx | 20 +++-- .../ui/src/elements/ListDrawer/index.scss | 2 +- packages/ui/src/elements/Pagination/index.tsx | 20 +++-- packages/ui/src/elements/PerPage/index.tsx | 4 +- packages/ui/src/elements/Pill/index.tsx | 12 ++- .../src/elements/Popup/PopupTrigger/index.tsx | 4 +- packages/ui/src/elements/Popup/index.tsx | 4 +- .../elements/PreviewButton/usePreviewURL.tsx | 24 ++++-- .../ui/src/elements/PreviewSizes/index.tsx | 20 +++-- .../ui/src/elements/PublishButton/index.tsx | 16 +++- .../ReactSelect/DropdownIndicator/index.tsx | 4 +- .../ui/src/elements/ReactSelect/index.tsx | 4 +- packages/ui/src/elements/SaveButton/index.tsx | 4 +- .../ui/src/elements/SaveDraftButton/index.tsx | 12 ++- .../ui/src/elements/SearchFilter/index.tsx | 4 +- .../ui/src/elements/ShimmerEffect/index.tsx | 4 +- packages/ui/src/elements/SortColumn/index.tsx | 8 +- .../ui/src/elements/SortComplex/index.tsx | 4 +- .../TableColumns/buildColumnState.tsx | 12 ++- .../ui/src/elements/TableColumns/index.tsx | 4 +- packages/ui/src/elements/Tooltip/index.tsx | 8 +- packages/ui/src/elements/Upload/index.scss | 2 +- packages/ui/src/elements/Upload/index.tsx | 4 +- .../WhereBuilder/reduceClientFields.tsx | 4 +- packages/ui/src/fields/Array/index.tsx | 8 +- .../src/fields/Blocks/BlocksDrawer/index.tsx | 8 +- packages/ui/src/fields/Checkbox/index.tsx | 4 +- packages/ui/src/fields/Collapsible/index.tsx | 4 +- packages/ui/src/fields/DateTime/index.tsx | 4 +- packages/ui/src/fields/JSON/index.tsx | 15 +++- packages/ui/src/fields/RadioGroup/index.tsx | 3 +- packages/ui/src/fields/Relationship/index.tsx | 12 ++- .../MultiValueLabel/index.tsx | 4 +- packages/ui/src/fields/Select/index.tsx | 3 +- packages/ui/src/fields/Text/index.tsx | 3 +- packages/ui/src/fields/Textarea/index.tsx | 3 +- .../ui/src/fields/Upload/HasMany/index.tsx | 4 +- .../ui/src/fields/Upload/HasOne/index.scss | 1 - packages/ui/src/fields/Upload/Input.tsx | 8 +- .../Upload/RelationshipContent/index.scss | 2 +- .../src/fields/Upload/UploadCard/index.scss | 6 +- packages/ui/src/fields/Upload/index.scss | 4 +- packages/ui/src/forms/Form/fieldReducer.ts | 8 +- packages/ui/src/forms/Form/index.tsx | 24 ++++-- .../ui/src/forms/Form/mergeServerFormState.ts | 4 +- packages/ui/src/forms/Form/rowHelpers.ts | 12 ++- packages/ui/src/forms/Form/rows.ts | 4 +- packages/ui/src/forms/NullifyField/index.tsx | 12 ++- .../ui/src/forms/RenderFields/RenderField.tsx | 3 +- .../calculateDefaultValues/promise.ts | 8 +- packages/ui/src/graphics/Account/index.tsx | 8 +- packages/ui/src/hooks/useHotkey.ts | 8 +- packages/ui/src/hooks/useIntersect.ts | 4 +- packages/ui/src/providers/Auth/index.tsx | 8 +- .../Config/createClientConfig/collections.tsx | 4 +- .../getCreateMappedComponent.tsx | 4 +- .../ui/src/providers/DocumentInfo/index.tsx | 16 +++- packages/ui/src/providers/ListQuery/index.tsx | 8 +- packages/ui/src/providers/Locale/index.tsx | 4 +- .../ui/src/providers/Preferences/index.tsx | 4 +- packages/ui/src/utilities/buildFormState.ts | 8 +- .../reduceFieldsToValuesWithValidation.ts | 8 +- 267 files changed, 1681 insertions(+), 611 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 3dbd4595e..a28e77400 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -40,6 +40,7 @@ export const rootEslintConfig = [ { ignores: [ ...defaultESLintIgnores, + 'packages/eslint-*/**', 'test/live-preview/next-app', 'packages/**/*.spec.ts', 'templates/**', diff --git a/packages/create-payload-app/src/lib/init-next.ts b/packages/create-payload-app/src/lib/init-next.ts index ed3273909..58e12d3c9 100644 --- a/packages/create-payload-app/src/lib/init-next.ts +++ b/packages/create-payload-app/src/lib/init-next.ts @@ -167,7 +167,9 @@ async function installAndConfigurePayload( } const logDebug = (message: string) => { - if (debug) origDebug(message) + if (debug) { + origDebug(message) + } } if (!fs.existsSync(projectDir)) { 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 e2671599b..a57201549 100644 --- a/packages/create-payload-app/src/lib/parse-project-name.ts +++ b/packages/create-payload-app/src/lib/parse-project-name.ts @@ -4,13 +4,19 @@ import slugify from '@sindresorhus/slugify' import type { CliArgs } from '../types.js' export async function parseProjectName(args: CliArgs): Promise { - if (args['--name']) return slugify(args['--name']) - if (args._[0]) return slugify(args._[0]) + if (args['--name']) { + return slugify(args['--name']) + } + if (args._[0]) { + return slugify(args._[0]) + } const projectName = await p.text({ message: 'Project name?', validate: (value) => { - if (!value) return 'Please enter a project name.' + if (!value) { + return 'Please enter a project name.' + } }, }) if (p.isCancel(projectName)) { diff --git a/packages/create-payload-app/src/lib/parse-template.ts b/packages/create-payload-app/src/lib/parse-template.ts index aa811e910..fa56467dd 100644 --- a/packages/create-payload-app/src/lib/parse-template.ts +++ b/packages/create-payload-app/src/lib/parse-template.ts @@ -9,7 +9,9 @@ export async function parseTemplate( if (args['--template']) { const templateName = args['--template'] const template = validTemplates.find((t) => t.name === templateName) - if (!template) throw new Error('Invalid template given') + if (!template) { + throw new Error('Invalid template given') + } return template } diff --git a/packages/create-payload-app/src/lib/select-db.ts b/packages/create-payload-app/src/lib/select-db.ts index a1a0e8995..0f3d13b76 100644 --- a/packages/create-payload-app/src/lib/select-db.ts +++ b/packages/create-payload-app/src/lib/select-db.ts @@ -54,7 +54,9 @@ export async function selectDb(args: CliArgs, projectName: string): Promise { - if (!appDetails.nextConfigPath) return { message: 'No Next.js config found', success: false } + if (!appDetails.nextConfigPath) { + return { message: 'No Next.js config found', success: false } + } const projectDir = path.dirname(appDetails.nextConfigPath) 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 e804e25c5..4ac3fa4ce 100644 --- a/packages/create-payload-app/src/lib/write-env-file.ts +++ b/packages/create-payload-app/src/lib/write-env-file.ts @@ -36,7 +36,9 @@ export async function writeEnvFile(args: { .split('\n') .filter((e) => e) .map((line) => { - if (line.startsWith('#') || !line.includes('=')) return line + if (line.startsWith('#') || !line.includes('=')) { + return line + } const split = line.split('=') const key = split[0] diff --git a/packages/email-nodemailer/src/index.ts b/packages/email-nodemailer/src/index.ts index f539635db..04cf3f873 100644 --- a/packages/email-nodemailer/src/index.ts +++ b/packages/email-nodemailer/src/index.ts @@ -47,7 +47,9 @@ async function buildEmail(emailConfig?: NodemailerAdapterArgs): Promise<{ }> { if (!emailConfig) { const transport = await createMockAccount(emailConfig) - if (!transport) throw new InvalidConfiguration('Unable to create Nodemailer test account.') + if (!transport) { + throw new InvalidConfiguration('Unable to create Nodemailer test account.') + } return { defaultFromAddress: 'info@payloadcms.com', diff --git a/packages/eslint-config/index.mjs b/packages/eslint-config/index.mjs index 0f6cc67e9..722e7cdd4 100644 --- a/packages/eslint-config/index.mjs +++ b/packages/eslint-config/index.mjs @@ -14,6 +14,7 @@ import { deepMerge } from './deepMerge.js' const baseRules = { // This rule makes no sense when overriding class methods. This is used a lot in richtext-lexical. 'class-methods-use-this': 'off', + curly: ['warn', 'all'], 'arrow-body-style': 0, 'import-x/prefer-default-export': 'off', 'no-restricted-exports': ['warn', { restrictDefaultExports: { direct: true } }], diff --git a/packages/graphql/src/resolvers/auth/resetPassword.ts b/packages/graphql/src/resolvers/auth/resetPassword.ts index 43632df7e..b17f4afa1 100644 --- a/packages/graphql/src/resolvers/auth/resetPassword.ts +++ b/packages/graphql/src/resolvers/auth/resetPassword.ts @@ -6,8 +6,12 @@ import type { Context } from '../types.js' export function resetPassword(collection: Collection): any { async function resolver(_, args, context: Context) { - if (args.locale) context.req.locale = args.locale - if (args.fallbackLocale) context.req.fallbackLocale = args.fallbackLocale + if (args.locale) { + context.req.locale = args.locale + } + if (args.fallbackLocale) { + context.req.fallbackLocale = args.fallbackLocale + } const options = { api: 'GraphQL', diff --git a/packages/graphql/src/resolvers/auth/verifyEmail.ts b/packages/graphql/src/resolvers/auth/verifyEmail.ts index 4cc46350e..ebd97a2ad 100644 --- a/packages/graphql/src/resolvers/auth/verifyEmail.ts +++ b/packages/graphql/src/resolvers/auth/verifyEmail.ts @@ -6,8 +6,12 @@ import type { Context } from '../types.js' export function verifyEmail(collection: Collection) { async function resolver(_, args, context: Context) { - if (args.locale) context.req.locale = args.locale - if (args.fallbackLocale) context.req.fallbackLocale = args.fallbackLocale + if (args.locale) { + context.req.locale = args.locale + } + if (args.fallbackLocale) { + context.req.fallbackLocale = args.fallbackLocale + } const options = { api: 'GraphQL', diff --git a/packages/graphql/src/resolvers/collections/delete.ts b/packages/graphql/src/resolvers/collections/delete.ts index 680141c1e..788a211c5 100644 --- a/packages/graphql/src/resolvers/collections/delete.ts +++ b/packages/graphql/src/resolvers/collections/delete.ts @@ -28,7 +28,9 @@ export function getDeleteResolver( req = isolateObjectProperty(req, 'fallbackLocale') req.locale = args.locale || locale req.fallbackLocale = args.fallbackLocale || fallbackLocale - if (!req.query) req.query = {} + if (!req.query) { + req.query = {} + } const draft: boolean = args.draft ?? req.query?.draft === 'false' @@ -36,7 +38,9 @@ export function getDeleteResolver( : req.query?.draft === 'true' ? true : undefined - if (typeof draft === 'boolean') req.query.draft = String(draft) + if (typeof draft === 'boolean') { + req.query.draft = String(draft) + } context.req = req diff --git a/packages/graphql/src/resolvers/collections/find.ts b/packages/graphql/src/resolvers/collections/find.ts index 8870f37c8..b5a0eb3ed 100644 --- a/packages/graphql/src/resolvers/collections/find.ts +++ b/packages/graphql/src/resolvers/collections/find.ts @@ -31,7 +31,9 @@ export function findResolver(collection: Collection): Resolver { req = isolateObjectProperty(req, ['locale', 'fallbackLocale', 'transactionID']) req.locale = args.locale || locale req.fallbackLocale = args.fallbackLocale || fallbackLocale - if (!req.query) req.query = {} + if (!req.query) { + req.query = {} + } const draft: boolean = args.draft ?? req.query?.draft === 'false' @@ -39,7 +41,9 @@ export function findResolver(collection: Collection): Resolver { : req.query?.draft === 'true' ? true : undefined - if (typeof draft === 'boolean') req.query.draft = String(draft) + if (typeof draft === 'boolean') { + req.query.draft = String(draft) + } context.req = req diff --git a/packages/graphql/src/resolvers/collections/findByID.ts b/packages/graphql/src/resolvers/collections/findByID.ts index d6108d4d8..08b45f18d 100644 --- a/packages/graphql/src/resolvers/collections/findByID.ts +++ b/packages/graphql/src/resolvers/collections/findByID.ts @@ -28,7 +28,9 @@ export function findByIDResolver( req = isolateObjectProperty(req, 'fallbackLocale') req.locale = args.locale || locale req.fallbackLocale = args.fallbackLocale || fallbackLocale - if (!req.query) req.query = {} + if (!req.query) { + req.query = {} + } const draft: boolean = args.draft ?? req.query?.draft === 'false' @@ -36,7 +38,9 @@ export function findByIDResolver( : req.query?.draft === 'true' ? true : undefined - if (typeof draft === 'boolean') req.query.draft = String(draft) + if (typeof draft === 'boolean') { + req.query.draft = String(draft) + } context.req = req diff --git a/packages/graphql/src/resolvers/collections/findVersions.ts b/packages/graphql/src/resolvers/collections/findVersions.ts index 79624632a..5710eadfa 100644 --- a/packages/graphql/src/resolvers/collections/findVersions.ts +++ b/packages/graphql/src/resolvers/collections/findVersions.ts @@ -29,7 +29,9 @@ export function findVersionsResolver(collection: Collection): Resolver { req = isolateObjectProperty(req, 'fallbackLocale') req.locale = args.locale || locale req.fallbackLocale = args.fallbackLocale || fallbackLocale - if (!req.query) req.query = {} + if (!req.query) { + req.query = {} + } const draft: boolean = args.draft ?? req.query?.draft === 'false' @@ -37,7 +39,9 @@ export function findVersionsResolver(collection: Collection): Resolver { : req.query?.draft === 'true' ? true : undefined - if (typeof draft === 'boolean') req.query.draft = String(draft) + if (typeof draft === 'boolean') { + req.query.draft = String(draft) + } context.req = req diff --git a/packages/graphql/src/resolvers/collections/update.ts b/packages/graphql/src/resolvers/collections/update.ts index 92626dc76..27b6b3440 100644 --- a/packages/graphql/src/resolvers/collections/update.ts +++ b/packages/graphql/src/resolvers/collections/update.ts @@ -30,7 +30,9 @@ export function updateResolver( req = isolateObjectProperty(req, 'fallbackLocale') req.locale = args.locale || locale req.fallbackLocale = args.fallbackLocale || fallbackLocale - if (!req.query) req.query = {} + if (!req.query) { + req.query = {} + } const draft: boolean = args.draft ?? req.query?.draft === 'false' @@ -38,7 +40,9 @@ export function updateResolver( : req.query?.draft === 'true' ? true : undefined - if (typeof draft === 'boolean') req.query.draft = String(draft) + if (typeof draft === 'boolean') { + req.query.draft = String(draft) + } context.req = req diff --git a/packages/graphql/src/resolvers/globals/findOne.ts b/packages/graphql/src/resolvers/globals/findOne.ts index a436afd73..a4ff55129 100644 --- a/packages/graphql/src/resolvers/globals/findOne.ts +++ b/packages/graphql/src/resolvers/globals/findOne.ts @@ -6,8 +6,12 @@ import type { Context } from '../types.js' export function findOne(globalConfig: SanitizedGlobalConfig): Document { return async function resolver(_, args, context: Context) { - if (args.locale) context.req.locale = args.locale - if (args.fallbackLocale) context.req.fallbackLocale = args.fallbackLocale + if (args.locale) { + context.req.locale = args.locale + } + if (args.fallbackLocale) { + context.req.fallbackLocale = args.fallbackLocale + } const { slug } = globalConfig diff --git a/packages/graphql/src/resolvers/globals/findVersionByID.ts b/packages/graphql/src/resolvers/globals/findVersionByID.ts index d93552825..fafa06340 100644 --- a/packages/graphql/src/resolvers/globals/findVersionByID.ts +++ b/packages/graphql/src/resolvers/globals/findVersionByID.ts @@ -19,8 +19,12 @@ export type Resolver = ( export function findVersionByID(globalConfig: SanitizedGlobalConfig): Resolver { return async function resolver(_, args, context: Context) { - if (args.locale) context.req.locale = args.locale - if (args.fallbackLocale) context.req.fallbackLocale = args.fallbackLocale + if (args.locale) { + context.req.locale = args.locale + } + if (args.fallbackLocale) { + context.req.fallbackLocale = args.fallbackLocale + } const options = { id: args.id, diff --git a/packages/graphql/src/resolvers/globals/update.ts b/packages/graphql/src/resolvers/globals/update.ts index 421da1b83..1656356dc 100644 --- a/packages/graphql/src/resolvers/globals/update.ts +++ b/packages/graphql/src/resolvers/globals/update.ts @@ -22,8 +22,12 @@ export function update( globalConfig: SanitizedGlobalConfig, ): Resolver { return async function resolver(_, args, context: Context) { - if (args.locale) context.req.locale = args.locale - if (args.fallbackLocale) context.req.fallbackLocale = args.fallbackLocale + if (args.locale) { + context.req.locale = args.locale + } + if (args.fallbackLocale) { + context.req.fallbackLocale = args.fallbackLocale + } const { slug } = globalConfig diff --git a/packages/graphql/src/schema/buildMutationInputType.ts b/packages/graphql/src/schema/buildMutationInputType.ts index cdfb10405..d634ab5f4 100644 --- a/packages/graphql/src/schema/buildMutationInputType.ts +++ b/packages/graphql/src/schema/buildMutationInputType.ts @@ -97,7 +97,9 @@ export function buildMutationInputType({ parentName: fullName, }) - if (!type) return inputObjectTypeConfig + if (!type) { + return inputObjectTypeConfig + } type = new GraphQLList(withNullableType(field, type, forceNullable)) return { @@ -120,7 +122,9 @@ export function buildMutationInputType({ collapsible: (inputObjectTypeConfig: InputObjectTypeConfig, field: CollapsibleField) => field.fields.reduce((acc, subField: CollapsibleField) => { const addSubField = fieldToSchemaMap[subField.type] - if (addSubField) return addSubField(acc, subField) + if (addSubField) { + return addSubField(acc, subField) + } return acc }, inputObjectTypeConfig), date: (inputObjectTypeConfig: InputObjectTypeConfig, field: DateField) => ({ @@ -142,9 +146,13 @@ export function buildMutationInputType({ parentName: fullName, }) - if (!type) return inputObjectTypeConfig + if (!type) { + return inputObjectTypeConfig + } - if (requiresAtLeastOneField) type = new GraphQLNonNull(type) + if (requiresAtLeastOneField) { + type = new GraphQLNonNull(type) + } return { ...inputObjectTypeConfig, [field.name]: { type }, @@ -227,7 +235,9 @@ export function buildMutationInputType({ row: (inputObjectTypeConfig: InputObjectTypeConfig, field: RowField) => field.fields.reduce((acc, subField: Field) => { const addSubField = fieldToSchemaMap[subField.type] - if (addSubField) return addSubField(acc, subField) + if (addSubField) { + return addSubField(acc, subField) + } return acc }, inputObjectTypeConfig), select: (inputObjectTypeConfig: InputObjectTypeConfig, field: SelectField) => { @@ -274,9 +284,13 @@ export function buildMutationInputType({ parentName: fullName, }) - if (!type) return acc + if (!type) { + return acc + } - if (requiresAtLeastOneField) type = new GraphQLNonNull(type) + if (requiresAtLeastOneField) { + type = new GraphQLNonNull(type) + } return { ...acc, [tab.name]: { type }, @@ -287,7 +301,9 @@ export function buildMutationInputType({ ...acc, ...tab.fields.reduce((subFieldSchema, subField) => { const addSubField = fieldToSchemaMap[subField.type] - if (addSubField) return addSubField(subFieldSchema, subField) + if (addSubField) { + return addSubField(subFieldSchema, subField) + } return subFieldSchema }, acc), } diff --git a/packages/graphql/src/schema/buildObjectType.ts b/packages/graphql/src/schema/buildObjectType.ts index eef1ff61b..0c62ea930 100644 --- a/packages/graphql/src/schema/buildObjectType.ts +++ b/packages/graphql/src/schema/buildObjectType.ts @@ -171,7 +171,9 @@ export function buildObjectType({ collapsible: (objectTypeConfig: ObjectTypeConfig, field: CollapsibleField) => field.fields.reduce((objectTypeConfigWithCollapsibleFields, subField) => { const addSubField = fieldToSchemaMap[subField.type] - if (addSubField) return addSubField(objectTypeConfigWithCollapsibleFields, subField) + if (addSubField) { + return addSubField(objectTypeConfigWithCollapsibleFields, subField) + } return objectTypeConfigWithCollapsibleFields }, objectTypeConfig), date: (objectTypeConfig: ObjectTypeConfig, field: DateField) => ({ @@ -459,7 +461,9 @@ export function buildObjectType({ }, async resolve(parent, args, context: Context) { let depth = config.defaultDepth - if (typeof args.depth !== 'undefined') depth = args.depth + if (typeof args.depth !== 'undefined') { + depth = args.depth + } if (!field?.editor) { throw new MissingEditorProp(field) // while we allow disabling editor functionality, you should not have any richText fields defined if you do not have an editor } @@ -506,7 +510,9 @@ export function buildObjectType({ row: (objectTypeConfig: ObjectTypeConfig, field: RowField) => field.fields.reduce((objectTypeConfigWithRowFields, subField) => { const addSubField = fieldToSchemaMap[subField.type] - if (addSubField) return addSubField(objectTypeConfigWithRowFields, subField) + if (addSubField) { + return addSubField(objectTypeConfigWithRowFields, subField) + } return objectTypeConfigWithRowFields }, objectTypeConfig), select: (objectTypeConfig: ObjectTypeConfig, field: SelectField) => { @@ -560,7 +566,9 @@ export function buildObjectType({ ...tabSchema, ...tab.fields.reduce((subFieldSchema, subField) => { const addSubField = fieldToSchemaMap[subField.type] - if (addSubField) return addSubField(subFieldSchema, subField) + if (addSubField) { + return addSubField(subFieldSchema, subField) + } return subFieldSchema }, tabSchema), } diff --git a/packages/graphql/src/schema/buildPoliciesType.ts b/packages/graphql/src/schema/buildPoliciesType.ts index 086ba1818..e5757937f 100644 --- a/packages/graphql/src/schema/buildPoliciesType.ts +++ b/packages/graphql/src/schema/buildPoliciesType.ts @@ -148,7 +148,9 @@ export function buildPolicyType(args: BuildPolicyType): GraphQLObjectType { let operations = [] - if (graphQL === false) return null + if (graphQL === false) { + return null + } if (type === 'collection') { operations = ['create', 'read', 'update', 'delete'] diff --git a/packages/graphql/src/schema/initCollections.ts b/packages/graphql/src/schema/initCollections.ts index 7a97a9db0..5d24b8197 100644 --- a/packages/graphql/src/schema/initCollections.ts +++ b/packages/graphql/src/schema/initCollections.ts @@ -57,7 +57,9 @@ export function initCollections({ config, graphqlResult }: InitCollectionsGraphQ config: { fields, graphQL = {} as SanitizedCollectionConfig['graphQL'], versions }, } = collection - if (!graphQL) return + if (!graphQL) { + return + } let singularName let pluralName diff --git a/packages/graphql/src/schema/initGlobals.ts b/packages/graphql/src/schema/initGlobals.ts index b70a6ee23..dd8452c3f 100644 --- a/packages/graphql/src/schema/initGlobals.ts +++ b/packages/graphql/src/schema/initGlobals.ts @@ -36,7 +36,9 @@ export function initGlobals({ config, graphqlResult }: InitGlobalsGraphQLArgs): const forceNullableObjectType = Boolean(versions?.drafts) - if (!graphqlResult.globals.graphQL) graphqlResult.globals.graphQL = {} + if (!graphqlResult.globals.graphQL) { + graphqlResult.globals.graphQL = {} + } const updateMutationInputType = buildMutationInputType({ name: formattedName, diff --git a/packages/graphql/src/schema/withOperators.ts b/packages/graphql/src/schema/withOperators.ts index 44ff25513..48c2f52e1 100644 --- a/packages/graphql/src/schema/withOperators.ts +++ b/packages/graphql/src/schema/withOperators.ts @@ -263,7 +263,9 @@ export const withOperators = ( field: FieldAffectingData, parentName: string, ): GraphQLInputObjectType => { - if (!defaults?.[field.type]) throw new Error(`Error: ${field.type} has no defaults configured.`) + if (!defaults?.[field.type]) { + throw new Error(`Error: ${field.type} has no defaults configured.`) + } const name = `${combineParentName(parentName, field.name)}_operator` diff --git a/packages/next/babel.config.cjs b/packages/next/babel.config.cjs index 2a16d7554..ed4b07a62 100644 --- a/packages/next/babel.config.cjs +++ b/packages/next/babel.config.cjs @@ -4,7 +4,10 @@ const fs = require('fs') const ReactCompilerConfig = { sources: (filename) => { const isInNodeModules = filename.includes('node_modules') - if (isInNodeModules || ( !filename.endsWith('.tsx') && !filename.endsWith('.jsx') && !filename.endsWith('.js'))) { + if ( + isInNodeModules || + (!filename.endsWith('.tsx') && !filename.endsWith('.jsx') && !filename.endsWith('.js')) + ) { return false } diff --git a/packages/next/src/elements/DocumentHeader/Tabs/index.tsx b/packages/next/src/elements/DocumentHeader/Tabs/index.tsx index 67252a2f4..bf0712678 100644 --- a/packages/next/src/elements/DocumentHeader/Tabs/index.tsx +++ b/packages/next/src/elements/DocumentHeader/Tabs/index.tsx @@ -40,9 +40,13 @@ export const DocumentTabs: React.FC<{ // if no `order`, append the view to the end // TODO: open `order` to the config and merge `defaultViews` with `customViews` ?.sort(([, a], [, b]) => { - if (a.order === undefined && b.order === undefined) return 0 - else if (a.order === undefined) return 1 - else if (b.order === undefined) return -1 + if (a.order === undefined && b.order === undefined) { + return 0 + } else if (a.order === undefined) { + return 1 + } else if (b.order === undefined) { + return -1 + } return a.order - b.order }) ?.map(([name, tab], index) => { diff --git a/packages/next/src/elements/DocumentHeader/Tabs/tabs/VersionsPill/index.tsx b/packages/next/src/elements/DocumentHeader/Tabs/tabs/VersionsPill/index.tsx index 38192c0d6..26a3f7555 100644 --- a/packages/next/src/elements/DocumentHeader/Tabs/tabs/VersionsPill/index.tsx +++ b/packages/next/src/elements/DocumentHeader/Tabs/tabs/VersionsPill/index.tsx @@ -12,7 +12,7 @@ export const VersionsPill: React.FC = () => { // documents that are version enabled _always_ have at least one version const hasVersions = versions?.totalDocs > 0 - if (hasVersions) + if (hasVersions) { return ( { {versions.totalDocs.toString()} ) + } } diff --git a/packages/next/src/elements/LeaveWithoutSaving/index.tsx b/packages/next/src/elements/LeaveWithoutSaving/index.tsx index 63622f268..3b533641d 100644 --- a/packages/next/src/elements/LeaveWithoutSaving/index.tsx +++ b/packages/next/src/elements/LeaveWithoutSaving/index.tsx @@ -25,8 +25,11 @@ const Component: React.FC<{ // }, [modalState, isActive, onCancel]) useEffect(() => { - if (isActive) openModal(modalSlug) - else closeModal(modalSlug) + if (isActive) { + openModal(modalSlug) + } else { + closeModal(modalSlug) + } }, [isActive, openModal, closeModal]) return ( diff --git a/packages/next/src/elements/LeaveWithoutSaving/usePreventLeave.tsx b/packages/next/src/elements/LeaveWithoutSaving/usePreventLeave.tsx index dce1cf2ed..95dcddcd9 100644 --- a/packages/next/src/elements/LeaveWithoutSaving/usePreventLeave.tsx +++ b/packages/next/src/elements/LeaveWithoutSaving/usePreventLeave.tsx @@ -145,7 +145,9 @@ export const usePreventLeave = ({ useEffect(() => { if (hasAccepted && cancelledURL.current) { - if (onAccept) onAccept() + if (onAccept) { + onAccept() + } router.push(cancelledURL.current) } }, [hasAccepted, onAccept, router]) diff --git a/packages/next/src/fetchAPI-multipart/handlers.ts b/packages/next/src/fetchAPI-multipart/handlers.ts index 28eacb55f..1c9229fd3 100644 --- a/packages/next/src/fetchAPI-multipart/handlers.ts +++ b/packages/next/src/fetchAPI-multipart/handlers.ts @@ -55,7 +55,9 @@ export const tempFileHandler: Handler = (options, fieldname, filename) => { complete: () => { completed = true debugLog(options, `Upload ${fieldname}->${filename} completed, bytes:${fileSize}.`) - if (writeStream instanceof WriteStream) writeStream.end() + if (writeStream instanceof WriteStream) { + writeStream.end() + } // Return empty buff since data was uploaded into a temp file. return Buffer.concat([]) }, diff --git a/packages/next/src/fetchAPI-multipart/processNested.ts b/packages/next/src/fetchAPI-multipart/processNested.ts index c08b868e1..28debc628 100644 --- a/packages/next/src/fetchAPI-multipart/processNested.ts +++ b/packages/next/src/fetchAPI-multipart/processNested.ts @@ -1,7 +1,9 @@ import { isSafeFromPollution } from './utilities.js' export const processNested = function (data) { - if (!data || data.length < 1) return Object.create(null) + if (!data || data.length < 1) { + return Object.create(null) + } const d = Object.create(null), keys = Object.keys(data) @@ -23,7 +25,9 @@ export const processNested = function (data) { if (index >= keyParts.length - 1) { current[k] = value } else { - if (!current[k]) current[k] = !keyParts[index + 1] ? [] : Object.create(null) + if (!current[k]) { + current[k] = !keyParts[index + 1] ? [] : Object.create(null) + } current = current[k] } } diff --git a/packages/next/src/fetchAPI-multipart/uploadTimer.ts b/packages/next/src/fetchAPI-multipart/uploadTimer.ts index 1e80ffa5f..5e312b5af 100644 --- a/packages/next/src/fetchAPI-multipart/uploadTimer.ts +++ b/packages/next/src/fetchAPI-multipart/uploadTimer.ts @@ -15,7 +15,9 @@ export const createUploadTimer: CreateUploadTimer = (timeout = 0, callback = () const set = () => { // Do not start a timer if zero timeout or it hasn't been set. - if (!timeout) return false + if (!timeout) { + return false + } clear() timer = setTimeout(callback, timeout) return true diff --git a/packages/next/src/fetchAPI-multipart/utilities.ts b/packages/next/src/fetchAPI-multipart/utilities.ts index 673d687b0..352e6c5b5 100644 --- a/packages/next/src/fetchAPI-multipart/utilities.ts +++ b/packages/next/src/fetchAPI-multipart/utilities.ts @@ -18,7 +18,9 @@ let tempCounter = 0 */ export const debugLog = (options: FetchAPIFileUploadOptions, msg: string) => { const opts = options || {} - if (!opts.debug) return false + if (!opts.debug) { + return false + } console.log(`Next-file-upload: ${msg}`) // eslint-disable-line return true } @@ -84,7 +86,9 @@ export const isSafeFromPollution: IsSafeFromPollution = (base, key) => { type BuildFields = (instance: any, field: string, value: any) => any export const buildFields: BuildFields = (instance, field, value) => { // Do nothing if value is not set. - if (value === null || value === undefined) return instance + if (value === null || value === undefined) { + return instance + } instance = instance || Object.create(null) if (!isSafeFromPollution(instance, field)) { @@ -110,11 +114,15 @@ export const buildFields: BuildFields = (instance, field, value) => { */ type CheckAndMakeDir = (fileUploadOptions: FetchAPIFileUploadOptions, filePath: string) => boolean export const checkAndMakeDir: CheckAndMakeDir = (fileUploadOptions, filePath) => { - if (!fileUploadOptions.createParentPath) return false + if (!fileUploadOptions.createParentPath) { + return false + } // Check whether folder for the file exists. const parentPath = path.dirname(filePath) // Create folder if it doesn't exist. - if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath, { recursive: true }) + if (!fs.existsSync(parentPath)) { + fs.mkdirSync(parentPath, { recursive: true }) + } // Checks folder again and return a results. return fs.existsSync(parentPath) } @@ -134,7 +142,9 @@ const copyFile: CopyFile = (src, dst, callback) => { // cbCalled flag and runCb helps to run cb only once. let cbCalled = false const runCb = (err?: Error) => { - if (cbCalled) return + if (cbCalled) { + return + } cbCalled = true callback(err) } @@ -247,14 +257,18 @@ export const parseFileNameExtension: ParseFileNameExtension = (preserveExtension name: fileName, extension: '', } - if (!preserveExtension) return defaultResult + if (!preserveExtension) { + return defaultResult + } // Define maximum extension length const maxExtLength = typeof preserveExtension === 'boolean' ? MAX_EXTENSION_LENGTH : preserveExtension const nameParts = fileName.split('.') - if (nameParts.length < 2) return defaultResult + if (nameParts.length < 2) { + return defaultResult + } let extension = nameParts.pop() if (extension.length > maxExtLength && maxExtLength > 0) { @@ -274,13 +288,17 @@ export const parseFileNameExtension: ParseFileNameExtension = (preserveExtension type ParseFileName = (opts: FetchAPIFileUploadOptions, fileName: string) => string export const parseFileName: ParseFileName = (opts, fileName) => { // Check fileName argument - if (!fileName || typeof fileName !== 'string') return getTempFilename() + if (!fileName || typeof fileName !== 'string') { + return getTempFilename() + } // Cut off file name if it's length more then 255. let parsedName = fileName.length <= 255 ? fileName : fileName.substr(0, 255) // Decode file name if uriDecodeFileNames option set true. parsedName = uriDecodeFileName(opts, parsedName) // Stop parsing file name if safeFileNames options hasn't been set. - if (!opts.safeFileNames) return parsedName + if (!opts.safeFileNames) { + return parsedName + } // Set regular expression for the file name. const nameRegex = typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp @@ -288,8 +306,9 @@ export const parseFileName: ParseFileName = (opts, fileName) => { : SAFE_FILE_NAME_REGEX // Parse file name extension. const parsedFileName = parseFileNameExtension(opts.preserveExtension, parsedName) - if (parsedFileName.extension.length) + if (parsedFileName.extension.length) { parsedFileName.extension = '.' + parsedFileName.extension.replace(nameRegex, '') + } return parsedFileName.name.replace(nameRegex, '').concat(parsedFileName.extension) } diff --git a/packages/next/src/routes/rest/collections/updateByID.ts b/packages/next/src/routes/rest/collections/updateByID.ts index 8ff510937..207c51cb9 100644 --- a/packages/next/src/routes/rest/collections/updateByID.ts +++ b/packages/next/src/routes/rest/collections/updateByID.ts @@ -35,8 +35,12 @@ export const updateByID: CollectionRouteHandlerWithID = async ({ let message = req.t('general:updatedSuccessfully') - if (draft) message = req.t('version:draftSavedSuccessfully') - if (autosave) message = req.t('version:autosavedSuccessfully') + if (draft) { + message = req.t('version:draftSavedSuccessfully') + } + if (autosave) { + message = req.t('version:autosavedSuccessfully') + } return Response.json( { diff --git a/packages/next/src/routes/rest/files/checkFileAccess.ts b/packages/next/src/routes/rest/files/checkFileAccess.ts index b05ac9cb5..1e6bf6fca 100644 --- a/packages/next/src/routes/rest/files/checkFileAccess.ts +++ b/packages/next/src/routes/rest/files/checkFileAccess.ts @@ -15,7 +15,9 @@ export async function checkFileAccess({ }): Promise { const { config } = collection const disableEndpoints = endpointsAreDisabled({ endpoints: config.endpoints, request: req }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } const accessResult = await executeAccess({ isReadingStaticFile: true, req }, config.access.read) diff --git a/packages/next/src/routes/rest/files/getFile.ts b/packages/next/src/routes/rest/files/getFile.ts index e9c784c2e..b66183b07 100644 --- a/packages/next/src/routes/rest/files/getFile.ts +++ b/packages/next/src/routes/rest/files/getFile.ts @@ -33,7 +33,9 @@ export const getFile = async ({ collection, filename, req }: Args): Promise { let message = req.t('general:updatedSuccessfully') - if (draft) message = req.t('version:draftSavedSuccessfully') - if (autosave) message = req.t('version:autosavedSuccessfully') + if (draft) { + message = req.t('version:draftSavedSuccessfully') + } + if (autosave) { + message = req.t('version:autosavedSuccessfully') + } return Response.json( { diff --git a/packages/next/src/routes/rest/index.ts b/packages/next/src/routes/rest/index.ts index 12fa5052d..940c746a4 100644 --- a/packages/next/src/routes/rest/index.ts +++ b/packages/next/src/routes/rest/index.ts @@ -246,7 +246,9 @@ export const GET = request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } collection = req.payload.collections?.[slug1] @@ -256,7 +258,9 @@ export const GET = endpoints: collection.config.endpoints, request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } const customEndpointResponse = await handleCustomEndpoints({ endpoints: collection.config.endpoints, @@ -327,7 +331,9 @@ export const GET = endpoints: globalConfig.endpoints, request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } const customEndpointResponse = await handleCustomEndpoints({ endpoints: globalConfig.endpoints, @@ -403,7 +409,9 @@ export const GET = req, }) - if (customEndpointResponse) return customEndpointResponse + if (customEndpointResponse) { + return customEndpointResponse + } return RouteNotFoundResponse({ slug, @@ -445,7 +453,9 @@ export const POST = request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } if (collection) { req.routeParams.collection = slug1 @@ -453,7 +463,9 @@ export const POST = endpoints: collection.config.endpoints, request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } const customEndpointResponse = await handleCustomEndpoints({ endpoints: collection.config.endpoints, @@ -516,7 +528,9 @@ export const POST = endpoints: globalConfig.endpoints, request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } const customEndpointResponse = await handleCustomEndpoints({ endpoints: globalConfig.endpoints, @@ -585,7 +599,9 @@ export const POST = req, }) - if (customEndpointResponse) return customEndpointResponse + if (customEndpointResponse) { + return customEndpointResponse + } return RouteNotFoundResponse({ slug, @@ -620,7 +636,9 @@ export const DELETE = endpoints: req.payload.config.endpoints, request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } if (collection) { req.routeParams.collection = slug1 @@ -629,7 +647,9 @@ export const DELETE = endpoints: collection.config.endpoints, request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } const customEndpointResponse = await handleCustomEndpoints({ endpoints: collection.config.endpoints, @@ -679,7 +699,9 @@ export const DELETE = req, }) - if (customEndpointResponse) return customEndpointResponse + if (customEndpointResponse) { + return customEndpointResponse + } return RouteNotFoundResponse({ slug, @@ -714,7 +736,9 @@ export const PATCH = endpoints: req.payload.config.endpoints, request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } if (collection) { req.routeParams.collection = slug1 @@ -723,7 +747,9 @@ export const PATCH = endpoints: collection.config.endpoints, request, }) - if (disableEndpoints) return disableEndpoints + if (disableEndpoints) { + return disableEndpoints + } const customEndpointResponse = await handleCustomEndpoints({ endpoints: collection.config.endpoints, @@ -774,7 +800,9 @@ export const PATCH = req, }) - if (customEndpointResponse) return customEndpointResponse + if (customEndpointResponse) { + return customEndpointResponse + } return RouteNotFoundResponse({ slug, diff --git a/packages/next/src/routes/rest/utilities/sanitizeCollectionID.ts b/packages/next/src/routes/rest/utilities/sanitizeCollectionID.ts index 9cc62a6ba..9a71ce46d 100644 --- a/packages/next/src/routes/rest/utilities/sanitizeCollectionID.ts +++ b/packages/next/src/routes/rest/utilities/sanitizeCollectionID.ts @@ -14,10 +14,14 @@ export const sanitizeCollectionID = ({ id, collectionSlug, payload }: Args): num let shouldSanitize = Boolean(payload.db.defaultIDType === 'number') // UNLESS the customIDType for this collection is text.... then we leave it - if (shouldSanitize && collection.customIDType === 'text') shouldSanitize = false + if (shouldSanitize && collection.customIDType === 'text') { + shouldSanitize = false + } // If we still should sanitize, parse float - if (shouldSanitize) sanitizedID = parseFloat(sanitizedID) + if (shouldSanitize) { + sanitizedID = parseFloat(sanitizedID) + } return sanitizedID } diff --git a/packages/next/src/templates/Default/Wrapper/index.scss b/packages/next/src/templates/Default/Wrapper/index.scss index 9d2dc1855..22b858e40 100644 --- a/packages/next/src/templates/Default/Wrapper/index.scss +++ b/packages/next/src/templates/Default/Wrapper/index.scss @@ -15,7 +15,6 @@ } &--nav-open { - .template-default { &__nav-overlay { transition: opacity var(--nav-trans-time) linear; diff --git a/packages/next/src/utilities/addLocalesToRequest.ts b/packages/next/src/utilities/addLocalesToRequest.ts index d1807c3c6..11e22644c 100644 --- a/packages/next/src/utilities/addLocalesToRequest.ts +++ b/packages/next/src/utilities/addLocalesToRequest.ts @@ -31,8 +31,12 @@ export function addLocalesToRequestFromData(req: PayloadRequest): void { localization: config.localization, }) - if (locale) req.locale = locale - if (fallbackLocale) req.fallbackLocale = fallbackLocale + if (locale) { + req.locale = locale + } + if (fallbackLocale) { + req.fallbackLocale = fallbackLocale + } } } diff --git a/packages/next/src/utilities/createPayloadRequest.ts b/packages/next/src/utilities/createPayloadRequest.ts index 4c08bad88..5cddbad50 100644 --- a/packages/next/src/utilities/createPayloadRequest.ts +++ b/packages/next/src/utilities/createPayloadRequest.ts @@ -69,8 +69,12 @@ export const createPayloadRequest = async ({ fallbackLocale = locales.fallbackLocale // Override if query params are present, in order to respect HTTP method override - if (query.locale) locale = query.locale - if (query?.['fallback-locale']) fallbackLocale = query['fallback-locale'] + if (query.locale) { + locale = query.locale + } + if (query?.['fallback-locale']) { + fallbackLocale = query['fallback-locale'] + } } const customRequest: CustomPayloadRequestProperties = { @@ -110,7 +114,9 @@ export const createPayloadRequest = async ({ req.user = user - if (responseHeaders) req.responseHeaders = responseHeaders + if (responseHeaders) { + req.responseHeaders = responseHeaders + } return req } diff --git a/packages/next/src/utilities/initPage/handleAuthRedirect.ts b/packages/next/src/utilities/initPage/handleAuthRedirect.ts index 5840ffda1..20393b698 100644 --- a/packages/next/src/utilities/initPage/handleAuthRedirect.ts +++ b/packages/next/src/utilities/initPage/handleAuthRedirect.ts @@ -23,7 +23,9 @@ export const handleAuthRedirect = ({ } = config if (!isAdminAuthRoute({ adminRoute, config, route })) { - if (searchParams && 'redirect' in searchParams) delete searchParams.redirect + if (searchParams && 'redirect' in searchParams) { + delete searchParams.redirect + } const redirectRoute = encodeURIComponent( route + Object.keys(searchParams ?? {}).length diff --git a/packages/next/src/utilities/initPage/index.ts b/packages/next/src/utilities/initPage/index.ts index a0cb348c3..99b539221 100644 --- a/packages/next/src/utilities/initPage/index.ts +++ b/packages/next/src/utilities/initPage/index.ts @@ -117,7 +117,9 @@ export const initPage = async ({ locale = findLocaleFromCode(localization, localeCode) - if (!locale) locale = findLocaleFromCode(localization, defaultLocaleCode) + if (!locale) { + locale = findLocaleFromCode(localization, defaultLocaleCode) + } req.locale = locale.code } diff --git a/packages/next/src/utilities/timestamp.ts b/packages/next/src/utilities/timestamp.ts index 7509e24b5..17884c9fb 100644 --- a/packages/next/src/utilities/timestamp.ts +++ b/packages/next/src/utilities/timestamp.ts @@ -1,5 +1,7 @@ export const timestamp = (label: string) => { - if (!process.env.PAYLOAD_TIME) process.env.PAYLOAD_TIME = String(new Date().getTime()) + if (!process.env.PAYLOAD_TIME) { + process.env.PAYLOAD_TIME = String(new Date().getTime()) + } const now = new Date() console.log(`[${now.getTime() - Number(process.env.PAYLOAD_TIME)}ms] ${label}`) } diff --git a/packages/next/src/views/Account/index.tsx b/packages/next/src/views/Account/index.tsx index 29d2e1511..6d25db166 100644 --- a/packages/next/src/views/Account/index.tsx +++ b/packages/next/src/views/Account/index.tsx @@ -1,6 +1,11 @@ import type { AdminViewProps } from 'payload' -import { DocumentInfoProvider, EditDepthProvider, HydrateAuthProvider, RenderComponent } from '@payloadcms/ui' +import { + DocumentInfoProvider, + EditDepthProvider, + HydrateAuthProvider, + RenderComponent, +} from '@payloadcms/ui' import { getCreateMappedComponent } from '@payloadcms/ui/shared' import { notFound } from 'next/navigation.js' import React from 'react' @@ -92,16 +97,15 @@ export const Account: React.FC = async ({ isEditing > - - - - + + + diff --git a/packages/next/src/views/Edit/Default/SetDocumentStepNav/index.tsx b/packages/next/src/views/Edit/Default/SetDocumentStepNav/index.tsx index 7c0b2b9b2..913bb39aa 100644 --- a/packages/next/src/views/Edit/Default/SetDocumentStepNav/index.tsx +++ b/packages/next/src/views/Edit/Default/SetDocumentStepNav/index.tsx @@ -91,7 +91,9 @@ export const SetDocumentStepNav: React.FC<{ }) } - if (drawerDepth <= 1) setStepNav(nav) + if (drawerDepth <= 1) { + setStepNav(nav) + } } }, [ setStepNav, diff --git a/packages/next/src/views/Edit/Default/index.tsx b/packages/next/src/views/Edit/Default/index.tsx index 980877ca8..ab2097e12 100644 --- a/packages/next/src/views/Edit/Default/index.tsx +++ b/packages/next/src/views/Edit/Default/index.tsx @@ -95,8 +95,12 @@ export const DefaultEditView: React.FC = () => { const classes = [baseClass, id && `${baseClass}--is-editing`] - if (globalSlug) classes.push(`global-edit--${globalSlug}`) - if (collectionSlug) classes.push(`collection-edit--${collectionSlug}`) + if (globalSlug) { + classes.push(`global-edit--${globalSlug}`) + } + if (collectionSlug) { + classes.push(`collection-edit--${collectionSlug}`) + } const [schemaPath, setSchemaPath] = React.useState(() => { if (operation === 'create' && auth && !auth.disableLocalStrategy) { diff --git a/packages/next/src/views/LivePreview/Context/index.tsx b/packages/next/src/views/LivePreview/Context/index.tsx index 74cf8777b..58bed3d58 100644 --- a/packages/next/src/views/LivePreview/Context/index.tsx +++ b/packages/next/src/views/LivePreview/Context/index.tsx @@ -146,7 +146,9 @@ export const LivePreviewProvider: React.FC = ({ (type: 'iframe' | 'popup') => { setAppIsReady(false) setPreviewWindowType(type) - if (type === 'popup') openPopupWindow() + if (type === 'popup') { + openPopupWindow() + } }, [openPopupWindow], ) diff --git a/packages/next/src/views/LivePreview/Device/index.tsx b/packages/next/src/views/LivePreview/Device/index.tsx index de0247c9d..fab8ca306 100644 --- a/packages/next/src/views/LivePreview/Device/index.tsx +++ b/packages/next/src/views/LivePreview/Device/index.tsx @@ -54,8 +54,11 @@ export const DeviceContainer: React.FC<{ if (deviceIsLargerThanFrame) { if (zoom > 1) { const differenceFromDeviceToFrame = measuredDeviceSize.width - outerFrameSize.width - if (differenceFromDeviceToFrame < 0) x = `${differenceFromDeviceToFrame / 2}px` - else x = '0' + if (differenceFromDeviceToFrame < 0) { + x = `${differenceFromDeviceToFrame / 2}px` + } else { + x = '0' + } } else { x = '0' } diff --git a/packages/next/src/views/LivePreview/Toolbar/SizeInput/index.tsx b/packages/next/src/views/LivePreview/Toolbar/SizeInput/index.tsx index 267cee96f..bad5f1aa0 100644 --- a/packages/next/src/views/LivePreview/Toolbar/SizeInput/index.tsx +++ b/packages/next/src/views/LivePreview/Toolbar/SizeInput/index.tsx @@ -24,7 +24,9 @@ export const PreviewFrameSizeInput: React.FC<{ (e: React.ChangeEvent) => { let newValue = Number(e.target.value) - if (newValue < 0) newValue = 0 + if (newValue < 0) { + newValue = 0 + } setInternalState(newValue) setBreakpoint('custom') @@ -46,8 +48,11 @@ export const PreviewFrameSizeInput: React.FC<{ // so we need to take the measurements provided by `actualDeviceSize` and sync internal state useEffect(() => { if (breakpoint === 'responsive' && measuredDeviceSize) { - if (axis === 'x') setInternalState(Number(measuredDeviceSize.width.toFixed(0)) * zoom) - else setInternalState(Number(measuredDeviceSize.height.toFixed(0)) * zoom) + if (axis === 'x') { + setInternalState(Number(measuredDeviceSize.width.toFixed(0)) * zoom) + } else { + setInternalState(Number(measuredDeviceSize.height.toFixed(0)) * zoom) + } } if (breakpoint !== 'responsive' && size) { diff --git a/packages/next/src/views/Login/LoginForm/index.tsx b/packages/next/src/views/Login/LoginForm/index.tsx index 7609e36ae..7b95412e4 100644 --- a/packages/next/src/views/Login/LoginForm/index.tsx +++ b/packages/next/src/views/Login/LoginForm/index.tsx @@ -40,8 +40,12 @@ export const LoginForm: React.FC<{ const canLoginWithUsername = authOptions.loginWithUsername const [loginType] = React.useState(() => { - if (canLoginWithEmail && canLoginWithUsername) return 'emailOrUsername' - if (canLoginWithUsername) return 'username' + if (canLoginWithEmail && canLoginWithUsername) { + return 'emailOrUsername' + } + if (canLoginWithUsername) { + return 'username' + } return 'email' }) diff --git a/packages/next/src/views/Root/isPathMatchingRoute.ts b/packages/next/src/views/Root/isPathMatchingRoute.ts index 4b03fb947..11f175cf9 100644 --- a/packages/next/src/views/Root/isPathMatchingRoute.ts +++ b/packages/next/src/views/Root/isPathMatchingRoute.ts @@ -25,6 +25,10 @@ export const isPathMatchingRoute = ({ const match = regex.exec(currentRoute) const viewRoute = match?.[0] || viewPath - if (exact) return currentRoute === viewRoute - if (!exact) return viewRoute.startsWith(currentRoute) + if (exact) { + return currentRoute === viewRoute + } + if (!exact) { + return viewRoute.startsWith(currentRoute) + } } diff --git a/packages/next/src/views/Verify/index.tsx b/packages/next/src/views/Verify/index.tsx index 069a793ce..5bd0836a1 100644 --- a/packages/next/src/views/Verify/index.tsx +++ b/packages/next/src/views/Verify/index.tsx @@ -43,7 +43,9 @@ export const Verify: React.FC = async ({ return redirect(formatAdminURL({ adminRoute, path: '/login' })) } catch (e) { // already verified - if (e?.status === 202) redirect(formatAdminURL({ adminRoute, path: '/login' })) + if (e?.status === 202) { + redirect(formatAdminURL({ adminRoute, path: '/login' })) + } textToRender = req.t('authentication:unableToVerify') } diff --git a/packages/next/src/views/Version/RenderFieldsToDiff/fields/Iterable/index.tsx b/packages/next/src/views/Version/RenderFieldsToDiff/fields/Iterable/index.tsx index 34bd2fe2e..b9c8b1aa3 100644 --- a/packages/next/src/views/Version/RenderFieldsToDiff/fields/Iterable/index.tsx +++ b/packages/next/src/views/Version/RenderFieldsToDiff/fields/Iterable/index.tsx @@ -43,7 +43,9 @@ const Iterable: React.FC = ({ let fields: ClientField[] = [] - if (field.type === 'array' && 'fields' in field) fields = field.fields + if (field.type === 'array' && 'fields' in field) { + fields = field.fields + } if (field.type === 'blocks') { fields = [ diff --git a/packages/next/src/views/Version/RenderFieldsToDiff/fields/Select/index.tsx b/packages/next/src/views/Version/RenderFieldsToDiff/fields/Select/index.tsx index e19fe02ec..46a474dde 100644 --- a/packages/next/src/views/Version/RenderFieldsToDiff/fields/Select/index.tsx +++ b/packages/next/src/views/Version/RenderFieldsToDiff/fields/Select/index.tsx @@ -55,7 +55,9 @@ const Select: React.FC> = ({ }) => { let placeholder = '' - if (version === comparison) placeholder = `[${i18n.t('general:noValue')}]` + if (version === comparison) { + placeholder = `[${i18n.t('general:noValue')}]` + } const options = 'options' in field && field.options diff --git a/packages/next/src/views/Version/RenderFieldsToDiff/fields/Text/index.tsx b/packages/next/src/views/Version/RenderFieldsToDiff/fields/Text/index.tsx index e6fad3138..8b9520d5d 100644 --- a/packages/next/src/views/Version/RenderFieldsToDiff/fields/Text/index.tsx +++ b/packages/next/src/views/Version/RenderFieldsToDiff/fields/Text/index.tsx @@ -24,14 +24,20 @@ const Text: React.FC> = ({ }) => { let placeholder = '' - if (version === comparison) placeholder = `[${i18n.t('general:noValue')}]` + if (version === comparison) { + placeholder = `[${i18n.t('general:noValue')}]` + } let versionToRender = version let comparisonToRender = comparison if (isRichText) { - if (typeof version === 'object') versionToRender = JSON.stringify(version, null, 2) - if (typeof comparison === 'object') comparisonToRender = JSON.stringify(comparison, null, 2) + if (typeof version === 'object') { + versionToRender = JSON.stringify(version, null, 2) + } + if (typeof comparison === 'object') { + comparisonToRender = JSON.stringify(comparison, null, 2) + } } return ( diff --git a/packages/next/src/views/Version/RenderFieldsToDiff/index.tsx b/packages/next/src/views/Version/RenderFieldsToDiff/index.tsx index 3757f9757..c19679b21 100644 --- a/packages/next/src/views/Version/RenderFieldsToDiff/index.tsx +++ b/packages/next/src/views/Version/RenderFieldsToDiff/index.tsx @@ -29,7 +29,9 @@ const RenderFieldsToDiff: React.FC = ({ return (
{fields?.map((field, i) => { - if ('name' in field && field.name === 'id') return null + if ('name' in field && field.name === 'id') { + return null + } const Component = diffComponents[field.type] @@ -53,7 +55,9 @@ const RenderFieldsToDiff: React.FC = ({ const subFieldPermissions = fieldPermissions?.[fieldName]?.fields - if (hasPermission === false) return null + if (hasPermission === false) { + return null + } const baseCellProps: FieldDiffProps = { comparison: comparisonValue, diff --git a/packages/next/src/views/Version/SelectComparison/index.tsx b/packages/next/src/views/Version/SelectComparison/index.tsx index 180e70736..fd27d9005 100644 --- a/packages/next/src/views/Version/SelectComparison/index.tsx +++ b/packages/next/src/views/Version/SelectComparison/index.tsx @@ -48,7 +48,9 @@ export const SelectComparison: React.FC = (props) => { const getResults = useCallback( async ({ lastLoadedPage: lastLoadedPageArg }) => { - if (loadedAllOptionsRef.current) return + if (loadedAllOptionsRef.current) { + return + } const query: { [key: string]: unknown where: Where diff --git a/packages/next/src/views/Version/SelectLocales/index.tsx b/packages/next/src/views/Version/SelectLocales/index.tsx index 75e144b42..4f67ca78c 100644 --- a/packages/next/src/views/Version/SelectLocales/index.tsx +++ b/packages/next/src/views/Version/SelectLocales/index.tsx @@ -14,7 +14,9 @@ export const SelectLocales: React.FC = ({ onChange, options, value }) => const format = (items) => { return items.map((item) => { - if (typeof item.label === 'string') return item + if (typeof item.label === 'string') { + return item + } if (typeof item.label !== 'string' && item.label[code]) { return { label: item.label[code], diff --git a/packages/next/src/views/Versions/cells/CreatedAt/index.tsx b/packages/next/src/views/Versions/cells/CreatedAt/index.tsx index ce0684aeb..4cbf50221 100644 --- a/packages/next/src/views/Versions/cells/CreatedAt/index.tsx +++ b/packages/next/src/views/Versions/cells/CreatedAt/index.tsx @@ -32,17 +32,19 @@ export const CreatedAtCell: React.FC = ({ let to: string - if (collectionSlug) + if (collectionSlug) { to = formatAdminURL({ adminRoute, path: `/collections/${collectionSlug}/${docID}/versions/${versionID}`, }) + } - if (globalSlug) + if (globalSlug) { to = formatAdminURL({ adminRoute, path: `/globals/${globalSlug}/versions/${versionID}`, }) + } return ( diff --git a/packages/payload/src/auth/executeAccess.ts b/packages/payload/src/auth/executeAccess.ts index 8ac52baee..7616d819c 100644 --- a/packages/payload/src/auth/executeAccess.ts +++ b/packages/payload/src/auth/executeAccess.ts @@ -23,7 +23,9 @@ const executeAccess = async ( }) if (!result) { - if (!disableErrors) throw new Forbidden(req.t) + if (!disableErrors) { + throw new Forbidden(req.t) + } } return result @@ -33,7 +35,9 @@ const executeAccess = async ( return true } - if (!disableErrors) throw new Forbidden(req.t) + if (!disableErrors) { + throw new Forbidden(req.t) + } return false } diff --git a/packages/payload/src/auth/getAuthFields.ts b/packages/payload/src/auth/getAuthFields.ts index e02803d5f..be8bf085b 100644 --- a/packages/payload/src/auth/getAuthFields.ts +++ b/packages/payload/src/auth/getAuthFields.ts @@ -32,7 +32,9 @@ export const getBaseAuthFields = (authConfig: IncomingAuthType): Field[] => { } authFields.push(emailField) - if (usernameField) authFields.push(usernameField) + if (usernameField) { + authFields.push(usernameField) + } authFields.push(...baseAuthFields) diff --git a/packages/payload/src/auth/isLocked.ts b/packages/payload/src/auth/isLocked.ts index a8ff78589..95efbea80 100644 --- a/packages/payload/src/auth/isLocked.ts +++ b/packages/payload/src/auth/isLocked.ts @@ -1,5 +1,7 @@ const isLocked = (date: number): boolean => { - if (!date) return false + if (!date) { + return false + } return date > Date.now() } export default isLocked diff --git a/packages/payload/src/auth/operations/auth.ts b/packages/payload/src/auth/operations/auth.ts index 2e5e924c5..2df9470c8 100644 --- a/packages/payload/src/auth/operations/auth.ts +++ b/packages/payload/src/auth/operations/auth.ts @@ -39,7 +39,9 @@ export const auth = async (args: Required): Promise => { req, }) - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return { permissions, diff --git a/packages/payload/src/auth/operations/forgotPassword.ts b/packages/payload/src/auth/operations/forgotPassword.ts index 609086b6f..5579f78ec 100644 --- a/packages/payload/src/auth/operations/forgotPassword.ts +++ b/packages/payload/src/auth/operations/forgotPassword.ts @@ -128,7 +128,9 @@ export const forgotPasswordOperation = async ( // We don't want to indicate specifically that an email was not found, // as doing so could lead to the exposure of registered emails. // Therefore, we prefer to fail silently. - if (!user) return null + if (!user) { + return null + } user.resetPasswordToken = token user.resetPasswordExpiration = new Date(expiration || Date.now() + 3600000).toISOString() // 1 hour @@ -197,7 +199,9 @@ export const forgotPasswordOperation = async ( result: token, }) - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return token } catch (error: unknown) { diff --git a/packages/payload/src/auth/operations/login.ts b/packages/payload/src/auth/operations/login.ts index 1b385b417..d3d037549 100644 --- a/packages/payload/src/auth/operations/login.ts +++ b/packages/payload/src/auth/operations/login.ts @@ -202,7 +202,9 @@ export const loginOperation = async ( }) } - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } throw new AuthenticationError(req.t) } @@ -332,7 +334,9 @@ export const loginOperation = async ( // Return results // ///////////////////////////////////// - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/auth/operations/logout.ts b/packages/payload/src/auth/operations/logout.ts index a84b4476a..1e76c2e04 100644 --- a/packages/payload/src/auth/operations/logout.ts +++ b/packages/payload/src/auth/operations/logout.ts @@ -18,9 +18,12 @@ export const logoutOperation = async (incomingArgs: Arguments): Promise req, } = incomingArgs - if (!user) throw new APIError('No User', httpStatus.BAD_REQUEST) - if (user.collection !== collectionConfig.slug) + if (!user) { + throw new APIError('No User', httpStatus.BAD_REQUEST) + } + if (user.collection !== collectionConfig.slug) { throw new APIError('Incorrect collection', httpStatus.FORBIDDEN) + } await collectionConfig.hooks.afterLogout.reduce(async (priorHook, hook) => { await priorHook diff --git a/packages/payload/src/auth/operations/me.ts b/packages/payload/src/auth/operations/me.ts index c997c0206..1774277a0 100644 --- a/packages/payload/src/auth/operations/me.ts +++ b/packages/payload/src/auth/operations/me.ts @@ -69,8 +69,12 @@ export const meOperation = async (args: Arguments): Promise = if (currentToken) { const decoded = jwt.decode(currentToken) as jwt.JwtPayload - if (decoded) result.exp = decoded.exp - if (!collection.config.auth.removeTokenFromResponses) result.token = currentToken + if (decoded) { + result.exp = decoded.exp + } + if (!collection.config.auth.removeTokenFromResponses) { + result.token = currentToken + } } } } diff --git a/packages/payload/src/auth/operations/refresh.ts b/packages/payload/src/auth/operations/refresh.ts index bea626581..d0dbb7e31 100644 --- a/packages/payload/src/auth/operations/refresh.ts +++ b/packages/payload/src/auth/operations/refresh.ts @@ -62,7 +62,9 @@ export const refreshOperation = async (incomingArgs: Arguments): Promise }, } = args - if (!args.req.user) throw new Forbidden(args.req.t) + if (!args.req.user) { + throw new Forbidden(args.req.t) + } const parsedURL = url.parse(args.req.url) const isGraphQL = parsedURL.pathname === config.routes.graphQL @@ -143,7 +145,9 @@ export const refreshOperation = async (incomingArgs: Arguments): Promise // Return results // ///////////////////////////////////// - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/auth/operations/registerFirstUser.ts b/packages/payload/src/auth/operations/registerFirstUser.ts index a8cb4997a..66ce4d727 100644 --- a/packages/payload/src/auth/operations/registerFirstUser.ts +++ b/packages/payload/src/auth/operations/registerFirstUser.ts @@ -58,7 +58,9 @@ export const registerFirstUserOperation = async ( req, }) - if (doc) throw new Forbidden(req.t) + if (doc) { + throw new Forbidden(req.t) + } // ///////////////////////////////////// // Register first user @@ -93,7 +95,9 @@ export const registerFirstUserOperation = async ( req, }) - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return { exp, diff --git a/packages/payload/src/auth/operations/resetPassword.ts b/packages/payload/src/auth/operations/resetPassword.ts index bfc8b2757..ac430e42a 100644 --- a/packages/payload/src/auth/operations/resetPassword.ts +++ b/packages/payload/src/auth/operations/resetPassword.ts @@ -64,7 +64,9 @@ export const resetPasswordOperation = async (args: Arguments): Promise = }, }) - if (!user) throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN) + if (!user) { + throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN) + } // TODO: replace this method const { hash, salt } = await generatePasswordSaltHash({ @@ -108,7 +110,9 @@ export const resetPasswordOperation = async (args: Arguments): Promise = overrideAccess, req, }) - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } const result = { token, diff --git a/packages/payload/src/auth/operations/unlock.ts b/packages/payload/src/auth/operations/unlock.ts index 96ee64b6c..f6d331835 100644 --- a/packages/payload/src/auth/operations/unlock.ts +++ b/packages/payload/src/auth/operations/unlock.ts @@ -102,7 +102,9 @@ export const unlockOperation = async ( result = null } - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/auth/operations/verifyEmail.ts b/packages/payload/src/auth/operations/verifyEmail.ts index ae4a157d2..0ae94c1f1 100644 --- a/packages/payload/src/auth/operations/verifyEmail.ts +++ b/packages/payload/src/auth/operations/verifyEmail.ts @@ -31,9 +31,12 @@ export const verifyEmailOperation = async (args: Args): Promise => { }, }) - if (!user) throw new APIError('Verification token is invalid.', httpStatus.FORBIDDEN) - if (user && user._verified === true) + if (!user) { + throw new APIError('Verification token is invalid.', httpStatus.FORBIDDEN) + } + if (user && user._verified === true) { throw new APIError('This account has already been activated.', httpStatus.ACCEPTED) + } await req.payload.db.updateOne({ id: user.id, @@ -46,7 +49,9 @@ export const verifyEmailOperation = async (args: Args): Promise => { req, }) - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return true } catch (error: unknown) { diff --git a/packages/payload/src/auth/strategies/local/authenticate.ts b/packages/payload/src/auth/strategies/local/authenticate.ts index 16df3213f..6170c7b73 100644 --- a/packages/payload/src/auth/strategies/local/authenticate.ts +++ b/packages/payload/src/auth/strategies/local/authenticate.ts @@ -17,7 +17,9 @@ export const authenticateLocalStrategy = async ({ doc, password }: Args): Promis if (typeof salt === 'string' && typeof hash === 'string') { const res = await new Promise((resolve, reject) => { crypto.pbkdf2(password, salt, 25000, 512, 'sha256', (e, hashBuffer) => { - if (e) reject(null) + if (e) { + reject(null) + } if (scmp(hashBuffer, Buffer.from(hash, 'hex'))) { resolve(doc) diff --git a/packages/payload/src/auth/strategies/local/register.ts b/packages/payload/src/auth/strategies/local/register.ts index 0a19df9d8..1ea35110f 100644 --- a/packages/payload/src/auth/strategies/local/register.ts +++ b/packages/payload/src/auth/strategies/local/register.ts @@ -78,7 +78,9 @@ export const registerLocalStrategy = async ({ const { hash, salt } = await generatePasswordSaltHash({ collection, password, req }) const sanitizedDoc = { ...doc } - if (sanitizedDoc.password) delete sanitizedDoc.password + if (sanitizedDoc.password) { + delete sanitizedDoc.password + } return payload.db.create({ collection: collection.slug, diff --git a/packages/payload/src/auth/strategies/local/resetLoginAttempts.ts b/packages/payload/src/auth/strategies/local/resetLoginAttempts.ts index 739323447..4231a466c 100644 --- a/packages/payload/src/auth/strategies/local/resetLoginAttempts.ts +++ b/packages/payload/src/auth/strategies/local/resetLoginAttempts.ts @@ -15,7 +15,9 @@ export const resetLoginAttempts = async ({ payload, req, }: Args): Promise => { - if (!('lockUntil' in doc && typeof doc.lockUntil === 'string') || doc.loginAttempts === 0) return + if (!('lockUntil' in doc && typeof doc.lockUntil === 'string') || doc.loginAttempts === 0) { + return + } await payload.update({ id: doc.id, collection: collection.slug, diff --git a/packages/payload/src/bin/generateTypes.ts b/packages/payload/src/bin/generateTypes.ts index 9e68f8709..c9ccb2630 100644 --- a/packages/payload/src/bin/generateTypes.ts +++ b/packages/payload/src/bin/generateTypes.ts @@ -15,7 +15,9 @@ export async function generateTypes( const shouldLog = options?.log ?? true - if (shouldLog) logger.info('Compiling TS types for Collections and Globals...') + if (shouldLog) { + logger.info('Compiling TS types for Collections and Globals...') + } const jsonSchema = configToJSONSchema(config, config.db.defaultIDType) @@ -54,5 +56,7 @@ export async function generateTypes( } fs.writeFileSync(outputFile, compiled) - if (shouldLog) logger.info(`Types written to ${outputFile}`) + if (shouldLog) { + logger.info(`Types written to ${outputFile}`) + } } diff --git a/packages/payload/src/bin/index.ts b/packages/payload/src/bin/index.ts index 666f9df80..97633b514 100755 --- a/packages/payload/src/bin/index.ts +++ b/packages/payload/src/bin/index.ts @@ -51,7 +51,9 @@ export const bin = async () => { const configPath = findConfig() const configPromise = await import(pathToFileURL(configPath).toString()) let config = await configPromise - if (config.default) config = await config.default + if (config.default) { + config = await config.default + } const userBinScript = Array.isArray(config.bin) ? config.bin.find(({ key }) => key === script) diff --git a/packages/payload/src/collections/config/sanitize.ts b/packages/payload/src/collections/config/sanitize.ts index 355c5a52b..50d97c931 100644 --- a/packages/payload/src/collections/config/sanitize.ts +++ b/packages/payload/src/collections/config/sanitize.ts @@ -50,8 +50,12 @@ export const sanitizeCollection = async ( let hasCreatedAt = null sanitized.fields.some((field) => { if (fieldAffectsData(field)) { - if (field.name === 'updatedAt') hasUpdatedAt = true - if (field.name === 'createdAt') hasCreatedAt = true + if (field.name === 'updatedAt') { + hasUpdatedAt = true + } + if (field.name === 'createdAt') { + hasCreatedAt = true + } } return hasCreatedAt && hasUpdatedAt }) @@ -84,7 +88,9 @@ export const sanitizeCollection = async ( sanitized.labels = sanitized.labels || formatLabels(sanitized.slug) if (sanitized.versions) { - if (sanitized.versions === true) sanitized.versions = { drafts: false } + if (sanitized.versions === true) { + sanitized.versions = { drafts: false } + } if (sanitized.timestamps === false) { throw new TimestampsRequired(collection) @@ -113,7 +119,9 @@ export const sanitizeCollection = async ( } if (sanitized.upload) { - if (sanitized.upload === true) sanitized.upload = {} + if (sanitized.upload === true) { + sanitized.upload = {} + } // sanitize fields for reserved names sanitizeUploadFields(sanitized.fields, sanitized) diff --git a/packages/payload/src/collections/dataloader.ts b/packages/payload/src/collections/dataloader.ts index dac7df990..3b7c9ef1e 100644 --- a/packages/payload/src/collections/dataloader.ts +++ b/packages/payload/src/collections/dataloader.ts @@ -75,7 +75,9 @@ const batchAndLoadDocs = let sanitizedID: number | string = id - if (idType === 'number') sanitizedID = parseFloat(id) + if (idType === 'number') { + sanitizedID = parseFloat(id) + } if (isValidID(sanitizedID, idType)) { return { diff --git a/packages/payload/src/collections/operations/create.ts b/packages/payload/src/collections/operations/create.ts index 2d5c88f07..fd239fd7a 100644 --- a/packages/payload/src/collections/operations/create.ts +++ b/packages/payload/src/collections/operations/create.ts @@ -364,7 +364,9 @@ export const createOperation = async ( // Return results // ///////////////////////////////////// - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/collections/operations/delete.ts b/packages/payload/src/collections/operations/delete.ts index 8c7396702..8209e134e 100644 --- a/packages/payload/src/collections/operations/delete.ts +++ b/packages/payload/src/collections/operations/delete.ts @@ -261,7 +261,9 @@ export const deleteOperation = async ( result, }) - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/collections/operations/deleteByID.ts b/packages/payload/src/collections/operations/deleteByID.ts index a2929d7ee..f72192a5c 100644 --- a/packages/payload/src/collections/operations/deleteByID.ts +++ b/packages/payload/src/collections/operations/deleteByID.ts @@ -102,8 +102,12 @@ export const deleteByIDOperation = async ( where: combineQueries({ id: { equals: id } }, accessResults), }) - if (!docToDelete && !hasWhereAccess) throw new NotFound(req.t) - if (!docToDelete && hasWhereAccess) throw new Forbidden(req.t) + if (!docToDelete && !hasWhereAccess) { + throw new NotFound(req.t) + } + if (!docToDelete && hasWhereAccess) { + throw new Forbidden(req.t) + } await deleteAssociatedFiles({ collectionConfig, @@ -213,7 +217,9 @@ export const deleteByIDOperation = async ( // 8. Return results // ///////////////////////////////////// - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/collections/operations/duplicate.ts b/packages/payload/src/collections/operations/duplicate.ts index 7de7701c8..4b1466e7e 100644 --- a/packages/payload/src/collections/operations/duplicate.ts +++ b/packages/payload/src/collections/operations/duplicate.ts @@ -101,8 +101,12 @@ export const duplicateOperation = async ( req, }) - if (!docWithLocales && !hasWherePolicy) throw new NotFound(req.t) - if (!docWithLocales && hasWherePolicy) throw new Forbidden(req.t) + if (!docWithLocales && !hasWherePolicy) { + throw new NotFound(req.t) + } + if (!docWithLocales && hasWherePolicy) { + throw new Forbidden(req.t) + } // remove the createdAt timestamp and id to rely on the db to set the default it delete docWithLocales.createdAt @@ -324,7 +328,9 @@ export const duplicateOperation = async ( // Return results // ///////////////////////////////////// - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/collections/operations/findByID.ts b/packages/payload/src/collections/operations/findByID.ts index 98ec17f6f..a77eefaa0 100644 --- a/packages/payload/src/collections/operations/findByID.ts +++ b/packages/payload/src/collections/operations/findByID.ts @@ -68,7 +68,9 @@ export const findByIDOperation = async ( : true // If errors are disabled, and access returns false, return null - if (accessResult === false) return null + if (accessResult === false) { + return null + } const findOneArgs: FindOneArgs = { collection: collectionConfig.slug, @@ -83,7 +85,9 @@ export const findByIDOperation = async ( // Find by ID // ///////////////////////////////////// - if (!findOneArgs.where.and[0].id) throw new NotFound(t) + if (!findOneArgs.where.and[0].id) { + throw new NotFound(t) + } let result: DataFromCollectionSlug = await req.payload.db.findOne(findOneArgs) diff --git a/packages/payload/src/collections/operations/findVersionByID.ts b/packages/payload/src/collections/operations/findVersionByID.ts index 538de3598..b08b795c1 100644 --- a/packages/payload/src/collections/operations/findVersionByID.ts +++ b/packages/payload/src/collections/operations/findVersionByID.ts @@ -50,7 +50,9 @@ export const findVersionByIDOperation = async ( : true // If errors are disabled, and access returns false, return null - if (accessResults === false) return null + if (accessResults === false) { + return null + } const hasWhereAccess = typeof accessResults === 'object' @@ -73,8 +75,12 @@ export const findVersionByIDOperation = async ( if (!result) { if (!disableErrors) { - if (!hasWhereAccess) throw new NotFound(req.t) - if (hasWhereAccess) throw new Forbidden(req.t) + if (!hasWhereAccess) { + throw new NotFound(req.t) + } + if (hasWhereAccess) { + throw new Forbidden(req.t) + } } return null diff --git a/packages/payload/src/collections/operations/restoreVersion.ts b/packages/payload/src/collections/operations/restoreVersion.ts index 70f81b8d0..e81a531a5 100644 --- a/packages/payload/src/collections/operations/restoreVersion.ts +++ b/packages/payload/src/collections/operations/restoreVersion.ts @@ -87,8 +87,12 @@ export const restoreVersionOperation = async ( const doc = await req.payload.db.findOne(findOneArgs) - if (!doc && !hasWherePolicy) throw new NotFound(req.t) - if (!doc && hasWherePolicy) throw new Forbidden(req.t) + if (!doc && !hasWherePolicy) { + throw new NotFound(req.t) + } + if (!doc && hasWherePolicy) { + throw new Forbidden(req.t) + } // ///////////////////////////////////// // fetch previousDoc diff --git a/packages/payload/src/collections/operations/update.ts b/packages/payload/src/collections/operations/update.ts index 3e1e49d8f..68a2b9d2a 100644 --- a/packages/payload/src/collections/operations/update.ts +++ b/packages/payload/src/collections/operations/update.ts @@ -428,7 +428,9 @@ export const updateOperation = async ( result, }) - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/collections/operations/updateByID.ts b/packages/payload/src/collections/operations/updateByID.ts index 0a07606c0..50eeecea6 100644 --- a/packages/payload/src/collections/operations/updateByID.ts +++ b/packages/payload/src/collections/operations/updateByID.ts @@ -127,8 +127,12 @@ export const updateByIDOperation = async ( req, }) - if (!docWithLocales && !hasWherePolicy) throw new NotFound(req.t) - if (!docWithLocales && hasWherePolicy) throw new Forbidden(req.t) + if (!docWithLocales && !hasWherePolicy) { + throw new NotFound(req.t) + } + if (!docWithLocales && hasWherePolicy) { + throw new Forbidden(req.t) + } const originalDoc = await afterRead({ collection: collectionConfig, @@ -404,7 +408,9 @@ export const updateByIDOperation = async ( // Return results // ///////////////////////////////////// - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/config/find.ts b/packages/payload/src/config/find.ts index 1671da8e6..9c9ca9d1e 100644 --- a/packages/payload/src/config/find.ts +++ b/packages/payload/src/config/find.ts @@ -71,7 +71,9 @@ export const findConfig = (): string => { : [configPath, srcPath, rootPath] for (const searchPath of searchPaths) { - if (!searchPath) continue + if (!searchPath) { + continue + } const configPath = findUpSync( (dir) => { @@ -106,13 +108,17 @@ export const findConfig = (): string => { cwd: path.resolve(process.cwd(), 'dist'), }) - if (distConfigPath) return distConfigPath + if (distConfigPath) { + return distConfigPath + } } else { const srcConfigPath = findUpSync(['payload.config.js', 'payload.config.ts'], { cwd: path.resolve(process.cwd(), 'src'), }) - if (srcConfigPath) return srcConfigPath + if (srcConfigPath) { + return srcConfigPath + } } throw new Error( diff --git a/packages/payload/src/config/sanitize.ts b/packages/payload/src/config/sanitize.ts index 5727fa6bc..d70448ca7 100644 --- a/packages/payload/src/config/sanitize.ts +++ b/packages/payload/src/config/sanitize.ts @@ -173,13 +173,17 @@ export const sanitizeConfig = async (incomingConfig: Config): Promise c.upload?.adapter).filter(Boolean)), ) // Pass through the email config as is so adapters don't break - if (incomingConfig.email) config.email = incomingConfig.email + if (incomingConfig.email) { + config.email = incomingConfig.email + } /* Execute richText sanitization diff --git a/packages/payload/src/database/combineQueries.ts b/packages/payload/src/database/combineQueries.ts index 763dce364..ee0f4e4cb 100644 --- a/packages/payload/src/database/combineQueries.ts +++ b/packages/payload/src/database/combineQueries.ts @@ -3,14 +3,20 @@ import type { Where } from '../types/index.js' import { hasWhereAccessResult } from '../auth/index.js' export const combineQueries = (where: Where, access: Where | boolean): Where => { - if (!where && !access) return {} + if (!where && !access) { + return {} + } const result: Where = { and: [], } - if (where) result.and.push(where) - if (hasWhereAccessResult(access)) result.and.push(access) + if (where) { + result.and.push(where) + } + if (hasWhereAccessResult(access)) { + result.and.push(access) + } return result } diff --git a/packages/payload/src/database/getLocalizedPaths.ts b/packages/payload/src/database/getLocalizedPaths.ts index ff864118b..07e731ef7 100644 --- a/packages/payload/src/database/getLocalizedPaths.ts +++ b/packages/payload/src/database/getLocalizedPaths.ts @@ -154,7 +154,9 @@ export async function getLocalizedPaths({ lastIncompletePath.fields = flattenFields(lastIncompletePath.field.fields, false) } - if (i + 1 === pathSegments.length) lastIncompletePath.complete = true + if (i + 1 === pathSegments.length) { + lastIncompletePath.complete = true + } lastIncompletePath.path = currentPath } } diff --git a/packages/payload/src/database/migrations/readMigrationFiles.ts b/packages/payload/src/database/migrations/readMigrationFiles.ts index 480f29960..8087a7f13 100644 --- a/packages/payload/src/database/migrations/readMigrationFiles.ts +++ b/packages/payload/src/database/migrations/readMigrationFiles.ts @@ -41,7 +41,9 @@ export const readMigrationFiles = async ({ typeof require === 'function' ? await eval(`require('${filePath.replaceAll('\\', '/')}')`) : await eval(`import('${pathToFileURL(filePath).href}')`) - if ('default' in migration) migration = migration.default + if ('default' in migration) { + migration = migration.default + } const result: Migration = { name: path.basename(filePath).split('.')?.[0], diff --git a/packages/payload/src/fields/config/sanitize.ts b/packages/payload/src/fields/config/sanitize.ts index 9b5804438..36c415e2f 100644 --- a/packages/payload/src/fields/config/sanitize.ts +++ b/packages/payload/src/fields/config/sanitize.ts @@ -53,7 +53,9 @@ export const sanitizeFields = async ({ richTextSanitizationPromises, validRelationships, }: Args): Promise => { - if (!fields) return [] + if (!fields) { + return [] + } for (let i = 0; i < fields.length; i++) { const field = fields[i] @@ -62,7 +64,9 @@ export const sanitizeFields = async ({ continue } - if (!field.type) throw new MissingFieldType(field) + if (!field.type) { + throw new MissingFieldType(field) + } // assert that field names do not contain forbidden characters if (fieldAffectsData(field) && field.name.includes('.')) { @@ -160,8 +164,12 @@ export const sanitizeFields = async ({ } } - if (!field.hooks) field.hooks = {} - if (!field.access) field.access = {} + if (!field.hooks) { + field.hooks = {} + } + if (!field.access) { + field.access = {} + } setDefaultBeforeDuplicate(field) } diff --git a/packages/payload/src/fields/hooks/afterRead/index.ts b/packages/payload/src/fields/hooks/afterRead/index.ts index 30dfc2c54..00aa5f969 100644 --- a/packages/payload/src/fields/hooks/afterRead/index.ts +++ b/packages/payload/src/fields/hooks/afterRead/index.ts @@ -58,7 +58,9 @@ export async function afterRead(args: Args): Promise incomingDepth || incomingDepth === 0 ? parseInt(String(incomingDepth), 10) : req.payload.config.defaultDepth - if (depth > req.payload.config.maxDepth) depth = req.payload.config.maxDepth + if (depth > req.payload.config.maxDepth) { + depth = req.payload.config.maxDepth + } const currentDepth = incomingCurrentDepth || 1 diff --git a/packages/payload/src/fields/hooks/afterRead/promise.ts b/packages/payload/src/fields/hooks/afterRead/promise.ts index 810765752..0925f23d1 100644 --- a/packages/payload/src/fields/hooks/afterRead/promise.ts +++ b/packages/payload/src/fields/hooks/afterRead/promise.ts @@ -313,7 +313,9 @@ export const promise = async ({ switch (field.type) { case 'group': { let groupDoc = siblingDoc[field.name] as JsonObject - if (typeof siblingDoc[field.name] !== 'object') groupDoc = {} + if (typeof siblingDoc[field.name] !== 'object') { + groupDoc = {} + } traverseFields({ collection, @@ -524,7 +526,9 @@ export const promise = async ({ let tabDoc = siblingDoc if (tabHasName(field)) { tabDoc = siblingDoc[field.name] as JsonObject - if (typeof siblingDoc[field.name] !== 'object') tabDoc = {} + if (typeof siblingDoc[field.name] !== 'object') { + tabDoc = {} + } } traverseFields({ diff --git a/packages/payload/src/fields/hooks/beforeChange/getExistingRowDoc.ts b/packages/payload/src/fields/hooks/beforeChange/getExistingRowDoc.ts index fd2df3357..289660e98 100644 --- a/packages/payload/src/fields/hooks/beforeChange/getExistingRowDoc.ts +++ b/packages/payload/src/fields/hooks/beforeChange/getExistingRowDoc.ts @@ -10,13 +10,17 @@ export const getExistingRowDoc = (incomingRow: JsonObject, existingRows?: unknow if (incomingRow.id && Array.isArray(existingRows)) { const matchedExistingRow = existingRows.find((existingRow) => { if (typeof existingRow === 'object' && 'id' in existingRow) { - if (existingRow.id === incomingRow.id) return existingRow + if (existingRow.id === incomingRow.id) { + return existingRow + } } return false }) - if (matchedExistingRow) return matchedExistingRow + if (matchedExistingRow) { + return matchedExistingRow + } } return {} diff --git a/packages/payload/src/fields/hooks/beforeChange/promise.ts b/packages/payload/src/fields/hooks/beforeChange/promise.ts index 5606b755a..28f3bbfb4 100644 --- a/packages/payload/src/fields/hooks/beforeChange/promise.ts +++ b/packages/payload/src/fields/hooks/beforeChange/promise.ts @@ -233,10 +233,15 @@ export const promise = async ({ } case 'group': { - if (typeof siblingData[field.name] !== 'object') siblingData[field.name] = {} - if (typeof siblingDoc[field.name] !== 'object') siblingDoc[field.name] = {} - if (typeof siblingDocWithLocales[field.name] !== 'object') + if (typeof siblingData[field.name] !== 'object') { + siblingData[field.name] = {} + } + if (typeof siblingDoc[field.name] !== 'object') { + siblingDoc[field.name] = {} + } + if (typeof siblingDocWithLocales[field.name] !== 'object') { siblingDocWithLocales[field.name] = {} + } await traverseFields({ id, @@ -384,10 +389,15 @@ export const promise = async ({ let tabSiblingDocWithLocales = siblingDocWithLocales if (tabHasName(field)) { - if (typeof siblingData[field.name] !== 'object') siblingData[field.name] = {} - if (typeof siblingDoc[field.name] !== 'object') siblingDoc[field.name] = {} - if (typeof siblingDocWithLocales[field.name] !== 'object') + if (typeof siblingData[field.name] !== 'object') { + siblingData[field.name] = {} + } + if (typeof siblingDoc[field.name] !== 'object') { + siblingDoc[field.name] = {} + } + if (typeof siblingDocWithLocales[field.name] !== 'object') { siblingDocWithLocales[field.name] = {} + } tabSiblingData = siblingData[field.name] as JsonObject tabSiblingDoc = siblingDoc[field.name] as JsonObject diff --git a/packages/payload/src/fields/hooks/beforeValidate/promise.ts b/packages/payload/src/fields/hooks/beforeValidate/promise.ts index fc06a44b5..e2dbd77a2 100644 --- a/packages/payload/src/fields/hooks/beforeValidate/promise.ts +++ b/packages/payload/src/fields/hooks/beforeValidate/promise.ts @@ -109,9 +109,15 @@ export const promise = async ({ } case 'checkbox': { - if (siblingData[field.name] === 'true') siblingData[field.name] = true - if (siblingData[field.name] === 'false') siblingData[field.name] = false - if (siblingData[field.name] === '') siblingData[field.name] = false + if (siblingData[field.name] === 'true') { + siblingData[field.name] = true + } + if (siblingData[field.name] === 'false') { + siblingData[field.name] = false + } + if (siblingData[field.name] === '') { + siblingData[field.name] = false + } break } @@ -293,8 +299,12 @@ export const promise = async ({ // Traverse subfields switch (field.type) { case 'group': { - if (typeof siblingData[field.name] !== 'object') siblingData[field.name] = {} - if (typeof siblingDoc[field.name] !== 'object') siblingDoc[field.name] = {} + if (typeof siblingData[field.name] !== 'object') { + siblingData[field.name] = {} + } + if (typeof siblingDoc[field.name] !== 'object') { + siblingDoc[field.name] = {} + } const groupData = siblingData[field.name] as Record const groupDoc = siblingDoc[field.name] as Record @@ -414,8 +424,12 @@ export const promise = async ({ let tabSiblingData let tabSiblingDoc if (tabHasName(field)) { - if (typeof siblingData[field.name] !== 'object') siblingData[field.name] = {} - if (typeof siblingDoc[field.name] !== 'object') siblingDoc[field.name] = {} + if (typeof siblingData[field.name] !== 'object') { + siblingData[field.name] = {} + } + if (typeof siblingDoc[field.name] !== 'object') { + siblingDoc[field.name] = {} + } tabSiblingData = siblingData[field.name] as Record tabSiblingDoc = siblingDoc[field.name] as Record diff --git a/packages/payload/src/fields/validations.ts b/packages/payload/src/fields/validations.ts index f58c2ab1d..fb74756c5 100644 --- a/packages/payload/src/fields/validations.ts +++ b/packages/payload/src/fields/validations.ts @@ -50,16 +50,24 @@ export const text: TextFieldValidation = ( let maxLength: number if (!required) { - if (!value) return true + if (!value) { + return true + } } if (hasMany === true) { const lengthValidationResult = validateArrayLength(value, { maxRows, minRows, required, t }) - if (typeof lengthValidationResult === 'string') return lengthValidationResult + if (typeof lengthValidationResult === 'string') { + return lengthValidationResult + } } - if (typeof config?.defaultMaxTextLength === 'number') maxLength = config.defaultMaxTextLength - if (typeof fieldMaxLength === 'number') maxLength = fieldMaxLength + if (typeof config?.defaultMaxTextLength === 'number') { + maxLength = config.defaultMaxTextLength + } + if (typeof fieldMaxLength === 'number') { + maxLength = fieldMaxLength + } const stringsToValidate: string[] = Array.isArray(value) ? value : [value] @@ -99,8 +107,12 @@ export const password: PasswordFieldValidation = ( ) => { let maxLength: number - if (typeof config?.defaultMaxTextLength === 'number') maxLength = config.defaultMaxTextLength - if (typeof fieldMaxLength === 'number') maxLength = fieldMaxLength + if (typeof config?.defaultMaxTextLength === 'number') { + maxLength = config.defaultMaxTextLength + } + if (typeof fieldMaxLength === 'number') { + maxLength = fieldMaxLength + } if (value && maxLength && value.length > maxLength) { return t('validation:shorterThanMax', { maxLength }) @@ -201,7 +213,9 @@ export const username: UsernameFieldValidation = ( } } - if (typeof config?.defaultMaxTextLength === 'number') maxLength = config.defaultMaxTextLength + if (typeof config?.defaultMaxTextLength === 'number') { + maxLength = config.defaultMaxTextLength + } if (value && maxLength && value.length > maxLength) { return t('validation:shorterThanMax', { maxLength }) @@ -229,8 +243,12 @@ export const textarea: TextareaFieldValidation = ( ) => { let maxLength: number - if (typeof config?.defaultMaxTextLength === 'number') maxLength = config.defaultMaxTextLength - if (typeof fieldMaxLength === 'number') maxLength = fieldMaxLength + if (typeof config?.defaultMaxTextLength === 'number') { + maxLength = config.defaultMaxTextLength + } + if (typeof fieldMaxLength === 'number') { + maxLength = fieldMaxLength + } if (value && maxLength && value.length > maxLength) { return t('validation:shorterThanMax', { maxLength }) } @@ -282,7 +300,9 @@ export const json: JSONFieldValidation = async ( } const fetchSchema = ({ schema, uri }: Record) => { - if (uri && schema) return schema + if (uri && schema) { + return schema + } // @ts-expect-error return fetch(uri) .then((response) => { @@ -380,7 +400,9 @@ const validateArrayLength = ( const arrayLength = Array.isArray(value) ? value.length : value || 0 - if (!required && arrayLength === 0) return true + if (!required && arrayLength === 0) { + return true + } if (minRows && arrayLength < minRows) { return t('validation:requiresAtLeast', { count: minRows, label: t('general:rows') }) @@ -404,19 +426,27 @@ export const number: NumberFieldValidation = ( ) => { if (hasMany === true) { const lengthValidationResult = validateArrayLength(value, { maxRows, minRows, required, t }) - if (typeof lengthValidationResult === 'string') return lengthValidationResult + if (typeof lengthValidationResult === 'string') { + return lengthValidationResult + } } if (!value && !isNumber(value)) { // if no value is present, validate based on required - if (required) return t('validation:required') - if (!required) return true + if (required) { + return t('validation:required') + } + if (!required) { + return true + } } const numbersToValidate: number[] = Array.isArray(value) ? value : [value] for (const number of numbersToValidate) { - if (!isNumber(number)) return t('validation:enterNumber') + if (!isNumber(number)) { + return t('validation:enterNumber') + } const numberValue = parseFloat(number as unknown as string) @@ -498,7 +528,9 @@ const validateFilterOptions: Validate< and: [{ id: { in: valueIDs } }], } - if (optionFilter && optionFilter !== true) findWhere.and.push(optionFilter) + if (optionFilter && optionFilter !== true) { + findWhere.and.push(optionFilter) + } if (optionFilter === false) { falseCollections.push(collection) @@ -551,7 +583,9 @@ const validateFilterOptions: Validate< return true } - if (!options[collection]) return true + if (!options[collection]) { + return true + } return options[collection].indexOf(requestedID) === -1 }) @@ -627,7 +661,9 @@ export const upload: UploadFieldValidation = async (value, options) => { requestedID = val.value } - if (requestedID === null) return false + if (requestedID === null) { + return false + } const idType = payload.collections[collectionSlug]?.customIDType || payload?.db?.defaultIDType || 'text' @@ -708,7 +744,9 @@ export const relationship: RelationshipFieldValidation = async (value, options) requestedID = val.value } - if (requestedID === null) return false + if (requestedID === null) { + return false + } const idType = payload.collections[collectionSlug]?.customIDType || payload?.db?.defaultIDType || 'text' diff --git a/packages/payload/src/globals/config/sanitize.ts b/packages/payload/src/globals/config/sanitize.ts index 9536204f6..afdd4f507 100644 --- a/packages/payload/src/globals/config/sanitize.ts +++ b/packages/payload/src/globals/config/sanitize.ts @@ -28,18 +28,38 @@ export const sanitizeGlobals = async ( // ///////////////////////////////// global.endpoints = global.endpoints ?? [] - if (!global.hooks) global.hooks = {} - if (!global.access) global.access = {} - if (!global.admin) global.admin = {} + if (!global.hooks) { + global.hooks = {} + } + if (!global.access) { + global.access = {} + } + if (!global.admin) { + global.admin = {} + } - if (!global.access.read) global.access.read = defaultAccess - if (!global.access.update) global.access.update = defaultAccess + if (!global.access.read) { + global.access.read = defaultAccess + } + if (!global.access.update) { + global.access.update = defaultAccess + } - if (!global.hooks.beforeValidate) global.hooks.beforeValidate = [] - if (!global.hooks.beforeChange) global.hooks.beforeChange = [] - if (!global.hooks.afterChange) global.hooks.afterChange = [] - if (!global.hooks.beforeRead) global.hooks.beforeRead = [] - if (!global.hooks.afterRead) global.hooks.afterRead = [] + if (!global.hooks.beforeValidate) { + global.hooks.beforeValidate = [] + } + if (!global.hooks.beforeChange) { + global.hooks.beforeChange = [] + } + if (!global.hooks.afterChange) { + global.hooks.afterChange = [] + } + if (!global.hooks.beforeRead) { + global.hooks.beforeRead = [] + } + if (!global.hooks.afterRead) { + global.hooks.afterRead = [] + } // Sanitize fields const validRelationships = collections.map((c) => c.slug) || [] @@ -52,7 +72,9 @@ export const sanitizeGlobals = async ( }) if (global.versions) { - if (global.versions === true) global.versions = { drafts: false } + if (global.versions === true) { + global.versions = { drafts: false } + } if (global.versions.drafts) { if (global.versions.drafts === true) { @@ -76,7 +98,9 @@ export const sanitizeGlobals = async ( } } - if (!global.custom) global.custom = {} + if (!global.custom) { + global.custom = {} + } // ///////////////////////////////// // Sanitize fields @@ -85,8 +109,12 @@ export const sanitizeGlobals = async ( let hasCreatedAt = null global.fields.some((field) => { if (fieldAffectsData(field)) { - if (field.name === 'updatedAt') hasUpdatedAt = true - if (field.name === 'createdAt') hasCreatedAt = true + if (field.name === 'updatedAt') { + hasUpdatedAt = true + } + if (field.name === 'createdAt') { + hasCreatedAt = true + } } return hasCreatedAt && hasUpdatedAt }) diff --git a/packages/payload/src/globals/operations/docAccess.ts b/packages/payload/src/globals/operations/docAccess.ts index 7d603ae53..bbb340494 100644 --- a/packages/payload/src/globals/operations/docAccess.ts +++ b/packages/payload/src/globals/operations/docAccess.ts @@ -29,7 +29,9 @@ export const docAccessOperation = async (args: Arguments): Promise = an : true // If errors are disabled, and access returns false, return null - if (accessResults === false) return null + if (accessResults === false) { + return null + } const hasWhereAccess = typeof accessResults === 'object' @@ -62,13 +64,19 @@ export const findVersionByIDOperation = async = an // Find by ID // ///////////////////////////////////// - if (!findGlobalVersionsArgs.where.and[0].id) throw new NotFound(req.t) + if (!findGlobalVersionsArgs.where.and[0].id) { + throw new NotFound(req.t) + } const { docs: results } = await payload.db.findGlobalVersions(findGlobalVersionsArgs) if (!results || results?.length === 0) { if (!disableErrors) { - if (!hasWhereAccess) throw new NotFound(req.t) - if (hasWhereAccess) throw new Forbidden(req.t) + if (!hasWhereAccess) { + throw new NotFound(req.t) + } + if (hasWhereAccess) { + throw new Forbidden(req.t) + } } return null diff --git a/packages/payload/src/globals/operations/restoreVersion.ts b/packages/payload/src/globals/operations/restoreVersion.ts index 2804465ea..d50d554b6 100644 --- a/packages/payload/src/globals/operations/restoreVersion.ts +++ b/packages/payload/src/globals/operations/restoreVersion.ts @@ -183,7 +183,9 @@ export const restoreVersionOperation = async = any })) || result }, Promise.resolve()) - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/globals/operations/update.ts b/packages/payload/src/globals/operations/update.ts index d02f77713..96c7fa202 100644 --- a/packages/payload/src/globals/operations/update.ts +++ b/packages/payload/src/globals/operations/update.ts @@ -283,7 +283,9 @@ export const updateOperation = async ( // Return results // ///////////////////////////////////// - if (shouldCommit) await commitTransaction(req) + if (shouldCommit) { + await commitTransaction(req) + } return result } catch (error: unknown) { diff --git a/packages/payload/src/index.ts b/packages/payload/src/index.ts index cda588fee..60dc171be 100644 --- a/packages/payload/src/index.ts +++ b/packages/payload/src/index.ts @@ -461,7 +461,9 @@ export class BasePayload { let customIDType - if (customID?.type === 'number' || customID?.type === 'text') customIDType = customID.type + if (customID?.type === 'number' || customID?.type === 'text') { + customIDType = customID.type + } this.collections[collection.slug] = { config: collection, @@ -554,8 +556,12 @@ export class BasePayload { } if (!options.disableOnInit) { - if (typeof options.onInit === 'function') await options.onInit(this) - if (typeof this.config.onInit === 'function') await this.config.onInit(this) + if (typeof options.onInit === 'function') { + await options.onInit(this) + } + if (typeof this.config.onInit === 'function') { + await this.config.onInit(this) + } } return this diff --git a/packages/payload/src/preferences/operations/findOne.ts b/packages/payload/src/preferences/operations/findOne.ts index a7eb363f0..f9235ce7f 100644 --- a/packages/payload/src/preferences/operations/findOne.ts +++ b/packages/payload/src/preferences/operations/findOne.ts @@ -10,7 +10,9 @@ async function findOne(args: PreferenceRequest): Promise Promise = async ({ overrideDelete, req, }) => { - if (!collectionConfig.upload) return + if (!collectionConfig.upload) { + return + } if (overrideDelete || files.length > 0) { const { staticDir: staticPath } = collectionConfig.upload diff --git a/packages/payload/src/uploads/docWithFilenameExists.ts b/packages/payload/src/uploads/docWithFilenameExists.ts index f7bff3cd0..ce8999809 100644 --- a/packages/payload/src/uploads/docWithFilenameExists.ts +++ b/packages/payload/src/uploads/docWithFilenameExists.ts @@ -17,7 +17,9 @@ const docWithFilenameExists = async ({ collectionSlug, filename, req }: Args): P }, }, }) - if (doc) return true + if (doc) { + return true + } return false } diff --git a/packages/payload/src/uploads/formatFilesize.ts b/packages/payload/src/uploads/formatFilesize.ts index cea549068..a4dde74bf 100644 --- a/packages/payload/src/uploads/formatFilesize.ts +++ b/packages/payload/src/uploads/formatFilesize.ts @@ -1,5 +1,7 @@ export function formatFilesize(bytes: number, decimals = 0): string { - if (bytes === 0) return '0 bytes' + if (bytes === 0) { + return '0 bytes' + } const k = 1024 const dm = decimals < 0 ? 0 : decimals diff --git a/packages/payload/src/uploads/generateFileData.ts b/packages/payload/src/uploads/generateFileData.ts index bbf3350d4..ee2321080 100644 --- a/packages/payload/src/uploads/generateFileData.ts +++ b/packages/payload/src/uploads/generateFileData.ts @@ -100,7 +100,9 @@ export const generateFileData = async ({ } if (!file) { - if (throwOnMissingFile) throw new MissingFile(req.t) + if (throwOnMissingFile) { + throw new MissingFile(req.t) + } return { data, @@ -133,7 +135,9 @@ export const generateFileData = async ({ const sharpOptions: SharpOptions = {} - if (fileIsAnimatedType) sharpOptions.animated = true + if (fileIsAnimatedType) { + sharpOptions.animated = true + } if (sharp && (fileIsAnimatedType || fileHasAdjustments)) { if (file.tempFilePath) { @@ -191,7 +195,9 @@ export const generateFileData = async ({ } // Adjust SVG mime type. fromBuffer modifies it. - if (mime === 'application/xml' && ext === 'svg') mime = 'image/svg+xml' + if (mime === 'application/xml' && ext === 'svg') { + mime = 'image/svg+xml' + } fileData.mimeType = mime const baseFilename = sanitize(file.name.substring(0, file.name.lastIndexOf('.')) || file.name) @@ -324,7 +330,9 @@ function parseUploadEditsFromReqOrIncomingData(args: { ? (req.query.uploadEdits as UploadEdits) : {} - if (uploadEdits.focalPoint) return uploadEdits + if (uploadEdits.focalPoint) { + return uploadEdits + } const incomingData = data as FileData const origDoc = originalDoc as FileData diff --git a/packages/payload/src/uploads/getBaseFields.ts b/packages/payload/src/uploads/getBaseFields.ts index 81473c9e2..e035f2abd 100644 --- a/packages/payload/src/uploads/getBaseFields.ts +++ b/packages/payload/src/uploads/getBaseFields.ts @@ -137,7 +137,9 @@ export const getBaseUploadFields = ({ collection, config }: Options): Field[] => hooks: { afterRead: [ ({ data, value }) => { - if (value && !data.filename) return value + if (value && !data.filename) { + return value + } return generateURL({ collectionSlug: collection.slug, @@ -199,7 +201,9 @@ export const getBaseUploadFields = ({ collection, config }: Options): Field[] => hooks: { afterRead: [ ({ data, value }) => { - if (value && size.height && size.width && !data.filename) return value + if (value && size.height && size.width && !data.filename) { + return value + } const sizeFilename = data?.sizes?.[size.name]?.filename diff --git a/packages/payload/src/uploads/getExternalFile.ts b/packages/payload/src/uploads/getExternalFile.ts index 0498d7ae4..7607fea81 100644 --- a/packages/payload/src/uploads/getExternalFile.ts +++ b/packages/payload/src/uploads/getExternalFile.ts @@ -28,7 +28,9 @@ export const getExternalFile = async ({ data, req, uploadConfig }: Args): Promis method: 'GET', }) - if (!res.ok) throw new APIError(`Failed to fetch file from ${fileURL}`, res.status) + if (!res.ok) { + throw new APIError(`Failed to fetch file from ${fileURL}`, res.status) + } const data = await res.arrayBuffer() diff --git a/packages/payload/src/uploads/imageResizer.ts b/packages/payload/src/uploads/imageResizer.ts index 8be883d95..cc9169495 100644 --- a/packages/payload/src/uploads/imageResizer.ts +++ b/packages/payload/src/uploads/imageResizer.ts @@ -178,15 +178,25 @@ const getImageResizeAction = ({ const originalImageIsSmallerXOrY = originalImage.width < targetWidth || originalImage.height < targetHeight - if (fit === 'contain' || fit === 'inside') return 'resize' - if (!isNumber(targetHeight) && !isNumber(targetWidth)) return 'resize' + if (fit === 'contain' || fit === 'inside') { + return 'resize' + } + if (!isNumber(targetHeight) && !isNumber(targetWidth)) { + return 'resize' + } const targetAspectRatio = targetWidth / targetHeight const originalAspectRatio = originalImage.width / originalImage.height - if (originalAspectRatio === targetAspectRatio) return 'resize' + if (originalAspectRatio === targetAspectRatio) { + return 'resize' + } - if (withoutEnlargement && originalImageIsSmallerXOrY) return 'resize' - if (withoutReduction && !originalImageIsSmallerXOrY) return 'resize' + if (withoutEnlargement && originalImageIsSmallerXOrY) { + return 'resize' + } + if (withoutReduction && !originalImageIsSmallerXOrY) { + return 'resize' + } return hasFocalPoint ? 'resizeWithFocalPoint' : 'resize' } @@ -274,7 +284,9 @@ export async function resizeAndTransformImageSizes({ const fileIsAnimatedType = ['image/avif', 'image/gif', 'image/webp'].includes(file.mimetype) const sharpOptions: SharpOptions = {} - if (fileIsAnimatedType) sharpOptions.animated = true + if (fileIsAnimatedType) { + sharpOptions.animated = true + } const sharpBase: Sharp | undefined = sharp(file.tempFilePath || file.data, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081 const originalImageMeta = await sharpBase.metadata() @@ -293,7 +305,9 @@ export async function resizeAndTransformImageSizes({ hasFocalPoint: Boolean(incomingFocalPoint), imageResizeConfig, }) - if (resizeAction === 'omit') return createResult({ name: imageResizeConfig.name }) + if (resizeAction === 'omit') { + return createResult({ name: imageResizeConfig.name }) + } const imageToResize = sharpBase.clone() let resized = imageToResize @@ -313,8 +327,12 @@ export async function resizeAndTransformImageSizes({ resizeHeight = Math.round(resizeWidth / originalAspectRatio) } - if (!resizeHeight) resizeHeight = resizeImageMeta.height - if (!resizeWidth) resizeWidth = resizeImageMeta.width + if (!resizeHeight) { + resizeHeight = resizeImageMeta.height + } + if (!resizeWidth) { + resizeWidth = resizeImageMeta.width + } const resizeAspectRatio = resizeWidth / resizeHeight const prioritizeHeight = resizeAspectRatio < originalAspectRatio @@ -352,7 +370,9 @@ export async function resizeAndTransformImageSizes({ // if the left bound is less than 0, adjust the left bound to 0 // keeping the focus on the left - if (leftBound < 0) leftBound = 0 + if (leftBound < 0) { + leftBound = 0 + } const halfResizeY = resizeHeight / 2 const yFocalCenter = resizeImageMeta.height * (incomingFocalPoint.y / 100) @@ -367,7 +387,9 @@ export async function resizeAndTransformImageSizes({ // if the top bound is less than 0, adjust the top bound to 0 // keeping the image focus near the top - if (topBound < 0) topBound = 0 + if (topBound < 0) { + topBound = 0 + } resized = resized.extract({ height: resizeHeight, diff --git a/packages/payload/src/uploads/optionallyAppendMetadata.ts b/packages/payload/src/uploads/optionallyAppendMetadata.ts index be1d5e386..5788cc4d8 100644 --- a/packages/payload/src/uploads/optionallyAppendMetadata.ts +++ b/packages/payload/src/uploads/optionallyAppendMetadata.ts @@ -22,7 +22,9 @@ export async function optionallyAppendMetadata({ } else if (typeof withMetadata === 'function') { const useMetadata = await withMetadata({ metadata, req }) - if (useMetadata) return sharpFile.withMetadata() + if (useMetadata) { + return sharpFile.withMetadata() + } } return sharpFile diff --git a/packages/payload/src/utilities/configToJSONSchema.ts b/packages/payload/src/utilities/configToJSONSchema.ts index d7f0d821c..b446e1ef2 100644 --- a/packages/payload/src/utilities/configToJSONSchema.ts +++ b/packages/payload/src/utilities/configToJSONSchema.ts @@ -17,10 +17,14 @@ import { getCollectionIDFieldTypes } from './getCollectionIDFieldTypes.js' const fieldIsRequired = (field: Field) => { const isConditional = Boolean(field?.admin && field?.admin?.condition) - if (isConditional) return false + if (isConditional) { + return false + } const isMarkedRequired = 'required' in field && field.required === true - if (fieldAffectsData(field) && isMarkedRequired) return true + if (fieldAffectsData(field) && isMarkedRequired) { + return true + } // if any subfields are required, this field is required if ('fields' in field && field.type !== 'array') { @@ -139,7 +143,9 @@ export function withNullableJSONSchemaType( isRequired: boolean, ): JSONSchema4TypeName | JSONSchema4TypeName[] { const fieldTypes = [fieldType] - if (isRequired) return fieldType + if (isRequired) { + return fieldType + } fieldTypes.push('null') return fieldTypes } @@ -169,7 +175,9 @@ export function fieldsToJSONSchema( properties: Object.fromEntries( fields.reduce((fieldSchemas, field) => { const isRequired = fieldAffectsData(field) && fieldIsRequired(field) - if (isRequired) requiredFieldNames.add(field.name) + if (isRequired) { + requiredFieldNames.add(field.name) + } let fieldSchema: JSONSchema4 diff --git a/packages/payload/src/utilities/createArrayFromCommaDelineated.ts b/packages/payload/src/utilities/createArrayFromCommaDelineated.ts index 344b59898..87e6367dd 100644 --- a/packages/payload/src/utilities/createArrayFromCommaDelineated.ts +++ b/packages/payload/src/utilities/createArrayFromCommaDelineated.ts @@ -1,5 +1,7 @@ export function createArrayFromCommaDelineated(input: string): string[] { - if (Array.isArray(input)) return input + if (Array.isArray(input)) { + return input + } if (input.indexOf(',') > -1) { return input.split(',') } diff --git a/packages/payload/src/utilities/createLocalReq.ts b/packages/payload/src/utilities/createLocalReq.ts index 8bc69d7c5..7ead1c051 100644 --- a/packages/payload/src/utilities/createLocalReq.ts +++ b/packages/payload/src/utilities/createLocalReq.ts @@ -32,7 +32,9 @@ const attachFakeURLProperties = (req: PayloadRequest) => { let urlObject function getURLObject() { - if (urlObject) return urlObject + if (urlObject) { + return urlObject + } const urlToUse = req?.url || req.payload.config?.serverURL || 'http://localhost' try { urlObject = new URL(urlToUse) @@ -43,15 +45,27 @@ const attachFakeURLProperties = (req: PayloadRequest) => { return urlObject } - if (!req.host) req.host = getURLObject().host - if (!req.protocol) req.protocol = getURLObject().protocol - if (!req.pathname) req.pathname = getURLObject().pathname - // @ts-expect-error - if (!req.searchParams) req.searchParams = getURLObject().searchParams - // @ts-expect-error - if (!req.origin) req.origin = getURLObject().origin - // @ts-expect-error - if (!req?.url) req.url = getURLObject().href + if (!req.host) { + req.host = getURLObject().host + } + if (!req.protocol) { + req.protocol = getURLObject().protocol + } + if (!req.pathname) { + req.pathname = getURLObject().pathname + } + if (!req.searchParams) { + // @ts-expect-error + req.searchParams = getURLObject().searchParams + } + if (!req.origin) { + // @ts-expect-error + req.origin = getURLObject().origin + } + if (!req?.url) { + // @ts-expect-error + req.url = getURLObject().href + } } type CreateLocalReq = ( @@ -88,8 +102,10 @@ export const createLocalReq: CreateLocalReq = async ( req?.i18n || (await getLocalI18n({ config: payload.config, language: payload.config.i18n.fallbackLanguage })) - // @ts-expect-error - if (!req.headers) req.headers = new Headers() + if (!req.headers) { + // @ts-expect-error + req.headers = new Headers() + } req.context = getRequestContext(req, context) req.payloadAPI = req?.payloadAPI || 'local' req.payload = payload diff --git a/packages/payload/src/utilities/deepCopyObject.ts b/packages/payload/src/utilities/deepCopyObject.ts index bd796d8d1..59ff9ce74 100644 --- a/packages/payload/src/utilities/deepCopyObject.ts +++ b/packages/payload/src/utilities/deepCopyObject.ts @@ -54,14 +54,20 @@ function cloneArray(a: T, fn): T { } export const deepCopyObject = (o: T): T => { - if (typeof o !== 'object' || o === null) return o - if (Array.isArray(o)) return cloneArray(o, deepCopyObject) + if (typeof o !== 'object' || o === null) { + return o + } + if (Array.isArray(o)) { + return cloneArray(o, deepCopyObject) + } if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, deepCopyObject) } const o2 = {} for (const k in o) { - if (Object.hasOwnProperty.call(o, k) === false) continue + if (Object.hasOwnProperty.call(o, k) === false) { + continue + } const cur = o[k] if (typeof cur !== 'object' || cur === null) { o2[k as string] = cur @@ -100,7 +106,9 @@ export function deepCopyObjectSimple(value: T): T { typeof e !== 'object' || e === null ? e : deepCopyObjectSimple(e), ) as T } else { - if (value instanceof Date) return new Date(value) as unknown as T + if (value instanceof Date) { + return new Date(value) as unknown as T + } const ret: { [key: string]: T } = {} for (const k in value) { const v = value[k] @@ -115,7 +123,9 @@ export function deepCopyObjectSimple(value: T): T { * Can be used if correctness is more important than speed. Supports circular dependencies */ export function deepCopyObjectComplex(object: T, cache: WeakMap = new WeakMap()): T { - if (object === null) return null + if (object === null) { + return null + } if (cache.has(object)) { return cache.get(object) diff --git a/packages/payload/src/utilities/dependencies/versionUtils.ts b/packages/payload/src/utilities/dependencies/versionUtils.ts index 58c30e745..76b4ad834 100644 --- a/packages/payload/src/utilities/dependencies/versionUtils.ts +++ b/packages/payload/src/utilities/dependencies/versionUtils.ts @@ -16,13 +16,21 @@ function comparePreRelease(v1: string, v2: string): number { const num2 = extractNumbers(v2) for (let i = 0; i < Math.max(num1.length, num2.length); i++) { - if ((num1[i] || 0) < (num2[i] || 0)) return -1 - if ((num1[i] || 0) > (num2[i] || 0)) return 1 + if ((num1[i] || 0) < (num2[i] || 0)) { + return -1 + } + if ((num1[i] || 0) > (num2[i] || 0)) { + return 1 + } } // If numeric parts are equal, compare the whole string - if (v1 < v2) return -1 - if (v1 > v2) return 1 + if (v1 < v2) { + return -1 + } + if (v1 > v2) { + return 1 + } return 0 } @@ -53,15 +61,23 @@ export function compareVersions( // Compare main version parts for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) { - if ((parts1[i] || 0) > (parts2[i] || 0)) return 'greater' - if ((parts1[i] || 0) < (parts2[i] || 0)) return 'lower' + if ((parts1[i] || 0) > (parts2[i] || 0)) { + return 'greater' + } + if ((parts1[i] || 0) < (parts2[i] || 0)) { + return 'lower' + } } // Compare pre-release parts if main versions are equal if (preReleases1?.length || preReleases2?.length) { for (let i = 0; i < Math.max(preReleases1.length, preReleases2.length); i++) { - if (!preReleases1[i]) return 'greater' - if (!preReleases2[i]) return 'lower' + if (!preReleases1[i]) { + return 'greater' + } + if (!preReleases2[i]) { + return 'lower' + } const result = comparePreRelease(preReleases1[i], preReleases2[i]) if (result !== 0) { diff --git a/packages/payload/src/utilities/getEntityPolicies.ts b/packages/payload/src/utilities/getEntityPolicies.ts index 35344f954..9618a0e25 100644 --- a/packages/payload/src/utilities/getEntityPolicies.ts +++ b/packages/payload/src/utilities/getEntityPolicies.ts @@ -144,7 +144,9 @@ export async function getEntityPolicies(args: T): Promise { if ('name' in field && field.name) { - if (!mutablePolicies[field.name]) mutablePolicies[field.name] = {} + if (!mutablePolicies[field.name]) { + mutablePolicies[field.name] = {} + } if ('access' in field && field.access && typeof field.access[operation] === 'function') { await createAccessPromise({ @@ -161,7 +163,9 @@ export async function getEntityPolicies(args: T): Promise(args: T): Promise { diff --git a/packages/payload/src/utilities/getObjectDotNotation.ts b/packages/payload/src/utilities/getObjectDotNotation.ts index 64decf2ca..6cdb7ab9a 100644 --- a/packages/payload/src/utilities/getObjectDotNotation.ts +++ b/packages/payload/src/utilities/getObjectDotNotation.ts @@ -3,7 +3,9 @@ export const getObjectDotNotation = ( path: string, defaultValue?: T, ): T => { - if (!path || !obj) return defaultValue + if (!path || !obj) { + return defaultValue + } const result = path.split('.').reduce((o, i) => o?.[i], obj) return result === undefined ? defaultValue : (result as T) } diff --git a/packages/payload/src/utilities/getSiblingData.ts b/packages/payload/src/utilities/getSiblingData.ts index 74fa71133..7c1543bef 100644 --- a/packages/payload/src/utilities/getSiblingData.ts +++ b/packages/payload/src/utilities/getSiblingData.ts @@ -4,7 +4,9 @@ import { reduceFieldsToValues } from './reduceFieldsToValues.js' import { unflatten } from './unflatten.js' export const getSiblingData = (fields: FormState, path: string): Data => { - if (!fields) return null + if (!fields) { + return null + } if (path.indexOf('.') === -1) { return reduceFieldsToValues(fields, true) diff --git a/packages/payload/src/utilities/isValidID.ts b/packages/payload/src/utilities/isValidID.ts index 2fa0462b1..6f9431568 100644 --- a/packages/payload/src/utilities/isValidID.ts +++ b/packages/payload/src/utilities/isValidID.ts @@ -15,7 +15,9 @@ export const isValidID = ( return false } - if (typeof value === 'number' && !Number.isNaN(value)) return true + if (typeof value === 'number' && !Number.isNaN(value)) { + return true + } if (type === 'ObjectID') { return ObjectId.isValid(String(value)) diff --git a/packages/payload/src/utilities/reduceFieldsToValues.ts b/packages/payload/src/utilities/reduceFieldsToValues.ts index 805933a7e..a72e20952 100644 --- a/packages/payload/src/utilities/reduceFieldsToValues.ts +++ b/packages/payload/src/utilities/reduceFieldsToValues.ts @@ -15,7 +15,9 @@ export const reduceFieldsToValues = ( ): Data => { let data = {} - if (!fields) return data + if (!fields) { + return data + } Object.keys(fields).forEach((key) => { if (ignoreDisableFormData === true || !fields[key]?.disableFormData) { diff --git a/packages/payload/src/utilities/timestamp.ts b/packages/payload/src/utilities/timestamp.ts index b60ecb911..adce0b000 100644 --- a/packages/payload/src/utilities/timestamp.ts +++ b/packages/payload/src/utilities/timestamp.ts @@ -1,5 +1,7 @@ export const timestamp = (label) => { - if (!process.env.PAYLOAD_TIME) process.env.PAYLOAD_TIME = String(new Date().getTime()) + if (!process.env.PAYLOAD_TIME) { + process.env.PAYLOAD_TIME = String(new Date().getTime()) + } const now = new Date() console.log(`[${now.getTime() - Number(process.env.PAYLOAD_TIME)}ms] ${label}`) } diff --git a/packages/payload/src/versions/drafts/getQueryDraftsSort.ts b/packages/payload/src/versions/drafts/getQueryDraftsSort.ts index 3da4ec935..a4425dce6 100644 --- a/packages/payload/src/versions/drafts/getQueryDraftsSort.ts +++ b/packages/payload/src/versions/drafts/getQueryDraftsSort.ts @@ -3,7 +3,9 @@ * @param sort */ export const getQueryDraftsSort = (sort: string): string => { - if (!sort) return sort + if (!sort) { + return sort + } let direction = '' let orderBy = sort diff --git a/packages/payload/src/versions/saveVersion.ts b/packages/payload/src/versions/saveVersion.ts index d6635c759..f18fc9df2 100644 --- a/packages/payload/src/versions/saveVersion.ts +++ b/packages/payload/src/versions/saveVersion.ts @@ -32,8 +32,12 @@ export const saveVersion = async ({ let createNewVersion = true const now = new Date().toISOString() const versionData = deepCopyObjectSimple(doc) - if (draft) versionData._status = 'draft' - if (versionData._id) delete versionData._id + if (draft) { + versionData._status = 'draft' + } + if (versionData._id) { + delete versionData._id + } try { if (autosave) { @@ -124,10 +128,12 @@ export const saveVersion = async ({ } catch (err) { let errorMessage: string - if (collection) + if (collection) { errorMessage = `There was an error while saving a version for the ${collection.labels.singular} with ID ${id}.` - if (global) + } + if (global) { errorMessage = `There was an error while saving a version for the global ${global.label}.` + } payload.logger.error(errorMessage) payload.logger.error(err) return @@ -135,9 +141,12 @@ export const saveVersion = async ({ let max = 100 - if (collection && typeof collection.versions.maxPerDoc === 'number') + if (collection && typeof collection.versions.maxPerDoc === 'number') { max = collection.versions.maxPerDoc - if (global && typeof global.versions.max === 'number') max = global.versions.max + } + if (global && typeof global.versions.max === 'number') { + max = global.versions.max + } if (createNewVersion && max > 0) { await enforceMaxVersions({ diff --git a/packages/plugin-cloud-storage/src/adapters/azure/index.ts b/packages/plugin-cloud-storage/src/adapters/azure/index.ts index 1372e7b9e..85c6b3da7 100644 --- a/packages/plugin-cloud-storage/src/adapters/azure/index.ts +++ b/packages/plugin-cloud-storage/src/adapters/azure/index.ts @@ -35,7 +35,9 @@ export const azureBlobStorageAdapter = ({ let storageClient: ContainerClient | null = null const getStorageClient = () => { - if (storageClient) return storageClient + if (storageClient) { + return storageClient + } let blobServiceClient = null try { blobServiceClient = BlobServiceClient.fromConnectionString(connectionString) diff --git a/packages/plugin-cloud-storage/src/adapters/gcs/index.ts b/packages/plugin-cloud-storage/src/adapters/gcs/index.ts index 16a3fa7c3..95fe5bf37 100644 --- a/packages/plugin-cloud-storage/src/adapters/gcs/index.ts +++ b/packages/plugin-cloud-storage/src/adapters/gcs/index.ts @@ -32,7 +32,9 @@ export const gcsAdapter = let storageClient: Storage | null = null const getStorageClient = (): Storage => { - if (storageClient) return storageClient + if (storageClient) { + return storageClient + } try { storageClient = new Storage(options) } catch (error) { diff --git a/packages/plugin-cloud-storage/src/adapters/s3/index.ts b/packages/plugin-cloud-storage/src/adapters/s3/index.ts index 1b1374b4d..b948a9f72 100644 --- a/packages/plugin-cloud-storage/src/adapters/s3/index.ts +++ b/packages/plugin-cloud-storage/src/adapters/s3/index.ts @@ -38,7 +38,9 @@ export const s3Adapter = } let storageClient: AWS.S3 | null = null const getStorageClient: () => AWS.S3 = () => { - if (storageClient) return storageClient + if (storageClient) { + return storageClient + } try { storageClient = new AWS.S3(config) } catch (error) { diff --git a/packages/plugin-cloud-storage/src/hooks/afterDelete.ts b/packages/plugin-cloud-storage/src/hooks/afterDelete.ts index 7c2f90cd0..4e63a7a0b 100644 --- a/packages/plugin-cloud-storage/src/hooks/afterDelete.ts +++ b/packages/plugin-cloud-storage/src/hooks/afterDelete.ts @@ -19,7 +19,9 @@ export const getAfterDeleteHook = ({ ] const promises = filesToDelete.map(async (filename) => { - if (filename) await adapter.handleDelete({ collection, doc, filename, req }) + if (filename) { + await adapter.handleDelete({ collection, doc, filename, req }) + } }) await Promise.all(promises) diff --git a/packages/plugin-cloud-storage/src/plugin.ts b/packages/plugin-cloud-storage/src/plugin.ts index 9d8033861..a7d4f7e80 100644 --- a/packages/plugin-cloud-storage/src/plugin.ts +++ b/packages/plugin-cloud-storage/src/plugin.ts @@ -39,7 +39,9 @@ export const cloudStoragePlugin = prefix: options.prefix, }) - if (adapter.onInit) initFunctions.push(adapter.onInit) + if (adapter.onInit) { + initFunctions.push(adapter.onInit) + } const fields = getFields({ adapter, @@ -90,7 +92,9 @@ export const cloudStoragePlugin = }), onInit: async (payload) => { initFunctions.forEach((fn) => fn()) - if (config.onInit) await config.onInit(payload) + if (config.onInit) { + await config.onInit(payload) + } }, } } diff --git a/packages/plugin-cloud/src/email.ts b/packages/plugin-cloud/src/email.ts index 9658e6824..d4e1f2ae6 100644 --- a/packages/plugin-cloud/src/email.ts +++ b/packages/plugin-cloud/src/email.ts @@ -12,9 +12,12 @@ export const payloadCloudEmail = async ( return undefined } - if (!args.apiKey) throw new Error('apiKey must be provided to use Payload Cloud Email') - if (!args.defaultDomain) + if (!args.apiKey) { + throw new Error('apiKey must be provided to use Payload Cloud Email') + } + if (!args.defaultDomain) { throw new Error('defaultDomain must be provided to use Payload Cloud Email') + } // Check if already has email configuration diff --git a/packages/plugin-cloud/src/hooks/uploadCache.ts b/packages/plugin-cloud/src/hooks/uploadCache.ts index e2010c420..7c4447eb1 100644 --- a/packages/plugin-cloud/src/hooks/uploadCache.ts +++ b/packages/plugin-cloud/src/hooks/uploadCache.ts @@ -7,7 +7,9 @@ interface Args { export const getCacheUploadsAfterChangeHook = ({ endpoint }: Args): CollectionAfterChangeHook => ({ doc, operation, req }) => { - if (!req || !process.env.PAYLOAD_CLOUD_CACHE_KEY) return doc + if (!req || !process.env.PAYLOAD_CLOUD_CACHE_KEY) { + return doc + } // WARNING: // TODO: Test this for 3.0 @@ -24,7 +26,9 @@ export const getCacheUploadsAfterChangeHook = export const getCacheUploadsAfterDeleteHook = ({ endpoint }: Args): CollectionAfterDeleteHook => ({ doc, req }) => { - if (!req || !process.env.PAYLOAD_CLOUD_CACHE_KEY) return doc + if (!req || !process.env.PAYLOAD_CLOUD_CACHE_KEY) { + return doc + } const { payloadAPI } = req diff --git a/packages/plugin-form-builder/src/collections/FormSubmissions/index.ts b/packages/plugin-form-builder/src/collections/FormSubmissions/index.ts index 19d7fd9af..46d033000 100644 --- a/packages/plugin-form-builder/src/collections/FormSubmissions/index.ts +++ b/packages/plugin-form-builder/src/collections/FormSubmissions/index.ts @@ -22,7 +22,9 @@ export const generateSubmissionCollection = ( required: true, validate: async (value, { req: { payload }, req }) => { /* Don't run in the client side */ - if (!payload) return true + if (!payload) { + return true + } if (payload) { let _existingForm diff --git a/packages/plugin-form-builder/src/collections/Forms/index.ts b/packages/plugin-form-builder/src/collections/Forms/index.ts index 02362e9ec..1229fd64c 100644 --- a/packages/plugin-form-builder/src/collections/Forms/index.ts +++ b/packages/plugin-form-builder/src/collections/Forms/index.ts @@ -57,7 +57,9 @@ export const generateFormCollection = (formConfig: FormBuilderPluginConfig): Col ], }) - if (redirect.fields[2].type !== 'row') redirect.fields[2].label = 'Custom URL' + if (redirect.fields[2].type !== 'row') { + redirect.fields[2].label = 'Custom URL' + } redirect.fields[2].admin = { condition: (_, siblingData) => siblingData?.type === 'custom', diff --git a/packages/plugin-form-builder/src/utilities/replaceDoubleCurlys.ts b/packages/plugin-form-builder/src/utilities/replaceDoubleCurlys.ts index c75bcf93d..e053d8d0a 100644 --- a/packages/plugin-form-builder/src/utilities/replaceDoubleCurlys.ts +++ b/packages/plugin-form-builder/src/utilities/replaceDoubleCurlys.ts @@ -10,7 +10,9 @@ export const replaceDoubleCurlys = (str: string, variables?: EmailVariables): st if (str && variables) { return str.replace(regex, (_, variable) => { const foundVariable = variables.find(({ field: fieldName }) => variable === fieldName) - if (foundVariable) return foundVariable.value + if (foundVariable) { + return foundVariable.value + } return variable }) } diff --git a/packages/plugin-nested-docs/src/hooks/resaveChildren.ts b/packages/plugin-nested-docs/src/hooks/resaveChildren.ts index 03b6326c3..abf1485aa 100644 --- a/packages/plugin-nested-docs/src/hooks/resaveChildren.ts +++ b/packages/plugin-nested-docs/src/hooks/resaveChildren.ts @@ -45,7 +45,9 @@ const resave = async ({ collection, doc, draft, pluginConfig, req }: ResaveArgs) collection.versions.drafts && child._status === 'published' - if (!parentDocIsPublished && childIsPublished) return + if (!parentDocIsPublished && childIsPublished) { + return + } await req.payload.update({ id: child.id, diff --git a/packages/plugin-nested-docs/src/utilities/populateBreadcrumbs.ts b/packages/plugin-nested-docs/src/utilities/populateBreadcrumbs.ts index c02455380..27e3eb288 100644 --- a/packages/plugin-nested-docs/src/utilities/populateBreadcrumbs.ts +++ b/packages/plugin-nested-docs/src/utilities/populateBreadcrumbs.ts @@ -33,7 +33,7 @@ export const populateBreadcrumbs = async ( const breadcrumbs = breadcrumbDocs.map((_, i) => formatBreadcrumb(pluginConfig, collection, breadcrumbDocs.slice(0, i + 1)), - ) + ) return { ...newData, diff --git a/packages/plugin-relationship-object-ids/src/hooks/beforeChange.ts b/packages/plugin-relationship-object-ids/src/hooks/beforeChange.ts index f09949906..500655099 100644 --- a/packages/plugin-relationship-object-ids/src/hooks/beforeChange.ts +++ b/packages/plugin-relationship-object-ids/src/hooks/beforeChange.ts @@ -14,7 +14,9 @@ const convertValue = ({ (field) => fieldAffectsData(field) && field.name === 'id', ) - if (!customIDField) return new mongoose.Types.ObjectId(value) + if (!customIDField) { + return new mongoose.Types.ObjectId(value) + } return value } diff --git a/packages/plugin-sentry/src/plugin.ts b/packages/plugin-sentry/src/plugin.ts index 26c0e5afd..ce76d3623 100644 --- a/packages/plugin-sentry/src/plugin.ts +++ b/packages/plugin-sentry/src/plugin.ts @@ -23,7 +23,9 @@ export const sentryPlugin = } config.onInit = async (payload) => { - if (incomingConfig.onInit) await incomingConfig.onInit(payload) + if (incomingConfig.onInit) { + await incomingConfig.onInit(payload) + } startSentry(pluginOptions, payload) } diff --git a/packages/plugin-sentry/src/startSentry.ts b/packages/plugin-sentry/src/startSentry.ts index ab9eadbc1..abd732236 100644 --- a/packages/plugin-sentry/src/startSentry.ts +++ b/packages/plugin-sentry/src/startSentry.ts @@ -11,7 +11,9 @@ export const startSentry = (pluginOptions: PluginOptions, payload: Payload): voi const { dsn, options } = pluginOptions const { express: app } = payload - if (!dsn || !app) return + if (!dsn || !app) { + return + } try { Sentry.init({ diff --git a/packages/plugin-seo/src/fields/MetaDescription/MetaDescriptionComponent.tsx b/packages/plugin-seo/src/fields/MetaDescription/MetaDescriptionComponent.tsx index bda292f97..98a5ba7d8 100644 --- a/packages/plugin-seo/src/fields/MetaDescription/MetaDescriptionComponent.tsx +++ b/packages/plugin-seo/src/fields/MetaDescription/MetaDescriptionComponent.tsx @@ -54,7 +54,9 @@ export const MetaDescriptionComponent: React.FC = (props) const { errorMessage, setValue, showError, value } = field const regenerateDescription = useCallback(async () => { - if (!hasGenerateDescriptionFn) return + if (!hasGenerateDescriptionFn) { + return + } const genDescriptionResponse = await fetch('/api/plugin-seo/generate-description', { body: JSON.stringify({ diff --git a/packages/plugin-seo/src/fields/MetaImage/MetaImageComponent.tsx b/packages/plugin-seo/src/fields/MetaImage/MetaImageComponent.tsx index 4100d3748..bf6e51eb9 100644 --- a/packages/plugin-seo/src/fields/MetaImage/MetaImageComponent.tsx +++ b/packages/plugin-seo/src/fields/MetaImage/MetaImageComponent.tsx @@ -51,7 +51,9 @@ export const MetaImageComponent: React.FC = (props) => { const { errorMessage, setValue, showError, value } = field const regenerateImage = useCallback(async () => { - if (!hasGenerateImageFn) return + if (!hasGenerateImageFn) { + return + } const genImageResponse = await fetch('/api/plugin-seo/generate-image', { body: JSON.stringify({ diff --git a/packages/plugin-seo/src/fields/MetaTitle/MetaTitleComponent.tsx b/packages/plugin-seo/src/fields/MetaTitle/MetaTitleComponent.tsx index 79aa480e7..e8ff995cc 100644 --- a/packages/plugin-seo/src/fields/MetaTitle/MetaTitleComponent.tsx +++ b/packages/plugin-seo/src/fields/MetaTitle/MetaTitleComponent.tsx @@ -55,7 +55,9 @@ export const MetaTitleComponent: React.FC = (props) => { const { errorMessage, setValue, showError, value } = field const regenerateTitle = useCallback(async () => { - if (!hasGenerateTitleFn) return + if (!hasGenerateTitleFn) { + return + } const genTitleResponse = await fetch('/api/plugin-seo/generate-title', { body: JSON.stringify({ diff --git a/packages/plugin-seo/src/fields/Overview/OverviewComponent.tsx b/packages/plugin-seo/src/fields/Overview/OverviewComponent.tsx index 57ac51c00..0bcd26353 100644 --- a/packages/plugin-seo/src/fields/Overview/OverviewComponent.tsx +++ b/packages/plugin-seo/src/fields/Overview/OverviewComponent.tsx @@ -58,10 +58,12 @@ export const OverviewComponent: React.FC = ({ }, [getFields]) useEffect(() => { - if (typeof metaTitle === 'string') + if (typeof metaTitle === 'string') { setTitleIsValid(metaTitle.length >= minTitle && metaTitle.length <= maxTitle) - if (typeof metaDesc === 'string') + } + if (typeof metaDesc === 'string') { setDescIsValid(metaDesc.length >= minDesc && metaDesc.length <= maxDesc) + } setImageIsValid(Boolean(metaImage)) }, [metaTitle, metaDesc, metaImage]) diff --git a/packages/plugin-stripe/src/hooks/createNewInStripe.ts b/packages/plugin-stripe/src/hooks/createNewInStripe.ts index 5ee18aee5..f166c5323 100644 --- a/packages/plugin-stripe/src/hooks/createNewInStripe.ts +++ b/packages/plugin-stripe/src/hooks/createNewInStripe.ts @@ -38,7 +38,9 @@ export const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (ar if (payload) { if (data?.skipSync) { - if (logs) payload.logger.info(`Bypassing collection-level hooks.`) + if (logs) { + payload.logger.info(`Bypassing collection-level hooks.`) + } } else { // initialize as 'false' so that all Payload admin events sync to Stripe // then conditionally set to 'true' to for events that originate from webhooks @@ -63,10 +65,11 @@ export const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (ar syncedFields = deepen(syncedFields) if (operation === 'update') { - if (logs) + if (logs) { payload.logger.info( `A '${collectionSlug}' document has changed in Payload with ID: '${data?.id}', syncing with Stripe...`, ) + } // NOTE: the Stripe document will be created in the "afterChange" hook, so create a new stripe document here if no stripeID exists if (!dataRef.stripeID) { @@ -77,10 +80,11 @@ export const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (ar syncedFields, ) - if (logs) + if (logs) { payload.logger.info( `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`, ) + } dataRef.stripeID = stripeResource.id @@ -88,22 +92,26 @@ export const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (ar dataRef.skipSync = true } catch (error: unknown) { const msg = error instanceof Error ? error.message : error - if (logs) payload.logger.error(`- Error creating Stripe document: ${msg}`) + if (logs) { + payload.logger.error(`- Error creating Stripe document: ${msg}`) + } } } } if (operation === 'create') { - if (logs) + if (logs) { payload.logger.info( `A new '${collectionSlug}' document was created in Payload with ID: '${data?.id}', syncing with Stripe...`, ) + } try { - if (logs) + if (logs) { payload.logger.info( `- Creating new '${syncConfig.stripeResourceType}' resource in Stripe...`, ) + } // NOTE: Typed as "any" because the "create" method is not standard across all Stripe resources const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create( @@ -111,10 +119,11 @@ export const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (ar syncedFields, ) - if (logs) + if (logs) { payload.logger.info( `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`, ) + } dataRef.stripeID = stripeResource.id diff --git a/packages/plugin-stripe/src/hooks/deleteFromStripe.ts b/packages/plugin-stripe/src/hooks/deleteFromStripe.ts index 1f739aa72..39f86b025 100644 --- a/packages/plugin-stripe/src/hooks/deleteFromStripe.ts +++ b/packages/plugin-stripe/src/hooks/deleteFromStripe.ts @@ -28,13 +28,16 @@ export const deleteFromStripe: CollectionAfterDeleteHookWithArgs = async (args) const { payload } = req const { slug: collectionSlug } = collection || {} - if (logs) + if (logs) { payload.logger.info( `Document with ID: '${doc?.id}' in collection: '${collectionSlug}' has been deleted, deleting from Stripe...`, ) + } if (process.env.NODE_ENV !== 'test') { - if (logs) payload.logger.info(`- Deleting Stripe document with ID: '${doc.stripeID}'...`) + if (logs) { + payload.logger.info(`- Deleting Stripe document with ID: '${doc.stripeID}'...`) + } const syncConfig = sync?.find((conf) => conf.collection === collectionSlug) @@ -44,15 +47,17 @@ export const deleteFromStripe: CollectionAfterDeleteHookWithArgs = async (args) if (found) { await stripe?.[syncConfig.stripeResourceType]?.del(doc.stripeID) - if (logs) + if (logs) { payload.logger.info( `✅ Successfully deleted Stripe document with ID: '${doc.stripeID}'.`, ) + } } else { - if (logs) + if (logs) { payload.logger.info( `- Stripe document with ID: '${doc.stripeID}' not found, skipping...`, ) + } } } catch (error: unknown) { const msg = error instanceof Error ? error.message : error diff --git a/packages/plugin-stripe/src/hooks/syncExistingWithStripe.ts b/packages/plugin-stripe/src/hooks/syncExistingWithStripe.ts index 1b1446d98..619c7883c 100644 --- a/packages/plugin-stripe/src/hooks/syncExistingWithStripe.ts +++ b/packages/plugin-stripe/src/hooks/syncExistingWithStripe.ts @@ -49,17 +49,21 @@ export const syncExistingWithStripe: CollectionBeforeChangeHookWithArgs = async syncedFields = deepen(syncedFields) - if (logs) + if (logs) { payload.logger.info( `A '${collectionSlug}' document has changed in Payload with ID: '${originalDoc?._id}', syncing with Stripe...`, ) + } if (!data.stripeID) { // NOTE: the "beforeValidate" hook populates this - if (logs) payload.logger.error(`- There is no Stripe ID for this document, skipping.`) + if (logs) { + payload.logger.error(`- There is no Stripe ID for this document, skipping.`) + } } else { - if (logs) + if (logs) { payload.logger.info(`- Syncing to Stripe resource with ID: '${data.stripeID}'...`) + } try { const stripeResource = await stripe?.[syncConfig?.stripeResourceType]?.update( @@ -67,10 +71,11 @@ export const syncExistingWithStripe: CollectionBeforeChangeHookWithArgs = async syncedFields, ) - if (logs) + if (logs) { payload.logger.info( `✅ Successfully synced Stripe resource with ID: '${stripeResource.id}'.`, ) + } } catch (error: unknown) { const msg = error instanceof Error ? error.message : error throw new APIError(`Failed to sync document with ID: '${data.id}' to Stripe: ${msg}`) diff --git a/packages/plugin-stripe/src/webhooks/handleCreatedOrUpdated.ts b/packages/plugin-stripe/src/webhooks/handleCreatedOrUpdated.ts index 0b6a21552..5bb45b0b2 100644 --- a/packages/plugin-stripe/src/webhooks/handleCreatedOrUpdated.ts +++ b/packages/plugin-stripe/src/webhooks/handleCreatedOrUpdated.ts @@ -31,17 +31,19 @@ export const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => { // } if (isNestedChange) { - if (logs) + if (logs) { payload.logger.info( `- This change occurred on a nested field of ${resourceType}. Nested fields are not yet supported in auto-sync but can be manually setup.`, ) + } } if (!isNestedChange) { - if (logs) + if (logs) { payload.logger.info( `- A new document was created or updated in Stripe, now syncing to Payload...`, ) + } const collectionSlug = syncConfig?.collection @@ -79,10 +81,11 @@ export const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => { }) if (!foundDoc) { - if (logs) + if (logs) { payload.logger.info( `- No existing '${collectionSlug}' document found with Stripe ID: '${stripeID}', creating new...`, ) + } // auth docs must use unique emails let authDoc = null @@ -102,10 +105,11 @@ export const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => { authDoc = authQuery.docs[0] as any if (authDoc) { - if (logs) + if (logs) { payload.logger.info( `- Account already exists with e-mail: ${stripeDoc.email}, updating now...`, ) + } // account exists by email, so update it instead try { @@ -115,37 +119,42 @@ export const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => { data: syncedData, }) - if (logs) + if (logs) { payload.logger.info( `✅ Successfully updated '${collectionSlug}' document in Payload with ID: '${authDoc.id}.'`, ) + } } catch (err: unknown) { const msg = err instanceof Error ? err.message : err - if (logs) + if (logs) { payload.logger.error( `- Error updating existing '${collectionSlug}' document: ${msg}`, ) + } } } } else { - if (logs) + if (logs) { payload.logger.error( `No email was provided from Stripe, cannot create new '${collectionSlug}' document.`, ) + } } } catch (error: unknown) { const msg = error instanceof Error ? error.message : error - if (logs) + if (logs) { payload.logger.error(`Error looking up '${collectionSlug}' document in Payload: ${msg}`) + } } } if (!isAuthCollection || (isAuthCollection && !authDoc)) { try { - if (logs) + if (logs) { payload.logger.info( `- Creating new '${collectionSlug}' document in Payload with Stripe ID: '${stripeID}'.`, ) + } // generate a strong, unique password for the new user const password: string = uuid() @@ -160,20 +169,24 @@ export const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => { disableVerificationEmail: isAuthCollection ? true : undefined, }) - if (logs) + if (logs) { payload.logger.info( `✅ Successfully created new '${collectionSlug}' document in Payload with Stripe ID: '${stripeID}'.`, ) + } } catch (error: unknown) { const msg = error instanceof Error ? error.message : error - if (logs) payload.logger.error(`Error creating new document in Payload: ${msg}`) + if (logs) { + payload.logger.error(`Error creating new document in Payload: ${msg}`) + } } } } else { - if (logs) + if (logs) { payload.logger.info( `- Existing '${collectionSlug}' document found in Payload with Stripe ID: '${stripeID}', updating now...`, ) + } try { await payload.update({ @@ -182,14 +195,16 @@ export const handleCreatedOrUpdated: HandleCreatedOrUpdated = async (args) => { data: syncedData, }) - if (logs) + if (logs) { payload.logger.info( `✅ Successfully updated '${collectionSlug}' document in Payload from Stripe ID: '${stripeID}'.`, ) + } } catch (error: unknown) { const msg = error instanceof Error ? error.message : error - if (logs) + if (logs) { payload.logger.error(`Error updating '${collectionSlug}' document in Payload: ${msg}`) + } } } } diff --git a/packages/plugin-stripe/src/webhooks/handleDeleted.ts b/packages/plugin-stripe/src/webhooks/handleDeleted.ts index 7dc3ddab7..0cdc769ca 100644 --- a/packages/plugin-stripe/src/webhooks/handleDeleted.ts +++ b/packages/plugin-stripe/src/webhooks/handleDeleted.ts @@ -23,17 +23,19 @@ export const handleDeleted: HandleDeleted = async (args) => { const isNestedDelete = eventObject !== resourceType if (isNestedDelete) { - if (logs) + if (logs) { payload.logger.info( `- This deletion occurred on a nested field of ${resourceType}. Nested fields are not yet supported.`, ) + } } if (!isNestedDelete) { - if (logs) + if (logs) { payload.logger.info( `- A '${resourceType}' resource was deleted in Stripe, now deleting '${collectionSlug}' document in Payload with Stripe ID: '${stripeID}'...`, ) + } try { const payloadQuery = await payload.find({ @@ -48,14 +50,17 @@ export const handleDeleted: HandleDeleted = async (args) => { const foundDoc = payloadQuery.docs[0] as any if (!foundDoc) { - if (logs) + if (logs) { payload.logger.info( `- Nothing to delete, no existing document found with Stripe ID: '${stripeID}'.`, ) + } } if (foundDoc) { - if (logs) payload.logger.info(`- Deleting Payload document with ID: '${foundDoc.id}'...`) + if (logs) { + payload.logger.info(`- Deleting Payload document with ID: '${foundDoc.id}'...`) + } try { // eslint-disable-next-line @typescript-eslint/no-floating-promises @@ -66,18 +71,23 @@ export const handleDeleted: HandleDeleted = async (args) => { // NOTE: the `afterDelete` hook will trigger, which will attempt to delete the document from Stripe and safely error out // There is no known way of preventing this from happening. In other hooks we use the `skipSync` field, but here the document is already deleted. - if (logs) + if (logs) { payload.logger.info( `- ✅ Successfully deleted Payload document with ID: '${foundDoc.id}'.`, ) + } } catch (error: unknown) { const msg = error instanceof Error ? error.message : error - if (logs) payload.logger.error(`Error deleting document: ${msg}`) + if (logs) { + payload.logger.error(`Error deleting document: ${msg}`) + } } } } catch (error: unknown) { const msg = error instanceof Error ? error.message : error - if (logs) payload.logger.error(`Error deleting document: ${msg}`) + if (logs) { + payload.logger.error(`Error deleting document: ${msg}`) + } } } } diff --git a/packages/plugin-stripe/src/webhooks/index.ts b/packages/plugin-stripe/src/webhooks/index.ts index 9f65dadd3..ec035d737 100644 --- a/packages/plugin-stripe/src/webhooks/index.ts +++ b/packages/plugin-stripe/src/webhooks/index.ts @@ -6,8 +6,9 @@ import { handleDeleted } from './handleDeleted.js' export const handleWebhooks: StripeWebhookHandler = (args) => { const { event, payload, pluginConfig } = args - if (pluginConfig?.logs) + if (pluginConfig?.logs) { payload.logger.info(`🪝 Received Stripe '${event.type}' webhook event with ID: '${event.id}'.`) + } // could also traverse into event.data.object.object to get the type, but that seems unreliable // use cli: `stripe resources` to see all available resources diff --git a/packages/richtext-lexical/babel.config.cjs b/packages/richtext-lexical/babel.config.cjs index 2a16d7554..ed4b07a62 100644 --- a/packages/richtext-lexical/babel.config.cjs +++ b/packages/richtext-lexical/babel.config.cjs @@ -4,7 +4,10 @@ const fs = require('fs') const ReactCompilerConfig = { sources: (filename) => { const isInNodeModules = filename.includes('node_modules') - if (isInNodeModules || ( !filename.endsWith('.tsx') && !filename.endsWith('.jsx') && !filename.endsWith('.js'))) { + if ( + isInNodeModules || + (!filename.endsWith('.tsx') && !filename.endsWith('.jsx') && !filename.endsWith('.js')) + ) { return false } diff --git a/packages/richtext-lexical/src/features/converters/html/field/index.ts b/packages/richtext-lexical/src/features/converters/html/field/index.ts index afca7bbf7..767ee5e06 100644 --- a/packages/richtext-lexical/src/features/converters/html/field/index.ts +++ b/packages/richtext-lexical/src/features/converters/html/field/index.ts @@ -176,10 +176,11 @@ export const lexicalHTML: ( const foundSiblingFields = findFieldPathAndSiblingFields(fields, [], field) - if (!foundSiblingFields) + if (!foundSiblingFields) { throw new Error( `Could not find sibling fields of current lexicalHTML field with name ${field?.name}`, ) + } const { siblingFields } = foundSiblingFields const lexicalField: RichTextField = diff --git a/packages/richtext-lexical/src/features/experimental_table/client/plugins/TablePlugin/index.scss b/packages/richtext-lexical/src/features/experimental_table/client/plugins/TablePlugin/index.scss index 9442d4e13..3fc98f018 100644 --- a/packages/richtext-lexical/src/features/experimental_table/client/plugins/TablePlugin/index.scss +++ b/packages/richtext-lexical/src/features/experimental_table/client/plugins/TablePlugin/index.scss @@ -84,7 +84,8 @@ height: 100%; } - &__tableAddColumns, &__tableAddRows { + &__tableAddColumns, + &__tableAddRows { position: absolute; background-color: var(--theme-elevation-100); animation: table-controls 0.2s ease; @@ -94,7 +95,8 @@ min-height: 24px; } - &__tableAddColumns:after, &__tableAddRows:after { + &__tableAddColumns:after, + &__tableAddRows:after { background-image: url(../../../../../lexical/ui/icons/Add/index.svg); background-position: center; background-repeat: no-repeat; @@ -108,7 +110,8 @@ opacity: 0.4; } - &__tableAddColumns:hover, &__tableAddRows:hover { + &__tableAddColumns:hover, + &__tableAddRows:hover { background-color: var(--theme-elevation-200); } @@ -167,7 +170,8 @@ html[data-theme='dark'] { background-color: var(--theme-elevation-50); } - &__tableAddColumns:after, &__tableAddRows:after { + &__tableAddColumns:after, + &__tableAddRows:after { background-image: url(../../../../../lexical/ui/icons/Add/light.svg); } } diff --git a/packages/richtext-lexical/src/features/link/client/plugins/autoLink/index.tsx b/packages/richtext-lexical/src/features/link/client/plugins/autoLink/index.tsx index 7b5bdb0d7..cd27479e0 100644 --- a/packages/richtext-lexical/src/features/link/client/plugins/autoLink/index.tsx +++ b/packages/richtext-lexical/src/features/link/client/plugins/autoLink/index.tsx @@ -40,7 +40,9 @@ export function createLinkMatcherWithRegExp( ) { return (text: string) => { const match = regExp.exec(text) - if (match === null) return null + if (match === null) { + return null + } return { index: match.index, length: match[0].length, diff --git a/packages/richtext-lexical/src/features/link/nodes/LinkNode.ts b/packages/richtext-lexical/src/features/link/nodes/LinkNode.ts index d5e98d0ba..beb677fc3 100644 --- a/packages/richtext-lexical/src/features/link/nodes/LinkNode.ts +++ b/packages/richtext-lexical/src/features/link/nodes/LinkNode.ts @@ -386,7 +386,7 @@ function $getAncestor( predicate: (ancestor: LexicalNode) => boolean, ): LexicalNode | null { let parent: LexicalNode | null = node - while (parent !== null && (parent = parent.getParent()) !== null && !predicate(parent)); + while (parent !== null && (parent = parent.getParent()) !== null && !predicate(parent)) {} return parent } diff --git a/packages/richtext-lexical/src/features/toolbars/shared/ToolbarDropdown/DropDown.tsx b/packages/richtext-lexical/src/features/toolbars/shared/ToolbarDropdown/DropDown.tsx index 58b7c5885..9b2fb7407 100644 --- a/packages/richtext-lexical/src/features/toolbars/shared/ToolbarDropdown/DropDown.tsx +++ b/packages/richtext-lexical/src/features/toolbars/shared/ToolbarDropdown/DropDown.tsx @@ -113,7 +113,9 @@ function DropDownItems({ ) const handleKeyDown = (event: React.KeyboardEvent): void => { - if (items == null) return + if (items == null) { + return + } const { key } = event @@ -125,13 +127,17 @@ function DropDownItems({ onClose() } else if (key === 'ArrowUp') { setHighlightedItem((prev) => { - if (prev == null) return items[0] + if (prev == null) { + return items[0] + } const index = items.indexOf(prev) - 1 return items[index === -1 ? items.length - 1 : index] }) } else if (key === 'ArrowDown') { setHighlightedItem((prev) => { - if (prev == null) return items[0] + if (prev == null) { + return items[0] + } return items[items.indexOf(prev) + 1] }) } diff --git a/packages/richtext-lexical/src/features/upload/server/feature.server.ts b/packages/richtext-lexical/src/features/upload/server/feature.server.ts index 09c1435d3..abfa8ede2 100644 --- a/packages/richtext-lexical/src/features/upload/server/feature.server.ts +++ b/packages/richtext-lexical/src/features/upload/server/feature.server.ts @@ -81,7 +81,9 @@ export const UploadFeature = createServerFeature< ClientFeature: '@payloadcms/richtext-lexical/client#UploadFeatureClient', clientFeatureProps: clientProps, generateSchemaMap: ({ props }) => { - if (!props?.collections) return null + if (!props?.collections) { + return null + } const schemaMap = new Map() diff --git a/packages/richtext-lexical/src/lexical/LexicalEditor.tsx b/packages/richtext-lexical/src/lexical/LexicalEditor.tsx index 56d8f8834..667e18fbf 100644 --- a/packages/richtext-lexical/src/lexical/LexicalEditor.tsx +++ b/packages/richtext-lexical/src/lexical/LexicalEditor.tsx @@ -129,7 +129,9 @@ export const LexicalEditor: React.FC< onChange={(editorState, editor, tags) => { // Ignore any onChange event triggered by focus only if (!tags.has('focus') || tags.size > 1) { - if (onChange != null) onChange(editorState, editor, tags) + if (onChange != null) { + onChange(editorState, editor, tags) + } } }} /> diff --git a/packages/richtext-lexical/src/lexical/plugins/SlashMenu/LexicalTypeaheadMenuPlugin/LexicalMenu.tsx b/packages/richtext-lexical/src/lexical/plugins/SlashMenu/LexicalTypeaheadMenuPlugin/LexicalMenu.tsx index dcda8a0a0..51976a4be 100644 --- a/packages/richtext-lexical/src/lexical/plugins/SlashMenu/LexicalTypeaheadMenuPlugin/LexicalMenu.tsx +++ b/packages/richtext-lexical/src/lexical/plugins/SlashMenu/LexicalTypeaheadMenuPlugin/LexicalMenu.tsx @@ -40,7 +40,9 @@ export type MenuRenderFn = ( const scrollIntoViewIfNeeded = (target: HTMLElement) => { const typeaheadContainerNode = document.getElementById('slash-menu') - if (!typeaheadContainerNode) return + if (!typeaheadContainerNode) { + return + } const typeaheadRect = typeaheadContainerNode.getBoundingClientRect() diff --git a/packages/richtext-lexical/src/lexical/plugins/handles/utils/doesLineHeightAffectElement.ts b/packages/richtext-lexical/src/lexical/plugins/handles/utils/doesLineHeightAffectElement.ts index 620edaa72..bb48a68f7 100644 --- a/packages/richtext-lexical/src/lexical/plugins/handles/utils/doesLineHeightAffectElement.ts +++ b/packages/richtext-lexical/src/lexical/plugins/handles/utils/doesLineHeightAffectElement.ts @@ -20,7 +20,9 @@ const replacedElements = [ * @param htmlElem */ export function doesLineHeightAffectElement(htmlElem: HTMLElement) { - if (!htmlElem) return false + if (!htmlElem) { + return false + } // Check for replaced elements, elements that typically don't support line-height adjustments, // and elements without visible content diff --git a/packages/richtext-lexical/src/lexical/utils/url.ts b/packages/richtext-lexical/src/lexical/utils/url.ts index bdf2ad4f5..57cdb1e54 100644 --- a/packages/richtext-lexical/src/lexical/utils/url.ts +++ b/packages/richtext-lexical/src/lexical/utils/url.ts @@ -8,7 +8,9 @@ export function sanitizeUrl(url: string): string { url = String(url).trim() - if (url.match(SAFE_URL_PATTERN) != null || url.match(DATA_URL_PATTERN) != null) return url + if (url.match(SAFE_URL_PATTERN) != null || url.match(DATA_URL_PATTERN) != null) { + return url + } return 'https://' } @@ -30,7 +32,9 @@ const relativeOrAnchorRegExp = /^[\w\-./]*(?:#\w[\w-]*)?$/ * @param url */ export function validateUrlMinimal(url: string): boolean { - if (!url) return false + if (!url) { + return false + } return !url.includes(' ') } @@ -41,15 +45,23 @@ export function validateUrl(url: string): boolean { // TODO Fix UI for link insertion; it should never default to an invalid URL such as https://. // Maybe show a dialog where they user can type the URL before inserting it. - if (!url) return false + if (!url) { + return false + } - if (url === 'https://') return true + if (url === 'https://') { + return true + } // This makes sure URLs starting with www. instead of https are valid too - if (absoluteRegExp.test(url)) return true + if (absoluteRegExp.test(url)) { + return true + } // Check relative or anchor links - if (relativeOrAnchorRegExp.test(url)) return true + if (relativeOrAnchorRegExp.test(url)) { + return true + } // While this doesn't allow URLs starting with www (which is why we use the regex above), it does properly handle tel: URLs try { diff --git a/packages/richtext-slate/src/data/validation.ts b/packages/richtext-slate/src/data/validation.ts index a304b098f..bfb24f771 100644 --- a/packages/richtext-slate/src/data/validation.ts +++ b/packages/richtext-slate/src/data/validation.ts @@ -13,7 +13,9 @@ export const richTextValidate: Validate< const { t } = req if (required) { const stringifiedDefaultValue = JSON.stringify(defaultRichTextValue) - if (value && JSON.stringify(value) !== stringifiedDefaultValue) return true + if (value && JSON.stringify(value) !== stringifiedDefaultValue) { + return true + } return t('validation:required') } diff --git a/packages/richtext-slate/src/field/RichText.tsx b/packages/richtext-slate/src/field/RichText.tsx index f2acf6cea..b450ee1f6 100644 --- a/packages/richtext-slate/src/field/RichText.tsx +++ b/packages/richtext-slate/src/field/RichText.tsx @@ -261,7 +261,9 @@ const RichTextField: React.FC = (props) => { const isButton = child.tagName === 'BUTTON' const isDisabling = clickState === 'disabled' child.setAttribute('tabIndex', isDisabling ? '-1' : '0') - if (isButton) child.setAttribute('disabled', isDisabling ? 'disabled' : null) + if (isButton) { + child.setAttribute('disabled', isDisabling ? 'disabled' : null) + } }) } @@ -307,7 +309,9 @@ const RichTextField: React.FC = (props) => { } } - if (!valueToRender) valueToRender = defaultRichTextValue + if (!valueToRender) { + valueToRender = defaultRichTextValue + } return (
{ - if (!editor.selection) return false + if (!editor.selection) { + return false + } const [match] = Array.from( Editor.nodes(editor, { diff --git a/packages/richtext-slate/src/field/elements/isLastSelectedElementEmpty.ts b/packages/richtext-slate/src/field/elements/isLastSelectedElementEmpty.ts index 6ea8ac3e0..1ae90a7be 100644 --- a/packages/richtext-slate/src/field/elements/isLastSelectedElementEmpty.ts +++ b/packages/richtext-slate/src/field/elements/isLastSelectedElementEmpty.ts @@ -3,7 +3,9 @@ import { Editor, Element } from 'slate' import { nodeIsTextNode } from '../../types.js' export const isLastSelectedElementEmpty = (editor: Editor): boolean => { - if (!editor.selection) return false + if (!editor.selection) { + return false + } const currentlySelectedNodes = Array.from( Editor.nodes(editor, { diff --git a/packages/richtext-slate/src/field/elements/isListActive.ts b/packages/richtext-slate/src/field/elements/isListActive.ts index 869339dd5..5488517a7 100644 --- a/packages/richtext-slate/src/field/elements/isListActive.ts +++ b/packages/richtext-slate/src/field/elements/isListActive.ts @@ -3,10 +3,14 @@ import { Editor, Element } from 'slate' import { getCommonBlock } from './getCommonBlock.js' export const isListActive = (editor: Editor, format: string): boolean => { - if (!editor.selection) return false + if (!editor.selection) { + return false + } const [topmostSelectedNode, topmostSelectedNodePath] = getCommonBlock(editor) - if (Editor.isEditor(topmostSelectedNode)) return false + if (Editor.isEditor(topmostSelectedNode)) { + return false + } const [match] = Array.from( Editor.nodes(editor, { diff --git a/packages/richtext-slate/src/field/elements/link/Element/index.tsx b/packages/richtext-slate/src/field/elements/link/Element/index.tsx index 51640696c..dc1aec7c0 100644 --- a/packages/richtext-slate/src/field/elements/link/Element/index.tsx +++ b/packages/richtext-slate/src/field/elements/link/Element/index.tsx @@ -46,7 +46,9 @@ const insertChange = (editor, fields) => { url: data.url, } - if (data.fields) newNode.fields = data.fields + if (data.fields) { + newNode.fields = data.fields + } Transforms.setNodes(editor, newNode, { at: parentPath }) @@ -214,7 +216,9 @@ export const LinkElement = () => { className={[`${baseClass}__popup-toggler`].filter(Boolean).join(' ')} onClick={() => setRenderPopup(true)} onKeyDown={(e) => { - if (e.key === 'Enter') setRenderPopup(true) + if (e.key === 'Enter') { + setRenderPopup(true) + } }} role="button" tabIndex={0} diff --git a/packages/richtext-slate/src/field/elements/toggleList.tsx b/packages/richtext-slate/src/field/elements/toggleList.tsx index a56106e76..84370e02b 100644 --- a/packages/richtext-slate/src/field/elements/toggleList.tsx +++ b/packages/richtext-slate/src/field/elements/toggleList.tsx @@ -9,8 +9,12 @@ import { unwrapList } from './unwrapList.js' export const toggleList = (editor: Editor, format: string): void => { let currentListFormat: string - if (isListActive(editor, 'ol')) currentListFormat = 'ol' - if (isListActive(editor, 'ul')) currentListFormat = 'ul' + if (isListActive(editor, 'ol')) { + currentListFormat = 'ol' + } + if (isListActive(editor, 'ul')) { + currentListFormat = 'ul' + } // If the format is currently active, // remove the list diff --git a/packages/richtext-slate/src/generateComponentMap.tsx b/packages/richtext-slate/src/generateComponentMap.tsx index 1a51c01f9..6cf76729e 100644 --- a/packages/richtext-slate/src/generateComponentMap.tsx +++ b/packages/richtext-slate/src/generateComponentMap.tsx @@ -61,11 +61,12 @@ export const getGenerateComponentMap = const ElementButton = element.Button const ElementComponent = element.Element - if (ElementButton) + if (ElementButton) { componentMap.set( `element.button.${element.name}`, createMappedComponent(ElementButton, undefined, undefined, 'slate-ElementButton'), ) + } componentMap.set( `element.component.${element.name}`, createMappedComponent(ElementComponent, undefined, undefined, 'slate-ElementComponent'), diff --git a/packages/storage-azure/src/staticHandler.ts b/packages/storage-azure/src/staticHandler.ts index f24f4a14b..9829fc2ff 100644 --- a/packages/storage-azure/src/staticHandler.ts +++ b/packages/storage-azure/src/staticHandler.ts @@ -26,7 +26,7 @@ export const getHandler = ({ collection, getStorageClient }: Args): StaticHandle ) const blob = await blockBlobClient.download(start, end) - + const response = blob._response // Manually create a ReadableStream for the web from a Node.js stream. diff --git a/packages/storage-azure/src/utils/getStorageClient.ts b/packages/storage-azure/src/utils/getStorageClient.ts index 8d68a7c7d..fab21996b 100644 --- a/packages/storage-azure/src/utils/getStorageClient.ts +++ b/packages/storage-azure/src/utils/getStorageClient.ts @@ -9,7 +9,9 @@ let storageClient: ContainerClient | null = null export function getStorageClient( options: Pick, ): ContainerClient { - if (storageClient) return storageClient + if (storageClient) { + return storageClient + } const { connectionString, containerName } = options diff --git a/packages/storage-gcs/src/index.ts b/packages/storage-gcs/src/index.ts index f1b3a9b9f..f1a8fae88 100644 --- a/packages/storage-gcs/src/index.ts +++ b/packages/storage-gcs/src/index.ts @@ -94,7 +94,9 @@ function gcsStorageInternal({ acl, bucket, options }: GcsStorageOptions): Adapte let storageClient: Storage | null = null const getStorageClient = (): Storage => { - if (storageClient) return storageClient + if (storageClient) { + return storageClient + } storageClient = new Storage(options) return storageClient } diff --git a/packages/storage-s3/src/index.ts b/packages/storage-s3/src/index.ts index 04aed8a8d..afde5e491 100644 --- a/packages/storage-s3/src/index.ts +++ b/packages/storage-s3/src/index.ts @@ -106,7 +106,9 @@ function s3StorageInternal({ acl, bucket, config = {} }: S3StorageOptions): Adap return ({ collection, prefix }): GeneratedAdapter => { let storageClient: AWS.S3 | null = null const getStorageClient: () => AWS.S3 = () => { - if (storageClient) return storageClient + if (storageClient) { + return storageClient + } storageClient = new AWS.S3(config) return storageClient } diff --git a/packages/storage-uploadthing/src/staticHandler.ts b/packages/storage-uploadthing/src/staticHandler.ts index 9ce481f3d..180efc32a 100644 --- a/packages/storage-uploadthing/src/staticHandler.ts +++ b/packages/storage-uploadthing/src/staticHandler.ts @@ -39,7 +39,9 @@ export const getHandler = ({ utApi }: Args): StaticHandler => { where: { or }, }) - if (result) retrievedDoc = result + if (result) { + retrievedDoc = result + } } if (!retrievedDoc) { diff --git a/packages/translations/scripts/translateNewKeys/sortKeys.ts b/packages/translations/scripts/translateNewKeys/sortKeys.ts index 78ee0e83e..65b54e95c 100644 --- a/packages/translations/scripts/translateNewKeys/sortKeys.ts +++ b/packages/translations/scripts/translateNewKeys/sortKeys.ts @@ -1,5 +1,7 @@ export function sortKeys(obj: any): any { - if (typeof obj !== 'object' || obj === null) return obj + if (typeof obj !== 'object' || obj === null) { + return obj + } if (Array.isArray(obj)) { return obj.map(sortKeys) diff --git a/packages/translations/src/importDateFNSLocale.ts b/packages/translations/src/importDateFNSLocale.ts index f9b84aa47..7d23b2ea3 100644 --- a/packages/translations/src/importDateFNSLocale.ts +++ b/packages/translations/src/importDateFNSLocale.ts @@ -122,7 +122,9 @@ export const importDateFNSLocale = async (locale: string): Promise => { break } - if (result.default) return result.default + if (result.default) { + return result.default + } return result as Locale } diff --git a/packages/translations/src/utilities/init.ts b/packages/translations/src/utilities/init.ts index 128386b6b..dec0066b5 100644 --- a/packages/translations/src/utilities/init.ts +++ b/packages/translations/src/utilities/init.ts @@ -34,7 +34,9 @@ export const getTranslationString = < let keySuffix = '' const translation: string = keys.reduce((acc: any, key, index) => { - if (typeof acc === 'string') return acc + if (typeof acc === 'string') { + return acc + } if (typeof count === 'number') { if (count === 0 && `${key}_zero` in acc) { diff --git a/packages/ui/babel.config.cjs b/packages/ui/babel.config.cjs index 2a16d7554..ed4b07a62 100644 --- a/packages/ui/babel.config.cjs +++ b/packages/ui/babel.config.cjs @@ -4,7 +4,10 @@ const fs = require('fs') const ReactCompilerConfig = { sources: (filename) => { const isInNodeModules = filename.includes('node_modules') - if (isInNodeModules || ( !filename.endsWith('.tsx') && !filename.endsWith('.jsx') && !filename.endsWith('.js'))) { + if ( + isInNodeModules || + (!filename.endsWith('.tsx') && !filename.endsWith('.jsx') && !filename.endsWith('.js')) + ) { return false } diff --git a/packages/ui/src/elements/Autosave/index.tsx b/packages/ui/src/elements/Autosave/index.tsx index d06e50b14..5c670a37a 100644 --- a/packages/ui/src/elements/Autosave/index.tsx +++ b/packages/ui/src/elements/Autosave/index.tsx @@ -57,8 +57,9 @@ export const Autosave: React.FC = ({ const { i18n, t } = useTranslation() let interval = versionDefaults.autosaveInterval - if (versionsConfig.drafts && versionsConfig.drafts.autosave) + if (versionsConfig.drafts && versionsConfig.drafts.autosave) { interval = versionsConfig.drafts.autosave.interval + } const [saving, setSaving] = useState(false) const [lastSaved, setLastSaved] = useState() @@ -221,7 +222,9 @@ export const Autosave: React.FC = ({ void autosave() return () => { - if (autosaveTimeout) clearTimeout(autosaveTimeout) + if (autosaveTimeout) { + clearTimeout(autosaveTimeout) + } if (abortController.signal) { try { abortController.abort('Autosave closed early.') diff --git a/packages/ui/src/elements/Banner/index.tsx b/packages/ui/src/elements/Banner/index.tsx index 874e7daf5..18e6736ae 100644 --- a/packages/ui/src/elements/Banner/index.tsx +++ b/packages/ui/src/elements/Banner/index.tsx @@ -52,8 +52,12 @@ export const Banner: React.FC = ({ let RenderedType: React.ComponentType | React.ElementType = 'div' - if (onClick && !to) RenderedType = 'button' - if (to) RenderedType = Link + if (onClick && !to) { + RenderedType = 'button' + } + if (to) { + RenderedType = Link + } return ( diff --git a/packages/ui/src/elements/BulkUpload/ActionsBar/index.scss b/packages/ui/src/elements/BulkUpload/ActionsBar/index.scss index 8636c3f92..6ea0e24d3 100644 --- a/packages/ui/src/elements/BulkUpload/ActionsBar/index.scss +++ b/packages/ui/src/elements/BulkUpload/ActionsBar/index.scss @@ -17,21 +17,21 @@ align-items: center; width: 100%; } - + &__locationText { font-variant-numeric: tabular-nums; margin: 0; } - + &__controls { display: flex; gap: calc(var(--base) / 2); - + .btn { background-color: var(--theme-elevation-100); width: calc(var(--base) * 1.2); height: calc(var(--base) * 1.2); - + &:hover { background-color: var(--theme-elevation-200); } diff --git a/packages/ui/src/elements/BulkUpload/ActionsBar/index.tsx b/packages/ui/src/elements/BulkUpload/ActionsBar/index.tsx index 1d7912a56..199bc18f5 100644 --- a/packages/ui/src/elements/BulkUpload/ActionsBar/index.tsx +++ b/packages/ui/src/elements/BulkUpload/ActionsBar/index.tsx @@ -30,8 +30,11 @@ export function ActionsBar() { buttonStyle="none" onClick={() => { const nextIndex = activeIndex - 1 - if (nextIndex < 0) setActiveIndex(forms.length - 1) - else setActiveIndex(nextIndex) + if (nextIndex < 0) { + setActiveIndex(forms.length - 1) + } else { + setActiveIndex(nextIndex) + } }} type="button" > @@ -42,8 +45,11 @@ export function ActionsBar() { buttonStyle="none" onClick={() => { const nextIndex = activeIndex + 1 - if (nextIndex === forms.length) setActiveIndex(0) - else setActiveIndex(nextIndex) + if (nextIndex === forms.length) { + setActiveIndex(0) + } else { + setActiveIndex(nextIndex) + } }} type="button" > diff --git a/packages/ui/src/elements/BulkUpload/AddFilesView/index.scss b/packages/ui/src/elements/BulkUpload/AddFilesView/index.scss index 9573c86c0..d953c728b 100644 --- a/packages/ui/src/elements/BulkUpload/AddFilesView/index.scss +++ b/packages/ui/src/elements/BulkUpload/AddFilesView/index.scss @@ -7,7 +7,7 @@ height: 100%; padding: calc(var(--base) * 2) var(--gutter-h); } - + .dropzone { flex-direction: column; justify-content: center; diff --git a/packages/ui/src/elements/BulkUpload/EditForm/index.tsx b/packages/ui/src/elements/BulkUpload/EditForm/index.tsx index 3c30656f9..2ed5d0c01 100644 --- a/packages/ui/src/elements/BulkUpload/EditForm/index.tsx +++ b/packages/ui/src/elements/BulkUpload/EditForm/index.tsx @@ -197,14 +197,18 @@ function ReportAllErrors() { const reportFormErrorCount = React.useCallback( (errorCount) => { - if (errorCount === errorCountRef.current) return + if (errorCount === errorCountRef.current) { + return + } setFormTotalErrorCount({ errorCount, index: activeIndex }) errorCountRef.current = errorCount }, [activeIndex, setFormTotalErrorCount], ) - if (!docConfig) return null + if (!docConfig) { + return null + } return } diff --git a/packages/ui/src/elements/BulkUpload/FileSidebar/index.scss b/packages/ui/src/elements/BulkUpload/FileSidebar/index.scss index 523882ec1..1135d31fd 100644 --- a/packages/ui/src/elements/BulkUpload/FileSidebar/index.scss +++ b/packages/ui/src/elements/BulkUpload/FileSidebar/index.scss @@ -58,7 +58,7 @@ border-radius: var(--style-radius-m); } } - + &__fileRowContainer { --rowPadding: calc(var(--base) / 4); position: relative; @@ -210,9 +210,8 @@ height: 100%; opacity: 0; transition: opacity 100ms cubic-bezier(0, 0.2, 0.2, 1); - } - + &__showingFiles { .file-selections__mobileBlur { opacity: 1; @@ -230,11 +229,11 @@ &__showingFiles { z-index: 2; } - + &__filesContainer { @include blur-bg; } - + &__fileRowContainer { z-index: 1; } @@ -242,7 +241,7 @@ &__header { margin-top: 0; } - + &__headerTopRow { border-top: 1px solid var(--theme-border-color); padding-block: calc(var(--base) * 0.8); @@ -255,17 +254,17 @@ padding-block: calc(var(--base) * 0.8); padding-inline: var(--file-gutter-h); border-top: 1px solid var(--theme-border-color); - + > div { display: flex; justify-content: flex-end; width: 100%; button { - flex: .5; + flex: 0.5; } } } - + &__toggler { padding-right: 0; display: block; @@ -275,5 +274,4 @@ margin: 0; } } - } diff --git a/packages/ui/src/elements/BulkUpload/FormsManager/index.tsx b/packages/ui/src/elements/BulkUpload/FormsManager/index.tsx index ab6b9e4dc..3cfc4596c 100644 --- a/packages/ui/src/elements/BulkUpload/FormsManager/index.tsx +++ b/packages/ui/src/elements/BulkUpload/FormsManager/index.tsx @@ -327,7 +327,9 @@ export function FormsManagerProvider({ children }: FormsManagerProps) { ) React.useEffect(() => { - if (!collectionSlug) return + if (!collectionSlug) { + return + } if (!hasInitializedState) { void initializeSharedFormState() } diff --git a/packages/ui/src/elements/BulkUpload/index.tsx b/packages/ui/src/elements/BulkUpload/index.tsx index ca89b176a..6080f6b5e 100644 --- a/packages/ui/src/elements/BulkUpload/index.tsx +++ b/packages/ui/src/elements/BulkUpload/index.tsx @@ -25,7 +25,9 @@ function DrawerContent() { [addFiles], ) - if (!collectionSlug) return null + if (!collectionSlug) { + return null + } if (!forms.length && !isInitializing) { return closeModal(drawerSlug)} onDrop={onDrop} /> diff --git a/packages/ui/src/elements/Button/index.tsx b/packages/ui/src/elements/Button/index.tsx index 458958426..f51a50991 100644 --- a/packages/ui/src/elements/Button/index.tsx +++ b/packages/ui/src/elements/Button/index.tsx @@ -89,8 +89,12 @@ export const Button = forwardRef(( function handleClick(event) { setShowTooltip(false) - if (type !== 'submit' && onClick) event.preventDefault() - if (onClick) onClick(event) + if (type !== 'submit' && onClick) { + event.preventDefault() + } + if (onClick) { + onClick(event) + } } const styleClasses = [ @@ -127,7 +131,9 @@ export const Button = forwardRef(( let LinkTag = Link // eslint-disable-line no-case-declarations - if (disabled) LinkTag = 'div' + if (disabled) { + LinkTag = 'div' + } buttonElement = ( @@ -164,7 +170,7 @@ export const Button = forwardRef(( ) break } - if (SubMenuPopupContent) + if (SubMenuPopupContent) { return (
{buttonElement} @@ -180,6 +186,7 @@ export const Button = forwardRef((
) + } return buttonElement }) diff --git a/packages/ui/src/elements/Collapsible/index.tsx b/packages/ui/src/elements/Collapsible/index.tsx index 024586d9c..c88beaddd 100644 --- a/packages/ui/src/elements/Collapsible/index.tsx +++ b/packages/ui/src/elements/Collapsible/index.tsx @@ -48,7 +48,9 @@ export const Collapsible: React.FC = ({ const isCollapsed = typeof collapsedFromProps === 'boolean' ? collapsedFromProps : collapsedLocal const toggleCollapsible = React.useCallback(() => { - if (typeof onToggle === 'function') void onToggle(!isCollapsed) + if (typeof onToggle === 'function') { + void onToggle(!isCollapsed) + } setCollapsedLocal(!isCollapsed) }, [onToggle, isCollapsed]) diff --git a/packages/ui/src/elements/ColumnSelector/index.tsx b/packages/ui/src/elements/ColumnSelector/index.tsx index 33b208056..13cceee01 100644 --- a/packages/ui/src/elements/ColumnSelector/index.tsx +++ b/packages/ui/src/elements/ColumnSelector/index.tsx @@ -49,11 +49,15 @@ export const ColumnSelector: React.FC = ({ collectionSlug }) => { }} > {filteredColumns.map((col, i) => { - if (!col) return null + if (!col) { + return null + } const { Label, accessor, active } = col - if (col.accessor === '_select') return null + if (col.accessor === '_select') { + return null + } return ( = (props) => { if (!customDisplayFormat) { // when no displayFormat is provided, determine format based on the picker appearance - if (pickerAppearance === 'default') dateFormat = 'MM/dd/yyyy' - else if (pickerAppearance === 'dayAndTime') dateFormat = 'MMM d, yyy h:mm a' - else if (pickerAppearance === 'timeOnly') dateFormat = 'h:mm a' - else if (pickerAppearance === 'dayOnly') dateFormat = 'MMM dd' - else if (pickerAppearance === 'monthOnly') dateFormat = 'MMMM' + if (pickerAppearance === 'default') { + dateFormat = 'MM/dd/yyyy' + } else if (pickerAppearance === 'dayAndTime') { + dateFormat = 'MMM d, yyy h:mm a' + } else if (pickerAppearance === 'timeOnly') { + dateFormat = 'h:mm a' + } else if (pickerAppearance === 'dayOnly') { + dateFormat = 'MMM dd' + } else if (pickerAppearance === 'monthOnly') { + dateFormat = 'MMMM' + } } const onChange = (incomingDate: Date) => { @@ -63,7 +69,9 @@ const DatePicker: React.FC = (props) => { const tzOffset = incomingDate.getTimezoneOffset() / 60 newDate.setHours(12 - tzOffset, 0) } - if (typeof onChangeFromProps === 'function') onChangeFromProps(newDate) + if (typeof onChangeFromProps === 'function') { + onChangeFromProps(newDate) + } } const dateTimePickerProps: ReactDatePickerProps = { diff --git a/packages/ui/src/elements/DraggableSortable/index.tsx b/packages/ui/src/elements/DraggableSortable/index.tsx index 26de8ce99..c37800509 100644 --- a/packages/ui/src/elements/DraggableSortable/index.tsx +++ b/packages/ui/src/elements/DraggableSortable/index.tsx @@ -43,7 +43,9 @@ export const DraggableSortable: React.FC = (props) => { event.activatorEvent.stopPropagation() - if (!active || !over) return + if (!active || !over) { + return + } if (typeof onDragEnd === 'function') { onDragEnd({ diff --git a/packages/ui/src/elements/Drawer/index.tsx b/packages/ui/src/elements/Drawer/index.tsx index b7fa99aa6..01a4797ed 100644 --- a/packages/ui/src/elements/Drawer/index.tsx +++ b/packages/ui/src/elements/Drawer/index.tsx @@ -31,7 +31,9 @@ export const DrawerToggler: React.FC = ({ const handleClick = useCallback( (e) => { openModal(slug) - if (typeof onClick === 'function') onClick(e) + if (typeof onClick === 'function') { + onClick(e) + } }, [openModal, slug, onClick], ) diff --git a/packages/ui/src/elements/Dropzone/index.scss b/packages/ui/src/elements/Dropzone/index.scss index c1dbb1d94..6a1ef6d90 100644 --- a/packages/ui/src/elements/Dropzone/index.scss +++ b/packages/ui/src/elements/Dropzone/index.scss @@ -4,7 +4,7 @@ position: relative; display: flex; align-items: center; - padding: calc(var(--base) * .9) var(--base); + padding: calc(var(--base) * 0.9) var(--base); background: transparent; border: 1px dotted var(--theme-elevation-400); border-radius: var(--style-radius-s); diff --git a/packages/ui/src/elements/EditUpload/index.tsx b/packages/ui/src/elements/EditUpload/index.tsx index 5dff698c4..e962b84f9 100644 --- a/packages/ui/src/elements/EditUpload/index.tsx +++ b/packages/ui/src/elements/EditUpload/index.tsx @@ -112,13 +112,19 @@ export const EditUpload: React.FC = ({ const fineTuneCrop = ({ dimension, value }: { dimension: 'height' | 'width'; value: string }) => { const intValue = parseInt(value) - if (dimension === 'width' && intValue >= uncroppedPixelWidth) return null - if (dimension === 'height' && intValue >= uncroppedPixelHeight) return null + if (dimension === 'width' && intValue >= uncroppedPixelWidth) { + return null + } + if (dimension === 'height' && intValue >= uncroppedPixelHeight) { + return null + } const percentage = 100 * (intValue / (dimension === 'width' ? uncroppedPixelWidth : uncroppedPixelHeight)) - if (percentage === 100 || percentage === 0) return null + if (percentage === 100 || percentage === 0) { + return null + } setCrop({ ...crop, @@ -140,13 +146,14 @@ export const EditUpload: React.FC = ({ } const saveEdits = () => { - if (typeof onSave === 'function') + if (typeof onSave === 'function') { onSave({ crop: crop ? crop : undefined, focalPoint: focalPosition, heightInPixels: Number(heightInputRef?.current?.value ?? uncroppedPixelHeight), widthInPixels: Number(widthInputRef?.current?.value ?? uncroppedPixelWidth), }) + } closeModal(editDrawerSlug) } @@ -393,7 +400,9 @@ const DraggableElement = ({ } const handleMouseMove = (event) => { - if (!isDragging) return null + if (!isDragging) { + return null + } const { x, y } = getCoordinates(event.clientX, event.clientY) setPosition({ x, y }) @@ -405,7 +414,9 @@ const DraggableElement = ({ } React.useEffect(() => { - if (isDragging || !dragRef.current) return + if (isDragging || !dragRef.current) { + return + } if (checkBounds) { const { height, left, top, width } = dragRef.current.getBoundingClientRect() const { x, y } = getCoordinates(left + width / 2, top + height / 2, true) diff --git a/packages/ui/src/elements/ErrorPill/index.tsx b/packages/ui/src/elements/ErrorPill/index.tsx index 94e763478..e8e9b50aa 100644 --- a/packages/ui/src/elements/ErrorPill/index.tsx +++ b/packages/ui/src/elements/ErrorPill/index.tsx @@ -22,7 +22,9 @@ export const ErrorPill: React.FC = (props) => { .filter(Boolean) .join(' ') - if (count === 0) return null + if (count === 0) { + return null + } return (
diff --git a/packages/ui/src/elements/FieldSelect/index.tsx b/packages/ui/src/elements/FieldSelect/index.tsx index 417f41f1b..83a617084 100644 --- a/packages/ui/src/elements/FieldSelect/index.tsx +++ b/packages/ui/src/elements/FieldSelect/index.tsx @@ -57,7 +57,9 @@ export const combineLabel = ({ RenderedComponent: customLabel, } - if (!LabelToRender) return null + if (!LabelToRender) { + return null + } return ( diff --git a/packages/ui/src/elements/ListDrawer/DrawerContent.tsx b/packages/ui/src/elements/ListDrawer/DrawerContent.tsx index 894971734..9bd3219f8 100644 --- a/packages/ui/src/elements/ListDrawer/DrawerContent.tsx +++ b/packages/ui/src/elements/ListDrawer/DrawerContent.tsx @@ -185,11 +185,21 @@ export const ListDrawerContent: React.FC = ({ } } - if (page) params.page = page - if (sort) params.sort = sort - if (cacheBust) params.cacheBust = cacheBust - if (copyOfWhere) params.where = copyOfWhere - if (versions?.drafts) params.draft = 'true' + if (page) { + params.page = page + } + if (sort) { + params.sort = sort + } + if (cacheBust) { + params.cacheBust = cacheBust + } + if (copyOfWhere) { + params.where = copyOfWhere + } + if (versions?.drafts) { + params.draft = 'true' + } setParams(params) }, [page, sort, where, search, cacheBust, filterOptions, selectedCollectionConfig, t, setParams]) diff --git a/packages/ui/src/elements/ListDrawer/index.scss b/packages/ui/src/elements/ListDrawer/index.scss index 47d6c2f27..ccda4f21a 100644 --- a/packages/ui/src/elements/ListDrawer/index.scss +++ b/packages/ui/src/elements/ListDrawer/index.scss @@ -50,7 +50,7 @@ &:focus-within:not(:focus-visible) { outline: none; } - + &:focus-visible { outline: var(--accessibility-outline); outline-offset: var(--accessibility-outline-offset); diff --git a/packages/ui/src/elements/Pagination/index.tsx b/packages/ui/src/elements/Pagination/index.tsx index 3f275b7a5..b2d678d89 100644 --- a/packages/ui/src/elements/Pagination/index.tsx +++ b/packages/ui/src/elements/Pagination/index.tsx @@ -52,10 +52,14 @@ export const Pagination: React.FC = (props) => { totalPages = null, } = props - if (!totalPages || totalPages <= 1) return null + if (!totalPages || totalPages <= 1) { + return null + } const updatePage = (page) => { - if (typeof onChange === 'function') onChange(page) + if (typeof onChange === 'function') { + onChange(page) + } } // Create array of integers for each page @@ -65,7 +69,9 @@ export const Pagination: React.FC = (props) => { let rangeStartIndex = currentPage - 1 - numberOfNeighbors // Sanitize rangeStartIndex in case it is less than zero for safe split - if (rangeStartIndex <= 0) rangeStartIndex = 0 + if (rangeStartIndex <= 0) { + rangeStartIndex = 0 + } const rangeEndIndex = currentPage - 1 + numberOfNeighbors + 1 @@ -73,7 +79,9 @@ export const Pagination: React.FC = (props) => { const nodes: Node[] = pages.slice(rangeStartIndex, rangeEndIndex) // Add prev separator if necessary - if (currentPage - numberOfNeighbors - 1 >= 2) nodes.unshift({ type: 'Separator' }) + if (currentPage - numberOfNeighbors - 1 >= 2) { + nodes.unshift({ type: 'Separator' }) + } // Add first page if necessary if (currentPage > numberOfNeighbors + 1) { nodes.unshift({ @@ -87,7 +95,9 @@ export const Pagination: React.FC = (props) => { } // Add next separator if necessary - if (currentPage + numberOfNeighbors + 1 < totalPages) nodes.push({ type: 'Separator' }) + if (currentPage + numberOfNeighbors + 1 < totalPages) { + nodes.push({ type: 'Separator' }) + } // Add last page if necessary if (rangeEndIndex < totalPages) { nodes.push({ diff --git a/packages/ui/src/elements/PerPage/index.tsx b/packages/ui/src/elements/PerPage/index.tsx index 3d30ee209..d105ef40e 100644 --- a/packages/ui/src/elements/PerPage/index.tsx +++ b/packages/ui/src/elements/PerPage/index.tsx @@ -54,7 +54,9 @@ export const PerPage: React.FC = ({ key={i} onClick={() => { close() - if (handleChange) handleChange(limitNumber) + if (handleChange) { + handleChange(limitNumber) + } }} > {limitNumber === limitToUse && ( diff --git a/packages/ui/src/elements/Pill/index.tsx b/packages/ui/src/elements/Pill/index.tsx index d95579668..42863f6a1 100644 --- a/packages/ui/src/elements/Pill/index.tsx +++ b/packages/ui/src/elements/Pill/index.tsx @@ -95,8 +95,12 @@ const StaticPill: React.FC = (props) => { let Element: ElementType | React.FC = 'div' - if (onClick && !to) Element = 'button' - if (to) Element = Link + if (onClick && !to) { + Element = 'button' + } + if (to) { + Element = Link + } return ( = (props) => { export const Pill: React.FC = (props) => { const { draggable } = props - if (draggable) return + if (draggable) { + return + } return } diff --git a/packages/ui/src/elements/Popup/PopupTrigger/index.tsx b/packages/ui/src/elements/Popup/PopupTrigger/index.tsx index a206c4192..b92330177 100644 --- a/packages/ui/src/elements/Popup/PopupTrigger/index.tsx +++ b/packages/ui/src/elements/Popup/PopupTrigger/index.tsx @@ -41,7 +41,9 @@ export const PopupTrigger: React.FC = (props) => { className={classes} onClick={handleClick} onKeyDown={(e) => { - if (e.key === 'Enter') handleClick() + if (e.key === 'Enter') { + handleClick() + } }} role="button" tabIndex={0} diff --git a/packages/ui/src/elements/Popup/index.tsx b/packages/ui/src/elements/Popup/index.tsx index 520e3d731..b9c1b3de3 100644 --- a/packages/ui/src/elements/Popup/index.tsx +++ b/packages/ui/src/elements/Popup/index.tsx @@ -133,7 +133,9 @@ export const Popup: React.FC = (props) => { }, [intersectionEntry, setPosition, windowHeight]) useEffect(() => { - if (typeof onToggleOpen === 'function') onToggleOpen(active) + if (typeof onToggleOpen === 'function') { + onToggleOpen(active) + } if (active) { document.addEventListener('mousedown', handleClickOutside) diff --git a/packages/ui/src/elements/PreviewButton/usePreviewURL.tsx b/packages/ui/src/elements/PreviewButton/usePreviewURL.tsx index d7970f793..cc96f7c17 100644 --- a/packages/ui/src/elements/PreviewButton/usePreviewURL.tsx +++ b/packages/ui/src/elements/PreviewButton/usePreviewURL.tsx @@ -35,25 +35,37 @@ export const usePreviewURL = (): { // this will ensure the latest data is used when generating the preview URL const generatePreviewURL = useCallback( async ({ openPreviewWindow = false }) => { - if (isGeneratingPreviewURL.current) return + if (isGeneratingPreviewURL.current) { + return + } isGeneratingPreviewURL.current = true try { setIsLoading(true) let url = `${serverURL}${api}` - if (collectionSlug) url = `${url}/${collectionSlug}/${id}/preview` - if (globalSlug) url = `${url}/globals/${globalSlug}/preview` + if (collectionSlug) { + url = `${url}/${collectionSlug}/${id}/preview` + } + if (globalSlug) { + url = `${url}/globals/${globalSlug}/preview` + } const res = await fetch(`${url}${locale ? `?locale=${locale}` : ''}`) - if (!res.ok) throw new Error() + if (!res.ok) { + throw new Error() + } const newPreviewURL = await res.json() - if (!newPreviewURL) throw new Error() + if (!newPreviewURL) { + throw new Error() + } setPreviewURL(newPreviewURL) setIsLoading(false) isGeneratingPreviewURL.current = false - if (openPreviewWindow) window.open(newPreviewURL, '_blank') + if (openPreviewWindow) { + window.open(newPreviewURL, '_blank') + } } catch (err) { setIsLoading(false) isGeneratingPreviewURL.current = false diff --git a/packages/ui/src/elements/PreviewSizes/index.tsx b/packages/ui/src/elements/PreviewSizes/index.tsx index da43faa37..c997aae52 100644 --- a/packages/ui/src/elements/PreviewSizes/index.tsx +++ b/packages/ui/src/elements/PreviewSizes/index.tsx @@ -16,7 +16,9 @@ type FilesSizesWithUrl = { } const sortSizes = (sizes: FilesSizesWithUrl, imageSizes: SanitizedUploadConfig['imageSizes']) => { - if (!imageSizes || imageSizes.length === 0) return sizes + if (!imageSizes || imageSizes.length === 0) { + return sizes + } const orderedSizes: FilesSizesWithUrl = {} @@ -50,8 +52,12 @@ const PreviewSizeCard: React.FC = ({ .join(' ')} onClick={typeof onClick === 'function' ? onClick : undefined} onKeyDown={(e) => { - if (typeof onClick !== 'function') return - if (e.key === 'Enter') onClick() + if (typeof onClick !== 'function') { + return + } + if (e.key === 'Enter') { + onClick() + } }} role="button" tabIndex={0} @@ -85,8 +91,12 @@ export const PreviewSizes: React.FC = ({ doc, imageCacheTag, const [selectedSize, setSelectedSize] = useState(null) const generateImageUrl = (doc) => { - if (!doc.filename) return null - if (doc.url) return `${doc.url}${imageCacheTag ? `?${imageCacheTag}` : ''}` + if (!doc.filename) { + return null + } + if (doc.url) { + return `${doc.url}${imageCacheTag ? `?${imageCacheTag}` : ''}` + } } useEffect(() => { setOrderedSizes(sortSizes(sizes, imageSizes)) diff --git a/packages/ui/src/elements/PublishButton/index.tsx b/packages/ui/src/elements/PublishButton/index.tsx index 837ada34a..198ce09ba 100644 --- a/packages/ui/src/elements/PublishButton/index.tsx +++ b/packages/ui/src/elements/PublishButton/index.tsx @@ -48,7 +48,9 @@ export const DefaultPublishButton: React.FC<{ label?: string }> = ({ label: labe const forceDisable = operation === 'update' && !modified const saveDraft = useCallback(async () => { - if (forceDisable) return + if (forceDisable) { + return + } const search = `?locale=${locale}&depth=0&fallback-locale=null&draft=true` let action @@ -56,7 +58,9 @@ export const DefaultPublishButton: React.FC<{ label?: string }> = ({ label: labe if (collectionSlug) { action = `${serverURL}${api}/${collectionSlug}${id ? `/${id}` : ''}${search}` - if (id) method = 'PATCH' + if (id) { + method = 'PATCH' + } } if (globalSlug) { @@ -90,7 +94,9 @@ export const DefaultPublishButton: React.FC<{ label?: string }> = ({ label: labe }) }, [submit]) - if (!hasPublishPermission) return null + if (!hasPublishPermission) { + return null + } return ( = ({ CustomComponent }) => { - if (CustomComponent) return + if (CustomComponent) { + return + } return } diff --git a/packages/ui/src/elements/ReactSelect/DropdownIndicator/index.tsx b/packages/ui/src/elements/ReactSelect/DropdownIndicator/index.tsx index 1648fb4ef..7399d8721 100644 --- a/packages/ui/src/elements/ReactSelect/DropdownIndicator/index.tsx +++ b/packages/ui/src/elements/ReactSelect/DropdownIndicator/index.tsx @@ -24,7 +24,9 @@ export const DropdownIndicator: React.FC< ref={ref} {...restInnerProps} onKeyDown={(e) => { - if (e.key === 'Enter') e.key = ' ' + if (e.key === 'Enter') { + e.key = ' ' + } }} type="button" > diff --git a/packages/ui/src/elements/ReactSelect/index.tsx b/packages/ui/src/elements/ReactSelect/index.tsx index 5cfc6a918..e497115f1 100644 --- a/packages/ui/src/elements/ReactSelect/index.tsx +++ b/packages/ui/src/elements/ReactSelect/index.tsx @@ -129,7 +129,9 @@ const SelectAdapter: React.FC = (props) => { return } } - if (!value || !inputValue || inputValue.trim() === '') return + if (!value || !inputValue || inputValue.trim() === '') { + return + } if (filterOption && !filterOption(null, inputValue)) { return } diff --git a/packages/ui/src/elements/SaveButton/index.tsx b/packages/ui/src/elements/SaveButton/index.tsx index 249ea428b..f04246861 100644 --- a/packages/ui/src/elements/SaveButton/index.tsx +++ b/packages/ui/src/elements/SaveButton/index.tsx @@ -56,6 +56,8 @@ type Props = { } export const SaveButton: React.FC = ({ CustomComponent }) => { - if (CustomComponent) return + if (CustomComponent) { + return + } return } diff --git a/packages/ui/src/elements/SaveDraftButton/index.tsx b/packages/ui/src/elements/SaveDraftButton/index.tsx index 8a51333ad..4d7cb4fb5 100644 --- a/packages/ui/src/elements/SaveDraftButton/index.tsx +++ b/packages/ui/src/elements/SaveDraftButton/index.tsx @@ -36,7 +36,9 @@ export const DefaultSaveDraftButton: React.FC = () => { const forceDisable = operation === 'update' && !modified const saveDraft = useCallback(async () => { - if (forceDisable) return + if (forceDisable) { + return + } const search = `?locale=${locale}&depth=0&fallback-locale=null&draft=true` let action @@ -44,7 +46,9 @@ export const DefaultSaveDraftButton: React.FC = () => { if (collectionSlug) { action = `${serverURL}${api}/${collectionSlug}${id ? `/${id}` : ''}${search}` - if (id) method = 'PATCH' + if (id) { + method = 'PATCH' + } } if (globalSlug) { @@ -96,6 +100,8 @@ type Props = { } export const SaveDraftButton: React.FC = ({ CustomComponent }) => { - if (CustomComponent) return + if (CustomComponent) { + return + } return } diff --git a/packages/ui/src/elements/SearchFilter/index.tsx b/packages/ui/src/elements/SearchFilter/index.tsx index 2cfd3c0d7..01a9535cd 100644 --- a/packages/ui/src/elements/SearchFilter/index.tsx +++ b/packages/ui/src/elements/SearchFilter/index.tsx @@ -28,7 +28,9 @@ export const SearchFilter: React.FC = (props) => { useEffect(() => { if (debouncedSearch !== previousSearch.current) { - if (handleChange) handleChange(debouncedSearch) + if (handleChange) { + handleChange(debouncedSearch) + } previousSearch.current = debouncedSearch } diff --git a/packages/ui/src/elements/ShimmerEffect/index.tsx b/packages/ui/src/elements/ShimmerEffect/index.tsx index 9f298d122..be27d8fa7 100644 --- a/packages/ui/src/elements/ShimmerEffect/index.tsx +++ b/packages/ui/src/elements/ShimmerEffect/index.tsx @@ -55,7 +55,9 @@ export const StaggeredShimmers: React.FC = ({ const shimmerDelayToPass = typeof shimmerDelay === 'number' ? `${shimmerDelay}ms` : shimmerDelay const [hasDelayed] = useDelay(renderDelay, true) - if (!hasDelayed) return null + if (!hasDelayed) { + return null + } return (
diff --git a/packages/ui/src/elements/SortColumn/index.tsx b/packages/ui/src/elements/SortColumn/index.tsx index e5319c8b2..6c423bd5e 100644 --- a/packages/ui/src/elements/SortColumn/index.tsx +++ b/packages/ui/src/elements/SortColumn/index.tsx @@ -31,10 +31,14 @@ export const SortColumn: React.FC = (props) => { const asc = name const ascClasses = [`${baseClass}__asc`] - if (sort === asc) ascClasses.push(`${baseClass}--active`) + if (sort === asc) { + ascClasses.push(`${baseClass}--active`) + } const descClasses = [`${baseClass}__desc`] - if (sort === desc) descClasses.push(`${baseClass}--active`) + if (sort === desc) { + descClasses.push(`${baseClass}--active`) + } const setSort = useCallback( async (newSort: string) => { diff --git a/packages/ui/src/elements/SortComplex/index.tsx b/packages/ui/src/elements/SortComplex/index.tsx index cc08b65c3..67fb737ec 100644 --- a/packages/ui/src/elements/SortComplex/index.tsx +++ b/packages/ui/src/elements/SortComplex/index.tsx @@ -54,7 +54,9 @@ export const SortComplex: React.FC = (props) => { if (sortField?.value) { const newSortValue = `${sortOrder.value}${sortField.value}` - if (handleChange) handleChange(newSortValue) + if (handleChange) { + handleChange(newSortValue) + } if (searchParams.sort !== newSortValue && modifySearchQuery) { const search = qs.stringify( diff --git a/packages/ui/src/elements/TableColumns/buildColumnState.tsx b/packages/ui/src/elements/TableColumns/buildColumnState.tsx index 49c5e0b5a..9a41503cc 100644 --- a/packages/ui/src/elements/TableColumns/buildColumnState.tsx +++ b/packages/ui/src/elements/TableColumns/buildColumnState.tsx @@ -58,9 +58,15 @@ export const buildColumnState = (args: Args): Column[] => { sortedFieldMap = sortedFieldMap.sort((a, b) => { const aIndex = sortTo.findIndex((column) => 'name' in a && column.accessor === a.name) const bIndex = sortTo.findIndex((column) => 'name' in b && column.accessor === b.name) - if (aIndex === -1 && bIndex === -1) return 0 - if (aIndex === -1) return 1 - if (bIndex === -1) return -1 + if (aIndex === -1 && bIndex === -1) { + return 0 + } + if (aIndex === -1) { + return 1 + } + if (bIndex === -1) { + return -1 + } return aIndex - bIndex }) } diff --git a/packages/ui/src/elements/TableColumns/index.tsx b/packages/ui/src/elements/TableColumns/index.tsx index e82fafa56..29659d4ae 100644 --- a/packages/ui/src/elements/TableColumns/index.tsx +++ b/packages/ui/src/elements/TableColumns/index.tsx @@ -91,7 +91,9 @@ export const TableColumnsProvider: React.FC = ({ let foundFirstActive = false const newColumns = columns.map((col) => { const linkColumn = col.active && !foundFirstActive && col.accessor !== '_select' - if (linkColumn) foundFirstActive = true + if (linkColumn) { + foundFirstActive = true + } return { ...col, diff --git a/packages/ui/src/elements/Tooltip/index.tsx b/packages/ui/src/elements/Tooltip/index.tsx index 906474873..6b57d3873 100644 --- a/packages/ui/src/elements/Tooltip/index.tsx +++ b/packages/ui/src/elements/Tooltip/index.tsx @@ -55,12 +55,16 @@ export const Tooltip: React.FC = (props) => { } return () => { - if (timerId) clearTimeout(timerId) + if (timerId) { + clearTimeout(timerId) + } } }, [showFromProps, delay]) useEffect(() => { - if (staticPositioning) return + if (staticPositioning) { + return + } setPosition(intersectionEntry?.isIntersecting ? 'top' : 'bottom') }, [intersectionEntry, staticPositioning]) diff --git a/packages/ui/src/elements/Upload/index.scss b/packages/ui/src/elements/Upload/index.scss index 4f687eeb1..6bd333919 100644 --- a/packages/ui/src/elements/Upload/index.scss +++ b/packages/ui/src/elements/Upload/index.scss @@ -97,7 +97,7 @@ &__dropzoneButtons { display: flex; - gap: calc(var(--base) * .5); + gap: calc(var(--base) * 0.5); } &__orText { diff --git a/packages/ui/src/elements/Upload/index.tsx b/packages/ui/src/elements/Upload/index.tsx index 995e860c0..271e6b290 100644 --- a/packages/ui/src/elements/Upload/index.tsx +++ b/packages/ui/src/elements/Upload/index.tsx @@ -50,7 +50,9 @@ export const UploadActions = ({ const fileTypeIsAdjustable = isImage(mimeType) && mimeType !== 'image/svg+xml' - if (!fileTypeIsAdjustable && (!customActions || customActions.length === 0)) return null + if (!fileTypeIsAdjustable && (!customActions || customActions.length === 0)) { + return null + } return (
diff --git a/packages/ui/src/elements/WhereBuilder/reduceClientFields.tsx b/packages/ui/src/elements/WhereBuilder/reduceClientFields.tsx index e518f5b00..bfe546e5e 100644 --- a/packages/ui/src/elements/WhereBuilder/reduceClientFields.tsx +++ b/packages/ui/src/elements/WhereBuilder/reduceClientFields.tsx @@ -29,7 +29,9 @@ export const reduceClientFields = ({ pathPrefix, }: ReduceClientFieldsArgs): FieldCondition[] => { return fields.reduce((reduced, field) => { - if (field.admin?.disableListFilter) return reduced + if (field.admin?.disableListFilter) { + return reduced + } if (field.type === 'tabs' && 'tabs' in field) { const tabs = field.tabs diff --git a/packages/ui/src/fields/Array/index.tsx b/packages/ui/src/fields/Array/index.tsx index 36e4ab565..bc7dd6c06 100644 --- a/packages/ui/src/fields/Array/index.tsx +++ b/packages/ui/src/fields/Array/index.tsx @@ -89,8 +89,12 @@ export const ArrayFieldComponent: React.FC = (props) => { // Handle labeling for Arrays, Global Arrays, and Blocks const getLabels = (p: ArrayFieldProps): Partial => { - if ('labels' in p && p?.labels) return p.labels - if ('label' in p.field && p.field.label) return { plural: undefined, singular: p.field.label } + if ('labels' in p && p?.labels) { + return p.labels + } + if ('label' in p.field && p.field.label) { + return { plural: undefined, singular: p.field.label } + } return { plural: t('general:rows'), singular: t('general:row') } } diff --git a/packages/ui/src/fields/Blocks/BlocksDrawer/index.tsx b/packages/ui/src/fields/Blocks/BlocksDrawer/index.tsx index 5f669840e..6e6034b91 100644 --- a/packages/ui/src/fields/Blocks/BlocksDrawer/index.tsx +++ b/packages/ui/src/fields/Blocks/BlocksDrawer/index.tsx @@ -24,7 +24,9 @@ export type Props = { const baseClass = 'blocks-drawer' const getBlockLabel = (block: ClientBlock, i18n: I18nClient) => { - if (typeof block.labels.singular === 'string') return block.labels.singular.toLowerCase() + if (typeof block.labels.singular === 'string') { + return block.labels.singular.toLowerCase() + } if (typeof block.labels.singular === 'object') { return getTranslation(block.labels.singular, i18n).toLowerCase() } @@ -50,7 +52,9 @@ export const BlocksDrawer: React.FC = (props) => { const matchingBlocks = blocks?.reduce((matchedBlocks, block) => { const blockLabel = getBlockLabel(block, i18n) - if (blockLabel.includes(searchTermToUse)) matchedBlocks.push(block) + if (blockLabel.includes(searchTermToUse)) { + matchedBlocks.push(block) + } return matchedBlocks }, []) diff --git a/packages/ui/src/fields/Checkbox/index.tsx b/packages/ui/src/fields/Checkbox/index.tsx index f4f4ba2d1..50f825171 100644 --- a/packages/ui/src/fields/Checkbox/index.tsx +++ b/packages/ui/src/fields/Checkbox/index.tsx @@ -76,7 +76,9 @@ const CheckboxFieldComponent: React.FC = (props) => { const onToggle = useCallback(() => { if (!disabled) { setValue(!value) - if (typeof onChangeFromProps === 'function') onChangeFromProps(!value) + if (typeof onChangeFromProps === 'function') { + onChangeFromProps(!value) + } } }, [onChangeFromProps, disabled, setValue, value]) diff --git a/packages/ui/src/fields/Collapsible/index.tsx b/packages/ui/src/fields/Collapsible/index.tsx index 2b2a9fa66..670d1ef12 100644 --- a/packages/ui/src/fields/Collapsible/index.tsx +++ b/packages/ui/src/fields/Collapsible/index.tsx @@ -110,7 +110,9 @@ const CollapsibleFieldComponent: React.FC = (props) => { void fetchInitialState() }, [getPreference, preferencesKey, fieldPreferencesKey, initCollapsed, path]) - if (typeof collapsedOnMount !== 'boolean') return null + if (typeof collapsedOnMount !== 'boolean') { + return null + } const disabled = readOnlyFromProps || readOnlyFromContext || formProcessing || formInitializing diff --git a/packages/ui/src/fields/DateTime/index.tsx b/packages/ui/src/fields/DateTime/index.tsx index 689f78e06..7b3beea3a 100644 --- a/packages/ui/src/fields/DateTime/index.tsx +++ b/packages/ui/src/fields/DateTime/index.tsx @@ -99,7 +99,9 @@ const DateTimeFieldComponent: React.FC = (props) => { { - if (!disabled) setValue(incomingDate?.toISOString() || null) + if (!disabled) { + setValue(incomingDate?.toISOString() || null) + } }} placeholder={getTranslation(placeholder, i18n)} readOnly={disabled} diff --git a/packages/ui/src/fields/JSON/index.tsx b/packages/ui/src/fields/JSON/index.tsx index 7d2fe98f6..56e3bc195 100644 --- a/packages/ui/src/fields/JSON/index.tsx +++ b/packages/ui/src/fields/JSON/index.tsx @@ -49,8 +49,9 @@ const JSONFieldComponent: React.FC = (props) => { const memoizedValidate = useCallback( (value, options) => { - if (typeof validate === 'function') + if (typeof validate === 'function') { return validate(value, { ...options, jsonError, required }) + } }, [validate, required, jsonError], ) @@ -67,7 +68,9 @@ const JSONFieldComponent: React.FC = (props) => { const handleMount = useCallback( (editor, monaco) => { - if (!jsonSchema) return + if (!jsonSchema) { + return + } const existingSchemas = monaco.languages.json.jsonDefaults.diagnosticsOptions.schemas || [] const modelUri = monaco.Uri.parse(jsonSchema.uri) @@ -86,7 +89,9 @@ const JSONFieldComponent: React.FC = (props) => { const handleChange = useCallback( (val) => { - if (disabled) return + if (disabled) { + return + } setStringValue(val) try { @@ -101,7 +106,9 @@ const JSONFieldComponent: React.FC = (props) => { ) useEffect(() => { - if (hasLoadedValue || value === undefined) return + if (hasLoadedValue || value === undefined) { + return + } setStringValue( value || initialValue ? JSON.stringify(value ? value : initialValue, null, 2) : '', diff --git a/packages/ui/src/fields/RadioGroup/index.tsx b/packages/ui/src/fields/RadioGroup/index.tsx index 54ec13058..cd755167e 100644 --- a/packages/ui/src/fields/RadioGroup/index.tsx +++ b/packages/ui/src/fields/RadioGroup/index.tsx @@ -50,8 +50,9 @@ const RadioGroupFieldComponent: React.FC = (props) => { const memoizedValidate = useCallback( (value, validationOptions) => { - if (typeof validate === 'function') + if (typeof validate === 'function') { return validate(value, { ...validationOptions, options, required }) + } }, [validate, options, required], ) diff --git a/packages/ui/src/fields/Relationship/index.tsx b/packages/ui/src/fields/Relationship/index.tsx index cd3996802..10ca8e369 100644 --- a/packages/ui/src/fields/Relationship/index.tsx +++ b/packages/ui/src/fields/Relationship/index.tsx @@ -260,7 +260,9 @@ const RelationshipFieldComponent: React.FC = (props) => } }, Promise.resolve()) - if (typeof onSuccess === 'function') onSuccess() + if (typeof onSuccess === 'function') { + onSuccess() + } } }, [ @@ -466,7 +468,9 @@ const RelationshipFieldComponent: React.FC = (props) => const valueToRender = findOptionsByValue({ options, value }) - if (!Array.isArray(valueToRender) && valueToRender?.value === 'null') valueToRender.value = null + if (!Array.isArray(valueToRender) && valueToRender?.value === 'null') { + valueToRender.value = null + } return (
= (props) => disabled={readOnly || formProcessing || drawerIsOpen} filterOption={enableWordBoundarySearch ? filterOption : undefined} getOptionValue={(option) => { - if (!option) return undefined + if (!option) { + return undefined + } return hasMany && Array.isArray(relationTo) ? `${option.relationTo}_${option.value}` : option.value diff --git a/packages/ui/src/fields/Relationship/select-components/MultiValueLabel/index.tsx b/packages/ui/src/fields/Relationship/select-components/MultiValueLabel/index.tsx index 1276f4225..77ce0269e 100644 --- a/packages/ui/src/fields/Relationship/select-components/MultiValueLabel/index.tsx +++ b/packages/ui/src/fields/Relationship/select-components/MultiValueLabel/index.tsx @@ -41,7 +41,9 @@ export const MultiValueLabel: React.FC> = (props) => { }) useEffect(() => { - if (typeof setDrawerIsOpen === 'function') setDrawerIsOpen(isDrawerOpen) + if (typeof setDrawerIsOpen === 'function') { + setDrawerIsOpen(isDrawerOpen) + } }, [isDrawerOpen, setDrawerIsOpen]) return ( diff --git a/packages/ui/src/fields/Select/index.tsx b/packages/ui/src/fields/Select/index.tsx index ec11ae166..56e0e0a7f 100644 --- a/packages/ui/src/fields/Select/index.tsx +++ b/packages/ui/src/fields/Select/index.tsx @@ -53,8 +53,9 @@ const SelectFieldComponent: React.FC = (props) => { const memoizedValidate = useCallback( (value, validationOptions) => { - if (typeof validate === 'function') + if (typeof validate === 'function') { return validate(value, { ...validationOptions, hasMany, options, required }) + } }, [validate, required, hasMany, options], ) diff --git a/packages/ui/src/fields/Text/index.tsx b/packages/ui/src/fields/Text/index.tsx index c7325c18f..751ca480b 100644 --- a/packages/ui/src/fields/Text/index.tsx +++ b/packages/ui/src/fields/Text/index.tsx @@ -55,8 +55,9 @@ const TextFieldComponent: React.FC = (props) => { const memoizedValidate = useCallback( (value, options) => { - if (typeof validate === 'function') + if (typeof validate === 'function') { return validate(value, { ...options, maxLength, minLength, required }) + } }, [validate, minLength, maxLength, required], ) diff --git a/packages/ui/src/fields/Textarea/index.tsx b/packages/ui/src/fields/Textarea/index.tsx index df9c82db5..e1c61c157 100644 --- a/packages/ui/src/fields/Textarea/index.tsx +++ b/packages/ui/src/fields/Textarea/index.tsx @@ -64,8 +64,9 @@ const TextareaFieldComponent: React.FC = (props) => { const memoizedValidate: TextareaFieldValidation = useCallback( (value, options) => { - if (typeof validate === 'function') + if (typeof validate === 'function') { return validate(value, { ...options, maxLength, minLength, required }) + } }, [validate, required, maxLength, minLength], ) diff --git a/packages/ui/src/fields/Upload/HasMany/index.tsx b/packages/ui/src/fields/Upload/HasMany/index.tsx index ff62121d8..360328db9 100644 --- a/packages/ui/src/fields/Upload/HasMany/index.tsx +++ b/packages/ui/src/fields/Upload/HasMany/index.tsx @@ -30,7 +30,9 @@ export function UploadComponentHasMany(props: Props) { const moveRow = React.useCallback( (moveFromIndex: number, moveToIndex: number) => { - if (moveFromIndex === moveToIndex) return + if (moveFromIndex === moveToIndex) { + return + } const updatedArray = [...fileDocs] const [item] = updatedArray.splice(moveFromIndex, 1) diff --git a/packages/ui/src/fields/Upload/HasOne/index.scss b/packages/ui/src/fields/Upload/HasOne/index.scss index b14928338..b07ac1a75 100644 --- a/packages/ui/src/fields/Upload/HasOne/index.scss +++ b/packages/ui/src/fields/Upload/HasOne/index.scss @@ -4,4 +4,3 @@ position: relative; max-width: 100%; } - diff --git a/packages/ui/src/fields/Upload/Input.tsx b/packages/ui/src/fields/Upload/Input.tsx index 091f3a980..38f5ede6f 100644 --- a/packages/ui/src/fields/Upload/Input.tsx +++ b/packages/ui/src/fields/Upload/Input.tsx @@ -259,10 +259,14 @@ export function UploadInput(props: UploadInputProps) { dataTransfer.items.add(fileList[0]) fileListToUse = dataTransfer.files } - if (fileListToUse) setInitialFiles(fileListToUse) + if (fileListToUse) { + setInitialFiles(fileListToUse) + } setCollectionSlug(relationTo) setOnSuccess(onUploadSuccess) - if (typeof maxRows === 'number') setMaxFiles(maxRows) + if (typeof maxRows === 'number') { + setMaxFiles(maxRows) + } openModal(drawerSlug) }, [ diff --git a/packages/ui/src/fields/Upload/RelationshipContent/index.scss b/packages/ui/src/fields/Upload/RelationshipContent/index.scss index 151573fe1..9f8437d56 100644 --- a/packages/ui/src/fields/Upload/RelationshipContent/index.scss +++ b/packages/ui/src/fields/Upload/RelationshipContent/index.scss @@ -22,7 +22,7 @@ flex-direction: column; gap: 0; overflow: hidden; - margin-right: calc(var(--base)* 2); + margin-right: calc(var(--base) * 2); } &__filename { diff --git a/packages/ui/src/fields/Upload/UploadCard/index.scss b/packages/ui/src/fields/Upload/UploadCard/index.scss index 8c9ab9e44..a9a46df7e 100644 --- a/packages/ui/src/fields/Upload/UploadCard/index.scss +++ b/packages/ui/src/fields/Upload/UploadCard/index.scss @@ -8,7 +8,7 @@ gap: calc(var(--base) / 2); &--size-medium { - padding: calc(var(--base) * .5); + padding: calc(var(--base) * 0.5); .thumbnail { width: 40px; @@ -18,10 +18,10 @@ &--size-small { padding: calc(var(--base) / 3) calc(var(--base) / 2); - + .thumbnail { width: 25px; height: 25px; } - }; + } } diff --git a/packages/ui/src/fields/Upload/index.scss b/packages/ui/src/fields/Upload/index.scss index 08390c892..4129546f9 100644 --- a/packages/ui/src/fields/Upload/index.scss +++ b/packages/ui/src/fields/Upload/index.scss @@ -22,12 +22,12 @@ .btn .btn__content { gap: calc(var(--base) / 5); } - + .btn__label { font-weight: 100; } } - + &__dropzoneContent__orText { color: var(--theme-elevation-500); text-transform: lowercase; diff --git a/packages/ui/src/forms/Form/fieldReducer.ts b/packages/ui/src/forms/Form/fieldReducer.ts index ae74a6ad5..158fa7dc0 100644 --- a/packages/ui/src/forms/Form/fieldReducer.ts +++ b/packages/ui/src/forms/Form/fieldReducer.ts @@ -44,7 +44,9 @@ export function fieldReducer(state: FormState, action: FieldAction): FormState { case 'REMOVE': { const newState = { ...state } - if (newState[action.path]) delete newState[action.path] + if (newState[action.path]) { + delete newState[action.path] + } return newState } @@ -251,7 +253,9 @@ export function fieldReducer(state: FormState, action: FieldAction): FormState { const rowsMetadata = [...(state[path].rows || [])] const duplicateRowMetadata = deepCopyObjectSimple(rowsMetadata[rowIndex]) - if (duplicateRowMetadata.id) duplicateRowMetadata.id = new ObjectId().toHexString() + if (duplicateRowMetadata.id) { + duplicateRowMetadata.id = new ObjectId().toHexString() + } const duplicateRowState = deepCopyObject(rows[rowIndex]) if (duplicateRowState.id) { diff --git a/packages/ui/src/forms/Form/index.tsx b/packages/ui/src/forms/Form/index.tsx index 2cbb2a3ad..26714c352 100644 --- a/packages/ui/src/forms/Form/index.tsx +++ b/packages/ui/src/forms/Form/index.tsx @@ -220,7 +220,9 @@ export const Form: React.FC = (props) => { setProcessing(true) setDisabled(true) - if (waitForAutocomplete) await wait(100) + if (waitForAutocomplete) { + await wait(100) + } // Execute server side validations if (Array.isArray(beforeSubmit)) { @@ -307,9 +309,13 @@ export const Form: React.FC = (props) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let json: Record = {} - if (isJSON) json = await res.json() + if (isJSON) { + json = await res.json() + } if (res.status < 400) { - if (typeof onSuccess === 'function') await onSuccess(json) + if (typeof onSuccess === 'function') { + await onSuccess(json) + } setSubmitted(false) setProcessing(false) @@ -562,11 +568,15 @@ export const Form: React.FC = (props) => { }, []) useEffect(() => { - if (typeof disabledFromProps === 'boolean') setDisabled(disabledFromProps) + if (typeof disabledFromProps === 'boolean') { + setDisabled(disabledFromProps) + } }, [disabledFromProps]) useEffect(() => { - if (typeof submittedFromProps === 'boolean') setSubmitted(submittedFromProps) + if (typeof submittedFromProps === 'boolean') { + setSubmitted(submittedFromProps) + } }, [submittedFromProps]) useEffect(() => { @@ -618,7 +628,9 @@ export const Form: React.FC = (props) => { } } - if (modified) void executeOnChange() + if (modified) { + void executeOnChange() + } }, 150, // Make sure we trigger this whenever modified changes (not just when `fields` changes), otherwise we will miss merging server form state for the first form update/onChange. Here's why: diff --git a/packages/ui/src/forms/Form/mergeServerFormState.ts b/packages/ui/src/forms/Form/mergeServerFormState.ts index 77240c977..e7452d0a2 100644 --- a/packages/ui/src/forms/Form/mergeServerFormState.ts +++ b/packages/ui/src/forms/Form/mergeServerFormState.ts @@ -24,7 +24,9 @@ export const mergeServerFormState = ( if (existingState) { Object.entries(existingState).forEach(([path, newFieldState]) => { - if (!incomingState[path]) return + if (!incomingState[path]) { + return + } /** * Handle error paths diff --git a/packages/ui/src/forms/Form/rowHelpers.ts b/packages/ui/src/forms/Form/rowHelpers.ts index 08c52629e..d03c08917 100644 --- a/packages/ui/src/forms/Form/rowHelpers.ts +++ b/packages/ui/src/forms/Form/rowHelpers.ts @@ -15,8 +15,12 @@ export const extractRowsAndCollapsedIDs = ({ } => { return rows.reduce( (acc, row) => { - if (rowID === row.id) row.collapsed = collapsed - if (row.collapsed) acc.collapsedIDs.push(row.id) + if (rowID === row.id) { + row.collapsed = collapsed + } + if (row.collapsed) { + acc.collapsedIDs.push(row.id) + } acc.updatedRows.push(row) return acc }, @@ -37,7 +41,9 @@ export const toggleAllRows = ({ return rows.reduce( (acc, row) => { row.collapsed = collapsed - if (collapsed) acc.collapsedIDs.push(row.id) + if (collapsed) { + acc.collapsedIDs.push(row.id) + } acc.updatedRows.push(row) return acc }, diff --git a/packages/ui/src/forms/Form/rows.ts b/packages/ui/src/forms/Form/rows.ts index 129e4491d..1ba93f31f 100644 --- a/packages/ui/src/forms/Form/rows.ts +++ b/packages/ui/src/forms/Form/rows.ts @@ -14,7 +14,9 @@ export const separateRows = (path: string, fields: FormState): Result => { if (fieldPath.indexOf(`${path}.`) === 0) { const [rowIndex] = fieldPath.replace(`${path}.`, '').split('.') - if (!newRows[rowIndex]) newRows[rowIndex] = {} + if (!newRows[rowIndex]) { + newRows[rowIndex] = {} + } newRows[rowIndex][fieldPath.replace(`${path}.${String(rowIndex)}.`, '')] = { ...field } } else { remainingFields[fieldPath] = field diff --git a/packages/ui/src/forms/NullifyField/index.tsx b/packages/ui/src/forms/NullifyField/index.tsx index ce1be5b33..90e9bf9fa 100644 --- a/packages/ui/src/forms/NullifyField/index.tsx +++ b/packages/ui/src/forms/NullifyField/index.tsx @@ -35,11 +35,17 @@ export const NullifyLocaleField: React.FC = ({ if (fieldValue) { let hideCheckbox = false - if (typeof fieldValue === 'number' && fieldValue > 0) hideCheckbox = true - if (Array.isArray(fieldValue) && fieldValue.length > 0) hideCheckbox = true + if (typeof fieldValue === 'number' && fieldValue > 0) { + hideCheckbox = true + } + if (Array.isArray(fieldValue) && fieldValue.length > 0) { + hideCheckbox = true + } if (hideCheckbox) { - if (checked) setChecked(false) // uncheck when field has value + if (checked) { + setChecked(false) + } // uncheck when field has value return null } } diff --git a/packages/ui/src/forms/RenderFields/RenderField.tsx b/packages/ui/src/forms/RenderFields/RenderField.tsx index c037ca50d..113241e21 100644 --- a/packages/ui/src/forms/RenderFields/RenderField.tsx +++ b/packages/ui/src/forms/RenderFields/RenderField.tsx @@ -57,8 +57,9 @@ export const RenderField: React.FC = ({ fieldComponentProps.readOnly = fieldComponentProps?.field?.admin?.readOnly // if parent field is `readOnly: true`, but this field is `readOnly: false`, the field should still be editable - if (readOnlyFromContext && fieldComponentProps.readOnly !== false) + if (readOnlyFromContext && fieldComponentProps.readOnly !== false) { fieldComponentProps.readOnly = true + } // if the user does not have access control to begin with, force it to be read-only if (permissions?.[operation]?.permission === false) { diff --git a/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/promise.ts b/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/promise.ts index 3842ac602..b677300f0 100644 --- a/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/promise.ts +++ b/packages/ui/src/forms/buildStateFromSchema/calculateDefaultValues/promise.ts @@ -40,7 +40,9 @@ export const defaultValuePromise = async ({ // Traverse subfields switch (field.type) { case 'group': { - if (typeof siblingData[field.name] !== 'object') siblingData[field.name] = {} + if (typeof siblingData[field.name] !== 'object') { + siblingData[field.name] = {} + } const groupData = siblingData[field.name] as Record @@ -125,7 +127,9 @@ export const defaultValuePromise = async ({ case 'tab': { let tabSiblingData if (tabHasName(field)) { - if (typeof siblingData[field.name] !== 'object') siblingData[field.name] = {} + if (typeof siblingData[field.name] !== 'object') { + siblingData[field.name] = {} + } tabSiblingData = siblingData[field.name] as Record } else { diff --git a/packages/ui/src/graphics/Account/index.tsx b/packages/ui/src/graphics/Account/index.tsx index 7975aca38..1fb0776e6 100644 --- a/packages/ui/src/graphics/Account/index.tsx +++ b/packages/ui/src/graphics/Account/index.tsx @@ -36,6 +36,10 @@ export const Account = () => { ) } - if (!user?.email || avatar === 'default') return - if (avatar === 'gravatar') return + if (!user?.email || avatar === 'default') { + return + } + if (avatar === 'gravatar') { + return + } } diff --git a/packages/ui/src/hooks/useHotkey.ts b/packages/ui/src/hooks/useHotkey.ts index 7998081b0..4489bb977 100644 --- a/packages/ui/src/hooks/useHotkey.ts +++ b/packages/ui/src/hooks/useHotkey.ts @@ -93,7 +93,9 @@ export const useHotkey = ( } }) - if (e.code) pushToKeys(e.code) + if (e.code) { + pushToKeys(e.code) + } // Check for Mac and iPad const hasCmd = window.navigator.userAgent.includes('Mac OS X') @@ -122,7 +124,9 @@ export const useHotkey = ( ) const keyup = useCallback((e: KeyboardEvent) => { - if (e.code) removeFromKeys(e.code) + if (e.code) { + removeFromKeys(e.code) + } }, []) useEffect(() => { diff --git a/packages/ui/src/hooks/useIntersect.ts b/packages/ui/src/hooks/useIntersect.ts index 7782551e0..3ccb47395 100644 --- a/packages/ui/src/hooks/useIntersect.ts +++ b/packages/ui/src/hooks/useIntersect.ts @@ -34,7 +34,9 @@ export const useIntersect = ( const { current: currentObserver } = observer currentObserver.disconnect() - if (node) currentObserver.observe(node) + if (node) { + currentObserver.observe(node) + } return () => currentObserver.disconnect() }, [node, disable]) diff --git a/packages/ui/src/providers/Auth/index.tsx b/packages/ui/src/providers/Auth/index.tsx index 30d7269cc..7614e3dfc 100644 --- a/packages/ui/src/providers/Auth/index.tsx +++ b/packages/ui/src/providers/Auth/index.tsx @@ -287,7 +287,9 @@ export function AuthProvider({ } return () => { - if (reminder) clearTimeout(reminder) + if (reminder) { + clearTimeout(reminder) + } } }, [tokenExpiration, openModal]) @@ -308,7 +310,9 @@ export function AuthProvider({ } return () => { - if (forceLogOut) clearTimeout(forceLogOut) + if (forceLogOut) { + clearTimeout(forceLogOut) + } } }, [tokenExpiration, closeAllModals, i18n, redirectToInactivityRoute, revokeTokenAndExpire]) diff --git a/packages/ui/src/providers/Config/createClientConfig/collections.tsx b/packages/ui/src/providers/Config/createClientConfig/collections.tsx index 6f5ae2de4..5546f2c74 100644 --- a/packages/ui/src/providers/Config/createClientConfig/collections.tsx +++ b/packages/ui/src/providers/Config/createClientConfig/collections.tsx @@ -87,7 +87,9 @@ export const createClientCollectionConfig = ({ if ('imageSizes' in clientCollection.upload && clientCollection.upload.imageSizes.length) { clientCollection.upload.imageSizes = clientCollection.upload.imageSizes.map((size) => { const sanitizedSize = { ...size } - if ('generateImageName' in sanitizedSize) delete sanitizedSize.generateImageName + if ('generateImageName' in sanitizedSize) { + delete sanitizedSize.generateImageName + } return sanitizedSize }) } diff --git a/packages/ui/src/providers/Config/createClientConfig/getCreateMappedComponent.tsx b/packages/ui/src/providers/Config/createClientConfig/getCreateMappedComponent.tsx index 0de9df994..1dbd28ea6 100644 --- a/packages/ui/src/providers/Config/createClientConfig/getCreateMappedComponent.tsx +++ b/packages/ui/src/providers/Config/createClientConfig/getCreateMappedComponent.tsx @@ -56,7 +56,9 @@ export function getCreateMappedComponent({ } // conditionally set props here to avoid bloating the HTML with `$undefined` props - if (clientProps) toReturn.props = clientProps + if (clientProps) { + toReturn.props = clientProps + } return toReturn } diff --git a/packages/ui/src/providers/DocumentInfo/index.tsx b/packages/ui/src/providers/DocumentInfo/index.tsx index 6199832bb..284708b11 100644 --- a/packages/ui/src/providers/DocumentInfo/index.tsx +++ b/packages/ui/src/providers/DocumentInfo/index.tsx @@ -72,7 +72,9 @@ const DocumentInfo: React.FC< const { uploadEdits } = useUploadEdits() const [documentTitle, setDocumentTitle] = useState(() => { - if (!initialDataFromProps) return '' + if (!initialDataFromProps) { + return '' + } return formatDocTitle({ collectionConfig, @@ -419,7 +421,9 @@ const DocumentInfo: React.FC< initialDataFromProps === undefined || localeChanged ) { - if (localeChanged) prevLocale.current = locale + if (localeChanged) { + prevLocale.current = locale + } const getInitialState = async () => { setIsError(false) @@ -443,7 +447,9 @@ const DocumentInfo: React.FC< const data = reduceFieldsToValues(result, true) setData(data) - if (localeChanged) void getDocPermissions(data) + if (localeChanged) { + void getDocPermissions(data) + } setInitialState(result) } catch (err) { @@ -541,7 +547,9 @@ const DocumentInfo: React.FC< })}` }, [baseURL, locale, pluralType, id, slug, uploadEdits]) - if (isError) notFound() + if (isError) { + notFound() + } const value: DocumentInfoContext = { ...props, diff --git a/packages/ui/src/providers/ListQuery/index.tsx b/packages/ui/src/providers/ListQuery/index.tsx index a69846fe8..d2f2dd938 100644 --- a/packages/ui/src/providers/ListQuery/index.tsx +++ b/packages/ui/src/providers/ListQuery/index.tsx @@ -76,10 +76,14 @@ export const ListQueryProvider: React.FC = ({ const refineListData = React.useCallback( async (query: RefineOverrides) => { - if (!modifySearchParams) return + if (!modifySearchParams) { + return + } let pageQuery = 'page' in query ? query.page : currentQuery?.page - if ('where' in query || 'search' in query) pageQuery = '1' + if ('where' in query || 'search' in query) { + pageQuery = '1' + } const updatedPreferences: Record = {} let updatePreferences = false diff --git a/packages/ui/src/providers/Locale/index.tsx b/packages/ui/src/providers/Locale/index.tsx index f9c360920..2ffaeb4eb 100644 --- a/packages/ui/src/providers/Locale/index.tsx +++ b/packages/ui/src/providers/Locale/index.tsx @@ -47,7 +47,9 @@ export const LocaleProvider: React.FC<{ children?: React.ReactNode }> = ({ child setLocaleCode(localeToSet) setLocale(findLocaleFromCode(localization, localeToSet)) try { - if (user) await setPreference('locale', localeToSet) + if (user) { + await setPreference('locale', localeToSet) + } } catch (error) { // swallow error } diff --git a/packages/ui/src/providers/Preferences/index.tsx b/packages/ui/src/providers/Preferences/index.tsx index d2bf81ab3..b5b546da6 100644 --- a/packages/ui/src/providers/Preferences/index.tsx +++ b/packages/ui/src/providers/Preferences/index.tsx @@ -50,7 +50,9 @@ export const PreferencesProvider: React.FC<{ children?: React.ReactNode }> = ({ const getPreference = useCallback( async (key: string): Promise => { const prefs = preferencesRef.current - if (typeof prefs[key] !== 'undefined') return prefs[key] + if (typeof prefs[key] !== 'undefined') { + return prefs[key] + } const promise = new Promise((resolve: (value: T) => void) => { void (async () => { const request = await requests.get(`${serverURL}${api}/payload-preferences/${key}`, { diff --git a/packages/ui/src/utilities/buildFormState.ts b/packages/ui/src/utilities/buildFormState.ts index 54ec026c9..0a15ea716 100644 --- a/packages/ui/src/utilities/buildFormState.ts +++ b/packages/ui/src/utilities/buildFormState.ts @@ -133,7 +133,9 @@ export const buildFormState = async ({ req }: { req: PayloadRequest }): Promise< }, })) as unknown as { docs: { value: DocumentPreferences }[] } - if (preferencesResult?.docs?.[0]?.value) docPreferences = preferencesResult.docs[0].value + if (preferencesResult?.docs?.[0]?.value) { + docPreferences = preferencesResult.docs[0].value + } } promises.preferences = fetchPreferences() @@ -142,7 +144,9 @@ export const buildFormState = async ({ req }: { req: PayloadRequest }): Promise< // If there is a form state, // then we can deduce data from that form state - if (formState) data = reduceFieldsToValues(formState, true) + if (formState) { + data = reduceFieldsToValues(formState, true) + } // If we do not have data at this point, // we can fetch it. This is useful for DocumentInfoProvider diff --git a/packages/ui/src/utilities/reduceFieldsToValuesWithValidation.ts b/packages/ui/src/utilities/reduceFieldsToValuesWithValidation.ts index b69198b64..89517d8a6 100644 --- a/packages/ui/src/utilities/reduceFieldsToValuesWithValidation.ts +++ b/packages/ui/src/utilities/reduceFieldsToValuesWithValidation.ts @@ -24,12 +24,16 @@ export const reduceFieldsToValuesWithValidation = ( valid: true, } - if (!fields) return state + if (!fields) { + return state + } Object.keys(fields).forEach((key) => { if (ignoreDisableFormData === true || !fields[key]?.disableFormData) { state.data[key] = fields[key]?.value - if (!fields[key].valid) state.valid = false + if (!fields[key].valid) { + state.valid = false + } } })