Files
danyang-match/miniapp/pages/discover/discover.ts
T
WorkBuddy 1fc34f1bcd fix(miniapp): 修复导航页与微信胶囊重合,并把首页两个栏目卡缩到 1/3
问题 1:五个导航页顶部与右上角胶囊按钮(··· ⊙)重合
- 根因:自定义导航用 env(safe-area-inset-top) 取的是设备物理安全区,
  在 Android 上常为 0,完全不反映胶囊位置;且右对齐元素从未为胶囊让出宽度。
- 新增 miniapp/utils/nav-metrics.js 作为唯一事实源:以
  wx.getMenuButtonBoundingClientRect() 实测胶囊矩形,反推并导出四个 CSS 变量
  --nav-status / --nav-h / --nav-right / --nav-top,并提供无接口时的兜底值。
- nav-bar 组件改为自行获取导航度量(attached + observer 双触发),
  标题按胶囊垂直居中并收窄 max-width;外部传参降级为兜底。
- index / discover / messages / activity / mine 五页根结点注入同一组变量,
  WXSS 里的 env(safe-area-inset-top)、硬编码 88rpx 与右对齐 right:0 全量替换。

问题 2:首页「善缘公益服务」「善缘安全提醒」两个栏目过宽
- 根因:封面 <image> 只声明 width 未声明 height,小程序默认按 240px 计算,
  实际把卡片撑到约 480rpx 高。
- 按「整体等比缩到 1/3」重构:两栏改为 mini-card 小卡,宽度
  calc((100% - 2*gap)/3)、高度写死 168rpx,封面 height:100%;
  公益服务一行三卡横向排布,安全提醒为「标题小卡 + 右侧文案条」,
  长文案收进详情页,安全提示原文保留。

守卫与验证
- 新增 ui-tests/miniapp-capsule-safe-contracts.mjs:
  A 层多机型断言导航行与胶囊垂直居中、右对齐让位、navTop 与兜底值;
  B 层纯函数审计五个自带导航行页面(页面清单由文件系统推导,失配直接报红);
  C 层断言首页小卡宽为 1/3 且显式声明高度,并钉住旧 service-/safety- 选择器回归。
  审计前剥离注释,避免守卫被自身示例文本误伤。
- 新增 scripts/audit-image-height.mjs:按属性名精确比对,审计全仓
  「有 width 无 height」的 <image>,当前 30 个类 0 命中。
- 负向注入 N1~N7(含 nav-safe 未接入、旧选择器回归、极小屏幕、无胶囊兜底等)
  全部被守卫咬住并 exit 1,还原后复跑通过。
- 真编译(wcc/wcsc):WXSS 88 / WXML 86,失败 0;
  tsc --noEmit 通过;UI 契约门控 21/21 PASS(新增第 21 个守卫并抬高 MIN_GUARDS)。
- 渲染探针实测:单卡 213rpx x 168rpx;五页右对齐元素右缘 423~528px,
  均在胶囊右缘 365px 之外。

未纳入本次提交:miniapp/project.config.json(微信开发者工具自动改写,
仅追加若干布尔开关并删掉文件末换行)与生成的预览页 artifacts preview.html
(约 7900 行生成产物),以免淹没代码评审视线。
2026-09-23 09:55:40 +08:00

