/**
* 首页 B — BMI 指数(过审默认)
* 干净工具风:原生顶栏、无品牌壳、少卡片。
*/
import { useEffect, useMemo, useState } from 'react'
import { Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import type { NomadroRemoteConfig } from '@/data/remoteConfig.defaults'
import { applyH5Theme, type H5Theme } from '@/utils/h5Theme'
import { H5Box as Box, H5Txt as Txt } from '@/components/H5Box'
import { trackClick, trackPage } from '@/utils/track'
import './bmi.scss'
const isH5 = process.env.TARO_ENV === 'h5'
const HISTORY_KEY = 'nomadro_bmi_history_v1'
const MAX_HISTORY = 8
type Gender = 'male' | 'female'
type BmiLevel = {
key: string
label: string
tip: string
color: string
min: number
max: number
}
const LEVELS: BmiLevel[] = [
{
key: 'under',
label: '偏瘦',
tip: '指数偏低,可对照下方参考区间。',
color: '#38bdf8',
min: 0,
max: 18.5,
},
{
key: 'normal',
label: '正常',
tip: '指数落在常见参考区间内。',
color: '#34d399',
min: 18.5,
max: 24,
},
{
key: 'over',
label: '超重',
tip: '指数偏高,可对照下方参考区间。',
color: '#fbbf24',
min: 24,
max: 28,
},
{
key: 'obese',
label: '肥胖',
tip: '指数较高,可对照下方参考区间。',
color: '#f87171',
min: 28,
max: 99,
},
]
type HistoryItem = {
id: string
bmi: number
heightCm: number
weightKg: number
label: string
at: string
}
function clamp(n: number, min: number, max: number) {
return Math.min(max, Math.max(min, n))
}
function calcBmi(heightCm: number, weightKg: number): number | null {
if (!heightCm || !weightKg || heightCm < 50 || heightCm > 250 || weightKg < 20 || weightKg > 300) {
return null
}
const m = heightCm / 100
return Math.round((weightKg / (m * m)) * 10) / 10
}
function levelOf(bmi: number): BmiLevel {
return LEVELS.find((l) => bmi >= l.min && bmi < l.max) || LEVELS[LEVELS.length - 1]!
}
function idealRange(heightCm: number): { low: number; high: number } | null {
if (heightCm < 50) return null
const m = heightCm / 100
return {
low: Math.round(18.5 * m * m * 10) / 10,
high: Math.round(23.9 * m * m * 10) / 10,
}
}
function estimateBmr(gender: Gender, heightCm: number, weightKg: number): number | null {
if (!heightCm || !weightKg) return null
const base = 10 * weightKg + 6.25 * heightCm - 5 * 28
return Math.round(gender === 'male' ? base + 5 : base - 161)
}
function gaugePercent(bmi: number): number {
return clamp(((bmi - 12) / 24) * 100, 3, 97)
}
function readHistory(): HistoryItem[] {
try {
const raw = Taro.getStorageSync(HISTORY_KEY)
if (!raw) return []
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
return Array.isArray(parsed) ? (parsed as HistoryItem[]) : []
} catch {
return []
}
}
function writeHistory(items: HistoryItem[]) {
try {
Taro.setStorageSync(HISTORY_KEY, JSON.stringify(items.slice(0, MAX_HISTORY)))
} catch {
/* ignore */
}
}
function Stepper({
label,
unit,
value,
min,
max,
step,
onChange,
}: {
label: string
unit: string
value: number
min: number
max: number
step: number
onChange: (n: number) => void
}) {
const bump = (d: number) => onChange(clamp(Math.round((value + d) * 10) / 10, min, max))
return (
{label}
{unit}
bump(-step)}>
−
{
const n = Number(e.detail.value)
if (!Number.isFinite(n)) return
onChange(clamp(n, min, max))
}}
/>
bump(step)}>
+
)
}
export default function BmiHome({
theme,
}: {
config: NomadroRemoteConfig
theme: H5Theme
}) {
const [height, setHeight] = useState(170)
const [weight, setWeight] = useState(60)
const [gender, setGender] = useState('male')
const [history, setHistory] = useState([])
const [justSaved, setJustSaved] = useState(false)
useEffect(() => {
applyH5Theme(theme)
setHistory(readHistory())
trackPage('pages/index/index', 'BMI首页', { homeVariant: 'bmi' })
}, [theme])
useEffect(() => {
if (!isH5) return
const html = document.documentElement
const prev = html.style.fontSize
const lock = () => {
html.style.fontSize = '16px'
}
lock()
const id = window.setInterval(lock, 500)
window.addEventListener('resize', lock)
return () => {
clearInterval(id)
window.removeEventListener('resize', lock)
html.style.fontSize = prev
}
}, [])
const bmi = useMemo(() => calcBmi(height, weight), [height, weight])
const level = bmi != null ? levelOf(bmi) : null
const ideal = useMemo(() => idealRange(height), [height])
const bmr = useMemo(() => estimateBmr(gender, height, weight), [gender, height, weight])
function saveRecord() {
if (bmi == null || !level) {
Taro.showToast({ title: '请先输入有效身高体重', icon: 'none' })
return
}
trackClick('保存BMI记录', {
bmi,
height,
weight,
gender,
level: level.label,
})
const item: HistoryItem = {
id: `${Date.now()}`,
bmi,
heightCm: height,
weightKg: weight,
label: level.label,
at: new Date().toISOString(),
}
const next = [item, ...history.filter((h) => h.id !== item.id)].slice(0, MAX_HISTORY)
setHistory(next)
writeHistory(next)
setJustSaved(true)
Taro.showToast({ title: '已保存到本机', icon: 'success' })
setTimeout(() => setJustSaved(false), 1400)
}
function clearHistory() {
trackClick('清空BMI记录', { count: history.length })
setHistory([])
writeHistory([])
Taro.showToast({ title: '已清空', icon: 'none' })
}
return (
Body Mass Index
BMI 指数
{
setGender('male')
trackClick('选择性别', { gender: 'male' })
}}
>
男
{
setGender('female')
trackClick('选择性别', { gender: 'female' })
}}
>
女
BMI
{bmi != null ? bmi.toFixed(1) : '—'}
{level ? (
{level.label}
) : null}
{LEVELS.map((l) => (
))}
{bmi != null ? : null}
{ideal ? (
参考体重
{ideal.low}–{ideal.high} kg
) : null}
{bmr != null ? (
估算消耗
{bmr} kcal
) : null}
{level ? {level.tip} : null}
{justSaved ? '已保存' : '保存本次记录'}
参考区间
{LEVELS.map((l) => (
{l.label}
{l.key === 'obese' ? '≥ 28' : `${l.min} – ${(l.max - 0.1).toFixed(1)}`}
))}
本机记录
{history.length > 0 ? (
清空
) : null}
{history.length === 0 ? (
还没有记录,算出结果后点保存即可
) : (
{history.map((h) => (
{h.bmi.toFixed(1)}
{h.heightCm}cm · {h.weightKg}kg · {h.label}
{h.at.slice(5, 10).replace('-', '/')} {h.at.slice(11, 16)}
))}
)}
计算结果仅供参考,数据只存在本机。
)
}