123

Pen Settings

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. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <render id="render"></render>
            
          
!
            
              body {
  width: 100%; 
  height: 100%;
}

* {
  padding: 0;
  margin: 0;
  user-select: none;
}
            
          
!
            
              const { Component, PropTypes } = React
const { render } = ReactDOM
const { Motion, spring } = ReactMotion
const View = ReactFlexbox.default
const reactTriggerChange = reactTriggerChange

const colors = {
  red: '#FF1744',
  green: '#00E676',
  active: 'white',
  background: 'rgba(0,0,0,0.2)'
}

function safeRatio(val) {
  return (
    val > 1 
        ? 1 
        : val < 0 
          ? 0 
          : val
  )
}

function parseValue(target) {
  switch(target.type) {
    case "checkbox": {
      return target.checked
    }
   
    case "number":
    case "range": {
      return parseFloat(target.value)
    }
      
    case "select-one": {
      try {
        return JSON.parse(target.value)
      } catch (e) {
        return target.value
      }
    }

    case "text":
    default:
      return target.value
  }
}

function numberExists(val) {
  return (
    val !== null &&
  	val !== undefined &&
    typeof val === "number"
  )
}

class Toggler extends Component {
  static propTypes = {
    value: PropTypes.bool.isRequired
  };

  static defaultProps = {
    value: false
  };


	constructor(props) {
		super(props);

		this.state = {
      xRatio: null,
      yRatio: null,
			mousing: false,
      touching: false,
      initialMouse: {},
      initialTouches: [],
      interval: null,
		};
	}

  componentDidMount() {
    window.addEventListener('mousemove', this.handleMouseMoving.bind(this))
    window.addEventListener('mouseup', this.handleMouseUp.bind(this))
  }

  componentWillUnmount() {
    window.removeEventListener('mousemove', this.handleMouseMoving.bind(this))
    window.removeEventListener('mouseup', this.handleMouseUp.bind(this))
  }

  resetState(state) {
    this.setState({
      xRatio: null,
      yRatio: null,
      mousing: false,
      touching: false,
      initialMouse: {},
      initialTouches: [],
      interval: null,
      ...state,
    })
  }

  triggerValueChange(value=!this.input.checked) {
    if (value !== this.input.checked) {
      this.input.checked = value
      reactTriggerChange(this.input)
    }
  }
                  
  handleClick() {
    this.triggerValueChange()
  }

  handleMouseMove(e) {
		const { left, top, width, height } = this.toggle.getBoundingClientRect()
    
		const xRatio = safeRatio((e.clientX - left) / width)
    const yRatio = safeRatio((e.clientY - top) / height);
    
    this.setState({ xRatio, yRatio })
    
    this.triggerValueChange(xRatio >= 0.5)
  }

  handleMouseDown(e) {
		this.setState({
      mousing: true,
      interval: new Date(),
      initialMouse: {
        clientX: e.clientX,
        clientY: e.clientY,
      },
    })

		this.handleMouseMove(e)
  }

  handleMouseMoving(e) {
    if (this.state.mousing) {
      this.handleMouseMove(e)
    }
  }

  handleMouseUp(e) {
    const { interval, mousing, touching, initialMouse } = this.state
    
    if (mousing && !touching) {
      const timelapse = new Date() - interval

      if (timelapse < 300) {
        const { clientX: initialClientX } = initialMouse

        if (e.clientX !== initialClientX) {
          this.triggerValueChange(e.clientX > initialClientX)
        } else {
          this.triggerValueChange()
        }
      }

      this.resetState({ mousing: false })
    }
  }

  // handleMouseOut(e) {
  //   this.resetState({ mousing: false })
  // }

  handleTouchMove(e) {
    const { clientX, clientY } = e.targetTouches[0]
    const { left, top, width, height } = this.toggle.getBoundingClientRect()
    
		const xRatio = safeRatio((clientX - left) / width)
    const yRatio = safeRatio((clientY - top) / height);
    
    this.setState({ xRatio, yRatio })
    
    this.triggerValueChange(xRatio >= 0.5)
  }

  handleTouchStart(e) {
    e.preventDefault()
    
    this.setState({ 
      touching: true,
      interval: new Date(),
      initialTouches: e.targetTouches,
    })
    
    this.handleTouchMove(e)
  }

  handleTouchMoving(e) {
    e.preventDefault()

    if (this.state.touching) {
      this.handleTouchMove(e)
    }
  }

  handleTouchCancel(e) {
    this.resetState({ touching: false })
  }

