Files
wx_pbzc/pages/index/index.js
T
lc 3532d0111b feat: 循环训练模式 + 语音补全 / 屏幕常亮 / 卡片渲染修复
循环训练(circuit)
- 新增 utils/circuitTimer.js 状态机: 工作->休息->...->完成, stop() 返回有效撑总秒(不含休息)
- 首页新增「循环训练·分组练习」入口 + stepper 配置弹窗
- 配置本地持久化 circuit_config(每组时长/组数/休息/每周目标), 下次自动预填
- 记录以 planId:'circuit' + mode:'circuit' 落库, duration 语义不变 -> 排行榜/统计/每日计划进度零改动
- 记录页展示「循环 N组xMs·休Rs」

计时器顶部循环进度面板
- 组进度点阵按组数等分铺满(flex:1 1 0, 去掉 max-width 封顶), 当前组以增高而非加宽强调
- 大号「X/Y 组」+ 四态阶段徽章(撑住/休息中/准备开始/已暂停) + 累计秒数副行
- 状态灯用纯 CSS 圆点(SVG 图标颜色烤死在 data URI 里, CSS 改不动)
- 超过 15 组自动降级为线性进度条; 面板不设固定高度, 规避真机大字体档裁字

修复: 循环训练全程无语音
- 根因: circuit 的 onTick 走 _circuitCue(只有震动), 从未调用 _remind
- 接入整场进度播报, 基准为 sets x holdPerSet(而非每组), 避免 4 组播 4 次「已完成一半」
- 新增 restStart/nextSet/lastSet 三条不含数字的词条, 客户端与 tts 云函数词表同步
- 修复必然撞车的时序: 偶数组时 halfway 与休息切换同一 tick, 加 2.6s 优先窗口让位
- 防吵闸门: 每组 <10s 不播过场语音, 休息 <5s 不播; 预载按模式取词条

训练期间屏幕常亮
- wx.setKeepScreenOn: onStart 开 / onUnload 关 / onShow 在 isRunning 时重新武装
- 切后台再回来该标志会被系统清掉, 故必须重新武装, 否则后半程丢语音与震动
- 低基础库与 Android 省电模式静默降级, 不弹 toast

修复: 首页打卡卡片左侧两个竖条
- 根因: ui-card 宿主节点无 display 声明为 inline, 页面侧加的 border 被打断成两个零宽行盒碎片
- ui-card 加 :host{display:block}, margin-bottom 从内部 view 上提到宿主
- 高亮由 border 改为 box-shadow spread 描边(不占布局, 无跳动) + 补 border-radius
- 连带修复失效的交错入场: nth-child 跨组件边界恒匹配 1, 改为 index 属性驱动内联 animation-delay, 14 处调用点补序号

注意: tts 云函数需重新部署, 否则新增的 3 条词条返回 Unknown prompt key(静默降级不报错)
2026-08-03 16:34:22 +08:00

293 lines
9.7 KiB
JavaScript

