Skip to content
Merged
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
215 changes: 212 additions & 3 deletions src/modules/home/components/home.statistics.component.vue
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
<!--
HomeStatisticsComponent
=======================
Statistics component with animated blur background.
Statistics component with animated blur background and scroll-triggered counters.

USAGE:
<homeStatisticsComponent
:setup="statistics"
:animated="true"
:animation-duration="1500"
:animation-speed="1.5"
:background-colors="['#4a90c2', '#3d7eb0', '#2d6a9e', '#1e5a8c', '#164578']"
:halo-colors="['#0891b2', '#0ea5e9', '#3b82f6', '#0284c7', '#0369a1']"
/>

PROPS:
- setup (Array): Array of { value: String, title: String }
- animated (Boolean): Enable counter animation (default: true)
- animationDuration (Number): Counter animation duration in ms (default: 1500)
- animationSpeed (Number): Animation speed multiplier (1.5 recommended)
- backgroundColors (Array): 5 colors for gradient background
- haloColors (Array): 5 colors for animated halos
- colorMode (String): 'light' | 'dark' | null — force text color mode

CONFIG EXAMPLE (config.home.statistics):
{
animated: true,
animationDuration: 1500,
blur: {
animationSpeed: 1.5,
light: {
Expand All @@ -38,7 +44,7 @@
}
-->
<template>
<section id="statistics" :style="sectionStyle">
<section id="statistics" ref="sectionRef" :style="sectionStyle">
<homeBlurBackgroundComponent
:ratio="statsRatio"
:animation-speed="animationSpeed"
Expand All @@ -50,7 +56,10 @@
<v-row v-if="setup && setup.length > 0" class="fill-height" align="center" justify="center">
<v-col v-for="({ value, title }, i) in setup" :key="i" cols="6" md="3">
<div class="text-center" :class="colorMode ? '' : 'text-white'" data-aos="fade">
<div class="font-weight-black text-display-small text-md-display-medium mb-4 stats-value" v-text="value"></div>
<div
class="font-weight-black text-display-small text-md-display-medium mb-4 stats-value"
v-text="displayValues[i] != null ? displayValues[i] : value"
></div>
<div class="text-uppercase text-body-large stats-title" v-text="title"></div>
</div>
</v-col>
Expand All @@ -64,6 +73,42 @@
import { overlapStyle, colorModeStyle } from '../../../lib/helpers/theme';
import homeBlurBackgroundComponent from './utils/home.blur.background.component.vue';

/**
* Parse a stat value string into numeric target with prefix and suffix parts.
* Examples: "1000+" -> { num: 1000, prefix: "", suffix: "+", decimals: 0 }
* "x2.08" -> { num: 2.08, prefix: "x", suffix: "", decimals: 2 }
* "50m" -> { num: 50, prefix: "", suffix: "m", decimals: 0 }
*
* @param {*} raw Raw stat value to parse.
* @returns {{ num: number, prefix: string, suffix: string, decimals: number } | null} Parsed stat parts, or null when parsing fails.
*/
function parseStatValue(raw) {
const str = String(raw);
const match = str.match(/^([^\d]*?)([\d]+(?:\.[\d]+)?)(.*)$/);
if (!match) return null;
const num = parseFloat(match[2]);
if (Number.isNaN(num)) return null;
const decPart = match[2].split('.')[1];
return {
num,
prefix: match[1],
suffix: match[3],
decimals: decPart ? decPart.length : 0,
};
}

/**
* Apply a cubic ease-out curve to a normalized progress value.
* @param {number} t The normalized progress value between 0 and 1.
* @returns {number} The eased progress value.
*/
function easeOutCubic(t) {
return 1 - Math.pow(1 - t, 3);
}

// Exported for unit testing
export { parseStatValue, easeOutCubic };

export default {
name: 'HomeStatisticsComponent',
components: {
Expand All @@ -74,6 +119,16 @@ export default {
type: Array,
required: true,
},
// Enable counter animation (default: true)
animated: {
type: Boolean,
default: true,
},
// Counter animation duration in ms
animationDuration: {
type: Number,
default: 1500,
},
// Animation speed multiplier (1.5 recommended for stats - slower than banner)
animationSpeed: {
type: Number,
Expand Down Expand Up @@ -101,6 +156,14 @@ export default {
validator: (value) => value === null || ['light', 'dark'].includes(value),
},
},
data() {
return {
displayValues: [],
hasAnimated: false,
observer: null,
animationFrameIds: [],
};
},
computed: {
statsRatio() {
// Smaller ratio for stats section (taller)
Expand All @@ -116,6 +179,152 @@ export default {
...colorModeStyle(this.colorMode),
};
},
/** Whether animation should be skipped (disabled or prefers-reduced-motion). */
shouldAnimate() {
if (!this.animated) return false;
if (typeof window !== 'undefined' && window.matchMedia) {
return !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}
return true;
},
},
watch: {
setup: {
handler() {
this.initDisplayValues();
// Re-observe when setup data changes (e.g. async fetch)
if (!this.hasAnimated && this.shouldAnimate) {
this.$nextTick(() => this.observeSection());
}
},
deep: true,
},
},
mounted() {
this.initDisplayValues();
if (this.shouldAnimate) {
this.observeSection();
}
Comment thread
PierreBrisorgueil marked this conversation as resolved.
},
beforeUnmount() {
this.cleanup();
},
methods: {
/** Initialise displayValues — show final values when not animating, "0" otherwise. */
initDisplayValues() {
if (!this.setup) return;
if (!this.shouldAnimate || this.hasAnimated) {
this.displayValues = this.setup.map((s) => s.value);
} else {
this.displayValues = this.setup.map((s) => {
const parsed = parseStatValue(s.value);
return parsed ? `${parsed.prefix}0${parsed.suffix}` : s.value;
});
}
},
/**
* Set up IntersectionObserver on the section element.
* Falls back to immediate animation when IntersectionObserver is unavailable.
* @returns {void}
*/
observeSection() {
this.cleanupObserver();
const el = this.$refs.sectionRef;
if (!el) return;
if (typeof IntersectionObserver === 'undefined') {
if (!this.hasAnimated) {
this.hasAnimated = true;
this.startCounters();
}
return;
}
this.observer = new IntersectionObserver(
(entries) => {
if (entries[0] && entries[0].isIntersecting && !this.hasAnimated) {
this.hasAnimated = true;
this.startCounters();
this.cleanupObserver();
}
},
{ threshold: 0.4 },
);
this.observer.observe(el);
},
/**
* Check whether a statistic value still matches the seeded placeholder.
* @param {string} value Statistic value to inspect.
* @returns {boolean} True when the value still looks like the initial unloaded placeholder.
*/
isPendingStatValue(value) {
return typeof value === 'string' && value.trim() === '0';
},
/**
* Animate a single counter, waiting briefly for async-loaded values if needed.
* @param {{ value: string }} stat Statistic entry being animated.
* @param {number} index Display slot index for the statistic.
* @returns {void}
*/
startCounter(stat, index) {
const duration = this.animationDuration;
const waitStartedAt = performance.now();
const maxWait = duration;

const waitForTarget = (now) => {
// If value is still the placeholder '0', wait for async data
if (this.isPendingStatValue(stat.value) && now - waitStartedAt < maxWait) {
this.animationFrameIds[index] = requestAnimationFrame(waitForTarget);
return;
}

const parsed = parseStatValue(stat.value);
if (!parsed) {
this.displayValues[index] = stat.value;
return;
}

const start = now;
const step = (frameNow) => {
const elapsed = frameNow - start;
const t = Math.min(elapsed / duration, 1);
const eased = easeOutCubic(t);
const current = eased * parsed.num;
const formatted = parsed.decimals > 0 ? current.toFixed(parsed.decimals) : String(Math.round(current));
this.displayValues[index] = `${parsed.prefix}${formatted}${parsed.suffix}`;
if (t < 1) {
this.animationFrameIds[index] = requestAnimationFrame(step);
} else {
// Ensure exact final value
this.displayValues[index] = stat.value;
}
};

this.animationFrameIds[index] = requestAnimationFrame(step);
};

this.animationFrameIds[index] = requestAnimationFrame(waitForTarget);
},
/** Animate all counters from 0 to their target values. */
startCounters() {
if (!this.setup) return;
this.setup.forEach((stat, i) => {
this.startCounter(stat, i);
});
},
/** Clean up observer. */
cleanupObserver() {
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
},
/** Clean up all resources. */
cleanup() {
this.cleanupObserver();
this.animationFrameIds.forEach((id) => {
if (id) cancelAnimationFrame(id);
});
this.animationFrameIds = [];
},
},
};
</script>
Expand Down
2 changes: 2 additions & 0 deletions src/modules/home/config/home.development.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,8 @@ export default {
statistics: {
icon: 'fa-solid fa-chart-line',
title: 'Our Impact',
animated: true, // enable scroll-triggered counter animation
animationDuration: 1500, // counter animation duration in ms
variant: 'blur', // 'parallax' | 'blur'
parallax: {
image: '/images/parallax.webp',
Expand Down
Loading
Loading