330 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 找对象页 — 筛选对齐后端 DiscoverController 5 个筛选参数:
* minAge, maxAge, regionCode, maritalStatus, educationCode
*
* 不变量(AGENTS.md):
* - Required 不可自动放宽——Discover 仅透传筛选条件到后端
* - Block 即时禁止互动
* - 单向意向不泄露
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { matchStore, appStore, authStore } from '../../stores';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { recommendationService } from '../../services';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { to } from '../../constants';
import type { RecommendationCandidate } from '../../types';
// 顶部安全区:实测右上角胶囊按钮矩形,避免筛选条与搜索图标被胶囊压住(见 utils/nav-metrics.js)
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { navSafeData } = require('../../utils/nav-metrics');
interface AppliedFilter {
keyword: string;
regionCode: string; // 后端参数名
minAge: number;
maxAge: number;
educationCode: string; // 后端参数名
maritalStatus: string; // 后端参数名
}
interface DiscoverData {
users: RecommendationCandidate[];
loading: boolean;
loadingMore: boolean;
cursor: string | null;
hasMore: boolean;
keywordInput: string;
showFilter: boolean;
// 面板临时态
tempRegionCode: string;
tempMinAge: number;
tempMaxAge: number;
tempEducationCode: string;
tempMaritalStatus: string;
applied: AppliedFilter;
hasActiveFilter: boolean;
regions: Array<{ code: string; label: string }>;
educations: Array<{ code: string; label: string }>;
maritalStatuses: Array<{ code: string; label: string }>;
actionLoadingUserId: string;
// 抽屉滚动/高亮定位
panelScrollTo: string;
panelHighlight: string;
}
const DEFAULT_MIN_AGE = 18;
const DEFAULT_MAX_AGE = 60;
const PAGE_SIZE = 20;
Page({
data: {
navVars: '',
users: [],
loading: false,
loadingMore: false,
cursor: null,
hasMore: true,
keywordInput: '',
showFilter: false,
tempRegionCode: '',
tempMinAge: DEFAULT_MIN_AGE,
tempMaxAge: DEFAULT_MAX_AGE,
tempEducationCode: '',
tempMaritalStatus: '',
applied: {
keyword: '',
regionCode: '',
minAge: DEFAULT_MIN_AGE,
maxAge: DEFAULT_MAX_AGE,
educationCode: '',
maritalStatus: '',
},
hasActiveFilter: false,
regions: [
{ code: '321181', label: '丹阳' },
{ code: '321100', label: '镇江' },
{ code: '320100', label: '南京' },
],
educations: [
{ code: 'high_school', label: '高中及以下' },
{ code: 'college', label: '大专' },
{ code: 'bachelor', label: '本科' },
{ code: 'master', label: '硕士及以上' },
],
maritalStatuses: [
{ code: 'never_married', label: '未婚' },
{ code: 'divorced', label: '离异' },
],
actionLoadingUserId: '',
panelScrollTo: '',
panelHighlight: '',
} as DiscoverData,
onLoad() {
// 顶部安全区先算:onLoad 早于首次渲染,避免出现「先压住胶囊再跳开」的闪动
this.setData(navSafeData());
if (!authStore.state.isLoggedIn) return;
this.fetchDiscover(true);
},
async fetchDiscover(first: boolean) {
if (this.data.loading) return;
this.setData({ loading: true });
try {
// @ts-ignore - recommendationService 接口待 TS 化
const result = await recommendationService.discover(this._buildParams());
const items: RecommendationCandidate[] = (result?.items as RecommendationCandidate[]) || [];
this.setData({
users: first ? items : [...this.data.users, ...items],
cursor: result?.nextCursor || null,
hasMore: !!result?.nextCursor,
loading: false,
});
} catch (err: unknown) {
this.setData({ loading: false });
appStore.toastError(err instanceof Error ? err.message : '加载失败');
}
},
async loadMore() {
if (this.data.loadingMore || !this.data.hasMore || !this.data.cursor) return;
this.setData({ loadingMore: true });
try {
// @ts-ignore
const result = await recommendationService.discover({
...this._buildParams(),
cursor: this.data.cursor,
});
const items: RecommendationCandidate[] = (result?.items as RecommendationCandidate[]) || [];
this.setData({
users: [...this.data.users, ...items],
cursor: result?.nextCursor || null,
hasMore: !!result?.nextCursor,
});
} catch (err: unknown) {
appStore.toastError(err instanceof Error ? err.message : '加载失败');
} finally {
this.setData({ loadingMore: false });
}
},
/** 对齐后端 DiscoverController 5 个筛选参数 */
_buildParams() {
const a = this.data.applied;
const params: Record<string, unknown> = { pageSize: PAGE_SIZE };
if (a.keyword) params.keyword = a.keyword;
if (a.regionCode) params.regionCode = a.regionCode;
if (a.minAge !== DEFAULT_MIN_AGE) params.minAge = a.minAge;
if (a.maxAge !== DEFAULT_MAX_AGE) params.maxAge = a.maxAge;
if (a.educationCode) params.educationCode = a.educationCode;
if (a.maritalStatus) params.maritalStatus = a.maritalStatus;
return params;
},
_hasActiveFilter(applied: AppliedFilter) {
return !!(
applied.keyword || applied.regionCode ||
applied.minAge !== DEFAULT_MIN_AGE || applied.maxAge !== DEFAULT_MAX_AGE ||
applied.educationCode || applied.maritalStatus
);
},
// ========== 搜索框 ==========
onKeywordInput(e: any) {
this.setData({ keywordInput: e.detail.value });
},
onSearch() {
const keyword = (this.data.keywordInput || '').trim();
const applied = { ...this.data.applied, keyword };
this.setData({ applied, hasActiveFilter: this._hasActiveFilter(applied) });
this.fetchDiscover(true);
},
// ========== 顶部 chip 点击(即时应用) ==========
onTopRegionTap() {
// 丹阳本地 chip:regionCode=321181
const target = '321181';
const nextCode = this.data.applied.regionCode === target ? '' : target;
const applied = { ...this.data.applied, regionCode: nextCode };
this.setData({
tempRegionCode: nextCode,
applied,
hasActiveFilter: this._hasActiveFilter(applied),
});
this.fetchDiscover(true);
},
/** 打开筛选面板,并同步当前 applied 状态到 temp,可选定位到 target section */
openFilterPanel(e?: WechatMiniprogram.TouchEvent) {
const target = e ? (e.currentTarget.dataset as any).target as string | undefined : undefined;
const sectionMap: Record<string, string> = { age: 'sec-age', education: 'sec-education', marital: 'sec-marital', region: 'sec-region' };
const a = this.data.applied;
this.setData({
showFilter: true,
tempRegionCode: a.regionCode,
tempMinAge: a.minAge,
tempMaxAge: a.maxAge,
tempEducationCode: a.educationCode,
tempMaritalStatus: a.maritalStatus,
panelScrollTo: target ? (sectionMap[target] || '') : '',
panelHighlight: target || '',
});
},
closeFilterPanel() {
this.setData({ showFilter: false });
},
// ========== 筛选面板内交互 ==========
onPanelRegionTap(e: WechatMiniprogram.TouchEvent) {
const code = (e.currentTarget.dataset as any).code as string;
this.setData({ tempRegionCode: this.data.tempRegionCode === code ? '' : code });
},
onPanelEducationTap(e: WechatMiniprogram.TouchEvent) {
const code = (e.currentTarget.dataset as any).code as string;
this.setData({ tempEducationCode: this.data.tempEducationCode === code ? '' : code });
},
onPanelMaritalTap(e: WechatMiniprogram.TouchEvent) {
const code = (e.currentTarget.dataset as any).code as string;
this.setData({ tempMaritalStatus: this.data.tempMaritalStatus === code ? '' : code });
},
onMinAgeChange(e: any) {
let min = Number(e.detail.value);
if (min > this.data.tempMaxAge) min = this.data.tempMaxAge;
this.setData({ tempMinAge: min });
},
onMaxAgeChange(e: any) {
let max = Number(e.detail.value);
if (max < this.data.tempMinAge) max = this.data.tempMinAge;
this.setData({ tempMaxAge: max });
},
onApplyFilter() {
const a = this.data.applied;
const applied: AppliedFilter = {
keyword: a.keyword,
regionCode: this.data.tempRegionCode,
minAge: this.data.tempMinAge,
maxAge: this.data.tempMaxAge,
educationCode: this.data.tempEducationCode,
maritalStatus: this.data.tempMaritalStatus,
};
this.setData({
applied,
hasActiveFilter: this._hasActiveFilter(applied),
showFilter: false,
});
this.fetchDiscover(true);
},
onResetFilter() {
const applied: AppliedFilter = {
keyword: '',
regionCode: '',
minAge: DEFAULT_MIN_AGE,
maxAge: DEFAULT_MAX_AGE,
educationCode: '',
maritalStatus: '',
};
this.setData({
keywordInput: '',
tempRegionCode: '',
tempMinAge: DEFAULT_MIN_AGE,
tempMaxAge: DEFAULT_MAX_AGE,
tempEducationCode: '',
tempMaritalStatus: '',
applied,
hasActiveFilter: false,
showFilter: false,
});
this.fetchDiscover(true);
},
// ========== 卡片交互 ==========
onViewDetail(e: WechatMiniprogram.TouchEvent) {
const { userId } = (e.detail as any) || {};
if (!userId) return;
wx.navigateTo({ url: to.detail(userId) });
},
async onLike(e: WechatMiniprogram.TouchEvent) {
const userId = (e.currentTarget.dataset as any).userId as string | undefined;
if (!userId || this.data.actionLoadingUserId) return;
this.setData({ actionLoadingUserId: userId });
try {
// @ts-ignore
const result = await matchStore.like(userId);
this.setData({ users: this.data.users.filter((u) => u.userId !== userId) });
if (result?.mutualMatch) {
appStore.toastSuccess('双向喜欢!可以开始聊天了');
if (result.matchedConversationId) {
wx.navigateTo({ url: to.chat(result.matchedConversationId) });
}
} else {
appStore.toastSuccess('已表达喜欢');
}
} catch (err: unknown) {
appStore.toastError(err instanceof Error ? err.message : '操作失败');
} finally {
this.setData({ actionLoadingUserId: '' });
}
},
onPullDownRefresh() {
this.fetchDiscover(true).finally(() => wx.stopPullDownRefresh());
},
onReachBottom() {
this.loadMore();
},
});