refactor pages struct

This commit is contained in:
Timi
2026-01-28 14:11:54 +08:00
parent 8adc28ae9c
commit 965743be38
73 changed files with 234 additions and 176 deletions

View File

@ -0,0 +1,14 @@
{
"usingComponents": {
"t-cell": "tdesign-miniprogram/cell/cell",
"t-popup": "tdesign-miniprogram/popup/popup",
"t-radio": "tdesign-miniprogram/radio/radio",
"t-navbar": "tdesign-miniprogram/navbar/navbar",
"t-button": "tdesign-miniprogram/button/button",
"t-checkbox": "tdesign-miniprogram/checkbox/checkbox",
"t-cell-group": "tdesign-miniprogram/cell-group/cell-group",
"journal-list": "/components/journal-list/index",
"t-radio-group": "tdesign-miniprogram/radio-group/radio-group"
},
"styleIsolation": "shared"
}

View File

@ -0,0 +1,190 @@
/* pages/main/moment/index.wxss */
.moment {
.tips {
padding: 4px 12px;
font-size: .8rem;
text-align: justify;
text-indent: 2em;
}
.action {
padding: 8px 12px;
.line {
display: flex;
margin-bottom: .5rem;
justify-content: space-between;
.btn {
width: 50%;
margin-right: 1rem;
&:last-child {
margin-right: 0;
}
}
}
}
.uploading {
padding: 4px 12px;
margin-bottom: 12rpx;
.progress {
margin-bottom: 8rpx;
}
.text {
color: var(--theme-text-secondary);
display: flex;
font-size: .8rem;
justify-content: space-between;
}
}
.items {
column-gap: .25rem;
column-count: 4;
padding-bottom: 2rem;
.item {
position: relative;
.thumbnail {
width: 100%;
display: block;
overflow: hidden;
background: var(--theme-bg-card);
break-inside: avoid;
margin-bottom: .25rem;
&.video {
height: auto;
position: relative;
&::after {
content: "";
top: 50%;
left: 53%;
width: 0;
height: 0;
position: absolute;
transform: translate(-50%, -50%);
border-top: 16px solid transparent;
border-left: 24px solid var(--theme-video-play);
border-bottom: 16px solid transparent;
pointer-events: none;
}
}
}
.checkbox {
top: 0;
right: 0;
padding: 16rpx 0 16rpx 16rpx;
z-index: 2;
position: absolute;
background: transparent;
}
.checkbox-fill {
top: 24rpx;
right: 26rpx;
width: 16px;
height: 16px;
z-index: 1;
position: absolute;
background: var(--theme-bg-card);
border-radius: 50%;
}
}
}
}
.t-popup--bottom {
padding-bottom: 0 !important;
}
.archive-popup {
.container {
width: 100vw;
display: flex;
overflow: hidden;
background: var(--td-bg-color-container);
flex-direction: column;
border-top-left-radius: 16rpx;
border-top-right-radius: 16rpx;
&.select-journal {
height: 80vh;
.content {
flex: 1;
height: 0;
}
}
&.form {
padding-bottom: 32rpx;
.content {
padding: 16rpx 32rpx;
.section {
width: 100%;
margin-top: 1.5rem;
.label {
color: var(--theme-text-secondary);
}
&.type {
display: flex;
.radio {
margin-right: 1em;
}
}
&.time {
display: flex;
.picker {
margin-right: .25rem;
}
}
}
}
}
.header {
display: flex;
align-items: center;
height: 116rpx;
border-bottom: 1px solid var(--td-component-stroke);
.title {
flex: 1;
color: var(--td-text-color-primary);
font-size: 36rpx;
text-align: center;
font-weight: bold;
}
.placeholder {
width: 128rpx;
}
.btn {
margin: 0 .5rem;
&.back,
&.cancel {
color: var(--td-text-color-secondary);
}
}
}
}
}

View File

