add module progress confetti

This commit is contained in:
Nathan Wang 2020-07-06 23:15:08 -07:00
parent 177b7bb23c
commit d56939f4d1
17 changed files with 1114 additions and 26 deletions

View file

@ -17,3 +17,7 @@ The following is written for individuals without front-end development experienc
- `yarn install`
4. Run development server
- `yarn develop`
## Credits
- Confetti taken from Josh Comeau: https://github.com/joshwcomeau/react-europe-talk-2018

View file

@ -0,0 +1,46 @@
import React, { Component } from 'react';
class Canvas extends Component {
componentDidMount() {
this.ctx = this.canvas.getContext('2d');
this.scale();
this.props.draw(this.ctx);
}
componentDidUpdate(prevProps) {
if (
this.props.width !== prevProps.width ||
this.props.height !== prevProps.height
)
this.scale();
this.props.draw(this.ctx);
}
scale = () => {
const ratio = window.devicePixelRatio || 1;
this.canvas.width = this.props.width * ratio;
this.canvas.height = this.props.height * ratio;
this.canvas.style.width = this.props.width + 'px';
this.canvas.style.height = this.props.height + 'px';
this.ctx.scale(ratio, ratio);
};
render() {
const { width, height, draw, ...delegatedProps } = this.props;
return (
<canvas
ref={node => (this.canvas = node)}
width={width}
height={height}
{...delegatedProps}
/>
);
}
}
export default Canvas;

View file

@ -0,0 +1,59 @@
const hexRegex = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;
type HexColor = string;
type RGBColor = {
r: number;
g: number;
b: number;
a: number;
};
export const random = (low: number, high: number) =>
Math.random() * (high - low) + low;
export const sample = (array: Array<any>): any =>
array[Math.floor(random(0, array.length))];
export const range = (n: number) => Array.from(Array(n).keys());
export const getDiameter = (width: number, height: number) =>
Math.sqrt(width * width + height * height);
export const convertHexColorToRgb = (color: HexColor): RGBColor => {
const match = color.match(hexRegex);
if (match) {
return {
r: parseInt(match[1], 16) / 255,
g: parseInt(match[2], 16) / 255,
b: parseInt(match[3], 16) / 255,
a: 1,
};
} else {
throw new Error(`Failed to parse color: ${color}`);
}
};
export const mix = (color: RGBColor, background: RGBColor) => ({
r: color.r * color.a + background.r * (1 - color.a),
g: color.g * color.a + background.g * (1 - color.a),
b: color.b * color.a + background.b * (1 - color.a),
a: 1,
});
export const mixWithBlack = (color: RGBColor, amount: number) => {
const black = { r: 0, g: 0, b: 0, a: amount };
return mix(black, color);
};
export const mixWithWhite = (color: RGBColor, amount: number) => {
const white = { r: 1, g: 1, b: 1, a: amount };
return mix(white, color);
};
// Stringify the color in an `rgba()` format.
export const formatRgbColor = (color: RGBColor) =>
'rgba(' +
`${Math.floor(color.r * 255)}, ${Math.floor(color.g * 255)}, ` +
`${Math.floor(color.b * 255)}, ${color.a.toFixed(2)})`;

View file

