Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="app"></div>
              
            
!

CSS

              
                @import url("https://fonts.googleapis.com/css2?family=Montserrat&display=swap");


body {
  display: flex;
  height: 100vh;
  width: auto;
  background-color: #fbb034;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-family: "Montserrat", sans-serif;
  background-image: linear-gradient(315deg, #fbb034 0%, #ffdd00 74%);

}

#calculator {
  align-self: center;
  width: 100%;
  height: 100%;
  padding: 10px;
  background-color: #485461;
  border-radius: 15px;
  background-image: linear-gradient(315deg, #485461 0%, #28313b 74%);


}

#button-box {
  margin-top: 15px;
  width: 100%;
  height: calc(100% - 110px);
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(5, 1fr);
  grid-gap: 10px;
}

.operator-box {
  width: 50px;
  height: 50px;
  background-color: #503cd1;
  border-radius: 10px;
  text-align: center;
  justify-content: center;
  align-items: center;
  color: #ffffff;
  border: none;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
}

.numberButton{
  width: 50px;
  height: 50px;
  background-color: #503cd1;
  border-radius: 50%;
  text-align: center;
  justify-content: center;
  align-items: center;
  color: #ffffff;
  border: none;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
}

.numberButton:hover {
  background-color: rgb(61, 43, 184);  
}

.topRow{
  color: white;
  background-color: #4357692d;
  width:auto;
  height: 30px;
  font-weight: bold;
  box-sizing: border-box;
  border-radius: 10px;
  align-content: center;
  justify-content: center;
}

#equals {
  background-color: rgb(243, 61, 29); 
  grid-column-start: 1;
  grid-column-end: 5;
  width:auto;
}

#equals:hover {
  background-color: rgb(228, 39, 15);
}

h1 {
  color: #485461;
  font-weight: bold;
}

              
            
!

JS

              
                import * as React from "https://cdn.skypack.dev/react@17.0.1";
import * as ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";

//website ref
//https://www.sitepoint.com/react-tutorial-build-calculator-app/

const { useState } = React;
const { useEffect } = React;

function App(){
  return(
  <div id="main">
      <h1>计算器</h1>
    <Calculator />
  </div>
  )
}

let isDecimalAllowed = true;
let isNegativeNumber = false

function Calculator(){
  const [input, setInput] = useState("0")
  const [activateReset, setActivateReset] = useState(false)
  const [operator, setOperator] = useState(null)
  const [activateCalculate, setActivateCalculate] = useState(false)
  const [stringToCalc, setStringToCalc] = useState(null)
  
  function useForceUpdate(){
    const [value, setValue] = useState(0); // integer state
    return () => setValue(value => value + 1); // update the state to force render
} 
  
  
  
  //3 + 5 * 6 - 2 / 4
  //32.5 or 11.5
  
  function calculate(){
    
       
    console.log("Current Input Before Evaluating")
    console.log(input)
    
    let result = eval(input)
    //the reason why Im doing this is because for some reason, when I call my function to delete the blank negative (-) it won't automatically re-render. so when it is done calculating, what happens is, it uses the old input that hasnt been formatted. so if 1+(-)+1 was entered, then it will just show that instead of 1+1
    
    console.log("Result: ")
    console.log(result)
    
    if(typeof result === "number"){
      setInput(result)
    }else{
      setInput("Error! Reset and try again.")
    }
    
    setActivateCalculate(false)
    // setStringToCalc("")
  }

  if(activateCalculate){
    calculate()
  }
  
  function resetDisplay(){
    setInput("0")
    isDecimalAllowed = true
    isNegativeNumber = false
    setActivateReset(false)
    setActivateCalculate(false)
    setStringToCalc("")
  }
  
  if(activateReset){
    resetDisplay()
  }
  
  
  // 3 + 5 * 6 - 2 / 4
  return(
  <div id="calculator">
    <Display input={input}/>
    <Buttons input={input} setInput={setInput} activateCalculate={activateCalculate} setActivateReset={setActivateReset} setActivateCalculate={setActivateCalculate} setOperator={setOperator}  />
  </div>
  )
}

