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

              
                <!-- The scene takes place in the JS panel! -->
<div id="root"></div>
              
            
!

CSS

              
                /* The scene takes place in the JS panel! */
              
            
!

JS

              
                // 🌱 Watch the elements pop up!
// šŸŒž Drag the Sun / Moon around the Earth
// šŸ’” Switch off / on the light!

// šŸ¤“ This pen is _a bit_ overengineered, ok: I'm a nerd
// šŸŽ‰ Yet it has been a lot of fun to create and to iterate on it
// šŸŽØ Originally inspired by this amazing CSS Pen: https://codepen.io/nicolasraube/pen/OgoeGx
// ā” Powered by:
//   - āš›ļø React
//   - šŸ“— GreenSock (TweenMax, Draggable, MorphSVGPlugin)
//   - šŸ’… styled-components
//   - ✨ polished

const { Component, Children, cloneElement } = React;
const { default: sc, injectGlobal } = styled;
const { lighten, darken, shade } = polished;

const renderTheScene = () =>
  ReactDOM.render(
    <Universe>
      <World />
      <Switch />
    </Universe>,
    document.getElementById('root')
  );

// -------------------------------------------------------------
// ----- Scene Configuration
// -------------------------------------------------------------

// like headings (h1, h2, h3), but for durations
const t1 = 0.5;
const t2 = 0.4;
const t3 = 0.3;
const t4 = 0.2;

const colors = {
  tree: 'hsl(123, 43%, 40%)',
  mountain: 'hsl(0, 0%, 74%)',
  earth: 'hsl(122, 39%, 49%)',
  star: {
    light: '#FFEB3B',
    dark: '#D0E2F5',
  },
  background: {
    light: '#FFF9C4',
    dark: '#626F8F',
  },
};

const initialSettings = {
  earth: {
    circularShape: true,
  },
  earthShadow: {
    rotation: 45,
    circularShape: true,
  },
  star: {
    opacity: 0,
    circularShape: true,
  },
};

const morphedPaths = {
  star: {
    light:
      'M150,60 C150,109.70562748479,109.70562748479,150,60,150,10.294372515210007,150,-30,109.70562748479,-30,60,-30,10.294372515210007,10.294372515210007,-30,60,-30,109.70562748479,-30,150,10.294372515210007,150,60z',
    dark:
      'M0 174.879C9.383 178.195 19.48 180 30 180c49.706 0 90-40.294 90-90S79.706 0 30 0C19.48 0 9.383 1.805 0 5.121 34.956 17.476 60 50.813 60 90c0 39.187-25.044 72.524-60 84.879z',
  },
};

// make the star appear after this element
const popUpStarAfterElement = 'BigTree';

// -------------------------------------------------------------
// ----- Utilities
// -------------------------------------------------------------

// only affect luminance
const shadowColor = color => darken(0.1, color);

// may affect hue
const isDayColor = ({ isDayMode, color }) =>
  isDayMode ? color : shade(0.7, color);

// star drag events callback updater
const updateShadow = (handleShadowLocation, earthShadow) => {
  // return a function because 'this' refers to the dragged element
  return function() {
    const { rotation } = this.target._gsTransform;

    // change shadow on elements of type mountain & tree
    handleShadowLocation(rotation % 360);

    // keep the earth shadow in sync with the star
    TweenMax.set(earthShadow, {
      rotation: (rotation + 45) % 360,
    });
  };
};

// get the right colors for the button depending on
// its current state (inactive, hovered, disabled)
const buttonColor = ({ isDayMode: mode, colorModifier = f => f }) => {
  const currentMode = mode ? 'dark' : 'light';

  return isDayColor({
    isDayMode: !mode,
    color: colorModifier(colors.background[currentMode]),
  });
};

const extractSettings = props =>
  Object.keys(props)
    .filter(key => key === 'x' || key === 'y' || key === 'finalScale')
    .reduce((settings, key) => ({ ...settings, [key]: props[key] }), {});

