Merge branch 'dev' into feature/rating

This commit is contained in:
Untone 2024-05-02 17:05:31 +03:00
commit 571e475445
36 changed files with 385 additions and 332 deletions

View File

@ -1,3 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.25 4.125C7.14583 4.125 6.13281 4.6901 5.60937 5.60156C5.40365 5.95573 5.16406 6.53385 5.03125 6.91927C4.91146 7.2474 3.07813 11.349 1.95313 13.8568L1.95833 13.8594C1.66667 14.4349 1.5 15.0755 1.5 15.75C1.5 18.2318 3.6875 20.25 6.375 20.25C9.0625 20.25 11.25 18.2318 11.25 15.75V14.3724C11.4505 14.3099 11.7109 14.25 12 14.25C12.2891 14.25 12.5495 14.3099 12.75 14.3724V15.75C12.75 18.2318 14.9375 20.25 17.625 20.25C20.3125 20.25 22.5 18.2318 22.5 15.75C22.5 15.0755 22.3333 14.4349 22.0417 13.8594L22.0469 13.8568C20.9219 11.349 19.0885 7.2474 18.9688 6.92448C18.8359 6.53646 18.5964 5.95833 18.3906 5.60417C17.8672 4.6901 16.8542 4.125 15.75 4.125C14.1354 4.125 12.8177 5.32813 12.7552 6.82813C12.526 6.78125 12.2734 6.75 12 6.75C11.7266 6.75 11.474 6.78125 11.2448 6.82813C11.1823 5.32813 9.86458 4.125 8.25 4.125ZM8.25 5.625C9.07813 5.625 9.75 6.21354 9.75 6.9375V12.5104C8.8724 11.7318 7.6849 11.25 6.375 11.25C5.75781 11.25 5.16927 11.362 4.625 11.5547C5.48177 9.64063 6.36458 7.65365 6.45052 7.40885C6.57292 7.04688 6.77604 6.58333 6.90885 6.35156C7.16667 5.90365 7.67969 5.625 8.25 5.625ZM15.75 5.625C16.3203 5.625 16.8333 5.90365 17.0911 6.35156C17.224 6.58333 17.4271 7.04948 17.5495 7.40885C17.6354 7.65365 18.5182 9.64063 19.3724 11.5547C18.8307 11.362 18.2422 11.25 17.625 11.25C16.3151 11.25 15.1276 11.7318 14.25 12.5104V6.9375C14.25 6.21354 14.9219 5.625 15.75 5.625ZM12 8.25C12.2891 8.25 12.5495 8.3099 12.75 8.3724V9.82552C12.5208 9.78125 12.2708 9.75 12 9.75C11.7292 9.75 11.4792 9.78125 11.25 9.82552V8.3724C11.4505 8.3099 11.7109 8.25 12 8.25ZM12 11.25C12.2891 11.25 12.5495 11.3099 12.75 11.3724V12.8255C12.5208 12.7812 12.2708 12.75 12 12.75C11.7292 12.75 11.4792 12.7812 11.25 12.8255V11.3724C11.4505 11.3099 11.7109 11.25 12 11.25ZM6.375 12.75C8.23698 12.75 9.75 14.0964 9.75 15.75C9.75 17.4036 8.23698 18.75 6.375 18.75C4.51302 18.75 3 17.4036 3 15.75C3 14.0964 4.51302 12.75 6.375 12.75ZM17.625 12.75C19.487 12.75 21 14.0964 21 15.75C21 17.4036 19.487 18.75 17.625 18.75C15.763 18.75 14.25 17.4036 14.25 15.75C14.25 14.0964 15.763 12.75 17.625 12.75Z" fill="#141414"/>
<path d="M8.625 4.5C7.59115 4.5 6.75 5.34115 6.75 6.375V8.25H5.625C4.59115 8.25 3.75 9.09115 3.75 10.125V17.25C3.75 18.4896 4.76042 19.5 6 19.5H18C19.2396 19.5 20.25 18.4896 20.25 17.25V6.375C20.25 5.34115 19.4089 4.5 18.375 4.5H8.625ZM8.625 6H18.375C18.5807 6 18.75 6.16927 18.75 6.375V17.25C18.75 17.6641 18.4141 18 18 18H8.1224C8.20313 17.7656 8.25 17.513 8.25 17.25V6.375C8.25 6.16927 8.41927 6 8.625 6ZM10.125 7.5C9.71094 7.5 9.375 7.83594 9.375 8.25C9.375 8.66406 9.71094 9 10.125 9H16.875C17.2891 9 17.625 8.66406 17.625 8.25C17.625 7.83594 17.2891 7.5 16.875 7.5H10.125ZM5.625 9.75H6.75V17.25C6.75 17.6641 6.41406 18 6 18C5.58594 18 5.25 17.6641 5.25 17.25V10.125C5.25 9.91927 5.41927 9.75 5.625 9.75ZM10.125 10.125C9.71094 10.125 9.375 10.4609 9.375 10.875C9.375 11.2891 9.71094 11.625 10.125 11.625H16.875C17.2891 11.625 17.625 11.2891 17.625 10.875C17.625 10.4609 17.2891 10.125 16.875 10.125H10.125ZM10.125 12.75C9.71094 12.75 9.375 13.0859 9.375 13.5V16.125C9.375 16.5391 9.71094 16.875 10.125 16.875H12.375C12.7891 16.875 13.125 16.5391 13.125 16.125V13.5C13.125 13.0859 12.7891 12.75 12.375 12.75H10.125ZM15 12.75C14.5859 12.75 14.25 13.0859 14.25 13.5C14.25 13.9141 14.5859 14.25 15 14.25H16.875C17.2891 14.25 17.625 13.9141 17.625 13.5C17.625 13.0859 17.2891 12.75 16.875 12.75H15ZM15 15.375C14.5859 15.375 14.25 15.7109 14.25 16.125C14.25 16.5391 14.5859 16.875 15 16.875H16.875C17.2891 16.875 17.625 16.5391 17.625 16.125C17.625 15.7109 17.2891 15.375 16.875 15.375H15Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@ -0,0 +1,3 @@
<svg width="18" height="10" viewBox="0 0 18 10" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M17.1042 9.90633C16.9063 9.90633 16.7136 9.82821 16.5626 9.67716L8.98965 1.91675L1.43236 9.66154C1.1459 9.95841 0.671944 9.96362 0.375069 9.67716C0.0781948 9.3855 0.0729868 8.91154 0.359444 8.61467L8.45319 0.322998C8.73965 0.0313314 9.24486 0.0313314 9.53132 0.322998L17.6407 8.63029C17.9272 8.92716 17.9219 9.40112 17.6251 9.69279C17.4792 9.83342 17.2917 9.90633 17.1042 9.90633Z" fill="#9FA1A7"/>
</svg>

After

Width:  |  Height:  |  Size: 511 B