@ -0,0 +1,307 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { random, sample, range, getDiameter } from './Confetti.helpers';
import { createCircle, createTriangle, createZigZag } from './confetti-shapes';
import Canvas from '../Canvas/Canvas';
class Confetti extends Component {
static propTypes = {
// The width of the HTML canvas.
width: PropTypes.number.isRequired,
// The height of the HTML canvas.
height: PropTypes.number.isRequired,
// An array of shapes, used when generating particles
// (each item provided has an equal chance of being selected as a
// particle)
shapes: PropTypes.array,
// When do we want to invoke "generateParticles"?
// NOTE: a better implementation would take an array. Doing it the simplest
// way for the demo, but a more fleshed-out implementation would be:
// PropTypes.arrayOf(PropTypes.oneOf(['click', 'mount', 'hover']))
makeItRainOn: PropTypes.oneOf(['click', 'mount']),
// The number of particles to generate, spread over the
// `emitDuration` length.
numParticles: PropTypes.number,
// Amount of time to spread the release of particles, in milliseconds.
emitDuration: PropTypes.number,
// The amount of downward acceleration to provide.
// Range: 10 = very slow, 10,000 = very fast.
gravity: PropTypes.number,
// The amount of Z-axis (2D) rotation to provide to each particle.
// Each particle has a random number specified, between 0 and n.
// Range: 0 = no spin, 10 = reasonable spin, 100 = pukeville
spin: PropTypes.number,
// The amount of X-axis (3D) rotation to provide to each particle.
// Each particle has a random number specified, between 0 and n.
// Range: 0 = no twist, 10 = reasonable twist, 100 = hummingbird
twist: PropTypes.number,
// Each particle will have a random speed assigned, contained by
// `minSpeed` and `maxSpeed`.
// This is the base speed, which is affected by `gravity`.
minSpeed: PropTypes.number,
maxSpeed: PropTypes.number,
// Each particle will have a random size applied, contained by
// `minScale` and `maxScale`. If you'd like all particles to retain
// their original size, simply provide `1` for both values.
minScale: PropTypes.number,
maxScale: PropTypes.number,
// Callback triggered when animation ends.
// NOTE: Only fires when all particles are off-canvas. Retriggering
// the confetti before it's completed will delay the handler.
onComplete: PropTypes.func,
};
static defaultProps = {
shapes: [
createZigZag({ fill: '#ca337c' }), // Pink
createZigZag({ fill: '#01d1c1' }), // Turquoise
createZigZag({ fill: '#f4d345' }), // Yellow
createCircle({ fill: '#63d9ea' }), // Blue
createCircle({ fill: '#ed5fa6' }), // Pink
createCircle({ fill: '#aa87ff' }), // Purple
createCircle({ fill: '#26edd5' }), // Turquoise
createTriangle({ fill: '#ed5fa6' }), // Pink
createTriangle({ fill: '#aa87ff' }), // Purple
createTriangle({ fill: '#26edd5' }), // Turquoise
],
numParticles: 80,
// By default emit all particles at once.
emitDuration: 0,
gravity: 1600,
spin: 20,
twist: 0,
minSpeed: 225,
maxSpeed: 675,
minScale: 0.4,
maxScale: 1.0,
};
state = {
particles: [],
};
componentDidMount() {
if (this.props.makeItRainOn === 'mount') {
this.generateParticles();
}
}
componentDidUpdate(prevProps, prevState) {
if (prevState.particles.length === 0 && this.state.particles.length > 0) {
this.tick();
}
}
componentWillUnmount() {
window.cancelAnimationFrame(this.animationFrameId);
}
generateParticles = () => {
const newParticles = range(this.props.numParticles).map(i => {
// Particles can be spread over a duration.
// Each particle should be "born" at a random time during the emit
// duration (if this value is 0, they'll all share the same birthdate).
const birth = Date.now() + random(0, this.props.emitDuration);
// Scale and Speed are specified in ranges. Select a value for this
// particle from within the range.
const speed = random(this.props.minSpeed, this.props.maxSpeed);
const scale = random(this.props.minScale, this.props.maxScale);
// Values for `spin` and `twist` are specified through props, but the
// values given represent the maximum absolute values possible.
// If `spin` is 30, that means each particle will select a random
// `spinForce` between -30 and 30.
const spinForce = this.props.spin * random(-1, 1);
const twistForce = this.props.twist * random(-1, 1);
// `currentSpin` and `currentTwist` are trackers for the current values
// as the animation progresses. Start them at `0`.
// NOTE: this does not mean that each particle will start with the same
// orientation - this is also influenced by `angle`, which is randomized.
// This represents the current deviation from the `angle`.
const currentSpin = 0;
const currentTwist = 0;
// Each particle starts along the top of the canvas, with a random
// `x` coordinate somewhere along its width.
const initialPosition = {
x: random(0, 1) * this.props.width,
y: 0,
};
const shape = sample(this.props.shapes);
const { front, back } = shape;
// ~~~ TRIGONOMETRY STUFF ~~~
// `angle` is the degree, in radians, that the shape is rotated along
// its Z-axis:
// ________
// /\ π radians \ /
// / \ -> \ /
// /______\ \/
//
const angle = random(0, 2 * Math.PI);
// `trajectory` represents the angle of the particle's movement.
// Larger numbers means the particle deviates further from its initial
// `x` coordinate.
const trajectoryVariance = random(-1, 1);
const trajectory = -Math.PI / 2 + trajectoryVariance;
// `vx` and `vy` represent the velocity across both axes, and will be
// used to compute how much a particle should move in a given frame.
const vx = Math.cos(trajectory) * speed;
const vy = Math.sin(trajectory) * speed * -1;
//
// ~~~ END TRIGONOMETRY STUFF ~~~
return {
birth,
initialPosition,
currentPosition: initialPosition,
spinForce,
twistForce,
currentSpin,
currentTwist,
angle,
scale,
vx,
vy,
front,
back,
width: front.naturalWidth,
height: front.naturalHeight,
};
});
this.setState({
particles: [...this.state.particles, ...newParticles],
});
};
tick = () => {
if (this.state.particles.length === 0) {
return;
}
this.animationFrameId = window.requestAnimationFrame(() => {
const particles = this.calculateNextPositionForParticles();
this.setState({ particles }, this.tick);
});
};
calculateNextPositionForParticles = () => {
const now = Date.now();
const { height, width } = this.props;
return this.state.particles
.map(particle => {
const age = (now - particle.birth) / 1000;
// Skip a particle if it hasn't been born yet.
if (age < 0) {
return particle;
}
const x = particle.initialPosition.x + particle.vx * age;
const y =
particle.initialPosition.y +
particle.vy * age +
(this.props.gravity * age * age) / 2;
const diameter = getDiameter(
particle.width * particle.scale,
particle.height * particle.scale
);
const isOffScreen =
x + diameter < 0 || x - diameter > width || y - diameter > height;
if (isOffScreen) {
return null;
}
// WARNING WARNING WARNING
// Mutating this.state directly here.
// This is a faux-pas, but it's important for performance.
particle.currentPosition = { x, y };
particle.currentSpin = particle.angle + particle.spinForce * age;
particle.currentTwist = particle.twistForce
? Math.cos(particle.angle + particle.twistForce * age)
: 1;
return particle;
})
.filter(particle => !!particle);
};
draw = ctx => {
const { width, height } = this.props;
const { particles } = this.state;
ctx.clearRect(0, 0, width, height);
particles.forEach(particle => {
// Apply its new position, in terms of cartesian coordinates.
ctx.translate(particle.currentPosition.x, particle.currentPosition.y);
// Apply its new Z-axis (2D) rotation (how much spin is currently
// applied?)
ctx.rotate(particle.currentSpin);
// Apply its new X-axis (3D rotation), and figure out whether it's
// "backwards" right now.
const imageElem =
particle.currentTwist >= 0 ? particle.front : particle.back;
ctx.scale(particle.currentTwist, 1);
// Draw the image into the context, applying the right scale and
// position so that it's in the right place.
ctx.drawImage(
imageElem,
imageElem.naturalWidth * particle.scale * -0.5,
imageElem.naturalHeight * particle.scale * -0.5,
imageElem.naturalWidth * particle.scale,
imageElem.naturalHeight * particle.scale
);
// Undo all of our transformations, so that our context is restored.
const ratio = window.devicePixelRatio || 1;
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
});
};
render() {
const { width, height, onClick, makeItRainOn } = this.props;
return (
<Canvas
width={width}
height={height}
draw={this.draw}
ref={node => (this.canvas = node)}
onClick={ev => {
if (makeItRainOn === 'click') {
this.generateParticles();
}
if (typeof onClick === 'function') {
onClick(ev);
}
}}
/>
);
}
}
export default Confetti;