// -------------------------------------------------------------
// ----- Container
// -------------------------------------------------------------

class Universe extends Component {
  state = {
    // is the world completely popped up?
    showButton: false, // boolean
    // when the world will be popped up,
    // the star will be on the left side of the screen
    isStarOnRightSide: null, // null -> boolean
    // are we on the day mode?
    isDayMode: true, // boolean
    // are we switching mode day/night?
    switchingMode: false, // boolean
    // rotate the star on first switch light to
    // indicate that it can be dragged
    onboardingDone: false,
  };

  elements = {};

  timeline = new TimelineMax();

  registerElementRef = ({ name, ...rest }) => ref => {
    if (!this.elements[name]) {
      this.elements[name] = ref;

      let defaultSettings = {
        scale: 0,
      };

      const { circularShape, ...displaySettings } = initialSettings[name] || {};

      const originSetting = circularShape
        ? { svgOrigin: '200 200' }
        : { transformOrigin: '50% 100%' };

      const { finalScale, ...settings } = extractSettings(rest);

      TweenMax.set(ref, {
        ...defaultSettings,
        ...originSetting,
        ...displaySettings,
        ...settings,
      });

      this.timeline
        .to(
          ref,
          t1,
          {
            scale: finalScale || 1,
            ease: Bounce.easeOut,
          },
          `-=${t4}`
        )
        .add(() => {
          // only pop the star if it's the right time and if the star & earth's shadow exists
          if (
            // note: maybe I should keep track of the elements in the state
            // and pop the star from componentDidUpdate?
            name === popUpStarAfterElement &&
            this.elements.star &&
            this.elements.earthShadow
          ) {
            this.popUpStar();
          }
        });
    }
  };

  popUpStar = () => {
    const { star, earthShadow } = this.elements;

    // pop the star!
    this.timeline
      .to(star, t1, { scale: 1, opacity: 1, ease: Sine.easeOut })
      // make shadows appear while the star is popping up
      // and set the world to poped up
      .add(
        () => this.setState({ isStarOnRightSide: false, showButton: true }),
        `-=${t2}`
      )
      .add(this.handleOnboarding);

    // the star has popped up! make it draggable \o/
    Draggable.create(star, {
      type: 'rotation',
      edgeResistance: 0.65,
      bounds: 'svg',
      throwProps: true,
      onDrag: updateShadow(this.handleShadowLocation, earthShadow),
      onThrowUpdate: updateShadow(this.handleShadowLocation, earthShadow),
    });
  };

  handleOnboarding = () => {
    this.setState(() => ({ onboardingDone: true }));

    const oscillationsNumber = Array(6).fill(null);

    oscillationsNumber.forEach((_, index) => {
      const orientation = index % 2 === 0 ? 1 : -1;

      this.timeline.to(this.elements.star, t4, {
        rotation: `${orientation * 3}deg`,
      });
    });
  };

  switchLight = () => {
    if (!this.state.switchingMode) {
      const switchToMode = this.state.isDayMode ? 'dark' : 'light';

      this.timeline
        .add(() =>
          this.setState(prevState => ({
            isDayMode: !prevState.isDayMode,
            switchingMode: true,
          }))
        )
        .to(this.elements.star, t1, {
          morphSVG: morphedPaths.star[switchToMode],
        })
        .to(
          this.elements.star,
          t4,
          {
            fill: colors.star[switchToMode],
            filter: 'none',
          },
          `-=${t1}`
        )
        .to(
          'body',
          t3,
          {
            backgroundColor: colors.background[switchToMode],
          },
          `-=${t1}`
        )
        .add(() =>
          this.setState(prevState => ({
            switchingMode: false,
          }))
        );
    }
  };

