create-nextjs-cms 0.8.10 → 0.9.1

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.
Files changed (36) hide show
  1. package/package.json +2 -2
  2. package/templates/default/app/(auth)/auth/login/LoginPage.tsx +9 -9
  3. package/templates/default/app/(auth)/auth-language-provider.tsx +34 -0
  4. package/templates/default/app/(auth)/layout.tsx +10 -10
  5. package/templates/default/app/(rootLayout)/edit/[section]/[itemId]/page.tsx +4 -1
  6. package/templates/default/app/(rootLayout)/layout.tsx +5 -5
  7. package/templates/default/app/(rootLayout)/section/[section]/page.tsx +4 -1
  8. package/templates/default/app/api/auth/route.ts +2 -2
  9. package/templates/default/app/api/submit/section/item/[slug]/route.ts +32 -3
  10. package/templates/default/app/api/submit/section/simple/route.ts +32 -3
  11. package/templates/default/app/globals.css +9 -0
  12. package/templates/default/cms.config.ts +4 -4
  13. package/templates/default/components/ItemEditPage.tsx +82 -2
  14. package/templates/default/components/LocaleSwitcher.tsx +89 -0
  15. package/templates/default/components/Navbar.tsx +5 -5
  16. package/templates/default/components/NewPage.tsx +1 -0
  17. package/templates/default/components/SectionPage.tsx +81 -1
  18. package/templates/default/components/form/ContentLocaleContext.tsx +11 -0
  19. package/templates/default/components/form/Form.tsx +48 -5
  20. package/templates/default/components/form/FormInputs.tsx +16 -7
  21. package/templates/default/components/form/helpers/_section-hot-reload.js +1 -1
  22. package/templates/default/components/form/inputs/NumberFormInput.tsx +2 -1
  23. package/templates/default/components/form/inputs/PhotoFormInput.tsx +168 -112
  24. package/templates/default/components/form/inputs/RichTextFormInput.tsx +3 -0
  25. package/templates/default/components/form/inputs/SelectFormInput.tsx +1 -1
  26. package/templates/default/components/form/inputs/TagsFormInput.tsx +6 -2
  27. package/templates/default/components/form/inputs/TextFormInput.tsx +3 -0
  28. package/templates/default/components/form/inputs/TextareaFormInput.tsx +3 -0
  29. package/templates/default/components/{locale-dropdown.tsx → language-dropdown.tsx} +74 -74
  30. package/templates/default/components/{locale-picker.tsx → language-picker.tsx} +85 -85
  31. package/templates/default/components/login-language-dropdown.tsx +46 -0
  32. package/templates/default/components/ui/alert.tsx +2 -1
  33. package/templates/default/dynamic-schemas/schema.ts +475 -448
  34. package/templates/default/package.json +1 -1
  35. package/templates/default/app/(auth)/auth-locale-provider.tsx +0 -34
  36. package/templates/default/components/login-locale-dropdown.tsx +0 -46
@@ -1,16 +1,24 @@
1
- import React, { useRef, useState } from 'react'
1
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
2
2
  import { useI18n } from 'nextjs-cms/translations/client'
3
3
  import FormInputElement from '@/components/form/FormInputElement'
4
4
  import ProtectedImage from '@/components/ProtectedImage'
5
5
  import Image from 'next/image'
6
6
  import useModal from '@/hooks/useModal'
7
- import { ChevronRight, InfoIcon, Trash2Icon, UploadIcon, X } from 'lucide-react'
7
+ import { ChevronRight, InfoIcon, Trash2Icon, Undo2Icon, UploadIcon, X } from 'lucide-react'
8
8
  import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
9
9
  import { Badge } from '@/components/ui/badge'
10
10
  import { PhotoFieldClientConfig } from 'nextjs-cms/core/fields'
11
11
  import { useController, useFormContext } from 'react-hook-form'
12
12
 
