@payloadcms/ui 3.15.2-canary.de7619e → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/DocumentInfo/index.tsx"],"names":[],"mappings":"AAUA,OAAO,KAA8E,MAAM,OAAO,CAAA;AAElG,OAAO,KAAK,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAcxE,mBAAmB,YAAY,CAAA;AAE/B,eAAO,MAAM,eAAe,QAAO,mBAA0C,CAAA;AAkU7E,eAAO,MAAM,oBAAoB,EAAE,KAAK,CAAC,EAAE,CACzC;IACE,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;CACnC,GAAG,iBAAiB,CAOtB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/DocumentInfo/index.tsx"],"names":[],"mappings":"AAUA,OAAO,KAQN,MAAM,OAAO,CAAA;AAEd,OAAO,KAAK,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAcxE,mBAAmB,YAAY,CAAA;AAE/B,eAAO,MAAM,eAAe,QAAO,mBAA0C,CAAA;AAsU7E,eAAO,MAAM,oBAAoB,EAAE,KAAK,CAAC,EAAE,CACzC;IACE,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;CACnC,GAAG,iBAAiB,CAOtB,CAAA"}
@@ -2,12 +2,12 @@
2
2
 
3
3
  import { jsx as _jsx } from "react/jsx-runtime";
4
4
  import * as qs from 'qs-esm';
5
- import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
5
+ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
6
6
  import { useAuth } from '../../providers/Auth/index.js';
7
7
  import { requests } from '../../utilities/api.js';
8
8
  import { formatDocTitle } from '../../utilities/formatDocTitle.js';
9
9
  import { useConfig } from '../Config/index.js';
10
- import { useLocale } from '../Locale/index.js';
10
+ import { useLocale, useLocaleLoading } from '../Locale/index.js';
11
11
  import { usePreferences } from '../Preferences/index.js';
12
12
  import { useTranslation } from '../Translation/index.js';
13
13
  import { UploadEditsProvider, useUploadEdits } from '../UploadEdits/index.js';
