refactor(client): 侧边列表重构

This commit is contained in:
CrescentLeaf
2025-12-07 00:36:51 +08:00
parent 07bc4a6654
commit 4788434445
7 changed files with 424 additions and 2 deletions

View File

@@ -24,12 +24,16 @@ export default function Main() {
const [showLoginDialog, setShowLoginDialog] = React.useState(false) const [showLoginDialog, setShowLoginDialog] = React.useState(false)
const [showRegisterDialog, setShowRegisterDialog] = React.useState(false) const [showRegisterDialog, setShowRegisterDialog] = React.useState(false)
// TODO
const [currentSelectedChatId, setCurrentSelectedChatId] = React.useState(false)
const sharedContext = { const sharedContext = {
ui_functions: React.useRef({ ui_functions: React.useRef({
}), }),
setShowLoginDialog, setShowLoginDialog,
setShowRegisterDialog, setShowRegisterDialog,
} }
useAsyncEffect(async () => { useAsyncEffect(async () => {
@@ -78,7 +82,6 @@ export default function Main() {
<mdui-navigation-rail-item icon="favorite_border" active-icon="favorite" value="Contacts"></mdui-navigation-rail-item> <mdui-navigation-rail-item icon="favorite_border" active-icon="favorite" value="Contacts"></mdui-navigation-rail-item>
<mdui-navigation-rail-item icon="chat--outlined" active-icon="chat--filled" value="AllChats"></mdui-navigation-rail-item> <mdui-navigation-rail-item icon="chat--outlined" active-icon="chat--filled" value="AllChats"></mdui-navigation-rail-item>
<mdui-dropdown trigger="hover" slot="bottom"> <mdui-dropdown trigger="hover" slot="bottom">
<mdui-button-icon icon="add" slot="trigger"></mdui-button-icon> <mdui-button-icon icon="add" slot="trigger"></mdui-button-icon>
<mdui-menu> <mdui-menu>
@@ -102,7 +105,7 @@ export default function Main() {
Recents: "最近对话", Recents: "最近对话",
Contacts: "收藏对话", Contacts: "收藏对话",
AllChats: "所有对话", AllChats: "所有对话",
})['Recents'] })[currentShowPage]
}</mdui-top-app-bar-title> }</mdui-top-app-bar-title>
<div style={{ <div style={{
flexGrow: 1, flexGrow: 1,

View File

@@ -0,0 +1,76 @@
import { TextField } from "mdui"
import React from "react"
import AllChatsListItem from "./AllChatsListItem.tsx"
import useEventListener from "../../utils/useEventListener.ts"
import useAsyncEffect from "../../utils/useAsyncEffect.ts"
import { CallbackError, Chat, User, UserMySelf } from "lingchair-client-protocol"
import getClient from "../../getClient.ts"
import showSnackbar from "../../utils/showSnackbar.ts"
import isMobileUI from "../../utils/isMobileUI.ts"
interface Args extends React.HTMLAttributes<HTMLElement> {
display: boolean
currentChatId: string
openChatInfoDialog: (chat: Chat) => void
}
export default function AllChatsList({ ...props }: React.HTMLAttributes<HTMLElement>) {
const searchRef = React.useRef<HTMLElement>(null)
const [searchText, setSearchText] = React.useState('')
const [allChatsList, setAllChatsList] = React.useState<Chat[]>([])
useEventListener(searchRef, 'input', (e) => {
setSearchText((e.target as unknown as TextField).value)
})
useAsyncEffect(async () => {
async function updateAllChats() {
try {
setAllChatsList(await (await UserMySelf.getMySelfOrThrow(getClient())).getMyAllChatsOrThrow())
} catch (e) {
if (e instanceof CallbackError)
if (e.code == 401 || e.code == 400)
showSnackbar({
message: '获取所有对话失败: ' + e.message
})
}
}
updateAllChats()
return () => {
}
})
return <mdui-list style={{
overflowY: 'auto',
paddingRight: '10px',
paddingLeft: '10px',
paddingTop: '0',
height: '100%',
width: '100%',
}} {...props}>
<mdui-text-field icon="search" type="search" clearable ref={searchRef} variant="outlined" placeholder="搜索..." style={{
paddingTop: '12px',
paddingBottom: '13px',
position: 'sticky',
top: '0',
backgroundColor: 'rgb(var(--mdui-color-background))',
zIndex: '10',
}}></mdui-text-field>
{
allChatsList.filter((chat) =>
searchText == '' ||
chat.getTitle().includes(searchText) ||
chat.getId().includes(searchText)
).map((v) =>
<AllChatsListItem
active={isMobileUI() ? false : currentChatId == v.getId()}
key={v.getId()}
onClick={() => {
openChatInfoDialog(v)
}}
chat={v} />
)
}
</mdui-list>
}

View File

@@ -0,0 +1,29 @@
import { $ } from "mdui/jq"
import Avatar from "../Avatar.tsx"
import React from 'react'
import { Chat } from "lingchair-client-protocol"
import getClient from "../../getClient.ts"
interface Args extends React.HTMLAttributes<HTMLElement> {
chat: Chat
active?: boolean
}
export default function AllChatsListItem({ chat, active, ...prop }: Args) {
const title = chat.getTitle()
const ref = React.useRef<HTMLElement>(null)
return (
<mdui-list-item active={active} ref={ref} rounded style={{
marginTop: '3px',
marginBottom: '3px',
width: '100%',
}} {...prop as any}>
<span style={{
width: "100%",
}}>{title}</span>
<Avatar src={getClient().getUrlForFileByHash(chat.getAvatarFileHash() as string)} text={title} slot="icon" />
</mdui-list-item>
)
}

View File

@@ -0,0 +1,164 @@
import React from "react"
import ContactsListItem from "./ContactsListItem.tsx"
import { dialog, Dialog, TextField } from "mdui"
interface Args extends React.HTMLAttributes<HTMLElement> {
display: boolean
openChatInfoDialog: (chat: Chat) => void
addContactDialogRef: React.MutableRefObject<Dialog>
createGroupDialogRef: React.MutableRefObject<Dialog>
setSharedFavouriteChats: React.Dispatch<React.SetStateAction<Chat[]>>
currentChatId: string
}
export default function ContactsList({
display,
openChatInfoDialog,
addContactDialogRef,
createGroupDialogRef,
setSharedFavouriteChats,
currentChatId,
...props
}: Args) {
const searchRef = React.useRef<HTMLElement>(null)
const [isMultiSelecting, setIsMultiSelecting] = React.useState(false)
const [searchText, setSearchText] = React.useState('')
const [contactsList, setContactsList] = React.useState<Chat[]>([])
const [checkedList, setCheckedList] = React.useState<{ [key: string]: boolean }>({})
useEventListener(searchRef, 'input', (e) => {
setSearchText((e.target as unknown as TextField).value)
})
React.useEffect(() => {
async function updateContacts() {
const re = await Client.invoke("User.getMyContacts", {
token: data.access_token,
})
if (re.code != 200) {
if (re.code != 401 && re.code != 400) checkApiSuccessOrSncakbar(re, "获取收藏对话列表失败")
return
}
const ls = re.data!.contacts_list as Chat[]
setContactsList(ls)
setSharedFavouriteChats(ls)
}
updateContacts()
EventBus.on('ContactsList.updateContacts', () => updateContacts())
return () => {
EventBus.off('ContactsList.updateContacts')
}
// 警告: 不添加 deps 導致無限執行
}, [])
return <mdui-list style={{
overflowY: 'auto',
paddingLeft: '10px',
paddingRight: '10px',
paddingTop: '0',
display: display ? undefined : 'none',
height: '100%',
width: '100%',
}} {...props}>
<div style={{
position: 'sticky',
top: '0',
backgroundColor: 'rgb(var(--mdui-color-background))',
zIndex: '10',
}}>
<mdui-text-field icon="search" type="search" clearable ref={searchRef} variant="outlined" placeholder="搜索..." style={{
paddingTop: '12px',
}}></mdui-text-field>
<mdui-list-item rounded style={{
marginTop: '13px',
width: '100%',
}} icon="person_add" onClick={() => addContactDialogRef.current!.open = true}></mdui-list-item>
<mdui-list-item rounded style={{
width: '100%',
}} icon="refresh" onClick={() => EventBus.emit('ContactsList.updateContacts')}></mdui-list-item>
<mdui-list-item rounded style={{
width: '100%',
}} icon={isMultiSelecting ? "done" : "edit"} onClick={() => {
if (isMultiSelecting)
setCheckedList({})
setIsMultiSelecting(!isMultiSelecting)
}}>{isMultiSelecting ? "关闭多选" : "多选模式"}</mdui-list-item>
{
isMultiSelecting && <>
<mdui-list-item rounded style={{
width: '100%',
}} icon="delete" onClick={() => dialog({
headline: "删除所选",
description: "确定要删除所选的收藏对话吗? 这并不会删除您的聊天记录, 也不会丢失对话成员身份",
closeOnEsc: true,
closeOnOverlayClick: true,
actions: [
{
text: "取消",
onClick: () => {
return true
},
},
{
text: "确定",
onClick: async () => {
const ls = Object.keys(checkedList).filter((chatId) => checkedList[chatId] == true)
const re = await Client.invoke("User.removeContacts", {
token: data.access_token,
targets: ls,
})
if (re.code != 200)
checkApiSuccessOrSncakbar(re, "删除所选收藏失败")
else {
setCheckedList({})
setIsMultiSelecting(false)
EventBus.emit('ContactsList.updateContacts')
snackbar({
message: "已删除所选",
placement: "top",
action: "撤销操作",
onActionClick: async () => {
const re = await Client.invoke("User.addContacts", {
token: data.access_token,
targets: ls,
})
if (re.code != 200)
checkApiSuccessOrSncakbar(re, "恢复所选收藏失败")
EventBus.emit('ContactsList.updateContacts')
}
})
}
},
}
],
})}></mdui-list-item>
</>
}
<div style={{
height: "10px",
}}></div>
</div>
{
contactsList.filter((chat) =>
searchText == '' ||
chat.title.includes(searchText) ||
chat.id.includes(searchText)
).map((v) =>
<ContactsListItem
active={isMultiSelecting ? checkedList[v.id] == true : (isMobileUI() ? false : currentChatId == v.id)}
onClick={() => {
if (isMultiSelecting)
setCheckedList({
...checkedList,
[v.id]: !checkedList[v.id],
})
else
openChatInfoDialog(v)
}}
key={v.id}
contact={v} />
)
}
</mdui-list>
}

View File

@@ -0,0 +1,27 @@
import Chat from "../../api/client_data/Chat.ts"
import getUrlForFileByHash from "../../getUrlForFileByHash.ts"
import Avatar from "../Avatar.tsx"
import React from 'react'
interface Args extends React.HTMLAttributes<HTMLElement> {
contact: Chat
active?: boolean
}
export default function ContactsListItem({ contact, ...prop }: Args) {
const { id, title, avatar_file_hash } = contact
const ref = React.useRef<HTMLElement>(null)
return (
<mdui-list-item ref={ref} rounded style={{
marginTop: '3px',
marginBottom: '3px',
width: '100%',
}} {...prop as any}>
<span style={{
width: "100%",
}}>{title}</span>
<Avatar src={getUrlForFileByHash(avatar_file_hash as string)} text={title} slot="icon" />
</mdui-list-item>
)
}

View File

@@ -0,0 +1,86 @@
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"
import useAsyncEffect from "../useAsyncEffect.ts"
import Client from "../../api/Client.ts"
import { checkApiSuccessOrSncakbar } from "../snackbar.ts";
import data from "../../Data.ts";
import EventBus from "../../EventBus.ts";
import isMobileUI from "../isMobileUI.ts";
interface Args extends React.HTMLAttributes<HTMLElement> {
display: boolean
currentChatId: string
openChatFragment: (id: string) => void
}
export default function RecentsList({
currentChatId,
display,
openChatFragment,
...props
}: Args) {
const searchRef = React.useRef<HTMLElement>(null)
const [searchText, setSearchText] = React.useState('')
const [recentsList, setRecentsList] = React.useState<RecentChat[]>([])
useEventListener(searchRef, 'input', (e) => {
setSearchText((e.target as unknown as TextField).value)
})
useAsyncEffect(async () => {
async function updateRecents() {
const re = await Client.invoke("User.getMyRecentChats", {
token: data.access_token,
})
if (re.code != 200) {
if (re.code != 401 && re.code != 400) checkApiSuccessOrSncakbar(re, "获取最近对话列表失败")
return
}
setRecentsList(re.data!.recent_chats as RecentChat[])
}
updateRecents()
EventBus.on('RecentsList.updateRecents', () => updateRecents())
const id = setInterval(() => updateRecents(), 15 * 1000)
return () => {
EventBus.off('RecentsList.updateRecents')
clearInterval(id)
}
})
return <mdui-list style={{
overflowY: 'auto',
paddingRight: '10px',
paddingLeft: '10px',
paddingTop: '0',
display: display ? undefined : 'none',
height: '100%',
width: '100%',
}} {...props}>
<mdui-text-field icon="search" type="search" clearable ref={searchRef} variant="outlined" placeholder="搜索..." style={{
paddingTop: '12px',
marginBottom: '13px',
position: 'sticky',
top: '0',
backgroundColor: 'rgb(var(--mdui-color-background))',
zIndex: '10',
}}></mdui-text-field>
{
recentsList.filter((chat) =>
searchText == '' ||
chat.title.includes(searchText) ||
chat.id.includes(searchText) ||
chat.content.includes(searchText)
).map((v) =>
<RecentsListItem
active={isMobileUI() ? false : currentChatId == v.id}
openChatFragment={() => openChatFragment(v.id)}
key={v.id}
recentChat={v} />
)
}
</mdui-list>
}

View File

@@ -0,0 +1,37 @@
import { $ } from "mdui/jq"
import RecentChat from "../../api/client_data/RecentChat.ts"
import Avatar from "../Avatar.tsx"
import React from 'react'
import getUrlForFileByHash from "../../getUrlForFileByHash.ts"
interface Args extends React.HTMLAttributes<HTMLElement> {
recentChat: RecentChat
openChatFragment: (id: string) => void
active?: boolean
}
export default function RecentsListItem({ recentChat, openChatFragment, active }: Args) {
const { id, title, avatar_file_hash, content } = recentChat
const itemRef = React.useRef<HTMLElement>(null)
React.useEffect(() => {
$(itemRef.current!.shadowRoot).find('.headline').css('margin-top', '3px')
})
return (
<mdui-list-item rounded style={{
marginTop: '3px',
marginBottom: '3px',
}} onClick={() => openChatFragment(id)} active={active} ref={itemRef}>
{title}
<Avatar src={getUrlForFileByHash(avatar_file_hash as string)} text={title} slot="icon" />
<span slot="description"
style={{
width: "100%",
display: "inline-block",
whiteSpace: "nowrap", /* 禁止换行 */
overflow: "hidden", /* 隐藏溢出内容 */
textOverflow: "ellipsis", /* 显示省略号 */
}}>{content}</span>
</mdui-list-item>
)
}