merge journal-creater, journal-editor

This commit is contained in:
Timi
2025-12-12 17:49:20 +08:00
parent cbf804c535
commit 880e702288
10 changed files with 505 additions and 858 deletions

View File

@ -2,7 +2,6 @@
"pages": [
"pages/index/index",
"pages/main/journal/index",
"pages/main/journal-creater/index",
"pages/main/journal-search/index",
"pages/main/journal-editor/index",
"pages/main/journal-map/index",

View File

@ -1,10 +0,0 @@
{
"component": true,
"usingComponents": {
"t-icon": "tdesign-miniprogram/icon/icon",
"t-radio": "tdesign-miniprogram/radio/radio",
"t-button": "tdesign-miniprogram/button/button",
"t-navbar": "tdesign-miniprogram/navbar/navbar",
"t-radio-group": "tdesign-miniprogram/radio-group/radio-group"
}
}

View File

@ -1,146 +0,0 @@
/* pages/main/journal-creater/index.wxss */
.container {
.content {
width: calc(100% - 64px);
padding: 0 32px 32px 32px;
display: flex;
align-items: center;
flex-direction: column;
.label {
color: var(--theme-text-secondary);
}
.section {
width: 100%;
margin-top: 1.5rem;
&.type {
display: flex;
.radio {
margin-right: 1em;
}
}
&.time {
display: flex;
.picker {
margin-right: .25rem;
}
}
&.media {
.ctrl {
display: flex;
.clear {
width: 100px;
padding-left: 0;
padding-right: 0;
}
}
.gallery {
gap: 10rpx;
display: grid;
grid-template-columns: repeat(3, 1fr);
.item {
height: 200rpx;
position: relative;
overflow: hidden;
background: var(--theme-bg-card);
box-shadow: 1px 1px 6px var(--theme-shadow-light);
border-radius: 2rpx;
&.add {
color: var(--theme-wx);
margin: 0;
font-size: 80rpx;
background: transparent;
}
.thumbnail {
width: 200rpx;
height: 200rpx;
display: block;
}
.video-container {
position: relative;
.play-icon {
top: 50%;
left: 50%;
color: rgba(255, 255, 255, .8);
z-index: 2;
position: absolute;
font-size: 128rpx;
transform: translate(-50%, -50%);
text-shadow: 4rpx 4rpx 0 rgba(0, 0, 0, .5);
pointer-events: none;
}
}
.delete {
top: 10rpx;
right: 10rpx;
color: rgba(255, 255, 255, .6);
z-index: 3;
position: absolute;
font-size: 45rpx;
&::after {
content: "";
top: 0;
width: 100%;
height: 100%;
z-index: -1;
position: absolute;
background: rgba(0, 0, 0, .6);
border-radius: 50%;
}
}
}
}
}
}
.uploading {
width: 100%;
margin-top: 1rem;
.progress {
margin-bottom: 8rpx;
}
.text {
color: var(--theme-text-secondary);
display: flex;
font-size: .8rem;
justify-content: space-between;
}
}
.ctrl {
width: 100%;
display: flex;
margin-top: 1rem;
align-items: center;
.clear {
width: 200rpx;
}
.submit {
flex: 1;
margin-left: 12rpx;
}
}
}
}

View File

@ -1,376 +0,0 @@
// pages/main/journal-creater/index.ts
import Events from "../../../utils/Events";
import Time from "../../../utils/Time";
import Toolkit from "../../../utils/Toolkit";
import config from "../../../config/index";
import { JournalType } from "../../../types/Journal";
import IOSize, { Unit } from "../../../utils/IOSize";
enum MediaItemType {
IMAGE,
VIDEO
}
type MediaItem = {
type: MediaItemType;
path: string;
thumbPath: string;
size: number;
duration: number | undefined;
raw: any;
}
export type Location = {
lat: number;
lng: number;
text?: string;
}
interface JournalEditorData {
idea: string;
date: string;
time: string;
type: JournalType;
mediaList: MediaItem[];
location?: Location;
qqMapSDK?: any;
isAuthLocation: boolean;
uploaded: string;
uploadTotal: string;
uploadSpeed: string;
uploadProgress: number;
isSubmitting: boolean;
}
Page({
data: <JournalEditorData>{
idea: "",
date: "2025-06-28",
time: "16:00",
type: JournalType.NORMAL,
mediaList: [],
location: undefined,
isAuthLocation: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadSpeed: "0 MB / s",
uploadProgress: 0,
isSubmitting: false,
mediaItemTypeEnum: {
...MediaItemType
}
},
async onLoad() {
// 授权定位
const setting = await wx.getSetting();
wx.setStorageSync("isAuthLocation", setting.authSetting["scope.userLocation"]);
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({
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
}
});
}
}
});
});
},
onChangeType(e: any) {
const { value } = e.detail;
this.setData({ type: value });
},
async chooseLocation() {
const location = await wx.chooseLocation({});
this.setData({
location: {
lat: location.latitude,
lng: location.longitude,
text: location.name
}
});
},
addMedia() {
const that = this;
wx.chooseMedia({
mediaType: ["mix"],
sourceType: ["album", "camera"],
camera: "back",
success(res) {
wx.showLoading({
title: "加载中..",
mask: true
})
const tempFiles = res.tempFiles;
const mediaList = tempFiles.map(item => {
return {
type: (<any>MediaItemType)[item.fileType.toUpperCase()],
path: item.tempFilePath,
thumbPath: item.thumbTempFilePath,
size: item.size,
duration: item.duration,
raw: item
} as MediaItem;
});
that.setData({
mediaList: [...that.data.mediaList, ...mediaList]
});
wx.hideLoading();
}
})
},
clearMedia() {
wx.showModal({
title: "提示",
content: "确认清空已选照片或视频吗?",
confirmText: "清空",
confirmColor: "#E64340",
cancelText: "取消",
success: res => {
if (res.confirm) {
this.setData({
mediaList: []
});
}
}
})
},
preview(e: WechatMiniprogram.BaseEvent) {
const itemIndex = e.currentTarget.dataset.index;
const total = this.data.mediaList.length;
const startIndex = Math.max(0, itemIndex - 25);
const endIndex = Math.min(total, startIndex + 50);
const newCurrentIndex = itemIndex - startIndex;
const sources = this.data.mediaList.slice(startIndex, endIndex).map(item => {
return {
url: item.path,
type: MediaItemType[item.type].toLowerCase()
} as WechatMiniprogram.MediaSource;
});
wx.previewMedia({
current: newCurrentIndex,
sources
});
},
deleteMedia(e: WechatMiniprogram.BaseEvent) {
const index = e.currentTarget.dataset.index;
const mediaList = [...this.data.mediaList];
mediaList.splice(index, 1);
this.setData({
mediaList
});
},
cancel() {
wx.switchTab({
url: "/pages/main/journal/index",
})
},
submit() {
const handleFail = () => {
wx.showToast({ title: "上传失败", icon: "error" });
wx.hideLoading();
this.setData({
isSubmitting: false
});
};
this.setData({
isSubmitting: true
});
// 获取 openId
const getOpenId = new Promise<string>((resolve, reject) => {
wx.login({
success: (res) => {
if (res.code) {
wx.request({
url: `${config.url}/journal/openid`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: {
code: res.code
},
success: (resp) => {
const data = resp.data as any;
if (data.code === 20000) {
resolve(data.data);
} else {
reject(new Error("获取 openId 失败"));
}
},
fail: () => reject(new Error("获取 openId 请求失败"))
});
} else {
reject(new Error("获取登录凭证失败"));
}
},
fail: () => reject(new Error("登录失败"))
});
});
// 文件上传
const uploadFiles = new Promise<string[]>((resolve, reject) => {
const mediaList = this.data.mediaList || [];
if (mediaList.length === 0) {
resolve([]);
return;
}
wx.showLoading({ title: "正在上传..", mask: true });
// 计算总大小
const sizePromises = mediaList.map(item => {
return new Promise<number>((sizeResolve, sizeReject) => {
wx.getFileSystemManager().getFileInfo({
filePath: item.path,
success: (res) => sizeResolve(res.size),
fail: (err) => sizeReject(err)
});
});
});
Promise.all(sizePromises).then(fileSizes => {
const totalSize = fileSizes.reduce((acc, size) => acc + size, 0);
const uploadTasks: WechatMiniprogram.UploadTask[] = [];
let uploadedSize = 0;
let lastUploadedSize = 0;
this.setData({
uploadTotal: IOSize.format(totalSize, 2, Unit.MB)
});
// 计算上传速度
const speedUpdateInterval = setInterval(() => {
const chunkSize = uploadedSize - lastUploadedSize;
this.setData({
uploadSpeed: `${IOSize.format(chunkSize)} / s`
});
lastUploadedSize = uploadedSize;
}, 1000);
// 上传文件
const uploadPromises = mediaList.map(item => {
return new Promise<string>((uploadResolve, uploadReject) => {
const task = wx.uploadFile({
url: `${config.url}/temp/file/upload`,
filePath: item.path,
name: "file",
success: (resp) => {
const result = JSON.parse(resp.data);
if (result && result.code === 20000) {
uploadResolve(result.data[0].id);
} else {
uploadReject(new Error(`文件上传失败: ${result?.message || "未知错误"}`));
}
},
fail: (err) => uploadReject(new Error(`文件上传失败: ${err.errMsg}`))
});
// 监听上传进度
let prevProgress = 0;
task.onProgressUpdate((res) => {
const fileUploaded = (res.totalBytesExpectedToSend * res.progress) / 100;
const delta = fileUploaded - prevProgress;
uploadedSize += delta;
prevProgress = fileUploaded;
// 更新进度条
this.setData({
uploaded: IOSize.formatWithoutUnit(uploadedSize, 2, Unit.MB),
uploadProgress: Math.round((uploadedSize / totalSize) * 10000) / 100
});
});
uploadTasks.push(task);
});
});
Promise.all(uploadPromises).then((tempFileIds) => {
// 清除定时器
clearInterval(speedUpdateInterval);
uploadTasks.forEach(task => task.offProgressUpdate());
this.setData({
uploadProgress: 100,
uploadSpeed: "0 MB / s"
});
resolve(tempFileIds);
}).catch((e: Error) => {
// 取消所有上传任务
uploadTasks.forEach(task => task.abort());
clearInterval(speedUpdateInterval);
reject(e);
});
}).catch(reject);
});
// 并行执行获取 openId 和文件上传
Promise.all([getOpenId, uploadFiles]).then(([openId, tempFileIds]) => {
wx.showLoading({ title: "正在保存..", mask: true });
wx.request({
url: `${config.url}/journal/create`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: {
idea: this.data.idea,
type: this.data.type,
lat: this.data.location?.lat,
lng: this.data.location?.lng,
location: this.data.location?.text,
pusher: openId,
createdAt: Date.parse(`${this.data.date} ${this.data.time}`),
tempFileIds
},
success: async () => {
Events.emit("JOURNAL_REFRESH");
wx.showToast({ title: "提交成功", icon: "success" });
this.setData({
idea: "",
mediaList: [],
isSubmitting: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadProgress: 0
});
await Toolkit.sleep(1000);
wx.switchTab({
url: "/pages/main/journal/index"
});
},
fail: handleFail
});
}).catch(handleFail);
}
});

