Merge branch 'prepare-inbox' of github.com:Discours/discoursio-webapp into layouts

This commit is contained in:
tonyrewin 2022-11-14 12:48:26 +03:00
commit 88efe043d5
15 changed files with 548 additions and 238 deletions

View File

@ -0,0 +1,35 @@
.DialogAvatar {
width: 40px;
height: 40px;
border-radius: 100%;
display: flex;
align-items: center;
justify-content: center;
position: relative;
&.online::before {
content: '';
position: absolute;
background: #2bb452;
width: 8px;
height: 8px;
top: -2px;
right: -2px;
border-radius: 50%;
border: 3px solid #fff;
}
> img,
> .letter {
display: block;
border-radius: 100%;
}
> .letter {
margin-bottom: -2px;
font-weight: 500;
font-size: 18px;
line-height: 10px;
color: #fff;
}
}

View File

@ -0,0 +1,48 @@
import { Show, createMemo } from 'solid-js'
import './DialogCard.module.scss'
import styles from './DialogAvatar.module.scss'
import { clsx } from 'clsx'
type Props = {
url: string
name: string
online?: boolean
}
const colors = [
'#001219',
'#005f73',
'#0a9396',
'#94d2bd',
'#ee9b00',
'#ca6702',
'#ae2012',
'#9b2226',
'#668CFF',
'#C34CFE',
'#E699FF',
'#6633FF'
]
const getById = (letter: string) =>
colors[Math.abs(Number(BigInt(letter.toLowerCase().charCodeAt(0) - 97) % BigInt(colors.length)))]
const DialogAvatar = (props: Props) => {
const nameFirstLetter = props.name.substring(0, 1)
const randomBg = createMemo(() => {
return getById(nameFirstLetter)
})
return (
<div
class={clsx(styles.DialogAvatar, props.online && styles.online)}
style={{ 'background-color': `${randomBg()}` }}
>
<Show when={props.url} fallback={() => <div class={styles.letter}>{nameFirstLetter}</div>}>
<img src={props.url} alt={props.name} />
</Show>
</div>
)
}
export default DialogAvatar

View File