View File

@ -529,5 +529,7 @@
"yesterday": "yesterday",
"Failed to delete comment": "Failed to delete comment",
"It's OK. Just enter your email to receive a link to change your password": "It's OK. Just enter your email to receive a link to change your password",
"Restore password": "Restore password"
"Restore password": "Restore password",
"Subscribing...": "Subscribing...",
"Unsubscribing...": "Unsubscribing..."
}

View File

@ -31,7 +31,7 @@
"All posts rating": "Рейтинг всех постов",
"All posts": "Все публикации",
"All topics": "Все темы",
"All": "Все",
"All": "Общая лента",
"Almost done! Check your email.": "Почти готово! Осталось подтвердить вашу почту.",
"Are you sure you want to delete this comment?": "Уверены, что хотите удалить этот комментарий?",
"Are you sure you want to delete this draft?": "Уверены, что хотите удалить этот черновик?",
@ -156,7 +156,7 @@
"FAQ": "Советы и предложения",
"Favorite topics": "Избранные темы",
"Favorite": "Избранное",
"Feed settings": "Настройки ленты",
"Feed settings": "Настроить ленту",
"Feed": "Лента",
"Feedback": "Обратная связь",
"Fill email": "Введите почту",
@ -556,5 +556,7 @@
"yesterday": "вчера",
"Failed to delete comment": "Не удалось удалить комментарий",
"It's OK. Just enter your email to receive a link to change your password": "Ничего страшного. Просто укажите свою почту, чтобы получить ссылку для смены пароля",
"Restore password": "Восстановить пароль"
"Restore password": "Восстановить пароль",
"Subscribing...": "Подписываем...",
"Unsubscribing...": "Отписываем..."
}

View File

@ -40,6 +40,7 @@ import { InboxPage } from '../pages/inbox.page'
import { HomePage } from '../pages/index.page'
import { ProfileSecurityPage } from '../pages/profile/profileSecurity.page'
import { ProfileSettingsPage } from '../pages/profile/profileSettings.page'
//TODO: ProfileSubscriptionsPage - garbage code?
import { ProfileSubscriptionsPage } from '../pages/profile/profileSubscriptions.page'
import { SearchPage } from '../pages/search.page'
import { TopicPage } from '../pages/topic.page'

View File