  handleShadowLocation = rotation => {
    const shadowShouldBeOnRightSide =
      (rotation > 38 && rotation < 220) || rotation < -140;

    if (shadowShouldBeOnRightSide) {
      if (!this.state.isStarOnRightSide) {
        this.setState(() => ({ isStarOnRightSide: true }));
      }
    } else {
      if (this.state.isStarOnRightSide) {
        this.setState(() => ({ isStarOnRightSide: false }));
      }
    }
  };

  colorElement = ({ name = 'tree', initialSide = 'left' }) => {
    // get the current position of the star (left or right?)
    const { isStarOnRightSide, isDayMode } = this.state;

    // get the colors related to this element
    // if the color is defined as a string (mountain, tree),
    // darken it automatically else fallback to the object definition
    const { light, dark } =
      typeof colors[name] === 'string'
        ? {
            light: colors[name],
            dark: shadowColor(colors[name]),
          }
        : colors[name];

    // return the element's color relative to the situation and its initialization on screen
    // -> default to element's light color when the star isn't there yet
    // -> else map the element's colors light/dark depending on the position of the star
    const color = {
      left:
        isStarOnRightSide === null ? light : isStarOnRightSide ? light : dark,
      right:
        isStarOnRightSide === null ? light : isStarOnRightSide ? dark : light,
    }[initialSide];

    return isDayColor({ isDayMode, color });
  };

  render() {
    return (
      <Wrapper>
        {Children.map(this.props.children, child =>
          cloneElement(child, {
            ...this.state,
            registerElementRef: this.registerElementRef,
            colorElement: this.colorElement,
            elements: this.elements,
            switchLight: this.switchLight,
          })
        )}
      </Wrapper>
    );
  }

  // uncomment to debug
  // componentDidUpdate(prevProps, prevState) {
  //  console.log('done rendering the universe!', prevState);
  // }
}

// -------------------------------------------------------------
// ----- Animated SVG
// -------------------------------------------------------------

class World extends Component {
  render() {
    return (
      <StyledSvg
        viewBox="-100 -100 640 640"
        xmlns="http://www.w3.org/2000/svg"
        height="60vw"
      > 
        <title>A little world animated with a sun/moon, trees and mountains</title>
        <Star
          innerRef={this.props.registerElementRef({ name: 'star' })}
          fill={colors.star.light}
          d={morphedPaths.star.light}
        />
        <Earth
          isStarOnRightSide={this.props.isStarOnRightSide}
          isDayMode={this.props.isDayMode}
          registerElementRef={this.props.registerElementRef}
          colorElement={this.props.colorElement}
          elements={this.props.elements}
        > 
          {/*
            <Mountain x={60} y={-20} finalScale={1.2} name="OtherMountain" /> 
          */}
          <Mountain x={100} name="Mountain" />
          <Tree x={50} y={100} finalScale={0.8} name="SmallTree" />
          <Tree x={240} y={50} name="BigTree" />
        </Earth>
      </StyledSvg>
    );
  }
}

// -------------------------------------------------------------
// ----- "SVG" Components
// -------------------------------------------------------------

class Earth extends Component {
  render() {
    return (
      <g>
        <g ref={this.props.registerElementRef({ name: 'earth' })}>
          <circle
            fill={isDayColor({
              isDayMode: this.props.isDayMode,
              color: colors.earth,
            })}
            cx="200"
            cy="200"
            r="180"
          />
          <path
            ref={this.props.registerElementRef({ name: 'earthShadow' })}
            transform="translate(190,20)"
            d="M0 359.727c3.31.181 6.644.273 10 .273 99.411 0 180-80.589 180-180S109.411 0 10 0C6.644 0 3.31.092 0 .273 94.76 5.462 170 83.944 170 180S94.76 354.538 0 359.727z"
            fill={
              this.props.isStarOnRightSide === null ? (
                'transparent'
              ) : (
                isDayColor({
                  isDayMode: this.props.isDayMode,
                  color: shadowColor(colors.earth),
                })
              )
            }
          />
        </g>
        {Children.map(this.props.children, child => {
          const { children, ...otherProps } = this.props;
          return cloneElement(child, otherProps);
        })}
      </g>
    );
  }
}

