优化小程序

This commit is contained in:
linghaihui 2023-03-27 21:38:52 +08:00
parent 06ca8011d7
commit a303d7072a
7 changed files with 162 additions and 124 deletions

View File

@ -1,19 +1,19 @@
import {
doRequest
} from "./config";
} from "./config"
App({
onShow: function () {},
onLaunch: function () {
this.getSid(sid => {
console.log(sid)
});
})
},
globalData: {},
getSid: function (callback) {
var that = this;
var that = this
if (!this.globalData.sid) {
var sid = wx.getStorageSync("sid1");
var sid = wx.getStorageSync("sid1")
if (!sid) {
wx.login({
success: (res) => {
@ -23,24 +23,24 @@ App({
if (data.statusCode != 200) {
console.log(data)
callback("")
return;
return
}
that.globalData.sid = data.data.data.openid;
wx.setStorageSync("sid1", that.globalData.sid);
that.globalData.sid = data.data.data.openid
wx.setStorageSync("sid1", that.globalData.sid)
callback(data.data.data.openid)
}).catch(err => {
console.log(err)
callback("")
})
},
});
})
} else {
this.globalData.sid = sid;
wx.setStorageSync("sid1", this.globalData.sid);
this.globalData.sid = sid
wx.setStorageSync("sid1", this.globalData.sid)
callback(sid)
}
} else {
callback(this.globalData.sid)
}
},
});
})

View File

@ -14,7 +14,7 @@
"sitemapLocation": "sitemap.json",
"networkTimeout": {
"request": 900000,
"connectSocket": 900000
"connectSocket": 120000
},
"resizable": true,
"lazyCodeLoading": "requiredComponents"

View File

@ -1,4 +1,4 @@
const app = getApp();
const app = getApp()
Component({
options: {
@ -8,21 +8,21 @@ Component({
properties: {},
pageLifetimes: {
show: function () {
this.initMessageHistory();
this.initMessageHistory()
},
},
lifetimes: {
attached() {
var that = this;
app.globalData.cht = that;
//that.initMessageHistory();
var that = this
app.globalData.cht = that
//that.initMessageHistory()
wx.getSystemInfo({
success: function (res) {
that.setData({
systemInfo: res,
});
})
},
});
})
},
detached() {
try {} catch (error) {}
@ -30,62 +30,68 @@ Component({
},
data: {
chatList: [],
receiveData: false,
},
methods: {
initMessageHistory() {
var that = this;
var data = wx.getStorageSync("chatList");
data = data ? data : [];
var that = this
var data = wx.getStorageSync("chatList")
data = data ? data : []
data.forEach((v) => {
if (v["suggests"] === undefined) {
v["suggests"] = [];
v["suggests"] = []
}
});
})
if (data.length > 0) {
that.setData({
chatList: data,
});
})
}
},
clearChat: function (e) {
var that = this;
var index = e.currentTarget.dataset.index;
var data = this.data.chatList;
var that = this
var index = e.currentTarget.dataset.index
var data = this.data.chatList
wx.showModal({
content: "是否删除该条聊天?",
complete: (res) => {
if (res.confirm) {
data.splice(index, 1);
data.splice(index, 1)
that.setData({
chatList: data,
});
})
wx.setStorage({
key: "chatList",
data: data,
});
})
}
},
});
})
},
copyContent: function (e) {
var index = e.currentTarget.dataset.index;
var content = this.data.chatList[index].originContent;
var index = e.currentTarget.dataset.index
var content = this.data.chatList[index].originContent
wx.setClipboardData({
data: content,
success: function () {
wx.showToast({
title: "复制成功",
});
})
},
});
})
},
suggestSubmit: function (e) {
var suggest = e.currentTarget.dataset.suggest;
var suggest = e.currentTarget.dataset.suggest
this.triggerEvent(
"suggestSubmit", {
suggest,
}, {}
);
)
},
cancelReceive: function () {
this.triggerEvent(
"cancelReceive", {}, {}
)
},
deletAllChat: function (e) {
var that = this
@ -95,14 +101,14 @@ Component({
if (res.confirm) {
that.setData({
chatList: [],
});
})
wx.setStorage({
key: "chatList",
data: [],
});
})
}
},
});
})
}
},
});
})

View File