@ -22,6 +22,7 @@ img {
.articleContent {
img:not([data-disable-lightbox='true']) {
cursor: zoom-in;
width: 100%;
}
}

View File

@ -179,6 +179,10 @@
@include font-size(1.2rem);
}
.commentAuthor {
margin-right: 2rem;
}
.articleAuthor {
@include font-size(1.2rem);

View File

@ -3,14 +3,11 @@
color: var(--secondary-color);
display: flex;
align-items: flex-start;
justify-content: flex-start;
justify-content: center;
flex-direction: column;
gap: .5rem;
flex: 1;
flex-wrap: wrap;
font-size: 1.2rem;
margin-bottom: .5rem;
.date {
font-weight: 500;

View File

@ -60,7 +60,7 @@ export type ArticlePageSearchParams = {
const scrollTo = (el: HTMLElement) => {
const { top } = el.getBoundingClientRect()
window.scrollTo({
top: top - DEFAULT_HEADER_OFFSET,
top: top + window.scrollY - DEFAULT_HEADER_OFFSET,
left: 0,
behavior: 'smooth',
})
@ -152,19 +152,6 @@ export const FullArticle = (props: Props) => {
current: HTMLDivElement
} = { current: null }
createEffect(() => {
if (props.scrollToComments) {
scrollTo(commentsRef.current)
}
})
createEffect(() => {
if (searchParams()?.scrollTo === 'comments' && commentsRef.current) {
requestAnimationFrame(() => scrollTo(commentsRef.current))
changeSearchParams({ scrollTo: null })
}
})
createEffect(() => {
if (searchParams().commentId && isReactionsLoaded()) {
const commentElement = document.querySelector<HTMLElement>(
@ -318,6 +305,19 @@ export const FullArticle = (props: Props) => {
install('G-LQ4B87H8C2')
window?.addEventListener('resize', updateIframeSizes)
onCleanup(() => window.removeEventListener('resize', updateIframeSizes))
createEffect(() => {
if (props.scrollToComments) {
scrollTo(commentsRef.current)
}
})
createEffect(() => {
if (searchParams()?.scrollTo === 'comments' && commentsRef.current) {
requestAnimationFrame(() => scrollTo(commentsRef.current))
changeSearchParams({ scrollTo: null })
}
})
})
createEffect(
@ -341,7 +341,7 @@ export const FullArticle = (props: Props) => {
width: 1200,
})
const description = getDescription(props.article.description || body())
const description = getDescription(props.article.description || body() || media()[0]?.body)
const ogTitle = props.article.title
const keywords = getKeywords(props.article)
const shareUrl = getShareUrl({ pathname: `/${props.article.slug}` })

View File

@ -115,8 +115,4 @@
}
}
}
.actionButtonLabelHovered {
display: none;
}
}

View File

@ -10,14 +10,12 @@ import { Author, FollowingEntity } from '../../../graphql/schema/core.gen'
import { router, useRouter } from '../../../stores/router'
import { translit } from '../../../utils/ru2en'
import { isCyrillic } from '../../../utils/translate'
import { BadgeSubscribeButton } from '../../_shared/BadgeSubscribeButton'
import { Button } from '../../_shared/Button'
import { CheckButton } from '../../_shared/CheckButton'
import { ConditionalWrapper } from '../../_shared/ConditionalWrapper'
import { Icon } from '../../_shared/Icon'
import { Userpic } from '../Userpic'
import { FollowedInfo } from '../../../pages/types'
import stylesButton from '../../_shared/Button/Button.module.scss'
import styles from './AuthorBadge.module.scss'
type Props = {
@ -29,13 +27,19 @@ type Props = {
inviteView?: boolean
onInvite?: (id: number) => void
selected?: boolean
isFollowed?: FollowedInfo
}
export const AuthorBadge = (props: Props) => {
const { mediaMatches } = useMediaQuery()
const { author, requireAuthentication } = useSession()
const { follow, unfollow, subscriptions, subscribeInAction } = useFollowing()
const [isMobileView, setIsMobileView] = createSignal(false)
const [isFollowed, setIsFollowed] = createSignal<boolean>()
const [isSubscribed, setIsSubscribed] = createSignal<boolean>()
createEffect(() => {
if (!subscriptions || !props.author) return
const subscribed = subscriptions.authors?.some((authorEntity) => authorEntity.id === props.author?.id)
setIsSubscribed(subscribed)
})
createEffect(() => {
setIsMobileView(!mediaMatches.sm)
@ -76,10 +80,10 @@ export const AuthorBadge = (props: Props) => {
)
const handleFollowClick = () => {
const value = !isFollowed()
requireAuthentication(() => {
setIsFollowed(value)
setFollowing(FollowingEntity.Author, props.author.slug, value)
isSubscribed()
? unfollow(FollowingEntity.Author, props.author.slug)
: follow(FollowingEntity.Author, props.author.slug)
}, 'subscribe')
}
@ -133,55 +137,13 @@ export const AuthorBadge = (props: Props) => {
</div>
<Show when={props.author.slug !== author()?.slug && !props.nameOnly}>
<div class={styles.actions}>
<Show
when={!props.minimizeSubscribeButton}
fallback={<CheckButton text={t('Follow')} checked={isFollowed()} onClick={handleFollowClick} />}
>
<Show
when={isFollowed()}
fallback={
<Button
variant={props.iconButtons ? 'secondary' : 'bordered'}
size="S"
value={
<Show when={props.iconButtons} fallback={t('Subscribe')}>
<Icon name="author-subscribe" class={stylesButton.icon} />
</Show>
<BadgeSubscribeButton
action={() => handleFollowClick()}
isSubscribed={isSubscribed()}
actionMessageType={
subscribeInAction()?.slug === props.author.slug ? subscribeInAction().type : undefined
}
onClick={handleFollowClick}
isSubscribeButton={true}
class={clsx(styles.actionButton, {
[styles.iconed]: props.iconButtons,
[stylesButton.subscribed]: isFollowed(),
})}
/>
}
>
<Button
variant={props.iconButtons ? 'secondary' : 'bordered'}
size="S"
value={
<Show
when={props.iconButtons}
fallback={
<>
<span class={styles.actionButtonLabel}>{t('Following')}</span>
<span class={styles.actionButtonLabelHovered}>{t('Unfollow')}</span>
</>
}
>
<Icon name="author-unsubscribe" class={stylesButton.icon} />
</Show>
}
onClick={handleFollowClick}
isSubscribeButton={true}
class={clsx(styles.actionButton, {
[styles.iconed]: props.iconButtons,
[stylesButton.subscribed]: isFollowed(),
})}
/>
</Show>
</Show>
<Show when={props.showMessageButton}>
<Button
variant={props.iconButtons ? 'secondary' : 'bordered'}

View File

@ -34,16 +34,18 @@ export const AuthorCard = (props: Props) => {
const { author, isSessionLoaded, requireAuthentication } = useSession()
const [authorSubs, setAuthorSubs] = createSignal<Array<Author | Topic | Community>>([])
const [subscriptionFilter, setSubscriptionFilter] = createSignal<SubscriptionFilter>('all')
const [isFollowed, setIsFollowed] = createSignal<boolean>()
const [isSubscribed, setIsSubscribed] = createSignal<boolean>()
const isProfileOwner = createMemo(() => author()?.slug === props.author.slug)
const { setFollowing, isOwnerSubscribed } = useFollowing()
const { follow, unfollow, subscriptions, subscribeInAction } = useFollowing()
onMount(() => {
setAuthorSubs(props.following)
})
createEffect(() => {
setIsFollowed(isOwnerSubscribed(props.author?.id))
if (!subscriptions || !props.author) return
const subscribed = subscriptions.authors?.some((authorEntity) => authorEntity.id === props.author?.id)
setIsSubscribed(subscribed)
})
const name = createMemo(() => {
@ -83,15 +85,19 @@ export const AuthorCard = (props: Props) => {
})
const handleFollowClick = () => {
const value = !isFollowed()
requireAuthentication(() => {
setIsFollowed(value)
setFollowing(FollowingEntity.Author, props.author.slug, value)
isSubscribed()
? unfollow(FollowingEntity.Author, props.author.slug)
: follow(FollowingEntity.Author, props.author.slug)
}, 'subscribe')
}
const followButtonText = createMemo(() => {
if (isOwnerSubscribed(props.author?.id)) {
if (subscribeInAction()?.slug === props.author.slug) {
return subscribeInAction().type === 'subscribe' ? t('Subscribing...') : t('Unsubscribing...')
}
if (isSubscribed()) {
return (
<>
<span class={stylesButton.buttonSubscribeLabel}>{t('Following')}</span>
@ -119,12 +125,7 @@ export const AuthorCard = (props: Props) => {
<Show when={props.author.bio}>
<div class={styles.authorAbout} innerHTML={props.author.bio} />
</Show>
<Show
when={
(props.followers && props.followers.length > 0) ||
(props.following && props.following.length > 0)
}
>
<Show when={props.followers?.length > 0 || props.following?.length > 0}>
<div class={styles.subscribersContainer}>
<Show when={props.followers && props.followers.length > 0}>
<a href="?m=followers" class={styles.subscribers}>
@ -204,13 +205,14 @@ export const AuthorCard = (props: Props) => {
when={isProfileOwner()}
fallback={
<div class={styles.authorActions}>
<Show when={authorSubs().length}>
<Show when={authorSubs()?.length}>
<Button
onClick={handleFollowClick}
disabled={Boolean(subscribeInAction())}
value={followButtonText()}
isSubscribeButton={true}
class={clsx({
[stylesButton.subscribed]: isFollowed(),
[stylesButton.subscribed]: isSubscribed(),
})}
/>
</Show>
@ -255,15 +257,7 @@ export const AuthorCard = (props: Props) => {
<div class="row">
<div class="col-24">
<For each={props.followers}>
{(follower: Author) => (
<AuthorBadge
author={follower}
isFollowed={{
loaded: Boolean(authorSubs()),
value: isOwnerSubscribed(follower.id),
}}
/>
)}
{(follower: Author) => <AuthorBadge author={follower} />}
</For>
</div>
</div>
@ -318,21 +312,9 @@ export const AuthorCard = (props: Props) => {
<For each={authorSubs()}>
{(subscription) =>
isAuthor(subscription) ? (
<AuthorBadge
isFollowed={{
loaded: Boolean(authorSubs()),
value: isOwnerSubscribed(subscription.id),
}}
author={subscription}
/>
<AuthorBadge author={subscription} />
) : (
<TopicBadge
isFollowed={{
loaded: Boolean(authorSubs()),
value: isOwnerSubscribed(subscription.id),
}}
topic={subscription}
/>
<TopicBadge topic={subscription} />
)
}
</For>

View File

@ -21,7 +21,6 @@ const PAGE_SIZE = 20
export const AuthorsList = (props: Props) => {
const { t } = useLocalize()
const { isOwnerSubscribed } = useFollowing()
const { authorsByShouts, authorsByFollowers } = useAuthorsStore()
const [loading, setLoading] = createSignal(false)
const [currentPage, setCurrentPage] = createSignal({ shouts: 0, followers: 0 })
@ -83,13 +82,7 @@ export const AuthorsList = (props: Props) => {
{(author) => (
<div class="row">
<div class="col-lg-20 col-xl-18">
<AuthorBadge
author={author}
isFollowed={{
loaded: !loading(),
value: isOwnerSubscribed(author.id),
}}
/>
<AuthorBadge author={author} />
</div>
</div>
)}

View File

@ -30,7 +30,6 @@ type Props = {
export const Beside = (props: Props) => {
const { t } = useLocalize()
const { isOwnerSubscribed } = useFollowing()
return (
<Show when={!!props.beside?.slug && props.values?.length > 0}>
@ -86,12 +85,7 @@ export const Beside = (props: Props) => {
/>
</Show>
<Show when={props.wrapper === 'author'}>
<AuthorBadge
author={value as Author}
isFollowed={{
value: isOwnerSubscribed(value.id),
}}
/>
<AuthorBadge author={value as Author} />
</Show>
<Show when={props.wrapper === 'article' && value?.slug}>
<ArticleCard

View File

@ -84,6 +84,10 @@
@include media-breakpoint-down(sm) {
right: 2px;
}
a {
border: none;
}
}
.settingsLabel {
@ -136,20 +140,22 @@
text-transform: uppercase;
position: relative;
&::after {
content: '+';
font-size: 1.6em;
line-height: 1;
.icon {
margin: 0;
min-width: 1.8rem;
position: absolute;
right: 2.5rem;
top: -0.2em;
right: 1.7rem;
top: 50%;
transform: translateY(-50%) rotate(180deg);
transform-origin: center;
transition: transform 0.3s;
width: 1.8rem;
}
&.opened {
&::after {
right: 0.9rem;
transform: rotate(45deg);
.icon {
right: 0;
transform: translateY(-50%);
}
}
}

View File

@ -119,6 +119,7 @@ export const Sidebar = () => {
}}
>
{t('My subscriptions')}
<Icon name="toggle-arrow" class={styles.icon} />
</h4>
<ul class={clsx(styles.subscriptions, { [styles.hidden]: !isSubscriptionsVisible() })}>

View File

@ -227,6 +227,7 @@ export const HeaderAuth = (props: Props) => {
<Show
when={isAuthenticatedControlsVisible()}
fallback={
<Show when={!isAuthenticated()}>
<div class={clsx(styles.userControlItem, styles.userControlItemVerbose, 'loginbtn')}>
<a href="?m=auth&mode=login">
<span class={styles.textLabel}>{t('Enter')}</span>
@ -234,6 +235,7 @@ export const HeaderAuth = (props: Props) => {
{/*<Icon name="user-default" class={clsx(styles.icon, styles.iconHover)} />*/}
</a>
</div>
</Show>
}
>
<Show when={!isSaveButtonVisible()}>

View File

@ -195,7 +195,7 @@ export const ProfileSettings = () => {
<div class="col-md-20 col-lg-18 col-xl-16">
<h1>{t('Profile settings')}</h1>
<p class="description">{t('Here you can customize your profile the way you want.')}</p>
<form enctype="multipart/form-data">
<form enctype="multipart/form-data" autocomplete="off">
<h4>{t('Userpic')}</h4>
<div class="pretty-form__item">
<div
@ -262,14 +262,16 @@ export const ProfileSettings = () => {
<div class="pretty-form__item">
<input
type="text"
name="username"
id="username"
name="nameOfUser"
id="nameOfUser"
data-lpignore="true"
autocomplete="one-time-code"
placeholder={t('Name')}
onInput={(event) => updateFormField('name', event.currentTarget.value)}
value={form.name}
ref={(el) => (nameInputRef.current = el)}
/>
<label for="username">{t('Name')}</label>
<label for="nameOfUser">{t('Name')}</label>
<Show when={nameError()}>
<div
style={{ position: 'absolute', 'margin-top': '-4px' }}
@ -289,6 +291,8 @@ export const ProfileSettings = () => {
type="text"
name="user-address"
id="user-address"
data-lpignore="true"
autocomplete="one-time-code2"
onInput={(event) => updateFormField('slug', event.currentTarget.value)}
value={form.slug}
ref={(el) => (slugInputRef.current = el)}

View File

@ -17,7 +17,7 @@ interface Props {
const isInViewport = (el: Element): boolean => {
const rect = el.getBoundingClientRect()
return rect.top <= DEFAULT_HEADER_OFFSET
return rect.top <= DEFAULT_HEADER_OFFSET + 24 // default offset + 1.5em (default header margin-top)
}
const scrollToHeader = (element) => {
window.scrollTo({

View File

@ -1,5 +1,5 @@
import { clsx } from 'clsx'
import { Show, createMemo, createSignal } from 'solid-js'
import { Show, createEffect, createMemo, createSignal } from 'solid-js'
import { useFollowing } from '../../context/following'
import { useLocalize } from '../../context/localize'
@ -38,14 +38,18 @@ export const TopicCard = (props: TopicProps) => {
capitalize(lang() === 'en' ? props.topic.slug.replaceAll('-', ' ') : props.topic.title || ''),
)
const { author, requireAuthentication } = useSession()
const { setFollowing, loading: subLoading } = useFollowing()
const [followed, setFollowed] = createSignal()
const [isSubscribed, setIsSubscribed] = createSignal()
const { follow, unfollow, subscriptions, subscribeInAction } = useFollowing()
createEffect(() => {
if (!subscriptions || !props.topic) return
const subscribed = subscriptions.topics?.some((topics) => topics.id === props.topic?.id)
setIsSubscribed(subscribed)
})
const handleFollowClick = () => {
const value = !followed()
requireAuthentication(() => {
setFollowed(value)
setFollowing(FollowingEntity.Topic, props.topic.slug, value)
follow(FollowingEntity.Topic, props.topic.slug)
}, 'subscribe')
}
@ -53,12 +57,12 @@ export const TopicCard = (props: TopicProps) => {
return (
<>
<Show when={props.iconButton}>
<Show when={followed()} fallback="+">
<Show when={isSubscribed()} fallback="+">
<Icon name="check-subscribed" />
</Show>
</Show>
<Show when={!props.iconButton}>
<Show when={followed()} fallback={t('Follow')}>
<Show when={isSubscribed()} fallback={t('Follow')}>
<span class={stylesButton.buttonSubscribeLabelHovered}>{t('Unfollow')}</span>
<span class={stylesButton.buttonSubscribeLabel}>{t('Following')}</span>
</Show>
@ -130,7 +134,7 @@ export const TopicCard = (props: TopicProps) => {
fallback={
<CheckButton
text={t('Follow')}
checked={Boolean(followed())}
checked={Boolean(isSubscribed())}
onClick={handleFollowClick}
/>
}
@ -142,10 +146,10 @@ export const TopicCard = (props: TopicProps) => {
onClick={handleFollowClick}
isSubscribeButton={true}
class={clsx(styles.actionButton, {
[styles.isSubscribing]: subLoading(),
[stylesButton.subscribed]: followed(),
[styles.isSubscribing]:
subscribeInAction()?.slug === props.topic.slug ? subscribeInAction().type : undefined,
[stylesButton.subscribed]: isSubscribed(),
})}
// disabled={subLoading()}
/>
</Show>
</Show>

View File

@ -8,16 +8,12 @@ import { useSession } from '../../../context/session'
import { FollowingEntity, Topic } from '../../../graphql/schema/core.gen'
import { capitalize } from '../../../utils/capitalize'
import { getImageUrl } from '../../../utils/getImageUrl'
import { Button } from '../../_shared/Button'
import { CheckButton } from '../../_shared/CheckButton'
import { FollowedInfo } from '../../../pages/types'
import { BadgeSubscribeButton } from '../../_shared/BadgeSubscribeButton'
import styles from './TopicBadge.module.scss'
type Props = {
topic: Topic
minimizeSubscribeButton?: boolean
isFollowed?: FollowedInfo
showStat?: boolean
}
@ -26,14 +22,20 @@ export const TopicBadge = (props: Props) => {
const { mediaMatches } = useMediaQuery()
const [isMobileView, setIsMobileView] = createSignal(false)
const { requireAuthentication } = useSession()
const { setFollowing, loading: subLoading } = useFollowing()
const [isFollowed, setIsFollowed] = createSignal<boolean>()
const [isSubscribed, setIsSubscribed] = createSignal<boolean>()
const { follow, unfollow, subscriptions, subscribeInAction } = useFollowing()
createEffect(() => {
if (!subscriptions || !props.topic) return
const subscribed = subscriptions.topics?.some((topics) => topics.id === props.topic?.id)
setIsSubscribed(subscribed)
})
const handleFollowClick = () => {
const value = !isFollowed()
requireAuthentication(() => {
setIsFollowed(value)
setFollowing(FollowingEntity.Topic, props.topic.slug, value)
isSubscribed()
? follow(FollowingEntity.Topic, props.topic.slug)
: unfollow(FollowingEntity.Topic, props.topic.slug)
}, 'subscribe')
}
@ -41,15 +43,6 @@ export const TopicBadge = (props: Props) => {
setIsMobileView(!mediaMatches.sm)
})
createEffect(
on(
() => props.isFollowed,
() => {
setIsFollowed(props.isFollowed.value)
},
),
)
const title = () =>
lang() === 'en' ? capitalize(props.topic.slug.replaceAll('-', ' ')) : props.topic.title
@ -83,35 +76,14 @@ export const TopicBadge = (props: Props) => {
</Show>
</a>
</div>
<div class={styles.actions}>
<Show
when={!props.minimizeSubscribeButton}
fallback={
<CheckButton text={t('Follow')} checked={Boolean(isFollowed())} onClick={handleFollowClick} />
<BadgeSubscribeButton
isSubscribed={isSubscribed()}
action={handleFollowClick}
actionMessageType={
subscribeInAction()?.slug === props.topic.slug ? subscribeInAction().type : undefined
}
>
<Show
when={isFollowed()}
fallback={
<Button
variant="primary"
size="S"
value={subLoading() ? t('subscribing...') : t('Subscribe')}
onClick={handleFollowClick}
class={styles.subscribeButton}
/>
}
>
<Button
onClick={handleFollowClick}
variant="bordered"
size="S"
value={t('Following')}
class={styles.subscribeButton}
/>
</Show>
</Show>
</div>
</div>
<div class={styles.stats}>

View File

@ -74,8 +74,6 @@ export const AllTopics = (props: Props) => {
return keys
})
const { isOwnerSubscribed } = useFollowing()
const showMore = () => setLimit((oldLimit) => oldLimit + PAGE_SIZE)
const [searchQuery, setSearchQuery] = createSignal('')
const filteredResults = createMemo(() => {
@ -188,14 +186,7 @@ export const AllTopics = (props: Props) => {
<For each={filteredResults().slice(0, limit())}>
{(topic) => (
<>
<TopicBadge
topic={topic}
isFollowed={{
loaded: filteredResults().length > 0,
value: isOwnerSubscribed(topic.slug),
}}
showStat={true}
/>
<TopicBadge topic={topic} showStat={true} />
</>
)}
</For>

View File

@ -3,7 +3,7 @@ import type { Author, Reaction, Shout, Topic } from '../../../graphql/schema/cor
import { getPagePath } from '@nanostores/router'
import { Meta, Title } from '@solidjs/meta'
import { clsx } from 'clsx'
import { For, Match, Show, Switch, createEffect, createMemo, createSignal, onMount } from 'solid-js'
import { For, Match, Show, Switch, createEffect, createMemo, createSignal, on, onMount } from 'solid-js'
import { useFollowing } from '../../../context/following'
import { useLocalize } from '../../../context/localize'
@ -75,7 +75,7 @@ export const AuthorView = (props: Props) => {
const bioContainerRef: { current: HTMLDivElement } = { current: null }
const bioWrapperRef: { current: HTMLDivElement } = { current: null }
const fetchData = async (slug) => {
const fetchData = async (slug: string) => {
try {
const [subscriptionsResult, followersResult, authorResult] = await Promise.all([
apiClient.getAuthorFollows({ slug }),
@ -112,14 +112,9 @@ export const AuthorView = (props: Props) => {
onMount(() => {
if (!modal) hideModal()
checkBioHeight()
fetchData(props.authorSlug)
// pagination
if (sortedArticles().length === PRERENDERED_ARTICLES_COUNT) {
checkBioHeight()
loadMore()
loadSubscriptions()
}
})
const pages = createMemo<Shout[][]>(() =>
@ -133,11 +128,17 @@ export const AuthorView = (props: Props) => {
setCommented(data)
}
createEffect(() => {
if (author()) {
const authorSlug = createMemo(() => author()?.slug)
createEffect(
on(
() => authorSlug(),
() => {
fetchData(authorSlug())
fetchComments(author())
}
})
},
{ defer: true },
),
)
const ogImage = createMemo(() =>
author()?.pic

View File

@ -1,16 +1,14 @@
import { getPagePath } from '@nanostores/router'
import { clsx } from 'clsx'
import { For, Show, createEffect, createMemo, createSignal, on, onCleanup, onMount } from 'solid-js'
import { For, Show, createEffect, createSignal, on, onCleanup, onMount } from 'solid-js'
import { useLocalize } from '../../../context/localize'
import { apiClient } from '../../../graphql/client/core'
import { LoadShoutsFilters, LoadShoutsOptions, Shout } from '../../../graphql/schema/core.gen'
import { LayoutType } from '../../../pages/types'
import { router } from '../../../stores/router'
import { loadShouts, resetSortedArticles, useArticlesStore } from '../../../stores/zine/articles'
import { getUnixtime } from '../../../utils/getServerDate'
import { restoreScrollPosition, saveScrollPosition } from '../../../utils/scroll'
import { splitToPages } from '../../../utils/splitToPages'
import { ArticleCard } from '../../Feed/ArticleCard'
import { Button } from '../../_shared/Button'
import { ConditionalWrapper } from '../../_shared/ConditionalWrapper'
@ -28,19 +26,12 @@ export const PRERENDERED_ARTICLES_COUNT = 36
const LOAD_MORE_PAGE_SIZE = 12
export const Expo = (props: Props) => {
const [isLoaded, setIsLoaded] = createSignal<boolean>(Boolean(props.shouts))
const { t } = useLocalize()
const [isLoadMoreButtonVisible, setIsLoadMoreButtonVisible] = createSignal(false)
const [favoriteTopArticles, setFavoriteTopArticles] = createSignal<Shout[]>([])
const [reactedTopMonthArticles, setReactedTopMonthArticles] = createSignal<Shout[]>([])
const { t } = useLocalize()
const { sortedArticles } = useArticlesStore({
shouts: isLoaded() ? props.shouts : [],
layout: props.layout,
})
const [articlesEndPage, setArticlesEndPage] = createSignal<number>(PRERENDERED_ARTICLES_COUNT)
const [expoShouts, setExpoShouts] = createSignal<Shout[]>([])
const getLoadShoutsFilters = (additionalFilters: LoadShoutsFilters = {}): LoadShoutsFilters => {
const filters = { ...additionalFilters }
@ -58,15 +49,18 @@ export const Expo = (props: Props) => {
const options: LoadShoutsOptions = {
filters: getLoadShoutsFilters(),
limit: count,
offset: sortedArticles().length,
offset: expoShouts().length,
}
options.filters = props.layout
? { layouts: [props.layout] }
: { layouts: ['audio', 'video', 'image', 'literature'] }
const { hasMore } = await loadShouts(options)
const newShouts = await apiClient.getShouts(options)
const hasMore = newShouts?.length !== options.limit + 1 && newShouts?.length !== 0
setIsLoadMoreButtonVisible(hasMore)
setExpoShouts((prev) => [...prev, ...newShouts])
}
const loadMoreWithoutScrolling = async (count: number) => {
@ -100,19 +94,7 @@ export const Expo = (props: Props) => {
}
onMount(() => {
if (isLoaded()) {
return
}
loadMore(PRERENDERED_ARTICLES_COUNT + LOAD_MORE_PAGE_SIZE)
setIsLoaded(true)
})
onMount(() => {
if (sortedArticles().length === PRERENDERED_ARTICLES_COUNT) {
loadMore(LOAD_MORE_PAGE_SIZE)
}
loadRandomTopArticles()
loadRandomTopMonthArticles()
})
@ -121,9 +103,11 @@ export const Expo = (props: Props) => {
on(
() => props.layout,
() => {
resetSortedArticles()
setExpoShouts([])
setIsLoadMoreButtonVisible(false)
setFavoriteTopArticles([])
setReactedTopMonthArticles([])
setArticlesEndPage(PRERENDERED_ARTICLES_COUNT)
loadMore(PRERENDERED_ARTICLES_COUNT + LOAD_MORE_PAGE_SIZE)
loadRandomTopArticles()
loadRandomTopMonthArticles()
@ -132,16 +116,17 @@ export const Expo = (props: Props) => {
)
onCleanup(() => {
resetSortedArticles()
setExpoShouts([])
})
const handleLoadMoreClick = () => {
loadMoreWithoutScrolling(LOAD_MORE_PAGE_SIZE)
setArticlesEndPage((prev) => prev + LOAD_MORE_PAGE_SIZE)
}
return (
<div class={styles.Expo}>
<Show when={sortedArticles()?.length > 0} fallback={<Loading />}>
<Show when={expoShouts().length > 0} fallback={<Loading />}>
<div class="wide-container">
<ul class={clsx('view-switcher')}>
<li class={clsx({ 'view-switcher__item--selected': !props.layout })}>
@ -194,7 +179,7 @@ export const Expo = (props: Props) => {
</li>
</ul>
<div class="row">
<For each={sortedArticles().slice(0, LOAD_MORE_PAGE_SIZE)}>
<For each={expoShouts()?.slice(0, LOAD_MORE_PAGE_SIZE)}>
{(shout) => (
<div class="col-md-6 mt-md-5 col-sm-8 mt-sm-3">
<ArticleCard
@ -209,7 +194,7 @@ export const Expo = (props: Props) => {
<Show when={reactedTopMonthArticles()?.length > 0} keyed={true}>
<ArticleCardSwiper title={t('Top month articles')} slides={reactedTopMonthArticles()} />
</Show>
<For each={sortedArticles().slice(LOAD_MORE_PAGE_SIZE, LOAD_MORE_PAGE_SIZE * 2)}>
<For each={expoShouts().slice(LOAD_MORE_PAGE_SIZE, LOAD_MORE_PAGE_SIZE * 2)}>
{(shout) => (
<div class="col-md-6 mt-md-5 col-sm-8 mt-sm-3">
<ArticleCard
@ -224,7 +209,7 @@ export const Expo = (props: Props) => {
<Show when={favoriteTopArticles()?.length > 0} keyed={true}>
<ArticleCardSwiper title={t('Favorite')} slides={favoriteTopArticles()} />
</Show>
<For each={sortedArticles().slice(LOAD_MORE_PAGE_SIZE * 2)}>
<For each={expoShouts().slice(LOAD_MORE_PAGE_SIZE * 2, articlesEndPage())}>
{(shout) => (
<div class="col-md-6 mt-md-5 col-sm-8 mt-sm-3">
<ArticleCard

View File

@ -170,7 +170,7 @@
}
}
.commentArticleTitle {
.comment .commentArticleTitle {
line-clamp: 1;
-webkit-line-clamp: 1;

View File

@ -54,6 +54,13 @@ type FeedSearchParams = {
visibility: VisibilityMode
}
type Props = {
loadShouts: (options: LoadShoutsOptions) => Promise<{
hasMore: boolean
newShouts: Shout[]
}>
}
const getFromDate = (period: FeedPeriod): number => {
const now = new Date()
let d: Date = now
@ -74,18 +81,10 @@ const getFromDate = (period: FeedPeriod): number => {
return Math.floor(d.getTime() / 1000)
}
type Props = {
loadShouts: (options: LoadShoutsOptions) => Promise<{
hasMore: boolean
newShouts: Shout[]
}>
}
export const FeedView = (props: Props) => {
const { t } = useLocalize()
const monthPeriod: PeriodItem = { value: 'month', title: t('This month') }
const visibilityAll = { value: 'featured', title: t('All') }
const periods: PeriodItem[] = [
{ value: 'week', title: t('This week') },
@ -121,7 +120,7 @@ export const FeedView = (props: Props) => {
const currentVisibility = createMemo(() => {
const visibility = visibilities.find((v) => v.value === searchParams().visibility)
if (!visibility) {
return visibilityAll
return visibilities[0]
}
return visibility
})
@ -172,6 +171,7 @@ export const FeedView = (props: Props) => {
}
const visibilityMode = searchParams().visibility
if (visibilityMode === 'all') {
options.filters = { ...options.filters }
} else if (visibilityMode) {
@ -185,6 +185,7 @@ export const FeedView = (props: Props) => {
const period = searchParams().period || 'month'
options.filters = { after: getFromDate(period) }
}
return props.loadShouts(options)
}

View File

@ -0,0 +1,29 @@
.actionButton {
border-radius: 0.8rem !important;
margin-right: 0 !important;
width: 9em;
&.iconed {
padding: 6px !important;
min-width: 4rem;
width: unset;
&:hover img {
filter: invert(1);
}
}
&:hover {
.actionButtonLabel {
display: none;
}
.actionButtonLabelHovered {
display: block;
}
}
}
.actionButtonLabelHovered {
display: none;
}

View File

@ -0,0 +1,87 @@
import { clsx } from 'clsx'
import { Show, createMemo } from 'solid-js'
import { useFollowing } from '../../../context/following'
import { useLocalize } from '../../../context/localize'
import { Button } from '../Button'
import stylesButton from '../Button/Button.module.scss'
import { CheckButton } from '../CheckButton'
import { Icon } from '../Icon'
import styles from './BadgeDubscribeButton.module.scss'
type Props = {
class?: string
isSubscribed: boolean
minimizeSubscribeButton?: boolean
action: () => void
iconButtons?: boolean
actionMessageType?: 'subscribe' | 'unsubscribe'
}
export const BadgeSubscribeButton = (props: Props) => {
const { t } = useLocalize()
const inActionText = createMemo(() => {
return props.actionMessageType === 'subscribe' ? t('Subscribing...') : t('Unsubscribing...')
})
return (
<div class={props.class}>
<Show
when={!props.minimizeSubscribeButton}
fallback={<CheckButton text={t('Follow')} checked={props.isSubscribed} onClick={props.action} />}
>
<Show
when={props.isSubscribed}
fallback={
<Button
variant={props.iconButtons ? 'secondary' : 'bordered'}
size="S"
value={
<Show
when={props.iconButtons}
fallback={props.actionMessageType ? inActionText() : t('Subscribe')}
>
<Icon name="author-subscribe" class={stylesButton.icon} />
</Show>
}
onClick={props.action}
isSubscribeButton={true}
class={clsx(styles.actionButton, {
[styles.iconed]: props.iconButtons,
[stylesButton.subscribed]: props.isSubscribed,
})}
/>
}
>
<Button
variant={props.iconButtons ? 'secondary' : 'bordered'}
size="S"
value={
<Show
when={props.iconButtons}
fallback={
props.actionMessageType ? (
inActionText()
) : (
<>
<span class={styles.actionButtonLabel}>{t('Following')}</span>
<span class={styles.actionButtonLabelHovered}>{t('Unfollow')}</span>
</>
)
}
>
<Icon name="author-unsubscribe" class={stylesButton.icon} />
</Show>
}
onClick={props.action}
isSubscribeButton={true}
class={clsx(styles.actionButton, {
[styles.iconed]: props.iconButtons,
[stylesButton.subscribed]: props.isSubscribed,
})}
/>
</Show>
</Show>
</div>
)
}

View File

@ -0,0 +1 @@
export { BadgeSubscribeButton } from './BadgeSubscribeButton'

View File

@ -1,11 +1,19 @@
import { Accessor, JSX, createContext, createEffect, createSignal, useContext } from 'solid-js'
import { Accessor, JSX, createContext, createEffect, createMemo, createSignal, useContext } from 'solid-js'
import { createStore } from 'solid-js/store'
import { apiClient } from '../graphql/client/core'
import { Author, AuthorFollowsResult, FollowingEntity } from '../graphql/schema/core.gen'
import { Author, AuthorFollowsResult, Community, FollowingEntity, Topic } from '../graphql/schema/core.gen'
import { useSession } from './session'
export type SubscriptionsData = {
topics?: Topic[]
authors?: Author[]
communities?: Community[]
}
type SubscribeAction = { slug: string; type: 'subscribe' | 'unsubscribe' }
interface FollowingContextType {
loading: Accessor<boolean>
followers: Accessor<Array<Author>>
@ -15,7 +23,8 @@ interface FollowingContextType {
loadSubscriptions: () => void
follow: (what: FollowingEntity, slug: string) => Promise<void>
unfollow: (what: FollowingEntity, slug: string) => Promise<void>
isOwnerSubscribed: (id: number | string) => boolean
// followers: Accessor<Author[]>
subscribeInAction?: Accessor<SubscribeAction>
}
const FollowingContext = createContext<FollowingContextType>()
@ -43,7 +52,6 @@ export const FollowingProvider = (props: { children: JSX.Element }) => {
console.debug('[context.following] fetching subs data...')
const result = await apiClient.getAuthorFollows({ user: session()?.user.id })
setSubscriptions(result || EMPTY_SUBSCRIPTIONS)
console.info('[context.following] subs:', subscriptions)
}
} catch (error) {
console.info('[context.following] cannot get subs', error)
@ -52,28 +60,37 @@ export const FollowingProvider = (props: { children: JSX.Element }) => {
}
}
createEffect(() => {
console.info('[context.following] subs:', subscriptions)
})
const [subscribeInAction, setSubscribeInAction] = createSignal<SubscribeAction>()
const follow = async (what: FollowingEntity, slug: string) => {
if (!author()) return
setSubscribeInAction({ slug, type: 'subscribe' })
try {
await apiClient.follow({ what, slug })
const subscriptionData = await apiClient.follow({ what, slug })
setSubscriptions((prevSubscriptions) => {
const updatedSubs = { ...prevSubscriptions }
if (!updatedSubs[what]) updatedSubs[what] = []
const exists = updatedSubs[what]?.some((entity) => entity.slug === slug)
if (!exists) updatedSubs[what].push(slug)
return updatedSubs
if (!prevSubscriptions[what]) prevSubscriptions[what] = []
prevSubscriptions[what].push(subscriptionData)
return prevSubscriptions
})
} catch (error) {
console.error(error)
} finally {
setSubscribeInAction() // Сбрасываем состояние действия подписки.
}
}
const unfollow = async (what: FollowingEntity, slug: string) => {
if (!author()) return
setSubscribeInAction({ slug: slug, type: 'unsubscribe' })
try {
await apiClient.unfollow({ what, slug })
} catch (error) {
console.error(error)
} finally {
setSubscribeInAction()
}
}
@ -114,23 +131,17 @@ export const FollowingProvider = (props: { children: JSX.Element }) => {
}
}
const isOwnerSubscribed = (id?: number | string) => {
if (!author() || !subscriptions) return
const isAuthorSubscribed = subscriptions.authors?.some((authorEntity) => authorEntity.id === id)
const isTopicSubscribed = subscriptions.topics?.some((topicEntity) => topicEntity.slug === id)
return !!isAuthorSubscribed || !!isTopicSubscribed
}
const value: FollowingContextType = {
loading,
subscriptions,
setSubscriptions,
isOwnerSubscribed,
setFollowing,
followers,
loadSubscriptions: fetchData,
follow,
unfollow,
// followers,
subscribeInAction,
}
return <FollowingContext.Provider value={value}>{props.children}</FollowingContext.Provider>

View File

@ -1,5 +1,5 @@
import type { Accessor, JSX, Resource } from 'solid-js'
import type { AuthModalSource } from '../components/Nav/AuthModal/types'
import type { AuthModalSearchParams, AuthModalSource } from '../components/Nav/AuthModal/types'
import type { Author } from '../graphql/schema/core.gen'
import {
@ -29,7 +29,6 @@ import {
import { inboxClient } from '../graphql/client/chat'
import { apiClient } from '../graphql/client/core'
import { notifierClient } from '../graphql/client/notifier'
import { useRouter } from '../stores/router'
import { showModal } from '../stores/ui'
import { addAuthors } from '../stores/zine/authors'
@ -136,6 +135,7 @@ export const SessionProvider = (props: {
const [isSessionLoaded, setIsSessionLoaded] = createSignal(false)
const [authError, setAuthError] = createSignal('')
const { clearSearchParams } = useRouter<AuthModalSearchParams>()
// Function to load session data
const sessionData = async () => {
@ -143,7 +143,7 @@ export const SessionProvider = (props: {
const s: ApiResponse<AuthToken> = await authorizer().getSession()
if (s?.data) {
console.info('[context.session] loading session', s)
clearSearchParams()
// Set session expiration time in local storage
const expires_at = new Date(Date.now() + s.data.expires_in * 1000)
localStorage.setItem('expires_at', `${expires_at.getTime()}`)
@ -379,6 +379,7 @@ export const SessionProvider = (props: {
}
const isAuthenticated = createMemo(() => Boolean(author()))
const actions = {
loadSession,
requireAuthentication,

View File

@ -4,6 +4,10 @@ export default gql`
mutation FollowMutation($what: FollowingEntity!, $slug: String!) {
follow(what: $what, slug: $slug) {
error
authors {
id
slug
}
}
}
`

View File

@ -320,3 +320,14 @@ h5 {
margin-bottom: 0;
}
}
// disable last pass extention
div[data-lastpass-icon-root="true"] {
opacity: 0 !important;
}
div[data-lastpass-infield="true"] {
opacity: 0 !important;
}

View File

@ -53,9 +53,4 @@ export type UploadedFile = {
originalFilename?: string
}
export type FollowedInfo = {
value?: boolean
loaded?: boolean
}
export type SubscriptionFilter = 'all' | 'authors' | 'topics' | 'communities'

View File

@ -588,6 +588,7 @@ figure {
display: block;
max-height: 90vh;
margin: auto;
width: 100%;
}
}

View File

@ -1,31 +1,41 @@
import { cdnUrl, thumborUrl } from './config'
const getSizeUrlPart = (options: { width?: number; height?: number; noSizeUrlPart?: boolean } = {}) => {
const widthString = options.width ? options.width.toString() : ''
const heightString = options.height ? options.height.toString() : ''
const URL_CONFIG = {
cdnUrl: cdnUrl,
thumborUrl: `${thumborUrl}/unsafe/`,
audioSubfolder: 'audio',
imageSubfolder: 'image',
productionFolder: 'production/',
}
if (!(widthString || heightString) || options.noSizeUrlPart) {
return ''
}
const AUDIO_EXTENSIONS = new Set(['wav', 'mp3', 'ogg', 'aif', 'flac'])
return `${widthString}x${heightString}/`
const isAudioFile = (filename: string): boolean => {
const extension = filename.split('.').pop()?.toLowerCase()
return AUDIO_EXTENSIONS.has(extension ?? '')
}
const getLastSegment = (url: string): string => url.toLowerCase().split('/').pop() || ''
const buildSizePart = (width?: number, height?: number, includeSize = true): string => {
if (!includeSize) return ''
const widthPart = width ? width.toString() : ''
const heightPart = height ? height.toString() : ''
return widthPart || heightPart ? `${widthPart}x${heightPart}/` : ''
}
export const getImageUrl = (
src: string,
options: { width?: number; height?: number; noSizeUrlPart?: boolean } = {},
) => {
): string => {
if (!src.includes('discours.io') && src.includes('http')) {
return src
}
const filename = src.toLowerCase().split('/').pop()
const ext = filename.split('.').pop()
const isAudio = ext in ['wav', 'mp3', 'ogg', 'aif', 'flac']
const base = isAudio ? cdnUrl : `${thumborUrl}/unsafe/`
const suffix = isAudio || options.noSizeUrlPart ? '' : getSizeUrlPart(options)
const subfolder = isAudio ? 'audio' : 'image'
const filename = getLastSegment(src)
const base = isAudioFile(filename) ? URL_CONFIG.cdnUrl : URL_CONFIG.thumborUrl
const suffix = options.noSizeUrlPart ? '' : buildSizePart(options.width, options.height)
const subfolder = isAudioFile(filename) ? URL_CONFIG.audioSubfolder : URL_CONFIG.imageSubfolder
return `${base}${suffix}production/${subfolder}/${filename}`
return `${base}${suffix}${URL_CONFIG.productionFolder}${subfolder}/${filename}`
}
export const getOpenGraphImageUrl = (
@ -37,17 +47,16 @@ export const getOpenGraphImageUrl = (
width?: number
height?: number
},
) => {
const sizeUrlPart = getSizeUrlPart(options)
): string => {
const sizeUrlPart = buildSizePart(options.width, options.height)
const filtersPart = `filters:discourstext('${encodeURIComponent(options.topic)}','${encodeURIComponent(
options.author,
)}','${encodeURIComponent(options.title)}')/`
if (src.startsWith(thumborUrl)) {
const thumborKey = src.replace(`${thumborUrl}/unsafe`, '')
return `${thumborUrl}/unsafe/${sizeUrlPart}${filtersPart}${thumborKey}`
if (src.startsWith(URL_CONFIG.thumborUrl)) {
const thumborKey = src.replace(URL_CONFIG.thumborUrl, '')
return `${URL_CONFIG.thumborUrl}${sizeUrlPart}${filtersPart}${thumborKey}`
}
return `${thumborUrl}/unsafe/${sizeUrlPart}${filtersPart}${src}`
return `${URL_CONFIG.thumborUrl}${sizeUrlPart}${filtersPart}${src}`
}