class Mountain extends Component {
  render() {
    const { x, y, finalScale, name } = this.props;
    return (
      <g ref={this.props.registerElementRef({ x, y, finalScale, name })}>
        <LeftTriangle
          colorElement={this.props.colorElement}
          name="mountain"
          d="M100 0v200h100z"
        />
        <RightTriangle
          name="mountain"
          colorElement={this.props.colorElement}
          d="M100 0v200H0z"
        />
      </g>
    );
  }
}

class Tree extends Component {
  render() {
    const { x, y, finalScale, name } = this.props;
    return (
      <g ref={this.props.registerElementRef({ x, y, finalScale, name })}>
        <path d="M40 140h20v60H40z" fill="#795548" />
        <LeftTriangle
          colorElement={this.props.colorElement}
          name="tree"
          d="M50 70v100h50z"
        />
        <RightTriangle
          name="tree"
          colorElement={this.props.colorElement}
          d="M50 70v100H0z"
        />

        <LeftTriangle
          colorElement={this.props.colorElement}
          name="tree"
          d="M50 40v100h50z"
        />
        <RightTriangle
          name="tree"
          colorElement={this.props.colorElement}
          d="M50 40v100H0z"
        />
        <LeftTriangle
          colorElement={this.props.colorElement}
          name="tree"
          d="M50 10v100h50z"
        />
        <RightTriangle
          name="tree"
          colorElement={this.props.colorElement}
          d="M50 10v100H0z"
        />
      </g>
    );
  }
}

const triangleFactory = initialSide => ({ colorElement, name, ...props }) => (
  <path
    fill={colorElement({ name, initialSide })}
    stroke={colorElement({ name, initialSide })}
    strokeWidth="1"
    {...props}
  />
);

const LeftTriangle = triangleFactory('left');
const RightTriangle = triangleFactory('right');

// -------------------------------------------------------------
// ----- "Classic" Components
// -------------------------------------------------------------

const Switch = ({ switchLight, showButton, isDayMode }) => (
  <Box onClick={switchLight} showButton={showButton} isDayMode={isDayMode}>
    {isDayMode ? 'Night' : 'Day'} Mode
  </Box>
);

const Wrapper = sc.div`
  display: flex;
  flex-direction: column-reverse;
  justify-content: flex-end;
  align-items: center;
  padding: 2rem;
`;

const Star = sc.path`
  cursor: move;
`;

const StyledSvg = sc.svg`
  height: 60vh;
`;

const Box = sc.button`
  opacity: ${props => (props.showButton ? 1 : 0)};
  ${props => !props.showButton && 'visibility: hidden;'}
  
  /* used view-width previously, but was messy on big screens */
  margin-bottom: 2rem;
  padding: 1rem 3rem;
  font-size: 2rem;
  font-weight: bold;
  text-transform: uppercase;
  letter-spacing: 0.2rem;
  
  border-color: transparent;
  border-radius: 1rem;

  transition: opacity ${t1}s ease-out, border-radius ${t3}s ease-in, background ${t3}s ease-in;
  cursor: pointer;
  
  color: ${({ isDayMode }) => buttonColor({ isDayMode: !isDayMode })};
  background: ${buttonColor};

  &:hover {
    background: ${({ isDayMode }) =>
      buttonColor({ isDayMode, colorModifier: color => lighten(0.1, color) })};
    border-radius: 1.5rem;
    transition: border-radius ${t3}s ease-out, background ${t3}s ease-out;
  }
  
  &:disabled {
    cursor: not-allowed;
  }

  &:focus {
    outline: none;
  }
`;

injectGlobal`
  body {
    margin: 0;
    background: ${colors.background.light};
  }

  path {
    transition: fill ${t2}s, stroke ${t2}s;
  }
`;

// -------------------------------------------------------------
// ----- \o/
// -------------------------------------------------------------

renderTheScene();

              
            
!
999px

Console