@ -9,7 +9,7 @@
<view style="display: flex;flex-direction: row;align-items: center;"><text class="dt" style="flex: 1;">{{item.dt}}</text><view wx:if="{{item.num_in_conversation && item.num_in_conversation != -1}}" style="display:flex;justify-content:flex-end; flex: 1;align-items: center;"><text class="conversation_num">{{item.num_in_conversation}}</text></view></view>
<view class="content bg-white" catchlongpress="copyContent" data-index="{{index}}"><view class="{{item.blink ? 'blinking': ''}}"><mp-html content="{{item.originContent}}" preview-img markdown="{{true}}" img-cache="{{true}}" lazy-load="{{true}}" container-style="margin-top: -1em;"/></view></view>
<view class="suggest">
<view hover-class="suggest-item-hover" class="suggest-item" bindtap="suggestSubmit" data-suggest="{{suggest}}" wx:for="{{item.suggests}}" wx:for-item="suggest">{{suggest}}</view>
<view hover-class="suggest-item-hover" class="suggest-item" bindtap="suggestSubmit" data-suggest="{{suggest}}" wx:for="{{item.suggests}}" wx:for-item="suggest" wx:if="{{suggest && suggest.length > 0}}">{{suggest}}</view>
</view>
</view>
</view>
@ -22,4 +22,5 @@
</view>
</view>
</scroll-view>
<icon wx:if="{{receiveData}}" type="cancel" bindtap="cancelReceive" style="position: absolute;bottom: 140rpx;right:1.5%;z-index: 10000;" size="20"></icon>
</view>

View File