@ -0,0 +1,462 @@
// pages/main/moment/index.ts
import config from "../../../../config/index";
import Events from "../../../../utils/Events";
import IOSize, { Unit } from "../../../../utils/IOSize";
import Time from "../../../../utils/Time";
import Toolkit from "../../../../utils/Toolkit";
import { Location, MediaItemType } from "../../../../types/UI";
import { PreviewImageMetadata } from "../../../../types/Attachment";
import { MomentApi } from "../../../../api/MomentApi";
import { JournalApi } from "../../../../api/JournalApi";
import { Network } from "../../../../utils/Network";
type Item = {
id: number;
type: MediaItemType;
thumbURL: string;
sourceURL: string;
checked: boolean;
}
type MD5Result = {
path: string;
md5: string;
}
type ArchiveStep = "select-type" | "select-journal" | "form";
interface MomentData {
list: Item[];
type: string;
idea: string;
date: string;
time: string;
location?: Location;
qqMapSDK?: any;
uploaded: string;
hasChecked: boolean;
isUploading: boolean;
isArchiving: boolean;
uploadSpeed: string;
uploadTotal: string;
uploadProgress: number;
isAuthLocation: boolean;
isVisibleArchivePopup: boolean;
archiveStep: ArchiveStep;
selectedJournalId: number | null;
}
Page({
data: <MomentData>{
list: [],
type: "NORMAL",
idea: "",
date: "2025-06-28",
time: "16:00",
location: undefined,
uploaded: "0",
hasChecked: false,
isUploading: false,
isArchiving: false,
uploadSpeed: "0 MB / s",
uploadTotal: "0 MB",
uploadProgress: 0,
isAuthLocation: false,
isVisibleArchivePopup: false,
archiveStep: "select-type",
selectedJournalId: null
},
async onLoad() {
this.fetch();
// 授权定位
const setting = await wx.getSetting();
wx.setStorageSync("isAuthLocation", setting.authSetting["scope.userLocation"] || false);
let isAuthLocation = JSON.parse(wx.getStorageSync("isAuthLocation"));
this.setData({ isAuthLocation });
if (!isAuthLocation) {
wx.authorize({
scope: "scope.userLocation"
}).then(() => {
isAuthLocation = true;
this.setData({ isAuthLocation });
});
}
const unixTime = new Date().getTime();
this.setData({
idea: this.data.idea,
date: Time.toDate(unixTime),
time: Time.toTime(unixTime)
});
// 获取默认定位
wx.getLocation({
type: "gcj02"
}).then(resp => {
this.setData({
location: {
lat: resp.latitude,
lng: resp.longitude
},
});
const argLoc = `location=${this.data.location!.lat},${this.data.location!.lng}`;
const argKey = "key=WW5BZ-J4LCM-UIT6I-65MXY-Z5HDT-VRFFU";
wx.request({
url: `https://apis.map.qq.com/ws/geocoder/v1/?${argLoc}&${argKey}`,
success: res => {
if (res.statusCode === 200) {
this.setData({
location: {
lat: this.data.location!.lat,
lng: this.data.location!.lng,
text: (res.data as any).result?.formatted_addresses?.recommend
}
});
}
}
});
});
},
async chooseLocation() {
const location = await wx.chooseLocation({});
this.setData({
location: {
lat: location.latitude,
lng: location.longitude,
text: location.name
}
});
},
async fetch() {
try {
const list = await MomentApi.getList();
if (!list || list.length === 0) {
return;
}
this.setData({
list: list.map((item: any) => {
const metadata = (typeof item.metadata === "string" ? JSON.parse(item.metadata) : item.metadata) as PreviewImageMetadata;
const thumbURL = `${config.url}/attachment/read/${item.mongoId}`;
const sourceURL = `${config.url}/attachment/read/${metadata.sourceMongoId}`;
const isImage = metadata.sourceMimeType?.startsWith("image/");
return {
id: item.id,
type: isImage ? MediaItemType.IMAGE : MediaItemType.VIDEO,
thumbURL,
sourceURL,
checked: false
} as Item;
})
});
} catch (error) {
console.error("加载 moment 列表失败:", error);
}
},
updateHasChecked() {
this.setData({ hasChecked: this.data.list.some(item => item.checked) });
},
onCheckChange(e: WechatMiniprogram.BaseEvent) {
const index = e.currentTarget.dataset.index;
const list = [...this.data.list];
list[index].checked = !list[index].checked;
this.setData({ list });
this.updateHasChecked();
},
preview(e: WechatMiniprogram.BaseEvent) {
const index = e.currentTarget.dataset.index;
const total = this.data.list.length;
const startIndex = Math.max(0, index - 25);
const endIndex = Math.min(total, startIndex + 50);
const newCurrentIndex = index - startIndex;
const sources = this.data.list.slice(startIndex, endIndex).map((item: Item) => {
return {
url: item.sourceURL,
type: item.type.toLowerCase()
}
}) as any;
wx.previewMedia({
current: newCurrentIndex,
sources
})
},
uploadMedia() {
const handleFail = (e?: any) => {
wx.showToast({ title: "上传失败", icon: "error" });
wx.hideLoading();
this.setData({
isUploading: false,
});
wx.reportEvent("wxdata_perf_monitor", {
wxdata_perf_monitor_id: "MOMENT_UPLOAD",
wxdata_perf_monitor_level: 9,
wxdata_perf_error_code: 1,
wxdata_perf_error_msg: e?.message
});
};
const that = this;
wx.chooseMedia({
mediaType: ["mix"],
sourceType: ["album", "camera"],
camera: "back",
async success(res) {
that.setData({
isUploading: true
});
wx.showLoading({
title: "正在读取..",
mask: true
})
let files = res.tempFiles;
// 计算 MD5
const md5Results: MD5Result[] = [];
await Promise.all(files.map(async (file) => {
const md5 = await new Promise((resolve, reject) => {
wx.getFileSystemManager().getFileInfo({
filePath: file.tempFilePath,
digestAlgorithm: "md5",
success: res => resolve(res.digest),
fail: () => reject(`读取失败: ${file.tempFilePath}`)
});
});
md5Results.push({
path: file.tempFilePath,
md5: md5,
} as MD5Result);
}));
// 查重
const filterMD5Result: string[] = await MomentApi.filterByMD5(
md5Results.map(item => item.md5)
);
// 过滤文件
const filterPath = md5Results.filter(item => filterMD5Result.indexOf(item.md5) !== -1)
.map(item => item.path);
files = files.filter(file => filterPath.indexOf(file.tempFilePath) !== -1);
if (files.length === 0) {
wx.hideLoading();
that.setData({ isUploading: false });
return;
}
// 使用 Network.uploadFiles 上传文件
try {
const tempFileIds = await Network.uploadFiles({
mediaList: files.map(file => ({
path: file.tempFilePath,
size: file.size
})),
onProgress: (progress) => {
that.setData({
uploaded: IOSize.formatWithoutUnit(progress.uploaded, 2, Unit.MB),
uploadTotal: IOSize.format(progress.total, 2, Unit.MB),
uploadSpeed: `${IOSize.format(progress.speed)} / s`,
uploadProgress: progress.percent
});
},
showLoading: true
});
// 上传完成转附件
const list = await MomentApi.create(tempFileIds);
wx.showToast({ title: "上传成功", icon: "success" });
const added = list.map((item: any) => {
const metadata = (typeof item.metadata === "string" ? JSON.parse(item.metadata) : item.metadata) as PreviewImageMetadata;
const thumbURL = `${config.url}/attachment/read/${item.mongoId}`;
const sourceURL = `${config.url}/attachment/read/${metadata.sourceMongoId}`;
const isImage = item.mimeType?.startsWith("image/");
return {
id: item.id,
type: isImage ? MediaItemType.IMAGE : MediaItemType.VIDEO,
thumbURL,
sourceURL,
checked: false
} as Item;
});
// 前插列表
that.data.list.unshift(...added);
that.setData({
list: that.data.list,
isUploading: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadProgress: 0
});
that.updateHasChecked();
} catch (error) {
handleFail(error);
}
}
})
},
showArchivePopup() {
this.setData({
isVisibleArchivePopup: true,
archiveStep: "select-type",
selectedJournalId: null
});
},
onArchiveToNew() {
this.setData({
archiveStep: "form",
selectedJournalId: null
});
},
onArchiveToExisting() {
this.setData({
archiveStep: "select-journal",
selectedJournalId: null
});
},
onJournalListSelect(e: any) {
const { id } = e.detail;
this.setData({
selectedJournalId: id
});
},
onJournalListConfirm() {
if (this.data.selectedJournalId) {
this.archiveChecked();
}
},
onJournalListCancel() {
this.setData({
archiveStep: "select-type",
selectedJournalId: null
});
},
onNewJournalBack() {
this.setData({
archiveStep: "select-type"
});
},
toggleArchivePopup() {
this.setData({
isVisibleArchivePopup: !this.data.isVisibleArchivePopup
});
},
onArchivePopupVisibleChange(e: any) {
this.setData({
isVisibleArchivePopup: e.detail.visible
});
},
onChangeArchiveType(e: any) {
const { value } = e.detail;
this.setData({ type: value });
},
async archiveChecked() {
const handleFail = () => {
wx.showToast({ title: "归档失败", icon: "error" });
wx.hideLoading();
this.setData({
isArchiving: false
});
};
this.setData({
isArchiving: true
});
wx.showLoading({
title: "正在归档..",
mask: true
})
const openId = await new Promise<string>((resolve, reject) => {
wx.login({
success: async (res) => {
if (res.code) {
try {
const openId = await JournalApi.getOpenId(res.code);
resolve(openId);
} catch (error) {
reject(new Error("获取 openId 失败"));
}
} else {
reject(new Error("获取登录凭证失败"));
}
},
fail: handleFail
});
});
const archiveData: any = {
type: this.data.type,
idea: this.data.idea,
lat: this.data.location?.lat,
lng: this.data.location?.lng,
location: this.data.location?.text,
pusher: openId,
thumbIds: this.data.list.filter(item => item.checked).map(item => item.id)
};
// 如果选择了已存在的记录,添加 id 参数
if (this.data.selectedJournalId) {
archiveData.id = this.data.selectedJournalId;
}
try {
await MomentApi.archive(archiveData);
Events.emit("JOURNAL_REFRESH");
wx.showToast({ title: "归档成功", icon: "success" });
this.setData({
idea: "",
list: [],
hasChecked: false,
isArchiving: false,
selectedJournalId: undefined,
isVisibleArchivePopup: false
});
await Toolkit.sleep(1000);
this.fetch();
} catch (error) {
handleFail();
}
},
allChecked() {
this.data.list.forEach(item => item.checked = true);
this.setData({
list: this.data.list
});
this.updateHasChecked();
},
clearChecked() {
wx.showModal({
title: "提示",
content: "确认清空已选照片或视频吗?",
confirmText: "清空已选",
confirmColor: "#E64340",
cancelText: "取消",
success: res => {
if (res.confirm) {
this.data.list.forEach(item => {
item.checked = false;
})
this.setData({
list: this.data.list
});
this.updateHasChecked();
}
}
})
},
deleteChecked() {
wx.showModal({
title: "提示",
content: "确认删除已选照片或视频吗?",
confirmText: "删除已选",
confirmColor: "#E64340",
cancelText: "取消",
success: async (res) => {
if (res.confirm) {
const selected = this.data.list.filter(item => item.checked);
try {
await MomentApi.delete(selected.map(item => item.id));
wx.showToast({ title: "删除成功", icon: "success" });
const list = this.data.list.filter(item => !item.checked);
this.setData({
list
});
this.updateHasChecked();
} catch (error) {
console.error("删除 moment 失败:", error);
wx.showToast({ title: "删除失败", icon: "error" });
}
}
}
})
}
})

