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.

            
              <div id="root">
    <!-- This element's contents will be replaced with your component. -->
</div>

            
          
!
            
              $defaultMargin: 0.3em;
$defaultMarginH: 0 $defaultMargin;
$defaultMarginV: $defaultMargin 0;
$defaultCornerRadius: 0.3em;

@mixin innerGap($margins) {
  & > * {
    margin: $margins;
  }
  & > :first-child {
    margin-top: 0 !important;
    margin-left: 0 !important;
  }
  & > :last-child {
    margin-bottom: 0 !important;
    margin-right: 0 !important;
  }
}

.color-rect {
  height: 32px;
}

.group {
  border: 1px solid lightgray;
  border-radius: $defaultCornerRadius;
  padding: $defaultCornerRadius;
}

.number-editor {
  @include innerGap($defaultMarginH);

  & > * {
    display: inline-block;
    vertical-align: middle;
    text-align: right;
  }

  .name {
    width: 5em;
  }
  .slider {
    width: 20em;
  }
  .textbox {
    width: 4em;
    vertical-align: middle;
  }
}

.color-editor {
  position: relative;
  display: inline-block;

  @include innerGap($defaultMarginV);

  .group {
    @include innerGap($defaultMarginV);
  }
  
  .btn-random {
    display: block;
    width: 100%;
  }
}

            
          
!
            
              // For some reason, this triggers on my PC
// https://blog.codepen.io/2016/06/08/can-adjust-infinite-loop-protection-timing/
window.CP && (window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 6000);

function isDefined(value) {
  return typeof value !== "undefined";
}

function firstDefined() {
  for (let i = 0; i < arguments.length; ++i) {
    if (isDefined(arguments[i])) return arguments[i];
  }
}

function mkColor(r, g, b, a = 1) {
  return { r, g, b, a };
}

/**
 * Converts an RGB color value to HSL. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
 * Assumes r, g, and b are contained in the set [0, 1] and
 * returns h, s, and l in the set [0, 1].
 *
 * @param   {r,g,b,...} The RGB representation
 * @return  {h,s,l,...} The HSL representation
 */
function rgbToHsl({ r, g, b, ...rest }) {
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  let h,
    s,
    l = (max + min) / 2;

  if (max == min) {
    h = s = 0; // achromatic
  } else {
    var d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r:
        h = (g - b) / d + (g < b ? 6 : 0);
        break;
      case g:
        h = (b - r) / d + 2;
        break;
      case b:
        h = (r - g) / d + 4;
        break;
    }
    h /= 6;
  }

  return { ...rest, h, s, l };
}

/**
 * Converts an HSL color value to RGB. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
 * Assumes h, s, and l are contained in the set [0, 1] and
 * returns r, g, and b in the set [0, 1].
 *
 * @param   {h,s,l,...}         The HSL representation
 * @return  {r,g,b,...}           The RGB representation
 */
function hslToRgb({ h, s, l, ...rest }) {
  var r, g, b;

  if (s == 0) {
    r = g = b = l; // achromatic
  } else {
    var hue2rgb = function hue2rgb(p, q, t) {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1 / 6) return p + (q - p) * 6 * t;
      if (t < 1 / 2) return q;
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
      return p;
    };

    var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    var p = 2 * l - q;
    r = hue2rgb(p, q, h + 1 / 3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1 / 3);
  }

  return { ...rest, r, g, b };
}

/** We want each component to be usable without defining any props (as far as possible), we'll use this color as the default one */
const defaultColor = mkColor(0.2, 0.5, 0.7, 1);