@ -1,5 +1,5 @@
const SERVER_HOST = "https://example.com";
const SERVER_WSS_HOST = "wss://example.com";
const SERVER_HOST = "https://example.com"
const SERVER_WSS_HOST = "wss://example.com"
function doRequest(url, method = "GET", data = {}) {
return new Promise((resolve, reject) => {

View File

@ -1,19 +1,17 @@
import {
doRequest,
SERVER_WSS_HOST
} from "../../config";
} from "../../config"
const systemInfo = wx.getSystemInfoSync()
// 各平台对话分离
const sid_prefix = systemInfo.platform == "ios" || systemInfo.platform == "android" ? "" : systemInfo.platform
const initHeight = inputPop() ? 20 : 5
function inputPop() {
return systemInfo.platform == "ios" || systemInfo.platform == "android"
}
// 各平台对话分离
var sid_prefix = systemInfo.platform == "ios" || systemInfo.platform == "android" ? "" : systemInfo.platform
const initHeight = inputPop() ? 20 : 5
Date.prototype.format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
@ -23,35 +21,35 @@ Date.prototype.format = function (fmt) {
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
S: this.getMilliseconds(), //毫秒
};
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(this.getFullYear() + "").substr(4 - RegExp.$1.length)
);
)
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
)
}
}
return fmt;
};
function getNow() {
return new Date().format("yyyy-MM-dd hh:mm:ss");
return fmt
}
const app = getApp();
const robAvatar = "../../image/bing-avatar.png";
const personAvatar = "../../image/person.jpeg";
function getNow() {
return new Date().format("yyyy-MM-dd hh:mm:ss")
}
const app = getApp()
const robAvatar = "../../image/bing-avatar.png"
const personAvatar = "../../image/person.jpeg"
Page({
data: {
InputBottom: initHeight,
inputBottom: initHeight,
content: "",
lastContent: "",
systemInfo: systemInfo,
@ -62,21 +60,21 @@ Page({
isOpen: false,
},
},
InputFocus(e) {
inputFocus(e) {
if (inputPop()) {
this.setData({
InputBottom: e.detail.height,
});
inputBottom: e.detail.height,
})
}
},
InputBlur(e) {
inputBlur(e) {
this.setData({
InputBottom: initHeight,
inputBottom: initHeight,
textareaFocus: false,
});
})
},
processContent(content) {
return content.replace(/\\n/g, "\n").replace(/\[\^\d+\^\]/g, "");
return content.replace(/\\n/g, "\n").replace(/\[\^\d+\^\]/g, "")
},
resetConversation: function (callback) {
app.getSid(sid => {
@ -90,38 +88,38 @@ Page({
})
},
onShow() {
const cht = app.globalData.cht;
const cht = app.globalData.cht
if (cht.data.chatList.length > 1) {
cht.setData({
scrollId: "item" + (cht.data.chatList.length - 2),
});
})
}
},
onLoad() {},
processData: function (data, suggests, content) {
var robContent = data["data"]["status"];
var robContent = data["data"]["status"]
if (robContent == "Success") {
robContent = data["data"]["text"];
suggests.push(...data["data"]["suggests"]);
robContent = data["data"]["text"]
suggests.push(...data["data"]["suggests"])
if (robContent.indexOf("New topic") != -1) {
robContent += "\n\n发送“重新对话”开始新的对话";
suggests.push("重新对话!");
suggests.push(content);
robContent += "\n\n发送“重新对话”开始新的对话"
suggests.push("重新对话!")
suggests.push(content)
}
} else {
if (robContent == "Throttled") {
robContent = "这真是愉快,但你已达到每日限制。是否明天再聊?";
suggests.push("重新对话!");
suggests.push(content);
robContent = "这真是愉快,但你已达到每日限制。是否明天再聊?"
suggests.push("重新对话!")
suggests.push(content)
} else {
var msg = data["data"]["message"];
var msg = data["data"]["message"]
if (msg.indexOf("has expired") != -1) {
this.resetConversation();
robContent = "本轮对话已过期,请重新开始。";
suggests.push(content);
this.resetConversation()
robContent = "本轮对话已过期,请重新开始。"
suggests.push(content)
} else {
robContent = "抱歉😭,发生错误:" + msg + ",请重试";
suggests.push(content);
robContent = "抱歉😭,发生错误:" + msg
suggests.push(content)
}
}
}
@ -139,7 +137,7 @@ Page({
},
sendHttpRequest: function (content) {
var that = this
const cht = app.globalData.cht;
const cht = app.globalData.cht
app.getSid(sid => {
doRequest("/chat", "POST", {
q: content,
@ -151,17 +149,17 @@ Page({
var num_in_conversation = -1
if (res.statusCode != 200) {
robContent =
"抱歉😭,网络异常,请稍后重试 [" + res.statusCode + "]";
suggests.push(content);
"抱歉😭,网络异常,请稍后重试 [" + res.statusCode + "]"
suggests.push(content)
} else {
robContent = that.processData(res.data, suggests, content)
num_in_conversation = res.data["data"]["num_in_conversation"];
num_in_conversation = res.data["data"]["num_in_conversation"]
}
that.pushStorageMessage(cht, robContent, "rob", suggests, false, true, num_in_conversation)
} catch (error) {
wx.showToast({
title: "fatal error",
});
})
that.pushStorageMessage(cht, "发生致命错误😱", "rob", [], false, true)
}
}).catch(e => {
@ -181,36 +179,30 @@ Page({
searching: true
})
}
var that = this;
const cht = app.globalData.cht;
var that = this
const cht = app.globalData.cht
that.pushStorageMessage(cht, content, "man", [], false)
that.setData({
content: "",
lastContent: content,
});
})
if (content == "重新对话!") {
that.resetConversation(() => {
that.pushStorageMessage(cht, "现在我们可以开始新的对话😊", "rob", [], false)
});
return;
})
return
} else {
that.pushStorageMessage(cht, "搜索中🔍...", "rob", [], true)
}
return that.sendWSRequest(content)
// 经测试mac 平台下打开debug才能触发websocket的onOpen回调。。。
if (systemInfo.platform == "mac") {
if (systemInfo.enableDebug) {
that.sendWSRequest(content)
} else {
that.sendHttpRequest(content)
}
} else {
if (systemInfo.platform != "windows") {
that.sendWSRequest(content)
} else {
that.sendHttpRequest(content)
}
},
pushStorageMessage: function (cht, content, role, suggests, blink, pop, num_in_conversation = -1, final = true) {
if (pop) {
cht.data.chatList.pop();
cht.data.chatList.pop()
}
cht.data.chatList.push({
type: role,
@ -220,10 +212,10 @@ Page({
suggests: suggests,
blink: blink,
num_in_conversation: num_in_conversation,
});
})
cht.setData({
chatList: cht.data.chatList,
});
})
if (role == "rob" && !blink && final) {
this.setData({
searching: false
@ -232,29 +224,29 @@ Page({
wx.setStorage({
key: "chatList",
data: cht.data.chatList,
});
})
setTimeout(() => {
cht.setData({
scrollId: "item" + (cht.data.chatList.length - 1),
});
}, 50);
})
}, 50)
},
submit() {
var content = this.data.content;
var content = this.data.content
if (content.length == 0 || content.trim().length == 0) {
return;
return
}
this.submitContent(content);
this.submitContent(content)
},
onShareAppMessage() {
return {
title: "New Bing Bot 🤖",
path: "/pages/index/index",
};
}
},
onSuggestSubmit: function (e) {
var suggest = e.detail.suggest;
this.submitContent(suggest);
var suggest = e.detail.suggest
this.submitContent(suggest)
},
focus: function (e) {
this.setData({
@ -266,6 +258,7 @@ Page({
return
}
var that = this
const cht = app.globalData.cht
const socket = wx.connectSocket({
url: SERVER_WSS_HOST + "/chat",
fail: function () {
@ -299,6 +292,9 @@ Page({
},
searching: false,
})
cht.setData({
receiveData: false
})
})
socket.onError(msg => {
console.log('Socket onError', msg)
@ -310,20 +306,29 @@ Page({
searching: false
})
wx.showToast({
title: '网络错误',
title: msg.errMsg,
})
cht.setData({
receiveData: false
})
})
socket.onMessage(data => {
const cht = app.globalData.cht;
const cht = app.globalData.cht
var data = JSON.parse(data.data)
var suggests = []
var robContent = ''
var num_in_conversation = -1
if (!data['final']) {
robContent = data['data'] + ' ...'
cht.setData({
receiveData: true
})
} else {
robContent = that.processData(data['data'], suggests, that.data.lastContent)
num_in_conversation = data['data']['data']['num_in_conversation']
cht.setData({
receiveData: false
})
}
that.pushStorageMessage(cht, robContent, "rob", suggests, false, true, num_in_conversation, data['final'])
})
@ -360,5 +365,31 @@ Page({
reason: "Page Unload"
})
}
},
inputData: function (e) {
var that = this
var value = e.detail.value
that.setData({
content: value
})
// 特定用户在桌面版本下触发提交因为textarea在桌面版下回车是换行并且无法监听快捷键输入只能出此下策
if (systemInfo.platform != 'windows' && systemInfo.platform != 'mac') {
return
}
if (value.indexOf("》》》\n") != -1 || value.indexOf(">>>\n") != -1) {
that.setData({
content: value.replace("》》》\n", "").replace(">>>\n", ""),
}, () => {
that.submit()
})
}
},
onCancelReceive: function (e) {
if (this.data.socket.isOpen) {
this.data.socket.socket.close({
code: 1000,
reason: "User cancel"
})
}
}
});
})