function Buttons({input, setInput, setActivateReset, activateCalculate, setActivateCalculate, setOperator}){
  
  function clickNumber(evt){
    let inputtedNumber = evt.target.textContent
    console.log(inputtedNumber)
    
    //the reason why I have this convoluted if statement maze is because I need to be able to correctly input and display the numbers, decimals, and zeros on the screen. 
    if(input === "0"){
      setInput(inputtedNumber)
    }
    if(inputtedNumber == "."
       && isDecimalAllowed && input !== "0"){
      setInput(prevVal => prevVal + inputtedNumber)
      isDecimalAllowed = false
    }else if(inputtedNumber == "."
       && isDecimalAllowed && input == "0"){
      setInput("0" + inputtedNumber)
      isDecimalAllowed = false
    }else if(inputtedNumber != "." && input != "0"){
      setInput(prevVal => prevVal + inputtedNumber)
    }
    
  }
 
  function negNumberBlankChecker(){
     let startingParenthesesIndex = input.indexOf("(")
     let endParenthesesIndex = input.indexOf(")")
    
    if (input.includes(")") && input.charAt(endParenthesesIndex - 1) === "-"){
     console.log("Start Parentheses")
     console.log(startingParenthesesIndex)
      console.log("End Parentheses")
      console.log(endParenthesesIndex)
//check if theres a number or if its just (-)
     if(input.charAt(endParenthesesIndex - 1) === "-"){
       console.log("There is a blank minus here...")
       console.log(input)
        let stringBeforeParentheses = input.substring(0, startingParenthesesIndex - 1)
        let stringAfterParentheses = input.substring(endParenthesesIndex + 1, input.length)
        
       console.log("String Before Parentheses: ")
       console.log(stringBeforeParentheses)
       
       console.log("String After Parentheses")
       console.log(stringAfterParentheses)
       console.log("Combining!")
       let combinedString = stringBeforeParentheses + stringAfterParentheses
       console.log(combinedString)
       setInput(combinedString)
       setStringToCalc(combinedString)
      }
    }
  }
  
  function clickOperator(e){
        
    let inputtedOperator = e.target.textContent
    console.log(inputtedOperator)
    setOperator(inputtedOperator)
    
    //I need to find out if the last button pressed was an operator or not. If it is, and the minus button is pressed, then I have to add a parentheses. The user will then ocntinue to put in however many numbers he wants, and then when he presses an operator again, I am going to add the ending parentheses before adding another operator.
    let negativeNumCheck = /.*[\+\/\*\-]$/.test(input)
    console.log("Negative Number Check: ")
    console.log(negativeNumCheck)
    
    if(isNegativeNumber && inputtedOperator != "="){
//       if(input.includes("(") && input.charAt(input.length - 1) === "-"){

//         let formatInput = input.substring(0, input.length - 3)
//         console.log("Format Input Value: ")
//         console.log(formatInput)
//         setInput(formatInput)
//         // setActivateCalculate(true)
//       }else{
        inputtedOperator = ")" + inputtedOperator
      // }
      
      isNegativeNumber = false
    }else if(isNegativeNumber && inputtedOperator == "="){
      setInput(prevVal => prevVal + ')')
      setActivateCalculate(true)
    }
    
    if (inputtedOperator != "=" && inputtedOperator != "-"){
      setInput(prevVal => prevVal + inputtedOperator)
    }else if(negativeNumCheck && inputtedOperator == "-" ) {
      setInput(prevVal => prevVal + "(" + inputtedOperator)
      isNegativeNumber = true
    }else if(negativeNumCheck == false && inputtedOperator == "-"){
      setInput(prevVal => prevVal + inputtedOperator)
    }else if(inputtedOperator === "=" && activateCalculate == false){
      setActivateCalculate(true)
    }
    
    
    isDecimalAllowed = true;
  }
  
  function triggerReset(){
    setActivateReset(true)
  }
  
  return(
  <div id="button-box">
      <button id="zero" className="numberButton" onClick={clickNumber}>0</button>
      <button id="one" className="numberButton" onClick={clickNumber}>1</button>
      <button id="two" className="numberButton" onClick={clickNumber}>2</button>
      <button id="three" className="numberButton" onClick={clickNumber}>3</button>
      <button id="four" className="numberButton" onClick={clickNumber}>4</button>
      <button id="five" className="numberButton" onClick={clickNumber}>5</button>
      <button id="six" className="numberButton" onClick={clickNumber}>6</button>
      <button id="seven" className="numberButton" onClick={clickNumber}>7</button>
      <button id="eight" className="numberButton" onClick={clickNumber}>8</button>
      <button id="nine" className="numberButton" onClick={clickNumber}>9</button>
      <button id="decimal" className="numberButton" onClick={clickNumber}>.</button>
      <button className="operator-box" id="clear" onClick={triggerReset}>AC</button>
      <button id="add" className="operator-box" onClick={clickOperator}>+</button>
      <button id="subtract" className="operator-box" onClick={clickOperator}>-</button>
      <button id="multiply" className="operator-box" onClick={clickOperator}>*</button>
      <button id="divide" className="operator-box" onClick={clickOperator}>/</button>
      <button id="equals" className="operator-box" onClick={clickOperator}>=</button>
  </div>
  )
 }

function Display({input}){
  return(
  <div id="display" className="topRow">{input}</div>
  )
}

ReactDOM.render(<App />, document.getElementById('app'))
              
            
!
999px

Console