Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to update prompt with useState hook? How to call the an environment variable from my function? Thanks for looking at my code. #32

Open
shaenr opened this issue Aug 22, 2021 · 0 comments

Comments

@shaenr
Copy link

shaenr commented Aug 22, 2021

Two related problems:

  1. How to update prompt with useState hook?
    I need to be able to run setPromptText() somewhere to update the prompt, but... I don't know how since the component doesn't have such a function to do that and I don't know how to extend it if its not a class.

  2. How to call the an environment variable from my function?
    Look at the buildPrompt function and see the comment where I point out my failing attempt to get the cwd from environment variables in state.

This is my code

import React, { useState } from 'react';

import ReactTerminalStateless, { 
  ReactOutputRenderers 
} from 'react-terminal-component';

import { 
  EmulatorState, 
  getEnvironmentVariable 
} from 'javascript-terminal';

import myTheme from './myTheme';
import Level from './levels/level1/index';

import "./app.css";

// Define Emulator State From Modules
const emulatorState = EmulatorState.create({
  'fs': Level.FS,
  'outputs': Level.Output,
  'history': Level.History,
  'environmentVariables': Level.Env,
  'commandMapping': Level.Commands,
})

const buildPrompt = (state) => {
  const headDelim = "┌──("
  const user = Level.Data.user
  const atChar = "@"
  const host = Level.Data.hostname
  const pathDelim = ")-["

// NOTE: This results in TypeError: Object(...) is not a function so Im not doing this right either.
  const cwd = getEnvironmentVariable(state.getEnvVariables(), 'cwd')        


  const tailDelim = "]\n└─$ "
  return headDelim + user + atChar + host + pathDelim + cwd + tailDelim
}

// Component: App
export default function App() {
  // Declaring State Hooks
  const [input, setInput] = useState('');
  const [emuState, setEmuState] = useState(emulatorState);
  const [promptText, setPromptText] = useState(buildPrompt(emuState))

  return (
    <ReactTerminalStateless
      emulatorState={emuState}
      theme={ myTheme }
      promptSymbol={promptText}
      outputRenderers={ ReactOutputRenderers  }
      inputStr={input}
      onInputChange={( (inp) => setInput(inp) )}
      onStateChange={( (eS) => setEmuState(eS) )}
      clickToFocus 
    />
  );
}

Any tips for a newbie? Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant