Skip to content

Commit

Permalink
basic cd pwd ls
Browse files Browse the repository at this point in the history
  • Loading branch information
soohoonc committed Dec 17, 2023
1 parent d27c55f commit 9ca9fb6
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 19 deletions.
6 changes: 2 additions & 4 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import '@/styles/globals.css';
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import { FileSystemProvider, TerminalStateProvider, ThemeProvider } from './providers';
import { ThemeProvider } from './providers';

const inter = Inter({ subsets: ['latin'] });

Expand All @@ -16,9 +16,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
<body className={inter.className}>
<main className={inter.className}>
<ThemeProvider attribute='class' defaultTheme='system' enableSystem>
<FileSystemProvider>
<TerminalStateProvider>{children}</TerminalStateProvider>
</FileSystemProvider>
{children}
</ThemeProvider>
</main>
</body>
Expand Down
7 changes: 6 additions & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { Terminal } from '@/components/terminal';
import { FileSystemProvider, TerminalStateProvider } from './providers';

export default function Home() {
return (
<div className='w-screen h-screen justify-center items-center'>
<Terminal />
<FileSystemProvider>
<TerminalStateProvider>
<Terminal />
</TerminalStateProvider>
</FileSystemProvider>
</div>
);
}
26 changes: 19 additions & 7 deletions src/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,36 @@ import { createFileSystem, type FileSystem } from '@/lib/fs';
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}
const FileSystemContext = React.createContext<FileSystem | null>(null);

const initialFileSystem = {
hello: () => 'hello',
} as FileSystem;

const FileSystemContext = React.createContext<FileSystem>(initialFileSystem)

export function useFileSystem() {
const context = React.useContext(FileSystemContext);
if (!context) {
throw new Error('useFileSystem must be used within a FileSystemProvider');
}
return context;
}

export function FileSystemProvider({ children }: { children: React.ReactNode }) {
const [initialFileSystem, setInitialFileSystem] = React.useState<FileSystem | null>(null);
const [fs, setFs] = React.useState<FileSystem>(initialFileSystem);
const [path, setPath] = React.useState<string>('');
React.useEffect(() => {
async function init() {
const fs = await createFileSystem();
console.log(fs.hello())
fs.change_dir('/users/guest')
console.log('changed dir')
console.log(fs.get_current())
setInitialFileSystem(fs);
fs.cd('/users/guest')
setPath(fs.pwd())
setFs(fs);
}
init();
}, []);
return (
<FileSystemContext.Provider value={initialFileSystem}>{children}</FileSystemContext.Provider>
<FileSystemContext.Provider value={fs}>{children}</FileSystemContext.Provider>
);
}

Expand Down
5 changes: 3 additions & 2 deletions src/components/terminal-input.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';

import { handleCommand } from '@/lib/commands';
import { useTerminalState } from '@/app/providers';
import { useTerminalState, useFileSystem } from '@/app/providers';

export const TerminalInput = React.forwardRef(({}, ref) => {
const {
Expand All @@ -16,6 +16,7 @@ export const TerminalInput = React.forwardRef(({}, ref) => {
} = useTerminalState();
const [input, setInput] = React.useState<string>('');
const inputRef = React.useRef<HTMLInputElement>(null);
const fs = useFileSystem();

React.useImperativeHandle(ref, () => ({
focus: () => {
Expand All @@ -29,7 +30,7 @@ export const TerminalInput = React.forwardRef(({}, ref) => {
const inputsLength = inputs.length;
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
const output = handleCommand(input.trim());
const output = handleCommand(input.trim(), fs);
if (!output) setShowWelcome(false);
setInputs(output ? [...inputs, input] : []);
setOutputs(output ? [...outputs, output] : []);
Expand Down
21 changes: 19 additions & 2 deletions src/lib/commands.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
'use client';

export const handleCommand = (command: string) => {
import { type FileSystem } from '@/lib/fs';

export const handleCommand = (command: string, fs: FileSystem) => {
// still better than yandere dev
const parsedCommand = command
.split(' ')
.map((item) => item.trim())
.filter((item) => item !== ' ');
switch (parsedCommand[0]) {
case 'pwd':
return <p>/users/guest</p>;
const curr_path = JSON.parse(fs.pwd());
return <p>{curr_path}</p>;
case 'ls':
const curr_ls: string[] = JSON.parse(fs.ls());
return (
<ul>
{curr_ls.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
case 'cd':
try {
fs.cd(parsedCommand[1]);
return <p></p>
} catch {
return <p>cd: no such file or directory: {parsedCommand[1]}</p>;
}
case 'touch':
case 'mkdir':
case 'rm':
Expand Down
14 changes: 11 additions & 3 deletions src/wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,15 @@ impl FileSystem {
JsValue::from_str("Hello from WASM!")
}

pub fn get_current(&self) -> String {
pub fn ls(&self) -> String {
let mut children = Vec::<String>::new();
for child in self.current.borrow().get_children() {
children.push(child.borrow().get_name());
}
serde_json::to_string(&children).unwrap()
}

pub fn pwd(&self) -> String {
// build path from root to current
let mut path = Vec::<String>::new();
let mut temp_dir = Rc::clone(&self.current);
Expand All @@ -89,7 +97,7 @@ impl FileSystem {
}

// Method to change the current directory
pub fn change_dir(&mut self, new_path: &str) -> Result<(), JsValue> {
pub fn cd(&mut self, new_path: &str) -> Result<JsValue, JsValue> {
// find the directory
// if it exists, change the current directory
// else, return an error
Expand Down Expand Up @@ -138,7 +146,7 @@ impl FileSystem {
}
}
self.current = temp_dir;
Ok(())
Ok(JsValue::from_str("Success"))
}
}

Expand Down

0 comments on commit 9ca9fb6

Please sign in to comment.