Compare commits

...

12 Commits

Author SHA1 Message Date
CrescentLeaf
eaf0f98058 update 2025-09-20 20:32:26 +08:00
CrescentLeaf
1acc73c7b4 chore: make lint happy 2025-09-20 20:14:47 +08:00
CrescentLeaf
23df74ddac ui: 微調 資料卡 昵稱字體 2025-09-20 20:13:20 +08:00
CrescentLeaf
70478584b7 chore: 精簡類型注解 2025-09-20 20:12:57 +08:00
CrescentLeaf
90295f0d38 fix: useAsyncEffect loops 2025-09-20 19:52:04 +08:00
CrescentLeaf
5ff726d834 fix(ui): 右側的面板沒有吃滿寬度 2025-09-20 19:51:41 +08:00
CrescentLeaf
ab1bc844ab fix: WTF Where is my React 2025-09-20 18:41:46 +08:00
CrescentLeaf
167b157134 refactor: 封裝 useAsyncEffect 2025-09-20 18:26:08 +08:00
CrescentLeaf
3b98fc4de3 feat(wip): 多選聯絡人 2025-09-20 18:14:52 +08:00
CrescentLeaf
4a32fd216b feat: search for recentschat 2025-09-20 18:00:12 +08:00
CrescentLeaf
af9b0d7cf2 fix: 由於未知原因導致的 輸入框 逃竄到 Tab 的 change 事件, 造成 Tab Panel 顯示異常 2025-09-20 17:35:12 +08:00
CrescentLeaf
c82d718fa7 feat: search contact by nickname/id/username 2025-09-20 17:29:12 +08:00
16 changed files with 251 additions and 113 deletions

View File

