forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path$version.docs.framework.$framework.examples.$.tsx
More file actions
409 lines (370 loc) · 12.9 KB
/
$version.docs.framework.$framework.examples.$.tsx
File metadata and controls
409 lines (370 loc) · 12.9 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import { isNotFound, notFound, createFileRoute } from '@tanstack/react-router'
import {
queryOptions,
useQuery,
useQueryClient,
useSuspenseQuery,
} from '@tanstack/react-query'
import React from 'react'
import { DocTitle } from '~/components/DocTitle'
import { Framework, getBranch, getLibrary } from '~/libraries'
import { fetchFile, fetchRepoDirectoryContents } from '~/utils/docs'
import {
getExampleStartingFileName,
getExampleStartingPath,
} from '~/utils/sandbox'
import { seo } from '~/utils/seo'
import { capitalize, slugToTitle } from '~/utils/utils'
import * as v from 'valibot'
import { CodeExplorer } from '~/components/CodeExplorer'
import type { GitHubFileNode } from '~/utils/documents.server'
import { ExternalLink } from 'lucide-react'
import {
ExampleDeployDialog,
type DeployProvider,
} from '~/components/ExampleDeployDialog'
const fileQueryOptions = (repo: string, branch: string, filePath: string) => {
return queryOptions({
queryKey: ['currentCode', repo, branch, filePath],
queryFn: () =>
fetchFile({
data: { repo, branch, filePath },
}),
staleTime: Infinity, // We can cache this forever. A refresh can invalidate the cache if necessary.
})
}
const repoDirApiContentsQueryOptions = (
repo: string,
branch: string,
startingPath: string,
) =>
queryOptions({
queryKey: ['repo-api-contents', repo, branch, startingPath],
queryFn: () =>
fetchRepoDirectoryContents({
data: { repo, branch, startingPath },
}),
staleTime: Infinity, // We can cache this forever. A refresh can invalidate the cache if necessary.
})
export const Route = createFileRoute(
'/$libraryId/$version/docs/framework/$framework/examples/$',
)({
component: RouteComponent,
validateSearch: v.object({
path: v.optional(v.string()),
panel: v.optional(v.string()),
}),
loaderDeps: ({ search }) => ({ path: search.path }),
loader: async ({ params, context: { queryClient }, deps: { path } }) => {
const library = getLibrary(params.libraryId)
const branch = getBranch(library, params.version)
const examplePath = [params.framework, params._splat].join('/')
// Used to tell the github contents api where to start looking for files in the target repository
const repoStartingDirPath = `examples/${examplePath}`
try {
// Fetching and Caching the contents of the target directory
const githubContents = await queryClient.ensureQueryData(
repoDirApiContentsQueryOptions(
library.repo,
branch,
repoStartingDirPath,
),
)
// Used to determine the starting file name for the explorer
// It's either the selected path in the search params or a default we can derive
// i.e. app.tsx, main.tsx, src/routes/__root.tsx, etc.
// This value is not absolutely guaranteed to be available, so further resolution may be necessary
const explorerCandidateStartingFileName =
path ||
getExampleStartingPath(params.framework as Framework, params.libraryId)
// Using the fetched contents, get the actual starting file-path for the explorer
// The `explorerCandidateStartingFileName` is used for matching, but the actual file-path may differ
const currentPath = determineStartingFilePath(
githubContents,
explorerCandidateStartingFileName,
params.framework as Framework,
params.libraryId,
)
// Now that we've resolved the starting file path, we can
// fetching and caching the file content for the starting file path
await queryClient.ensureQueryData(
fileQueryOptions(library.repo, branch, currentPath),
)
return { repoStartingDirPath, currentPath }
} catch (error) {
const isNotFoundError =
isNotFound(error) ||
(error && typeof error === 'object' && 'isNotFound' in error)
if (isNotFoundError) {
throw notFound()
}
throw error
}
},
head: ({ params }) => {
const library = getLibrary(params.libraryId)
return {
meta: seo({
title: `${capitalize(params.framework)} ${library.name} ${slugToTitle(
params._splat || '',
)} Example | ${library.name} Docs`,
description: `An example showing how to implement ${slugToTitle(
params._splat || '',
)} in ${capitalize(params.framework)} using ${library.name}.`,
noindex: library.visible === false,
}),
}
},
staleTime: 1000 * 60 * 5, // 5 minutes
})
function RouteComponent() {
const { _splat } = Route.useParams()
return <PageComponent key={`page-${_splat}`} />
}
function PageComponent() {
const { repoStartingDirPath, currentPath } = Route.useLoaderData()
const navigate = Route.useNavigate()
const queryClient = useQueryClient()
const { version, framework, _splat, libraryId } = Route.useParams()
const library = getLibrary(libraryId)
const branch = getBranch(library, version)
const examplePath = [framework, _splat].join('/')
const mainExampleFile = getExampleStartingPath(
framework as Framework,
libraryId,
)
const { data: githubContents } = useSuspenseQuery(
repoDirApiContentsQueryOptions(library.repo, branch, repoStartingDirPath),
)
const [isDark, setIsDark] = React.useState(true)
const [deployDialogOpen, setDeployDialogOpen] = React.useState(false)
const [deployProvider, setDeployProvider] =
React.useState<DeployProvider | null>(null)
const openDeployDialog = (provider: DeployProvider) => {
setDeployProvider(provider)
setDeployDialogOpen(true)
}
const closeDeployDialog = () => {
setDeployDialogOpen(false)
setDeployProvider(null)
}
const activeTab = Route.useSearch({
select: (s) => {
if (typeof window === 'undefined') return s.panel || 'code'
const localValue = localStorage.getItem('exampleViewPreference') as
| 'code'
| 'sandbox'
| null
return s.panel || localValue || 'code'
},
})
const setActiveTab = (tab: string) => {
if (typeof window === 'undefined') {
localStorage.setItem('exampleViewPreference', tab)
}
navigate({
search: { path: undefined, panel: tab },
replace: true,
resetScroll: true,
})
}
const setCurrentPath = (path: string) => {
navigate({
search: { path, panel: undefined },
replace: true,
resetScroll: false,
})
}
const { data: currentCode } = useQuery(
fileQueryOptions(library.repo, branch, currentPath),
)
const prefetchFileContent = React.useCallback(
(path: string) => {
queryClient.prefetchQuery(fileQueryOptions(library.repo, branch, path))
},
[queryClient, library.repo, branch],
)
// Update local storage when tab changes
React.useEffect(() => {
localStorage.setItem('exampleViewPreference', activeTab)
}, [activeTab])
React.useEffect(() => {
setIsDark(window.matchMedia?.(`(prefers-color-scheme: dark)`).matches)
}, [])
const githubUrl = `https://github.com/${library.repo}/tree/${branch}/examples/${examplePath}`
// preset=node can be removed once Stackblitz runs Angular as webcontainer by default
// See https://github.com/stackblitz/core/issues/2957
const stackBlitzUrl = `https://stackblitz.com/github/${
library.repo
}/tree/${branch}/examples/${examplePath}?embed=1&theme=${
isDark ? 'dark' : 'light'
}&preset=node&file=${mainExampleFile}`
const codeSandboxUrl = `https://codesandbox.io/p/devbox/github/${
library.repo
}/tree/${branch}/examples/${examplePath}?embed=1&theme=${
isDark ? 'dark' : 'light'
}&file=${mainExampleFile}`
return (
<div className="flex-1 flex flex-col min-h-0 overflow-auto h-[95dvh]">
<div className="p-4 lg:p-6">
<DocTitle>
<span>
{capitalize(framework)} Example: {slugToTitle(_splat!)}
</span>
<div className="flex items-center gap-4 flex-wrap font-normal text-xs">
{library.showCloudflareUrl ? (
<button
type="button"
onClick={() => openDeployDialog('cloudflare')}
className="hover:opacity-80 transition-opacity"
>
<img
src="https://deploy.workers.cloudflare.com/button"
loading="lazy"
alt="Deploy to Cloudflare"
/>
</button>
) : null}
{library.showNetlifyUrl ? (
<button
type="button"
onClick={() => openDeployDialog('netlify')}
className="hover:opacity-80 transition-opacity"
>
<img
src="https://www.netlify.com/img/deploy/button.svg"
loading="lazy"
alt="Deploy with Netlify"
/>
</button>
) : null}
{library.showRailwayUrl ? (
<button
type="button"
onClick={() => openDeployDialog('railway')}
className="hover:opacity-80 transition-opacity"
>
<img
src="https://railway.com/button.svg?utm_medium=sponsor&utm_source=oss&utm_campaign=tanstack"
loading="lazy"
alt="Deploy on Railway"
/>
</button>
) : null}
<a
href={githubUrl}
target="_blank"
className="flex gap-1 items-center"
rel="noreferrer"
>
<ExternalLink /> GitHub
</a>
{!library.hideStackblitzUrl ? (
<a
href={stackBlitzUrl}
target="_blank"
className="flex gap-1 items-center"
rel="noreferrer"
>
<ExternalLink /> StackBlitz
</a>
) : null}
{!library.hideCodesandboxUrl ? (
<a
href={codeSandboxUrl}
target="_blank"
className="flex gap-1 items-center"
rel="noreferrer"
>
<ExternalLink /> CodeSandbox
</a>
) : null}
</div>
</DocTitle>
</div>
<div className="flex-1 lg:px-6 flex flex-col min-h-0">
<CodeExplorer
activeTab={activeTab as 'code' | 'sandbox'}
codeSandboxUrl={codeSandboxUrl}
currentCode={currentCode || ''}
currentPath={currentPath}
examplePath={examplePath}
githubContents={githubContents || undefined}
library={library}
prefetchFileContent={prefetchFileContent}
setActiveTab={setActiveTab}
setCurrentPath={setCurrentPath}
stackBlitzUrl={stackBlitzUrl}
/>
</div>
{deployProvider && (
<ExampleDeployDialog
isOpen={deployDialogOpen}
onClose={closeDeployDialog}
provider={deployProvider}
repo={library.repo}
branch={branch}
examplePath={examplePath}
exampleName={slugToTitle(_splat!)}
libraryName={library.name}
/>
)}
</div>
)
}
function determineStartingFilePath(
nodes: Array<GitHubFileNode> | null,
candidate: string,
framework: Framework,
libraryId: string,
) {
if (!nodes) return candidate
const bannedDirs = new Set(['public', '.vscode', 'tests', 'spec', 'assets'])
const flattened = recursiveFlattenGithubContents(nodes, bannedDirs)
const found = flattened.find((node) => node.path === candidate)
if (found) {
return candidate
}
const preferenceFiles = new Set([
getExampleStartingFileName(framework, libraryId),
...['__root', 'App', 'main', 'index', 'page', 'action']
.map((name) => [`${name}.tsx`, `${name}.ts`, `${name}.js`, `${name}.jsx`])
.flat(),
'README.md',
])
const preferenceDirs = new Set(['src', 'routes', 'app', 'pages'])
// Try and find a preference file
for (const file of preferenceFiles) {
const found = flattened.find((node) => node.name === file)
if (found) {
return found.path
}
}
// If no preference file is found, try and find the first file from a preference directory
for (const dir of preferenceDirs) {
const found = flattened.find(
(node) => node.path.startsWith(dir) && node.type === 'file',
)
if (found) {
return found.path
}
}
// If no preference file is found, just return the first file
const firstFile = flattened.find((node) => node.type === 'file')
if (firstFile) {
return firstFile.path
}
// If no file is found, return the candidate
return candidate
}
function recursiveFlattenGithubContents(
nodes: Array<GitHubFileNode>,
bannedDirs: Set<string> = new Set(),
): Array<GitHubFileNode> {
return nodes.flatMap((node) => {
if (node.type === 'dir' && node.children && !bannedDirs.has(node.name)) {
return recursiveFlattenGithubContents(node.children, bannedDirs)
}
return node
})
}