Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/components/package-port/CodeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { loadDefaultLibMap, fetchWithPackageCaching } from "@/lib/ts-lib-cache"
import { tsAutocomplete, tsFacet, tsSync } from "@valtown/codemirror-ts"
import { getLints } from "@valtown/codemirror-ts"
import { EditorView } from "codemirror"
import { useEffect, useMemo, useRef, useState } from "react"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import tsModule from "typescript"
import CodeEditorHeader, {
FileName,
Expand All @@ -52,6 +52,8 @@ import { inlineCopilot } from "codemirror-copilot"
import { useViewTsFilesDialog } from "@/components/dialogs/view-ts-files-dialog"
import { Loader2 } from "lucide-react"
import { useAxios } from "@/hooks/use-axios"
import { useToast } from "@/hooks/use-toast"
import { handleFormatFile as handleFormatFileRaw } from "@/lib/utils/handle-format-file"

const defaultImports = `
import React from "@types/react/jsx-runtime"
Expand Down Expand Up @@ -139,6 +141,11 @@ export const CodeEditor = ({
})
const { Dialog: ViewTsFilesDialog, openDialog: openViewTsFilesDialog } =
useViewTsFilesDialog()
const { toast } = useToast()

const handleFormatFile = useCallback(() => {
handleFormatFileRaw({ files, currentFile, updateFileContent, toast })
}, [currentFile, files, toast])
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

toast dep?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
}, [currentFile, files, toast])
}, [currentFile, files])


const entryPointFileName = useMemo(() => {
const entryPointFile = findTargetFile({ files, filePathFromUrl: null })
Expand Down Expand Up @@ -308,6 +315,13 @@ export const CodeEditor = ({
return true
},
},
{
key: "Shift-Alt-f",
run: () => {
handleFormatFile()
return true
},
},
]),
),
keymap.of([indentWithTab]),
Expand Down Expand Up @@ -838,6 +852,7 @@ export const CodeEditor = ({
aiAutocompleteEnabled,
setAiAutocompleteEnabled,
]}
handleFormatFile={handleFormatFile}
/>
)}
<div
Expand Down
116 changes: 25 additions & 91 deletions src/components/package-port/CodeEditorHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ interface CodeEditorHeaderProps {
isLoadingFiles: boolean
createFile: (props: ICreateFileProps) => ICreateFileResult
aiAutocompleteState: [boolean, React.Dispatch<React.SetStateAction<boolean>>]
handleFormatFile: () => void
}

export const CodeEditorHeader: React.FC<CodeEditorHeaderProps> = ({
Expand All @@ -65,6 +66,7 @@ export const CodeEditorHeader: React.FC<CodeEditorHeaderProps> = ({
entrypointFileName = "index.tsx",
createFile,
aiAutocompleteState,
handleFormatFile,
}) => {
const { Dialog: ImportComponentDialog, openDialog: openImportDialog } =
useImportComponentDialog()
Expand All @@ -80,95 +82,6 @@ export const CodeEditorHeader: React.FC<CodeEditorHeaderProps> = ({
}
}, [session?.token])

const handleFormatFile = useCallback(() => {
if (!window.prettier || !window.prettierPlugins) return
if (!currentFile) return
try {
const currentContent = files[currentFile]
let fileExtension = currentFile.split(".").pop()?.toLowerCase()
if (currentContent.trim().length === 0) {
toast({
title: "Empty file",
description: "Cannot format an empty file.",
})
return
}
if (!fileExtension) {
toast({
title: "Cannot determine file type",
description: "Unable to format file without an extension.",
})
return
}

if (["readme"].includes(currentFile.toLowerCase())) {
fileExtension = "md"
}

if (fileExtension === currentFile.toLowerCase()) {
toast({
title: "Cannot determine file type",
description: "Unable to format file without an extension.",
})
return
}

// Handle JSON formatting separately
if (fileExtension === "json") {
try {
const jsonObj = JSON.parse(currentContent)
const formattedJson = JSON.stringify(jsonObj, null, 2)
updateFileContent(currentFile, formattedJson)
} catch (jsonError) {
toast({
title: "Invalid JSON",
description: "Failed to format JSON: invalid syntax.",
variant: "destructive",
})
}
return
}

const parserMap: Record<string, string> = {
js: "babel",
jsx: "babel",
ts: "typescript",
tsx: "typescript",
md: "markdown",
markdown: "markdown",
}

const parser = parserMap[fileExtension] || "tsx"
const formattedCode = window.prettier.format(currentContent, {
semi: false,
parser: parser,
plugins: window.prettierPlugins,
})

updateFileContent(currentFile, formattedCode)
} catch (error) {
console.error("Formatting error:", error)
if (
error instanceof Error &&
error.message.includes("No parser could be inferred")
) {
toast({
title: "Unsupported File Type",
description: `Formatting not supported for .${currentFile.split(".").pop()?.toLowerCase()} files. Tried default parser.`,
})
} else {
toast({
title: "Formatting error",
description:
error instanceof Error
? error.message
: "Failed to format the code. Please check for syntax errors.",
variant: "destructive",
})
}
}
}, [currentFile, files, toast, updateFileContent])

const handleTscircuitPackageSelected = useCallback(
async ({ fullPackageName }: TscircuitPackageSelectedPayload) => {
if (!currentFile) {
Expand Down Expand Up @@ -446,8 +359,29 @@ export const CodeEditorHeader: React.FC<CodeEditorHeaderProps> = ({
<span className="hidden lg:inline">Format</span>
</Button>
</TooltipTrigger>
<TooltipContent>
<p>Format the current file</p>
<TooltipContent
sideOffset={8}
className="p-0 bg-transparent border-none shadow-none pointer-events-none"
>
<div className="ml-1 flex items-center px-2.5 py-1.5 bg-slate-900 rounded-md shadow-xl border border-slate-800/60">
<p className="pr-2">Format the current file</p>

<kbd className="bg-slate-800 px-1.5 py-0.5 rounded text-[10px] font-sans font-medium border border-slate-700 text-slate-200 leading-none">
Shift
</kbd>
<span className="text-slate-500 text-[11px] font-medium leading-none">
+
</span>
<kbd className="bg-slate-800 px-1.5 py-0.5 rounded text-[10px] font-sans font-medium border border-slate-700 text-slate-200 leading-none">
Alt
</kbd>
<span className="text-slate-500 text-[11px] font-medium leading-none">
+
</span>
<kbd className="bg-slate-800 px-1.5 py-0.5 rounded text-[10px] font-sans font-medium border border-slate-700 text-slate-200 leading-none">
F
</kbd>
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
Expand Down
99 changes: 99 additions & 0 deletions src/lib/utils/handle-format-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { ToasterToast } from "@/hooks/use-toast"
import { PackageFile } from "@/types/package"

export function handleFormatFile({
files,
currentFile,
updateFileContent,
toast,
}: {
files: PackageFile[]
currentFile: string | null
updateFileContent: (path: string, content: string) => void
toast: (toastData: ToasterToast) => string
}) {
if (!window.prettier || !window.prettierPlugins) return
if (!currentFile) return

const currentFileObj = files.find((f) => f.path === currentFile)
const currentContent = currentFileObj?.content

if (!currentContent || currentContent.trim().length === 0) {
toast({
title: "Empty file",
description: "Cannot format an empty file.",
})
return
}

let fileExtension = currentFile.split(".").pop()?.toLowerCase()

if (!fileExtension || fileExtension === currentFile.toLowerCase()) {
if (["readme"].includes(currentFile.toLowerCase())) {
fileExtension = "md"
} else {
toast({
title: "Cannot determine file type",
description: "Unable to format file without an extension.",
})
return
}
}

// Handle JSON formatting separately
if (fileExtension === "json") {
try {
const jsonObj = JSON.parse(currentContent)
const formattedJson = JSON.stringify(jsonObj, null, 2)
updateFileContent(currentFile, formattedJson)
} catch (jsonError) {
toast({
title: "Invalid JSON",
description: "Failed to format JSON: invalid syntax.",
variant: "destructive",
})
}
return
}

const parserMap: Record<string, string> = {
js: "babel",
jsx: "babel",
ts: "typescript",
tsx: "typescript",
md: "markdown",
markdown: "markdown",
}

const parser = parserMap[fileExtension] || "tsx"

try {
const formattedCode = window.prettier.format(currentContent, {
semi: false,
parser: parser,
plugins: window.prettierPlugins,
})

updateFileContent(currentFile, formattedCode)
} catch (error) {
console.error("Formatting error:", error)
if (
error instanceof Error &&
error.message.includes("No parser could be inferred")
) {
toast({
title: "Unsupported File Type",
description: `Formatting not supported for .${fileExtension} files. Tried default parser.`,
})
} else {
toast({
title: "Formatting error",
description:
error instanceof Error
? error.message
: "Failed to format the code. Please check for syntax errors.",
variant: "destructive",
})
}
}
}