View File

@ -1,118 +0,0 @@
<!--pages/main/journal-creater/index.wxml-->
<t-navbar title="新纪录">
<text slot="left" bindtap="cancel">取消</text>
</t-navbar>
<scroll-view
class="container"
type="custom"
scroll-y
show-scrollbar="{{false}}"
scroll-into-view="{{intoView}}"
>
<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="onChangeType" 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 class="section media">
<view class="gallery">
<block wx:for="{{mediaList}}" wx:key="index">
<view class="item">
<!-- 图片 -->
<image
wx:if="{{item.type === mediaItemTypeEnum.IMAGE}}"
src="{{item.path}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
></image>
<!-- 视频 -->
<view wx:if="{{item.type === mediaItemTypeEnum.VIDEO}}" class="video-container">
<image
src="{{item.thumbPath}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
></image>
<t-icon class="play-icon" name="play" />
</view>
<!-- 删除 -->
<t-icon
class="delete"
name="close"
bindtap="deleteMedia"
data-index="{{index}}"
data-new-media="{{true}}"
/>
</view>
</block>
<t-button
class="item add"
theme="primary"
plain="true"
disabled="{{isSubmitting}}"
bind:tap="addMedia"
>
<t-icon class="icon" name="add" />
</t-button>
</view>
</view>
<view wx:if="{{isSubmitting}}" class="uploading">
<progress
class="progress"
percent="{{uploadProgress}}"
stroke-width="6"
/>
<view class="text">
<view>{{uploaded}} / {{uploadTotal}}</view>
<view>{{uploadSpeed}}</view>
</view>
</view>
<view class="ctrl">
<t-button
class="clear"
theme="danger"
variant="outline"
disabled="{{isSubmitting}}"
bind:tap="clearMedia"
disabled="{{mediaList.length === 0}}"
>清空已选</t-button>
<t-button
class="submit"
theme="primary"
bind:tap="submit"
disabled="{{(!idea && mediaList.length === 0) || isSubmitting}}"
>提交</t-button>
</view>
</view>
</scroll-view>