@@ -92,7 +92,6 @@ const DocumentInfo = ({
92
92
  const updateUploadStatus = useCallback(status => {
93
93
  setUploadStatus(status);
94
94
  }, []);
95
- const isInitializing = initialState === undefined || initialData === undefined;
96
95
  const {
97
96
  getPreference,
98
97
  setPreference
@@ -100,6 +99,10 @@ const DocumentInfo = ({
100
99
  const {
101
100
  code: locale
102
101
  } = useLocale();
102
+ const {
103
+ localeIsLoading
104
+ } = useLocaleLoading();
105
+ const isInitializing = useMemo(() => initialState === undefined || initialData === undefined || localeIsLoading, [initialData, initialState, localeIsLoading]);
103
106
  const baseURL = `${serverURL}${api}`;
104
107
  let slug;
105
108
  let pluralType;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["qs","React","createContext","useCallback","useContext","useEffect","useRef","useState","useAuth","requests","formatDocTitle","useConfig","useLocale","usePreferences","useTranslation","UploadEditsProvider","useUploadEdits","useGetDocPermissions","Context","useDocumentInfo","DocumentInfo","children","props","id","collectionSlug","currentEditor","currentEditorFromProps","docPermissions","docPermissionsFromProps","globalSlug","hasPublishedDoc","hasPublishedDocFromProps","hasPublishPermission","hasPublishPermissionFromProps","hasSavePermission","hasSavePermissionFromProps","initialData","initialState","isLocked","isLockedFromProps","lastUpdateTime","lastUpdateTimeFromProps","mostRecentVersionIsAutosaved","mostRecentVersionIsAutosavedFromProps","unpublishedVersionCount","unpublishedVersionCountFromProps","versionCount","versionCountFromProps","setDocPermissions","setHasSavePermission","setHasPublishPermission","permissions","config","admin","dateFormat","routes","api","serverURL","getEntityConfig","collectionConfig","globalConfig","abortControllerRef","AbortController","docConfig","i18n","uploadEdits","documentTitle","setDocumentTitle","data","fallback","toString","setMostRecentVersionIsAutosaved","setVersionCount","setHasPublishedDoc","setUnpublishedVersionCount","documentIsLocked","setDocumentIsLocked","setCurrentEditor","setLastUpdateTime","savedDocumentData","setSavedDocumentData","uploadStatus","setUploadStatus","updateUploadStatus","status","isInitializing","undefined","getPreference","setPreference","code","locale","baseURL","slug","pluralType","preferencesKey","unlockDocument","docID","isGlobal","query","request","get","docs","json","length","lockID","delete","headers","error","console","updateDocumentEditor","user","userData","relationTo","collection","value","patch","body","JSON","stringify","getDocPermissions","getDocPreferences","setDocFieldPreferences","path","fieldPreferences","allPreferences","fields","e","incrementVersionCount","versions","Math","min","maxPerDoc","max","updateSavedDocumentData","re1","current","abort","_err","action","useMemo","docURL","params","depth","addQueryPrefix","title","_jsx","Provider","DocumentInfoProvider"],"sources":["../../../src/providers/DocumentInfo/index.tsx"],"sourcesContent":["'use client'\nimport type {\n ClientCollectionConfig,\n ClientGlobalConfig,\n ClientUser,\n DocumentPreferences,\n SanitizedDocumentPermissions,\n} from 'payload'\n\nimport * as qs from 'qs-esm'\nimport React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'\n\nimport type { DocumentInfoContext, DocumentInfoProps } from './types.js'\n\nimport { useAuth } from '../../providers/Auth/index.js'\nimport { requests } from '../../utilities/api.js'\nimport { formatDocTitle } from '../../utilities/formatDocTitle.js'\nimport { useConfig } from '../Config/index.js'\nimport { useLocale } from '../Locale/index.js'\nimport { usePreferences } from '../Preferences/index.js'\nimport { useTranslation } from '../Translation/index.js'\nimport { UploadEditsProvider, useUploadEdits } from '../UploadEdits/index.js'\nimport { useGetDocPermissions } from './useGetDocPermissions.js'\n\nconst Context = createContext({} as DocumentInfoContext)\n\nexport type * from './types.js'\n\nexport const useDocumentInfo = (): DocumentInfoContext => useContext(Context)\n\nconst DocumentInfo: React.FC<\n {\n readonly children: React.ReactNode\n } & DocumentInfoProps\n> = ({ children, ...props }) => {\n const {\n id,\n collectionSlug,\n currentEditor: currentEditorFromProps,\n docPermissions: docPermissionsFromProps,\n globalSlug,\n hasPublishedDoc: hasPublishedDocFromProps,\n hasPublishPermission: hasPublishPermissionFromProps,\n hasSavePermission: hasSavePermissionFromProps,\n initialData,\n initialState,\n isLocked: isLockedFromProps,\n lastUpdateTime: lastUpdateTimeFromProps,\n mostRecentVersionIsAutosaved: mostRecentVersionIsAutosavedFromProps,\n unpublishedVersionCount: unpublishedVersionCountFromProps,\n versionCount: versionCountFromProps,\n } = props\n\n const [docPermissions, setDocPermissions] =\n useState<SanitizedDocumentPermissions>(docPermissionsFromProps)\n\n const [hasSavePermission, setHasSavePermission] = useState<boolean>(hasSavePermissionFromProps)\n\n const [hasPublishPermission, setHasPublishPermission] = useState<boolean>(\n hasPublishPermissionFromProps,\n )\n\n const { permissions } = useAuth()\n\n const {\n config: {\n admin: { dateFormat },\n routes: { api },\n serverURL,\n },\n getEntityConfig,\n } = useConfig()\n\n const collectionConfig = getEntityConfig({ collectionSlug }) as ClientCollectionConfig\n const globalConfig = getEntityConfig({ globalSlug }) as ClientGlobalConfig\n\n const abortControllerRef = useRef(new AbortController())\n const docConfig = collectionConfig || globalConfig\n\n const { i18n } = useTranslation()\n\n const { uploadEdits } = useUploadEdits()\n\n const [documentTitle, setDocumentTitle] = useState(() =>\n formatDocTitle({\n collectionConfig,\n data: { ...(initialData || {}), id },\n dateFormat,\n fallback: id?.toString(),\n globalConfig,\n i18n,\n }),\n )\n\n const [mostRecentVersionIsAutosaved, setMostRecentVersionIsAutosaved] = useState(\n mostRecentVersionIsAutosavedFromProps,\n )\n\n const [versionCount, setVersionCount] = useState(versionCountFromProps)\n\n const [hasPublishedDoc, setHasPublishedDoc] = useState(hasPublishedDocFromProps)\n const [unpublishedVersionCount, setUnpublishedVersionCount] = useState(\n unpublishedVersionCountFromProps,\n )\n\n const [documentIsLocked, setDocumentIsLocked] = useState<boolean | undefined>(isLockedFromProps)\n const [currentEditor, setCurrentEditor] = useState<ClientUser | null>(currentEditorFromProps)\n const [lastUpdateTime, setLastUpdateTime] = useState<number>(lastUpdateTimeFromProps)\n const [savedDocumentData, setSavedDocumentData] = useState(initialData)\n const [uploadStatus, setUploadStatus] = useState<'failed' | 'idle' | 'uploading'>('idle')\n\n const updateUploadStatus = useCallback((status: 'failed' | 'idle' | 'uploading') => {\n setUploadStatus(status)\n }, [])\n\n const isInitializing = initialState === undefined || initialData === undefined\n\n const { getPreference, setPreference } = usePreferences()\n const { code: locale } = useLocale()\n\n const baseURL = `${serverURL}${api}`\n let slug: string\n let pluralType: 'collections' | 'globals'\n let preferencesKey: string\n\n if (globalSlug) {\n slug = globalSlug\n pluralType = 'globals'\n preferencesKey = `global-${slug}`\n }\n\n if (collectionSlug) {\n slug = collectionSlug\n pluralType = 'collections'\n\n if (id) {\n preferencesKey = `collection-${slug}-${id}`\n }\n }\n\n const unlockDocument = useCallback(\n async (docID: number | string, slug: string) => {\n try {\n const isGlobal = slug === globalSlug\n\n const query = isGlobal\n ? `where[globalSlug][equals]=${slug}`\n : `where[document.value][equals]=${docID}&where[document.relationTo][equals]=${slug}`\n\n const request = await requests.get(`${serverURL}${api}/payload-locked-documents?${query}`)\n\n const { docs } = await request.json()\n\n if (docs.length > 0) {\n const lockID = docs[0].id\n await requests.delete(`${serverURL}${api}/payload-locked-documents/${lockID}`, {\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n setDocumentIsLocked(false)\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to unlock the document', error)\n }\n },\n [serverURL, api, globalSlug],\n )\n\n const updateDocumentEditor = useCallback(\n async (docID: number | string, slug: string, user: ClientUser | number | string) => {\n try {\n const isGlobal = slug === globalSlug\n\n const query = isGlobal\n ? `where[globalSlug][equals]=${slug}`\n : `where[document.value][equals]=${docID}&where[document.relationTo][equals]=${slug}`\n\n // Check if the document is already locked\n const request = await requests.get(`${serverURL}${api}/payload-locked-documents?${query}`)\n\n const { docs } = await request.json()\n\n if (docs.length > 0) {\n const lockID = docs[0].id\n\n const userData =\n typeof user === 'object'\n ? { relationTo: user.collection, value: user.id }\n : { relationTo: 'users', value: user }\n\n // Send a patch request to update the _lastEdited info\n await requests.patch(`${serverURL}${api}/payload-locked-documents/${lockID}`, {\n body: JSON.stringify({\n user: userData,\n }),\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to update the document editor', error)\n }\n },\n [serverURL, api, globalSlug],\n )\n\n const getDocPermissions = useGetDocPermissions({\n id: id as string,\n api,\n collectionSlug,\n globalSlug,\n i18n,\n locale,\n permissions,\n serverURL,\n setDocPermissions,\n setHasPublishPermission,\n setHasSavePermission,\n })\n\n const getDocPreferences = useCallback(() => {\n return getPreference<DocumentPreferences>(preferencesKey)\n }, [getPreference, preferencesKey])\n\n const setDocFieldPreferences = useCallback<DocumentInfoContext['setDocFieldPreferences']>(\n async (path, fieldPreferences) => {\n const allPreferences = await getDocPreferences()\n\n if (preferencesKey) {\n try {\n await setPreference(preferencesKey, {\n ...allPreferences,\n fields: {\n ...(allPreferences?.fields || {}),\n [path]: {\n ...allPreferences?.fields?.[path],\n ...fieldPreferences,\n },\n },\n })\n } catch (e) {\n console.error(e) // eslint-disable-line no-console\n }\n }\n },\n [setPreference, preferencesKey, getDocPreferences],\n )\n\n const incrementVersionCount = useCallback(() => {\n if (collectionConfig && collectionConfig.versions) {\n setVersionCount(Math.min(versionCount + 1, collectionConfig.versions.maxPerDoc))\n } else if (globalConfig && globalConfig.versions) {\n setVersionCount(Math.min(versionCount + 1, globalConfig.versions.max))\n }\n }, [collectionConfig, globalConfig, versionCount])\n\n const updateSavedDocumentData = React.useCallback<DocumentInfoContext['updateSavedDocumentData']>(\n (json) => {\n setSavedDocumentData(json)\n },\n [],\n )\n\n useEffect(() => {\n setDocumentTitle(\n formatDocTitle({\n collectionConfig,\n data: { ...savedDocumentData, id },\n dateFormat,\n fallback: id?.toString(),\n globalConfig,\n i18n,\n }),\n )\n }, [collectionConfig, globalConfig, savedDocumentData, dateFormat, i18n, id])\n\n // clean on unmount\n useEffect(() => {\n const re1 = abortControllerRef.current\n\n return () => {\n if (re1) {\n try {\n re1.abort()\n } catch (_err) {\n // swallow error\n }\n }\n }\n }, [])\n\n const action: string = React.useMemo(() => {\n const docURL = `${baseURL}${pluralType === 'globals' ? `/globals` : ''}/${slug}${id ? `/${id}` : ''}`\n const params = {\n depth: 0,\n 'fallback-locale': 'null',\n locale,\n uploadEdits: uploadEdits || undefined,\n }\n\n return `${docURL}${qs.stringify(params, {\n addQueryPrefix: true,\n })}`\n }, [baseURL, locale, pluralType, id, slug, uploadEdits])\n\n const value: DocumentInfoContext = {\n ...props,\n action,\n currentEditor,\n docConfig,\n docPermissions,\n documentIsLocked,\n getDocPermissions,\n getDocPreferences,\n hasPublishedDoc,\n hasPublishPermission,\n hasSavePermission,\n incrementVersionCount,\n initialData,\n initialState,\n isInitializing,\n lastUpdateTime,\n mostRecentVersionIsAutosaved,\n preferencesKey,\n savedDocumentData,\n setCurrentEditor,\n setDocFieldPreferences,\n setDocumentIsLocked,\n setDocumentTitle,\n setHasPublishedDoc,\n setLastUpdateTime,\n setMostRecentVersionIsAutosaved,\n setUnpublishedVersionCount,\n setUploadStatus: updateUploadStatus,\n title: documentTitle,\n unlockDocument,\n unpublishedVersionCount,\n updateDocumentEditor,\n updateSavedDocumentData,\n uploadStatus,\n versionCount,\n }\n\n return <Context.Provider value={value}>{children}</Context.Provider>\n}\n\nexport const DocumentInfoProvider: React.FC<\n {\n readonly children: React.ReactNode\n } & DocumentInfoProps\n> = (props) => {\n return (\n <UploadEditsProvider>\n <DocumentInfo {...props} />\n </UploadEditsProvider>\n )\n}\n"],"mappings":"AAAA;;;AASA,YAAYA,EAAA,MAAQ;AACpB,OAAOC,KAAA,IAASC,aAAa,EAAEC,WAAW,EAAEC,UAAU,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ;AAI3F,SAASC,OAAO,QAAQ;AACxB,SAASC,QAAQ,QAAQ;AACzB,SAASC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C9B;IAEA,OAAO,GAAGsD,MAAA,GAAS5I,EAAA,CAAGsH,SAAS,CAACuB,MAAA,EAAQ;MACtCE,cAAA,EAAgB;IAClB,IAAI;EACN,GAAG,CAACpD,OAAA,EAASD,MAAA,EAAQG,UAAA,EAAYtE,EAAA,EAAIqE,IAAA,EAAM3B,WAAA,CAAY;EAEvD,MAAMiD,KAAA,GAA6B;IACjC,GAAG5F,KAAK;IACRoH,MAAA;IACAjH,aAAA;IACAsC,SAAA;IACApC,cAAA;IACAgD,gBAAA;IACA4C,iBAAA;IACAC,iBAAA;IACA1F,eAAA;IACAE,oBAAA;IACAE,iBAAA;IACA6F,qBAAA;IACA3F,WAAA;IACAC,YAAA;IACAgD,cAAA;IACA7C,cAAA;IACAE,4BAAA;IACAoD,cAAA;IACAf,iBAAA;IACAF,gBAAA;IACA4C,sBAAA;IACA7C,mBAAA;IACAT,gBAAA;IACAM,kBAAA;IACAK,iBAAA;IACAP,+BAAA;IACAG,0BAAA;IACAQ,eAAA,EAAiBC,kBAAA;IACjB6D,KAAA,EAAO9E,aAAA;IACP6B,cAAA;IACAnD,uBAAA;IACAiE,oBAAA;IACAwB,uBAAA;IACApD,YAAA;IACAnC;EACF;EAEA,oBAAOmG,IAAA,CAAC/H,OAAA,CAAQgI,QAAQ;IAAChC,KAAA,EAAOA,KAAA;cAAQ7F;;AAC1C;AAEA,OAAO,MAAM8H,oBAAA,GAIR7H,KAAA;EACH,oBACE2H,IAAA,CAAClI,mBAAA;cACC,aAAAkI,IAAA,CAAC7H,YAAA;MAAc,GAAGE;;;AAGxB","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["qs","React","createContext","useCallback","useContext","useEffect","useMemo","useRef","useState","useAuth","requests","formatDocTitle","useConfig","useLocale","useLocaleLoading","usePreferences","useTranslation","UploadEditsProvider","useUploadEdits","useGetDocPermissions","Context","useDocumentInfo","DocumentInfo","children","props","id","collectionSlug","currentEditor","currentEditorFromProps","docPermissions","docPermissionsFromProps","globalSlug","hasPublishedDoc","hasPublishedDocFromProps","hasPublishPermission","hasPublishPermissionFromProps","hasSavePermission","hasSavePermissionFromProps","initialData","initialState","isLocked","isLockedFromProps","lastUpdateTime","lastUpdateTimeFromProps","mostRecentVersionIsAutosaved","mostRecentVersionIsAutosavedFromProps","unpublishedVersionCount","unpublishedVersionCountFromProps","versionCount","versionCountFromProps","setDocPermissions","setHasSavePermission","setHasPublishPermission","permissions","config","admin","dateFormat","routes","api","serverURL","getEntityConfig","collectionConfig","globalConfig","abortControllerRef","AbortController","docConfig","i18n","uploadEdits","documentTitle","setDocumentTitle","data","fallback","toString","setMostRecentVersionIsAutosaved","setVersionCount","setHasPublishedDoc","setUnpublishedVersionCount","documentIsLocked","setDocumentIsLocked","setCurrentEditor","setLastUpdateTime","savedDocumentData","setSavedDocumentData","uploadStatus","setUploadStatus","updateUploadStatus","status","getPreference","setPreference","code","locale","localeIsLoading","isInitializing","undefined","baseURL","slug","pluralType","preferencesKey","unlockDocument","docID","isGlobal","query","request","get","docs","json","length","lockID","delete","headers","error","console","updateDocumentEditor","user","userData","relationTo","collection","value","patch","body","JSON","stringify","getDocPermissions","getDocPreferences","setDocFieldPreferences","path","fieldPreferences","allPreferences","fields","e","incrementVersionCount","versions","Math","min","maxPerDoc","max","updateSavedDocumentData","re1","current","abort","_err","action","docURL","params","depth","addQueryPrefix","title","_jsx","Provider","DocumentInfoProvider"],"sources":["../../../src/providers/DocumentInfo/index.tsx"],"sourcesContent":["'use client'\nimport type {\n ClientCollectionConfig,\n ClientGlobalConfig,\n ClientUser,\n DocumentPreferences,\n SanitizedDocumentPermissions,\n} from 'payload'\n\nimport * as qs from 'qs-esm'\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nimport type { DocumentInfoContext, DocumentInfoProps } from './types.js'\n\nimport { useAuth } from '../../providers/Auth/index.js'\nimport { requests } from '../../utilities/api.js'\nimport { formatDocTitle } from '../../utilities/formatDocTitle.js'\nimport { useConfig } from '../Config/index.js'\nimport { useLocale, useLocaleLoading } from '../Locale/index.js'\nimport { usePreferences } from '../Preferences/index.js'\nimport { useTranslation } from '../Translation/index.js'\nimport { UploadEditsProvider, useUploadEdits } from '../UploadEdits/index.js'\nimport { useGetDocPermissions } from './useGetDocPermissions.js'\n\nconst Context = createContext({} as DocumentInfoContext)\n\nexport type * from './types.js'\n\nexport const useDocumentInfo = (): DocumentInfoContext => useContext(Context)\n\nconst DocumentInfo: React.FC<\n {\n readonly children: React.ReactNode\n } & DocumentInfoProps\n> = ({ children, ...props }) => {\n const {\n id,\n collectionSlug,\n currentEditor: currentEditorFromProps,\n docPermissions: docPermissionsFromProps,\n globalSlug,\n hasPublishedDoc: hasPublishedDocFromProps,\n hasPublishPermission: hasPublishPermissionFromProps,\n hasSavePermission: hasSavePermissionFromProps,\n initialData,\n initialState,\n isLocked: isLockedFromProps,\n lastUpdateTime: lastUpdateTimeFromProps,\n mostRecentVersionIsAutosaved: mostRecentVersionIsAutosavedFromProps,\n unpublishedVersionCount: unpublishedVersionCountFromProps,\n versionCount: versionCountFromProps,\n } = props\n\n const [docPermissions, setDocPermissions] =\n useState<SanitizedDocumentPermissions>(docPermissionsFromProps)\n\n const [hasSavePermission, setHasSavePermission] = useState<boolean>(hasSavePermissionFromProps)\n\n const [hasPublishPermission, setHasPublishPermission] = useState<boolean>(\n hasPublishPermissionFromProps,\n )\n\n const { permissions } = useAuth()\n\n const {\n config: {\n admin: { dateFormat },\n routes: { api },\n serverURL,\n },\n getEntityConfig,\n } = useConfig()\n\n const collectionConfig = getEntityConfig({ collectionSlug }) as ClientCollectionConfig\n const globalConfig = getEntityConfig({ globalSlug }) as ClientGlobalConfig\n\n const abortControllerRef = useRef(new AbortController())\n const docConfig = collectionConfig || globalConfig\n\n const { i18n } = useTranslation()\n\n const { uploadEdits } = useUploadEdits()\n\n const [documentTitle, setDocumentTitle] = useState(() =>\n formatDocTitle({\n collectionConfig,\n data: { ...(initialData || {}), id },\n dateFormat,\n fallback: id?.toString(),\n globalConfig,\n i18n,\n }),\n )\n\n const [mostRecentVersionIsAutosaved, setMostRecentVersionIsAutosaved] = useState(\n mostRecentVersionIsAutosavedFromProps,\n )\n\n const [versionCount, setVersionCount] = useState(versionCountFromProps)\n\n const [hasPublishedDoc, setHasPublishedDoc] = useState(hasPublishedDocFromProps)\n const [unpublishedVersionCount, setUnpublishedVersionCount] = useState(\n unpublishedVersionCountFromProps,\n )\n\n const [documentIsLocked, setDocumentIsLocked] = useState<boolean | undefined>(isLockedFromProps)\n const [currentEditor, setCurrentEditor] = useState<ClientUser | null>(currentEditorFromProps)\n const [lastUpdateTime, setLastUpdateTime] = useState<number>(lastUpdateTimeFromProps)\n const [savedDocumentData, setSavedDocumentData] = useState(initialData)\n const [uploadStatus, setUploadStatus] = useState<'failed' | 'idle' | 'uploading'>('idle')\n\n const updateUploadStatus = useCallback((status: 'failed' | 'idle' | 'uploading') => {\n setUploadStatus(status)\n }, [])\n\n const { getPreference, setPreference } = usePreferences()\n const { code: locale } = useLocale()\n const { localeIsLoading } = useLocaleLoading()\n\n const isInitializing = useMemo(\n () => initialState === undefined || initialData === undefined || localeIsLoading,\n [initialData, initialState, localeIsLoading],\n )\n\n const baseURL = `${serverURL}${api}`\n let slug: string\n let pluralType: 'collections' | 'globals'\n let preferencesKey: string\n\n if (globalSlug) {\n slug = globalSlug\n pluralType = 'globals'\n preferencesKey = `global-${slug}`\n }\n\n if (collectionSlug) {\n slug = collectionSlug\n pluralType = 'collections'\n\n if (id) {\n preferencesKey = `collection-${slug}-${id}`\n }\n }\n\n const unlockDocument = useCallback(\n async (docID: number | string, slug: string) => {\n try {\n const isGlobal = slug === globalSlug\n\n const query = isGlobal\n ? `where[globalSlug][equals]=${slug}`\n : `where[document.value][equals]=${docID}&where[document.relationTo][equals]=${slug}`\n\n const request = await requests.get(`${serverURL}${api}/payload-locked-documents?${query}`)\n\n const { docs } = await request.json()\n\n if (docs.length > 0) {\n const lockID = docs[0].id\n await requests.delete(`${serverURL}${api}/payload-locked-documents/${lockID}`, {\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n setDocumentIsLocked(false)\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to unlock the document', error)\n }\n },\n [serverURL, api, globalSlug],\n )\n\n const updateDocumentEditor = useCallback(\n async (docID: number | string, slug: string, user: ClientUser | number | string) => {\n try {\n const isGlobal = slug === globalSlug\n\n const query = isGlobal\n ? `where[globalSlug][equals]=${slug}`\n : `where[document.value][equals]=${docID}&where[document.relationTo][equals]=${slug}`\n\n // Check if the document is already locked\n const request = await requests.get(`${serverURL}${api}/payload-locked-documents?${query}`)\n\n const { docs } = await request.json()\n\n if (docs.length > 0) {\n const lockID = docs[0].id\n\n const userData =\n typeof user === 'object'\n ? { relationTo: user.collection, value: user.id }\n : { relationTo: 'users', value: user }\n\n // Send a patch request to update the _lastEdited info\n await requests.patch(`${serverURL}${api}/payload-locked-documents/${lockID}`, {\n body: JSON.stringify({\n user: userData,\n }),\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to update the document editor', error)\n }\n },\n [serverURL, api, globalSlug],\n )\n\n const getDocPermissions = useGetDocPermissions({\n id: id as string,\n api,\n collectionSlug,\n globalSlug,\n i18n,\n locale,\n permissions,\n serverURL,\n setDocPermissions,\n setHasPublishPermission,\n setHasSavePermission,\n })\n\n const getDocPreferences = useCallback(() => {\n return getPreference<DocumentPreferences>(preferencesKey)\n }, [getPreference, preferencesKey])\n\n const setDocFieldPreferences = useCallback<DocumentInfoContext['setDocFieldPreferences']>(\n async (path, fieldPreferences) => {\n const allPreferences = await getDocPreferences()\n\n if (preferencesKey) {\n try {\n await setPreference(preferencesKey, {\n ...allPreferences,\n fields: {\n ...(allPreferences?.fields || {}),\n [path]: {\n ...allPreferences?.fields?.[path],\n ...fieldPreferences,\n },\n },\n })\n } catch (e) {\n console.error(e) // eslint-disable-line no-console\n }\n }\n },\n [setPreference, preferencesKey, getDocPreferences],\n )\n\n const incrementVersionCount = useCallback(() => {\n if (collectionConfig && collectionConfig.versions) {\n setVersionCount(Math.min(versionCount + 1, collectionConfig.versions.maxPerDoc))\n } else if (globalConfig && globalConfig.versions) {\n setVersionCount(Math.min(versionCount + 1, globalConfig.versions.max))\n }\n }, [collectionConfig, globalConfig, versionCount])\n\n const updateSavedDocumentData = React.useCallback<DocumentInfoContext['updateSavedDocumentData']>(\n (json) => {\n setSavedDocumentData(json)\n },\n [],\n )\n\n useEffect(() => {\n setDocumentTitle(\n formatDocTitle({\n collectionConfig,\n data: { ...savedDocumentData, id },\n dateFormat,\n fallback: id?.toString(),\n globalConfig,\n i18n,\n }),\n )\n }, [collectionConfig, globalConfig, savedDocumentData, dateFormat, i18n, id])\n\n // clean on unmount\n useEffect(() => {\n const re1 = abortControllerRef.current\n\n return () => {\n if (re1) {\n try {\n re1.abort()\n } catch (_err) {\n // swallow error\n }\n }\n }\n }, [])\n\n const action: string = React.useMemo(() => {\n const docURL = `${baseURL}${pluralType === 'globals' ? `/globals` : ''}/${slug}${id ? `/${id}` : ''}`\n const params = {\n depth: 0,\n 'fallback-locale': 'null',\n locale,\n uploadEdits: uploadEdits || undefined,\n }\n\n return `${docURL}${qs.stringify(params, {\n addQueryPrefix: true,\n })}`\n }, [baseURL, locale, pluralType, id, slug, uploadEdits])\n\n const value: DocumentInfoContext = {\n ...props,\n action,\n currentEditor,\n docConfig,\n docPermissions,\n documentIsLocked,\n getDocPermissions,\n getDocPreferences,\n hasPublishedDoc,\n hasPublishPermission,\n hasSavePermission,\n incrementVersionCount,\n initialData,\n initialState,\n isInitializing,\n lastUpdateTime,\n mostRecentVersionIsAutosaved,\n preferencesKey,\n savedDocumentData,\n setCurrentEditor,\n setDocFieldPreferences,\n setDocumentIsLocked,\n setDocumentTitle,\n setHasPublishedDoc,\n setLastUpdateTime,\n setMostRecentVersionIsAutosaved,\n setUnpublishedVersionCount,\n setUploadStatus: updateUploadStatus,\n title: documentTitle,\n unlockDocument,\n unpublishedVersionCount,\n updateDocumentEditor,\n updateSavedDocumentData,\n uploadStatus,\n versionCount,\n }\n\n return <Context.Provider value={value}>{children}</Context.Provider>\n}\n\nexport const DocumentInfoProvider: React.FC<\n {\n readonly children: React.ReactNode\n } & DocumentInfoProps\n> = (props) => {\n return (\n <UploadEditsProvider>\n <DocumentInfo {...props} />\n </UploadEditsProvider>\n )\n}\n"],"mappings":"AAAA;;;AASA,YAAYA,EAAA,MAAQ;AACpB,OAAOC,KAAA,IACLC,aAAa,EACbC,WAAW,EACXC,UAAU,EACVC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,QACH;AAIP,SAASC,OAAO,QAAQ;AACxB,SAASC,QAAQ,QAAQ;AACzB,SAASC,cAAc,QAAQ;AAC/B,SAASC,SAAS,QAAQ;AAC1B,SAASC,SAAS,EAAEC,gBAAgB,QAAQ;AAC5C,SAASC,cAAc,QAAQ;AAC/B,SAASC,cAAc,QAAQ;AAC/B,SAASC,mBAAmB,EAAEC,cAAc,QAAQ;AACpD,SAASC,oBAAoB,QAAQ;AAErC,MAAMC,OAAA,gBAAUlB,aAAA,CAAc,CAAC;AAI/B,OAAO,MAAMmB,eAAA,GAAkBA,CAAA;EAAA,OAA2BjB,UAAA,CAAAgB,OAAW;AAAA;AAErE,MAAME,YAAA,GAIFA,CAAC;EAAEC,QAAQ;EAAE,GAAGC;AAAA,CAAO;EACzB,MAAM;IACJC,EAAE;IACFC,cAAc;IACdC,aAAA,EAAeC,sBAAsB;IACrCC,cAAA,EAAgBC,uBAAuB;IACvCC,UAAU;IACVC,eAAA,EAAiBC,wBAAwB;IACzCC,oBAAA,EAAsBC,6BAA6B;IACnDC,iBAAA,EAAmBC,0BAA0B;IAC7CC,WAAW;IACXC,YAAY;IACZC,QAAA,EAAUC,iBAAiB;IAC3BC,cAAA,EAAgBC,uBAAuB;IACvCC,4BAAA,EAA8BC,qCAAqC;IACnEC,uBAAA,EAAy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,+BAAA;IACAG,0BAAA;IACAQ,eAAA,EAAiBC,kBAAA;IACjB6D,KAAA,EAAO9E,aAAA;IACP8B,cAAA;IACApD,uBAAA;IACAkE,oBAAA;IACAwB,uBAAA;IACArD,YAAA;IACAnC;EACF;EAEA,oBAAOmG,IAAA,CAAC/H,OAAA,CAAQgI,QAAQ;IAAC/B,KAAA,EAAOA,KAAA;cAAQ9F;;AAC1C;AAEA,OAAO,MAAM8H,oBAAA,GAIR7H,KAAA;EACH,oBACE2H,IAAA,CAAClI,mBAAA;cACC,aAAAkI,IAAA,CAAC7H,YAAA;MAAc,GAAGE;;;AAGxB","ignoreList":[]}
@@ -1,25 +1,20 @@
1
1
  import type { Locale } from 'payload';
2
2
  import React from 'react';
3
+ export declare const LocaleLoadingContext: React.Context<{
4
+ localeIsLoading: boolean;
5
+ setLocaleIsLoading: (_: boolean) => any;
6
+ }>;
3
7
  export declare const LocaleProvider: React.FC<{
4
8
  children?: React.ReactNode;
5
9
  locale?: Locale['code'];
6
10
  }>;
11
+ export declare const useLocaleLoading: () => {
12
+ localeIsLoading: boolean;
13
+ setLocaleIsLoading: (_: boolean) => any;
14
+ };
7
15
  /**
8
- * @deprecated A hook that returns the current locale object.
9
- *
10
- * ---
11
- *
12
- * #### 🚨 V4 Breaking Change
13
- * The `useLocale` return type now reflects `null | Locale` instead of `false | Locale`.
14
- *
15
- * **Old (V3):**
16
- * ```ts
17
- * const { code } = useLocale();
18
- * ```
19
- * **New (V4):**
20
- * ```ts
21
- * const locale = useLocale();
22
- * ```
16
+ * TODO: V4
17
+ * The return type of the `useLocale` hook will change in v4. It will return `null | Locale` instead of `false | {} | Locale`.
23
18
  */
24
19
  export declare const useLocale: () => Locale;
25
20
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/Locale/index.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAGrC,OAAO,KAAyD,MAAM,OAAO,CAAA;AAS7E,eAAO,MAAM,cAAc,EAAE,KAAK,CAAC,EAAE,CAAC;IAAE,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,CAAA;CAAE,CAsD5F,CAAA;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,SAAS,QAAO,MAAmC,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/Locale/index.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAGrC,OAAO,KAAiE,MAAM,OAAO,CAAA;AASrF,eAAO,MAAM,oBAAoB;;4BAEP,OAAO;EAC/B,CAAA;AAaF,eAAO,MAAM,cAAc,EAAE,KAAK,CAAC,EAAE,CAAC;IAAE,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,CAAA;CAAE,CAmF5F,CAAA;AAED,eAAO,MAAM,gBAAgB;;4BAnGH,OAAO;CAmGqC,CAAA;AAEtE;;;GAGG;AACH,eAAO,MAAM,SAAS,QAAO,MAAmC,CAAA"}
@@ -1,80 +1,158 @@
1
1
  'use client';
2
2
 
3
+ import { c as _c } from "react/compiler-runtime";
3
4
  import { jsx as _jsx } from "react/jsx-runtime";
4
5
  import { useSearchParams } from 'next/navigation.js';
5
- import React, { createContext, useContext, useEffect, useState } from 'react';
6
+ import React, { createContext, useContext, useEffect, useRef, useState } from 'react';
6
7
  import { findLocaleFromCode } from '../../utilities/findLocaleFromCode.js';
7
8
  import { useAuth } from '../Auth/index.js';
8
9
  import { useConfig } from '../Config/index.js';
9
10
  import { usePreferences } from '../Preferences/index.js';
10
11
  const LocaleContext = /*#__PURE__*/createContext({});
11
- export const LocaleProvider = ({
12
- children,
13
- locale: localeFromProps
14
- }) => {
12
+ export const LocaleLoadingContext = /*#__PURE__*/createContext({
13
+ localeIsLoading: false,
14
+ setLocaleIsLoading: _ => undefined
15
+ });
16
+ const fetchPreferences = async key => await fetch(`/api/payload-preferences/${key}`, {
17
+ credentials: 'include',
18
+ headers: {
19
+ 'Content-Type': 'application/json'
20
+ },
21
+ method: 'GET'
22
+ })?.then(res => res.json());
23
+ export const LocaleProvider = t0 => {
24
+ const $ = _c(25);
15
25
  const {
16
- config: {
17
- localization = false
18
- }
26
+ children,
27
+ locale: initialLocaleFromPrefs
28
+ } = t0;
29
+ const {
30
+ config: t1
19
31
  } = useConfig();
32
+ const {
33
+ localization: t2
34
+ } = t1;
35
+ const localization = t2 === undefined ? false : t2;
20
36
  const {
21
37
  user
22
38
  } = useAuth();
23
- const defaultLocale = localization && localization.defaultLocale ? localization.defaultLocale : 'en';
39
+ const defaultLocale = localization && localization.defaultLocale ? localization.defaultLocale : "en";
24
40
  const {
25
- getPreference,
26
- setPreference
41
+ getPreference
27
42
  } = usePreferences();
28
- const localeFromParams = useSearchParams().get('locale');
29
- // `localeFromProps` originates from the root layout, which does not have access to search params
30
- const [localeCode, setLocaleCode] = useState(localeFromProps || localeFromParams);
31
- const locale = React.useMemo(() => {
32
- if (!localization) {
33
- // TODO: return null V4
34
- return {};
35
- }
36
- return findLocaleFromCode(localization, localeFromParams || localeCode) || findLocaleFromCode(localization, defaultLocale);
37
- }, [localeCode, localeFromParams, localization, defaultLocale]);
38
- useEffect(() => {
39
- async function setInitialLocale() {
40
- if (localization && user) {
41
- if (typeof localeFromParams !== 'string') {
42
- try {
43
- const localeToSet = await getPreference('locale');
44
- setLocaleCode(localeToSet);
45
- } catch (_) {
46
- setLocaleCode(defaultLocale);
47
- }
48
- } else {
49
- void setPreference('locale', findLocaleFromCode(localization, localeFromParams)?.code || defaultLocale);
50
- }
43
+ const t3 = useSearchParams();
44
+ let t4;
45
+ if ($[0] !== t3) {
46
+ t4 = t3.get("locale");
47
+ $[0] = t3;
48
+ $[1] = t4;
49
+ } else {
50
+ t4 = $[1];
51
+ }
52
+ const localeFromParams = t4;
53
+ let t5;
54
+ if ($[2] !== defaultLocale || $[3] !== initialLocaleFromPrefs || $[4] !== localeFromParams || $[5] !== localization) {
55
+ t5 = () => {
56
+ if (!localization) {
57
+ return {};
51
58
  }
52
- }
53
- void setInitialLocale();
54
- }, [defaultLocale, getPreference, localization, localeFromParams, setPreference, user]);
55
- return /*#__PURE__*/_jsx(LocaleContext.Provider, {
56
- value: locale,
57
- children: children
58
- });
59
+ return findLocaleFromCode(localization, localeFromParams) || findLocaleFromCode(localization, initialLocaleFromPrefs) || findLocaleFromCode(localization, defaultLocale);
60
+ };
61
+ $[2] = defaultLocale;
62
+ $[3] = initialLocaleFromPrefs;
63
+ $[4] = localeFromParams;
64
+ $[5] = localization;
65
+ $[6] = t5;
66
+ } else {
67
+ t5 = $[6];
68
+ }
69
+ const [locale, setLocale] = React.useState(t5);
70
+ const [isLoading, setLocaleIsLoading] = useState(false);
71
+ const prevLocale = useRef(locale);
72
+ let t6;
73
+ let t7;
74
+ if ($[7] !== locale) {
75
+ t6 = () => {
76
+ if (locale.code !== prevLocale.current.code) {
77
+ setLocaleIsLoading(false);
78
+ }
79
+ prevLocale.current = locale;
80
+ };
81
+ t7 = [locale];
82
+ $[7] = locale;
83
+ $[8] = t6;
84
+ $[9] = t7;
85
+ } else {
86
+ t6 = $[8];
87
+ t7 = $[9];
88
+ }
89
+ useEffect(t6, t7);
90
+ let t8;
91
+ if ($[10] !== defaultLocale || $[11] !== localeFromParams || $[12] !== localization || $[13] !== user?.id) {
92
+ t8 = () => {
93
+ const resetLocale = async function resetLocale() {
94
+ if (localization && user?.id) {
95
+ const localeToUse = localeFromParams || (await fetchPreferences("locale")?.then(_temp)) || defaultLocale;
96
+ const newLocale = findLocaleFromCode(localization, localeToUse) || findLocaleFromCode(localization, defaultLocale);
97
+ setLocale(newLocale);
98
+ }
99
+ };
100
+ resetLocale();
101
+ };
102
+ $[10] = defaultLocale;
103
+ $[11] = localeFromParams;
104
+ $[12] = localization;
105
+ $[13] = user?.id;
106
+ $[14] = t8;
107
+ } else {
108
+ t8 = $[14];
109
+ }
110
+ const t9 = user?.id;
111
+ let t10;
112
+ if ($[15] !== defaultLocale || $[16] !== getPreference || $[17] !== localeFromParams || $[18] !== localization || $[19] !== t9) {
113
+ t10 = [defaultLocale, getPreference, localization, localeFromParams, t9];
114
+ $[15] = defaultLocale;
115
+ $[16] = getPreference;
116
+ $[17] = localeFromParams;
117
+ $[18] = localization;
118
+ $[19] = t9;
119
+ $[20] = t10;
120
+ } else {
121
+ t10 = $[20];
122
+ }
123
+ useEffect(t8, t10);
124
+ let t11;
125
+ if ($[21] !== children || $[22] !== isLoading || $[23] !== locale) {
126
+ t11 = _jsx(LocaleContext.Provider, {
127
+ value: locale,
128
+ children: _jsx(LocaleLoadingContext.Provider, {
129
+ value: {
130
+ localeIsLoading: isLoading,
131
+ setLocaleIsLoading
132
+ },
133
+ children
134
+ })
135
+ });
136
+ $[21] = children;
137
+ $[22] = isLoading;
138
+ $[23] = locale;
139
+ $[24] = t11;
140
+ } else {
141
+ t11 = $[24];
142
+ }
143
+ return t11;
144
+ };
145
+ export const useLocaleLoading = () => {
146
+ return useContext(LocaleLoadingContext);
59
147
  };
60
148
  /**
61
- * @deprecated A hook that returns the current locale object.
62
- *
63
- * ---
64
- *
65
- * #### 🚨 V4 Breaking Change
66
- * The `useLocale` return type now reflects `null | Locale` instead of `false | Locale`.
67
- *
68
- * **Old (V3):**
69
- * ```ts
70
- * const { code } = useLocale();
71
- * ```
72
- * **New (V4):**
73
- * ```ts
74
- * const locale = useLocale();
75
- * ```
149
+ * TODO: V4
150
+ * The return type of the `useLocale` hook will change in v4. It will return `null | Locale` instead of `false | {} | Locale`.
76
151
  */
77
152
  export const useLocale = () => {
78
153
  return useContext(LocaleContext);
79
154
  };
155
+ function _temp(res) {
156
+ return res.value;
157
+ }
80
158
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["useSearchParams","React","createContext","useContext","useEffect","useState","findLocaleFromCode","useAuth","useConfig","usePreferences","LocaleContext","LocaleProvider","children","locale","localeFromProps","config","localization","user","defaultLocale","getPreference","setPreference","localeFromParams","get","localeCode","setLocaleCode","useMemo","setInitialLocale","localeToSet","_","code","_jsx","Provider","value","useLocale"],"sources":["../../../src/providers/Locale/index.tsx"],"sourcesContent":["'use client'\n\nimport type { Locale } from 'payload'\n\nimport { useSearchParams } from 'next/navigation.js'\nimport React, { createContext, useContext, useEffect, useState } from 'react'\n\nimport { findLocaleFromCode } from '../../utilities/findLocaleFromCode.js'\nimport { useAuth } from '../Auth/index.js'\nimport { useConfig } from '../Config/index.js'\nimport { usePreferences } from '../Preferences/index.js'\n\nconst LocaleContext = createContext({} as Locale)\n\nexport const LocaleProvider: React.FC<{ children?: React.ReactNode; locale?: Locale['code'] }> = ({\n children,\n locale: localeFromProps,\n}) => {\n const {\n config: { localization = false },\n } = useConfig()\n\n const { user } = useAuth()\n\n const defaultLocale =\n localization && localization.defaultLocale ? localization.defaultLocale : 'en'\n\n const { getPreference, setPreference } = usePreferences()\n const localeFromParams = useSearchParams().get('locale')\n\n // `localeFromProps` originates from the root layout, which does not have access to search params\n const [localeCode, setLocaleCode] = useState<string>(localeFromProps || localeFromParams)\n\n const locale: Locale = React.useMemo(() => {\n if (!localization) {\n // TODO: return null V4\n return {} as Locale\n }\n\n return (\n findLocaleFromCode(localization, localeFromParams || localeCode) ||\n findLocaleFromCode(localization, defaultLocale)\n )\n }, [localeCode, localeFromParams, localization, defaultLocale])\n\n useEffect(() => {\n async function setInitialLocale() {\n if (localization && user) {\n if (typeof localeFromParams !== 'string') {\n try {\n const localeToSet = await getPreference<string>('locale')\n setLocaleCode(localeToSet)\n } catch (_) {\n setLocaleCode(defaultLocale)\n }\n } else {\n void setPreference(\n 'locale',\n findLocaleFromCode(localization, localeFromParams)?.code || defaultLocale,\n )\n }\n }\n }\n\n void setInitialLocale()\n }, [defaultLocale, getPreference, localization, localeFromParams, setPreference, user])\n\n return <LocaleContext.Provider value={locale}>{children}</LocaleContext.Provider>\n}\n\n/**\n * @deprecated A hook that returns the current locale object.\n *\n * ---\n *\n * #### 🚨 V4 Breaking Change\n * The `useLocale` return type now reflects `null | Locale` instead of `false | Locale`.\n *\n * **Old (V3):**\n * ```ts\n * const { code } = useLocale();\n * ```\n * **New (V4):**\n * ```ts\n * const locale = useLocale();\n * ```\n */\nexport const useLocale = (): Locale => useContext(LocaleContext)\n"],"mappings":"AAAA;;;AAIA,SAASA,eAAe,QAAQ;AAChC,OAAOC,KAAA,IAASC,aAAa,EAAEC,UAAU,EAAEC,SAAS,EAAEC,QAAQ,QAAQ;AAEtE,SAASC,kBAAkB,QAAQ;AACnC,SAASC,OAAO,QAAQ;AACxB,SAASC,SAAS,QAAQ;AAC1B,SAASC,cAAc,QAAQ;AAE/B,MAAMC,aAAA,gBAAgBR,aAAA,CAAc,CAAC;AAErC,OAAO,MAAMS,cAAA,GAAoFA,CAAC;EAChGC,QAAQ;EACRC,MAAA,EAAQC;AAAe,CACxB;EACC,MAAM;IACJC,MAAA,EAAQ;MAAEC,YAAA,GAAe;IAAK;EAAE,CACjC,GAAGR,SAAA;EAEJ,MAAM;IAAES;EAAI,CAAE,GAAGV,OAAA;EAEjB,MAAMW,aAAA,GACJF,YAAA,IAAgBA,YAAA,CAAaE,aAAa,GAAGF,YAAA,CAAaE,aAAa,GAAG;EAE5E,MAAM;IAAEC,aAAa;IAAEC;EAAa,CAAE,GAAGX,cAAA;EACzC,MAAMY,gBAAA,GAAmBrB,eAAA,GAAkBsB,GAAG,CAAC;EAE/C;EACA,MAAM,CAACC,UAAA,EAAYC,aAAA,CAAc,GAAGnB,QAAA,CAAiBS,eAAA,IAAmBO,gBAAA;EAExE,MAAMR,MAAA,GAAiBZ,KAAA,CAAMwB,OAAO,CAAC;IACnC,IAAI,CAACT,YAAA,EAAc;MACjB;MACA,OAAO,CAAC;IACV;IAEA,OACEV,kBAAA,CAAmBU,YAAA,EAAcK,gBAAA,IAAoBE,UAAA,KACrDjB,kBAAA,CAAmBU,YAAA,EAAcE,aAAA;EAErC,GAAG,CAACK,UAAA,EAAYF,gBAAA,EAAkBL,YAAA,EAAcE,aAAA,CAAc;EAE9Dd,SAAA,CAAU;IACR,eAAesB,iBAAA;MACb,IAAIV,YAAA,IAAgBC,IAAA,EAAM;QACxB,IAAI,OAAOI,gBAAA,KAAqB,UAAU;UACxC,IAAI;YACF,MAAMM,WAAA,GAAc,MAAMR,aAAA,CAAsB;YAChDK,aAAA,CAAcG,WAAA;UAChB,EAAE,OAAOC,CAAA,EAAG;YACVJ,aAAA,CAAcN,aAAA;UAChB;QACF,OAAO;UACL,KAAKE,aAAA,CACH,UACAd,kBAAA,CAAmBU,YAAA,EAAcK,gBAAA,GAAmBQ,IAAA,IAAQX,aAAA;QAEhE;MACF;IACF;IAEA,KAAKQ,gBAAA;EACP,GAAG,CAACR,aAAA,EAAeC,aAAA,EAAeH,YAAA,EAAcK,gBAAA,EAAkBD,aAAA,EAAeH,IAAA,CAAK;EAEtF,oBAAOa,IAAA,CAACpB,aAAA,CAAcqB,QAAQ;IAACC,KAAA,EAAOnB,MAAA;cAASD;;AACjD;AAEA;;;;;;;;;;;;;;;;;AAiBA,OAAO,MAAMqB,SAAA,GAAYA,CAAA;EAAA,OAAc9B,UAAA,CAAAO,aAAW;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["c","_c","useSearchParams","React","createContext","useContext","useEffect","useRef","useState","findLocaleFromCode","useAuth","useConfig","usePreferences","LocaleContext","LocaleLoadingContext","localeIsLoading","setLocaleIsLoading","_","undefined","fetchPreferences","key","fetch","credentials","headers","method","then","res","json","LocaleProvider","t0","$","children","locale","initialLocaleFromPrefs","config","t1","localization","t2","user","defaultLocale","getPreference","t3","t4","get","localeFromParams","t5","setLocale","isLoading","prevLocale","t6","t7","code","current","t8","id","resetLocale","localeToUse","_temp","newLocale","t9","t10","t11","_jsx","Provider","value","useLocaleLoading","useLocale"],"sources":["../../../src/providers/Locale/index.tsx"],"sourcesContent":["'use client'\n\nimport type { Locale } from 'payload'\n\nimport { useSearchParams } from 'next/navigation.js'\nimport React, { createContext, useContext, useEffect, useRef, useState } from 'react'\n\nimport { findLocaleFromCode } from '../../utilities/findLocaleFromCode.js'\nimport { useAuth } from '../Auth/index.js'\nimport { useConfig } from '../Config/index.js'\nimport { usePreferences } from '../Preferences/index.js'\n\nconst LocaleContext = createContext({} as Locale)\n\nexport const LocaleLoadingContext = createContext({\n localeIsLoading: false,\n setLocaleIsLoading: (_: boolean) => undefined,\n})\n\nconst fetchPreferences = async <T extends Record<string, unknown> | string>(\n key: string,\n): Promise<{ id: string; value: T }> =>\n await fetch(`/api/payload-preferences/${key}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })?.then((res) => res.json() as Promise<{ id: string; value: T }>)\n\nexport const LocaleProvider: React.FC<{ children?: React.ReactNode; locale?: Locale['code'] }> = ({\n children,\n /**\n The `locale` prop originates from the root layout, which does not have access to search params\n This component uses the `useSearchParams` hook to get the locale from the URL as precedence over this prop\n This prop does not update as the user navigates the site, because the root layout does not re-render\n */\n locale: initialLocaleFromPrefs,\n}) => {\n const {\n config: { localization = false },\n } = useConfig()\n\n const { user } = useAuth()\n\n const defaultLocale =\n localization && localization.defaultLocale ? localization.defaultLocale : 'en'\n\n const { getPreference, setPreference } = usePreferences()\n const localeFromParams = useSearchParams().get('locale')\n\n const [locale, setLocale] = React.useState<Locale>(() => {\n if (!localization) {\n // TODO: return null V4\n return {} as Locale\n }\n\n return (\n findLocaleFromCode(localization, localeFromParams) ||\n findLocaleFromCode(localization, initialLocaleFromPrefs) ||\n findLocaleFromCode(localization, defaultLocale)\n )\n })\n\n const [isLoading, setLocaleIsLoading] = useState(false)\n\n const prevLocale = useRef<Locale>(locale)\n\n useEffect(() => {\n /**\n * We need to set `isLoading` back to false once the locale is detected to be different\n * This happens when the user clicks an anchor link which appends the `?locale=` query param\n * This triggers a client-side navigation, which re-renders the page with the new locale\n * In Next.js, local state is persisted during this type of navigation because components are not unmounted\n */\n if (locale.code !== prevLocale.current.code) {\n setLocaleIsLoading(false)\n }\n\n prevLocale.current = locale\n }, [locale])\n\n useEffect(() => {\n /**\n * This effect should only run when `localeFromParams` changes, i.e. when the user clicks an anchor link\n * The root layout, which sends the initial locale from prefs, will not re-render as the user navigates the site\n * For this reason, we need to fetch the locale from prefs if the search params clears the `locale` query param\n */\n async function resetLocale() {\n if (localization && user?.id) {\n const localeToUse =\n localeFromParams ||\n (await fetchPreferences<Locale['code']>('locale')?.then((res) => res.value)) ||\n defaultLocale\n\n const newLocale =\n findLocaleFromCode(localization, localeToUse) ||\n findLocaleFromCode(localization, defaultLocale)\n\n setLocale(newLocale)\n }\n }\n\n void resetLocale()\n }, [defaultLocale, getPreference, localization, localeFromParams, user?.id])\n\n return (\n <LocaleContext.Provider value={locale}>\n <LocaleLoadingContext.Provider value={{ localeIsLoading: isLoading, setLocaleIsLoading }}>\n {children}\n </LocaleLoadingContext.Provider>\n </LocaleContext.Provider>\n )\n}\n\nexport const useLocaleLoading = () => useContext(LocaleLoadingContext)\n\n/**\n * TODO: V4\n * The return type of the `useLocale` hook will change in v4. It will return `null | Locale` instead of `false | {} | Locale`.\n */\nexport const useLocale = (): Locale => useContext(LocaleContext)\n"],"mappings":"AAAA;;AAAA,SAAAA,CAAA,IAAAC,EAAA;;AAIA,SAASC,eAAe,QAAQ;AAChC,OAAOC,KAAA,IAASC,aAAa,EAAEC,UAAU,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ;AAE9E,SAASC,kBAAkB,QAAQ;AACnC,SAASC,OAAO,QAAQ;AACxB,SAASC,SAAS,QAAQ;AAC1B,SAASC,cAAc,QAAQ;AAE/B,MAAMC,aAAA,gBAAgBT,aAAA,CAAc,CAAC;AAErC,OAAO,MAAMU,oBAAA,gBAAuBV,aAAA,CAA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AhD,oBAAA,CAAAiD,QAAA;QAAAC,KAAA;UAAAjD,eAAA,EAAyDgC,SAAA;UAAA/B;QAAA;QAAAe;MAAA,C;;;;;;;;;SAD3D8B,G;CAMJ;AAEA,OAAO,MAAMI,gBAAA,GAAmBA,CAAA;EAAA,OAAM5D,UAAA,CAAAS,oBAAW;AAAA;AAEjD;;;;AAIA,OAAO,MAAMoD,SAAA,GAAYA,CAAA;EAAA,OAAc7D,UAAA,CAAAQ,aAAW;AAAA;AA3F+C,SAAA4C,MAAA/B,GAAA;EAAA,OA8DtBA,GAAA,CAAAsC,KAAA;AAAA","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"buildTableState.js","names":["formatErrors","isNumber","getClientConfig","renderFilters","renderTable","upsertPreferences","buildTableStateHandler","args","req","res","buildTableState","err","payload","logger","error","msg","message","collectionSlug","columns","docs","docsFromArgs","enableRowSelections","query","renderRowTypes","i18n","config","user","tableAppearance","incomingUserSlug","collection","adminUserSlug","admin","adminAccessFunction","collections","access","canAccessAdmin","Error","hasUsers","find","depth","limit","pagination","length","clientConfig","importMap","collectionConfig","clientCollectionConfig","slug","listPreferences","key","value","Number","undefined","sort","data","parseInt","overrideAccess","page","where","columnState","Table","columnPreferences","useAsTitle","renderedFilters","fields","preferences","state"],"sources":["../../src/utilities/buildTableState.ts"],"sourcesContent":["import type {\n BuildTableStateArgs,\n ClientCollectionConfig,\n ClientConfig,\n ErrorResult,\n ListPreferences,\n PaginatedDocs,\n SanitizedCollectionConfig,\n} from 'payload'\n\nimport { formatErrors } from 'payload'\nimport { isNumber } from 'payload/shared'\n\nimport type { Column } from '../elements/Table/index.js'\n\nimport { getClientConfig } from './getClientConfig.js'\nimport { renderFilters, renderTable } from './renderTable.js'\nimport { upsertPreferences } from './upsertPreferences.js'\n\ntype BuildTableStateSuccessResult = {\n clientConfig?: ClientConfig\n data: PaginatedDocs\n errors?: never\n preferences: ListPreferences\n renderedFilters: Map<string, React.ReactNode>\n state: Column[]\n Table: React.ReactNode\n}\n\ntype BuildTableStateErrorResult = {\n data?: any\n renderedFilters?: never\n state?: never\n Table?: never\n} & (\n | {\n message: string\n }\n | ErrorResult\n)\n\nexport type BuildTableStateResult = BuildTableStateErrorResult | BuildTableStateSuccessResult\n\nexport const buildTableStateHandler = async (\n args: BuildTableStateArgs,\n): Promise<BuildTableStateResult> => {\n const { req } = args\n\n try {\n const res = await buildTableState(args)\n return res\n } catch (err) {\n req.payload.logger.error({ err, msg: `There was an error building form state` })\n\n if (err.message === 'Could not find field schema for given path') {\n return {\n message: err.message,\n }\n }\n\n if (err.message === 'Unauthorized') {\n return null\n }\n\n return formatErrors(err)\n }\n}\n\nexport const buildTableState = async (\n args: BuildTableStateArgs,\n): Promise<BuildTableStateSuccessResult> => {\n const {\n collectionSlug,\n columns,\n docs: docsFromArgs,\n enableRowSelections,\n query,\n renderRowTypes,\n req,\n req: {\n i18n,\n payload,\n payload: { config },\n user,\n },\n tableAppearance,\n } = args\n\n const incomingUserSlug = user?.collection\n\n const adminUserSlug = config.admin.user\n\n // If we have a user slug, test it against the functions\n if (incomingUserSlug) {\n const adminAccessFunction = payload.collections[incomingUserSlug].config.access?.admin\n\n // Run the admin access function from the config if it exists\n if (adminAccessFunction) {\n const canAccessAdmin = await adminAccessFunction({ req })\n\n if (!canAccessAdmin) {\n throw new Error('Unauthorized')\n }\n\n // Match the user collection to the global admin config\n } else if (adminUserSlug !== incomingUserSlug) {\n throw new Error('Unauthorized')\n }\n } else {\n const hasUsers = await payload.find({\n collection: adminUserSlug,\n depth: 0,\n limit: 1,\n pagination: false,\n })\n\n // If there are users, we should not allow access because of /create-first-user\n if (hasUsers.docs.length) {\n throw new Error('Unauthorized')\n }\n }\n\n const clientConfig = getClientConfig({\n config,\n i18n,\n importMap: payload.importMap,\n })\n\n let collectionConfig: SanitizedCollectionConfig\n let clientCollectionConfig: ClientCollectionConfig\n\n if (req.payload.collections[collectionSlug]) {\n collectionConfig = req.payload.collections[collectionSlug].config\n clientCollectionConfig = clientConfig.collections.find(\n (collection) => collection.slug === collectionSlug,\n )\n }\n\n const listPreferences = await upsertPreferences<ListPreferences>({\n key: `${collectionSlug}-list`,\n req,\n value: {\n columns,\n limit: isNumber(query?.limit) ? Number(query.limit) : undefined,\n sort: query?.sort,\n },\n })\n\n let docs = docsFromArgs\n let data: PaginatedDocs\n\n // lookup docs, if desired, i.e. within `join` field which initialize with `depth: 0`\n\n if (!docs || query) {\n data = await payload.find({\n collection: collectionSlug,\n depth: 0,\n limit: query?.limit ? parseInt(query.limit, 10) : undefined,\n overrideAccess: false,\n page: query?.page ? parseInt(query.page, 10) : undefined,\n sort: query?.sort,\n user: req.user,\n where: query?.where,\n })\n\n docs = data.docs\n }\n\n const { columnState, Table } = renderTable({\n clientCollectionConfig,\n collectionConfig,\n columnPreferences: undefined, // TODO, might not be needed\n columns,\n docs,\n enableRowSelections,\n i18n: req.i18n,\n payload,\n renderRowTypes,\n tableAppearance,\n useAsTitle: collectionConfig.admin.useAsTitle,\n })\n\n const renderedFilters = renderFilters(collectionConfig.fields, req.payload.importMap)\n\n return {\n data,\n preferences: listPreferences,\n renderedFilters,\n state: columnState,\n Table,\n }\n}\n"],"mappings":"AAUA,SAASA,YAAY,QAAQ;AAC7B,SAASC,QAAQ,QAAQ;AAIzB,SAASC,eAAe,QAAQ;AAChC,SAASC,aAAa,EAAEC,WAAW,QAAQ;AAC3C,SAASC,iBAAiB,QAAQ;AA0BlC,OAAO,MAAMC,sBAAA,GAAyB,MACpCC,IAAA;EAEA,MAAM;IAAEC;EAAG,CAAE,GAAGD,IAAA;EAEhB,IAAI;IACF,MAAME,GAAA,GAAM,MAAMC,eAAA,CAAgBH,IAAA;IAClC,OAAOE,GAAA;EACT,EAAE,OAAOE,GAAA,EAAK;IACZH,GAAA,CAAII,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC;MAAEH,GAAA;MAAKI,GAAA,EAAK;IAAyC;IAE9E,IAAIJ,GAAA,CAAIK,OAAO,KAAK,8CAA8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;MACdgC,KAAA,EAAOpC,KAAA,EAAOoC;IAChB;IAEAvC,IAAA,GAAOmC,IAAA,CAAKnC,IAAI;EAClB;EAEA,MAAM;IAAEwC,WAAW;IAAEC;EAAK,CAAE,GAAGxD,WAAA,CAAY;IACzC0C,sBAAA;IACAD,gBAAA;IACAgB,iBAAA,EAAmBT,SAAA;IACnBlC,OAAA;IACAC,IAAA;IACAE,mBAAA;IACAG,IAAA,EAAMhB,GAAA,CAAIgB,IAAI;IACdZ,OAAA;IACAW,cAAA;IACAI,eAAA;IACAmC,UAAA,EAAYjB,gBAAA,CAAiBd,KAAK,CAAC+B;EACrC;EAEA,MAAMC,eAAA,GAAkB5D,aAAA,CAAc0C,gBAAA,CAAiBmB,MAAM,EAAExD,GAAA,CAAII,OAAO,CAACgC,SAAS;EAEpF,OAAO;IACLU,IAAA;IACAW,WAAA,EAAajB,eAAA;IACbe,eAAA;IACAG,KAAA,EAAOP,WAAA;IACPC;EACF;AACF","ignoreList":[]}
1
+ {"version":3,"file":"buildTableState.js","names":["formatErrors","isNumber","getClientConfig","renderFilters","renderTable","upsertPreferences","buildTableStateHandler","args","req","res","buildTableState","err","payload","logger","error","msg","message","collectionSlug","columns","docs","docsFromArgs","enableRowSelections","query","renderRowTypes","i18n","config","user","tableAppearance","incomingUserSlug","collection","adminUserSlug","admin","adminAccessFunction","collections","access","canAccessAdmin","Error","hasUsers","find","depth","limit","pagination","length","clientConfig","importMap","collectionConfig","clientCollectionConfig","slug","listPreferences","key","value","Number","undefined","sort","data","parseInt","overrideAccess","page","where","columnState","Table","columnPreferences","useAsTitle","renderedFilters","fields","preferences","state"],"sources":["../../src/utilities/buildTableState.ts"],"sourcesContent":["import type {\n BuildTableStateArgs,\n ClientCollectionConfig,\n ClientConfig,\n ErrorResult,\n ListPreferences,\n PaginatedDocs,\n SanitizedCollectionConfig,\n} from 'payload'\n\nimport { formatErrors } from 'payload'\nimport { isNumber } from 'payload/shared'\n\nimport type { Column } from '../elements/Table/index.js'\n\nimport { getClientConfig } from './getClientConfig.js'\nimport { renderFilters, renderTable } from './renderTable.js'\nimport { upsertPreferences } from './upsertPreferences.js'\n\ntype BuildTableStateSuccessResult = {\n clientConfig?: ClientConfig\n data: PaginatedDocs\n errors?: never\n preferences: ListPreferences\n renderedFilters: Map<string, React.ReactNode>\n state: Column[]\n Table: React.ReactNode\n}\n\ntype BuildTableStateErrorResult = {\n data?: any\n renderedFilters?: never\n state?: never\n Table?: never\n} & (\n | {\n message: string\n }\n | ErrorResult\n)\n\nexport type BuildTableStateResult = BuildTableStateErrorResult | BuildTableStateSuccessResult\n\nexport const buildTableStateHandler = async (\n args: BuildTableStateArgs,\n): Promise<BuildTableStateResult> => {\n const { req } = args\n\n try {\n const res = await buildTableState(args)\n return res\n } catch (err) {\n req.payload.logger.error({ err, msg: `There was an error building form state` })\n\n if (err.message === 'Could not find field schema for given path') {\n return {\n message: err.message,\n }\n }\n\n if (err.message === 'Unauthorized') {\n return null\n }\n\n return formatErrors(err)\n }\n}\n\nexport const buildTableState = async (\n args: BuildTableStateArgs,\n): Promise<BuildTableStateSuccessResult> => {\n const {\n collectionSlug,\n columns,\n docs: docsFromArgs,\n enableRowSelections,\n query,\n renderRowTypes,\n req,\n req: {\n i18n,\n payload,\n payload: { config },\n user,\n },\n tableAppearance,\n } = args\n\n const incomingUserSlug = user?.collection\n\n const adminUserSlug = config.admin.user\n\n // If we have a user slug, test it against the functions\n if (incomingUserSlug) {\n const adminAccessFunction = payload.collections[incomingUserSlug].config.access?.admin\n\n // Run the admin access function from the config if it exists\n if (adminAccessFunction) {\n const canAccessAdmin = await adminAccessFunction({ req })\n\n if (!canAccessAdmin) {\n throw new Error('Unauthorized')\n }\n\n // Match the user collection to the global admin config\n } else if (adminUserSlug !== incomingUserSlug) {\n throw new Error('Unauthorized')\n }\n } else {\n const hasUsers = await payload.find({\n collection: adminUserSlug,\n depth: 0,\n limit: 1,\n pagination: false,\n })\n\n // If there are users, we should not allow access because of /create-first-user\n if (hasUsers.docs.length) {\n throw new Error('Unauthorized')\n }\n }\n\n const clientConfig = getClientConfig({\n config,\n i18n,\n importMap: payload.importMap,\n })\n\n let collectionConfig: SanitizedCollectionConfig\n let clientCollectionConfig: ClientCollectionConfig\n\n if (req.payload.collections[collectionSlug]) {\n collectionConfig = req.payload.collections[collectionSlug].config\n clientCollectionConfig = clientConfig.collections.find(\n (collection) => collection.slug === collectionSlug,\n )\n }\n\n const listPreferences = await upsertPreferences<ListPreferences>({\n key: `${collectionSlug}-list`,\n req,\n value: {\n columns,\n limit: isNumber(query?.limit) ? Number(query.limit) : undefined,\n sort: query?.sort as string,\n },\n })\n\n let docs = docsFromArgs\n let data: PaginatedDocs\n\n // lookup docs, if desired, i.e. within `join` field which initialize with `depth: 0`\n\n if (!docs || query) {\n data = await payload.find({\n collection: collectionSlug,\n depth: 0,\n limit: query?.limit ? parseInt(query.limit, 10) : undefined,\n overrideAccess: false,\n page: query?.page ? parseInt(query.page, 10) : undefined,\n sort: query?.sort,\n user: req.user,\n where: query?.where,\n })\n\n docs = data.docs\n }\n\n const { columnState, Table } = renderTable({\n clientCollectionConfig,\n collectionConfig,\n columnPreferences: undefined, // TODO, might not be needed\n columns,\n docs,\n enableRowSelections,\n i18n: req.i18n,\n payload,\n renderRowTypes,\n tableAppearance,\n useAsTitle: collectionConfig.admin.useAsTitle,\n })\n\n const renderedFilters = renderFilters(collectionConfig.fields, req.payload.importMap)\n\n return {\n data,\n preferences: listPreferences,\n renderedFilters,\n state: columnState,\n Table,\n }\n}\n"],"mappings":"AAUA,SAASA,YAAY,QAAQ;AAC7B,SAASC,QAAQ,QAAQ;AAIzB,SAASC,eAAe,QAAQ;AAChC,SAASC,aAAa,EAAEC,WAAW,QAAQ;AAC3C,SAASC,iBAAiB,QAAQ;AA0BlC,OAAO,MAAMC,sBAAA,GAAyB,MACpCC,IAAA;EAEA,MAAM;IAAEC;EAAG,CAAE,GAAGD,IAAA;EAEhB,IAAI;IACF,MAAME,GAAA,GAAM,MAA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Y,SAAA;MAClDI,cAAA,EAAgB;MAChBC,IAAA,EAAMnC,KAAA,EAAOmC,IAAA,GAAOF,QAAA,CAASjC,KAAA,CAAMmC,IAAI,EAAE,MAAML,SAAA;MAC/CC,IAAA,EAAM/B,KAAA,EAAO+B,IAAA;MACb3B,IAAA,EAAMlB,GAAA,CAAIkB,IAAI;MACdgC,KAAA,EAAOpC,KAAA,EAAOoC;IAChB;IAEAvC,IAAA,GAAOmC,IAAA,CAAKnC,IAAI;EAClB;EAEA,MAAM;IAAEwC,WAAW;IAAEC;EAAK,CAAE,GAAGxD,WAAA,CAAY;IACzC0C,sBAAA;IACAD,gBAAA;IACAgB,iBAAA,EAAmBT,SAAA;IACnBlC,OAAA;IACAC,IAAA;IACAE,mBAAA;IACAG,IAAA,EAAMhB,GAAA,CAAIgB,IAAI;IACdZ,OAAA;IACAW,cAAA;IACAI,eAAA;IACAmC,UAAA,EAAYjB,gBAAA,CAAiBd,KAAK,CAAC+B;EACrC;EAEA,MAAMC,eAAA,GAAkB5D,aAAA,CAAc0C,gBAAA,CAAiBmB,MAAM,EAAExD,GAAA,CAAII,OAAO,CAACgC,SAAS;EAEpF,OAAO;IACLU,IAAA;IACAW,WAAA,EAAajB,eAAA;IACbe,eAAA;IACAG,KAAA,EAAOP,WAAA;IACPC;EACF;AACF","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=fetchPreferences.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchPreferences.d.ts","sourceRoot":"","sources":["../../src/utilities/fetchPreferences.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=fetchPreferences.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchPreferences.js","names":[],"sources":["../../src/utilities/fetchPreferences.ts"],"sourcesContent":[null],"mappings":"","ignoreList":[]}
@@ -7,9 +7,9 @@ import type { PayloadRequest } from 'payload';
7
7
  * @param key - The key of the preferences to update
8
8
  * @param value - The new value to merge with the existing preferences
9
9
  */
10
- export declare const upsertPreferences: <T extends Record<string, any>>({ key, req, value: incomingValue, }: {
10
+ export declare const upsertPreferences: <T extends Record<string, unknown> | string>({ key, req, value: incomingValue, }: {
11
11
  key: string;
12
12
  req: PayloadRequest;
13
- value: Record<string, any>;
13
+ value: T;
14
14
  }) => Promise<T>;
15
15
  //# sourceMappingURL=upsertPreferences.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upsertPreferences.d.ts","sourceRoot":"","sources":["../../src/utilities/upsertPreferences.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,uCAIlE;IACD,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,cAAc,CAAA;IACnB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAC3B,KAAG,OAAO,CAAC,CAAC,CAwEZ,CAAA"}
1
+ {"version":3,"file":"upsertPreferences.d.ts","sourceRoot":"","sources":["../../src/utilities/upsertPreferences.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAyB,cAAc,EAAE,MAAM,SAAS,CAAA;AA4CpE;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,uCAI/E;IACD,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,cAAc,CAAA;IACnB,KAAK,EAAE,CAAC,CAAA;CACT,KAAG,OAAO,CAAC,CAAC,CAqDZ,CAAA"}
@@ -1,19 +1,10 @@
1
1
  import { dequal } from 'dequal/lite';
2
2
  import { removeUndefined } from './removeUndefined.js';
3
- /**
4
- * Will update the given preferences by key, creating a new record if it doesn't already exist, or merging existing preferences with the new value.
5
- * This is not possible to do with the existing `db.upsert` operation because it stores on the `value` key and does not perform a deep merge beyond the first level.
6
- * I.e. if you have a preferences record with a `value` key, `db.upsert` will overwrite the existing value. In the future if this supported we should use that instead.
7
- * @param req - The PayloadRequest object
8
- * @param key - The key of the preferences to update
9
- * @param value - The new value to merge with the existing preferences
10
- */
11
- export const upsertPreferences = async ({
3
+ const getPreferences = async ({
12
4
  key,
13
- req,
14
- value: incomingValue
5
+ req
15
6
  }) => {
16
- const preferencesResult = await req.payload.find({
7
+ const result = await req.payload.find({
17
8
  collection: 'payload-preferences',
18
9
  depth: 0,
19
10
  limit: 1,
@@ -33,12 +24,28 @@ export const upsertPreferences = async ({
33
24
  }
34
25
  }]
35
26
  }
36
- }).then(res => res.docs[0] ?? {
37
- id: null,
38
- value: {}
27
+ }).then(res => res.docs?.[0]);
28
+ return result;
29
+ };
30
+ /**
31
+ * Will update the given preferences by key, creating a new record if it doesn't already exist, or merging existing preferences with the new value.
32
+ * This is not possible to do with the existing `db.upsert` operation because it stores on the `value` key and does not perform a deep merge beyond the first level.
33
+ * I.e. if you have a preferences record with a `value` key, `db.upsert` will overwrite the existing value. In the future if this supported we should use that instead.
34
+ * @param req - The PayloadRequest object
35
+ * @param key - The key of the preferences to update
36
+ * @param value - The new value to merge with the existing preferences
37
+ */
38
+ export const upsertPreferences = async ({
39
+ key,
40
+ req,
41
+ value: incomingValue
42
+ }) => {
43
+ const existingPrefs = await getPreferences({
44
+ key,
45
+ req
39
46
  });
40
- let newPrefs = preferencesResult.value;
41
- if (!preferencesResult.id) {
47
+ let newPrefs = existingPrefs?.value;
48
+ if (!existingPrefs?.id) {
42
49
  await req.payload.create({
43
50
  collection: 'payload-preferences',
44
51
  data: {
@@ -53,13 +60,14 @@ export const upsertPreferences = async ({
53
60
  req
54
61
  });
55
62
  } else {
56
- const mergedPrefs = {
57
- ...(preferencesResult?.value || {}),
63
+ // Strings are valid JSON, i.e. `locale` saved as a string to the locale preferences
64
+ const mergedPrefs = typeof incomingValue === 'object' ? {
65
+ ...(typeof existingPrefs.value === 'object' ? existingPrefs?.value : {}),
58
66
  ...removeUndefined(incomingValue || {})
59
- };
60
- if (!dequal(mergedPrefs, preferencesResult.value)) {
67
+ } : incomingValue;
68
+ if (!dequal(mergedPrefs, existingPrefs.value)) {
61
69
  newPrefs = await req.payload.update({
62
- id: preferencesResult.id,
70
+ id: existingPrefs.id,
63
71
  collection: 'payload-preferences',
64
72
  data: {
65
73
  key,