13
- export default function PhotoFormInput({ input, sectionName }: { input: PhotoFieldClientConfig; sectionName: string }) {
13
+ export default function PhotoFormInput({
14
+ input,
15
+ sectionName,
16
+ submitSuccessCount = 0,
17
+ }: {
18
+ input: PhotoFieldClientConfig
19
+ sectionName: string
20
+ submitSuccessCount?: number
21
+ }) {
14
22
  const t = useI18n()
15
23
  const { control } = useFormContext()
16
24
  const {
@@ -25,7 +33,34 @@ export default function PhotoFormInput({ input, sectionName }: { input: PhotoFie
25
33
  const [fileName, setFileName] = useState(t('noFileSelected'))
26
34
  const fileInputContainerRef = useRef<HTMLDivElement>(null)
27
35
  const [image, setImage] = useState<string | null>(null)
28
- const { setModal, modal, modalResponse, setModalResponse } = useModal()
36
+ const [markedForDeletion, setMarkedForDeletion] = useState(false)
37
+ const handledSubmitSuccessCountRef = useRef(0)
38
+ const { setModal } = useModal()
39
+
40
+ const clearSelectedFile = useCallback(() => {
41
+ setFileName(t('noFileSelected'))
42
+ setImage(null)
43
+ field.onChange(undefined)
44
+ if (fileInputContainerRef.current?.firstChild) {
45
+ ;(fileInputContainerRef.current.firstChild as HTMLInputElement).value = ''
46
+ }
47
+ }, [field.onChange, t])
48
+
49
+ useEffect(() => {
50
+ return () => {
51
+ if (image?.startsWith('blob:')) {
52
+ URL.revokeObjectURL(image)
53
+ }
54
+ }
55
+ }, [image])
56
+
57
+ useEffect(() => {
58
+ if (!submitSuccessCount || handledSubmitSuccessCountRef.current === submitSuccessCount) return
59
+
60
+ handledSubmitSuccessCountRef.current = submitSuccessCount
61
+ setMarkedForDeletion(false)
62
+ clearSelectedFile()
63
+ }, [clearSelectedFile, submitSuccessCount])
29
64
 
30
65
  const onImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
31
66
  if (event.target.files && event.target.files[0]) {
@@ -52,7 +87,16 @@ export default function PhotoFormInput({ input, sectionName }: { input: PhotoFie
52
87
  />
53
88
  )
54
89
 
55
- const handleImageDelete = () => {}
90
+ const handleImageDelete = () => {
91
+ setMarkedForDeletion(true)
92
+ clearSelectedFile()
93
+ setModal(null)
94
+ }
95
+
96
+ const handleUndoDeletion = () => {
97
+ setMarkedForDeletion(false)
98
+ }
99
+
56
100
  return (
57
101
  <FormInputElement
58
102
  validationError={error}
@@ -61,6 +105,13 @@ export default function PhotoFormInput({ input, sectionName }: { input: PhotoFie
61
105
  label={input.label}
62
106
  required={input.required}
63
107
  >
108
+ {markedForDeletion && input.value ? (
109
+ <input
110
+ type='hidden'
111
+ name='__removedFile'
112
+ value={JSON.stringify({ fieldName: input.name, fileName: input.value })}
113
+ />
114
+ ) : null}
64
115
  <Card className='flex max-w-full flex-col'>
65
116
  <CardHeader>
66
117
  <CardTitle className='flex flex-wrap content-center items-center gap-1.5'>
@@ -99,119 +150,124 @@ export default function PhotoFormInput({ input, sectionName }: { input: PhotoFie
99
150
  </div>
100
151
  ) : null}
101
152
  </div>
102
- <div className='flex flex-col gap-4'>
103
- {input.value ? protectedImage : null}
104
- {image ? (
105
- <div className='relative flex items-center'>
106
- <ChevronRight fontSize='large' />
107
- <div className='relative h-[150px] w-[150px]'>
108
- <X
109
- className='absolute -right-3 -top-3 z-10 cursor-pointer rounded-full border-2 border-gray-500 bg-white p-1'
110
- onClick={() => {
111
- setImage(null)
112
- setFileName(t('noFileSelected'))
113
- field.onChange(undefined)
114
- if (fileInputContainerRef.current) {
115
- /**
116
- * Clear the child input value
117
- */
153
+ {markedForDeletion ? (
154
+ <div className='flex items-center gap-3 rounded border border-amber-400 bg-amber-50 p-3 dark:border-amber-600 dark:bg-amber-950'>
155
+ <span className='text-sm text-amber-800 dark:text-amber-200'>
156
+ {t('photoMarkedForDeletion')}
157
+ </span>
158
+ <button
159
+ type='button'
160
+ className='flex items-center gap-1 text-sm font-medium text-blue-600 underline hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300'
161
+ onClick={handleUndoDeletion}
162
+ >
163
+ <Undo2Icon size={14} /> {t('undo')}
164
+ </button>
165
+ </div>
166
+ ) : (
167
+ <>
168
+ <div className='flex flex-col gap-4'>
169
+ {input.value ? protectedImage : null}
170
+ {image ? (
171
+ <div className='relative flex items-center'>
172
+ <ChevronRight fontSize='large' />
173
+ <div className='relative h-[150px] w-[150px]'>
174
+ <X
175
+ className='absolute -right-3 -top-3 z-10 cursor-pointer rounded-full border-2 border-gray-500 bg-white p-1'
176
+ onClick={clearSelectedFile}
177
+ />
178
+ <Image
179
+ className='mb-4 rounded p-1 ring-3 ring-green-600'
180
+ src={image}
181
+ alt={t('newImage') as string}
182
+ fill={true}
183
+ style={{
184
+ objectFit: 'contain',
185
+ }}
186
+ />
187
+ </div>
188
+ </div>
189
+ ) : null}
190
+ </div>
191
+ <div ref={fileInputContainerRef}>
192
+ <input
193
+ type='file'
194
+ className='hidden'
195
+ name={field.name}
196
+ ref={field.ref}
197
+ onChange={(e) => {
198
+ onImageChange(e)
199
+ if (!input.value) {
200
+ field.onChange(e.target?.files?.length ? e.target.files[0] : undefined)
201
+ }
202
+ }}
203
+ />
204
+ </div>
205
+ <div className='flex flex-col items-center gap-2 md:flex-row'>
206
+ <div className='flex w-full flex-col'>
207
+ {[false, 'false', 0].includes(input.required) &&
208
+ !['', null, undefined].includes(input.value) ? (
209
+ <div className='w-[400px] max-w-full'>
210
+ <button
211
+ type='button'
212
+ className='flex w-full flex-wrap items-center justify-center gap-1.5 rounded border bg-linear-to-r from-red-600 to-amber-500 p-2 text-center text-sm font-bold uppercase text-white drop-shadow-sm hover:from-red-400 hover:to-amber-400'
213
+ onClick={() => {
214
+ setModal({
215
+ title: t('deletePhoto'),
216
+ body: (
217
+ <div className='p-4'>
218
+ <div className='flex flex-col gap-4'>
219
+ <div>{t('deletePhotoText')}</div>
220
+ <div className='flex gap-2'>
221
+ <button
222
+ className='rounded bg-green-600 px-2 py-1 text-white'
223
+ onClick={handleImageDelete}
224
+ >
225
+ {t('yes')}
226
+ </button>
227
+ <button
228
+ className='rounded bg-red-800 px-2 py-1 text-white'
229
+ onClick={() => {
230
+ setModal(null)
231
+ }}
232
+ >
233
+ {t('no')}
234
+ </button>
235
+ </div>
236
+ </div>
237
+ </div>
238
+ ),
239
+ headerColor: 'bg-red-700',
240
+ titleColor: 'text-white',
241
+ lang: 'en',
242
+ })
243
+ }}
244
+ >
245
+ <Trash2Icon size={20} /> {t('delete')}
246
+ </button>
247
+ </div>
248
+ ) : null}
249
+ <div className='dark:border-neutral my-2 flex w-[400px] max-w-full flex-col gap-1 rounded-lg border border-gray-400 p-2'>
250
+ <button
251
+ type='button'
252
+ className='flex w-full flex-wrap items-center justify-center gap-1.5 rounded border bg-linear-to-r from-blue-700 to-sky-500 p-2 text-center text-sm font-bold uppercase text-white drop-shadow-sm hover:from-blue-500 hover:to-sky-400'
253
+ onClick={() => {
118
254
  if (fileInputContainerRef.current?.firstChild) {
119
255
  ;(
120
256
  fileInputContainerRef.current.firstChild as HTMLInputElement
121
- ).value = ''
257
+ ).click()
122
258
  }
123
- }
124
- }}
125
- />
126
- <Image
127
- className='mb-4 rounded p-1 ring-3 ring-green-600'
128
- src={image}
129
- alt={t('newImage') as string}
130
- fill={true}
131
- style={{
132
- objectFit: 'contain',
133
- }}
134
- />
259
+ }}
260
+ >
261
+ <UploadIcon size={20} /> {t('selectFile')}
262
+ </button>
263
+ <div className='flex w-full ps-2'>
264
+ <div className='break-all'>{fileName}</div>
265
+ </div>
266
+ </div>
135
267
  </div>
136
268
  </div>
137
- ) : null}
138
- </div>
139
- <div ref={fileInputContainerRef}>
140
- <input
141
- type='file'
142
- className='hidden'
143
- name={field.name}
144
- ref={field.ref}
145
- onChange={(e) => {
146
- onImageChange(e)
147
- if (!input.value) {
148
- field.onChange(e.target?.files?.length ? e.target.files[0] : undefined)
149
- }
150
- }}
151
- />
152
- </div>
153
- <div className='flex flex-col items-center gap-2 md:flex-row'>
154
- <div className='flex w-full flex-col'>
155
- {[false, 'false', 0].includes(input.required) &&
156
- !['', null, undefined].includes(input.value) ? (
157
- <div className='w-[400px] max-w-full'>
158
- <button
159
- type='button'
160
- className='flex w-full flex-wrap items-center justify-center gap-1.5 rounded border bg-linear-to-r from-red-600 to-amber-500 p-2 text-center text-sm font-bold uppercase text-white drop-shadow-sm hover:from-red-400 hover:to-amber-400'
161
- onClick={() => {
162
- setModal({
163
- title: t('deletePhoto'),
164
- body: (
165
- <div className='p-4'>
166
- <div className='flex flex-col gap-4'>
167
- <div>{t('deletePhotoText')}</div>
168
- <div className='flex gap-2'>
169
- <button
170
- className='rounded bg-green-600 px-2 py-1 text-white'
171
- onClick={handleImageDelete}
172
- >
173
- {t('yes')}
174
- </button>
175
- <button
176
- className='rounded bg-red-800 px-2 py-1 text-white'
177
- onClick={() => {
178
- setModal(null)
179
- }}
180
- >
181
- {t('no')}
182
- </button>
183
- </div>
184
- </div>
185
- </div>
186
- ),
187
- headerColor: 'bg-red-700',
188
- titleColor: 'text-white',
189
- lang: 'en',
190
- })
191
- }}
192
- >
193
- <Trash2Icon size={20} /> {t('delete')}
194
- </button>
195
- </div>
196
- ) : null}
197
- <div className='dark:border-neutral my-2 flex w-[400px] max-w-full flex-col gap-1 rounded-lg border border-gray-400 p-2'>
198
- <button
199
- type='button'
200
- className='flex w-full flex-wrap items-center justify-center gap-1.5 rounded border bg-linear-to-r from-blue-700 to-sky-500 p-2 text-center text-sm font-bold uppercase text-white drop-shadow-sm hover:from-blue-500 hover:to-sky-400'
201
- onClick={() => {
202
- if (fileInputContainerRef.current?.firstChild) {
203
- ;(fileInputContainerRef.current.firstChild as HTMLInputElement).click()
204
- }
205
- }}
206
- >
207
- <UploadIcon size={20} /> {t('selectFile')}
208
- </button>
209
- <div className='flex w-full ps-2'>
210
- <div className='break-all'>{fileName}</div>
211
- </div>
212
- </div>
213
- </div>
214
- </div>
269
+ </>
270
+ )}
215
271
  </CardContent>
216
272
  </Card>
217
273
  </FormInputElement>
@@ -5,6 +5,7 @@ import FormInputElement from '@/components/form/FormInputElement'
5
5
  import { useAxiosPrivate } from 'nextjs-cms/auth/hooks'
6
6
  import { RichTextFieldClientConfig } from 'nextjs-cms/core/fields'
7
7
  import { FieldError, useFormContext } from 'react-hook-form'
8
+ import { useLocale } from '@/components/form/ContentLocaleContext'
8
9
 
9
10
  export default function RichTextFormInput({ input }: { input: RichTextFieldClientConfig }) {
10
11
  const { setValue, register, formState } = useFormContext()
@@ -13,6 +14,7 @@ export default function RichTextFormInput({ input }: { input: RichTextFieldClien
13
14
  const value = input.value ? input.value : ''
14
15
  const [initialValue, setInitialValue] = useState('')
15
16
  const [key, setKey] = useState(0) // Step 1: Add key state
17
+ const locale = useLocale()
16
18
  // const [editorPhotos, setEditorPhotos] = useState<string[]>([])
17
19
  // const { theme } = useTheme()
18
20
  const axiosPrivate = useAxiosPrivate()
@@ -114,6 +116,7 @@ export default function RichTextFormInput({ input }: { input: RichTextFieldClien
114
116
  plugins: plugins,
115
117
  toolbar: toolbar,
116
118
 
119
+ directionality: input.rtl !== undefined ? (input.rtl ? 'rtl' : 'ltr') : (locale?.rtl ? 'rtl' : 'ltr'),
117
120
  content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
118
121
  // skin: theme === 'light' ? 'oxide' : 'oxide-dark',
119
122
  // content_css: theme === 'light' ? 'default' : 'dark',
@@ -23,7 +23,7 @@ export default function SelectFormInput({
23
23
  }) {
24
24
  const t = useI18n()
25
25
  const session = useSession()
26
- const locale = session?.data?.user?.locale
26
+ const locale = session?.data?.user?.language
27
27
 
28
28
  /**
29
29
  * Create options array with translated placeholder option.
@@ -6,6 +6,7 @@ import { Badge } from '@/components/ui/badge'
6
6
  import { Input } from '@/components/ui/input'
7
7
  import { X } from 'lucide-react'
8
8
  import { useState, useRef, useEffect, useCallback } from 'react'
9
+ import { useSearchParams } from 'next/navigation'
9
10
  import { cn } from '@/lib/utils'
10
11
  import { trpc } from '@/app/_trpc/client'
11
12
 
@@ -16,7 +17,10 @@ export default function TagsFormInput({
16
17
  input: TagsFieldClientConfig
17
18
  sectionName: string
18
19
  }) {
19
- const t = useI18n()
20
+ const t = useI18n()
21
+ const searchParams = useSearchParams()
22
+ const localeParam = searchParams.get('locale')
23
+ const locale = input.localized ? (localeParam?.trim() ? localeParam : undefined) : undefined
20
24
  const { control } = useFormContext()
21
25
  const {
22
26
  field,
@@ -45,7 +49,7 @@ export default function TagsFormInput({
45
49
  }, [inputValue, input.hasAutoCompletion])
46
50
 
47
51
  const { data: suggestions } = trpc.fields.tagsAutoComplete.useQuery(
48
- { sectionName, fieldName: input.name, query: debouncedQuery },
52
+ { sectionName, fieldName: input.name, query: debouncedQuery, locale },
49
53
  { enabled: input.hasAutoCompletion && debouncedQuery.length >= 1 },
50
54
  )
51
55
 
@@ -2,6 +2,7 @@ import React from 'react'
2
2
  import FormInputElement from '@/components/form/FormInputElement'
3
3
  import type { TextFieldClientConfig } from 'nextjs-cms/core/fields'
4
4
  import { useFormContext, useController } from 'react-hook-form'
5
+ import { useLocale } from '@/components/form/ContentLocaleContext'
5
6
 
6
7
  export default function TextFormInput({
7
8
  input,
@@ -22,6 +23,7 @@ export default function TextFormInput({
22
23
  defaultValue: input.value ?? undefined,
23
24
  disabled: disabled,
24
25
  })
26
+ const locale = useLocale()
25
27
 
26
28
  return (
27
29
  <FormInputElement
@@ -34,6 +36,7 @@ export default function TextFormInput({
34
36
  <input
35
37
  placeholder={input.placeholder ? input.placeholder : input.label}
36
38
  type='text'
39
+ dir={input.rtl !== undefined ? (input.rtl ? 'rtl' : 'ltr') : (locale?.rtl ? 'rtl' : 'ltr')}
37
40
  readOnly={disabled}
38
41
  disabled={field.disabled}
39
42
  name={field.name}
@@ -2,6 +2,7 @@ import React from 'react'
2
2
  import FormInputElement from '@/components/form/FormInputElement'
3
3
  import { TextAreaFieldClientConfig } from 'nextjs-cms/core/fields'
4
4
  import { FieldError, useController, useFormContext } from 'react-hook-form'
5
+ import { useLocale } from '@/components/form/ContentLocaleContext'
5
6
 
6
7
  export default function TextareaFormInput({
7
8
  input,
@@ -22,6 +23,7 @@ export default function TextareaFormInput({
22
23
  defaultValue: defaultValue ?? input.value ?? undefined,
23
24
  disabled: input.readonly,
24
25
  })
26
+ const locale = useLocale()
25
27
 
26
28
  return (
27
29
  <FormInputElement
@@ -33,6 +35,7 @@ export default function TextareaFormInput({
33
35
  >
34
36
  <textarea
35
37
  placeholder={input.label}
38
+ dir={input.rtl !== undefined ? (input.rtl ? 'rtl' : 'ltr') : (locale?.rtl ? 'rtl' : 'ltr')}
36
39
  readOnly={input.readonly}
37
40
  disabled={field.disabled}
38
41
  name={field.name}
@@ -1,74 +1,74 @@
1
- 'use client'
2
-
3
- import { useCallback, useState } from 'react'
4
- import { useRouter } from 'next/navigation'
5
- import { trpc } from '@/app/_trpc/client'
6
- import { useSession, refreshSession } from 'nextjs-cms/auth/react'
7
- import { useI18n } from 'nextjs-cms/translations/client'
8
- import { setLoginPageLocaleCookie } from 'nextjs-cms/translations'
9
- import { useToast } from '@/components/ui/use-toast'
10
- import LocalePicker from './locale-picker'
11
-
12
- /**
13
- * Locale dropdown for the app Navbar (authenticated).
14
- * Persists via accountSettings.updateLocale → admins table → auth refresh.
15
- * Also writes nextjs-cms-locale cookie so the login page shows the same locale after logout.
16
- */
17
- export default function LocaleDropdown() {
18
- const t = useI18n()
19
- const router = useRouter()
20
- const { toast } = useToast()
21
- const { data: session } = useSession()
22
- const i18nQuery = trpc.config.getI18n.useQuery()
23
- const updateLocale = trpc.accountSettings.updateLocale.useMutation({
24
- onSuccess: async (_data, variables) => {
25
- setLoginPageLocaleCookie(variables.locale)
26
- try {
27
- const res = await fetch('/api/auth/refresh', { credentials: 'include' })
28
- const data = await res.json()
29
- if (res.ok && data.session) {
30
- await refreshSession(data.session)
31
- router.refresh()
32
- } else {
33
- router.refresh()
34
- }
35
- } catch {
36
- router.refresh()
37
- } finally {
38
- setPendingLocale(null)
39
- }
40
- },
41
- onError: () => {
42
- setPendingLocale(null)
43
- toast({
44
- variant: 'destructive',
45
- title: t('error'),
46
- description: t('somethingWentWrong'),
47
- })
48
- },
49
- })
50
- const [pendingLocale, setPendingLocale] = useState<string | null>(null)
51
-
52
- const supported = i18nQuery.data?.supportedLanguages ?? []
53
- const currentLocale = session?.user?.locale ?? i18nQuery.data?.fallbackLanguage ?? 'en'
54
-
55
- const handleSelect = useCallback(
56
- (locale: string) => {
57
- if (locale === currentLocale) return
58
- setPendingLocale(locale)
59
- updateLocale.mutate({ locale })
60
- },
61
- [currentLocale, updateLocale],
62
- )
63
-
64
- return (
65
- <LocalePicker
66
- supportedLanguages={supported}
67
- currentLocale={currentLocale}
68
- onLocaleChange={handleSelect}
69
- disabled={updateLocale.isPending}
70
- loading={updateLocale.isPending && pendingLocale != null}
71
- ariaLabel={t('language')}
72
- />
73
- )
74
- }
1
+ 'use client'
2
+
3
+ import { useCallback, useState } from 'react'
4
+ import { useRouter } from 'next/navigation'
5
+ import { trpc } from '@/app/_trpc/client'
6
+ import { useSession, refreshSession } from 'nextjs-cms/auth/react'
7
+ import { useI18n } from 'nextjs-cms/translations/client'
8
+ import { setLoginPageLanguageCookie } from 'nextjs-cms/translations'
9
+ import { useToast } from '@/components/ui/use-toast'
10
+ import LanguagePicker from './language-picker'
11
+
12
+ /**
13
+ * Language dropdown for the app Navbar (authenticated).
14
+ * Persists via accountSettings.updateLanguage → admins table → auth refresh.
15
+ * Also writes nextjs-cms-locale cookie so the login page shows the same language after logout.
16
+ */
17
+ export default function LanguageDropdown() {
18
+ const t = useI18n()
19
+ const router = useRouter()
20
+ const { toast } = useToast()
21
+ const { data: session } = useSession()
22
+ const i18nQuery = trpc.config.getI18n.useQuery()
23
+ const updateLanguage = trpc.accountSettings.updateLanguage.useMutation({
24
+ onSuccess: async (_data, variables) => {
25
+ setLoginPageLanguageCookie(variables.language)
26
+ try {
27
+ const res = await fetch('/api/auth/refresh', { credentials: 'include' })
28
+ const data = await res.json()
29
+ if (res.ok && data.session) {
30
+ await refreshSession(data.session)
31
+ router.refresh()
32
+ } else {
33
+ router.refresh()
34
+ }
35
+ } catch {
36
+ router.refresh()
37
+ } finally {
38
+ setPendingLanguage(null)
39
+ }
40
+ },
41
+ onError: () => {
42
+ setPendingLanguage(null)
43
+ toast({
44
+ variant: 'destructive',
45
+ title: t('error'),
46
+ description: t('somethingWentWrong'),
47
+ })
48
+ },
49
+ })
50
+ const [pendingLanguage, setPendingLanguage] = useState<string | null>(null)
51
+
52
+ const supported = i18nQuery.data?.supportedLanguages ?? []
53
+ const currentLanguage = session?.user?.language ?? i18nQuery.data?.fallbackLanguage ?? 'en'
54
+
55
+ const handleSelect = useCallback(
56
+ (language: string) => {
57
+ if (language === currentLanguage) return
58
+ setPendingLanguage(language)
59
+ updateLanguage.mutate({ language })
60
+ },
61
+ [currentLanguage, updateLanguage],
62
+ )
63
+
64
+ return (
65
+ <LanguagePicker
66
+ supportedLanguages={supported}
67
+ currentLanguage={currentLanguage}
68
+ onLanguageChange={handleSelect}
69
+ disabled={updateLanguage.isPending}
70
+ loading={updateLanguage.isPending && pendingLanguage != null}
71
+ ariaLabel={t('language')}
72
+ />
73
+ )
74
+ }