View file

@ -0,0 +1,252 @@
import * as React from 'react';
import { random, sample, range, getDiameter } from './Confetti.helpers';
import { defaultShapes } from './confetti-shapes.js';
import type { Particle, Shape } from './types';
type State = {
particles: Array<Particle>;
};
type ChildFnProps = {
particles: Array<Particle>;
generateParticles: () => void;
};
type Props = {
// The width of the HTML canvas. No default value provided.
width: number;
// The height of the HTML canvas. No default value provided.
height: number;
// An array of shapes, used when generating particles
// (each item provided has an equal chance of being selected as a
// particle)
shapes: Array<Shape>;
// The number of particles to generate, spread over the
// `emitDuration` length.
numParticles: number;
// The amount of downward acceleration to provide.
// Range: 10 = very slow, 10,000 = very fast.
gravity: number;
// The amount of Z-axis (2D) rotation to provide to each particle.
// Each particle has a random number specified, between 0 and n.
// Range: 0 = no spin, 10 = reasonable spin, 100 = pukeville
spin: number;
// The amount of X-axis (3D) rotation to provide to each particle.
// Each particle has a random number specified, between 0 and n.
// Range: 0 = no twist, 10 = reasonable twist, 100 = hummingbird
twist: number;
// Each particle will have a random speed assigned, contained by
// `minSpeed` and `maxSpeed`.
// This is the base speed, which is affected by `gravity`.
minSpeed: number;
maxSpeed: number;
// Each particle will have a random size applied, contained by
// `minScale` and `maxScale`. If you'd like all particles to retain
// their original size, simply provide `1` for both values.
minScale: number;
maxScale: number;
// Amount of time to spread the release of particles, in milliseconds.
emitDuration: number;
// Callback triggered when animation ends.
// NOTE: Only fires when all particles are off-canvas. Retriggering
// the confetti before it's completed will delay the handler.
onComplete?: () => void;
// This component simply creates and updates the Particles.
// The children are responsible for figuring out what to do with them.
children: (props: ChildFnProps) => React.ReactNode;
};
class Particles extends React.PureComponent<Props, State> {
static defaultProps = {
shapes: defaultShapes,
numParticles: 100,
gravity: 1000,
spin: 10,
twist: 5,
minSpeed: 225,
maxSpeed: 575,
minScale: 1,
maxScale: 1.5,
emitDuration: 1000,
};
state = {
particles: [],
};
animationFrameId: number;
componentDidUpdate(prevProps: Props, prevState: State) {
if (prevState.particles.length === 0 && this.state.particles.length > 0) {
this.tick();
}
}
componentWillUnmount() {
window.cancelAnimationFrame(this.animationFrameId);
}
generateParticles = () => {
const newParticles = range(this.props.numParticles).map(i => {
// Particles can be spread over a duration.
// Each particle should be "born" at a random time during the emit
// duration (if this value is 0, they'll all share the same birthdate).
const birth = Date.now() + random(0, this.props.emitDuration);
// Scale and Speed are specified in ranges. Select a value for this
// particle from within the range.
const speed = random(this.props.minSpeed, this.props.maxSpeed);
const scale = random(this.props.minScale, this.props.maxScale);
// Values for `spin` and `twist` are specified through props, but the
// values given represent the maximum absolute values possible.
// If `spin` is 30, that means each particle will select a random
// `spinForce` between -30 and 30.
const spinForce = this.props.spin * random(-1, 1);
const twistForce = this.props.twist * random(-1, 1);
// `currentSpin` and `currentTwist` are trackers for the current values
// as the animation progresses. Start them at `0`.
// NOTE: this does not mean that each particle will start with the same
// orientation - this is also influenced by `angle`, which is randomized.
// This represents the current deviation from the `angle`.
const currentSpin = 0;
const currentTwist = 0;
// Each particle starts along the top of the canvas, with a random
// `x` coordinate somewhere along its width.
const initialPosition = {
x: random(0, 1) * this.props.width,
y: 0,
};
const shape = sample(this.props.shapes);
const { front, back } = shape;
// ~~~ TRIGONOMETRY STUFF ~~~
// `angle` is the degree, in radians, that the shape is rotated along
// its Z-axis:
// ________
// /\ π radians \ /
// / \ -> \ /
// /______\ \/
//
const angle = random(0, 2 * Math.PI);
// `trajectory` represents the angle of the particle's movement.
// Larger numbers means the particle deviates further from its initial
// `x` coordinate.
const trajectoryVariance = random(-1, 1);
const trajectory = -Math.PI / 2 + trajectoryVariance;
// `vx` and `vy` represent the velocity across both axes, and will be
// used to compute how much a particle should move in a given frame.
const vx = Math.cos(trajectory) * speed;
const vy = Math.sin(trajectory) * speed * -1;
//
// ~~~ END TRIGONOMETRY STUFF ~~~
return {
birth,
initialPosition,
currentPosition: initialPosition,
spinForce,
twistForce,
currentSpin,
currentTwist,
angle,
scale,
vx,
vy,
front,
back,
width: front.naturalWidth,
height: front.naturalHeight,
};
});
this.setState({
particles: [...this.state.particles, ...newParticles],
});
};
tick = () => {
if (this.state.particles.length === 0) {
return;
}
this.animationFrameId = window.requestAnimationFrame(() => {
const particles = this.calculateNextPositionForParticles();
this.setState({ particles }, this.tick);
});
};
calculateNextPositionForParticles = () => {
const now = Date.now();
const { height, width } = this.props;
return this.state.particles
.map(particle => {
const age = (now - particle.birth) / 1000;
// Skip a particle if it hasn't been born yet.
if (age < 0) {
return particle;
}
const x = particle.initialPosition.x + particle.vx * age;
const y =
particle.initialPosition.y +
particle.vy * age +
(this.props.gravity * age * age) / 2;
const diameter = getDiameter(
particle.width * particle.scale,
particle.height * particle.scale
);
const isOffScreen =
x + diameter < 0 || x - diameter > width || y - diameter > height;
if (isOffScreen) {
return null;
}
// WARNING WARNING WARNING
// Mutating this.state directly here.
// This is a faux-pas, but it's important for performance.
particle.currentPosition = { x, y };
particle.currentSpin = particle.angle + particle.spinForce * age;
particle.currentTwist = particle.twistForce
? Math.cos(particle.angle + particle.twistForce * age)
: 1;
return particle;
})
.filter(particle => !!particle);
};
render() {
const { children } = this.props;
const { particles } = this.state;
return children({
// State
particles,
// Actions
generateParticles: this.generateParticles,
});
}
}
export default Particles;