@@ -15,8 +15,9 @@ import { checkApiSuccessOrSncakbar } from "./snackbar.ts"
import RegisterDialog from "./dialog/RegisterDialog.tsx"
import LoginDialog from "./dialog/LoginDialog.tsx"
import UserProfileDialog from "./dialog/UserProfileDialog.tsx"
import ContactsList from "./main/ContactsList.tsx";
import RecentsList from "./main/RecentsList.tsx";
import ContactsList from "./main/ContactsList.tsx"
import RecentsList from "./main/RecentsList.tsx"
import useAsyncEffect from "./useAsyncEffect.ts"
declare global {
namespace React {
@@ -56,7 +57,7 @@ export default function App() {
nickname: "Maya Fey",
},
] as User[])
const [navigationItemSelected, setNavigationItemSelected] = React.useState('Recents')
const navigationRailRef = React.useRef<NavigationRail>(null)
@@ -85,29 +86,27 @@ export default function App() {
const [currentChatId, setCurrentChatId] = React.useState('')
React.useEffect(() => {
; (async () => {
const split = Split(['#SideBar', '#ChatFragment'], {
sizes: data.split_sizes ? data.split_sizes : [25, 75],
minSize: [200, 400],
gutterSize: 2,
onDragEnd: function () {
data.split_sizes = split.getSizes()
data.apply()
}
})
Client.connect()
const re = await Client.auth(data.access_token || "")
if (re.code == 401)
loginDialogRef.current!.open = true
else if (re.code != 200) {
if (checkApiSuccessOrSncakbar(re, "驗證失敗")) return
} else if (re.code == 200) {
setMyUserProfileCache(Client.myUserProfile as User)
useAsyncEffect(async () => {
const split = Split(['#SideBar', '#ChatFragment'], {
sizes: data.split_sizes ? data.split_sizes : [25, 75],
minSize: [200, 400],
gutterSize: 2,
onDragEnd: function () {
data.split_sizes = split.getSizes()
data.apply()
}
})()
}, [])
})
Client.connect()
const re = await Client.auth(data.access_token || "")
if (re.code == 401)
loginDialogRef.current!.open = true
else if (re.code != 200) {
if (checkApiSuccessOrSncakbar(re, "驗證失敗")) return
} else if (re.code == 200) {
setMyUserProfileCache(Client.myUserProfile as User)
}
})
return (
<div style={{
@@ -131,7 +130,7 @@ export default function App() {
loginInputPasswordRef={loginInputPasswordRef} />
<UserProfileDialog
userProfileDialogRef={userProfileDialogRef}
userProfileDialogRef={userProfileDialogRef as any}
user={myUserProfileCache} />
<mdui-navigation-rail contained value="Recents" ref={navigationRailRef}>
@@ -152,10 +151,11 @@ export default function App() {
// 最近聊天
<RecentsList
openChatFragment={(id) => {
setCurrentChatId(id)
setIsShowChatFragment(true)
}}
display={navigationItemSelected == "Recents"}
currentChatId={currentChatId}
recentsList={recentsList}
setRecentsList={setRecentsList} />
}
@@ -165,16 +165,15 @@ export default function App() {
openChatFragment={(id) => {
setIsShowChatFragment(true)
}}
display={navigationItemSelected == "Contacts"}
contactsList={contactsList}
setContactsList={setContactsList} />
display={navigationItemSelected == "Contacts"} />
}
</div>
{
// 聊天页面
}
<div id="ChatFragment" style={{
display: "flex"
display: "flex",
width: '100%'
}}>
{
!isShowChatFragment && <div style={{

View File

@@ -14,6 +14,7 @@ import LoginDialog from "./dialog/LoginDialog.tsx"
import UserProfileDialog from "./dialog/UserProfileDialog.tsx"
import ContactsList from "./main/ContactsList.tsx"
import RecentsList from "./main/RecentsList.tsx"
import useAsyncEffect from "./useAsyncEffect.ts"
declare global {
namespace React {
@@ -79,19 +80,17 @@ export default function AppMobile() {
const [myUserProfileCache, setMyUserProfileCache]: [User, React.Dispatch<React.SetStateAction<User>>] = React.useState(null as unknown as User)
React.useEffect(() => {
; (async () => {
Client.connect()
const re = await Client.auth(data.access_token || "")
if (re.code == 401)
loginDialogRef.current!.open = true
else if (re.code != 200) {
if (checkApiSuccessOrSncakbar(re, "驗證失敗")) return
} else if (re.code == 200) {
setMyUserProfileCache(Client.myUserProfile as User)
}
})()
}, [])
useAsyncEffect(async () => {
Client.connect()
const re = await Client.auth(data.access_token || "")
if (re.code == 401)
loginDialogRef.current!.open = true
else if (re.code != 200) {
if (checkApiSuccessOrSncakbar(re, "驗證失敗")) return
} else if (re.code == 200) {
setMyUserProfileCache(Client.myUserProfile as User)
}
})
return (
<div style={{

View File

@@ -1,6 +1,6 @@
import { Tab } from "mdui"
import useEventListener from "../useEventListener.ts"
import Element_Message from "./Message.jsx"
import Element_Message from "./Message.jsx"
import MessageContainer from "./MessageContainer.jsx"
import * as React from 'react'
@@ -9,6 +9,7 @@ import Message from "../../api/client_data/Message.ts"
import Chat from "../../api/client_data/Chat.ts"
import data from "../../Data.ts"
import { checkApiSuccessOrSncakbar } from "../snackbar.ts"
import useAsyncEffect from "../useAsyncEffect.ts"
interface Args extends React.HTMLAttributes<HTMLElement> {
target: string,
@@ -21,23 +22,22 @@ export default function ChatFragment({ target, ...props }: Args) {
} as Chat)
const [tabItemSelected, setTabItemSelected] = React.useState('Chat')
const tabRef: React.MutableRefObject<Tab | null> = React.useRef(null)
useEventListener(tabRef, 'change', (event) => {
setTabItemSelected((event.target as HTMLElement as Tab).value as string)
const tabRef = React.useRef<Tab>(null)
useEventListener(tabRef, 'change', () => {
setTabItemSelected(tabRef.current?.value || "Chat")
})
React.useEffect(() => {
;(async () => {
const re = await Client.invoke('Chat.getInfo', {
token: data.access_token,
target: target,
})
if (re.code != 200)
return checkApiSuccessOrSncakbar(re, "對話錯誤")
setChatInfo(re.data as Chat)
})()
useAsyncEffect(async () => {
const re = await Client.invoke('Chat.getInfo', {
token: data.access_token,
target: target,
})
if (re.code != 200)
return checkApiSuccessOrSncakbar(re, "對話錯誤")
setChatInfo(re.data as Chat)
}, [target])
console.log(tabItemSelected)
return (
<div style={{
width: '100%',

View File

@@ -0,0 +1,55 @@
import React from 'react'
import Chat from "../../api/client_data/Chat.ts"
import useAsyncEffect from "../useAsyncEffect.ts"
import Client from "../../api/Client.ts"
import data from "../../Data.ts"
import { Dialog } from "mdui"
interface Args extends React.HTMLAttributes<HTMLElement> {
chat: Chat
chatInfoDialogRef: React.MutableRefObject<Dialog>
}
export default function ChatInfoDialog({ chat, chatInfoDialogRef }: Args) {
const [isMySelf, setIsMySelf] = React.useState(false)
useAsyncEffect(async () => {
const re = await Client.invoke("Chat.getInfo", {
token: data.access_token,
target: chat.id,
})
})
return (
<mdui-dialog close-on-overlay-click close-on-esc ref={chatInfoDialogRef}>
<div style={{
display: 'flex',
alignItems: 'center',
}}>
<Avatar src={chat?.avatar} text={chat?.nickname} style={{
width: '50px',
height: '50px',
}} />
<span style={{
marginLeft: "15px",
fontSize: '16.5px',
}}>{user?.nickname}</span>
</div>
<mdui-divider style={{
marginTop: "10px",
marginBottom: "10px",
}}></mdui-divider>
<mdui-list>
{!isMySelf && <mdui-list-item icon="edit" rounded></mdui-list-item>}
{
isMySelf && <>
<mdui-list-item icon="edit" rounded></mdui-list-item>
<mdui-list-item icon="settings" rounded></mdui-list-item>
<mdui-list-item icon="lock" rounded></mdui-list-item>
</>
}
</mdui-list>
</mdui-dialog>
)
}

View File

@@ -10,7 +10,7 @@ import Avatar from "../Avatar.tsx"
import User from "../../api/client_data/User.ts"
interface Refs {
userProfileDialogRef: React.MutableRefObject<Dialog | null>
userProfileDialogRef: React.MutableRefObject<Dialog>
user: User
}
@@ -20,8 +20,8 @@ export default function UserProfileDialog({
}: Refs) {
const isMySelf = Client.myUserProfile?.id == user?.id
const editAvatarButtonRef: React.MutableRefObject<HTMLElement | null> = React.useRef(null)
const chooseAvatarFileRef: React.MutableRefObject<HTMLInputElement | null> = React.useRef(null)
const editAvatarButtonRef = React.useRef<HTMLElement>(null)
const chooseAvatarFileRef = React.useRef<HTMLInputElement>(null)
useEventListener(editAvatarButtonRef, 'click', () => chooseAvatarFileRef.current!.click())
useEventListener(chooseAvatarFileRef, 'change', async (_e) => {
const file = chooseAvatarFileRef.current!.files?.[0] as File
@@ -57,8 +57,8 @@ export default function UserProfileDialog({
height: '50px',
}} />
<span style={{
marginLeft: "10px",
fontSize: '15.5px',
marginLeft: "15px",
fontSize: '16.5px',
}}>{user?.nickname}</span>
</div>
<mdui-divider style={{

View File

@@ -1,21 +1,46 @@
import React from "react"
import User from "../../api/client_data/User.ts"
import ContactsListItem from "./ContactsListItem.tsx"
import useEventListener from "../useEventListener.ts"
import { ListItem, TextField } from "mdui"
import useAsyncEffect from "../useAsyncEffect.ts"
import Client from "../../api/Client.ts"
import data from "../../Data.ts"
interface Args extends React.HTMLAttributes<HTMLElement> {
contactsList: User[]
setContactsList: React.Dispatch<React.SetStateAction<User[]>>
display: boolean
openChatFragment: (id: string) => void
}
export default function ContactsList({
contactsList,
setContactsList,
display,
openChatFragment,
...props
}: Args) {
const searchRef = React.useRef<HTMLElement>(null)
const [isMultiSelecting, setIsMultiSelecting] = React.useState(false)
const [searchText, setSearchText] = React.useState('')
const [contactsList, setContactsList] = React.useState([
{
id: '1',
avatar: "https://www.court-records.net/mugshot/aa6-004-maya.png",
nickname: "麻油衣酱",
},
{
id: '0',
avatar: "https://www.court-records.net/mugshot/aa6-004-maya.png",
nickname: "Maya Fey",
},
] as User[])
useEventListener(searchRef, 'input', (e) => {
setSearchText((e.target as unknown as TextField).value)
})
useAsyncEffect(async () => {
})
return <mdui-list style={{
overflowY: 'auto',
paddingLeft: '10px',
@@ -23,15 +48,38 @@ export default function ContactsList({
display: display ? undefined : 'none',
height: '100%',
}} {...props}>
<mdui-text-field icon="search" type="search" clearable ref={searchRef} variant="outlined" placeholder="搜索..." style={{
marginTop: '5px',
}}></mdui-text-field>
<mdui-list-item rounded style={{
width: '100%',
marginTop: '13px',
marginBottom: '15px',
}} icon="person_add"></mdui-list-item>
{/* <mdui-list-item rounded style={{
width: '100%',
marginBottom: '15px',
}} icon={ isMultiSelecting ? "done" : "edit"} onClick={() => setIsMultiSelecting(!isMultiSelecting)}>{ isMultiSelecting ? "關閉多選" : "多選模式" }</mdui-list-item> */}
{
contactsList.map((v2) =>
contactsList.filter((user) =>
searchText == '' ||
user.nickname.includes(searchText) ||
user.id.includes(searchText) ||
user.username?.includes(searchText)
).map((v) =>
<ContactsListItem
openChatFragment={openChatFragment}
key={v2.id}
contact={v2} />
/* active={!isMultiSelecting && false}
onClick={(e) => {
const self = (e.target as ListItem)
if (isMultiSelecting)
self.active = !self.active
else
void(0)
}} */
key={v.id}
contact={v} />
)
}
</mdui-list>

View File

@@ -1,13 +1,14 @@
import { ListItem } from "mdui";
import User from "../../api/client_data/User.ts"
import Avatar from "../Avatar.tsx"
import React from 'react'
interface Args extends React.HTMLAttributes<HTMLElement> {
contact: User
openChatFragment: (id: string) => void
active?: boolean
}
export default function ContactsListItem({ contact, openChatFragment }: Args) {
export default function ContactsListItem({ contact, ...prop }: Args) {
const { id, nickname, avatar } = contact
const ref = React.useRef<HTMLElement>(null)
@@ -16,7 +17,7 @@ export default function ContactsListItem({ contact, openChatFragment }: Args) {
marginTop: '3px',
marginBottom: '3px',
width: '100%',
}} onClick={() => openChatFragment(id)}>
}} {...prop as any}>
<span style={{
width: "100%",
}}>{nickname}</span>

View File

@@ -1,30 +1,53 @@
import { TextField } from "mdui"
import RecentChat from "../../api/client_data/RecentChat.ts"
import useEventListener from "../useEventListener.ts"
import RecentsListItem from "./RecentsListItem.tsx"
import React from "react"
interface Args extends React.HTMLAttributes<HTMLElement> {
recentsList: RecentChat[]
setRecentsList: React.Dispatch<React.SetStateAction<RecentChat[]>>
display: boolean
currentChatId: string
openChatFragment: (id: string) => void
}
export default function RecentsList({
recentsList,
setRecentsList,
currentChatId,
display,
openChatFragment,
...props
}: Args) {
const searchRef = React.useRef<HTMLElement>(null)
const [searchText, setSearchText] = React.useState('')
useEventListener(searchRef, 'input', (e) => {
setSearchText((e.target as unknown as TextField).value)
})
return <mdui-list style={{
overflowY: 'auto',
paddingRight: '10px',
display: display ? undefined : 'none',
height: '100%',
}} {...props}>
<mdui-text-field icon="search" type="search" clearable ref={searchRef} variant="outlined" placeholder="搜索..." style={{
marginTop: '5px',
marginBottom: '13px',
paddingLeft: '10px',
}}></mdui-text-field>
{
recentsList.map((v) =>
recentsList.filter((chat) =>
searchText == '' ||
chat.title.includes(searchText) ||
chat.id.includes(searchText) ||
chat.content?.includes(searchText)
).map((v) =>
<RecentsListItem
openChatFragment={openChatFragment}
active={currentChatId == v.id}
openChatFragment={() => openChatFragment(v.id)}
key={v.id}
recentChat={v} />
)

View File

@@ -4,15 +4,16 @@ import Avatar from "../Avatar.tsx"
interface Args extends React.HTMLAttributes<HTMLElement> {
recentChat: RecentChat
openChatFragment: (id: string) => void
active?: boolean
}
export default function RecentsListItem({ recentChat, openChatFragment }: Args) {
export default function RecentsListItem({ recentChat, openChatFragment, active }: Args) {
const { id, title, avatar, content } = recentChat
return (
<mdui-list-item rounded style={{
marginTop: '3px',
marginBottom: '3px',
}} onClick={() => openChatFragment(id)}>
}} onClick={() => openChatFragment(id)} active={active}>
{title}
<Avatar src={avatar} text={title} slot="icon" />
<span slot="description"

View File

@@ -0,0 +1,8 @@
import React from "react"
export default function useAsyncEffect(func: Function, deps?: React.DependencyList) {
React.useEffect(() => {
func()
// 警告: 不添加 deps 有可能導致無限執行
}, deps || [])
}

View File

@@ -8,8 +8,9 @@ export type CallMethod =
"User.setAvatar" |
"User.getMyInfo" |
"User.getMyContactGroups" |
"User.setMyContactGroups" |
"User.getMyContacts" |
"User.addContact" |
"User.removeContacts" |
"Chat.getInfo" |
"Chat.sendMessage" |

View File

@@ -29,20 +29,15 @@ export default class ChatApi extends BaseApi {
// 私聊
if (chat!.bean.type == 'private') {
const targetId = args.target as string
const target = User.findById(targetId)
const mine = User.findById(token.author) as User
if (target == null) return {
code: 404,
msg: "找不到用户",
}
return {
code: 200,
msg: "成功",
data: {
type: chat.bean.type,
title: ChatPrivate.fromChat(chat).getTitleForPrivate(mine, target)
title: chat.getTitleForPrivate(mine),
avatar: chat.bean.avatar_file_hash ? "uploaded_files/" + chat.bean.avatar_file_hash : chat.bean.avatar_file_hash
}
}
}

View File

@@ -2,6 +2,8 @@ import { Buffer } from "node:buffer";
import User from "../data/User.ts";
import BaseApi from "./BaseApi.ts"
import TokenManager from "./TokenManager.ts";
import ChatPrivate from "../data/ChatPrivate.ts";
import Chat from "../data/Chat.ts";
export default class UserApi extends BaseApi {
override getName(): string {
@@ -196,7 +198,7 @@ export default class UserApi extends BaseApi {
}
})
// 獲取聯絡人列表
this.registerEvent("User.getMyContactGroups", (args) => {
this.registerEvent("User.getMyContacts", (args) => {
if (this.checkArgsMissing(args, ['token'])) return {
msg: "參數缺失",
code: 400,
@@ -214,13 +216,15 @@ export default class UserApi extends BaseApi {
msg: "成功",
code: 200,
data: {
contact_groups: user!.getContactGroups()
contacts: user!.getContactsList().map((id) => {
title: Chat.findById(id)?.bean.title
})
}
}
})
// 更新聯絡人列表
this.registerEvent("User.setMyContactGroups", (args) => {
if (this.checkArgsMissing(args, ['token', 'contact_groups'])) return {
// 添加聯絡人
this.registerEvent("User.addContact", (args) => {
if (this.checkArgsMissing(args, ['token', 'contact_chat_id'])) return {
msg: "參數缺失",
code: 400,
}
@@ -232,7 +236,7 @@ export default class UserApi extends BaseApi {
}
const user = User.findById(token.author)
user!.setContactGroups(args.contact_groups as { [key: string]: string[] })
user!.addContact(args.contact_chat_id as string)
return {
msg: "成功",

View File

@@ -30,13 +30,13 @@ export default class Chat {
/* 设置 */ settings TEXT NOT NULL
);
`)
return db
return db
}
protected static findAllBeansByCondition(condition: string, ...args: SQLInputValue[]): ChatBean[] {
return this.database.prepare(`SELECT * FROM ${Chat.table_name} WHERE ${condition}`).all(...args) as unknown as ChatBean[]
}
static findById(id: string) {
const beans = this.findAllBeansByCondition('id = ?', id)
if (beans.length == 0)
@@ -49,7 +49,7 @@ export default class Chat {
static create(chatId: string, type: 'private' | 'group') {
const chat = new Chat(
Chat.findAllBeansByCondition(
'count = ?',
'count = ?',
Chat.database.prepare(`INSERT INTO ${Chat.table_name} (
type,
id,
@@ -80,4 +80,13 @@ export default class Chat {
Chat.database.prepare(`UPDATE ${Chat.table_name} SET ${key} = ? WHERE id = ?`).run(value, this.bean.id)
this.bean[key] = value
}
getTitleForPrivate(userMySelf: User) {
if (this.bean.user_a_id == userMySelf.bean.id)
return User.findById(this.bean?.user_b_id as string)?.getNickName() || "未知對話"
if (this.bean.user_b_id == userMySelf.bean.id)
return userMySelf.getNickName()
return "未知對話"
}
}

View File

@@ -25,15 +25,4 @@ export default class ChatPrivate extends Chat {
}
return a
}
getTitleForPrivate(user: User, targetUser: User) {
const chat = Chat.findById(ChatPrivate.getChatIdByUsersId(user.bean.id, targetUser.bean.id))
if (chat?.bean.user_a_id == user.bean.id)
return targetUser.getNickName()
if (chat?.bean.user_b_id == user.bean.id)
return user.getNickName()
return "未知對話"
}
}

View File

@@ -9,8 +9,11 @@ import config from '../config.ts'
import UserBean from './UserBean.ts'
import FileManager from './FileManager.ts'
import { SQLInputValue } from "node:sqlite";
import DataWrongError from "../api/DataWrongError.ts";
import { SQLInputValue } from "node:sqlite"
import DataWrongError from "../api/DataWrongError.ts"
import ChatPrivate from "./ChatPrivate.ts"
import Chat from "./Chat.ts"
import ChatBean from "./ChatBean.ts";
type UserBeanKey = keyof UserBean
@@ -77,6 +80,7 @@ export default class User {
)[0]
)
avatar && user.setAvatar(avatar)
user.addContact(ChatPrivate.getChatIdByUsersId(user.bean.id, user.bean.id))
return user
}
@@ -115,12 +119,14 @@ export default class User {
setUserName(userName: string) {
this.setAttr("username", userName)
}
addContact(userId) {
addContact(chatId: string) {
const ls = this.getContactsList()
ls.push(chatId)
this.setAttr("contacts_list", JSON.stringify(ls))
}
getContactsList() {
try {
return JSON.parse(this.bean.contacts_list)
return JSON.parse(this.bean.contacts_list) as string[]
} catch (e) {
console.log(chalk.yellow(`警告: 聯絡人組解析失敗: ${(e as Error).message}`))
return [