  handleTouchEnd(e) {
    const { interval, touching, mousing, initialTouches } = this.state
    
    if (touching && !mousing) {
      const timelapse = new Date() - interval

      if (timelapse < 300) {
        const { clientX: initialClientX } = initialTouches[0]
        const { clientX } = e.changedTouches[0]

        if (clientX !== initialClientX) {
          this.triggerValueChange(clientX > initialClientX)
        } else {
          this.triggerValueChange()
        }
      }

      this.resetState({ touching: false })
    }
  }
  
  render() {
    const {
      value,
      onChange,
      disabled,
      style,
      toggleStyle,
      ...props
    } = this.props
    
    const styles = {
      container: {
        display: 'inline-flex',
        // position: 'relative',
        justifyContent: 'center',
        alignItems: 'center',
        flex: '0 1 auto',
        // textAlign: 'initial',
        // verticalAlign: 'middle',
        // cursor: 'pointer',
        margin: '0.25em',
        // WebkitTapHighlightColor: "rgba(0,0,0,0)",
        ...style,
      },
      toggle: {
        // disable touch highlighting on devices
        tapHighlightColor: "rgba(0,0,0,0)",
        WebkitTapHighlightColor: "rgba(0,0,0,0)",
        ...toggleStyle
      }
    }
          
    const circleDiameter = 15
    const circleRadius = circleDiameter / 2
      
    const border = 1.5
    
    const height = border + circleDiameter + border
    const width = border + ( circleDiameter * 2 ) + border
    const borderRadius = height / 2
      
    const cy = height / 2
      
    function xPosition(p) {
      return ( border + circleRadius ) + ( p  * circleDiameter )
    }
      
    return (
      <View
        row
        style={styles.container}
      >
        <input
          type="checkbox"
          ref={(input) => this.input = input}
          name={name}
          checked={value}
          onChange={onChange}
          disabled={disabled}
          style={{display: "none"}}
        />

        <svg
          ref={(toggle) => this.toggle = toggle}
          height="1em" 
          style={styles.toggle} 
          viewBox={`0 0 ${width} ${height}`}
          {...props}
        >
          <rect 
            x="0" y="0" 
            width={width} height={height} 
            rx={borderRadius} ry={borderRadius} 
            fill={colors.background}
            onClick={this.handleClick.bind(this)}
          />
          
          
          <Motion
            style={{
              cx: spring(xPosition(value ? 1 : 0), {stiffness: 400, damping: 27})
            }}
          >
          {({ cx }) =>
            <circle 
              cx={cx} 
              cy={cy} 
              r={circleRadius} 
              fill={colors.active}
              stroke="transparent"
              strokeWidth={border*2}
              cursor="pointer"
              onMouseDown={this.handleMouseDown.bind(this)}
              // onMouseMove={this.handleMouseMoving.bind(this)}
              // onMouseOut={this.handleMouseOut.bind(this)}
              // onMouseUp={this.handleMouseUp.bind(this)}
              onTouchStart={this.handleTouchStart.bind(this)}
              onTouchMove={this.handleTouchMoving.bind(this)}
              onTouchCancel={this.handleTouchCancel.bind(this)}
              onTouchEnd={this.handleTouchEnd.bind(this)}
             />
          }
          </Motion>
        </svg>
      </View>
    )
    
  }
}

class Render extends Component {
  constructor() {
    super()
    
    this.state = {
      active: false
    }
  }
    
  handleChange(e) {
    this.setState({active: parseValue(e.target)})
  }
  
  handleToggleOn(e) {
    this.setState({ active: true })
  }
  
  handleToggleOff(e) {
    this.setState({ active: false })
  }
  
  render() {
    const { active } = this.state
    
    const pointerStyle = {
      cursor: "pointer",
      tapHighlightColor: "rgba(0,0,0,0)",
      WebkitTapHighlightColor: "rgba(0,0,0,0)",
    }
    
    const style = {
      container: {
        fontFamily: 'Nunito, sans-serif',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        fontSize: '10vw',
        background: active ? colors.green : colors.red,
      },
      wrapper: {
                justifyContent: 'center',
        alignItems: 'center',
      },
      on: {
        ...pointerStyle,
        color: active ? colors.active : colors.background
      },
      off: {
        ...pointerStyle,
        color: active ? colors.background : colors.active
      }
    }

    return (
      <View column style={style.container}>
        <View row auto style={style.wrapper}>
          <p 
            style={style.on}
            onClick={this.handleToggleOn.bind(this)}
          >On</p>
          <Toggler
            value={active}
            onChange={this.handleChange.bind(this)}
          />
          <p 
            style={style.off}
            onClick={this.handleToggleOff.bind(this)}
          >Off</p>
        </View>
      </View>
    )
  }
}

render(
  <Render />,
  document.getElementById('render')
)
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console