View File

@ -0,0 +1,193 @@
<!--pages/main/moment/index.wxml-->
<view class="custom-navbar">
<t-navbar class="custom-navbar" title="瞬间" placeholder />
</view>
<view class="moment">
<view class="tips">
<text>由于微信限制,一次只能上传 20 张照片或视频,可以先在此页面分批次将所有照片或视频上传,</text>
<text style="color: #F30">记得勾选原图</text>
<text>。无需担心重复选择,已上传的文件不会再次上传。上传后有空再挑选归档,归档后此页面不再显示该照片或视频。</text>
</view>
<view class="action">
<view class="line">
<t-button
class="btn upload"
theme="primary"
plain="true"
disabled="{{isSubmitting}}"
bind:tap="uploadMedia"
>上传照片/视频</t-button>
<t-button
class="btn archive"
theme="primary"
plain="true"
bind:tap="showArchivePopup"
disabled="{{isSubmitting || list.length === 0 || !hasChecked}}"
>归档已选</t-button>
</view>
<view class="line">
<t-button
class="btn clear"
theme="primary"
variant="outline"
bind:tap="allChecked"
disabled="{{isSubmitting || list.length === 0}}"
>全选</t-button>
<t-button
class="btn clear"
theme="danger"
variant="outline"
bind:tap="clearChecked"
disabled="{{isSubmitting || list.length === 0 || !hasChecked}}"
>清空已选</t-button>
<t-button
class="btn delete"
theme="danger"
variant="outline"
bind:tap="deleteChecked"
disabled="{{isSubmitting || list.length === 0 || !hasChecked}}"
>删除已选</t-button>
</view>
</view>
<view wx:if="{{isUploading}}" class="uploading">
<progress
class="progress"
percent="{{uploadProgress}}"
stroke-width="6"
/>
<view class="text">
<view>{{uploaded}} / {{uploadTotal}}</view>
<view>{{uploadSpeed}}</view>
</view>
</view>
<view class="items">
<view class="item" wx:for="{{list}}" wx:key="mongoId">
<image
class="thumbnail {{item.type}}"
src="{{item.thumbURL}}"
mode="widthFix"
bind:tap="preview"
data-index="{{index}}"
></image>
<t-checkbox
class="checkbox"
block="{{true}}"
checked="{{item.checked}}"
bind:change="onCheckChange"
data-index="{{index}}"
/>
<view wx:if="{{item.checked}}" class="checkbox-fill"></view>
</view>
</view>
</view>
<t-popup
class="archive-popup"
visible="{{isVisibleArchivePopup}}"
placement="bottom"
usingCustomNavbar
bind:visible-change="onArchivePopupVisibleChange"
>
<!-- 选择归档方式 -->
<view wx:if="{{archiveStep === 'select-type'}}" class="container select-type">
<view class="header">
<t-button
class="btn cancel"
bind:tap="toggleArchivePopup"
variant="text"
>取消</t-button>
<view class="title">归档到</view>
<view class="placeholder"></view>
</view>
<t-cell-group class="content">
<t-cell
title="新纪录"
leftIcon="bookmark-add"
arrow
bind:tap="onArchiveToNew"
/>
<t-cell
title="已存在记录"
leftIcon="view-list"
arrow
bind:tap="onArchiveToExisting"
/>
</t-cell-group>
</view>
<!-- 归档表单 -->
<view wx:if="{{archiveStep === 'form'}}" class="container form">
<view class="header">
<t-button
class="btn back"
bind:tap="onNewJournalBack"
variant="text"
>返回</t-button>
<view class="title">归档到新纪录</view>
<t-button
class="btn confirm"
theme="primary"
bind:tap="archiveChecked"
variant="text"
>确定</t-button>
</view>
<view class="content">
<view class="section">
<textarea
class="idea"
placeholder="那一刻的想法..."
model:value="{{idea}}"
/>
</view>
<view class="section type">
<text class="label">类型:</text>
<t-radio-group bind:change="onChangeArchiveType" default-value="NORMAL" borderless t-class="box">
<t-radio class="radio" block="{{false}}" label="日常" value="NORMAL" />
<t-radio class="radio" block="{{false}}" label="专拍" value="PORTFOLIO" />
</t-radio-group>
</view>
<view class="section time">
<text class="label">时间:</text>
<picker class="picker" mode="date" model:value="{{date}}">
<view class="picker">
{{date}}
</view>
</picker>
<picker class="picker" mode="time" model:value="{{time}}">
<view class="picker">
{{time}}
</view>
</picker>
</view>
<view class="section location">
<text class="label">位置:</text>
<text wx:if="{{location}}" bind:tap="chooseLocation">{{location.text}}</text>
<text wx:else bind:tap="chooseLocation">选择位置..</text>
</view>
</view>
</view>
<!-- 选择已存在记录 -->
<view wx:if="{{archiveStep === 'select-journal'}}" class="container select-journal">
<view class="header">
<t-button
class="btn back"
bind:tap="onJournalListCancel"
variant="text"
>返回</t-button>
<view class="title">归档到已存在记录</view>
<t-button
class="btn confirm"
bind:tap="onJournalListConfirm"
theme="primary"
variant="text"
disabled="{{!selectedJournalId}}"
>确定</t-button>
</view>
<view class="content">
<journal-list
visible="{{archiveStep === 'select-journal'}}"
searchable="{{true}}"
selectedId="{{selectedJournalId}}"
bind:select="onJournalListSelect"
/>
</view>
</view>
</t-popup>