View file

@ -0,0 +1,169 @@
import {
convertHexColorToRgb,
mixWithBlack,
mixWithWhite,
formatRgbColor,
} from './Confetti.helpers';
// Creates an actual <img> element. This is needed to paint a shape into an
// HTML canvas.
const createImageElement = svgString => {
// window.btoa creates a base64 encoded string. Combined with the data
// prefix, it can be used as an image `src`.
const base64ShapeString =
'data:image/svg+xml;base64,' + window.btoa(svgString);
const imageElement = new Image();
imageElement.src = base64ShapeString;
return imageElement;
};
// Each of the following shape factories returns a string representation of
// an SVG, which can be used to create an <img> element.
// TODO (josh): See if there's a way to use React components instead, just
// need to find a client-side way to get a string representation of a
// component's rendered result.
const circleShapeFactory = ({ size = 15, fill }) => `
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 10 10"
width="${size}"
height="${size}"
>
<circle
cx="5"
cy="5"
r="5"
fill="${formatRgbColor(fill)}"
/>
</svg>
`;
const triangleShapeFactory = ({ size = 16, fill }) => `
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 10 10"
width="${size}"
height="${size}"
>
<polygon
fill="${formatRgbColor(fill)}"
points="0 10 5 0 10 10"
/>
</svg>
`;
const rectangleShapeFactory = ({ width = 6, height = 12, fill }) => `
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 ${width} ${height}"
width="${width}"
height="${height}"
>
<rect
x="0"
y="0"
width="${width}"
height="${height}"
fill="${formatRgbColor(fill)}"
/>
</svg>
`;
const zigZagShapeFactory = ({ size = 20, fill }) => `
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 23.74 92.52"
width="${size}"
height="${size * 4}"
>
<polygon
fill="${formatRgbColor(fill)}"
points="17.08 31.49 3.56 29.97 10.22 0 23.74 1.52 17.08 31.49"
/>
<polygon
fill="${formatRgbColor(fill)}"
points="13.53 92.52 0 91 6.66 61.03 20.19 62.55 13.53 92.52"
/>
<polygon
fill="${formatRgbColor(mixWithWhite(fill, 0.35))}"
points="20.19 62.55 6.66 61.03 3.56 29.97 17.08 31.49 20.19 62.55"
/>
</svg>
`;
type ShapeProps = {
fill?: string;
backsideDarkenAmount?: number;
size?: number;
width?: number;
height?: number;
};
// Our base export, this generalized helper is used to create image tags
// from the props provided.
// NOTE: You probably want to use one of the preloaded helpers below
// (eg. createCircle).
export const createShape = (shape: string) => ({
fill = '#000000',
backsideDarkenAmount = 0.25,
...args
}: ShapeProps = {}) => {
// Convert fill to RGB
const fillRgb = convertHexColorToRgb(fill);
// Get the factory for the provided shape
let shapeFactory;
switch (shape) {
case 'circle': {
shapeFactory = circleShapeFactory;
break;
}
case 'triangle': {
shapeFactory = triangleShapeFactory;
break;
}
case 'rectangle': {
shapeFactory = rectangleShapeFactory;
break;
}
case 'zigZag': {
shapeFactory = zigZagShapeFactory;
break;
}
default:
throw new Error('Unrecognized shape passed to `createShape`');
}
// Create a front and back side, where the back is identical but with a
// darker colour.
const backColor = mixWithBlack(fillRgb, backsideDarkenAmount);
const frontSvgString = shapeFactory({ fill: fillRgb, ...args });
const backSvgString = shapeFactory({ fill: backColor, ...args });
// Create and return image elements for both sides.
return {
front: createImageElement(frontSvgString),
back: createImageElement(backSvgString),
};
};
export const createCircle = createShape('circle');
export const createTriangle = createShape('triangle');
export const createRectangle = createShape('rectangle');
export const createZigZag = createShape('zigZag');
export const defaultShapes = [
createZigZag({ fill: '#ca337c' }), // Pink
createZigZag({ fill: '#01d1c1' }), // Turquoise
createZigZag({ fill: '#f4d345' }), // Yellow
createCircle({ fill: '#63d9ea' }), // Blue
createCircle({ fill: '#ed5fa6' }), // Pink
createCircle({ fill: '#aa87ff' }), // Purple
createCircle({ fill: '#26edd5' }), // Turquoise
createTriangle({ fill: '#ed5fa6' }), // Pink
createTriangle({ fill: '#aa87ff' }), // Purple
createTriangle({ fill: '#26edd5' }), // Turquoise
];

