From 2674717f04875d2912144a8f60db92b3334d5e81 Mon Sep 17 00:00:00 2001 From: Ilya Y <75578537+ilya-bkv@users.noreply.github.com> Date: Sat, 14 Oct 2023 14:39:24 +0300 Subject: [PATCH] Feature/notifications (#244) * WIP * WIP * WIP * packaga-lock.json * WIP * WIP * WIP * WIP * v0.1 * debug code removed --------- Co-authored-by: Igor Lobanov --- public/locales/en/translation.json | 3 +- public/locales/ru/translation.json | 7 +- src/components/App.tsx | 9 +- src/components/Discours/Donate.tsx | 14 +- src/components/Nav/HeaderAuth.tsx | 65 ++++----- src/components/Nav/Modal/Modal.tsx | 14 +- src/components/Nav/Notifications.tsx | 19 --- .../NotificationView.module.scss | 32 +++++ .../NotificationView/NotificationView.tsx | 128 ++++++++++++++++++ .../NotificationView/index.ts | 1 + .../NotificationsPanel.module.scss | 66 +++++++++ .../NotificationsPanel/NotificationsPanel.tsx | 70 ++++++++++ src/components/NotificationsPanel/index.ts | 1 + src/components/Views/Author/Author.tsx | 34 ++--- src/components/_shared/PageLayout.tsx | 2 +- src/context/notifications.tsx | 106 +++++++++++++++ src/graphql/mutation/auth-logout.ts | 2 - .../mutation/mark-notification-as-read.ts | 9 ++ src/graphql/mutation/unfollow.ts | 1 - src/graphql/mutation/update-profile.ts | 1 - src/graphql/query/auth-login.ts | 1 + src/graphql/query/author-reacted-shouts.ts | 2 - src/graphql/query/notifications.ts | 20 +++ src/graphql/subs/new-message.ts | 15 -- src/graphql/subs/new-reaction.ts | 26 ---- src/graphql/subs/new-shout.ts | 25 ---- src/main.astro | 33 ----- src/pages/topic/[slug].astro | 21 --- src/stores/ui.ts | 19 --- src/styles/app.scss | 2 + src/utils/apiClient.ts | 18 ++- src/utils/pageLoadManager.ts | 1 - src/utils/sseService.ts | 33 +++++ 33 files changed, 554 insertions(+), 246 deletions(-) delete mode 100644 src/components/Nav/Notifications.tsx create mode 100644 src/components/NotificationsPanel/NotificationView/NotificationView.module.scss create mode 100644 src/components/NotificationsPanel/NotificationView/NotificationView.tsx create mode 100644 src/components/NotificationsPanel/NotificationView/index.ts create mode 100644 src/components/NotificationsPanel/NotificationsPanel.module.scss create mode 100644 src/components/NotificationsPanel/NotificationsPanel.tsx create mode 100644 src/components/NotificationsPanel/index.ts create mode 100644 src/context/notifications.tsx create mode 100644 src/graphql/mutation/mark-notification-as-read.ts create mode 100644 src/graphql/query/notifications.ts delete mode 100644 src/graphql/subs/new-message.ts delete mode 100644 src/graphql/subs/new-reaction.ts delete mode 100644 src/graphql/subs/new-shout.ts delete mode 100644 src/main.astro delete mode 100644 src/pages/topic/[slug].astro create mode 100644 src/utils/sseService.ts diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index 91b84fc6..7b5f0ee8 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -211,6 +211,7 @@ "New stories every day and even more!": "New stories and more are waiting for you every day!", "Newsletter": "Newsletter", "Night mode": "Night mode", + "No notifications, yet": "No notifications, yet", "No such account, please try to register": "No such account found, please try to register", "Nothing here yet": "There's nothing here yet", "Nothing is here": "There is nothing here", @@ -244,6 +245,7 @@ "Profile": "Profile", "Profile settings": "Profile settings", "Publications": "Publications", + "PublicationsWithCount": "{count, plural, =0 {no publications} one {{count} publication} other {{count} publications}}", "Publish Album": "Publish Album", "Publish Settings": "Publish Settings", "Punchline": "Punchline", @@ -414,6 +416,5 @@ "view": "view", "zine": "zine", "SubscriptionWithPlurals": "{count, plural, =0 {no subscriptions} one {{count} subscription} other {{count} subscriptions}", - "PublicationsWithCount": "{count, plural, =0 {no publications} one {{count} publication} other {{count} publications}}", "Edit profile": "Edit profile" } diff --git a/public/locales/ru/translation.json b/public/locales/ru/translation.json index 5f63ca7c..ba470f72 100644 --- a/public/locales/ru/translation.json +++ b/public/locales/ru/translation.json @@ -221,6 +221,7 @@ "New stories every day and even more!": "Каждый день вас ждут новые истории и ещё много всего интересного!", "Newsletter": "Рассылка", "Night mode": "Ночная тема", + "No notifications, yet": "Тут пока пусто", "No such account, please try to register": "Такой адрес не найден, попробуйте зарегистрироваться", "Nothing here yet": "Здесь пока ничего нет", "Nothing is here": "Здесь ничего нет", @@ -257,6 +258,7 @@ "Profile successfully saved": "Профиль успешно сохранён", "Publication settings": "Настройки публикации", "Publications": "Публикации", + "PublicationsWithCount": "{count, plural, =0 {нет публикаций} one {{count} публикация} few {{count} публикации} other {{count} публикаций}}", "Publish": "Опубликовать", "Publish Album": "Опубликовать альбом", "Publish Settings": "Настройки публикации", @@ -438,6 +440,7 @@ "zine": "журнал", "SubscriberWithCount": "{count, plural, =0 {нет подписчиков} one {{count} подписчик} few {{count} подписчика} other {{count} подписчиков}}", "SubscriptionWithCount": "{count, plural, =0 {нет подписок} one {{count} подписка} few {{count} подписки} other {{count} подписок}}", - "PublicationsWithCount": "{count, plural, =0 {нет публикаций} one {{count} публикация} few {{count} публикации} other {{count} публикаций}}", - "Edit profile": "Редактировать профиль" + "Edit profile": "Редактировать профиль", + "NewCommentNotificationText": "{commentsCount, plural, one {Новый комментарий} few {{commentsCount} новых комментария} other {{commentsCount} новых комментариев}} к вашей публикации {shoutTitle} от {lastCommenterName}{restUsersCount, plural, =0 {} one { и ещё 1 пользователя} few { и ещё {restUsersCount} пользователей} other { и ещё {restUsersCount} пользователей}}", + "NewReplyNotificationText": "{commentsCount, plural, one {Новый ответ} few {{commentsCount} новых ответа} other {{commentsCount} новых ответов}} к вашему комментарию к публикации {shoutTitle} от {lastCommenterName}{restUsersCount, plural, =0 {} one { и ещё 1 пользователя} few { и ещё {restUsersCount} пользователей} other { и ещё {restUsersCount} пользователей}}" } diff --git a/src/components/App.tsx b/src/components/App.tsx index 59662098..f5e054c5 100644 --- a/src/components/App.tsx +++ b/src/components/App.tsx @@ -40,6 +40,7 @@ import { SnackbarProvider } from '../context/snackbar' import { LocalizeProvider } from '../context/localize' import { ConfirmProvider } from '../context/confirm' import { EditorProvider } from '../context/editor' +import { NotificationsProvider } from '../context/notifications' // TODO: lazy load // const SomePage = lazy(() => import('./Pages/SomePage')) @@ -113,9 +114,11 @@ export const App = (props: PageProps) => { - - - + + + + + diff --git a/src/components/Discours/Donate.tsx b/src/components/Discours/Donate.tsx index 597be698..08b92b14 100644 --- a/src/components/Discours/Donate.tsx +++ b/src/components/Discours/Donate.tsx @@ -1,7 +1,8 @@ import '../../styles/help.scss' import { createSignal, onMount } from 'solid-js' -import { showModal, warn } from '../../stores/ui' +import { showModal } from '../../stores/ui' import { useLocalize } from '../../context/localize' +import { useSnackbar } from '../../context/snackbar' export const Donate = () => { const { t } = useLocalize() @@ -20,6 +21,9 @@ export const Donate = () => { const [showingPayment, setShowingPayment] = createSignal() const [period, setPeriod] = createSignal(monthly) const [amount, setAmount] = createSignal(0) + const { + actions: { showSnackbar } + } = useSnackbar() const initiated = () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -104,10 +108,10 @@ export const Donate = () => { // fail // действие при неуспешной оплате console.debug('[donate] options', options) - warn({ - kind: 'error', - body: reason, - seen: false + + showSnackbar({ + type: 'error', + body: reason }) } ) diff --git a/src/components/Nav/HeaderAuth.tsx b/src/components/Nav/HeaderAuth.tsx index a24e2132..5fe286b7 100644 --- a/src/components/Nav/HeaderAuth.tsx +++ b/src/components/Nav/HeaderAuth.tsx @@ -3,10 +3,9 @@ import { clsx } from 'clsx' import { router, useRouter } from '../../stores/router' import { Icon } from '../_shared/Icon' import { createMemo, createSignal, onCleanup, onMount, Show } from 'solid-js' -import Notifications from './Notifications' import { ProfilePopup } from './ProfilePopup' import { Userpic } from '../Author/Userpic' -import { showModal, useWarningsStore } from '../../stores/ui' +import { showModal } from '../../stores/ui' import { ShowOnlyOnClient } from '../_shared/ShowOnlyOnClient' import { useSession } from '../../context/session' import { useLocalize } from '../../context/localize' @@ -14,6 +13,7 @@ import { getPagePath } from '@nanostores/router' import { Button } from '../_shared/Button' import { useEditorContext } from '../../context/editor' import { Popover } from '../_shared/Popover' +import { useNotifications } from '../../context/notifications' type Props = { setIsProfilePopupVisible: (value: boolean) => void @@ -29,18 +29,17 @@ const MD_WIDTH_BREAKPOINT = 992 export const HeaderAuth = (props: Props) => { const { t } = useLocalize() const { page } = useRouter() - const [visibleWarnings, setVisibleWarnings] = createSignal(false) - const { warnings } = useWarningsStore() - const { session, isSessionLoaded, isAuthenticated } = useSession() + const { + unreadNotificationsCount, + actions: { showNotificationsPanel } + } = useNotifications() const { form, actions: { toggleEditorPanel, saveShout, publishShout } } = useEditorContext() - const toggleWarnings = () => setVisibleWarnings(!visibleWarnings()) - const handleBellIconClick = (event: Event) => { event.preventDefault() @@ -48,15 +47,16 @@ export const HeaderAuth = (props: Props) => { showModal('auth') return } - toggleWarnings() + + showNotificationsPanel() } const isEditorPage = createMemo(() => page().route === 'edit' || page().route === 'editSettings') - const showNotifications = createMemo(() => isAuthenticated() && !isEditorPage()) - const showSaveButton = createMemo(() => isAuthenticated() && isEditorPage()) - const showCreatePostButton = createMemo(() => isAuthenticated() && !isEditorPage()) - const showAuthenticatedControls = createMemo(() => isAuthenticated()) + const isNotificationsVisible = createMemo(() => isAuthenticated() && !isEditorPage()) + const isSaveButtonVisible = createMemo(() => isAuthenticated() && isEditorPage()) + const isCreatePostButtonVisible = createMemo(() => isAuthenticated() && !isEditorPage()) + const isAuthenticatedControlsVisible = createMemo(() => isAuthenticated()) const handleBurgerButtonClick = () => { toggleEditorPanel() @@ -71,8 +71,9 @@ export const HeaderAuth = (props: Props) => { } const [width, setWidth] = createSignal(0) - const handleResize = () => setWidth(window.innerWidth) + onMount(() => { + const handleResize = () => setWidth(window.innerWidth) handleResize() window.addEventListener('resize', handleResize) onCleanup(() => window.removeEventListener('resize', handleResize)) @@ -109,7 +110,7 @@ export const HeaderAuth = (props: Props) => {
diff --git a/src/components/Nav/Notifications.tsx b/src/components/Nav/Notifications.tsx deleted file mode 100644 index 4a53736d..00000000 --- a/src/components/Nav/Notifications.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Portal } from 'solid-js/web' -import { useWarningsStore } from '../../stores/ui' -import { createMemo, For, Show } from 'solid-js' - -export default () => { - const { warnings } = useWarningsStore() - - const notSeen = createMemo(() => warnings().filter((warning) => !warning.seen)) - - return ( - 0}> - -
    - {(warning) =>
  • {warning.body}
  • }
    -
-
-
- ) -} diff --git a/src/components/NotificationsPanel/NotificationView/NotificationView.module.scss b/src/components/NotificationsPanel/NotificationView/NotificationView.module.scss new file mode 100644 index 00000000..284af187 --- /dev/null +++ b/src/components/NotificationsPanel/NotificationView/NotificationView.module.scss @@ -0,0 +1,32 @@ +.NotificationView { + display: flex; + align-items: center; + height: 72px; + margin-left: -16px; + border-radius: 16px; + padding: 16px; + background-color: var(--yellow-50); + // TODO: check markup + font-size: 15px; + // font-weight: 700; + line-height: 20px; + cursor: pointer; + transition: background-color 100ms; + + &.seen { + background-color: transparent; + } + + &:hover { + background-color: var(--gray-100); + } +} + +.userpic { + margin-right: 15px; +} + +.timeContainer { + margin-left: auto; + padding-left: 16px; +} diff --git a/src/components/NotificationsPanel/NotificationView/NotificationView.tsx b/src/components/NotificationsPanel/NotificationView/NotificationView.tsx new file mode 100644 index 00000000..397572fb --- /dev/null +++ b/src/components/NotificationsPanel/NotificationView/NotificationView.tsx @@ -0,0 +1,128 @@ +import { clsx } from 'clsx' +import styles from './NotificationView.module.scss' +import type { Notification } from '../../../graphql/types.gen' +import { formatDate } from '../../../utils' +import { createMemo, createSignal, onMount, Show } from 'solid-js' +import { NotificationType } from '../../../graphql/types.gen' +import { openPage } from '@nanostores/router' +import { router } from '../../../stores/router' +import { useNotifications } from '../../../context/notifications' +import { Userpic } from '../../Author/Userpic' +import { useLocalize } from '../../../context/localize' +import notifications from '../../../graphql/query/notifications' + +type Props = { + notification: Notification + onClick: () => void + class?: string +} + +type NotificationData = { + shout: { + slug: string + title: string + } + users: { + id: number + name: string + slug: string + userpic: string + }[] +} + +export const NotificationView = (props: Props) => { + const { + actions: { markNotificationAsRead } + } = useNotifications() + + const { t } = useLocalize() + + const [data, setData] = createSignal(null) + + onMount(() => { + setTimeout(() => setData(JSON.parse(props.notification.data))) + }) + + const lastUser = createMemo(() => { + if (!data()) { + return null + } + + return data().users[data().users.length - 1] + }) + + const content = createMemo(() => { + if (!data()) { + return null + } + + let shoutTitle = '' + let i = 0 + const shoutTitleWords = data().shout.title.split(' ') + + while (shoutTitle.length <= 30 && i < shoutTitleWords.length) { + shoutTitle += shoutTitleWords[i] + ' ' + i++ + } + + if (shoutTitle.length < data().shout.title.length) { + shoutTitle += '...' + } + + switch (props.notification.type) { + case NotificationType.NewComment: { + return t('NewCommentNotificationText', { + commentsCount: props.notification.occurrences, + shoutTitle, + lastCommenterName: lastUser().name, + restUsersCount: data().users.length - 1 + }) + } + case NotificationType.NewReply: { + return t('NewReplyNotificationText', { + commentsCount: props.notification.occurrences, + shoutTitle, + lastCommenterName: lastUser().name, + restUsersCount: data().users.length - 1 + }) + } + } + }) + + const handleClick = () => { + if (!props.notification.seen) { + markNotificationAsRead(props.notification) + } + + openPage(router, 'article', { slug: data().shout.slug }) + props.onClick() + + // switch (props.notification.type) { + // case NotificationType.NewComment: { + // openPage(router, 'article', { slug: data().shout.slug }) + // break + // } + // case NotificationType.NewReply: { + // openPage(router, 'article', { slug: data().shout.slug }) + // break + // } + // } + } + + return ( + +
+ +
{content()}
+
+ {/*{formatDate(new Date(props.notification.createdAt), { month: 'numeric' })}*/} +
+
+
+ ) +} diff --git a/src/components/NotificationsPanel/NotificationView/index.ts b/src/components/NotificationsPanel/NotificationView/index.ts new file mode 100644 index 00000000..59dcafc6 --- /dev/null +++ b/src/components/NotificationsPanel/NotificationView/index.ts @@ -0,0 +1 @@ +export { NotificationView } from './NotificationView' diff --git a/src/components/NotificationsPanel/NotificationsPanel.module.scss b/src/components/NotificationsPanel/NotificationsPanel.module.scss new file mode 100644 index 00000000..a1b18dd0 --- /dev/null +++ b/src/components/NotificationsPanel/NotificationsPanel.module.scss @@ -0,0 +1,66 @@ +$transition-duration: 200ms; + +.container { + display: flex; + align-items: stretch; + justify-content: flex-end; + position: fixed; + top: 0; + right: 0; + bottom: 0; + width: 0; + z-index: 10000; + background-color: rgb(0 0 0 / 0%); + overflow: hidden; + transition: + background-color $transition-duration, + width 0ms linear $transition-duration; + + .panel { + position: relative; + background-color: #fff; + width: 700px; + padding: 48px 96px 96px 48px; + transform: translateX(100%); + transition: transform $transition-duration; + overflow-y: auto; + } + + &.isOpened { + width: 100%; + background-color: rgb(0 0 0 / 60%); + transition: + background-color $transition-duration, + width 0ms; + + .panel { + transform: translateX(0); + } + } +} + +.title { + // TODO: check markup + color: var(--black-500, #141414); + font-size: 32px; + font-style: normal; + font-weight: 700; + line-height: 36px; + margin-bottom: 32px; +} + +.closeButton { + position: absolute; + top: 0; + right: 0; + padding: 20px; + cursor: pointer; +} + +.notificationView + .notificationView { + margin-top: 8px; +} + +.emptyMessageContainer { + text-align: center; +} diff --git a/src/components/NotificationsPanel/NotificationsPanel.tsx b/src/components/NotificationsPanel/NotificationsPanel.tsx new file mode 100644 index 00000000..ddfc66b2 --- /dev/null +++ b/src/components/NotificationsPanel/NotificationsPanel.tsx @@ -0,0 +1,70 @@ +import { clsx } from 'clsx' +import styles from './NotificationsPanel.module.scss' +import { useEscKeyDownHandler } from '../../utils/useEscKeyDownHandler' +import { useOutsideClickHandler } from '../../utils/useOutsideClickHandler' +import { useLocalize } from '../../context/localize' +import { Icon } from '../_shared/Icon' +import { createEffect, For, onCleanup, onMount } from 'solid-js' +import { useNotifications } from '../../context/notifications' +import { NotificationView } from './NotificationView' + +type Props = { + isOpen: boolean + onClose: () => void +} + +export const NotificationsPanel = (props: Props) => { + const { t } = useLocalize() + const { sortedNotifications } = useNotifications() + const handleHide = () => { + props.onClose() + } + + const panelRef: { current: HTMLDivElement } = { + current: null + } + + useOutsideClickHandler({ + containerRef: panelRef, + predicate: () => props.isOpen, + handler: () => handleHide() + }) + + createEffect(() => { + document.body.classList.toggle('fixed', props.isOpen) + }) + + useEscKeyDownHandler(handleHide) + + const handleNotificationViewClick = () => { + handleHide() + } + + return ( +
+
(panelRef.current = el)} class={styles.panel}> +
+ {/*TODO: check markup (hover)*/} + +
+
{t('Notifications')}
+ {t('No notifications, yet')}
} + > + {(notification) => ( + + )} + +
+
+ ) +} diff --git a/src/components/NotificationsPanel/index.ts b/src/components/NotificationsPanel/index.ts new file mode 100644 index 00000000..5d134561 --- /dev/null +++ b/src/components/NotificationsPanel/index.ts @@ -0,0 +1 @@ +export { NotificationsPanel } from './NotificationsPanel' diff --git a/src/components/Views/Author/Author.tsx b/src/components/Views/Author/Author.tsx index 4c4399af..027d260d 100644 --- a/src/components/Views/Author/Author.tsx +++ b/src/components/Views/Author/Author.tsx @@ -34,7 +34,7 @@ export const AuthorView = (props: Props) => { const { sortedArticles } = useArticlesStore({ shouts: props.shouts }) const { authorEntities } = useAuthorsStore({ authors: [props.author] }) - const { page } = useRouter() + const { page: getPage } = useRouter() const { user } = useSession() const author = createMemo(() => authorEntities()[props.authorSlug]) const [isLoadMoreButtonVisible, setIsLoadMoreButtonVisible] = createSignal(false) @@ -104,14 +104,14 @@ export const AuthorView = (props: Props) => { // return t('Top recent') // }) - const shouts = createMemo(() => + const pages = createMemo(() => splitToPages(sortedArticles(), PRERENDERED_ARTICLES_COUNT, LOAD_MORE_PAGE_SIZE) ) const [commented, setCommented] = createSignal([]) createEffect(async () => { - if (page().route === 'authorComments') { + if (getPage().route === 'authorComments') { try { const data = await apiClient.getReactionsBy({ by: { comment: true, createdBy: props.authorSlug } @@ -140,17 +140,17 @@ export const AuthorView = (props: Props) => {
- +
@@ -194,7 +194,7 @@ export const AuthorView = (props: Props) => {
- +
@@ -207,7 +207,7 @@ export const AuthorView = (props: Props) => {
- + @@ -228,15 +228,15 @@ export const AuthorView = (props: Props) => { - - {(shout) => ( + + {(page) => ( <> - - - - - - + + + + + + )} diff --git a/src/components/_shared/PageLayout.tsx b/src/components/_shared/PageLayout.tsx index be4e29f6..cc28b618 100644 --- a/src/components/_shared/PageLayout.tsx +++ b/src/components/_shared/PageLayout.tsx @@ -31,7 +31,7 @@ export const PageLayout = (props: Props) => { props.scrollToComments(scrollToComments()) } }) - // const { randomTopics } = useTopicsStore() + return ( <> diff --git a/src/context/notifications.tsx b/src/context/notifications.tsx new file mode 100644 index 00000000..06802100 --- /dev/null +++ b/src/context/notifications.tsx @@ -0,0 +1,106 @@ +import type { Accessor, JSX } from 'solid-js' +import { createContext, createEffect, createMemo, createSignal, useContext } from 'solid-js' +import { useSession } from './session' +import SSEService, { EventData } from '../utils/sseService' +import { apiBaseUrl } from '../utils/config' +import { Portal } from 'solid-js/web' +import { ShowIfAuthenticated } from '../components/_shared/ShowIfAuthenticated' +import { NotificationsPanel } from '../components/NotificationsPanel' +import { apiClient } from '../utils/apiClient' +import { createStore } from 'solid-js/store' +import { Notification } from '../graphql/types.gen' + +type NotificationsContextType = { + notificationEntities: Record + unreadNotificationsCount: Accessor + sortedNotifications: Accessor + actions: { + showNotificationsPanel: () => void + markNotificationAsRead: (notification: Notification) => Promise + } +} + +const NotificationsContext = createContext() + +export function useNotifications() { + return useContext(NotificationsContext) +} + +const sseService = new SSEService() + +export const NotificationsProvider = (props: { children: JSX.Element }) => { + const [isNotificationsPanelOpen, setIsNotificationsPanelOpen] = createSignal(false) + const [unreadNotificationsCount, setUnreadNotificationsCount] = createSignal(0) + const { isAuthenticated, user } = useSession() + const [notificationEntities, setNotificationEntities] = createStore>({}) + + const loadNotifications = async () => { + const { notifications, totalUnreadCount } = await apiClient.getNotifications({ + limit: 100 + }) + const newNotificationEntities = notifications.reduce((acc, notification) => { + acc[notification.id] = notification + return acc + }, {}) + + setUnreadNotificationsCount(totalUnreadCount) + setNotificationEntities(newNotificationEntities) + return notifications + } + + const sortedNotifications = createMemo(() => { + return Object.values(notificationEntities).sort( + (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime() + ) + }) + + createEffect(() => { + if (isAuthenticated()) { + loadNotifications() + + sseService.connect(`${apiBaseUrl}/subscribe/${user().id}`) + sseService.subscribeToEvent('message', (data: EventData) => { + if (data.type === 'newNotifications') { + loadNotifications() + } else { + console.error(`[NotificationsProvider] unknown message type: ${JSON.stringify(data)}`) + } + }) + } else { + sseService.disconnect() + } + }) + + const markNotificationAsRead = async (notification: Notification) => { + await apiClient.markNotificationAsRead(notification.id) + loadNotifications() + } + + const showNotificationsPanel = () => { + setIsNotificationsPanelOpen(true) + } + + const actions = { showNotificationsPanel, markNotificationAsRead } + + const value: NotificationsContextType = { + notificationEntities, + sortedNotifications, + unreadNotificationsCount, + actions + } + + const handleNotificationPanelClose = () => { + setIsNotificationsPanelOpen(false) + } + + return ( + + {props.children} + + + + + + + ) +} diff --git a/src/graphql/mutation/auth-logout.ts b/src/graphql/mutation/auth-logout.ts index be6ea2a1..8ffa91c9 100644 --- a/src/graphql/mutation/auth-logout.ts +++ b/src/graphql/mutation/auth-logout.ts @@ -1,7 +1,5 @@ import { gql } from '@urql/core' -// WARNING: need Auth header - export default gql` query SignOutQuery { signOut { diff --git a/src/graphql/mutation/mark-notification-as-read.ts b/src/graphql/mutation/mark-notification-as-read.ts new file mode 100644 index 00000000..8b7b1e53 --- /dev/null +++ b/src/graphql/mutation/mark-notification-as-read.ts @@ -0,0 +1,9 @@ +import { gql } from '@urql/core' + +export default gql` + mutation MarkNotificationAsReadMutation($notificationId: Int!) { + markNotificationAsRead(notification_id: $notificationId) { + error + } + } +` diff --git a/src/graphql/mutation/unfollow.ts b/src/graphql/mutation/unfollow.ts index 9b2d8198..763b49d7 100644 --- a/src/graphql/mutation/unfollow.ts +++ b/src/graphql/mutation/unfollow.ts @@ -1,5 +1,4 @@ import { gql } from '@urql/core' - export default gql` mutation UnfollowMutation($what: FollowingEntity!, $slug: String!) { unfollow(what: $what, slug: $slug) { diff --git a/src/graphql/mutation/update-profile.ts b/src/graphql/mutation/update-profile.ts index ca6c12ea..25de9830 100644 --- a/src/graphql/mutation/update-profile.ts +++ b/src/graphql/mutation/update-profile.ts @@ -1,5 +1,4 @@ import { gql } from '@urql/core' -// WARNING: need Auth header export default gql` mutation ProfileUpdateMutation($profile: ProfileInput!) { diff --git a/src/graphql/query/auth-login.ts b/src/graphql/query/auth-login.ts index 7dcafc83..ee233d0c 100644 --- a/src/graphql/query/auth-login.ts +++ b/src/graphql/query/auth-login.ts @@ -6,6 +6,7 @@ export default gql` error token user { + id name slug userpic diff --git a/src/graphql/query/author-reacted-shouts.ts b/src/graphql/query/author-reacted-shouts.ts index 780e9c3a..1ab9e2ad 100644 --- a/src/graphql/query/author-reacted-shouts.ts +++ b/src/graphql/query/author-reacted-shouts.ts @@ -1,7 +1,5 @@ import { gql } from '@urql/core' -// WARNING: need Auth header - export default gql` query ShoutsReactedByUserQuery($slug: String!, $limit: Int!, $offset: Int!) { userReactedShouts(slug: String!, page: Int!, size: Int!) { diff --git a/src/graphql/query/notifications.ts b/src/graphql/query/notifications.ts new file mode 100644 index 00000000..a1951b0f --- /dev/null +++ b/src/graphql/query/notifications.ts @@ -0,0 +1,20 @@ +import { gql } from '@urql/core' + +export default gql` + query LoadNotificationsQuery { + loadNotifications(params: { limit: 10, offset: 0 }) { + notifications { + id + shout + reaction + type + createdAt + seen + data + occurrences + } + totalCount + totalUnreadCount + } + } +` diff --git a/src/graphql/subs/new-message.ts b/src/graphql/subs/new-message.ts deleted file mode 100644 index bb941a5f..00000000 --- a/src/graphql/subs/new-message.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { gql } from '@urql/core' - -export default gql` - subscription { - newMessage { - id - chatId - author - body - replyTo - createdAt - updatedAt - } - } -` diff --git a/src/graphql/subs/new-reaction.ts b/src/graphql/subs/new-reaction.ts deleted file mode 100644 index 8ffd4cf8..00000000 --- a/src/graphql/subs/new-reaction.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { gql } from '@urql/core' - -export default gql` - subscription { - newReactions { - id - body - kind - range - createdAt - replyTo - stat { - rating - } - shout { - id - slug - } - createdBy { - name - slug - userpic - } - } - } -` diff --git a/src/graphql/subs/new-shout.ts b/src/graphql/subs/new-shout.ts deleted file mode 100644 index 8172fd63..00000000 --- a/src/graphql/subs/new-shout.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { gql } from '@urql/core' - -export default gql` - subscription { - newShout { - id - slug - title - subtitle - body - topics { - # id - title - slug - } - authors { - id - name - slug - userpic - caption - } - } - } -` diff --git a/src/main.astro b/src/main.astro deleted file mode 100644 index 05fc5dc3..00000000 --- a/src/main.astro +++ /dev/null @@ -1,33 +0,0 @@ ---- -import './styles/app.scss' -import { Seo } from "astro-seo-meta" - -const ln = Astro.url.searchParams.get('lng') || 'ru' -const { protocol, host } = Astro.url -const title = ln === 'ru' ? 'Дискурс' : 'Discours' -const imageUrl = Astro.props.imageUrl ?? `${protocol}${host}/public/bonfire.png` -const description = ln === 'ru' ? 'Горизонтальная платформа коллаборативной журналистики' : 'Horizontal collaborative journalistic platform' ---- - - - - - - - - - - - - diff --git a/src/pages/topic/[slug].astro b/src/pages/topic/[slug].astro deleted file mode 100644 index 35795a0e..00000000 --- a/src/pages/topic/[slug].astro +++ /dev/null @@ -1,21 +0,0 @@ ---- -import { Root } from '../../components/Root' -import Prerendered from '../../main.astro' -import { apiClient } from '../../utils/apiClient' -import { PRERENDERED_ARTICLES_COUNT } from '../../components/Views/Topic' - -const slug = Astro.params.slug?.toString() || '' -const shouts = await apiClient.getShouts({ filters: { topic: slug }, limit: PRERENDERED_ARTICLES_COUNT }) -const topic = await apiClient.getTopic({ slug }) - -import { initRouter } from '../../stores/router' - -const { pathname, search } = Astro.url -initRouter(pathname, search) - -Astro.response.headers.set('Cache-Control', 's-maxage=1, stale-while-revalidate') ---- - - - - diff --git a/src/stores/ui.ts b/src/stores/ui.ts index 4bcdba76..b9600651 100644 --- a/src/stores/ui.ts +++ b/src/stores/ui.ts @@ -23,14 +23,6 @@ export type ModalType = | 'followers' | 'following' -type WarnKind = 'error' | 'warn' | 'info' - -export interface Warning { - body: string - kind: WarnKind - seen?: boolean -} - export const MODALS: Record = { auth: 'auth', subscribe: 'subscribe', @@ -50,8 +42,6 @@ export const MODALS: Record = { const [modal, setModal] = createSignal(null) -const [warnings, setWarnings] = createSignal([]) - const { searchParams, changeSearchParam } = useRouter< AuthModalSearchParams & ConfirmEmailSearchParams & RootSearchParams >() @@ -85,15 +75,6 @@ export const hideModal = () => { setModal(null) } -export const clearWarns = () => setWarnings([]) -export const warn = (warning: Warning) => setWarnings([...warnings(), warning]) - -export const useWarningsStore = () => { - return { - warnings - } -} - export const useModalStore = () => { return { modal diff --git a/src/styles/app.scss b/src/styles/app.scss index 5d215dd8..d2731f41 100644 --- a/src/styles/app.scss +++ b/src/styles/app.scss @@ -36,6 +36,8 @@ --black-400: #696969; --white-500: #fff; --blue-500: #2638d9; + --yellow-50: #fffbeb; + --gray-100: #f3f4f6; } [data-editor-dark-mode='true'] { diff --git a/src/utils/apiClient.ts b/src/utils/apiClient.ts index fef9e7e5..431c5a84 100644 --- a/src/utils/apiClient.ts +++ b/src/utils/apiClient.ts @@ -15,7 +15,9 @@ import type { ReactionInput, Chat, ReactionBy, - Shout + Shout, + NotificationsQueryParams, + NotificationsQueryResult } from '../graphql/types.gen' import { publicGraphQLClient } from '../graphql/publicGraphQLClient' import { getToken, privateGraphQLClient } from '../graphql/privateGraphQLClient' @@ -54,6 +56,8 @@ import createMessage from '../graphql/mutation/create-chat-message' import updateProfile from '../graphql/mutation/update-profile' import updateArticle from '../graphql/mutation/article-update' import deleteShout from '../graphql/mutation/article-delete' +import notifications from '../graphql/query/notifications' +import markNotificationAsRead from '../graphql/mutation/mark-notification-as-read' type ApiErrorCode = | 'unknown' @@ -349,6 +353,18 @@ export const apiClient = { // console.debug(resp) return resp.data.loadReactionsBy }, + getNotifications: async (params: NotificationsQueryParams): Promise => { + const resp = await privateGraphQLClient.query(notifications, params).toPromise() + console.debug(resp.data) + return resp.data.loadNotifications + }, + markNotificationAsRead: async (notificationId: number): Promise => { + await privateGraphQLClient + .mutation(markNotificationAsRead, { + notificationId + }) + .toPromise() + }, // inbox getChats: async (options: QueryLoadChatsArgs): Promise => { diff --git a/src/utils/pageLoadManager.ts b/src/utils/pageLoadManager.ts index d04a3d3d..a25ff347 100644 --- a/src/utils/pageLoadManager.ts +++ b/src/utils/pageLoadManager.ts @@ -5,7 +5,6 @@ const pageLoadManager: { export const getPageLoadManagerPromise = () => { return pageLoadManager.promise } - export const setPageLoadManagerPromise = (promise: Promise) => { pageLoadManager.promise = promise } diff --git a/src/utils/sseService.ts b/src/utils/sseService.ts new file mode 100644 index 00000000..20121c35 --- /dev/null +++ b/src/utils/sseService.ts @@ -0,0 +1,33 @@ +export type EventData = { + type: string +} + +class SSEService { + private eventSource: EventSource | null + + constructor() { + this.eventSource = null + } + + public connect(url: string): void { + this.eventSource = new EventSource(url) + } + + public disconnect(): void { + if (this.eventSource) { + this.eventSource.close() + this.eventSource = null + } + } + + public subscribeToEvent(eventName: string, callback: (eventData: EventData) => void): void { + if (this.eventSource) { + this.eventSource.addEventListener(eventName, (event: MessageEvent) => { + const data = JSON.parse(event.data) + callback(data) + }) + } + } +} + +export default SSEService