View File

@ -1,5 +1,5 @@
<chat-box bindsuggestSubmit="onSuggestSubmit"></chat-box>
<view style="bottom:{{InputBottom}}px; border-radius: 20rpx;margin-left: 1.5%;width: 97%;min-height: 100rpx;position: fixed;background-color: #f4f6f8;display: flex;align-items:flex-start; justify-content: space-between;{{textareaFocus ? 'border: 1rpx solid;': ''}}">
<textarea bindfocus="InputFocus" bindblur="InputBlur" model:value="{{content}}" adjust-position="{{false}}" focus="{{textareaFocus}}" maxlength="2000" auto-height="{{true}}" cursor-spacing="10" bindconfirm="submit" fixed="{{true}}" show-confirm-bar="{{false}}" confirm-type="send" placeholder="请输入问题..." style="padding: 10rpx;" placeholder-style="color: #b4bbc4" bindtap="focus"></textarea>
<chat-box bindsuggestSubmit="onSuggestSubmit" bindcancelReceive="onCancelReceive"></chat-box>
<view style="bottom:{{inputBottom}}px; border-radius: 20rpx;margin-left: 1.5%;width: 97%;min-height: 100rpx;position: fixed;background-color: #f4f6f8;display: flex;align-items:flex-start; justify-content: space-between;{{textareaFocus ? 'border: 1rpx solid;': ''}}">
<textarea bindfocus="inputFocus" bindblur="inputBlur" value="{{content}}" adjust-position="{{false}}" focus="{{textareaFocus}}" maxlength="2000" auto-height="{{true}}" cursor-spacing="10" bindconfirm="submit" fixed="{{true}}" show-confirm-bar="{{false}}" confirm-type="send" placeholder="{{systemInfo.platform == 'mac' || systemInfo.platform == 'windows' ? '请输入问题,输入>>>提交...': '请输入问题...'}}" style="padding: 10rpx;flex: 9;" placeholder-style="color: #b4bbc4" bindtap="focus" bindinput="inputData"></textarea>
<view style="background-color: #f4f6f8;color: {{content ? black : '#b4bbc4'}};border-radius: 0 20rpx 20rpx 0;height: 90rpx;cursor: pointer;margin-right: 15rpx;padding-top:10rpx;font-size: 32rpx;" bindtap="submit" wx:if="{{systemInfo.platform != 'ios'}}">发送</view>
</view>