View file

@ -0,0 +1,3 @@
/* Source: https://github.com/joshwcomeau/react-europe-talk-2018 */
export { default } from './Confetti';

View file

@ -0,0 +1,22 @@
export type Particle = {
birth: number;
initialPosition: [number, number];
currentPosition: [number, number];
spinForce: number;
twistForce: number;
currentSpin: number;
currentTwist: number;
angle: number;
scale: number;
vx: number;
vy: number;
front: HTMLElement;
back: HTMLElement;
width: number;
height: number;
};
export type Shape = {
front: HTMLImageElement;
back: HTMLImageElement;
};

View file

@ -0,0 +1,100 @@
import * as React from 'react';
import Transition from '../Transition';
const options = ['Not Started', 'Reading', 'Practicing', 'Complete', 'Skipped'];
const MarkCompleteButton = ({
state,
onChange,
dropdownAbove,
}: {
state: string;
onChange: Function;
dropdownAbove?: boolean;
}) => {
const [show, setShow] = React.useState(false);
const handleSelect = option => {
setShow(false);
onChange(option);
};
const ref = React.useRef();
React.useEffect(() => {
const handleClick = e => {
// @ts-ignore
if (ref.current.contains(e.target)) return;
setShow(false);
};
document.addEventListener('mousedown', handleClick);
return () => document.removeEventListener('mousedown', handleClick);
}, []);
return (
<div className="relative inline-block text-left" ref={ref}>
<div>
<span className="rounded-md shadow-sm">
<button
type="button"
className="inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-sm leading-5 font-medium text-gray-700 hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-gray-50 active:text-gray-800 transition ease-in-out duration-150"
id="options-menu"
aria-haspopup="true"
aria-expanded="true"
onClick={() => setShow(!show)}
>
{state}
<svg
className="-mr-1 ml-2 h-5 w-5"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
</button>
</span>
</div>
<Transition
show={show}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<div
className={`${
dropdownAbove
? 'origin-bottom-right bottom-0 mb-12'
: 'origin-top-right'
} right-0 absolute z-10 mt-2 w-32 rounded-md shadow-lg`}
>
<div className="rounded-md bg-white shadow-xs">
<div
className="py-1"
role="menu"
aria-orientation="vertical"
aria-labelledby="options-menu"
>
{options.map(option => (
<button
onClick={() => handleSelect(option)}
className="block w-full text-left px-4 py-2 text-sm leading-5 text-gray-700 hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus:bg-gray-100 focus:text-gray-900"
role="menuitem"
>
{option}
</button>
))}
</div>
</div>
</div>
</Transition>
</div>
);
};
export default MarkCompleteButton;