/** 
* The idea of an 'attr' is that it becomes a readonly ES5 property on the React component. 
*
* The value of this attribute comes either from the props or from the state.
* Like this one can make rich components with local state that can be overriden using a prop...
*
* A typical example is an accordion that has an `isOpen` attribute. 
* Usually the `isOpen` is local state, but it should be possible for the parent to make this a prop if needed.
* 
* This is most likely completely against the React guidelines, but when coming from OO UI frameworks,
* it feels more naturally to be able to "bind" every property.
*
* If an attribute needs to be editable by some input widget, 
* a default event handler in the state will change the state.
* If you provide a prop value but no prop event handler, the widget will change it's local state, but will render the prop state, and that is confusing (a warning should be printed in that case, not yet done) 
*/
function getAttr(view, name) {
  const result = firstDefined(view.props[name], view.state[name]);
  if (typeof result === "undefined") {
    const type = view.constructor.name || this.constructor.displayName;
    console.warn(
      `Expected '${name}' to be either defined in the state or props of ${type}`
    );
  }
  return result;
}

function getAttrs(view, ...names) {
  return names.reduce(
    (table, name) => ((table[name] = getAttr(view, name)), table),
    {}
  );
}

/** TODO: This should be done with decorators, but I can't get them working in this JSX Babel Codepen (works for regular JS)*/
function mapAttrs(type, mapping) {
  type.propTypes = { ...type.propTypes };

  Object.keys(mapping).forEach(name => {
    Object.defineProperty(type.prototype, name, {
      get: function() {
        return getAttr(this, name);
      },
      enumerable: false
    });

    type.propTypes[name] = mapping[name];
  });
}

class ColorRect extends React.PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      color: defaultColor
    };
  }
  render() {
    const { r, g, b, a } = this.color;
    const toByte = c => Math.round(c * 255);
    const cssColor = `rgba(${toByte(r)}, ${toByte(g)}, ${toByte(b)}, ${a}`;
    return <div className="color-rect" style={{ backgroundColor: cssColor }} />;
  }
}

mapAttrs(ColorRect, {
  color: PropTypes.object
});

class EditableValueComponent extends React.PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      value: this.getDefaultValue(),
      onValueChange: value => {
        this.setState({ value });
      }
    };

    this.raiseValueChange = this.raiseValueChange.bind(this);
  }

  getDefaultValue() {
    return 0;
  }

  raiseValueChange(value) {
    this.onValueChange(value);
  }
}

mapAttrs(EditableValueComponent, {
  value: PropTypes.any,
  onValueChange: PropTypes.func
});

class NumberEditor extends EditableValueComponent {
  constructor(props, context) {
    super(props, context);

    this.state = {
      ...this.state,
      name: "value",
      min: 0,
      max: 100,
      step: 1,
      digits: 0
    };

    this.handleValueChangeEvent = this.handleValueChangeEvent.bind(this);
  }

  handleValueChangeEvent(event) {
    const value = this.parseDisplayedValue(event.target.value);
    this.raiseValueChange(value);
  }

  render() {
    const sliderValue = this.getSliderValue();
    const stringValue = this.getStringValue();

    return (
      <div className="number-editor">
        <span className="name">{this.name}</span>
        <input
          className="slider"
          type="range"
          min={this.min}
          max={this.max}
          step={this.step}
          value={sliderValue}
          onChange={this.handleValueChangeEvent}
        />
        <input
          className="textbox"
          type="text"
          value={stringValue}
          onChange={this.handleValueChangeEvent}
        />
      </div>
    );
  }

  getSliderValue() {
    return this.value;
  }

  getStringValue() {
    return this.getSliderValue().toFixed(this.digits);
  }

  parseDisplayedValue(value) {
    const parser = this.digits === 0 ? parseInt : parseFloat;
    const inputValue = parser(value) || 0;
    const clampedValue = Math.max(this.min, Math.min(this.max, inputValue));
    return clampedValue;
  }
}

mapAttrs(NumberEditor, {
  name: PropTypes.string,
  min: PropTypes.number,
  max: PropTypes.number,
  step: PropTypes.number,
  digits: PropTypes.number,
  value: PropTypes.number
});