View File

@ -141,10 +141,12 @@
margin-top: 1rem;
align-items: center;
.clear,
.delete {
width: 200rpx;
}
.submit,
.save {
flex: 1;
margin-left: 12rpx;

View File

@ -9,28 +9,49 @@ import { MediaAttachExt, MediaAttachType } from "../../../types/Attachment";
import IOSize, { Unit } from "../../../utils/IOSize";
interface JournalEditorData {
/** 模式create 或 edit */
mode: "create" | "edit";
/** 日记 ID编辑模式 */
id?: number;
/** 想法 */
idea: string;
/** 日期 */
date: string;
/** 时间 */
time: string;
/** 类型 */
type: JournalType;
mediaList: MediaItem[];
/** 媒体列表(创建模式:新选择的媒体;编辑模式:现有附件) */
mediaList: (MediaItem | WechatMediaItem)[];
/** 新媒体列表(仅编辑模式使用) */
newMediaList: WechatMediaItem[];
/** 位置 */
location?: Location;
/** 是否授权定位 */
isAuthLocation: boolean;
/** 是否正在加载(编辑模式) */
isLoading: boolean;
/** 是否正在保存/提交 */
isSaving: boolean;
/** 已上传大小 */
uploaded: string;
/** 总大小 */
uploadTotal: string;
/** 上传速度 */
uploadSpeed: string;
/** 上传进度 */
uploadProgress: number;
/** 媒体类型枚举 */
mediaItemTypeEnum: any;
/** 删除对话框可见性 */
deleteDialogVisible: boolean;
/** 删除确认文本 */
deleteConfirmText: string;
}
Page({
data: <JournalEditorData>{
mode: "create",
id: undefined,
idea: "",
date: "2025-06-28",
@ -40,7 +61,7 @@ Page({
newMediaList: [],
location: undefined,
isSaving: false,
isLoading: true,
isLoading: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadSpeed: "0 MB / s",
@ -52,6 +73,7 @@ Page({
deleteDialogVisible: false,
deleteConfirmText: ""
},
async onLoad(options: any) {
// 授权定位
const setting = await wx.getSetting();
@ -66,22 +88,65 @@ Page({
this.setData({ isAuthLocation });
});
}
// 获取日记 ID
// 判断模式:有 ID 是编辑,无 ID 是创建
const id = options.id ? parseInt(options.id) : undefined;
if (!id) {
wx.showToast({
title: "缺少日志 ID",
icon: "error"
if (id) {
// 编辑模式
this.setData({
mode: "edit",
id,
isLoading: true
});
setTimeout(() => {
wx.navigateBack();
}, 1500);
return;
await this.loadJournalDetail(id);
} else {
// 创建模式
this.setData({
mode: "create",
isLoading: false
});
// 设置当前时间
const unixTime = new Date().getTime();
this.setData({
date: Time.toDate(unixTime),
time: Time.toTime(unixTime)
});
// 获取默认定位
this.getDefaultLocation();
}
this.setData({ id });
await this.loadJournalDetail(id);
},
/** 加载日记详情 */
/** 获取默认定位(创建模式) */
getDefaultLocation() {
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
}
});
}
}
});
}).catch(() => {
// 忽略定位失败
});
},
/** 加载日记详情(编辑模式) */
async loadJournalDetail(id: number) {
wx.showLoading({ title: "加载中...", mask: true });
try {
@ -102,6 +167,7 @@ Page({
fail: reject
});
});
const items = journal.items || [];
const thumbItems = items.filter((item) => item.attachType === MediaAttachType.THUMB);
@ -117,6 +183,7 @@ Page({
attachmentId: thumbItem.id
} as MediaItem;
});
this.setData({
idea: journal.idea || "",
date: Time.toDate(journal.createdAt),
@ -142,20 +209,25 @@ Page({
}, 1500);
}
},
/** 改变类型 */
onChangeType(e: any) {
const { value } = e.detail;
this.setData({ type: value });
},
/** 选择位置 */
async chooseLocation() {
const location = await wx.chooseLocation({});
this.setData({
location: {
lat: location.latitude,
lng: location.longitude,
text: location.name
}
});
try {
const location = await wx.chooseLocation({});
this.setData({
location: {
lat: location.latitude,
lng: location.longitude,
text: location.name
}
});
} catch (err) {
// 用户取消选择
}
},
/** 新增附件 */
addMedia() {
@ -180,58 +252,117 @@ Page({
raw: item
} as WechatMediaItem;
});
that.setData({
newMediaList: [...that.data.newMediaList, ...newMedia]
});
if (that.data.mode === "create") {
// 创建模式:直接添加到 mediaList
that.setData({
mediaList: [...that.data.mediaList, ...newMedia]
});
} else {
// 编辑模式:添加到 newMediaList
that.setData({
newMediaList: [...that.data.newMediaList, ...newMedia]
});
}
wx.hideLoading();
}
});
},
/** 清空媒体(仅创建模式) */
clearMedia() {
wx.showModal({
title: "提示",
content: "确认清空已选照片或视频吗?",
confirmText: "清空",
confirmColor: "#E64340",
cancelText: "取消",
success: res => {
if (res.confirm) {
this.setData({
mediaList: []
});
}
}
});
},
/** 预览附件 */
preview(e: WechatMiniprogram.BaseEvent) {
const isNewMedia = e.currentTarget.dataset.newMedia;
const index = e.currentTarget.dataset.index;
const sources = this.data.mediaList.map(item => ({
url: item.sourceURL,
type: MediaItemType[item.type].toLowerCase()
}));
const newSources = this.data.newMediaList.map(item => ({
url: item.path,
type: MediaItemType[item.type].toLowerCase()
}));
const allSources = [...sources, ...newSources];
const itemIndex = isNewMedia ? this.data.mediaList.length + index : index;
const total = allSources.length;
if (this.data.mode === "create") {
// 创建模式:只有 mediaList
const sources = (this.data.mediaList as WechatMediaItem[]).map(item => ({
url: item.path,
type: MediaItemType[item.type].toLowerCase()
}));
const startIndex = Math.max(0, itemIndex - 25);
const endIndex = Math.min(total, startIndex + 50);
const newCurrentIndex = itemIndex - startIndex;
const total = sources.length;
const startIndex = Math.max(0, index - 25);
const endIndex = Math.min(total, startIndex + 50);
const newCurrentIndex = index - startIndex;
wx.previewMedia({
current: newCurrentIndex,
sources: allSources.slice(startIndex, endIndex) as WechatMiniprogram.MediaSource[]
});
wx.previewMedia({
current: newCurrentIndex,
sources: sources.slice(startIndex, endIndex) as WechatMiniprogram.MediaSource[]
});
} else {
// 编辑模式mediaList + newMediaList
const sources = (this.data.mediaList as MediaItem[]).map(item => ({
url: item.sourceURL,
type: MediaItemType[item.type].toLowerCase()
}));
const newSources = this.data.newMediaList.map(item => ({
url: item.path,
type: MediaItemType[item.type].toLowerCase()
}));
const allSources = [...sources, ...newSources];
const itemIndex = isNewMedia ? this.data.mediaList.length + index : index;
const total = allSources.length;
const startIndex = Math.max(0, itemIndex - 25);
const endIndex = Math.min(total, startIndex + 50);
const newCurrentIndex = itemIndex - startIndex;
wx.previewMedia({
current: newCurrentIndex,
sources: allSources.slice(startIndex, endIndex) as WechatMiniprogram.MediaSource[]
});
}
},
/** 删除附件 */
deleteMedia(e: WechatMiniprogram.BaseEvent) {
const isNewMedia = e.currentTarget.dataset.newMedia;
const index = e.currentTarget.dataset.index;
if (isNewMedia) {
if (this.data.mode === "create") {
// 创建模式:从 mediaList 删除
const mediaList = [...this.data.mediaList];
mediaList.splice(index, 1);
this.setData({ mediaList });
} else {
const newMediaList = [...this.data.newMediaList];
newMediaList.splice(index, 1);
this.setData({ newMediaList });
// 编辑模式:根据标识删除
if (isNewMedia) {
const newMediaList = [...this.data.newMediaList];
newMediaList.splice(index, 1);
this.setData({ newMediaList });
} else {
const mediaList = [...this.data.mediaList];
mediaList.splice(index, 1);
this.setData({ mediaList });
}
}
},
/** 取消编辑 */
/** 取消 */
cancel() {
wx.navigateBack();
if (this.data.mode === "create") {
wx.switchTab({
url: "/pages/main/journal/index"
});
} else {
wx.navigateBack();
}
},
/** 删除记录 */
/** 删除记录(仅编辑模式) */
deleteJournal() {
this.setData({
deleteDialogVisible: true,
@ -301,8 +432,100 @@ Page({
}
});
},
/** 保存 */
save() {
/** 提交/保存 */
submit() {
if (this.data.mode === "create") {
this.createJournal();
} else {
this.updateJournal();
}
},
/** 创建日记 */
createJournal() {
const handleFail = () => {
wx.showToast({ title: "上传失败", icon: "error" });
wx.hideLoading();
this.setData({
isSaving: false
});
};
this.setData({
isSaving: true
});
// 获取 openId
const getOpenId = new Promise<string>((resolve, reject) => {
wx.login({
success: (res) => {
if (res.code) {
wx.request({
url: `${config.url}/journal/openid`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: {
code: res.code
},
success: (resp) => {
const data = resp.data as any;
if (data.code === 20000) {
resolve(data.data);
} else {
reject(new Error("获取 openId 失败"));
}
},
fail: () => reject(new Error("获取 openId 请求失败"))
});
} else {
reject(new Error("获取登录凭证失败"));
}
},
fail: () => reject(new Error("登录失败"))
});
});
// 文件上传
const uploadFiles = this.uploadMediaFiles(this.data.mediaList as WechatMediaItem[]);
// 并行执行获取 openId 和文件上传
Promise.all([getOpenId, uploadFiles]).then(([openId, tempFileIds]) => {
wx.showLoading({ title: "正在保存..", mask: true });
wx.request({
url: `${config.url}/journal/create`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: {
idea: this.data.idea,
type: this.data.type,
lat: this.data.location?.lat,
lng: this.data.location?.lng,
location: this.data.location?.text,
pusher: openId,
createdAt: Date.parse(`${this.data.date} ${this.data.time}`),
tempFileIds
},
success: async () => {
Events.emit("JOURNAL_REFRESH");
wx.showToast({ title: "提交成功", icon: "success" });
this.setData({
idea: "",
mediaList: [],
isSaving: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadProgress: 0
});
await Toolkit.sleep(1000);
wx.switchTab({
url: "/pages/main/journal/index"
});
},
fail: handleFail
});
}).catch(handleFail);
},
/** 更新日记 */
updateJournal() {
const handleFail = () => {
wx.showToast({ title: "保存失败", icon: "error" });
wx.hideLoading();
@ -314,99 +537,10 @@ Page({
isSaving: true
});
// 收集保留的附件 ID缩略图 ID
const attachmentIds = this.data.mediaList.map(item => item.attachmentId);
const attachmentIds = (this.data.mediaList as MediaItem[]).map(item => item.attachmentId);
// 上传新媒体文件
const uploadFiles = new Promise<string[]>((resolve, reject) => {
if (this.data.newMediaList.length === 0) {
resolve([]);
return;
}
const uploadFiles = this.uploadMediaFiles(this.data.newMediaList);
wx.showLoading({ title: "正在上传..", mask: true });
// 计算总大小
const sizePromises = this.data.newMediaList.map(item => {
return new Promise<number>((sizeResolve, sizeReject) => {
wx.getFileSystemManager().getFileInfo({
filePath: item.path,
success: (res) => sizeResolve(res.size),
fail: (err) => sizeReject(err)
});
});
});
Promise.all(sizePromises).then(fileSizes => {
const totalSize = fileSizes.reduce((acc, size) => acc + size, 0);
const uploadTasks: WechatMiniprogram.UploadTask[] = [];
let uploadedSize = 0;
let lastUploadedSize = 0;
this.setData({
uploadTotal: IOSize.format(totalSize, 2, Unit.MB)
});
// 计算上传速度
const speedUpdateInterval = setInterval(() => {
const chunkSize = uploadedSize - lastUploadedSize;
this.setData({
uploadSpeed: `${IOSize.format(chunkSize)} / s`
});
lastUploadedSize = uploadedSize;
}, 1000);
// 上传文件
const uploadPromises = this.data.newMediaList.map(item => {
return new Promise<string>((uploadResolve, uploadReject) => {
const task = wx.uploadFile({
url: `${config.url}/temp/file/upload`,
filePath: item.path,
name: "file",
success: (resp) => {
const result = JSON.parse(resp.data);
if (result && result.code === 20000) {
uploadResolve(result.data[0].id);
} else {
uploadReject(new Error(`文件上传失败: ${result?.message || "未知错误"}`));
}
},
fail: (err) => uploadReject(new Error(`文件上传失败: ${err.errMsg}`))
});
// 监听上传进度
let prevProgress = 0;
task.onProgressUpdate((res) => {
const fileUploaded = (res.totalBytesExpectedToSend * res.progress) / 100;
const delta = fileUploaded - prevProgress;
uploadedSize += delta;
prevProgress = fileUploaded;
// 更新进度条
this.setData({
uploaded: IOSize.formatWithoutUnit(uploadedSize, 2, Unit.MB),
uploadProgress: Math.round((uploadedSize / totalSize) * 10000) / 100
});
});
uploadTasks.push(task);
});
});
Promise.all(uploadPromises).then((tempFileIds) => {
// 清除定时器
clearInterval(speedUpdateInterval);
uploadTasks.forEach(task => task.offProgressUpdate());
this.setData({
uploadProgress: 100,
uploadSpeed: "0 MB / s"
});
resolve(tempFileIds);
}).catch((e: Error) => {
// 取消所有上传任务
uploadTasks.forEach(task => task.abort());
clearInterval(speedUpdateInterval);
reject(e);
});
}).catch(reject);
});
// 提交保存
uploadFiles.then((tempFileIds) => {
wx.showLoading({ title: "正在保存..", mask: true });
@ -449,5 +583,97 @@ Page({
fail: handleFail
});
}).catch(handleFail);
},
/** 上传媒体文件 */
uploadMediaFiles(mediaList: WechatMediaItem[]): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
if (mediaList.length === 0) {
resolve([]);
return;
}
wx.showLoading({ title: "正在上传..", mask: true });
// 计算总大小
const sizePromises = mediaList.map(item => {
return new Promise<number>((sizeResolve, sizeReject) => {
wx.getFileSystemManager().getFileInfo({
filePath: item.path,
success: (res) => sizeResolve(res.size),
fail: (err) => sizeReject(err)
});
});
});
Promise.all(sizePromises).then(fileSizes => {
const totalSize = fileSizes.reduce((acc, size) => acc + size, 0);
const uploadTasks: WechatMiniprogram.UploadTask[] = [];
let uploadedSize = 0;
let lastUploadedSize = 0;
this.setData({
uploadTotal: IOSize.format(totalSize, 2, Unit.MB)
});
// 计算上传速度
const speedUpdateInterval = setInterval(() => {
const chunkSize = uploadedSize - lastUploadedSize;
this.setData({
uploadSpeed: `${IOSize.format(chunkSize)} / s`
});
lastUploadedSize = uploadedSize;
}, 1000);
// 上传文件
const uploadPromises = mediaList.map(item => {
return new Promise<string>((uploadResolve, uploadReject) => {
const task = wx.uploadFile({
url: `${config.url}/temp/file/upload`,
filePath: item.path,
name: "file",
success: (resp) => {
const result = JSON.parse(resp.data);
if (result && result.code === 20000) {
uploadResolve(result.data[0].id);
} else {
uploadReject(new Error(`文件上传失败: ${result?.message || "未知错误"}`));
}
},
fail: (err) => uploadReject(new Error(`文件上传失败: ${err.errMsg}`))
});
// 监听上传进度
let prevProgress = 0;
task.onProgressUpdate((res) => {
const fileUploaded = (res.totalBytesExpectedToSend * res.progress) / 100;
const delta = fileUploaded - prevProgress;
uploadedSize += delta;
prevProgress = fileUploaded;
// 更新进度条
this.setData({
uploaded: IOSize.formatWithoutUnit(uploadedSize, 2, Unit.MB),
uploadProgress: Math.round((uploadedSize / totalSize) * 10000) / 100
});
});
uploadTasks.push(task);
});
});
Promise.all(uploadPromises).then((tempFileIds) => {
// 清除定时器
clearInterval(speedUpdateInterval);
uploadTasks.forEach(task => task.offProgressUpdate());
this.setData({
uploadProgress: 100,
uploadSpeed: "0 MB / s"
});
resolve(tempFileIds);
}).catch((e: Error) => {
// 取消所有上传任务
uploadTasks.forEach(task => task.abort());
clearInterval(speedUpdateInterval);
reject(e);
});
}).catch(reject);
});
}
});

