-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
templateAppDir.ts
199 lines (169 loc) · 5.52 KB
/
templateAppDir.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import { ParsedFilePkg } from './types'
import {
interceptExport,
addLoadLocalesFrom,
clientLine,
INTERNAL_CONFIG_KEY,
} from './utils'
const validPages = [
'/page',
'/layout',
'/error',
'/loading',
'/not-found',
'/global-error',
]
const validPagesRegex = new RegExp(`(${validPages.join('|')})$`)
export default function templateAppDir(
pagePkg: ParsedFilePkg,
{
code = '',
pageNoExt = '/',
normalizedResourcePath = '',
appFolder = '',
isClientComponent = false,
existLocalesFolder = true,
} = {}
) {
const routeType =
validPages.find((pageName) => pageNoExt.endsWith(pageName)) || 'component'
const isPage =
routeType !== 'component' && normalizedResourcePath.includes(appFolder)
// Ignore files that are not RSC or RCC valid pages
if (!isPage) return code
const hash = Date.now().toString(16)
const pathname = pageNoExt.replace(validPagesRegex, '/')
// Removes the export default from the page
// and tells under what name we can get the old export
const pageVariableName = interceptExport(
pagePkg,
'default',
`__Next_Translate__Page__${hash}__`
)
// Client/Server pages without default export should not be transpiled
if (isPage && !pageVariableName) return code
// Client pages (RCC)
if (isClientComponent) {
return templateRCCPage({
pagePkg,
hash,
pageVariableName,
pathname,
routeType,
existLocalesFolder,
})
}
// Server pages (RSC)
return templateRSCPage({
pagePkg,
hash,
pageVariableName,
pathname,
routeType,
existLocalesFolder,
})
}
type Params = {
pagePkg: ParsedFilePkg
hash: string
pageVariableName: string
pathname?: string
routeType: string
existLocalesFolder: boolean
}
function templateRSCPage({
pagePkg,
hash,
pageVariableName,
pathname,
routeType,
existLocalesFolder,
}: Params) {
const code = pagePkg.getCode()
return `
import ${INTERNAL_CONFIG_KEY} from '@next-translate-root/i18n'
import AppDirI18nProvider from 'next-translate/AppDirI18nProvider'
import __loadNamespaces from 'next-translate/loadNamespaces'
${code}
export default async function __Next_Translate_new__${hash}__(props) {
const detectedLang = props.params?.lang ?? props.searchParams?.lang
if (detectedLang === 'favicon.ico') return <${pageVariableName} {...props} />
${routeType !== '/page'
// Related with https://github.com/aralroca/next-translate/issues/1090
// Early return to avoid conflicts with /layout or /loading that don't have detectedLang
? `if (globalThis.__NEXT_TRANSLATE__ && !detectedLang) return <${pageVariableName} {...props} />`
: ''
}
const config = {
...${INTERNAL_CONFIG_KEY},
locale: detectedLang ?? ${INTERNAL_CONFIG_KEY}.defaultLocale,
loaderName: 'server ${routeType}',
pathname: '${pathname}'
}
const { __lang, __namespaces } = await __loadNamespaces({ ...config, ${addLoadLocalesFrom(
existLocalesFolder
)} });
const oldNamespaces = globalThis.__NEXT_TRANSLATE__?.namespaces ?? {}
const namespaces = { ...oldNamespaces, ...__namespaces }
globalThis.__NEXT_TRANSLATE__ = { lang: __lang, namespaces, config }
return <AppDirI18nProvider lang={__lang} namespaces={namespaces} config={JSON.parse(JSON.stringify(config))}><${pageVariableName} {...props} /></AppDirI18nProvider>
}
`
}
function templateRCCPage({
pagePkg,
hash,
pageVariableName,
pathname,
routeType,
existLocalesFolder,
}: Params) {
const topLine = clientLine[0]
let clientCode = pagePkg.getCode()
// Clear current "use client" top line
clientLine.forEach((line) => {
clientCode = clientCode.replace(line, '')
})
return `${topLine}
import ${INTERNAL_CONFIG_KEY} from '@next-translate-root/i18n'
import AppDirI18nProvider from 'next-translate/AppDirI18nProvider'
import { useSearchParams as __useSearchParams, useParams as __useParams } from 'next/navigation'
import { use as __use, Suspense as __Suspense } from 'react'
import __loadNamespaces from 'next-translate/loadNamespaces'
${clientCode}
export default function __Next_Translate_new__${hash}__(props) {
const searchParams = __useSearchParams()
const params = __useParams()
const detectedLang = params.lang ?? searchParams.get('lang')
if (detectedLang === 'favicon.ico') return <${pageVariableName} {...props} />
${routeType !== '/page'
// Related with https://github.com/aralroca/next-translate/issues/1090
// Early return to avoid conflicts with /layout or /loading that don't have detectedLang
? `if (globalThis.__NEXT_TRANSLATE__ && !detectedLang) return <${pageVariableName} {...props} />`
: ''
}
const lang = detectedLang ?? ${INTERNAL_CONFIG_KEY}.defaultLocale
const config = {
...${INTERNAL_CONFIG_KEY},
locale: lang,
loaderName: 'client ${routeType}',
pathname: '${pathname}',
}
return (
<__Suspense fallback={null}>
<__Next_Translate__child__${hash}__
{...props}
config={config}
promise={__loadNamespaces({ ...config, ${addLoadLocalesFrom(existLocalesFolder)} })}
/>
</__Suspense>
)
}
function __Next_Translate__child__${hash}__({ promise, config, ...props }) {
const { __lang, __namespaces } = __use(promise);
const oldNamespaces = globalThis.__NEXT_TRANSLATE__?.namespaces ?? {};
globalThis.__NEXT_TRANSLATE__ = { lang: __lang, namespaces: { ...oldNamespaces, ...__namespaces }, config };
return <${pageVariableName} {...props} />;
}
`
}