const KEY = 'dashen-ui:preferences:v1'; function readout(name) { const count = Array.from(name.trim()).length; return {name, count, fill: Math.min(count / 24, 1) * 100, validLength: count >= 2 && count <= 24}; } Page({ data: { ...readout('编辑'), notifications: true, message: '', tone: '', editing: false, fieldInvalid: false, pressing: false }, onLoad() { try { const value = wx.getStorageSync(KEY); if (value && typeof value.name === 'string' && typeof value.notifications === 'boolean') { this.setData({...readout(value.name), notifications: value.notifications}); } } catch { this.setData({message: '读取失败,可重新填写并保存。', tone: 'error'}); } }, changeName(event) { this.setData({...readout(event.detail.value), message: '', tone: '', fieldInvalid: false}); }, toggleNotifications(event) { this.setData({notifications: event.detail.value, message: '', tone: ''}); }, pressStart() { this.setData({pressing: true}); }, pressEnd() { this.setData({pressing: false}); }, focusName() { this.setData({editing: true}); }, blurName() { this.setData({editing: false}); }, save() { const name = this.data.name.trim(); const count = Array.from(name).length; if (count < 2 || count > 24) { this.setData({message: '请输入 2–24 个字符。', tone: 'error', editing: true, fieldInvalid: true}); return; } try { wx.setStorageSync(KEY, {name, notifications: this.data.notifications}); this.setData({name, message: '偏好设置已保存到此设备。', tone: 'success'}); } catch { this.setData({message: '保存失败,请检查存储后重试。', tone: 'error'}); } }, });