Winter Snow
Ambient snowfall with real-time 1D heightfield snowdrifts on any element edge and deterministic procedural frost crystals.
canvas particles seasonal zero-dependency
Live previewstable
Accumulates smoothly along any [data-snow-pile] surface
Grows deterministic frost crystals on [data-snow-frost] edges
This Computersolstice-ui
Ask anything, @ to mention, / for actions
Winter Snow (@solstice-ui/react)↑
Copies self-contained TypeScript & React source directly into your repo
npx shadcn@latest add https://solstice-ui.pages.dev/r/winter-snow.jsonSource code
import { WinterSnow } from '@solstice-ui/react/winter-snow';
export function App() {
return (
<main>
<WinterSnow storageKey="solstice-winter-snow" />
<div data-snow-pile className="rounded-2xl border p-4">
<div data-snow-frost="medium" className="relative overflow-hidden rounded-xl p-4">
Your content stays interactive under the overlay.
</div>
</div>
</main>
);
}'use client';
import {
createWinterSnow,
type FrostIntensity,
type WinterSnowController,
type WinterSnowOptions,
type WinterSnowTheme,
} from '@/lib/solstice-ui/winter-snow';
import { type RefObject, useCallback, useEffect, useRef, useState } from 'react';
export type { FrostIntensity, WinterSnowController, WinterSnowOptions, WinterSnowTheme };
export interface UseWinterSnowOptions extends Omit<WinterSnowOptions, 'container'> {
/** Ref to a bounding container. Omit for full-viewport snowfall. */
containerRef?: RefObject<HTMLElement | null>;
/** Controlled active state. */
enabled?: boolean;
/** Initial active state when uncontrolled. Default: true. */
defaultEnabled?: boolean;
/** Callback fired when active state changes. */
onEnabledChange?: (enabled: boolean) => void;
/** Optional localStorage key to remember the user's preference. */
storageKey?: string;
}
export interface UseWinterSnowReturn {
enabled: boolean;
setEnabled: (next: boolean) => void;
toggle: () => void;
reset: () => void;
controllerRef: RefObject<WinterSnowController | null>;
}
export function useWinterSnow({
containerRef,
enabled: controlledEnabled,
defaultEnabled = true,
onEnabledChange,
storageKey,
density = 85,
speed = 1,
wind = 1,
maxPileHeight = 9.5,
cornerInset = 18,
frostIntensity = 'medium',
seedInitialPile = true,
pileSelector = '[data-snow-pile]',
frostSelector = '[data-snow-frost]',
theme = 'auto',
respectReducedMotion = true,
zIndex = 40,
}: UseWinterSnowOptions = {}): UseWinterSnowReturn {
const [uncontrolledEnabled, setUncontrolledEnabled] = useState<boolean>(defaultEnabled);
const controllerRef = useRef<WinterSnowController | null>(null);
const enabled = controlledEnabled ?? uncontrolledEnabled;
// Hydrate persisted user preference on client mount when uncontrolled
useEffect(() => {
if (!storageKey || controlledEnabled !== undefined || typeof window === 'undefined') return;
try {
const stored = window.localStorage.getItem(storageKey);
if (stored === '0' || stored === 'false') {
setUncontrolledEnabled(false);
} else if (stored === '1' || stored === 'true') {
setUncontrolledEnabled(true);
}
} catch {
// Ignore storage access errors in private browsing modes
}
}, [storageKey, controlledEnabled]);
const setEnabled = useCallback(
(next: boolean) => {
if (controlledEnabled === undefined) {
setUncontrolledEnabled(next);
}
if (storageKey && typeof window !== 'undefined') {
try {
window.localStorage.setItem(storageKey, next ? '1' : '0');
} catch {
// Ignore storage write errors
}
}
onEnabledChange?.(next);
},
[controlledEnabled, onEnabledChange, storageKey],
);
const toggle = useCallback(() => {
setEnabled(!enabled);
}, [enabled, setEnabled]);
const reset = useCallback(() => {
controllerRef.current?.reset();
}, []);
const latestConfigRef = useRef({
density,
speed,
wind,
maxPileHeight,
cornerInset,
frostIntensity,
theme,
zIndex,
enabled,
});
latestConfigRef.current = {
density,
speed,
wind,
maxPileHeight,
cornerInset,
frostIntensity,
theme,
zIndex,
enabled,
};
// Mount / unmount the underlying zero-dependency engine
useEffect(() => {
const initial = latestConfigRef.current;
const controller = createWinterSnow({
container: containerRef?.current ?? null,
density: initial.density,
speed: initial.speed,
wind: initial.wind,
maxPileHeight: initial.maxPileHeight,
cornerInset: initial.cornerInset,
frostIntensity: initial.frostIntensity,
seedInitialPile,
pileSelector,
frostSelector,
theme: initial.theme,
respectReducedMotion,
zIndex: initial.zIndex,
});
controllerRef.current = controller;
if (initial.enabled) {
controller.start();
}
return () => {
controller.destroy();
controllerRef.current = null;
};
}, [containerRef, pileSelector, frostSelector, seedInitialPile, respectReducedMotion]);
// Sync live reactive options without recreating the canvas
useEffect(() => {
controllerRef.current?.updateOptions({
density,
speed,
wind,
maxPileHeight,
cornerInset,
frostIntensity,
theme,
zIndex,
});
}, [density, speed, wind, maxPileHeight, cornerInset, frostIntensity, theme, zIndex]);
// Sync active play/pause state
useEffect(() => {
const controller = controllerRef.current;
if (!controller) return;
if (enabled) {
controller.start();
} else {
controller.stop();
}
}, [enabled]);
return { enabled, setEnabled, toggle, reset, controllerRef };
}
export interface WinterSnowProps extends UseWinterSnowOptions {
/** Render the floating "Hide snow" / "Show snow" capsule toggle. Default: true. */
showToggle?: boolean;
/** Custom labels for the floating toggle button. */
toggleLabel?: {
hide?: string;
show?: string;
};
/** Extra classes merged onto the floating toggle button. */
toggleClassName?: string;
/** Incrementing number that triggers snowdrift reset from a parent control. */
resetSignal?: number;
}
export function WinterSnow({
showToggle = true,
toggleLabel,
toggleClassName,
resetSignal,
...options
}: WinterSnowProps) {
const { enabled, toggle, reset } = useWinterSnow(options);
const lastResetRef = useRef(resetSignal);
useEffect(() => {
if (resetSignal !== undefined && resetSignal !== lastResetRef.current) {
lastResetRef.current = resetSignal;
reset();
}
}, [resetSignal, reset]);
if (!showToggle) return null;
const hideText = toggleLabel?.hide ?? 'Hide snow';
const showText = toggleLabel?.show ?? 'Show snow';
const positionClass = options.containerRef ? 'absolute top-4 right-4' : 'fixed top-5 right-5';
return (
<button
type="button"
onClick={toggle}
aria-pressed={enabled}
className={[
'solstice-snow-toggle z-50 inline-flex items-center gap-2 rounded-full border border-slate-900/10 bg-white/90 px-3.5 py-1.5 text-[13px] font-medium text-slate-900 shadow-sm backdrop-blur-md transition hover:bg-white hover:shadow active:scale-[0.97] dark:border-sky-100/15 dark:bg-slate-900/85 dark:text-slate-100 dark:hover:bg-slate-900',
positionClass,
toggleClassName ?? '',
]
.filter(Boolean)
.join(' ')}
>
<span>{enabled ? hideText : showText}</span>
<span aria-hidden="true" className="text-sm leading-none opacity-65">
{enabled ? '×' : '❄'}
</span>
</button>
);
}
export type FrostIntensity = 'none' | 'light' | 'medium' | 'heavy';
export interface RenderFrostOptions {
intensity: FrostIntensity;
resolvedTheme: 'light' | 'dark';
seed?: number;
}
const INTENSITY_SCALE: Record<FrostIntensity, number> = {
none: 0,
light: 0.55,
medium: 1.0,
heavy: 1.45,
};
export function parseFrostIntensity(
attrValue: string | null,
fallback: FrostIntensity,
): FrostIntensity {
if (
attrValue === 'none' ||
attrValue === 'light' ||
attrValue === 'medium' ||
attrValue === 'heavy'
) {
return attrValue;
}
return fallback;
}
export function renderFrostOverlay(
canvas: HTMLCanvasElement,
width: number,
height: number,
dpr: number,
options: RenderFrostOptions,
): void {
const ctx = canvas.getContext('2d');
if (!ctx) return;
const w = Math.max(1, Math.round(width));
const h = Math.max(1, Math.round(height));
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
const scale = INTENSITY_SCALE[options.intensity];
if (scale <= 0) return;
const isDark = options.resolvedTheme === 'dark';
const glowRgb = isDark ? '205, 228, 255' : '180, 212, 245';
const branchRgb = isDark ? '218, 236, 255' : '126, 174, 224';
const grainRgb = isDark ? '224, 240, 255' : '142, 188, 232';
const glowSpots = [
{ x: w, y: 0, r: 165, a: 0.32 * scale },
{ x: w, y: h, r: 155, a: 0.28 * scale },
{ x: w * 0.86, y: h * 0.5, r: 140, a: 0.14 * scale },
{ x: 0, y: h, r: 105, a: 0.22 * scale },
{ x: 0, y: 0, r: 65, a: 0.09 * scale },
];
for (const spot of glowSpots) {
const g = ctx.createRadialGradient(spot.x, spot.y, 0, spot.x, spot.y, spot.r);
g.addColorStop(0, `rgba(${glowRgb}, ${Math.min(0.55, spot.a)})`);
g.addColorStop(0.5, `rgba(${glowRgb}, ${Math.min(0.32, spot.a * 0.45)})`);
g.addColorStop(1, `rgba(${glowRgb}, 0)`);
ctx.fillStyle = g;
ctx.fillRect(0, 0, w, h);
}
let seed = options.seed ?? 4219;
const rand = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
function drawCrystalBranch(
x: number,
y: number,
angle: number,
len: number,
depth: number,
alpha: number,
): void {
if (depth <= 0 || len < 4 || !ctx) return;
const x2 = x + Math.cos(angle) * len;
const y2 = y + Math.sin(angle) * len;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x2, y2);
ctx.strokeStyle = `rgba(${branchRgb}, ${Math.min(0.75, alpha * scale)})`;
ctx.lineWidth = Math.max(0.45, depth * 0.36);
ctx.stroke();
const subCount = 2 + (rand() > 0.45 ? 1 : 0);
for (let i = 0; i < subCount; i++) {
const t = 0.35 + (i / subCount) * 0.55;
const bx = x + (x2 - x) * t;
const by = y + (y2 - y) * t;
const dir = i % 2 === 0 ? 1 : -1;
const spread = 0.42 + rand() * 0.32;
drawCrystalBranch(
bx,
by,
angle + dir * spread,
len * (0.42 + rand() * 0.2),
depth - 1,
alpha * 0.72,
);
}
}
const topBranches = Math.round(14 * scale);
for (let i = 0; i < topBranches; i++) {
const startX = w - rand() * Math.min(145, w * 0.35);
const startY = rand() * 10;
const angle = Math.PI * (0.38 + rand() * 0.35);
drawCrystalBranch(startX, startY, angle, 20 + rand() * 32, 3, 0.26 + rand() * 0.14);
}
const rightBranches = Math.round(10 * scale);
for (let i = 0; i < rightBranches; i++) {
const startX = w - 2;
const startY = rand() * h;
const angle = Math.PI + (rand() - 0.5) * 0.9;
drawCrystalBranch(startX, startY, angle, 18 + rand() * 30, 3, 0.24 + rand() * 0.14);
}
const bottomLeftBranches = Math.round(6 * scale);
for (let i = 0; i < bottomLeftBranches; i++) {
const startX = rand() * Math.min(54, w * 0.2);
const startY = h - 2;
const angle = -Math.PI * (0.25 + rand() * 0.35);
drawCrystalBranch(startX, startY, angle, 16 + rand() * 24, 3, 0.2 + rand() * 0.12);
}
const grainCount = Math.round(380 * scale);
for (let i = 0; i < grainCount; i++) {
let px: number;
let py: number;
let distFactor: number;
if (rand() < 0.76) {
const span = Math.min(185, w * 0.42);
const rx = rand() ** 2.2 * span;
px = w - rx;
py = rand() * h;
distFactor = 1 - rx / Math.max(1, span);
} else {
const spanX = Math.min(95, w * 0.25);
const spanY = Math.min(65, h * 0.65);
const lx = rand() ** 2.1 * spanX;
const ly = rand() ** 1.8 * spanY;
px = lx;
py = h - ly;
distFactor = (1 - lx / Math.max(1, spanX)) * (1 - ly / Math.max(1, spanY));
}
const r = 0.5 + rand() * 1.1;
ctx.beginPath();
ctx.arc(px, py, r, 0, Math.PI * 2);
ctx.fillStyle = `rgba(${grainRgb}, ${Math.min(0.65, (0.1 + distFactor * 0.3) * scale)})`;
ctx.fill();
}
}
import { type FrostIntensity, parseFrostIntensity, renderFrostOverlay } from './frost';
import {
createHeightfield,
depositSnowAt,
drawSnowPile,
type PileRect,
resampleHeightfield,
} from './pile';
export type { FrostIntensity } from './frost';
export {
createHeightfield,
depositSnowAt,
drawSnowPile,
edgeTaper,
resampleHeightfield,
smoothHeightfield,
} from './pile';
export type WinterSnowTheme = 'auto' | 'light' | 'dark';
export interface WinterSnowOptions {
/** Optional bounding container. Defaults to full-viewport fixed overlay on document.body. */
container?: HTMLElement | null;
/** Number of active snow particles. Default: 85. */
density?: number;
/** Fall speed multiplier. Default: 1. */
speed?: number;
/** Horizontal breeze amplitude multiplier. Default: 1. */
wind?: number;
/** Maximum accumulated snowdrift height in pixels. Default: 9.5. */
maxPileHeight?: number;
/** Corner inset (px) where snowdrifts smoothly taper off. Default: 18. */
cornerInset?: number;
/** Default frost overlay intensity on [data-snow-frost] targets. Default: 'medium'. */
frostIntensity?: FrostIntensity;
/** Seed a gentle initial snow layer on mount. Default: true. */
seedInitialPile?: boolean;
/** Selector for elements that accumulate snow along their top edge. Default: '[data-snow-pile]'. */
pileSelector?: string;
/** Selector for elements that receive procedural edge frost. Default: '[data-snow-frost]'. */
frostSelector?: string;
/** Visual color palette. Default: 'auto'. */
theme?: WinterSnowTheme;
/** Automatically disable animation when prefers-reduced-motion is active. Default: true. */
respectReducedMotion?: boolean;
/** Z-index for the snow canvas overlay. Default: 40. */
zIndex?: number;
}
export interface WinterSnowController {
start(): void;
stop(): void;
toggle(nextEnabled?: boolean): boolean;
reset(): void;
syncTargets(): void;
updateOptions(partial: Partial<Omit<WinterSnowOptions, 'container'>>): void;
isRunning(): boolean;
destroy(): void;
}
interface Snowflake {
x: number;
y: number;
r: number;
vy: number;
vx: number;
phase: number;
freq: number;
amp: number;
alpha: number;
}
interface PileTarget {
el: HTMLElement;
rect: PileRect;
heights: Float32Array;
}
interface FrostTarget {
el: HTMLElement;
canvas: HTMLCanvasElement;
seed: number;
}
const SAMPLE_STEP = 3;
function resolveTheme(mode: WinterSnowTheme, container?: HTMLElement | null): 'light' | 'dark' {
if (mode === 'light' || mode === 'dark') return mode;
if (typeof document !== 'undefined') {
const scopedTheme = container?.closest('[data-theme]')?.getAttribute('data-theme');
if (scopedTheme === 'dark') return 'dark';
if (scopedTheme === 'light') return 'light';
const root = document.documentElement;
if (root.classList.contains('dark') || root.getAttribute('data-theme') === 'dark') {
return 'dark';
}
}
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
return 'light';
}
function prefersReducedMotion(): boolean {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false;
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}
export function createWinterSnow(initialOptions: WinterSnowOptions = {}): WinterSnowController {
let options: Required<Omit<WinterSnowOptions, 'container'>> & {
container: HTMLElement | null;
} = {
container: initialOptions.container ?? null,
density: initialOptions.density ?? 85,
speed: initialOptions.speed ?? 1,
wind: initialOptions.wind ?? 1,
maxPileHeight: initialOptions.maxPileHeight ?? 9.5,
cornerInset: initialOptions.cornerInset ?? 18,
frostIntensity: initialOptions.frostIntensity ?? 'medium',
seedInitialPile: initialOptions.seedInitialPile ?? true,
pileSelector: initialOptions.pileSelector ?? '[data-snow-pile]',
frostSelector: initialOptions.frostSelector ?? '[data-snow-frost]',
theme: initialOptions.theme ?? 'auto',
respectReducedMotion: initialOptions.respectReducedMotion ?? true,
zIndex: initialOptions.zIndex ?? 40,
};
const isScoped = Boolean(options.container);
const host = options.container ?? (typeof document !== 'undefined' ? document.body : null);
let destroyed = false;
let running = false;
let rafId: number | null = null;
let lastTime = 0;
let dpr = 1;
let width = 0;
let height = 0;
let frostProgress = options.seedInitialPile ? 0.72 : 0.12;
const flakes: Snowflake[] = [];
const pileTargets = new Map<HTMLElement, PileTarget>();
const frostTargets = new Map<HTMLElement, FrostTarget>();
let nextFrostSeed = 4219;
// Create snow overlay canvas
const snowCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;
const ctx = snowCanvas?.getContext('2d') ?? null;
if (snowCanvas && host) {
snowCanvas.setAttribute('data-solstice-snow-canvas', 'true');
snowCanvas.setAttribute('aria-hidden', 'true');
Object.assign(snowCanvas.style, {
position: isScoped ? 'absolute' : 'fixed',
inset: '0',
width: '100%',
height: '100%',
pointerEvents: 'none',
zIndex: String(options.zIndex),
transition: 'opacity 0.4s ease',
opacity: '0',
});
host.appendChild(snowCanvas);
}
function createFlake(randomY: boolean): Snowflake {
const r = 0.9 + Math.random() * 1.9;
return {
x: Math.random() * Math.max(1, width),
y: randomY ? Math.random() * Math.max(1, height) : -8 - Math.random() * 36,
r,
vy: 18 + r * 14 + Math.random() * 12,
vx: (Math.random() - 0.5) * 8,
phase: Math.random() * Math.PI * 2,
freq: 0.6 + Math.random() * 1.2,
amp: 6 + Math.random() * 12,
alpha: 0.25 + (r / 2.8) * 0.55,
};
}
function ensureFlakeCount(targetCount: number, randomY: boolean): void {
const count = Math.max(0, Math.round(targetCount));
if (flakes.length < count) {
while (flakes.length < count) {
flakes.push(createFlake(randomY));
}
} else if (flakes.length > count) {
flakes.length = count;
}
}
function getRelativeRect(el: HTMLElement): PileRect {
const rect = el.getBoundingClientRect();
if (isScoped && options.container) {
const origin = options.container.getBoundingClientRect();
return {
left: rect.left - origin.left,
top: rect.top - origin.top,
width: rect.width,
};
}
return { left: rect.left, top: rect.top, width: rect.width };
}
function measureBounds(): void {
if (!snowCanvas || !ctx) return;
dpr = typeof window !== 'undefined' ? Math.min(window.devicePixelRatio || 1, 2) : 1;
if (isScoped && options.container) {
const rect = options.container.getBoundingClientRect();
width = Math.max(1, Math.round(rect.width));
height = Math.max(1, Math.round(rect.height));
} else if (typeof window !== 'undefined') {
width = Math.max(1, window.innerWidth);
height = Math.max(1, window.innerHeight);
}
snowCanvas.width = Math.round(width * dpr);
snowCanvas.height = Math.round(height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function renderAllFrost(): void {
const resolvedTheme = resolveTheme(options.theme, options.container);
for (const target of frostTargets.values()) {
const rect = target.el.getBoundingClientRect();
const intensity = parseFrostIntensity(
target.el.getAttribute('data-snow-frost'),
options.frostIntensity,
);
renderFrostOverlay(target.canvas, rect.width, rect.height, dpr, {
intensity,
resolvedTheme,
seed: target.seed,
});
target.canvas.style.opacity = running && intensity !== 'none' ? String(frostProgress) : '0';
}
}
const resizeObserver =
typeof ResizeObserver !== 'undefined'
? new ResizeObserver(() => {
measureBounds();
updateTargetRects();
renderAllFrost();
})
: null;
function updateTargetRects(): void {
for (const entry of pileTargets.values()) {
const rect = getRelativeRect(entry.el);
entry.rect = rect;
const cols = Math.max(8, Math.ceil(rect.width / SAMPLE_STEP) + 1);
if (entry.heights.length !== cols) {
entry.heights = resampleHeightfield(entry.heights, cols);
}
}
}
function syncTargets(): void {
if (destroyed || typeof document === 'undefined') return;
const scopeRoot: ParentNode = options.container ?? document;
// Sync pile targets
const pileNodes = new Set<HTMLElement>(
Array.from(scopeRoot.querySelectorAll<HTMLElement>(options.pileSelector)),
);
for (const [el] of pileTargets) {
if (!pileNodes.has(el)) {
resizeObserver?.unobserve(el);
pileTargets.delete(el);
}
}
for (const el of pileNodes) {
if (!pileTargets.has(el)) {
const rect = getRelativeRect(el);
const heights = createHeightfield(
rect.width,
SAMPLE_STEP,
options.maxPileHeight,
options.seedInitialPile,
);
pileTargets.set(el, { el, rect, heights });
resizeObserver?.observe(el);
}
}
// Sync frost targets
const frostNodes = new Set<HTMLElement>(
Array.from(scopeRoot.querySelectorAll<HTMLElement>(options.frostSelector)),
);
for (const [el, target] of frostTargets) {
if (!frostNodes.has(el)) {
resizeObserver?.unobserve(el);
target.canvas.remove();
frostTargets.delete(el);
}
}
for (const el of frostNodes) {
if (!frostTargets.has(el)) {
const canvas = document.createElement('canvas');
canvas.setAttribute('data-solstice-frost-canvas', 'true');
canvas.setAttribute('aria-hidden', 'true');
Object.assign(canvas.style, {
position: 'absolute',
inset: '0',
width: '100%',
height: '100%',
pointerEvents: 'none',
borderRadius: 'inherit',
zIndex: '2',
transition: 'opacity 0.55s ease',
opacity: '0',
});
el.appendChild(canvas);
const seed = nextFrostSeed;
nextFrostSeed += 977;
frostTargets.set(el, { el, canvas, seed });
resizeObserver?.observe(el);
}
}
updateTargetRects();
renderAllFrost();
}
let scrollScheduled = false;
const onScroll = () => {
if (scrollScheduled || !running) return;
scrollScheduled = true;
requestAnimationFrame(() => {
scrollScheduled = false;
updateTargetRects();
});
};
const onResize = () => {
measureBounds();
updateTargetRects();
renderAllFrost();
};
const onVisibilityChange = () => {
if (destroyed || !running) return;
if (document.hidden) {
if (rafId !== null) {
cancelAnimationFrame(rafId);
rafId = null;
}
} else if (rafId === null) {
lastTime = performance.now();
rafId = requestAnimationFrame(tick);
}
};
const mutationObserver =
typeof MutationObserver !== 'undefined' && host
? new MutationObserver((records) => {
const hasExternalMutation = records.some((rec) => {
const added = Array.from(rec.addedNodes);
const removed = Array.from(rec.removedNodes);
return [...added, ...removed].some(
(node) =>
node instanceof HTMLElement &&
!node.hasAttribute('data-solstice-snow-canvas') &&
!node.hasAttribute('data-solstice-frost-canvas'),
);
});
if (hasExternalMutation) {
syncTargets();
}
})
: null;
if (options.container) {
resizeObserver?.observe(options.container);
}
if (typeof window !== 'undefined') {
window.addEventListener('resize', onResize, { passive: true });
if (!isScoped) {
window.addEventListener('scroll', onScroll, { passive: true });
}
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', onVisibilityChange);
}
if (host && mutationObserver) {
mutationObserver.observe(host, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['data-snow-pile', 'data-snow-frost', 'data-theme', 'class'],
});
}
function tick(now: number): void {
if (!running || destroyed || !ctx) return;
const dt = Math.min(0.05, Math.max(0.001, (now - lastTime) / 1000));
lastTime = now;
const t = now * 0.001;
const resolvedTheme = resolveTheme(options.theme, options.container);
ctx.clearRect(0, 0, width, height);
if (frostProgress < 1) {
frostProgress = Math.min(1, frostProgress + dt * 0.018 * options.speed);
for (const target of frostTargets.values()) {
const intensity = parseFrostIntensity(
target.el.getAttribute('data-snow-frost'),
options.frostIntensity,
);
if (intensity !== 'none') {
target.canvas.style.opacity = String(frostProgress);
}
}
}
const flakeRgb = resolvedTheme === 'dark' ? '236, 246, 255' : '138, 190, 240';
for (let i = 0; i < flakes.length; i++) {
const f = flakes[i];
if (!f) continue;
f.y += f.vy * options.speed * dt;
f.x += (f.vx + Math.sin(t * f.freq + f.phase) * f.amp * options.wind) * dt;
let landed = false;
if (options.maxPileHeight > 0) {
for (const target of pileTargets.values()) {
const { rect, heights } = target;
if (
rect.width >= 16 &&
rect.top >= -20 &&
rect.top <= height + 20 &&
f.x >= rect.left + 8 &&
f.x <= rect.left + rect.width - 8
) {
const col = Math.min(
heights.length - 1,
Math.max(0, Math.round((f.x - rect.left) / SAMPLE_STEP)),
);
const surfaceY = rect.top + 1 - (heights[col] ?? 0);
if (f.y >= surfaceY && f.y <= rect.top + 14) {
depositSnowAt(heights, f.x - rect.left, f.r, SAMPLE_STEP, options.maxPileHeight);
flakes[i] = createFlake(false);
landed = true;
break;
}
}
}
}
if (landed) continue;
if (f.y > height + 10) {
flakes[i] = createFlake(false);
continue;
}
if (f.x < -10) f.x = width + 10;
if (f.x > width + 10) f.x = -10;
ctx.beginPath();
ctx.arc(f.x, f.y, f.r, 0, Math.PI * 2);
ctx.fillStyle = `rgba(${flakeRgb}, ${f.alpha})`;
ctx.fill();
}
for (const target of pileTargets.values()) {
if (target.rect.top >= -30 && target.rect.top <= height + 30) {
drawSnowPile(ctx, target.rect, target.heights, {
sampleStep: SAMPLE_STEP,
maxHeight: options.maxPileHeight,
cornerInset: options.cornerInset,
resolvedTheme,
});
}
}
rafId = requestAnimationFrame(tick);
}
function start(): void {
if (destroyed || running) return;
if (options.respectReducedMotion && prefersReducedMotion()) return;
running = true;
measureBounds();
syncTargets();
ensureFlakeCount(options.density, flakes.length === 0);
if (snowCanvas) {
snowCanvas.style.opacity = '1';
}
for (const target of frostTargets.values()) {
const intensity = parseFrostIntensity(
target.el.getAttribute('data-snow-frost'),
options.frostIntensity,
);
target.canvas.style.opacity = intensity !== 'none' ? String(frostProgress) : '0';
}
lastTime = performance.now();
rafId = requestAnimationFrame(tick);
}
function stop(): void {
if (!running) return;
running = false;
if (rafId !== null) {
cancelAnimationFrame(rafId);
rafId = null;
}
if (snowCanvas) {
snowCanvas.style.opacity = '0';
}
for (const target of frostTargets.values()) {
target.canvas.style.opacity = '0';
}
}
function toggle(nextEnabled?: boolean): boolean {
const shouldRun = nextEnabled ?? !running;
if (shouldRun) {
start();
} else {
stop();
}
return running;
}
function reset(): void {
for (const entry of pileTargets.values()) {
entry.heights = createHeightfield(
entry.rect.width,
SAMPLE_STEP,
options.maxPileHeight,
false,
);
}
frostProgress = 0.08;
renderAllFrost();
}
function updateOptions(partial: Partial<Omit<WinterSnowOptions, 'container'>>): void {
const prevTheme = options.theme;
const prevFrost = options.frostIntensity;
const prevMaxPile = options.maxPileHeight;
options = { ...options, ...partial };
ensureFlakeCount(options.density, true);
if (snowCanvas && partial.zIndex !== undefined) {
snowCanvas.style.zIndex = String(options.zIndex);
}
if (prevMaxPile !== options.maxPileHeight) {
for (const entry of pileTargets.values()) {
for (let i = 0; i < entry.heights.length; i++) {
entry.heights[i] = Math.min(options.maxPileHeight, entry.heights[i] ?? 0);
}
}
}
if (prevTheme !== options.theme || prevFrost !== options.frostIntensity) {
renderAllFrost();
}
}
function destroy(): void {
if (destroyed) return;
stop();
destroyed = true;
resizeObserver?.disconnect();
mutationObserver?.disconnect();
if (typeof window !== 'undefined') {
window.removeEventListener('resize', onResize);
window.removeEventListener('scroll', onScroll);
}
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', onVisibilityChange);
}
for (const target of frostTargets.values()) {
target.canvas.remove();
}
frostTargets.clear();
pileTargets.clear();
snowCanvas?.remove();
}
measureBounds();
syncTargets();
return {
start,
stop,
toggle,
reset,
syncTargets,
updateOptions,
isRunning: () => running,
destroy,
};
}
export interface PileRect {
left: number;
top: number;
width: number;
}
export interface DrawPileOptions {
sampleStep: number;
maxHeight: number;
cornerInset: number;
resolvedTheme: 'light' | 'dark';
}
export function createHeightfield(
width: number,
sampleStep: number,
maxHeight: number,
seedInitial: boolean,
): Float32Array {
const cols = Math.max(8, Math.ceil(width / sampleStep) + 1);
const heights = new Float32Array(cols);
if (seedInitial && maxHeight > 0) {
const baseRatio = Math.min(1, maxHeight / 9.5);
for (let i = 0; i < cols; i++) {
const t = i / (cols - 1);
const wave =
Math.sin(t * 26) * 0.9 + Math.sin(t * 63 + 1.3) * 0.55 + Math.cos(t * 115 + 0.4) * 0.3;
heights[i] = Math.min(maxHeight, Math.max(1.1 * baseRatio, (3.1 + wave) * baseRatio));
}
smoothHeightfield(heights, 3);
}
return heights;
}
export function smoothHeightfield(heights: Float32Array, iterations = 1): void {
const n = heights.length;
for (let iter = 0; iter < iterations; iter++) {
for (let i = 1; i < n - 1; i++) {
const prev = heights[i - 1] ?? 0;
const curr = heights[i] ?? 0;
const next = heights[i + 1] ?? 0;
heights[i] = prev * 0.22 + curr * 0.56 + next * 0.22;
}
}
}
export function depositSnowAt(
heights: Float32Array,
localX: number,
radius: number,
sampleStep: number,
maxHeight: number,
): void {
if (maxHeight <= 0 || heights.length < 3) return;
const centerIdx = Math.round(localX / sampleStep);
const spread = 5;
const amount = 0.28 + radius * 0.22;
for (let offset = -spread; offset <= spread; offset++) {
const idx = centerIdx + offset;
if (idx >= 0 && idx < heights.length) {
const weight = Math.exp(-(offset * offset) / (2 * 2.1 * 2.1));
const curr = heights[idx] ?? 0;
heights[idx] = Math.min(maxHeight, curr + amount * weight);
}
}
const start = Math.max(1, centerIdx - spread - 1);
const end = Math.min(heights.length - 2, centerIdx + spread + 1);
for (let i = start; i <= end; i++) {
const prev = heights[i - 1] ?? 0;
const curr = heights[i] ?? 0;
const next = heights[i + 1] ?? 0;
heights[i] = prev * 0.2 + curr * 0.6 + next * 0.2;
}
}
export function resampleHeightfield(prev: Float32Array, nextCols: number): Float32Array {
const cols = Math.max(8, nextCols);
if (prev.length === cols) return prev;
const next = new Float32Array(cols);
if (prev.length === 0) return next;
for (let i = 0; i < cols; i++) {
const srcIdx = Math.min(prev.length - 1, Math.round((i / (cols - 1)) * (prev.length - 1)));
next[i] = prev[srcIdx] ?? 0;
}
return next;
}
export function edgeTaper(localX: number, width: number, cornerInset: number): number {
if (width <= 8) return 0;
const inset = Math.max(1, Math.min(cornerInset, width * 0.25));
const leftRatio = Math.min(1, Math.max(0, (localX - 4) / inset));
const rightRatio = Math.min(1, Math.max(0, (width - 4 - localX) / inset));
const r = Math.min(leftRatio, rightRatio);
return r * r * (3 - 2 * r);
}
export function drawSnowPile(
ctx: CanvasRenderingContext2D,
rect: PileRect,
heights: Float32Array,
options: DrawPileOptions,
): void {
const n = heights.length;
if (n < 2 || options.maxHeight <= 0 || rect.width < 16) return;
const baseY = rect.top + 1.5;
const { left, width } = rect;
const { sampleStep, maxHeight, cornerInset, resolvedTheme } = options;
ctx.save();
ctx.beginPath();
ctx.moveTo(left + 4, baseY);
for (let i = 0; i < n; i++) {
const localX = Math.min(width, i * sampleStep);
const h = (heights[i] ?? 0) * edgeTaper(localX, width, cornerInset);
const x = left + localX;
const y = baseY - h;
if (i === 0) {
ctx.lineTo(x, y);
} else {
const prevLocalX = (i - 1) * sampleStep;
const prevH = (heights[i - 1] ?? 0) * edgeTaper(prevLocalX, width, cornerInset);
const midX = left + (prevLocalX + localX) * 0.5;
const midY = baseY - (prevH + h) * 0.5;
ctx.quadraticCurveTo(left + prevLocalX, baseY - prevH, midX, midY);
}
}
ctx.lineTo(left + width - 4, baseY);
ctx.closePath();
const grad = ctx.createLinearGradient(0, baseY - maxHeight, 0, baseY + 2);
if (resolvedTheme === 'dark') {
grad.addColorStop(0, 'rgba(232, 244, 255, 0.90)');
grad.addColorStop(0.55, 'rgba(206, 228, 252, 0.72)');
grad.addColorStop(1, 'rgba(182, 212, 246, 0.25)');
} else {
grad.addColorStop(0, 'rgba(176, 210, 246, 0.88)');
grad.addColorStop(0.55, 'rgba(202, 227, 252, 0.78)');
grad.addColorStop(1, 'rgba(224, 240, 255, 0.42)');
}
ctx.fillStyle = grad;
ctx.fill();
ctx.strokeStyle =
resolvedTheme === 'dark' ? 'rgba(244, 250, 255, 0.48)' : 'rgba(138, 186, 236, 0.46)';
ctx.lineWidth = 1;
ctx.stroke();
ctx.restore();
}
Accessibility contract
Automatically stays paused when prefers-reduced-motion: reduce is active unless respectReducedMotion={false} is explicitly passed.
All overlay canvases set pointer-events: none and aria-hidden="true"; the optional toggle button exposes aria-pressed and keyboard focus.