@ -0,0 +1,67 @@
.DialogCard {
display: inline-flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
font-size: 14px;
padding: 12px;
transition: background 0.3s ease-in-out;
cursor: pointer;
&:hover {
background: #f7f7f7;
}
.avatar {
flex-basis: 40px;
margin-right: 12px;
}
.row {
flex-basis: 0;
flex-grow: 1;
min-width: 0;
.name,
.message {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.name {
color: #141414;
font-weight: 500;
}
.message {
color: #9fa1a7;
}
}
.activity {
font-size: 12px;
margin-left: 12px;
.time {
text-align: right;
color: #ccc;
}
.counter {
display: flex;
margin-left: auto;
align-items: center;
justify-content: center;
border-radius: 12px;
padding: 0 8px;
background: #d00820;
font-weight: 400;
color: #fff;
width: 22px;
height: 22px;
line-height: 6px;
> span {
margin-bottom: -2px;
}
}
}
}

View File

@ -0,0 +1,34 @@
import './DialogCard.module.scss'
import styles from './DialogCard.module.scss'
import DialogAvatar from './DialogAvatar'
import type { Author } from '../../graphql/types.gen'
type Props = {
online?: boolean
message?: string
counter?: number
} & Author
const DialogCard = (props: Props) => {
return (
<div class={styles.DialogCard}>
<div class={styles.avatar}>
<DialogAvatar name={props.name} url={props.userpic} online={props.online} />
</div>
<div class={styles.row}>
<div class={styles.name}>{props.name}</div>
<div class={styles.message}>
Указать предпочтительные языки для результатов поиска можно в разделе
</div>
</div>
<div class={styles.activity}>
<div class={styles.time}>22:22</div>
<div class={styles.counter}>
<span>12</span>
</div>
</div>
</div>
)
}
export default DialogCard

View File

@ -0,0 +1,44 @@
.Search {
.field {
position: relative;
background: #ffffff;
border: 2px solid #e8e8e8;
border-radius: 2px;
overflow: hidden;
input {
display: block;
height: 40px;
border: none;
box-shadow: none;
padding: 10px 36px 10px 12px;
width: 100%;
font-family: Muller, Arial, Helvetica, sans-serif;
font-style: normal;
font-weight: 400;
font-size: 15px;
&::placeholder {
color: #858585;
font-family: inherit;
}
&:focus {
outline: none;
& + .icon {
opacity: 0;
right: -30px;
}
}
}
.icon {
transition: 0.3s ease-in-out;
position: absolute;
width: 16px;
height: 16px;
top: 12px;
right: 12px;
opacity: 0.5;
}
}
}

View File

@ -0,0 +1,27 @@
import styles from './Search.module.scss'
import { createSignal } from 'solid-js'
import { Icon } from '../Nav/Icon'
type Props = {
placeholder: string
onChange: (value: () => string) => void
}
const Search = (props: Props) => {
const [value, setValue] = createSignal<string>('')
const search = (event) => {
event.preventDefault()
setValue(event.target.value)
props.onChange(value)
}
return (
<div class={styles.Search}>
<div class={styles.field}>
<input type="text" onInput={search} placeholder={props.placeholder} />
<Icon name="search" class={styles.icon} />
</div>
</div>
)
}
export default Search

View File

@ -22,7 +22,7 @@ export const ForgotPasswordForm = () => {
setValidationErrors(({ email: _notNeeded, ...rest }) => rest)
setEmail(newEmail)
}
const [sended, setSended] = createSignal(false)
const [submitError, setSubmitError] = createSignal('')
const [isSubmitting, setIsSubmitting] = createSignal(false)
const [validationErrors, setValidationErrors] = createSignal<ValidationErrors>({})
@ -53,6 +53,7 @@ export const ForgotPasswordForm = () => {
try {
const result = await signSendLink({ email: email(), lang: locale() })
if (result.error) setSubmitError(result.error)
else setSended(true)
} catch (error) {
setSubmitError(error.message)
} finally {
@ -63,7 +64,12 @@ export const ForgotPasswordForm = () => {
return (
<form onSubmit={handleSubmit}>
<h4>{t('Forgot password?')}</h4>
<Show
when={!sended()}
fallback={<div class={styles.authInfo}>{t('Link sent, check your email')}</div>}
>
<div class={styles.authSubtitle}>{t('Everything is ok, please give us your email address')}</div>
</Show>
<Show when={submitError()}>
<div class={styles.authInfo}>
<ul>

View File

@ -1,59 +1,140 @@
import { For, createSignal, Show, onMount, createEffect } from 'solid-js'
import type { Author } from '../../graphql/types.gen'
import { AuthorCard } from '../Author/Card'
import { Icon } from '../Nav/Icon'
import { Loading } from '../Loading'
import DialogCard from '../Inbox/DialogCard'
import Search from '../Inbox/Search'
import { useAuthorsStore } from '../../stores/zine/authors'
import '../../styles/Inbox.scss'
// Для моков
import { createClient } from '@urql/core'
import { findAndLoadGraphQLConfig } from '@graphql-codegen/cli'
const OWNER_ID = '501'
const client = createClient({
url: 'https://graphqlzero.almansi.me/api'
})
// interface InboxProps {
// chats?: Chat[]
// messages?: Message[]
// }
const messageQuery = `
query Comments ($options: PageQueryOptions) {
comments(options: $options) {
data {
id
body
email
}
}
}
`
const newMessageQuery = `
mutation postComment($messageBody: String!) {
createComment(
input: { body: $messageBody, email: "test@test.com", name: "User" }
) {
id
body
name
email
}
}
`
const userSearch = (array: Author[], keyword: string) => {
const searchTerm = keyword.toLowerCase()
return array.filter((value) => {
return value.name.toLowerCase().match(new RegExp(searchTerm, 'g'))
})
}
export const InboxView = () => {
const [messages, setMessages] = createSignal([])
const [authors, setAuthors] = createSignal<Author[]>([])
const [postMessageText, setPostMessageText] = createSignal('')
const [loading, setLoading] = createSignal<boolean>(false)
const { sortedAuthors } = useAuthorsStore()
createEffect(() => {
setAuthors(sortedAuthors())
})
// Поиск по диалогам
const getQuery = (query) => {
if (query().length >= 2) {
const match = userSearch(authors(), query())
console.log('!!! match:', match)
setAuthors(match)
} else {
setAuthors(sortedAuthors())
}
}
const fetchMessages = async (query) => {
const response = await client
.query(query, {
options: { slice: { start: 0, end: 3 } }
})
.toPromise()
if (response.error) console.debug('getMessages', response.error)
setMessages(response.data.comments.data)
}
const postMessage = async (msg: string) => {
const response = await client.mutation(newMessageQuery, { messageBody: msg }).toPromise()
return response.data.createComment
}
let chatWindow
onMount(async () => {
setLoading(true)
await fetchMessages(messageQuery)
.then(() => {
setLoading(false)
chatWindow.scrollTop = chatWindow.scrollHeight
})
.catch(() => setLoading(false))
})
const handleSubmit = async () => {
postMessage(postMessageText())
.then((result) => {
setMessages((prev) => [...prev, result])
})
.then(() => {
setPostMessageText('')
chatWindow.scrollTop = chatWindow.scrollHeight
})
}
const handleChangeMessage = (event) => {
setPostMessageText(event.target.value)
}
// TODO: get user session
return (
<div class="messages container">
<div class="row">
<div class="chat-list col-md-4">
<form class="chat-list__search">
<input type="search" placeholder="Поиск" />
<button class="button">+</button>
</form>
<Search placeholder="Поиск" onChange={getQuery} />
<div class="chat-list__types">
<ul>
<li>
<strong>
<a href="/">Все</a>
</strong>
</li>
<li>
<a href="/">Переписки</a>
</li>
<li>
<a href="/">Группы</a>
<strong>Все</strong>
</li>
<li>Переписки</li>
<li>Группы</li>
</ul>
</div>
<div class="chat-list__users">
<ul>
<li>
<AuthorCard author={{} as Author} hideFollow={true} />
<div class="last-message-date">12:15</div>
<div class="last-message-text">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
<div class="holder">
<div class="dialogs">
<For each={authors()}>
{(author) => <DialogCard name={author.name} slug={author.slug} online={true} />}
</For>
</div>
</li>
<li class="user--online chat-list__user--current">
<AuthorCard author={{} as Author} hideFollow={true} />
<div class="last-message-date">19:48</div>
<div class="last-message-text">
Assumenda delectus deleniti dolores doloribus ducimus, et expedita facere iste laborum,
nihil similique suscipit, ut voluptatem. Accusantium consequuntur doloremque ex molestiae
nemo.
</div>
</li>
</ul>
</div>
</div>
@ -64,59 +145,50 @@ export const InboxView = () => {
</div>
<div class="conversation__messages">
<div class="conversation__messages-container">
<div class="conversation__message-container conversation__message-container--other">
<div class="conversation__messages-container" ref={chatWindow}>
<Show when={loading()}>
<Loading />
</Show>
<For each={messages()}>
{(comment: { body: string; id: string; email: string }) => (
<div
class={`conversation__message-container
${
OWNER_ID === comment.id
? 'conversation__message-container--own'
: 'conversation__message-container--other'
}`}
>
<div class="conversation__message">
Круто, беру в оборот!
{comment.body}
<div class="conversation__message-details">
<time>14:26</time>
{comment.email} id: {comment.id}
</div>
<button class="conversation__context-popup-control">
<Icon name="ellipsis" />
</button>
</div>
</div>
)}
</For>
<div class="conversation__message-container conversation__message-container--own">
<div class="conversation__message">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut beatae earum iste itaque
libero perspiciatis possimus quod! Accusamus, aliquam amet consequuntur debitis dolorum
esse laudantium magni omnis rerum voluptatem voluptates!
<div class="conversation__message-details">
<time>14:31</time>
Отредактировано
</div>
<button class="conversation__context-popup-control">
<Icon name="ellipsis" />
</button>
{/*<div class="conversation__date">*/}
{/* <time>12 сентября</time>*/}
{/*</div>*/}
</div>
</div>
<div class="conversation__date">
<time>12 сентября</time>
</div>
<div class="conversation__message-container conversation__message-container--other">
<div class="conversation__message">
Нужна грамотная инфраструктура для сообщений, если ожидается нагрузка - надо опираться на
это. Но в целом это несложно сделать.
<div class="conversation__message-details">
<time>10:47</time>
</div>
<button class="conversation__context-popup-control">
<Icon name="ellipsis" />
</button>
</div>
</div>
</div>
</div>
<form class="conversation__message-form">
<input type="text" placeholder="Написать сообщение" />
<button type="submit">
<div class="conversation__message-form">
<textarea
value={postMessageText()}
onInput={(event) => handleChangeMessage(event)}
placeholder="Написать сообщение"
/>
<button type="submit" disabled={postMessageText().length === 0} onClick={handleSubmit}>
<Icon name="send-message" />
</button>
</form>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,26 @@
import { gql } from '@urql/core'
export default gql`
query GetChatsQuery {
myChats {
error
chats {
title
description
updatedAt
messages {
id
author
body
replyTo
createdAt
}
users {
slug
name
userpic
}
}
}
}
`

View File

@ -0,0 +1,16 @@
import { gql } from '@urql/core'
export default gql`
query LoadMessagesQuery($chatId: String!, $offset: Int, $amount: Int) {
loadChat(chatId: $chatId, offset: $offset, amount: $amount) {
error
messages {
author
body
createdAt
updatedAt
seen
}
}
}
`

View File

@ -1,23 +0,0 @@
import { gql } from '@urql/core'
export default gql`
query GetChatsQuery {
myChats {
messages {
chatId
id
author
body
replyTo
createdAt
}
users {
slug
name
pic
}
title
createdAt
}
}
`

View File

@ -4,7 +4,7 @@ import { Root } from '../components/Root'
import { apiClient } from '../utils/apiClient'
import { initRouter } from '../stores/router'
const chatrooms = await apiClient.getInboxes()
const chatrooms = await apiClient.getChats()
const { pathname, search } = Astro.url
initRouter(pathname, search)

View File

@ -11,11 +11,15 @@ export const signIn = async (params) => {
setToken(authResult.token)
console.debug('signed in')
}
export const signOut = () => {
// TODO: call backend to revoke token
export const signOut = async () => {
const result = await apiClient.authSignOut()
if (result.error) {
console.error('[auth] sign out error', result.error)
} else {
setSession(null)
resetToken()
console.debug('signed out')
}
}
export const [emailChecks, setEmailChecks] = createSignal<{ [email: string]: boolean }>({})

View File

@ -1,16 +1,23 @@
main {
display: flex;
height: 100%;
height: 100vh;
flex-direction: column;
position: relative;
}
.messages {
top: 74px;
height: calc(100% - 74px);
left: 0;
right: 0;
padding-left: 42px;
padding-right: 26px;
background: #fff;
display: flex;
flex: 1;
flex-direction: column;
height: 100%;
position: relative;
position: fixed;
z-index: 1;
> .row {
flex: 1;
@ -23,34 +30,53 @@ main {
.author {
position: relative;
}
.user--online .author {
&::before {
background: #2bb452;
border: 5px solid #fff;
border-radius: 100%;
content: '';
height: 5px;
left: 20px;
position: absolute;
top: 0;
width: 5px;
z-index: 1;
}
}
.circlewrap {
position: absolute;
}
}
// список диалогов и юзеров
.chat-list {
border-right: 1px solid #141414;
display: flex;
flex-direction: column;
padding: 10px;
height: calc(100% - 10px);
.author__name {
@include font-size(1.5rem);
$fade-height: 10px;
.holder {
overflow: hidden;
flex: 1;
position: relative;
padding: $fade-height 0;
&::before,
&::after {
content: '';
position: absolute;
width: 100%;
right: 10px;
z-index: 1;
height: $fade-height;
}
&::before {
top: 0;
background: linear-gradient(white, transparent $fade-height);
}
&::after {
bottom: 0;
background: linear-gradient(transparent, white $fade-height);
}
.dialogs {
scroll-behavior: smooth;
display: flex;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
overflow: auto;
flex-direction: column;
box-sizing: border-box;
}
}
}
@ -60,41 +86,10 @@ main {
padding: 1em 0;
}
.chat-list__search {
display: flex;
input,
.button {
border-radius: 2px;
height: 5.6rem;
line-height: 5.6rem;
vertical-align: bottom;
}
input {
border: 2px solid #e8e8e8;
flex: 1;
@include font-size(1.7rem);
margin-right: 1.6rem;
padding: 1.6rem 1.2rem;
}
.button {
@include font-size(4rem);
font-weight: 100;
padding: 0;
width: 5.6rem;
}
}
// табы выбора списка
.chat-list__types {
@include font-size(1.7rem);
margin-bottom: 1.5em;
padding-top: 1em;
margin: 16px 0;
ul {
display: flex;
flex-wrap: wrap;
@ -113,66 +108,6 @@ main {
}
}
.chat-list__users {
flex: 1;
position: relative;
ul {
height: 100%;
list-style: none;
margin: 0;
overflow: auto;
padding: 0;
position: absolute;
width: 100%;
}
li {
align-items: baseline;
background: #fff;
cursor: pointer;
display: flex;
flex-wrap: wrap;
@include font-size(1.5rem);
padding: 2.4rem 0.8rem;
position: relative;
transition: background-color 0.3s;
&:hover {
background: #f6f6f6;
}
}
.chat-list__user--current {
background: #f6f6f6;
cursor: default;
}
.author {
flex: 1;
margin-bottom: 0;
}
.author__details {
margin-left: 4.2rem;
}
.last-message-date {
color: rgb(0 0 0 / 30%);
@include font-size(1rem);
}
.last-message-text {
color: rgb(0 0 0 / 30%);
flex: 1 100%;
margin-left: 4.2rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.interlocutor {
height: 56px;
box-sizing: content-box;
@ -218,7 +153,6 @@ main {
.conversation__messages {
flex: 1;
min-height: 20em;
overflow: auto;
position: relative;
}
@ -226,14 +160,19 @@ main {
.conversation__message-form {
border-top: 1px solid #141414;
display: flex;
flex-direction: row;
align-items: center;
padding: 1em 1em 1em 0;
input {
border: none;
textarea {
@include font-size(2rem);
height: 5.6rem;
font-family: inherit;
height: 4.4em;
width: 100%;
padding: 1em;
margin-bottom: 0;
min-height: unset;
}
button {
@ -266,6 +205,7 @@ main {
position: absolute;
top: 0;
width: 100%;
scroll-behavior: smooth;
}
.conversation__date {
@ -298,10 +238,11 @@ main {
}
.conversation__message {
@include font-size(1.5rem);
font-size: 14px;
max-width: 60%;
padding: 1.6rem 2.4rem;
border-radius: 16px;
padding: 12px 16px;
position: relative;
&:hover {

View File

@ -28,7 +28,8 @@ import reactionUpdate from '../graphql/mutation/reaction-update'
import authorsBySlugs from '../graphql/query/authors-by-slugs'
import incrementView from '../graphql/mutation/increment-view'
import createArticle from '../graphql/mutation/article-create'
import myChats from '../graphql/query/my-chats'
import myChats from '../graphql/query/im-chats'
import loadChat from '../graphql/query/im-load-messages'
import getRecentByLayout from '../graphql/query/layout-recent'
import getTopByLayout from '../graphql/query/layout-top'
import getTopMonthByLayout from '../graphql/query/layout-top-month'
@ -337,7 +338,7 @@ export const apiClient = {
incrementView: async ({ articleSlug }) => {
await privateGraphQLClient.mutation(incrementView, { shout: articleSlug })
},
getInboxes: async (payload = {}) => {
getChats: async (payload = {}) => {
const resp = await privateGraphQLClient.query(myChats, payload).toPromise()
return resp.data.myChats
},
@ -354,5 +355,17 @@ export const apiClient = {
.query(getTopMonthByLayout, { amount, offset, layout })
.toPromise()
return resp.data.topMonthLayoutShouts
},
getChatMessages: async ({
chatId,
offset = 0,
amount = 50
}: {
chatId: string
offset?: number
amount?: number
}) => {
const resp = await privateGraphQLClient.query(loadChat, { chatId, offset, amount }).toPromise()
return resp.data.loadChat
}
}