Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 0 additions & 14 deletions app/javascript/components/common/Wrapper.tsx

This file was deleted.

34 changes: 6 additions & 28 deletions app/javascript/components/modals/Modal.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React from 'react'
import { Aria, default as ReactModal, Props } from 'react-modal'
import { Icon } from '../common/Icon'
import { Wrapper } from '../common/Wrapper'
import { useAppTranslation } from '@/i18n/useAppTranslation'
import { ActiveBackground, Confetti } from '@exercism/active-background'
import { ConfettiBackground } from './confetti/ConfettiBackground'

type Theme = 'light' | 'dark' | 'unset'
export type ModalProps = Omit<Props, 'isOpen' | 'onRequestClose'> & {
Expand Down Expand Up @@ -52,32 +51,11 @@ export function Modal({
overlayClassName={overlayClassNames.join(' ')}
overlayElement={(props, contentElement) => (
<div {...props}>
<Wrapper
condition={celebratory}
wrapper={(children) => (
<ActiveBackground
Pattern={Confetti}
patternOptions={{
colorPairs: [
['#df0049', '#660671'],
['#00e857', '#005291'],
['#2bebbc', '#05798a'],
['#ffd200', '#b06c00'],
],
confettiPaperCount: 100,
confettiRibbonCount: 40,
speed: 30,
}}
>
{children}
</ActiveBackground>
)}
>
<div className={`--modal-container ${containerClassName}`}>
{closeButton ? <CloseButton onClose={onClose} /> : null}
{contentElement}
</div>
</Wrapper>
{celebratory ? <ConfettiBackground /> : null}
<div className={`--modal-container ${containerClassName}`}>
{closeButton ? <CloseButton onClose={onClose} /> : null}
{contentElement}
</div>
</div>
)}
{...props}
Expand Down
125 changes: 125 additions & 0 deletions app/javascript/components/modals/confetti/Confetti.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// Copied from @exercism/active-background 0.6.2
// (https://github.com/exercism/react-active-background, MIT, Copyright (c) 2021
// Exercism) so the website no longer depends on that package. See
// ConfettiBackground.tsx for the component that draws it.
import { ConfettiPaper } from './ConfettiPaper'
import { ConfettiRibbon } from './ConfettiRibbon'

type ColorPair = [string, string]

export interface ConfettiOptions {
speed?: number
duration?: number
confettiPaperCount?: number
scaleConfettiCount?: boolean
confettiRibbonCount?: number
colorPairs?: ColorPair[]
}

const SPEED = 50
const DEFAULT_CONFETTI_PAPERS = 50
const DEFAULT_CONFETTI_RIBBONS = 10
const DEFAULT_SCALE_CONFETTI_COUNT = true

const COLORS: ColorPair[] = [
['#df0049', '#660671'],
['#00e857', '#005291'],
['#2bebbc', '#05798a'],
['#ffd200', '#b06c00'],
]

export class Confetti {
private readonly canvas: HTMLCanvasElement
private readonly context: CanvasRenderingContext2D | null

private readonly ratio: number
public readonly width: number
public readonly height: number

private readonly speed: number
private readonly duration: number
private readonly confettiPapers: ConfettiPaper[]
private readonly confettiRibbons: ConfettiRibbon[]
private readonly colorPairs: ColorPair[]

private animationFrameRequestId: number | null

constructor(canvas: HTMLCanvasElement, options: ConfettiOptions = {}) {
this.canvas = canvas
this.context = canvas.getContext('2d')

this.speed = options?.speed ?? SPEED
this.duration = options?.duration ?? 1.0 / this.speed

this.ratio = window.devicePixelRatio
this.width = canvas.offsetWidth * this.ratio
this.height = canvas.offsetHeight * this.ratio

this.colorPairs = options?.colorPairs ?? COLORS

let confettiPaperCount =
options?.confettiPaperCount ?? DEFAULT_CONFETTI_PAPERS

if (options?.scaleConfettiCount ?? DEFAULT_SCALE_CONFETTI_COUNT) {
confettiPaperCount = Math.round(confettiPaperCount / this.ratio)
}

const getRandomColorPair = getRandomColors(this.colorPairs)

this.confettiPapers = [...new Array(confettiPaperCount)].map(() => {
return new ConfettiPaper({
parent: this,
fetchColors: getRandomColorPair,
})
})

let confettiRibbonCount =
options?.confettiRibbonCount ?? DEFAULT_CONFETTI_RIBBONS

this.confettiRibbons = [...new Array(confettiRibbonCount)].map(() => {
return new ConfettiRibbon({
parent: this,
fetchColors: getRandomColorPair,
})
})

this.animationFrameRequestId = null
}

public start(): void {
this.animationFrameRequestId = requestAnimationFrame(this.render.bind(this))
}

public stop(): void {
if (this.animationFrameRequestId) {
cancelAnimationFrame(this.animationFrameRequestId)
}
}

public render(): void {
if (!this.context) {
return
}

this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)

for (const confettiPaper of this.confettiPapers) {
confettiPaper.update(this.duration)
confettiPaper.draw(this.context)
}

for (const confettiRibbon of this.confettiRibbons) {
confettiRibbon.update(this.duration)
confettiRibbon.draw(this.context)
}

this.animationFrameRequestId = requestAnimationFrame(this.render.bind(this))
}
}

function getRandomColors(colors: ColorPair[] = COLORS): () => ColorPair {
return function () {
const randomIndex = Math.round(Math.random() * (colors.length - 1))
return colors[randomIndex]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React, { useEffect, useRef } from 'react'
import { Confetti, type ConfettiOptions } from './Confetti'

const OPTIONS: ConfettiOptions = {
colorPairs: [
['#df0049', '#660671'],
['#00e857', '#005291'],
['#2bebbc', '#05798a'],
['#ffd200', '#b06c00'],
],
confettiPaperCount: 100,
confettiRibbonCount: 40,
speed: 30,
}

const prefersReducedMotion = () =>
window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false

// Confetti that keeps falling behind a celebratory modal until it closes.
// It fills its parent element and restarts whenever the parent resizes.
export function ConfettiBackground(): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null)

useEffect(() => {
const canvas = canvasRef.current
const parent = canvas?.parentElement
if (!canvas || !parent || prefersReducedMotion()) return

let confetti: Confetti | null = null

const start = () => {
confetti?.stop()

// The canvas is sized in CSS pixels, without devicePixelRatio, as it was
// in @exercism/active-background. Confetti spreads its pieces over a
// devicePixelRatio-scaled area, so scaling the canvas as well would make
// the confetti several times denser on retina screens than it has been.
canvas.style.width = `${parent.offsetWidth}px`
canvas.style.height = `${parent.offsetHeight}px`
canvas.width = parent.offsetWidth
canvas.height = parent.offsetHeight

confetti = new Confetti(canvas, OPTIONS)
confetti.start()
}

// The observer also calls start once straight away
const observer = new ResizeObserver(start)
observer.observe(parent)

return () => {
observer.disconnect()
confetti?.stop()
}
}, [])

return (
<canvas
ref={canvasRef}
aria-hidden="true"
className="absolute top-0 left-0 pointer-events-none"
/>
)
}
119 changes: 119 additions & 0 deletions app/javascript/components/modals/confetti/ConfettiPaper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import type { Confetti } from './Confetti'
import { Vector2D } from './Vector'

type ConfettiPaperConfig = {
parent: Confetti
fetchColors: () => string[]
}

const DEG_360_IN_RAD = 2 * Math.PI
const DEG_90_IN_RAD = Math.PI / 2
const DEG_45_IN_RAD = Math.PI / 4

const ROTATION_SPEED_VARIANCE = 600
const ROTATION_SPEED_MINIMUM = 800
const OSCILLATION_SPEED_VARIANCE = 1.5
const OSCILLATION_SPEED_MINIMUM = 0.5
const X_VELOCITY = 40
const Y_VELOCITY_VARIANCE = 60
const Y_VELOCITY_MINIMUM = 50

type Position = { x: number; y: number }
type Positions = readonly Position[]

export class ConfettiPaper {
private readonly position: Vector2D
private readonly rotationSpeed: number
private readonly angle: number
private cosRotation: number
private rotation: number
private readonly size: number
private readonly oscillationSpeed: number
private readonly xVelocity: number
private readonly yVelocity: number
private readonly corners: Vector2D[]
private time: number
private readonly frontColor: string
private readonly backColor: string

private readonly parent: Confetti
private readonly fetchColors: () => string[]

constructor(config: ConfettiPaperConfig) {
this.parent = config.parent
this.fetchColors = config.fetchColors

this.position = new Vector2D(
Math.random() * this.parent.width,
Math.random() * this.parent.height
)

this.cosRotation = 1.0
this.angle = Math.random() * DEG_360_IN_RAD
this.rotation = Math.random() * DEG_360_IN_RAD
this.rotationSpeed =
Math.random() * ROTATION_SPEED_VARIANCE + ROTATION_SPEED_MINIMUM

this.oscillationSpeed =
Math.random() * OSCILLATION_SPEED_VARIANCE + OSCILLATION_SPEED_MINIMUM

this.xVelocity = X_VELOCITY
this.yVelocity = Math.random() * Y_VELOCITY_VARIANCE + Y_VELOCITY_MINIMUM
this.time = Math.random()

this.corners = computeCorners(this.angle)

const [frontColor, backColor] = this.fetchColors()
this.frontColor = frontColor
this.backColor = backColor
this.size = 5.0
}

public update(dt: number): void {
this.time += dt
this.rotation += this.rotationSpeed * dt
this.cosRotation = Math.cos((this.rotation * Math.PI) / 180)

this.position.x +=
Math.cos(this.time * this.oscillationSpeed) * this.xVelocity * dt
this.position.y += this.yVelocity * dt

// Reset paper to the top of the screen
if (this.position.y > this.parent.height) {
this.position.x = Math.random() * this.parent.width
this.position.y = 0
}
}

public draw(context: CanvasRenderingContext2D): void {
if (this.cosRotation > 0) {
context.fillStyle = this.frontColor
} else {
context.fillStyle = this.backColor
}

const [firstCorner, ...remainingCorners] = this.computeCornerDrawPositions()
context.beginPath()
context.moveTo(firstCorner.x, firstCorner.y)
remainingCorners.forEach(({ x, y }) => context.lineTo(x, y))
context.closePath()
context.fill()
}

private computeCornerDrawPositions(): Positions {
return this.corners.map(({ x, y }, i) => {
x = this.position.x + x * this.size
y = this.position.y + y * this.size * this.cosRotation

return { x, y }
})
}
}

function computeCorners(angle: number) {
return [0, 1, 2, 3].map((i) => {
const dx = Math.cos(angle + (i * DEG_90_IN_RAD + DEG_45_IN_RAD))
const dy = Math.sin(angle + (i * DEG_90_IN_RAD + DEG_45_IN_RAD))
return new Vector2D(dx, dy)
})
}
Loading
Loading