const storage = require('../../utils/storage')
const planMod = require('../../utils/plan')
const util = require('../../utils/util')
const themeMod = require('../../utils/theme')
const iconsMod = require('../../utils/icons')
const config = require('../../config')
const MAX_CUSTOM_DURATION = 3600 // 1 hour max
Page({
data: {
theme: { primary: '#FF6B35', primaryLight: '#FF8C5A', primaryBg: '#FFF3ED', primaryRgb: '255,107,53' },
themeStyle: themeMod.BASE_VARS,
todayTarget: 0,
todayDone: false,
todayDuration: 0,
todayTargetText: '',
// Ring number font size in rpx. WeChat auto-scales text by the user's
// font-size setting (fontSizeScaleFactor) but does NOT scale rpx box
// dimensions — so on a real device with enlarged system font the 84rpx
// number grows past the fixed-size circular ring and gets clipped. We
// cancel that scale here so the number renders at a constant visual size
// (matching the devtools/simulator) on every device. See _readFontScale().
targetTimeFontSize: 84,
streakCount: 0,
planName: '',
planDay: 1,
planTotal: 7,
planProgress: 0,
useSegments: false,
planDays: [],
showPicker: false,
pickerInputFocus: false,
presets: [30, 60, 90, 120, 180, 300],
customDuration: 60,
customInput: '',
// --- Circuit (循环训练) config panel (persisted via storage.saveCircuitConfig) ---
showCircuitPicker: false,
cHold: 30,
cSets: 4,
cRest: 15,
cSessions: 3,
icons: iconsMod.build()
},
onLoad() {
themeMod.applyThemeToPage(this)
this._readFontScale()
this._firstShow = true
},
/**
* Read the device's WeChat font-size scale and compensate the ring number
* so it never overflows the fixed circular clip on real devices.
*
* WeChat auto-applies `fontSizeScaleFactor` to ALL text (including rpx font
* sizes) but leaves rpx box dimensions untouched. A user who bumps up the
* system font therefore sees enlarged text inside a non-enlarged ring.
*
* CRITICAL asymmetry: the DevTools simulator reports the SAME
* `fontSizeScaleFactor` as a real device (the user's actual WeChat setting)
* but does NOT actually scale rendered text. So if we compensate there, the
* number ends up too small in the simulator. We therefore SKIP the
* compensation under DevTools (host.env === 'devtools') and keep the design
* size — matching what the simulator renders literally.
*
* On real devices, dividing our design size by the factor cancels the
* auto-scale, keeping the number a constant 84rpx-equivalent everywhere.
* Bounded so a bad reading can only ever make the number smaller (safe),
* never larger (overflow).
*/
_readFontScale() {
let factor = 1
try {
const info = wx.getAppBaseInfo ? wx.getAppBaseInfo() : wx.getSystemInfoSync()
const isDevtools = info.host && info.host.env === 'devtools'
if (!isDevtools) {
if (typeof info.fontSizeScaleFactor === 'number' && info.fontSizeScaleFactor > 0) {
factor = info.fontSizeScaleFactor
} else if (typeof info.fontSizeSetting === 'number' && info.fontSizeSetting > 0) {
// fontSizeScaleFactor == currentFontSize / standardFontSize(17px)
factor = info.fontSizeSetting / 17
}
}
} catch (e) {}
const DESIGN = 84
let size = Math.round(DESIGN / factor)
size = Math.max(48, Math.min(96, size))
this.setData({ targetTimeFontSize: size })
},
onShow() {
themeMod.applyThemeToPage(this)
try {
const tb = this.getTabBar()
if (tb) tb.setData({ selected: 0 })
} catch (e) {}
// Skip the first onShow to avoid double-refresh; subsequent tab switches still refresh.
if (this._firstShow) {
this._firstShow = false
this.refresh()
this._checkFreshTrain()
return
}
this.refresh()
this._checkFreshTrain()
},
/**
* If user just returned from completing a training, briefly highlight
* the "今日已完成" badge so the success feels tangible. The flag is
* timestamped; older than 10s is treated as stale (e.g. user reopened
* the app later).
*/
_checkFreshTrain() {
try {
const at = wx.getStorageSync('_last_train_at')
if (!at) return
const age = Date.now() - at
if (age < 0 || age > 10 * 1000) {
wx.removeStorageSync('_last_train_at')
return
}
wx.removeStorageSync('_last_train_at')
this.setData({ justCompleted: true })
if (this._justCompletedTimer) clearTimeout(this._justCompletedTimer)
this._justCompletedTimer = setTimeout(() => {
this.setData({ justCompleted: false })
}, 3000)
} catch (e) {}
},
onPullDownRefresh() {
this.refresh()
wx.stopPullDownRefresh()
},
refresh() {
const settings = storage.getSettings()
const streak = storage.validateStreak()
const todayRecord = storage.getTodayRecord()
const allRecords = Object.values(storage.getRecords()).flat()
const customPlans = storage.getCustomPlans()
const plan = planMod.getPlan(settings.planId, customPlans)
const planDay = planMod.getPlanDay(settings.planId, allRecords, settings.planStartDate, customPlans)
const clampedDay = Math.min(planDay, plan.totalDays)
const target = planMod.getTodayTarget(settings.planId, clampedDay, customPlans)
const theme = themeMod.getCurrentTheme()
// 防御:totalDays 为 0(极端数据损坏)时避免除以 0 得到 NaN
const planProgress = plan.totalDays > 0 ? Math.round((clampedDay / plan.totalDays) * 100) : 0
// 分段格子(每天一格)只在计划天数 <= 10 时用;更长则退化为里程碑连续条,避免格子过密
const useSegments = plan.totalDays > 0 && plan.totalDays <= 10
const planDays = useSegments ? Array.from({ length: plan.totalDays }, (_, i) => i) : []
this.setData({
theme,
icons: iconsMod.build(theme),
todayTarget: target,
todayDone: todayRecord && todayRecord.duration >= target,
todayDuration: todayRecord ? todayRecord.duration : 0,
todayTargetText: util.formatTime(target),
streakCount: streak.count,
planName: plan.name,
planDay: clampedDay,
planTotal: plan.totalDays,
planProgress,
useSegments,
planDays
})
},
onStartTrain() {
wx.navigateTo({ url: '/pages/timer/timer' })
},
onFreeTrain() {
this.setData({ showPicker: true, customInput: '', customDuration: 60 })
},
onClosePicker() {
this.setData({ showPicker: false })
},
onSelectPreset(e) {
const val = e.currentTarget.dataset.value
// 收起键盘(失焦 input),避免清空 customInput 时触发 adjust-position 让页面向上跳
this.setData({ pickerInputFocus: false, customDuration: val, customInput: '' })
},
onPickerInputFocus() {
this.setData({ pickerInputFocus: true })
},
onCustomInput(e) {
let val = parseInt(e.detail.value) || 0
if (val > MAX_CUSTOM_DURATION) val = MAX_CUSTOM_DURATION
this.setData({ customInput: e.detail.value, customDuration: val })
},
onConfirmFree() {
const dur = this.data.customDuration
if (!dur || dur <= 0) {
wx.showToast({ title: '请输入有效时长', icon: 'none' })
return
}
if (dur > MAX_CUSTOM_DURATION) {
wx.showToast({ title: '最大时长为1小时', icon: 'none' })
return
}
this.setData({ showPicker: false })
wx.navigateTo({ url: `/pages/timer/timer?free=${dur}` })
},
/**
* 循环训练入口:打开配置弹窗,预填上次保存的设置(getCircuitConfig 含默认值
* + 校验),用户改完确认后持久化并跳计时器。设置因此被保存下来——下次打开直接
* 沿用,无需重填。
*/
onCircuitTrain() {
const cfg = storage.getCircuitConfig()
this.setData({
showCircuitPicker: true,
cHold: cfg.holdPerSet,
cSets: cfg.sets,
cRest: cfg.restPerSet,
cSessions: cfg.sessionsPerWeek
})
},
onCloseCircuitPicker() {
this.setData({ showCircuitPicker: false })
},
onCircuitStep(e) {
const field = e.currentTarget.dataset.field
const delta = Number(e.currentTarget.dataset.delta) || 0
const keyMap = { hold: 'cHold', sets: 'cSets', rest: 'cRest', sessions: 'cSessions' }
const key = keyMap[field]
if (!key) return
const bounds = {
hold: [5, 600],
sets: [1, 50],
rest: [0, 600],
sessions: [1, 14]
}
let v = this.data[key] + delta
const min = bounds[field][0]
const max = bounds[field][1]
if (v < min) v = min
if (v > max) v = max
this.setData({ [key]: v })
},
onConfirmCircuit() {
const cfg = {
holdPerSet: this.data.cHold,
sets: this.data.cSets,
restPerSet: this.data.cRest,
sessionsPerWeek: this.data.cSessions
}
storage.saveCircuitConfig(cfg)
this.setData({ showCircuitPicker: false })
wx.navigateTo({
url: `/pages/timer/timer?circuit=1&hold=${cfg.holdPerSet}&sets=${cfg.sets}&rest=${cfg.restPerSet}&sessions=${cfg.sessionsPerWeek}`
})
},
/**
* 分享给朋友。微信在用户点击右上角"···"菜单里的"转发给朋友"、
* 或者页面内任何 `<button open-type="share">` / `<button open-type="share">`
* 时,都会调用这个钩子,返回值即分享卡片的内容。
* 没声明这个方法时分享按钮就是灰色的,见上轮分析。
*/
onShareAppMessage() {
const s = config.share.default
return {
title: s.title,
path: s.path
}
},
/**
* 分享到朋友圈。基础库 2.11.3+ 可用。同样不实现就让"分享到朋友圈"按钮
* 灰掉。各页统一用 config.share.timelineTitle 作为朋友圈文案。
*/
onShareTimeline() {
return {
title: config.share.timelineTitle
}
}
})