Merge pull request #10 from Code-Victor/feat/ui-fixes-n-updates

Feat/UI fixes n updates
This commit is contained in:
James Murdza 2024-10-14 07:43:51 -07:00 committed by GitHub
commit 930519515c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 510 additions and 227 deletions

View File

@ -9,7 +9,7 @@ import {
DialogTrigger, DialogTrigger,
} from "@/components/ui/dialog" } from "@/components/ui/dialog"
import Image from "next/image" import Image from "next/image"
import { useState } from "react" import { useState, useCallback, useEffect, useMemo } from "react"
import { set, z } from "zod" import { set, z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
@ -34,10 +34,20 @@ import {
import { useUser } from "@clerk/nextjs" import { useUser } from "@clerk/nextjs"
import { createSandbox } from "@/lib/actions" import { createSandbox } from "@/lib/actions"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import { Loader2 } from "lucide-react" import {
Loader2,
ChevronRight,
ChevronLeft,
Search,
SlashSquare,
} from "lucide-react"
import { Button } from "../ui/button" import { Button } from "../ui/button"
import { projectTemplates } from "@/lib/data" import { projectTemplates } from "@/lib/data"
import useEmblaCarousel from "embla-carousel-react"
import type { EmblaCarouselType } from "embla-carousel"
import { WheelGesturesPlugin } from "embla-carousel-wheel-gestures"
import { cn } from "@/lib/utils"
const formSchema = z.object({ const formSchema = z.object({
name: z name: z
.string() .string()
@ -57,11 +67,20 @@ export default function NewProjectModal({
open: boolean open: boolean
setOpen: (open: boolean) => void setOpen: (open: boolean) => void
}) { }) {
const router = useRouter()
const user = useUser()
const [selected, setSelected] = useState("reactjs") const [selected, setSelected] = useState("reactjs")
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const router = useRouter() const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false }, [
WheelGesturesPlugin(),
const user = useUser() ])
const {
prevBtnDisabled,
nextBtnDisabled,
onPrevButtonClick,
onNextButtonClick,
} = usePrevNextButtons(emblaApi)
const [search, setSearch] = useState("")
const form = useForm<z.infer<typeof formSchema>>({ const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema),
@ -71,6 +90,26 @@ export default function NewProjectModal({
}, },
}) })
const handleTemplateClick = useCallback(
({ id, index }: { id: string; index: number }) => {
setSelected(id)
emblaApi?.scrollTo(index)
},
[emblaApi]
)
const filteredTemplates = useMemo(
() =>
projectTemplates.filter(
(item) =>
item.name.toLowerCase().includes(search.toLowerCase()) ||
item.description.toLowerCase().includes(search.toLowerCase())
),
[search, projectTemplates]
)
const emptyTemplates = useMemo(
() => filteredTemplates.length === 0,
[filteredTemplates]
)
async function onSubmit(values: z.infer<typeof formSchema>) { async function onSubmit(values: z.infer<typeof formSchema>) {
if (!user.isSignedIn) return if (!user.isSignedIn) return
@ -80,7 +119,6 @@ export default function NewProjectModal({
const id = await createSandbox(sandboxData) const id = await createSandbox(sandboxData)
router.push(`/code/${id}`) router.push(`/code/${id}`)
} }
return ( return (
<Dialog <Dialog
open={open} open={open}
@ -92,25 +130,89 @@ export default function NewProjectModal({
<DialogHeader> <DialogHeader>
<DialogTitle>Create A Sandbox</DialogTitle> <DialogTitle>Create A Sandbox</DialogTitle>
</DialogHeader> </DialogHeader>
<div className="grid grid-cols-2 w-full gap-2 mt-2"> <div className="flex flex-col gap-2 max-w-full overflow-hidden">
{projectTemplates.map((item) => ( <div className="flex items-center justify-end">
<SearchInput
{...{
value: search,
onValueChange: setSearch,
}}
/>
</div>
<div className="overflow-hidden relative" ref={emblaRef}>
<div
className={cn(
"grid grid-flow-col gap-x-2 min-h-[97px]",
emptyTemplates ? "auto-cols-[100%]" : "auto-cols-[200px]"
)}
>
{filteredTemplates.map((item, i) => (
<button <button
disabled={item.disabled || loading} disabled={item.disabled || loading}
key={item.id} key={item.id}
onClick={() => setSelected(item.id)} onClick={handleTemplateClick.bind(null, {
className={`${ id: item.id,
selected === item.id ? "border-foreground" : "border-border" index: i,
} rounded-md border bg-card text-card-foreground shadow text-left p-4 flex flex-col transition-all focus-visible:outline-none focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 disabled:cursor-not-allowed`} })}
className={cn(
selected === item.id
? "shadow-foreground"
: "shadow-border",
"shadow-[0_0_0_1px_inset] rounded-md border bg-card text-card-foreground text-left p-4 flex flex-col transition-all focus-visible:outline-none focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 disabled:cursor-not-allowed"
)}
> >
<div className="space-x-2 flex items-center justify-start w-full"> <div className="space-x-2 flex items-center justify-start w-full">
<Image alt="" src={item.icon} width={20} height={20} /> <Image alt="" src={item.icon} width={20} height={20} />
<div className="font-medium">{item.name}</div> <div className="font-medium">{item.name}</div>
</div> </div>
<div className="mt-2 text-muted-foreground text-sm"> <div className="mt-2 text-muted-foreground text-xs line-clamp-2">
{item.description} {item.description}
</div> </div>
</button> </button>
))} ))}
{emptyTemplates && (
<div className="flex flex-col gap-2 items-center text-center justify-center text-muted-foreground text-sm">
<p>No templates found</p>
<Button size="xs" asChild>
<a
href="https://github.com/jamesmurdza/sandbox"
target="_blank"
>
Contribute
</a>
</Button>
</div>
)}
</div>
<div
className={cn(
"absolute transition-all opacity-100 duration-400 bg-gradient-to-r from-background via-background to-transparent w-14 pl-1 left-0 top-0 -translate-x-1 bottom-0 h-full flex items-center",
prevBtnDisabled && "opacity-0 pointer-events-none"
)}
>
<Button
size="smIcon"
className="rounded-full"
onClick={onPrevButtonClick}
>
<ChevronLeft className="size-5" />
</Button>
</div>
<div
className={cn(
"absolute transition-all opacity-100 duration-400 bg-gradient-to-l from-background via-background to-transparent w-14 pl-1 right-0 top-0 translate-x-1 bottom-0 h-full flex items-center",
nextBtnDisabled && "opacity-0 pointer-events-none"
)}
>
<Button
size="smIcon"
className="rounded-full"
onClick={onNextButtonClick}
>
<ChevronRight className="size-5" />
</Button>
</div>
</div>
</div> </div>
<Form {...form}> <Form {...form}>
@ -178,3 +280,68 @@ export default function NewProjectModal({
</Dialog> </Dialog>
) )
} }
function SearchInput({
value,
onValueChange,
}: {
value?: string
onValueChange?: (value: string) => void
}) {
const onSubmit = useCallback((e: React.FormEvent) => {
e.preventDefault()
console.log("searching")
}, [])
return (
<form {...{ onSubmit }} className="w-40 h-8 ">
<label
htmlFor="template-search"
className="flex gap-2 rounded-sm transition-colors bg-[#2e2e2e] border border-[--s-color] [--s-color:hsl(var(--muted-foreground))] focus-within:[--s-color:#fff] h-full items-center px-2"
>
<Search className="size-4 text-[--s-color] transition-colors" />
<input
id="template-search"
type="text"
name="search"
placeholder="Search templates"
value={value}
onChange={(e) => onValueChange?.(e.target.value)}
className="bg-transparent placeholder:text-muted-foreground text-white w-full focus:outline-none text-xs"
/>
</label>
</form>
)
}
const usePrevNextButtons = (emblaApi: EmblaCarouselType | undefined) => {
const [prevBtnDisabled, setPrevBtnDisabled] = useState(true)
const [nextBtnDisabled, setNextBtnDisabled] = useState(true)
const onPrevButtonClick = useCallback(() => {
if (!emblaApi) return
emblaApi.scrollPrev()
}, [emblaApi])
const onNextButtonClick = useCallback(() => {
if (!emblaApi) return
emblaApi.scrollNext()
}, [emblaApi])
const onSelect = useCallback((emblaApi: EmblaCarouselType) => {
setPrevBtnDisabled(!emblaApi.canScrollPrev())
setNextBtnDisabled(!emblaApi.canScrollNext())
}, [])
useEffect(() => {
if (!emblaApi) return
onSelect(emblaApi)
emblaApi.on("reInit", onSelect).on("select", onSelect)
}, [emblaApi, onSelect])
return {
prevBtnDisabled,
nextBtnDisabled,
onPrevButtonClick,
onNextButtonClick,
}
}

View File

@ -36,7 +36,7 @@ import { useSocket } from "@/context/SocketContext"
import { Button } from "../ui/button" import { Button } from "../ui/button"
import React from "react" import React from "react"
import { parseTSConfigToMonacoOptions } from "@/lib/tsconfig" import { parseTSConfigToMonacoOptions } from "@/lib/tsconfig"
import { deepMerge } from "@/lib/utils" import { cn, deepMerge } from "@/lib/utils"
export default function CodeEditor({ export default function CodeEditor({
userData, userData,
@ -62,9 +62,9 @@ export default function CodeEditor({
// This heartbeat is critical to preventing the E2B sandbox from timing out // This heartbeat is critical to preventing the E2B sandbox from timing out
useEffect(() => { useEffect(() => {
// 10000 ms = 10 seconds // 10000 ms = 10 seconds
const interval = setInterval(() => socket?.emit("heartbeat"), 10000); const interval = setInterval(() => socket?.emit("heartbeat"), 10000)
return () => clearInterval(interval); return () => clearInterval(interval)
}, [socket]); }, [socket])
//Preview Button state //Preview Button state
const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true) const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true)
@ -80,7 +80,7 @@ export default function CodeEditor({
const [activeFileContent, setActiveFileContent] = useState("") const [activeFileContent, setActiveFileContent] = useState("")
const [deletingFolderId, setDeletingFolderId] = useState("") const [deletingFolderId, setDeletingFolderId] = useState("")
// Added this state to track the most recent content for each file // Added this state to track the most recent content for each file
const [fileContents, setFileContents] = useState<Record<string, string>>({}); const [fileContents, setFileContents] = useState<Record<string, string>>({})
// Editor state // Editor state
const [editorLanguage, setEditorLanguage] = useState("plaintext") const [editorLanguage, setEditorLanguage] = useState("plaintext")
@ -462,16 +462,17 @@ export default function CodeEditor({
const model = editorRef?.getModel() const model = editorRef?.getModel()
// added this because it was giving client side exception - Illegal value for lineNumber when opening an empty file // added this because it was giving client side exception - Illegal value for lineNumber when opening an empty file
if (model) { if (model) {
const totalLines = model.getLineCount(); const totalLines = model.getLineCount()
// Check if the cursorLine is a valid number, If cursorLine is out of bounds, we fall back to 1 (the first line) as a default safe value. // Check if the cursorLine is a valid number, If cursorLine is out of bounds, we fall back to 1 (the first line) as a default safe value.
const lineNumber = cursorLine > 0 && cursorLine <= totalLines ? cursorLine : 1; // fallback to a valid line number const lineNumber =
cursorLine > 0 && cursorLine <= totalLines ? cursorLine : 1 // fallback to a valid line number
// If for some reason the content doesn't exist, we use an empty string as a fallback. // If for some reason the content doesn't exist, we use an empty string as a fallback.
const line = model.getLineContent(lineNumber) ?? ""; const line = model.getLineContent(lineNumber) ?? ""
// Check if the line is not empty or only whitespace (i.e., `.trim()` removes spaces). // Check if the line is not empty or only whitespace (i.e., `.trim()` removes spaces).
// If the line has content, we clear any decorations using the instance of the `decorations` object. // If the line has content, we clear any decorations using the instance of the `decorations` object.
// Decorations refer to editor highlights, underlines, or markers, so this clears those if conditions are met. // Decorations refer to editor highlights, underlines, or markers, so this clears those if conditions are met.
if (line.trim() !== "") { if (line.trim() !== "") {
decorations.instance?.clear(); decorations.instance?.clear()
return return
} }
} }
@ -497,28 +498,28 @@ export default function CodeEditor({
debounce((activeFileId: string | undefined) => { debounce((activeFileId: string | undefined) => {
if (activeFileId) { if (activeFileId) {
// Get the current content of the file // Get the current content of the file
const content = fileContents[activeFileId]; const content = fileContents[activeFileId]
// Mark the file as saved in the tabs // Mark the file as saved in the tabs
setTabs((prev) => setTabs((prev) =>
prev.map((tab) => prev.map((tab) =>
tab.id === activeFileId ? { ...tab, saved: true } : tab tab.id === activeFileId ? { ...tab, saved: true } : tab
) )
); )
console.log(`Saving file...${activeFileId}`); console.log(`Saving file...${activeFileId}`)
console.log(`Saving file...${content}`); console.log(`Saving file...${content}`)
socket?.emit("saveFile", activeFileId, content); socket?.emit("saveFile", activeFileId, content)
} }
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000), }, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000),
[socket, fileContents] [socket, fileContents]
); )
// Keydown event listener to trigger file save on Ctrl+S or Cmd+S // Keydown event listener to trigger file save on Ctrl+S or Cmd+S
useEffect(() => { useEffect(() => {
const down = (e: KeyboardEvent) => { const down = (e: KeyboardEvent) => {
if (e.key === "s" && (e.metaKey || e.ctrlKey)) { if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
e.preventDefault() e.preventDefault()
debouncedSaveData(activeFileId); debouncedSaveData(activeFileId)
} }
} }
document.addEventListener("keydown", down) document.addEventListener("keydown", down)
@ -615,7 +616,7 @@ export default function CodeEditor({
// Socket event listener effect // Socket event listener effect
useEffect(() => { useEffect(() => {
const onConnect = () => { } const onConnect = () => {}
const onDisconnect = () => { const onDisconnect = () => {
setTerminals([]) setTerminals([])
@ -685,46 +686,49 @@ export default function CodeEditor({
} // 300ms debounce delay, adjust as needed } // 300ms debounce delay, adjust as needed
const selectFile = (tab: TTab) => { const selectFile = (tab: TTab) => {
if (tab.id === activeFileId) return; if (tab.id === activeFileId) return
setGenerate((prev) => ({ ...prev, show: false })); setGenerate((prev) => ({ ...prev, show: false }))
// Check if the tab already exists in the list of open tabs // Check if the tab already exists in the list of open tabs
const exists = tabs.find((t) => t.id === tab.id); const exists = tabs.find((t) => t.id === tab.id)
setTabs((prev) => { setTabs((prev) => {
if (exists) { if (exists) {
// If the tab exists, make it the active tab // If the tab exists, make it the active tab
setActiveFileId(exists.id); setActiveFileId(exists.id)
return prev; return prev
} }
// If the tab doesn't exist, add it to the list of tabs and make it active // If the tab doesn't exist, add it to the list of tabs and make it active
return [...prev, tab]; return [...prev, tab]
}); })
// If the file's content is already cached, set it as the active content // If the file's content is already cached, set it as the active content
if (fileContents[tab.id]) { if (fileContents[tab.id]) {
setActiveFileContent(fileContents[tab.id]); setActiveFileContent(fileContents[tab.id])
} else { } else {
// Otherwise, fetch the content of the file and cache it // Otherwise, fetch the content of the file and cache it
debouncedGetFile(tab.id, (response: string) => { debouncedGetFile(tab.id, (response: string) => {
setFileContents(prev => ({ ...prev, [tab.id]: response })); setFileContents((prev) => ({ ...prev, [tab.id]: response }))
setActiveFileContent(response); setActiveFileContent(response)
}); })
} }
// Set the editor language based on the file type // Set the editor language based on the file type
setEditorLanguage(processFileType(tab.name)); setEditorLanguage(processFileType(tab.name))
// Set the active file ID to the new tab // Set the active file ID to the new tab
setActiveFileId(tab.id); setActiveFileId(tab.id)
}; }
// Added this effect to update fileContents when the editor content changes // Added this effect to update fileContents when the editor content changes
useEffect(() => { useEffect(() => {
if (activeFileId) { if (activeFileId) {
// Cache the current active file content using the file ID as the key // Cache the current active file content using the file ID as the key
setFileContents(prev => ({ ...prev, [activeFileId]: activeFileContent })); setFileContents((prev) => ({
...prev,
[activeFileId]: activeFileContent,
}))
} }
}, [activeFileContent, activeFileId]); }, [activeFileContent, activeFileId])
// Close tab and remove from tabs // Close tab and remove from tabs
const closeTab = (id: string) => { const closeTab = (id: string) => {
@ -834,7 +838,7 @@ export default function CodeEditor({
<DisableAccessModal <DisableAccessModal
message={disableAccess.message} message={disableAccess.message}
open={disableAccess.isDisabled} open={disableAccess.isDisabled}
setOpen={() => { }} setOpen={() => {}}
/> />
<Loading /> <Loading />
</> </>
@ -862,7 +866,10 @@ export default function CodeEditor({
)} )}
</AnimatePresence> </AnimatePresence>
</div> </div>
<div className="z-50 p-1" ref={generateWidgetRef}> <div
className={cn(generate.show && "z-50 p-1")}
ref={generateWidgetRef}
>
{generate.show ? ( {generate.show ? (
<GenerateInput <GenerateInput
user={userData} user={userData}
@ -1012,7 +1019,7 @@ export default function CodeEditor({
onChange={(value) => { onChange={(value) => {
// If the new content is different from the cached content, update it // If the new content is different from the cached content, update it
if (value !== fileContents[activeFileId]) { if (value !== fileContents[activeFileId]) {
setActiveFileContent(value ?? ""); // Update the active file content setActiveFileContent(value ?? "") // Update the active file content
// Mark the file as unsaved by setting 'saved' to false // Mark the file as unsaved by setting 'saved' to false
setTabs((prev) => setTabs((prev) =>
prev.map((tab) => prev.map((tab) =>

View File

@ -84,8 +84,10 @@ export default function Loading({
</div> </div>
</div> </div>
<div className="w-full mt-1 flex flex-col"> <div className="w-full mt-1 flex flex-col">
<div className="w-full flex justify-center"> <div className="w-full flex flex-col justify-center">
<Loader2 className="w-4 h-4 animate-spin" /> {new Array(6).fill(0).map((_, i) => (
<Skeleton key={i} className="h-[1.625rem] mb-0.5 rounded-sm" />
))}
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,4 +1,4 @@
"use client"; "use client"
import { import {
FilePlus, FilePlus,
@ -7,20 +7,22 @@ import {
MonitorPlay, MonitorPlay,
Search, Search,
Sparkles, Sparkles,
} from "lucide-react"; } from "lucide-react"
import SidebarFile from "./file"; import SidebarFile from "./file"
import SidebarFolder from "./folder"; import SidebarFolder from "./folder"
import { Sandbox, TFile, TFolder, TTab } from "@/lib/types"; import { Sandbox, TFile, TFolder, TTab } from "@/lib/types"
import { useEffect, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react"
import New from "./new"; import New from "./new"
import { Socket } from "socket.io-client"; import { Socket } from "socket.io-client"
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch"
import { import {
dropTargetForElements, dropTargetForElements,
monitorForElements, monitorForElements,
} from "@atlaskit/pragmatic-drag-and-drop/element/adapter"; } from "@atlaskit/pragmatic-drag-and-drop/element/adapter"
import Button from "@/components/ui/customButton"; import Button from "@/components/ui/customButton"
import { Skeleton } from "@/components/ui/skeleton"
import { sortFileExplorer } from "@/lib/utils"
export default function Sidebar({ export default function Sidebar({
sandboxData, sandboxData,
@ -34,75 +36,75 @@ export default function Sidebar({
addNew, addNew,
deletingFolderId, deletingFolderId,
}: { }: {
sandboxData: Sandbox; sandboxData: Sandbox
files: (TFile | TFolder)[]; files: (TFile | TFolder)[]
selectFile: (tab: TTab) => void; selectFile: (tab: TTab) => void
handleRename: ( handleRename: (
id: string, id: string,
newName: string, newName: string,
oldName: string, oldName: string,
type: "file" | "folder" type: "file" | "folder"
) => boolean; ) => boolean
handleDeleteFile: (file: TFile) => void; handleDeleteFile: (file: TFile) => void
handleDeleteFolder: (folder: TFolder) => void; handleDeleteFolder: (folder: TFolder) => void
socket: Socket; socket: Socket
setFiles: (files: (TFile | TFolder)[]) => void; setFiles: (files: (TFile | TFolder)[]) => void
addNew: (name: string, type: "file" | "folder") => void; addNew: (name: string, type: "file" | "folder") => void
deletingFolderId: string; deletingFolderId: string
}) { }) {
const ref = useRef(null); // drop target const ref = useRef(null) // drop target
const [creatingNew, setCreatingNew] = useState<"file" | "folder" | null>(
null
);
const [movingId, setMovingId] = useState("");
const [creatingNew, setCreatingNew] = useState<"file" | "folder" | null>(null)
const [movingId, setMovingId] = useState("")
const sortedFiles = useMemo(() => {
return sortFileExplorer(files)
}, [files])
useEffect(() => { useEffect(() => {
const el = ref.current; const el = ref.current
if (el) { if (el) {
return dropTargetForElements({ return dropTargetForElements({
element: el, element: el,
getData: () => ({ id: `projects/${sandboxData.id}` }), getData: () => ({ id: `projects/${sandboxData.id}` }),
canDrop: ({ source }) => { canDrop: ({ source }) => {
const file = files.find((child) => child.id === source.data.id); const file = files.find((child) => child.id === source.data.id)
return !file; return !file
}, },
}); })
} }
}, [files]); }, [files])
useEffect(() => { useEffect(() => {
return monitorForElements({ return monitorForElements({
onDrop({ source, location }) { onDrop({ source, location }) {
const destination = location.current.dropTargets[0]; const destination = location.current.dropTargets[0]
if (!destination) { if (!destination) {
return; return
} }
const fileId = source.data.id as string; const fileId = source.data.id as string
const folderId = destination.data.id as string; const folderId = destination.data.id as string
const fileFolder = fileId.split("/").slice(0, -1).join("/"); const fileFolder = fileId.split("/").slice(0, -1).join("/")
if (fileFolder === folderId) { if (fileFolder === folderId) {
return; return
} }
console.log("move file", fileId, "to folder", folderId); console.log("move file", fileId, "to folder", folderId)
setMovingId(fileId); setMovingId(fileId)
socket.emit( socket.emit(
"moveFile", "moveFile",
fileId, fileId,
folderId, folderId,
(response: (TFolder | TFile)[]) => { (response: (TFolder | TFile)[]) => {
setFiles(response); setFiles(response)
setMovingId(""); setMovingId("")
} }
); )
}, },
}); })
}, []); }, [])
return ( return (
<div className="h-full w-56 select-none flex flex-col text-sm items-start justify-between p-2"> <div className="h-full w-56 select-none flex flex-col text-sm items-start justify-between p-2">
@ -137,13 +139,15 @@ export default function Sidebar({
isDraggedOver ? "bg-secondary/50" : "" isDraggedOver ? "bg-secondary/50" : ""
} rounded-sm w-full mt-1 flex flex-col`} } rounded-sm w-full mt-1 flex flex-col`}
> */} > */}
{files.length === 0 ? ( {sortedFiles.length === 0 ? (
<div className="w-full flex justify-center"> <div className="w-full flex flex-col justify-center">
<Loader2 className="w-4 h-4 animate-spin" /> {new Array(6).fill(0).map((_, i) => (
<Skeleton key={i} className="h-[1.625rem] mb-0.5 rounded-sm" />
))}
</div> </div>
) : ( ) : (
<> <>
{files.map((child) => {sortedFiles.map((child) =>
child.type === "file" ? ( child.type === "file" ? (
<SidebarFile <SidebarFile
key={child.id} key={child.id}
@ -172,7 +176,7 @@ export default function Sidebar({
socket={socket} socket={socket}
type={creatingNew} type={creatingNew}
stopEditing={() => { stopEditing={() => {
setCreatingNew(null); setCreatingNew(null)
}} }}
addNew={addNew} addNew={addNew}
/> />
@ -187,5 +191,5 @@ export default function Sidebar({
</Button> */} </Button> */}
</div> </div>
</div> </div>
); )
} }

View File

@ -1,12 +1,13 @@
"use client"; "use client"
import { Terminal } from "@xterm/xterm"; import { Terminal } from "@xterm/xterm"
import { FitAddon } from "@xterm/addon-fit"; import { FitAddon } from "@xterm/addon-fit"
import "./xterm.css"; import "./xterm.css"
import { useEffect, useRef, useState } from "react"; import { ElementRef, useEffect, useRef, useState } from "react"
import { Socket } from "socket.io-client"; import { Socket } from "socket.io-client"
import { Loader2 } from "lucide-react"; import { Loader2 } from "lucide-react"
import { debounce } from "@/lib/utils"
export default function EditorTerminal({ export default function EditorTerminal({
socket, socket,
@ -15,16 +16,17 @@ export default function EditorTerminal({
setTerm, setTerm,
visible, visible,
}: { }: {
socket: Socket; socket: Socket
id: string; id: string
term: Terminal | null; term: Terminal | null
setTerm: (term: Terminal) => void; setTerm: (term: Terminal) => void
visible: boolean; visible: boolean
}) { }) {
const terminalRef = useRef(null); const terminalRef = useRef<ElementRef<"div">>(null)
const fitAddonRef = useRef<FitAddon | null>(null)
useEffect(() => { useEffect(() => {
if (!terminalRef.current) return; if (!terminalRef.current) return
// console.log("new terminal", id, term ? "reusing" : "creating"); // console.log("new terminal", id, term ? "reusing" : "creating");
const terminal = new Terminal({ const terminal = new Terminal({
@ -36,56 +38,80 @@ export default function EditorTerminal({
fontSize: 14, fontSize: 14,
lineHeight: 1.5, lineHeight: 1.5,
letterSpacing: 0, letterSpacing: 0,
}); })
setTerm(terminal); setTerm(terminal)
const dispose = () => {
return () => { terminal.dispose()
if (terminal) terminal.dispose(); }
}; return dispose
}, []); }, [])
useEffect(() => { useEffect(() => {
if (!term) return; if (!term) return
if (!terminalRef.current) return; if (!terminalRef.current) return
const fitAddon = new FitAddon(); if (!fitAddonRef.current) {
term.loadAddon(fitAddon); const fitAddon = new FitAddon()
term.open(terminalRef.current); term.loadAddon(fitAddon)
fitAddon.fit(); term.open(terminalRef.current)
fitAddon.fit()
fitAddonRef.current = fitAddon
}
const disposableOnData = term.onData((data) => { const disposableOnData = term.onData((data) => {
socket.emit("terminalData", id, data); socket.emit("terminalData", id, data)
}); })
const disposableOnResize = term.onResize((dimensions) => { const disposableOnResize = term.onResize((dimensions) => {
// const terminal_size = { fitAddonRef.current?.fit()
// width: dimensions.cols, socket.emit("terminalResize", dimensions)
// height: dimensions.rows, })
// }; const resizeObserver = new ResizeObserver(
fitAddon.fit(); debounce((entries) => {
socket.emit("terminalResize", dimensions); if (!fitAddonRef.current || !terminalRef.current) return
});
const entry = entries[0]
if (!entry) return
const { width, height } = entry.contentRect
// Only call fit if the size has actually changed
if (
width !== terminalRef.current.offsetWidth ||
height !== terminalRef.current.offsetHeight
) {
try {
fitAddonRef.current.fit()
} catch (err) {
console.error("Error during fit:", err)
}
}
}, 50) // Debounce for 50ms
)
// start observing for resize
resizeObserver.observe(terminalRef.current)
return () => { return () => {
disposableOnData.dispose(); disposableOnData.dispose()
disposableOnResize.dispose(); disposableOnResize.dispose()
}; resizeObserver.disconnect()
}, [term, terminalRef.current]); }
}, [term, terminalRef.current])
useEffect(() => { useEffect(() => {
if (!term) return; if (!term) return
const handleTerminalResponse = (response: { id: string; data: string }) => { const handleTerminalResponse = (response: { id: string; data: string }) => {
if (response.id === id) { if (response.id === id) {
term.write(response.data); term.write(response.data)
} }
}; }
socket.on("terminalResponse", handleTerminalResponse); socket.on("terminalResponse", handleTerminalResponse)
return () => { return () => {
socket.off("terminalResponse", handleTerminalResponse); socket.off("terminalResponse", handleTerminalResponse)
}; }
}, [term, id, socket]); }, [term, id, socket])
return ( return (
<> <>
@ -102,5 +128,5 @@ export default function EditorTerminal({
) : null} ) : null}
</div> </div>
</> </>
); )
} }

View File

@ -22,15 +22,15 @@ export const projectTemplates: {
{ {
id: "nextjs", id: "nextjs",
name: "NextJS", name: "NextJS",
icon: "/project-icons/node.svg", icon: "/project-icons/next-js.svg",
description: "A JavaScript runtime built on the V8 JavaScript engine", description: "a React framework for building full-stack web applications",
disabled: false, disabled: false,
}, },
{ {
id: "streamlit", id: "streamlit",
name: "Streamlit", name: "Streamlit",
icon: "/project-icons/python.svg", icon: "/project-icons/python.svg",
description: "A JavaScript runtime built on the V8 JavaScript engine", description: "A faster way to build and share data apps",
disabled: false, disabled: false,
}, },
] ]

View File

@ -98,3 +98,28 @@ export const deepMerge = (target: any, source: any) => {
const isObject = (item: any) => { const isObject = (item: any) => {
return item && typeof item === "object" && !Array.isArray(item) return item && typeof item === "object" && !Array.isArray(item)
} }
export function sortFileExplorer(
items: (TFile | TFolder)[]
): (TFile | TFolder)[] {
return items
.sort((a, b) => {
// First, sort by type (folders before files)
if (a.type !== b.type) {
return a.type === "folder" ? -1 : 1
}
// Then, sort alphabetically by name
return a.name.localeCompare(b.name, undefined, { sensitivity: "base" })
})
.map((item) => {
// If it's a folder, recursively sort its children
if (item.type === "folder") {
return {
...item,
children: sortFileExplorer(item.children),
}
}
return item
})
}

View File

@ -34,6 +34,8 @@
"@xterm/xterm": "^5.5.0", "@xterm/xterm": "^5.5.0",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"embla-carousel-react": "^8.3.0",
"embla-carousel-wheel-gestures": "^8.0.1",
"framer-motion": "^11.2.3", "framer-motion": "^11.2.3",
"fs": "^0.0.1-security", "fs": "^0.0.1-security",
"geist": "^1.3.0", "geist": "^1.3.0",
@ -2690,6 +2692,45 @@
"integrity": "sha512-w+9yAVHoHhysCa+gln7AzbO9CdjFcL/wN/5dd+XW/Msl2d/4+WisEaCF1nty0xbAKaxdaJfgLB2296U7zZB7BA==", "integrity": "sha512-w+9yAVHoHhysCa+gln7AzbO9CdjFcL/wN/5dd+XW/Msl2d/4+WisEaCF1nty0xbAKaxdaJfgLB2296U7zZB7BA==",
"dev": true "dev": true
}, },
"node_modules/embla-carousel": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.3.0.tgz",
"integrity": "sha512-Ve8dhI4w28qBqR8J+aMtv7rLK89r1ZA5HocwFz6uMB/i5EiC7bGI7y+AM80yAVUJw3qqaZYK7clmZMUR8kM3UA=="
},
"node_modules/embla-carousel-react": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/embla-carousel-react/-/embla-carousel-react-8.3.0.tgz",
"integrity": "sha512-P1FlinFDcIvggcErRjNuVqnUR8anyo8vLMIH8Rthgofw7Nj8qTguCa2QjFAbzxAUTQTPNNjNL7yt0BGGinVdFw==",
"dependencies": {
"embla-carousel": "8.3.0",
"embla-carousel-reactive-utils": "8.3.0"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.1 || ^18.0.0"
}
},
"node_modules/embla-carousel-reactive-utils": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/embla-carousel-reactive-utils/-/embla-carousel-reactive-utils-8.3.0.tgz",
"integrity": "sha512-EYdhhJ302SC4Lmkx8GRsp0sjUhEN4WyFXPOk0kGu9OXZSRMmcBlRgTvHcq8eKJE1bXWBsOi1T83B+BSSVZSmwQ==",
"peerDependencies": {
"embla-carousel": "8.3.0"
}
},
"node_modules/embla-carousel-wheel-gestures": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/embla-carousel-wheel-gestures/-/embla-carousel-wheel-gestures-8.0.1.tgz",
"integrity": "sha512-LMAnruDqDmsjL6UoQD65aLotpmfO49Fsr3H0bMi7I+BH6jbv9OJiE61kN56daKsVtCQEt0SU1MrJslbhtgF3yQ==",
"dependencies": {
"wheel-gestures": "^2.2.5"
},
"engines": {
"node": ">=10"
},
"peerDependencies": {
"embla-carousel": "^8.0.0 || ~8.0.0-rc03"
}
},
"node_modules/emoji-regex": { "node_modules/emoji-regex": {
"version": "9.2.2", "version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
@ -4553,6 +4594,14 @@
"webidl-conversions": "^3.0.0" "webidl-conversions": "^3.0.0"
} }
}, },
"node_modules/wheel-gestures": {
"version": "2.2.48",
"resolved": "https://registry.npmjs.org/wheel-gestures/-/wheel-gestures-2.2.48.tgz",
"integrity": "sha512-f+Gy33Oa5Z14XY9679Zze+7VFhbsQfBFXodnU2x589l4kxGM9L5Y8zETTmcMR5pWOPQyRv4Z0lNax6xCO0NSlA==",
"engines": {
"node": ">=18"
}
},
"node_modules/which": { "node_modules/which": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",

View File

@ -35,6 +35,8 @@
"@xterm/xterm": "^5.5.0", "@xterm/xterm": "^5.5.0",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"embla-carousel-react": "^8.3.0",
"embla-carousel-wheel-gestures": "^8.0.1",
"framer-motion": "^11.2.3", "framer-motion": "^11.2.3",
"fs": "^0.0.1-security", "fs": "^0.0.1-security",
"geist": "^1.3.0", "geist": "^1.3.0",

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="255" height="255" fill="none"><g clip-path="url(#a)"><rect width="255" height="255" fill="#fff" rx="127.5"/><g clip-path="url(#b)"><path fill="#000" d="M119.084-.93c-.553.05-2.311.225-3.894.35-36.502 3.291-70.694 22.984-92.349 53.252C10.782 69.502 3.07 88.592.156 108.812-.874 115.87-1 117.955-1 127.525s.126 11.655 1.156 18.713c6.984 48.253 41.326 88.794 87.902 103.815 8.34 2.688 17.133 4.522 27.132 5.627 3.894.427 20.726.427 24.62 0 17.259-1.909 31.88-6.179 46.3-13.539 2.211-1.13 2.638-1.432 2.336-1.683-.201-.151-9.621-12.785-20.926-28.057l-20.55-27.756-25.751-38.105c-14.168-20.949-25.825-38.08-25.926-38.08-.1-.025-.2 16.905-.25 37.577-.076 36.196-.101 37.653-.554 38.507-.653 1.231-1.155 1.733-2.21 2.286-.804.402-1.508.477-5.301.477h-4.346l-1.156-.728a4.692 4.692 0 0 1-1.683-1.834l-.528-1.13.05-50.363.076-50.388.779-.98c.402-.527 1.256-1.205 1.859-1.531 1.03-.503 1.432-.553 5.778-.553 5.125 0 5.979.201 7.31 1.658.377.402 14.32 21.401 31.001 46.695s39.492 59.832 50.697 76.787l20.349 30.821 1.03-.678c9.119-5.928 18.766-14.368 26.403-23.16 16.254-18.663 26.73-41.42 30.247-65.685 1.03-7.058 1.156-9.143 1.156-18.713s-.126-11.655-1.156-18.713c-6.984-48.253-41.326-88.794-87.902-103.815-8.215-2.662-16.958-4.496-26.755-5.601-2.412-.251-19.018-.528-21.103-.327Zm52.606 77.716c1.206.603 2.186 1.758 2.537 2.964.201.653.251 14.619.201 46.092l-.075 45.163-7.964-12.207-7.989-12.208v-32.83c0-21.225.101-33.156.252-33.734.401-1.407 1.281-2.512 2.487-3.165 1.03-.527 1.406-.578 5.351-.578 3.718 0 4.371.05 5.2.503Z"/></g></g><defs><clipPath id="a"><rect width="255" height="255" fill="#fff" rx="127.5"/></clipPath><clipPath id="b"><path fill="#fff" d="M-1-1h257v257H-1z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB