Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs 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 its URL and the proper URL extension.

+ 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

Auto Save

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='root'>
</div> 


              
            
!

CSS

              
                body {
  background: #ffffff;
}

#root {
  display: flex;
  justify-content: center;
}

#app {
  /* 親コンテナにdisplay: flex; を使うと、子要素は縦並びでなく「横」に配置 */
  display: grid;
  align-items: center;
  justify-content: center;
  
  // 3つずつ配置させる(9こあるので3x3のグリッドを想定)
  // grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-columns: repeat(4, 1fr); 
  justify-items: center;
  grid-gap: 1px;
  grid-column-gap: 2px;
}

.button {
  font-size: 30px;
  border: solid 1pt silver;
  background: ivory;
  
  /* 要素を並列に並べる */
  display: flex;
  
  // コンテナ内のアイテムの交差軸方向(初期値では縦方向)を規定 (縦方向に中央に配置)
  align-items: center;
  // コンテナの横方向でのセンタリング
  justify-content: center;
  
  // 100x100の要素にする
  // 外側にボーダーが左右8px取るので116px使う
  width: 60px;
  height: 60px;
  padding: 0;
  
  &.equals {
    grid-column-start: 4; 
    grid-row-start: 4; 
    grid-row-end: 6;
    height: 124px;
  }
  
  &.zero {
    grid-column-start: 1; 
    grid-column-end: 3; 
    width: 124px;
  }
  
  &.displayWrapper {
    grid-column-start: 1; 
    grid-column-end: 5; 
    width: 254px;
    text-align: right;
    background: #FFF8E1;
  }
  
  &:hover {
    background: #FFF9C4; 
  }
  
  &.ac {
    grid-column-start: 1; 
    grid-column-end: 3; 
    width: 124px;
  }
}

#display {
  width: 90%;
  padding: 4px;
}

#formula {
  width: 90%;
  padding: 4px;
  font-size: 10px;
  color: silver;
}
              
            
!

JS

              
                /* global React, ReactDOM */
/* eslint-disable react/prop-types, react/no-multi-comp,
 no-eval, no-nested-ternary */

// #clear
class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      display: 0,
      digits: [],
      keyInput: []
    }
    this.generateDisplayValue = this.generateDisplayValue.bind(this)
    this.clearDisplay = this.clearDisplay.bind(this)
    this.numberDisplay = this.numberDisplay.bind(this)
    this.setOperator = this.setOperator.bind(this)
    this.calculate = this.calculate.bind(this)
    this.addDigits = this.addDigits.bind(this)
  }
  
  clearDisplay(event) {
    this.setState({ display: 0, digits: [], keyInput: [] })    
  }
  
  // 計算結果やボタン入力による表示を実施 
  generateDisplayValue(value) {
    let newValue = this.state.display + value
    newValue = newValue.replace(/^0/, '')
    return newValue
  }
  
  numberDisplay(event) {
    const inputNumber = event.target.innerText;
    const newDigits = this.addDigits(inputNumber, this.state.digits)
    
    // 入力内容が処理対象のキーによって更新されていたら、表示関連のstateも更新する
    if (newDigits.toString() != this.state.digits.toString()) {
      const keyInput = [...this.state.keyInput]
      keyInput.push(inputNumber)
      this.setState({digits: [...newDigits], 
                     keyInput: keyInput, 
                     display: this.generateDisplayValue(inputNumber) 
                    })
        
    }
  }
  
  safeEval(val){
    return Function('"use strict";return ('+val+')')();
  }
  
  // 演算子の入力
  setOperator(event) {
    const inputOperator = event.target.innerText;
    let keyInput = [...this.state.keyInput]
    
    // 直前の入力データが=を含む集計結果だった場合は、入力データをクリアして集計結果のみにする
    if (this.state.keyInput.indexOf('=') > -1) {
      const newVal = [...this.state.keyInput].pop()
      keyInput = [ newVal ]
    }
    const newDigits = this.addDigits(inputOperator, this.state.digits)
    
    keyInput.push(inputOperator)
    this.setState({ digits: [...newDigits], keyInput: keyInput, display: inputOperator })
  }
  
  // 実際の計算
  calculate(event) {
    let calculateText = this.state.digits.join('')
    calculateText = calculateText.replace(/(\+|\*|\/+)(\-)(\+|\*|\/)(\d)/g, '$3$4').replace(/(\+|\-){2,}(\d)/g, '$1$2')
    const value = this.safeEval(calculateText)
    let keyInput = [...this.state.keyInput]
    keyInput.push('=')
    keyInput.push(value)
    this.setState({ keyInput: keyInput,  display: value, digits: [ value ] })
  }

  /* 入力された値をチェックして登録: 有効な入力値の入った配列を返す */
  addDigits(value, digits) {
    const operators = /\-|\+|\*|\//
    let newDigits = [...digits]
    
    // 入力データの直前の1つを取得
    let lastDigit = [...digits].pop()

    // 0のみ入力されていて、追加データも0の場合は値は増やさない
    if (newDigits.length == 1 && parseInt(lastDigit) == 0 && parseInt(value) == 0) {
      return newDigits
    }
    
    if (newDigits.length == 1 && parseInt(lastDigit) == 0 && parseInt(value) != 0) {
      return [value]
    }
    
    /* 12.45 + 12.3 に対して追加で '.' が来た場合: 演算子で分割し、直前の数字文字列に '.' が入っていたら変更しない */
    if (value == '.') {
      const lastNumber = [...digits.join('').split(operators)].pop()
      if (lastNumber.indexOf('.') > -1) {
        return newDigits  
      }                                       
    }

    newDigits.push(value)
    return newDigits
  }

  render() {
    return(
    <div id='app'>
      <div id="clear" className="button ac" onClick={this.clearDisplay}>AC</div>
      <div id="divide" className="button divide" onClick={this.setOperator}>/</div>
      <div id="multiply" className="button multiply" onClick={this.setOperator}>*</div>
      <div id="seven" className="button seven" onClick={this.numberDisplay}>7</div>
      <div id="eight" className="button eight" onClick={this.numberDisplay}>8</div>
      <div id="nine" className="button nine" onClick={this.numberDisplay}>9</div>
      <div id="subtract" className="button subtract" onClick={this.setOperator}>-</div>
      <div id="four" className="button four" onClick={this.numberDisplay}>4</div> 
      <div id="five" className="button five" onClick={this.numberDisplay}>5</div> 
      <div id="six" className="button six" onClick={this.numberDisplay}>6</div>
      <div id="add" className="button add" onClick={this.setOperator}>+</div>
      <div id="one" className="button one" onClick={this.numberDisplay}>1</div>
      <div id="two" className="button two" onClick={this.numberDisplay}>2</div>
      <div id="three" className="button three" onClick={this.numberDisplay}>3</div>
      <div id="equals" className="button equals" onClick={this.calculate}>=</div>
      <div id="zero" className="button zero" onClick={this.numberDisplay}>0</div>
      <div id="decimal" className="button decimal" onClick={this.numberDisplay}>.</div>
      <div className="button displayWrapper">
        <div id="display">{this.state.display}</div>
      </div>
      <div className="button displayWrapper">
        <div id="formula">{this.state.keyInput.join('')}</div>
      </div>
    </div>
    )
  }
}

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

Console