Skip to content

Commit

Permalink
Fixes for first review
Browse files Browse the repository at this point in the history
  • Loading branch information
Pillowbee committed Apr 17, 2024
1 parent 110aede commit 71ddb5b
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 16 deletions.
5 changes: 5 additions & 0 deletions src/components/avatar/avatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ type AvatarProps = {

export default class Avatar extends Block {
constructor(props: AvatarProps) {
if (!props.src) {
props.src = 'https://i2.wp.com/vdostavka.ru/wp-content/uploads/2019/05/no-avatar.png?fit=512%2C512&ssl=1'
}

super(props)

if (!this.props.canChange) {
this.props.canChange = false
}
Expand Down
106 changes: 97 additions & 9 deletions src/components/chatWindow/chatWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const ChatTemplate: string = `
<div class="chat-menu__actions">
{{{ addUserBtn }}}
{{{ deleteUserBtn }}}
{{{ deleteChatBtn }}}
</div>
</div>
</div>
Expand Down Expand Up @@ -59,12 +60,14 @@ export class ChatWindow extends Block {
private socket: WebSocket | null = null
private chat: Chat | null = null
private modal: Modal
private isChatAdmin: boolean = false

constructor(props: ChatWindowProps) {
super(props)

this.modal = new Modal()
this.children.addUserBtn = new Button({
label: '<i class="lni lni-menu"></i>Добавить пользователя',
label: '<i class="lni lni-plus"></i>Добавить пользователя',
className: 'chat-menu__action',
withId: true,
events: {
Expand All @@ -74,7 +77,7 @@ export class ChatWindow extends Block {
},
})
this.children.deleteUserBtn = new Button({
label: '<i class="lni lni-menu"></i>Удалить пользователя',
label: '<i class="lni lni-trash-can"></i>Удалить пользователя',
className: 'chat-menu__action',
withId: true,
events: {
Expand All @@ -83,6 +86,90 @@ export class ChatWindow extends Block {
},
},
})
this.children.deleteChatBtn = new Button({
label: '<i class="lni lni-close"></i>Удалить чат',
className: 'chat-menu__action',
withId: true,
events: {
click: () => {
if (this.chat) {
chatController.deleteChat(this.chat.id)
}
},
},
})

this.isChatAdmin = this.checkUserIsChatAdmin()
}

checkUserIsChatAdmin() {
if (this.props.chatUsers && Array.isArray(this.props.chatUsers)) {
const user = this.props.chatUsers.filter((user: User) => {
return user.id === store.getState().userdata.id
})[0]

const element = this.children.deleteChatBtn.element as HTMLElement

if (user && user.role !== 'admin') {
element.style.display = 'none'
} else {
element.style.display = 'flex'
}

return user && user.role === 'admin'
} else {
return false
}
}

uploadChatAvatarHandler(isChatAdmin: boolean) {
if (!isChatAdmin) {
return
}

const fileInput = document.createElement('input')
fileInput.type = 'file'

fileInput.onchange = async (e: Event) => {
if (
e.currentTarget instanceof HTMLInputElement &&
e.currentTarget.files
) {
const formData = new FormData()

formData.append('avatar', e.currentTarget.files[0])
formData.append('chatId', `${store.getState().selectedChat}`)

chatController.uploadChatAvatar(formData).then(() => {
chatController.getChats().then(() => {
this.chat = store
.getState()
.chats.filter((chat) => chat.id === this.props.selectedChat)[0]

if (this.chat) {
this.setProps({ currentChat: { ...this.chat, src: this.chat.avatar } })
}
})
})
}
}

fileInput.click()
}

updateChatAvatar(chat: Chat) {
this.children.avatar = new Avatar({
src: chat.avatar ? getResourceURL(chat.avatar) : '',
alt: chat.avatar ? (this.props.title as string) : '',
size: '40px',
withId: true,
canChange: this.isChatAdmin,
events: {
click: () => {
this.uploadChatAvatarHandler(this.isChatAdmin)
},
},
})
}

createSocket() {
Expand All @@ -97,13 +184,9 @@ export class ChatWindow extends Block {
this.chat = store
.getState()
.chats.filter((chat) => chat.id === this.props.selectedChat)[0]

this.props.title = this.chat.title
this.children.avatar = new Avatar({
src: this.chat.avatar ? getResourceURL(this.chat.avatar) : '',
alt: this.chat.avatar ? (this.props.title as string) : '',
size: '40px',
withId: true,
})
this.updateChatAvatar(this.chat)

this.children.messageInput = new Input({
type: 'text',
Expand Down Expand Up @@ -177,7 +260,6 @@ export class ChatWindow extends Block {
users: [user.id],
chatId: Number(this.props.selectedChat),
})
console.log(store.getState().chatUsers)
this.closeModal()
})

Expand Down Expand Up @@ -216,6 +298,11 @@ export class ChatWindow extends Block {
}

this.blockArrays.messages = this.showMessages(store.getState().messages)
this.isChatAdmin = this.checkUserIsChatAdmin()

if (newProps.currentChat) {
this.updateChatAvatar(newProps.currentChat as Chat)
}

return super.componentDidUpdate(oldProps, newProps)
}
Expand All @@ -229,4 +316,5 @@ export const chatWindow = connect((state) => ({
selectedChat: state.selectedChat,
messages: state.messages,
chatUsers: state.chatUsers,
currentChat: state.currentChat,
}))(ChatWindow)
5 changes: 5 additions & 0 deletions src/components/input/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ export default class Input extends Block {
this._validation = props.validation
}

componentDidUpdate(oldProps: Props, newProps: Partial<Props>): boolean {
this._inputElement.setProps(newProps)
return super.componentDidUpdate(oldProps, newProps)
}

get name() {
return this._name
}
Expand Down
1 change: 1 addition & 0 deletions src/constants/initialState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ export const initialState = {
selectedChat: 0,
messages: [],
chatUsers: [],
currentChat: null
}
14 changes: 14 additions & 0 deletions src/controllers/ChatController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export class ChatController {

public async getToken(chatId: number) {
return chatService.getToken(chatId).then((resp) => {
const currentChat = store
.getState()
.chats.filter((chat) => chat.id === store.getState().selectedChat)[0]
store.set('currentChat', currentChat)
return JSON.parse(resp.response)
})
}
Expand All @@ -32,6 +36,16 @@ export class ChatController {
})
}

public async deleteChat(chatId: number) {
return chatService.deleteChat(chatId).then(() => {
this.getChats()
})
}

public async uploadChatAvatar(data: FormData) {
return chatService.uploadChatAvatar(data)
}

public async addUserToChat(data: ChatUsersRequest) {
return chatService.addUserToChat(data).then(() => {
this.getChatUsers(data.chatId)
Expand Down
2 changes: 1 addition & 1 deletion src/core/HTTPTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type HTTPMethod = (url: string, options: Options) => Promise<XMLHttpRequest>

export type Options = {
method?: keyof typeof METHODS
body?: Record<string, number | number[] | string> | FormData
body?: Record<string, number | number[] | string | FormData> | FormData
headers?: Record<string, string>
timeout?: number
}
Expand Down
1 change: 1 addition & 0 deletions src/core/Store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type StateType = {
selectedChat: number
messages: MessageItemProps[]
chatUsers: User[]
currentChat: Chat | null
}

class Store extends EventBus {
Expand Down
32 changes: 26 additions & 6 deletions src/pages/editUserdataPage/editUserdataPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { UserController } from '@/controllers/UserController.ts'
import Block from '@/core/Block'
import router from '@/router.ts'
import '../profilePage/profilePage.css'
import connect from '@/utils/connect.ts'

const EditUserdataPageTemplate = `
<div class="profile">
Expand Down Expand Up @@ -50,13 +51,32 @@ const submitHandler = (e: Event) => {
}
}

const emailInputWithUserdata = connect((state) => ({ value: state.userdata.email }))(
Input
)
const loginInputWithUserdata = connect((state) => ({ value: state.userdata.login }))(
Input
)
const firstNameInputWithUserdata = connect((state) => ({ value: state.userdata.first_name }))(
Input
)
const secondNameInputWithUserdata = connect((state) => ({ value: state.userdata.second_name }))(
Input
)
const displayNameInputWithUserdata = connect((state) => ({ value: state.userdata.display_name }))(
Input
)
const phoneNameInputWithUserdata = connect((state) => ({ value: state.userdata.phone }))(
Input
)

const editUserdataForm = new Form({
className: 'edit-userdata dialog-form',
events: {
submit: submitHandler,
},
inputs: [
new Input({
new emailInputWithUserdata({
type: 'text',
name: 'email',
label: 'Почта',
Expand All @@ -66,7 +86,7 @@ const editUserdataForm = new Form({
errorText: 'Неверный формат почты',
},
}),
new Input({
new loginInputWithUserdata({
type: 'text',
name: 'login',
label: 'Логин',
Expand All @@ -76,7 +96,7 @@ const editUserdataForm = new Form({
errorText: 'Неверный формат логина',
},
}),
new Input({
new firstNameInputWithUserdata({
type: 'text',
name: 'first_name',
label: 'Имя',
Expand All @@ -86,7 +106,7 @@ const editUserdataForm = new Form({
errorText: 'Неверный формат имени',
},
}),
new Input({
new secondNameInputWithUserdata({
type: 'text',
name: 'second_name',
label: 'Фамилия',
Expand All @@ -96,7 +116,7 @@ const editUserdataForm = new Form({
errorText: 'Неверный формат фамилии',
},
}),
new Input({
new displayNameInputWithUserdata({
type: 'text',
name: 'display_name',
label: 'Имя в чате',
Expand All @@ -106,7 +126,7 @@ const editUserdataForm = new Form({
errorText: 'Неверный формат фамилии',
},
}),
new Input({
new phoneNameInputWithUserdata({
type: 'text',
name: 'phone',
label: 'Телефон',
Expand Down
6 changes: 6 additions & 0 deletions src/services/ChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ export class ChatService {
})
}

uploadChatAvatar(data: FormData) {
return HTTPTransport.put(`${this.baseURL}/avatar`, {
body: data,
})
}

addUserToChat(data: ChatUsersRequest) {
return HTTPTransport.put(`${this.baseURL}/users`, {
body: data,
Expand Down

0 comments on commit 71ddb5b

Please sign in to comment.