View file

@ -0,0 +1,44 @@
import * as React from 'react';
import Confetti from '../Confetti';
import useWindowDimensions from '../../hooks/useWindowDimensions';
const ModuleConfetti = ({ show, onDone }) => {
let config = {
numParticles: 100,
gravity: 250,
speed: 250,
scale: 0.5,
spin: 0,
twist: 0,
};
const { numParticles, gravity, speed, scale, spin, twist } = config;
const { height, width } = useWindowDimensions();
React.useEffect(() => {
let timeout = null;
if (show) timeout = setTimeout(() => onDone(), 3000);
if (timeout) return () => clearTimeout(timeout);
}, [show]);
if (!show) return null;
return (
<div className="fixed inset-0 pointer-events-none z-20">
<Confetti
width={width}
height={height}
makeItRainOn="mount"
emitDuration={1000}
numParticles={numParticles}
gravity={gravity}
minSpeed={speed}
maxSpeed={speed * 3}
minScale={scale}
maxScale={scale * 2}
spin={spin}
twist={twist}
/>
</div>
);
};
export default ModuleConfetti;

View file

@ -1,17 +1,19 @@
import * as React from 'react';
import Transition from './Transition';
import { useState } from 'react';
import Transition from '../Transition';
import { useRef, useState } from 'react';
// @ts-ignore
import logo from '../assets/logo.svg';
import { ModuleFrequency, ModuleLinkInfo } from '../module';
import logo from '../../assets/logo.svg';
import { ModuleFrequency, ModuleLinkInfo } from '../../module';
import { Link } from 'gatsby';
import ModuleOrdering, {
divisionLabels,
isModuleOrderingGroup,
ModuleOrderingItem,
} from '../../content/ordering';
import Dots from './Dots';
import ReportIssueSlideover from './ReportIssueSlideover';
} from '../../../content/ordering';
import Dots from '../Dots';
import ReportIssueSlideover from '../ReportIssueSlideover';
import MarkCompleteButton from './MarkCompleteButton';
import ModuleConfetti from './ModuleConfetti';
const Frequency = ({ frequency }: { frequency: ModuleFrequency }) => {
const textColors = [
@ -331,6 +333,8 @@ export default function ModuleLayout({
const [isMobileNavOpen, setIsMobileNavOpen] = useState(false);
const [isReportIssueActive, setIsReportIssueActive] = useState(false);
const [isGetHelpActive, setIsGetHelpActive] = useState(false);
const [isConfettiActive, setIsConfettiActive] = useState(false);
const [moduleProgress, setModuleProgress] = useState('Not Complete'); // todo initialize from localstorage?
const navLinks: NavLinkItem[] = React.useMemo(() => {
const getLinks = (item: ModuleOrderingItem): NavLinkItem => {
@ -363,9 +367,23 @@ export default function ModuleLayout({
return null;
}, [navLinks]);
const handleCompletionChange = progress => {
if (moduleProgress === progress) return;
setModuleProgress(progress);
if (
moduleProgress !== 'Complete' &&
(progress === 'Practicing' || progress === 'Complete')
)
setIsConfettiActive(true);
};
return (
<>
<Transition show={isMobileNavOpen}>
<ModuleConfetti
show={isConfettiActive}
onDone={() => setIsConfettiActive(false)}
/>
<Transition show={isMobileNavOpen} timeout={300}>
<div className="lg:hidden">
<div className="fixed inset-0 flex z-40">
<Transition
@ -511,20 +529,27 @@ export default function ModuleLayout({
</h1>
<p className={`text-gray-500`}>Author: {module.author}</p>
</div>
{/*<div className="hidden lg:flex-shrink-0 lg:flex ml-4">*/}
{/* <span className="shadow-sm rounded-md">*/}
{/* <button*/}
{/* type="button"*/}
{/* className="inline-flex items-center px-4 py-2 border border-gray-300 text-sm leading-5 font-medium rounded-md text-gray-700 bg-white hover:text-gray-500 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 active:text-gray-800 active:bg-gray-50 transition duration-150 ease-in-out"*/}
{/* >*/}
{/* Mark Complete*/}
{/* </button>*/}
{/* </span>*/}
{/*</div>*/}
<div className="hidden lg:flex-shrink-0 lg:flex ml-4">
<MarkCompleteButton
state={moduleProgress}
onChange={handleCompletionChange}
/>
</div>
</div>
</div>
{children}
<h3 className="text-lg leading-6 font-medium text-gray-900 text-center mb-8 border-t border-gray-200 pt-8">
Module Progress:
<span className="ml-4">
<MarkCompleteButton
onChange={handleCompletionChange}
state={moduleProgress}
dropdownAbove
/>
</span>
</h3>
<div className="border-t border-gray-200 pt-4">
<CompactNav
division={division}

View file

@ -21,7 +21,7 @@ export default function ReportIssueSlideover({
else setIssueLocation('');
}, [activeModule]);
return (
<Transition show={isOpen}>
<Transition show={isOpen} timeout={700}>
<div className="fixed inset-0 overflow-hidden">
<div className="absolute inset-0 overflow-hidden">
<Transition

View file

@ -24,6 +24,8 @@ function CSSTransition({
leaveTo = '',
appear,
children,
isParent,
timeout,
}) {
const enterClasses = enter.split(' ').filter(s => s.length);
const enterFromClasses = enterFrom.split(' ').filter(s => s.length);
@ -45,9 +47,20 @@ function CSSTransition({
appear={appear}
unmountOnExit
in={show}
addEndListener={(node, done) => {
node.addEventListener('transitionend', done, false);
}}
addEndListener={
isParent && timeout
? undefined
: (node, done) => {
node.addEventListener(
'transitionend',
e => {
if (node === e.target) done();
},
false
);
}
}
timeout={isParent ? timeout : undefined}
onEnter={node => {
addClasses(node, [...enterClasses, ...enterFromClasses]);
}}
@ -85,6 +98,7 @@ function Transition({ show, appear, ...rest }: any) {
<CSSTransition
appear={parent.appear || !parent.isInitialRender}
show={parent.show}
isParent={false}
{...rest}
/>
);
@ -102,7 +116,7 @@ function Transition({ show, appear, ...rest }: any) {
>
{/*
// @ts-ignore*/}
<CSSTransition appear={appear} show={show} {...rest} />
<CSSTransition appear={appear} show={show} isParent={true} {...rest} />
</TransitionContext.Provider>
);
}

View file

@ -52,7 +52,7 @@ export function ProblemsListComponent(props: ProblemsListComponentProps) {
</div>
</div>
<Transition show={showModal}>
<Transition show={showModal} timeout={300}>
<div className="fixed z-10 bottom-0 inset-x-0 px-4 pb-6 sm:inset-0 sm:p-0 sm:flex sm:items-center sm:justify-center">
<Transition
enter="ease-out duration-300"

View file

@ -0,0 +1,44 @@
import { useState, useEffect } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height,
};
}
function debounce(func, wait, immediate = false) {
var timeout;
return function () {
var context = this,
args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
const efficientResize = debounce(handleResize, 250);
window.addEventListener('resize', efficientResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}

View file

@ -2,7 +2,6 @@ import * as React from 'react';
import { Link, PageProps } from 'gatsby';
import Layout from '../components/layout';
import SEO from '../components/seo';
import CodeBlock from '../components/markdown/CodeBlock';
export default function LicensePage(props: PageProps) {
return (

View file

@ -7,7 +7,7 @@ import { divisionLabels } from '../../content/ordering';
import { graphqlToModuleInfo, graphqlToModuleLinks } from '../utils';
import SEO from '../components/seo';
import { KatexRenderer } from '../components/markdown/KatexRenderer';
import ModuleLayout from '../components/ModuleLayout';
import ModuleLayout from '../components/ModuleLayout/ModuleLayout';
const renderPrerequisite = prerequisite => {
return <li key={prerequisite}>{prerequisite}</li>;