View File

@ -1,5 +1,5 @@
<!--pages/main/journal-editor/index.wxml-->
<t-navbar title="编辑记录">
<t-navbar title="{{mode === 'create' ? '新纪录' : '编辑记录'}}">
<text slot="left" bindtap="cancel">取消</text>
</t-navbar>
<scroll-view
@ -48,22 +48,51 @@
</view>
<view class="section media">
<view class="gallery">
<!-- 现有附件 -->
<block wx:for="{{mediaList}}" wx:key="attachmentId">
<view class="item">
<!-- 图片 -->
<image
wx:if="{{item.type === mediaItemTypeEnum.IMAGE}}"
src="{{item.thumbURL}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
data-new-media="{{false}}"
></image>
<!-- 视频 -->
<view wx:if="{{item.type === mediaItemTypeEnum.VIDEO}}" class="video-container">
<!-- 创建模式mediaList 显示新选择的媒体 -->
<block wx:if="{{mode === 'create'}}">
<block wx:for="{{mediaList}}" wx:key="index">
<view class="item">
<!-- 图片 -->
<image
wx:if="{{item.type === mediaItemTypeEnum.IMAGE}}"
src="{{item.path}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
data-new-media="{{true}}"
></image>
<!-- 视频 -->
<view wx:if="{{item.type === mediaItemTypeEnum.VIDEO}}" class="video-container">
<image
src="{{item.thumbPath}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
data-new-media="{{true}}"
></image>
<t-icon class="play-icon" name="play" />
</view>
<!-- 删除 -->
<t-icon
class="delete"
name="close"
bindtap="deleteMedia"
data-index="{{index}}"
data-new-media="{{true}}"
/>
</view>
</block>
</block>
<!-- 编辑模式mediaList 显示现有附件newMediaList 显示新添加的附件 -->
<block wx:else>
<!-- 现有附件 -->
<block wx:for="{{mediaList}}" wx:key="attachmentId">
<view class="item">
<!-- 图片 -->
<image
wx:if="{{item.type === mediaItemTypeEnum.IMAGE}}"
src="{{item.thumbURL}}"
class="thumbnail"
mode="aspectFill"
@ -71,55 +100,68 @@
data-index="{{index}}"
data-new-media="{{false}}"
></image>
<t-icon class="play-icon" name="play" />
<!-- 视频 -->
<view wx:if="{{item.type === mediaItemTypeEnum.VIDEO}}" class="video-container">
<image
src="{{item.thumbURL}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
data-new-media="{{false}}"
></image>
<t-icon class="play-icon" name="play" />
</view>
<!-- 删除 -->
<t-icon
class="delete"
name="close"
bindtap="deleteMedia"
data-index="{{index}}"
data-new-media="{{false}}"
/>
</view>
<!-- 删除 -->
<t-icon
class="delete"
name="close"
bindtap="deleteMedia"
data-index="{{index}}"
data-new-media="{{true}}"
/>
</view>
</block>
<!-- 新选择附件 -->
<block wx:for="{{newMediaList}}" wx:key="index">
<view class="item new-item">
<!-- 图片 -->
<image
wx:if="{{item.type === mediaItemTypeEnum.IMAGE}}"
src="{{item.path}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
data-new-media="{{true}}"
></image>
<!-- 视频 -->
<view wx:if="{{item.type === mediaItemTypeEnum.VIDEO}}" class="video-container">
</block>
<!-- 新选择附件 -->
<block wx:for="{{newMediaList}}" wx:key="index">
<view class="item new-item">
<!-- 图片 -->
<image
src="{{item.thumbPath}}"
wx:if="{{item.type === mediaItemTypeEnum.IMAGE}}"
src="{{item.path}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
data-new-media="{{true}}"
></image>
<t-icon class="play-icon" name="play" />
<!-- 视频 -->
<view wx:if="{{item.type === mediaItemTypeEnum.VIDEO}}" class="video-container">
<image
src="{{item.thumbPath}}"
class="thumbnail"
mode="aspectFill"
bindtap="preview"
data-index="{{index}}"
data-new-media="{{true}}"
></image>
<t-icon class="play-icon" name="play" />
</view>
<!-- 新增标识 -->
<t-icon class="new-badge" name="add" />
<!-- 删除 -->
<t-icon
class="delete"
name="close"
bindtap="deleteMedia"
data-index="{{index}}"
data-new-media="{{true}}"
/>
</view>
<!-- 新增标识 -->
<t-icon class="new-badge" name="add" />
<!-- 删除 -->
<t-icon
class="delete"
name="close"
bindtap="deleteMedia"
data-index="{{index}}"
data-new-media="{{true}}"
/>
</view>
</block>
</block>
<!-- 添加按钮 -->
<t-button
class="item add"
theme="primary"
@ -142,19 +184,47 @@
<view>{{uploadSpeed}}</view>
</view>
</view>
<!-- 控制按钮 -->
<view class="ctrl">
<t-button class="delete" theme="danger" bind:tap="deleteJournal" disabled="{{isSaving}}">删除记录</t-button>
<t-button
class="save"
theme="primary"
bind:tap="save"
disabled="{{(!idea && mediaList.length === 0 && newMediaList.length === 0) || isSaving}}"
>保存</t-button>
<!-- 创建模式 -->
<block wx:if="{{mode === 'create'}}">
<t-button
class="clear"
theme="danger"
variant="outline"
disabled="{{isSaving}}"
bind:tap="clearMedia"
disabled="{{mediaList.length === 0}}"
>清空已选</t-button>
<t-button
class="submit"
theme="primary"
bind:tap="submit"
disabled="{{(!idea && mediaList.length === 0) || isSaving}}"
>提交</t-button>
</block>
<!-- 编辑模式 -->
<block wx:else>
<t-button
class="delete"
theme="danger"
bind:tap="deleteJournal"
disabled="{{isSaving}}"
>删除记录</t-button>
<t-button
class="save"
theme="primary"
bind:tap="submit"
disabled="{{(!idea && mediaList.length === 0 && newMediaList.length === 0) || isSaving}}"
>保存</t-button>
</block>
</view>
</block>
</view>
</scroll-view>
<!-- 删除对话框(仅编辑模式) -->
<t-dialog
wx:if="{{mode === 'edit'}}"
visible="{{deleteDialogVisible}}"
title="删除记录"
confirm-btn="{{ {content: '删除', variant: 'text', theme: 'danger'} }}"

View File

@ -125,7 +125,7 @@ Page({
},
toCreater() {
wx.navigateTo({
"url": "/pages/main/journal-creater/index?from=journal"
"url": "/pages/main/journal-editor/index?from=journal"
})
},
toSearch() {

View File

@ -4,7 +4,7 @@ import Events from "../../../utils/Events";
import IOSize, { Unit } from "../../../utils/IOSize";
import Time from "../../../utils/Time";
import Toolkit from "../../../utils/Toolkit";
import type { Location } from "../journal-creater/index";
import type { Location } from "../../../types/UI";
type Item = {
id: number;