-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy path[...filePath].vue
More file actions
623 lines (559 loc) · 22 KB
/
[...filePath].vue
File metadata and controls
623 lines (559 loc) · 22 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
<script setup lang="ts">
definePageMeta({
name: 'code',
path: '/package-code/:org?/:packageName/v/:version/:filePath(.*)?',
alias: [
'/package/code/:org?/:packageName/v/:version/:filePath(.*)?',
'/package/code/:packageName/v/:version/:filePath(.*)?',
// '/code/@:org?/:packageName/v/:version/:filePath(.*)?',
],
scrollMargin: 160,
})
const route = useRoute('code')
// Parse package name, version, and file path from URL
// Patterns:
// /code/nuxt/v/4.2.0 → packageName: "nuxt", version: "4.2.0", filePath: null (show tree)
// /code/nuxt/v/4.2.0/src/index.ts → packageName: "nuxt", version: "4.2.0", filePath: "src/index.ts"
// /code/@nuxt/kit/v/1.0.0 → packageName: "@nuxt/kit", version: "1.0.0", filePath: null
const parsedRoute = computed(() => {
const packageName = route.params.org
? `${route.params.org}/${route.params.packageName}`
: route.params.packageName
const version = route.params.version
const filePath = route.params.filePath || null
return { packageName, version, filePath }
})
const packageName = computed(() => parsedRoute.value.packageName)
const version = computed(() => parsedRoute.value.version)
const filePathOrig = computed(() => parsedRoute.value.filePath)
const filePath = computed(() => parsedRoute.value.filePath?.replace(/\/$/, ''))
// Navigation helper - build URL for a path
function getCodeUrl(args: {
org?: string
packageName: string
version: string
filePath?: string
}): string {
const base = args.org
? `/package-code/${args.org}/${args.packageName}/v/${args.version}`
: `/package-code/${args.packageName}/v/${args.version}`
return args.filePath ? `${base}/${args.filePath}` : base
}
// Fetch package data for version list
const { data: pkg } = usePackage(packageName)
// URL pattern for version selector - includes file path if present
const versionUrlPattern = computed(() =>
getCodeUrl({
org: route.params.org,
packageName: route.params.packageName,
version: '{version}',
filePath: filePath.value,
}),
)
// Fetch file tree
const { data: fileTree, status: treeStatus } = useFetch<PackageFileTreeResponse>(
() => `/api/registry/files/${packageName.value}/v/${version.value}`,
{
immediate: !!version.value,
},
)
// Determine what to show based on the current path
// Note: This needs fileTree to be loaded first
const currentNode = computed(() => {
if (!fileTree.value?.tree || !filePathOrig.value) return null
// We use original file path to correctly handle trailing slashes for file tree navigation
// - /src/index.ts - correct file path
// - /src/index.ts/ - incorrect file path (but formally can exist as a directory)
// - /src/index and /src/index/ - correct directory paths
const parts = filePathOrig.value.split('/')
let current: PackageFileTree[] | undefined = fileTree.value.tree
let lastFound: PackageFileTree | null = null
const partsLength = parts.length
for (let i = 0; i < partsLength; i++) {
const part = parts[i]
const isLast = i === partsLength - 1
// If the previous part is a directory and the last one is empty (like /lib/) then return the previous directory
if (!part && isLast && lastFound?.type === 'directory') return lastFound
const found: PackageFileTree | undefined = current?.find(n => n.name === part)
if (!found) return null
lastFound = found
if (found.type === 'file' && isLast) return found
current = found.children
}
return lastFound
})
const isViewingFile = computed(() => currentNode.value?.type === 'file')
// Maximum file size we'll try to load (500KB) - must match server
const MAX_FILE_SIZE = 500 * 1024
// Estimate binary file based on mime type
const isBinaryFile = computed(() => {
const contentType = fileContent.value?.contentType
if (!contentType) return false
return isBinaryContentType(contentType)
})
const isFileTooLarge = computed(() => {
const size = currentNode.value?.size
return size !== undefined && size > MAX_FILE_SIZE
})
// Fetch file content when a file is selected (and not too large)
const fileContentUrl = computed(() => {
// Don't fetch if no file path, file tree not loaded, file is too large, or it's a directory
if (!filePath.value || !fileTree.value || isFileTooLarge.value || !isViewingFile.value) {
return null
}
return `/api/registry/file/${packageName.value}/v/${version.value}/${filePath.value}`
})
const {
data: fileContent,
status: fileStatus,
execute: fetchFileContent,
} = useFetch<PackageFileContentResponse>(() => fileContentUrl.value!, { immediate: false })
watch(
fileContentUrl,
url => {
if (url) fetchFileContent()
},
{ immediate: true },
)
// Track hash manually since we update it via history API to avoid scroll
const currentHash = shallowRef('')
onMounted(() => {
currentHash.value = window.location.hash
})
useEventListener('popstate', () => (currentHash.value = window.location.hash))
// Also sync when route changes (e.g., navigating to a different file)
watch(
() => route.hash,
hash => {
currentHash.value = hash
},
)
// Line number handling from hash
const selectedLines = computed(() => {
const hash = currentHash.value
if (!hash) return null
// Parse #L10 or #L10-L20
const match = hash.match(/^#L(\d+)(?:-L(\d+))?$/)
if (!match) return null
const start = parseInt(match[1] ?? '0', 10)
const end = match[2] ? parseInt(match[2], 10) : start
return { start, end }
})
// Scroll to selected line only on initial load or file change (not on click)
const shouldScrollOnHashChange = shallowRef(true)
function scrollToLine() {
if (!shouldScrollOnHashChange.value) return
if (!selectedLines.value) return
const lineEl = document.getElementById(`L${selectedLines.value.start}`)
if (lineEl) {
lineEl.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
}
// Scroll on file content load (initial or file change)
watch(fileContent, () => {
shouldScrollOnHashChange.value = true
nextTick(scrollToLine)
})
// Build breadcrumb path segments
const breadcrumbs = computed(() => {
const parts = filePath.value?.split('/').filter(Boolean) ?? []
const result: { name: string; path: string }[] = []
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
if (part) {
result.push({
name: part,
path: parts.slice(0, i + 1).join('/'),
})
}
}
return result
})
// Navigation helper - build URL for a path
function getCurrentCodeUrlWithPath(path?: string): string {
return getCodeUrl({
...route.params,
filePath: path,
})
}
// Line number click handler - update URL hash without scrolling
function handleLineClick(lineNum: number, event: MouseEvent) {
let newHash: string
if (event.shiftKey && selectedLines.value) {
// Shift+click: select range
const start = Math.min(selectedLines.value.start, lineNum)
const end = Math.max(selectedLines.value.end, lineNum)
newHash = `#L${start}-L${end}`
} else {
// Single click: select line
newHash = `#L${lineNum}`
}
// Don't scroll when user clicks - only scroll on initial load
shouldScrollOnHashChange.value = false
// Update URL without triggering scroll - use history API directly
const url = new URL(window.location.href)
url.hash = newHash
window.history.replaceState(history.state, '', url.toString())
// Update our reactive hash tracker
currentHash.value = newHash
}
// Copy link to current line(s)
const { copied: permalinkCopied, copy: copyPermalink } = useClipboard({ copiedDuring: 2000 })
function copyPermalinkUrl() {
const url = new URL(window.location.href)
copyPermalink(url.toString())
}
const { copied: fileContentCopied, copy: copyFileContent } = useClipboard({
source: () => fileContent.value?.content || '',
copiedDuring: 2000,
})
// Canonical URL for this code page
const canonicalUrl = computed(() => `https://npmx.dev${getCodeUrl(route.params)}`)
// Toggle markdown view mode
const markdownViewModes = [
{
key: 'preview',
label: $t('code.markdown_view_mode.preview'),
icon: 'i-lucide:eye',
},
{
key: 'code',
label: $t('code.markdown_view_mode.code'),
icon: 'i-lucide:code',
},
] as const
const markdownViewMode = shallowRef<(typeof markdownViewModes)[number]['key']>('preview')
const bytesFormatter = useBytesFormatter()
// Keep latestVersion for comparison (to show "(latest)" badge)
const latestVersion = computed(() => {
if (!pkg.value) return null
const latestTag = pkg.value['dist-tags']?.latest
if (!latestTag) return null
return pkg.value.versions[latestTag] ?? null
})
useHead({
link: [{ rel: 'canonical', href: canonicalUrl }],
})
useSeoMeta({
title: () => {
if (filePath.value) {
return `${filePath.value} - ${packageName.value}@${version.value} - npmx`
}
return `Code - ${packageName.value}@${version.value} - npmx`
},
ogTitle: () => {
if (filePath.value) {
return `${filePath.value} - ${packageName.value}@${version.value} - npmx`
}
return `Code - ${packageName.value}@${version.value} - npmx`
},
twitterTitle: () => {
if (filePath.value) {
return `${filePath.value} - ${packageName.value}@${version.value} - npmx`
}
return `Code - ${packageName.value}@${version.value} - npmx`
},
description: () => `Browse source code for ${packageName.value}@${version.value}`,
ogDescription: () => `Browse source code for ${packageName.value}@${version.value}`,
twitterDescription: () => `Browse source code for ${packageName.value}@${version.value}`,
})
defineOgImageComponent('Default', {
title: () => `${pkg.value?.name ?? 'Package'} - Code`,
description: () => pkg.value?.license ?? '',
primaryColor: '#60a5fa',
})
// Sidebar visibility
const { settings } = useSettings()
const isSidebarCollapsed = computed({
get: () => settings.value.sidebar.collapsed.includes('code'),
set: value => {
const collapsed = settings.value.sidebar.collapsed.filter(id => id !== 'code')
if (value) {
collapsed.push('code')
}
settings.value.sidebar.collapsed = collapsed
},
})
function toggleSidebar() {
isSidebarCollapsed.value = !isSidebarCollapsed.value
}
</script>
<template>
<main class="flex-1 flex flex-col">
<PackageHeader
:pkg="pkg"
:resolved-version="version"
:display-version="pkg?.requestedVersion"
:latest-version="latestVersion"
:version-url-pattern="versionUrlPattern"
page="code"
/>
<!-- Error: no version -->
<div v-if="!version" class="container py-20 text-center">
<p class="text-fg-muted mb-4">{{ $t('code.version_required') }}</p>
<LinkBase variant="button-secondary" :to="packageRoute(packageName)">{{
$t('code.go_to_package')
}}</LinkBase>
</div>
<!-- Loading state -->
<div v-else-if="treeStatus === 'pending'" class="container py-20 text-center">
<div class="i-svg-spinners:ring-resize w-8 h-8 mx-auto text-fg-muted" />
<p class="mt-4 text-fg-muted">{{ $t('code.loading_tree') }}</p>
</div>
<!-- Error state -->
<div v-else-if="treeStatus === 'error'" class="container py-20 text-center" role="alert">
<p class="text-fg-muted mb-4">{{ $t('code.failed_to_load_tree') }}</p>
<LinkBase variant="button-secondary" :to="packageRoute(packageName, version)">{{
$t('code.back_to_package')
}}</LinkBase>
</div>
<!-- Main content: file tree + file viewer -->
<div v-else-if="fileTree" class="flex flex-1" dir="ltr">
<!-- File tree sidebar - sticky with internal scroll -->
<aside
v-show="!isSidebarCollapsed"
class="w-64 lg:w-72 border-ie border-border shrink-0 hidden md:block bg-bg-subtle sticky top-25 self-start h-[calc(100vh-7rem)] overflow-y-auto"
>
<CodeFileTree
:tree="fileTree.tree"
:current-path="filePath ?? ''"
:base-url="getCurrentCodeUrlWithPath()"
:base-route="route"
/>
</aside>
<!-- File content / Directory listing - sticky with internal scroll on desktop -->
<div class="flex-1 min-w-0 self-start">
<div
class="sticky z-5 top-25 bg-bg border-b border-border px-4 py-2 flex items-center justify-between gap-2 text-nowrap overflow-x-auto max-w-full"
>
<div class="flex items-center gap-2">
<!-- Sidebar toggle button -->
<button
type="button"
class="hidden md:flex items-center justify-center w-8 h-8 text-fg-subtle hover:text-fg transition-colors focus-visible:outline-accent/70 rounded"
:aria-label="$t(isSidebarCollapsed ? 'code.show_sidebar' : 'code.hide_sidebar')"
@click="toggleSidebar"
>
<span
class="w-4 h-4"
:class="isSidebarCollapsed ? 'i-lucide:sidebar-open' : 'i-lucide:sidebar-close'"
aria-hidden="true"
/>
</button>
<div
v-if="fileContent?.markdownHtml"
class="flex items-center gap-1 p-0.5 bg-bg-subtle border border-border-subtle rounded-md overflow-x-auto"
role="tablist"
aria-label="Markdown view mode selector"
>
<button
v-for="mode in markdownViewModes"
:key="mode.key"
role="tab"
class="px-2 py-1.5 font-mono text-xs rounded transition-colors duration-150 border border-solid focus-visible:outline-accent/70 inline-flex items-center gap-1.5"
:class="
markdownViewMode === mode.key
? 'bg-bg shadow text-fg border-border'
: 'text-fg-subtle hover:text-fg border-transparent'
"
:aria-selected="markdownViewMode === mode.key"
@click="markdownViewMode = mode.key"
>
<span class="inline-block h-3 w-3" :class="mode.icon" aria-hidden="true" />
{{ mode.label }}
</button>
</div>
<!-- Breadcrumb navigation -->
<nav
:aria-label="$t('code.file_path')"
class="flex items-center gap-0.5 font-mono text-sm overflow-x-auto"
dir="ltr"
>
<NuxtLink
v-if="filePath"
:to="getCurrentCodeUrlWithPath()"
class="text-fg-muted hover:text-fg transition-colors shrink-0"
>
{{ $t('code.root') }}
</NuxtLink>
<span v-else class="text-fg shrink-0">{{ $t('code.root') }}</span>
<template v-for="(crumb, i) in breadcrumbs" :key="crumb.path">
<span class="text-fg-subtle">/</span>
<NuxtLink
v-if="i < breadcrumbs.length - 1"
:to="getCurrentCodeUrlWithPath(crumb.path)"
class="text-fg-muted hover:text-fg transition-colors"
>
{{ crumb.name }}
</NuxtLink>
<span v-else class="text-fg">{{ crumb.name }}</span>
</template>
</nav>
</div>
<div class="flex items-center gap-2" v-if="isViewingFile && !isBinaryFile && fileContent">
<button
v-if="selectedLines"
type="button"
class="px-2 py-1 font-mono text-xs text-fg-muted bg-bg-subtle border border-border rounded hover:text-fg hover:border-border-hover transition-colors active:scale-95"
@click="copyPermalinkUrl"
>
{{ permalinkCopied ? $t('common.copied') : $t('code.copy_link') }}
</button>
<button
v-if="!!fileContent?.content"
type="button"
class="px-2 py-1 font-mono text-xs text-fg-muted bg-bg-subtle border border-border rounded hover:text-fg hover:border-border-hover transition-colors inline-flex items-center gap-1 capitalize"
@click="copyFileContent()"
>
<span
class="w-3 h-3"
:class="fileContentCopied ? 'i-lucide:check' : 'i-lucide:file'"
/>
{{ fileContentCopied ? $t('common.copied') : $t('common.copy') }}
</button>
<a
:href="`https://cdn.jsdelivr.net/npm/${packageName}@${version}/${filePath}`"
target="_blank"
rel="noopener noreferrer"
class="px-2 py-1 font-mono text-xs text-fg-muted bg-bg-subtle border border-border rounded hover:text-fg hover:border-border-hover transition-colors inline-flex items-center gap-1"
>
{{ $t('code.raw') }}
<span class="i-lucide:external-link w-3 h-3" />
</a>
</div>
</div>
<!-- File viewer -->
<template v-if="isViewingFile && !isBinaryFile && fileContent">
<div
v-if="fileContent.markdownHtml"
v-show="markdownViewMode === 'preview'"
class="flex justify-center p-4"
>
<Readme :html="fileContent.markdownHtml.html" />
</div>
<CodeViewer
v-show="!fileContent.markdownHtml || markdownViewMode === 'code'"
:html="fileContent.html"
:lines="fileContent.lines"
:selected-lines="selectedLines"
@line-click="handleLineClick"
/>
<div class="sticky bottom-0 bg-bg border-t border-border px-4 py-1">
<div class="flex items-center gap-3 text-sm justify-end">
<span class="text-fg-muted" dir="auto">{{
$t('code.lines', { count: fileContent.lines })
}}</span>
<span v-if="currentNode?.size" class="text-fg-subtle">{{
bytesFormatter.format(currentNode.size)
}}</span>
</div>
</div>
</template>
<!-- Binary file warning -->
<div v-else-if="isViewingFile && isBinaryFile" class="py-20 text-center">
<div class="i-lucide:binary w-12 h-12 mx-auto text-fg-subtle mb-4" />
<p class="text-fg-muted mb-2">{{ $t('code.binary_file') }}</p>
<p class="text-fg-subtle text-sm mb-4">
{{
$t('code.binary_rendering_warning', {
contentType: fileContent?.contentType ?? 'unknown',
})
}}
</p>
<LinkBase
variant="button-secondary"
:to="`https://cdn.jsdelivr.net/npm/${packageName}@${version}/${filePath}`"
>
{{ $t('code.view_raw') }}
</LinkBase>
</div>
<!-- File too large warning -->
<div v-else-if="isViewingFile && isFileTooLarge" class="py-20 text-center">
<div class="i-lucide:file-text w-12 h-12 mx-auto text-fg-subtle mb-4" />
<p class="text-fg-muted mb-2">{{ $t('code.file_too_large') }}</p>
<p class="text-fg-subtle text-sm mb-4">
{{
$t('code.file_size_warning', { size: bytesFormatter.format(currentNode?.size ?? 0) })
}}
</p>
<LinkBase
variant="button-secondary"
:to="`https://cdn.jsdelivr.net/npm/${packageName}@${version}/${filePath}`"
>
{{ $t('code.view_raw') }}
</LinkBase>
</div>
<!-- Loading file content -->
<div
v-else-if="filePath && fileStatus === 'pending'"
class="flex min-h-full"
aria-busy="true"
:aria-label="$t('common.loading')"
>
<!-- Fake line numbers column -->
<div class="shrink-0 bg-bg-subtle border-ie border-border w-14 py-0">
<div v-for="n in 20" :key="n" class="px-3 h-6 flex items-center justify-end">
<SkeletonInline class="w-4 h-3 rounded-sm" />
</div>
</div>
<!-- Fake code content -->
<div class="flex-1 p-4 space-y-1.5">
<SkeletonBlock class="h-4 w-32 rounded-sm" />
<SkeletonBlock class="h-4 w-48 rounded-sm" />
<SkeletonBlock class="h-4 w-24 rounded-sm" />
<div class="h-4" />
<SkeletonBlock class="h-4 w-64 rounded-sm" />
<SkeletonBlock class="h-4 w-56 rounded-sm" />
<SkeletonBlock class="h-4 w-40 rounded-sm" />
<SkeletonBlock class="h-4 w-72 rounded-sm" />
<div class="h-4" />
<SkeletonBlock class="h-4 w-36 rounded-sm" />
<SkeletonBlock class="h-4 w-52 rounded-sm" />
<SkeletonBlock class="h-4 w-44 rounded-sm" />
<SkeletonBlock class="h-4 w-28 rounded-sm" />
<div class="h-4" />
<SkeletonBlock class="h-4 w-60 rounded-sm" />
<SkeletonBlock class="h-4 w-48 rounded-sm" />
<SkeletonBlock class="h-4 w-32 rounded-sm" />
<SkeletonBlock class="h-4 w-56 rounded-sm" />
<SkeletonBlock class="h-4 w-40 rounded-sm" />
<SkeletonBlock class="h-4 w-24 rounded-sm" />
</div>
</div>
<!-- Error loading file -->
<div v-else-if="filePath && fileStatus === 'error'" class="py-20 text-center" role="alert">
<div class="i-lucide:circle-alert w-8 h-8 mx-auto text-fg-subtle mb-4" />
<p class="text-fg-muted mb-2">{{ $t('code.failed_to_load') }}</p>
<p class="text-fg-subtle text-sm mb-4">{{ $t('code.unavailable_hint') }}</p>
<LinkBase
variant="button-secondary"
:to="`https://cdn.jsdelivr.net/npm/${packageName}@${version}/${filePath}`"
>
{{ $t('code.view_raw') }}
</LinkBase>
</div>
<!-- Directory listing (when no file selected or viewing a directory) -->
<template v-else>
<CodeDirectoryListing
:tree="fileTree.tree"
:current-path="filePath ?? ''"
:base-url="getCurrentCodeUrlWithPath()"
:base-route="route"
/>
</template>
</div>
</div>
<!-- Mobile file tree toggle -->
<ClientOnly>
<Teleport to="body">
<CodeMobileTreeDrawer
v-if="fileTree"
:tree="fileTree.tree"
:current-path="filePath ?? ''"
:base-url="getCurrentCodeUrlWithPath()"
:base-route="route"
/>
</Teleport>
</ClientOnly>
</main>
</template>