class ColorComponentEditor extends EditableValueComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      ...this.state,
      label: "red",
      range: 255,
      componentName: "r"
    };

    this.handleComponentValueChange = this.handleComponentValueChange.bind(this);
  }

  withComponentValue(componentValue) {
    return { ...this.value, [this.componentName]: componentValue / this.range };
  }

  getComponentValue() {
    return this.value[this.componentName] * this.range;
  }

  handleComponentValueChange(componentValue) {
    const color = this.withComponentValue(componentValue);
    this.raiseValueChange(color);
  }

  getDefaultValue() {
    return defaultColor;
  }

  render() {
    const componentValue = this.getComponentValue();
    return (
      <NumberEditor
        name={this.name}
        max={this.range}
        value={componentValue}
        onValueChange={this.handleComponentValueChange}
      />
    );
  }
}

mapAttrs(ColorComponentEditor, {
  label: PropTypes.string,
  value: PropTypes.object,
  range: PropTypes.number,
  componentName: PropTypes.string
});

class HslComponentEditor extends ColorComponentEditor {
  constructor(props, context) {
    super(props, context);
    this.state = {
      ...this.state,
      name: "hue",
      range: 359,
      scale: 360,
      componentName: "h"
    };
  }

  withComponentValue(componentValue) {
    const hsl = rgbToHsl(this.value);
    hsl[this.componentName] = componentValue / this.scale;
    return hslToRgb(hsl);
  }

  getComponentValue() {
    const hsl = rgbToHsl(this.value);
    return hsl[this.componentName] * this.scale;
  }
}

class TransparencyComponentEditor extends ColorComponentEditor {
  constructor(props, context) {
    super(props, context);
    this.state = {
      ...this.state,
      name: "transparency",
      componentName: "a"
    };
  }

  withComponentValue(componentValue) {
    return super.withComponentValue(255 - componentValue);
  }

  getComponentValue() {
    return 255 - super.getComponentValue();
  }
}

mapAttrs(HslComponentEditor, {
  scale: PropTypes.number
});

class ColorEditor extends EditableValueComponent {
  constructor(props, context) {
    super(props, context);
    this.pickRandomColor = this.pickRandomColor.bind(this);
  }

  getDefaultValue() {
    return defaultColor;
  }

  pickRandomColor() {
    const r = Math.random();
    const g = Math.random();
    const b = Math.random();
    const a = this.value.a;
    this.raiseValueChange(mkColor(r, g, b, a));
  }

  render() {
    const color = this.value;

    return (
      <div className="color-editor">
        <div className="group">
          <HslComponentEditor
            name="hue"
            range={359}
            scale={360}
            componentName="h"
            value={color}
            onValueChange={this.raiseValueChange}
          />
          <HslComponentEditor
            name="saturation"
            range={100}
            scale={100}
            componentName="s"
            value={color}
            onValueChange={this.raiseValueChange}
          />
          <HslComponentEditor
            name="lightness"
            range={100}
            scale={100}
            componentName="l"
            value={color}
            onValueChange={this.raiseValueChange}
          />
        </div>
        <div className="group">
          <ColorRect color={color} />
          <button className="btn-random" onClick={this.pickRandomColor}>
            Random
          </button>
        </div>
        <div className="group">
          <ColorComponentEditor
            name="red"
            componentName="r"
            value={color}
            onValueChange={this.raiseValueChange}
          />
          <ColorComponentEditor
            name="green"
            componentName="g"
            value={color}
            onValueChange={this.raiseValueChange}
          />
          <ColorComponentEditor
            name="blue"
            componentName="b"
            value={color}
            onValueChange={this.raiseValueChange}
          />
          <TransparencyComponentEditor
            value={color}
            onValueChange={this.raiseValueChange}
          />
        </div>
      </div>
    );
  }
}

mapAttrs(ColorEditor, {
  color: PropTypes.object
});

ReactDOM.render(<ColorEditor />, document.getElementById("root"));

            
          
!
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