Skip to content

Commit

Permalink
perf: optimized some codes
Browse files Browse the repository at this point in the history
  • Loading branch information
ayangweb committed Mar 16, 2023
1 parent d52ac8e commit fdcb490
Show file tree
Hide file tree
Showing 14 changed files with 103 additions and 59 deletions.
2 changes: 1 addition & 1 deletion src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"resizable": false,
"maximized": false,
"title": "ChatGPT",
"alwaysOnTop": false,
"alwaysOnTop": true,
"decorations": false,
"transparent": true
}
Expand Down
52 changes: 29 additions & 23 deletions src/App.vue
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
<script setup lang="ts">
import { appWindow } from '@tauri-apps/api/window'
import { initSQL } from '@/sqls'
import { useSettingsStore, useRoleStore, useSessionStore } from '@/stores'
import { useSettingsStore } from '@/stores'
// TODO: 首次加载有问题,获取不到初始化的角色列表
initSQL()
const { themeClass, isFix } = storeToRefs(useSettingsStore())
const { currentRole } = storeToRefs(useRoleStore())
const { showHistory } = storeToRefs(useSessionStore())
const isLoading = ref(true)
// 窗口获取焦点状态
const windowFocused = ref(true)
onMounted(async () => {
await initSQL()
isLoading.value = false
// 监听窗口有无获取焦点
appWindow.onFocusChanged(({ payload }) => {
if (!payload && !isFix.value) appWindow.hide()
Expand All @@ -29,30 +32,33 @@ onMounted(async () => {
:class="[themeClass, windowFocused ? 'bordered' : 'bordered-transparent']"
data-tauri-drag-region
>
<div class="text-7 fixed top-2 right-2 flex gap-2">
<!-- 主题切换 -->
<Theme />
<!-- 固定窗口 -->
<Fixed />
<div class="flex h-full items-center justify-center" v-if="isLoading">
<a-spin :size="50" :loading="true" />
</div>

<!-- 会话信息 -->
<Session />
<template v-else>
<div class="text-7 fixed top-2 right-2 flex gap-2">
<!-- 主题切换 -->
<Theme />
<!-- 固定窗口 -->
<Fixed />
</div>

<!-- 历史会话 -->
<History v-if="showHistory" />
<!-- 会话信息 -->
<Session />

<div class="flex cursor-default flex-col gap-2 pt-2">
<div class="text-6 relative flex justify-end gap-4">
<!-- 当前聊天角色对象 -->
<div class="top-50% left-50% text-4 -translate-1/2 absolute">
正在与 <span class="mark">{{ currentRole?.name }}</span> 对话
<div class="flex cursor-default flex-col gap-2 pt-2">
<div class="text-6 relative flex justify-end gap-4">
<!-- 当前聊天角色对象 -->
<!-- <div class="top-50% left-50% text-4 -translate-1/2 absolute">
正在与 <span class="mark">{{ currentRole?.name }}</span> 对话
</div> -->
<!-- 功能按钮 -->
<Function />
</div>
<!-- 功能按钮 -->
<Function />
<!-- 输入框 -->
<Input />
</div>
<!-- 输入框 -->
<Input />
</div>
</template>
</div>
</template>
2 changes: 1 addition & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const getOpenAIResultApi = async (messages: RecordData[]) => {
body: Body.json({
model: 'gpt-3.5-turbo-0301',
messages,
stream: false
stream: true
}),
headers: {
Authorization: `Bearer ${apiKey || import.meta.env.VITE_OPEN_AI_API_KEY}`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,21 @@
import { useSessionStore } from '@/stores'
import { IconDelete } from '@arco-design/web-vue/es/icon'
defineProps<{ visible: boolean; setVisible: () => void }>()
const sessionStore = useSessionStore()
const { sessionList, showHistory, currentSession } = storeToRefs(sessionStore)
const { sessionList, currentSession } = storeToRefs(sessionStore)
const { switchSession, getSessionList, deleteSession } = sessionStore
</script>

<template>
<a-drawer
:visible="showHistory"
:visible="visible"
placement="left"
:footer="false"
:closable="false"
@cancel="showHistory = false"
@open="getSessionList"
@cancel="setVisible"
@before-open="getSessionList"
unmountOnClose
>
<template #title> 会话历史 </template>
Expand Down
9 changes: 8 additions & 1 deletion src/components/Function/components/SettingsModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const { apiKey, autoStart } = storeToRefs(useSettingsStore())
}"
@ok="setVisible"
>
<div class="flex flex-col gap-8">
<div class="flex flex-col gap-6">
<div class="flex gap-2">
<a-checkbox v-model="autoStart">开机自启动</a-checkbox>
<a-checkbox>隐藏菜单栏图标</a-checkbox>
Expand All @@ -28,6 +28,13 @@ const { apiKey, autoStart } = storeToRefs(useSettingsStore())
<!-- 热键绑定 -->
<ShortcutKey />

<div class="flex items-end gap-2">
<a-checkbox>记忆对话</a-checkbox>
<span class="text-3 text-[var(--color-text-3)]">
开启连续对话,将加倍消耗 Token
</span>
</div>

<a-input-password
v-model="apiKey"
class="w-full"
Expand Down
17 changes: 15 additions & 2 deletions src/components/Function/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,26 @@ import { getAiMessage } from '@/utils'
const sessionStore = useSessionStore()
const { switchSession, deleteSession } = sessionStore
const { isThinking, sessionDataList, showHistory } = storeToRefs(sessionStore)
const { isThinking, sessionDataList } = storeToRefs(sessionStore)
// 控制设置弹框
const modalVisible = ref(false)
const setModalVisible = () => {
modalVisible.value = !modalVisible.value
}
// 控制历史列表抽屉
const drawerVisible = ref(false)
const setDrawerVisible = () => {
drawerVisible.value = !drawerVisible.value
}
// TODO: 在获取数据时删除的处理,在获取数据时切换历史记录的处理
const functions = computed(() => [
{
content: '新建对话',
icon: IconPlusCircle,
disabled: isThinking.value || !sessionDataList.value.length,
handleClick: () => switchSession()
},
{
Expand All @@ -40,7 +48,7 @@ const functions = computed(() => [
{
content: '历史记录',
icon: IconHistory,
handleClick: () => (showHistory.value = true)
handleClick: setDrawerVisible
},
{
content: '设置',
Expand All @@ -50,6 +58,7 @@ const functions = computed(() => [
])
</script>

<!-- TODO:把聊天对象移过来 -->
<template>
<div class="function flex gap-2">
<a-tooltip
Expand All @@ -69,7 +78,11 @@ const functions = computed(() => [
</a-tooltip>
</div>

<!-- 设置弹框 -->
<SettingsModal :visible="modalVisible" :set-visible="setModalVisible" />

<!-- 历史会话抽屉 -->
<HistoryDrawer :visible="drawerVisible" :set-visible="setDrawerVisible" />
</template>

<style scoped lang="scss">
Expand Down
12 changes: 8 additions & 4 deletions src/components/Input/components/RoleList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,14 @@ const handleAdd = () => {
// TODO 这里需要优化,自动聚焦到输入框
}
const handleHide = () => {
const handleHide = (value: boolean) => {
console.log('value', value)
// 判断是否有正在编辑的角色
const isEdit = showList.value.some((item) => item.isEdit)
if (isEdit) return
isShow.value = false
isShow.value = value
}
</script>
<!-- TODO:优化代码和 css 样式 -->
Expand All @@ -48,9 +51,10 @@ const handleHide = () => {
<template>
<a-popover
title="请选择对话的角色"
:popup-visible="sessionDataList.length ? false : isShow"
class="role-popover w-full"
@click="isShow = true"
trigger="click"
:popup-visible="isShow && !sessionDataList.length"
@click="isShow = !isShow"
@popup-visible-change="handleHide"
>
<template #title>
Expand Down
8 changes: 3 additions & 5 deletions src/components/Session/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,16 @@ const { currentRole } = storeToRefs(useRoleStore())
</script>

<template>
<div id="node" class="flex-1 cursor-default overflow-auto">
<!-- TODO: 复制,一键发送,导出图片-->
<div class="flex-1 cursor-default overflow-auto">
<template v-if="sessionDataList.length">
<h3>当前session{{ currentSession?.id }}{{ currentSession?.title }}</h3>
<div
class="flex items-start p-2"
v-for="item in sessionDataList"
:key="item.time"
>
<Avatar
class="w-14!"
:value="item.type === 'answer' ? uuid : currentRole?.name"
/>
<Avatar class="w-14!" :value="item.is_ask ? uuid : currentRole?.name" />
<div>
{{ item.messages }}
</div>
Expand Down
3 changes: 1 addition & 2 deletions src/sqls/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ export const executeSQL = async (sql: string) => {
await db.execute(sql)
}
} catch (error) {
console.log('error', error)
let action

switch (sliceSQL) {
Expand Down Expand Up @@ -65,7 +64,7 @@ export const initSQL = async () => {
await executeSQL(
`
CREATE TABLE IF NOT EXISTS session (id TEXT, title TEXT, role_id INTEGER);
CREATE TABLE IF NOT EXISTS session_data (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT,type TEXT, messages TEXT, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE IF NOT EXISTS session_data (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, is_ask INTEGER, is_memory INTEGER, message TEXT, message_type TEXT DEFAULT 'text', time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE IF NOT EXISTS role (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT, is_default INTEGER DEFAULT false);
CREATE TABLE IF NOT EXISTS credit (id INTEGER PRIMARY KEY AUTOINCREMENT, history_id INTEGER, token_cost INTEGER, api_key TEXT);
`
Expand Down
6 changes: 4 additions & 2 deletions src/stores/role.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { selectSQL, insertSQL, updateSQL, deleteSQL, executeSQL } from '@/sqls'
import type { RolePayload, SessionPayload } from '@/types'
import { useSessionStore } from '.'
import type { RolePayload, SessionPayload } from '@/types'

export const useRoleStore = defineStore(
'roleStore',
Expand All @@ -9,16 +9,18 @@ export const useRoleStore = defineStore(
const currentRole = ref<RolePayload>()
// 角色列表
const roleList = ref<RolePayload[]>([])
// 检索出来的角色列表
const filterList = ref<RolePayload[]>([])

const isShow = ref(false)
const isAddNew = ref(false)

// 获取角色列表
const getRoleList = async () => {
const result = await selectSQL('role')

isAddNew.value = false
defaultRole.value.length = 0
defaultRole.value = []

roleList.value = result.map((item) => ({ ...item, isEdit: false }))

Expand Down
14 changes: 7 additions & 7 deletions src/stores/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { executeSQL } from '@/sqls'
import type { SessionPayload, SessionData, RecordData } from '@/types'
import { useRoleStore } from './role'

// TODO: 无记忆对话和有记忆对话
// 用来管理当前会话的状态
export const useSessionStore = defineStore(
'sessionStore',
Expand All @@ -14,8 +15,6 @@ export const useSessionStore = defineStore(
const sessionList = ref<SessionPayload[]>([])
// 请求发送状态
const isThinking = ref(false)
// 是否显示历史
const showHistory = ref(false)

const getSessionList = async () => {
const sql =
Expand Down Expand Up @@ -60,8 +59,11 @@ export const useSessionStore = defineStore(

const { changeCurrentRole, currentRole } = useRoleStore()

// TODO: 是否为记忆对话
// TODO: messageType从 types 中取到
const addSessionData = async (
type: 'ask' | 'answer',
isAsk: boolean,
messageType: string,
data: RecordData[]
) => {
if (!currentSession.value) return
Expand All @@ -73,8 +75,8 @@ export const useSessionStore = defineStore(
executeSQL(sql)
}

const sql = `INSERT INTO session_data (session_id,type, messages) VALUES (
'${currentSession.value.id}','${type}', '${JSON.stringify(data)}');`
const sql = `INSERT INTO session_data (session_id, is_ask, messages) VALUES (
'${currentSession.value.id}','${isAsk}', '${JSON.stringify(data)}');`

executeSQL(sql)
getSessionData()
Expand All @@ -88,7 +90,6 @@ export const useSessionStore = defineStore(
}
changeCurrentRole()
getSessionData()
showHistory.value = false
}

onMounted(() => switchSession(currentSession.value))
Expand All @@ -98,7 +99,6 @@ export const useSessionStore = defineStore(
sessionDataList,
isThinking,
sessionList,
showHistory,
addSessionData,
switchSession,
getSessionList,
Expand Down
13 changes: 12 additions & 1 deletion src/stores/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ export const useSettingsStore = defineStore(
// 开机自启动
const autoStart = ref(false)

// 记忆对话
const isMemory = ref(false)

// 切换主题
const toggleTheme = () => {
themeMode.value =
Expand Down Expand Up @@ -96,12 +99,20 @@ export const useSettingsStore = defineStore(
shortcutKeys,
isBinding,
autoStart,
isMemory,
toggleTheme
}
},
{
persist: {
paths: ['themeMode', 'uuid', 'apiKey', 'shortcutKeys', 'autoStart']
paths: [
'themeMode',
'uuid',
'apiKey',
'shortcutKeys',
'autoStart',
'isMemory'
]
}
}
)
Loading

0 comments on commit fdcb490

Please sign in to comment.