Skip to content

Commit

Permalink
Resolve "Change functionality of categories and tags in PostForm"
Browse files Browse the repository at this point in the history
  • Loading branch information
KKocot authored and func0x committed Mar 28, 2024
1 parent 3ddae2f commit 978383f
Show file tree
Hide file tree
Showing 16 changed files with 131 additions and 53 deletions.
12 changes: 11 additions & 1 deletion apps/blog/components/communities-list-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import type { Community } from '@transaction/lib/bridge';
import { useTranslation } from 'next-i18next';
import { useUser } from '@smart-signer/lib/auth/use-user';
import SubscribeCommunity from './subscribe-community';
import { useEffect, useState } from 'react';

const CommunitiesListItem = ({ community }: { community: Community }) => {
const { user } = useUser();
const { t } = useTranslation('common_blog');
const [isSubscribe, setIsSubscribe] = useState(() => community.context.subscribed);
useEffect(() => {
setIsSubscribe(community.context.subscribed);
}, [community.context.subscribed]);
return (
<Card
className={cn(
Expand Down Expand Up @@ -54,7 +59,12 @@ const CommunitiesListItem = ({ community }: { community: Community }) => {
</CardFooter>
</div>
<div className="mr-4 flex w-24 items-center">
<SubscribeCommunity user={user} username={community.name} subStatus={community.context.subscribed} />
<SubscribeCommunity
user={user}
username={community.name}
subStatus={isSubscribe}
OnIsSubscribe={(e) => setIsSubscribe(e)}
/>
</div>
</Card>
);
Expand Down
16 changes: 12 additions & 4 deletions apps/blog/components/community-description.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { ActivityLogDialog } from './activity-log-dialog';
import { Badge } from '@ui/components/badge';
import { useTranslation } from 'next-i18next';
import { useUser } from '@smart-signer/lib/auth/use-user';
import { useContext } from 'react';
import { useContext, useEffect, useState } from 'react';
import { HiveRendererContext } from './hive-renderer-context';
import SubscribeCommunity from './subscribe-community';
import NewPost from './new_post_button';
Expand All @@ -24,6 +24,7 @@ const CommunityDescription = ({
notificationData: IAccountNotification[] | null | undefined;
username: string;
}) => {
const [isSubscribe, setIsSubscribe] = useState(() => data.context.subscribed);
const { user } = useUser();
const { t } = useTranslation('common_blog');
const { hiveRenderer } = useContext(HiveRendererContext);
Expand All @@ -32,7 +33,9 @@ const CommunityDescription = ({
if (data.description && hiveRenderer) {
post_body_html = hiveRenderer.render(data.description);
}

useEffect(() => {
setIsSubscribe(data.context.subscribed);
}, [data.context.subscribed]);
return (
<div className="flex w-auto max-w-[240px] flex-col">
<Card
Expand Down Expand Up @@ -63,8 +66,13 @@ const CommunityDescription = ({
</div>
</div>
<div className="my-4 flex flex-col gap-2">
<SubscribeCommunity user={user} username={username} subStatus={data.context.subscribed} />
<NewPost name={data.name} />
<SubscribeCommunity
user={user}
username={username}
subStatus={isSubscribe}
OnIsSubscribe={(e) => setIsSubscribe(e)}
/>
<NewPost name={data.name} disabled={!isSubscribe} />
</div>
<div data-testid="community-leadership" className="my-6 flex flex-col">
<h6 className="my-1.5 font-semibold leading-none tracking-tight">
Expand Down
16 changes: 14 additions & 2 deletions apps/blog/components/community-simple-description.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useTranslation } from 'next-i18next';
import SubscribeCommunity from './subscribe-community';
import { useUser } from '@smart-signer/lib/auth/use-user';
import NewPost from './new_post_button';
import { useEffect, useState } from 'react';

const CommunitySimpleDescription = ({
data,
Expand All @@ -20,7 +21,13 @@ const CommunitySimpleDescription = ({
username: string;
}) => {
const { t } = useTranslation('common_blog');
const [isSubscribe, setIsSubscribe] = useState(() => data.context.subscribed);
const { user } = useUser();

useEffect(() => {
setIsSubscribe(data.context.subscribed);
}, [data.context.subscribed]);

return (
<Card
className="my-4 grid h-fit w-full grid-cols-3 gap-4 p-2 dark:bg-background/95 dark:text-white"
Expand Down Expand Up @@ -50,8 +57,13 @@ const CommunitySimpleDescription = ({
</CardHeader>
<CardContent className="col-span-1 flex items-center justify-center p-0">
<div className="my-4 flex flex-col gap-4">
<SubscribeCommunity user={user} username={username} subStatus={data.context.subscribed} />
<NewPost name={data.name} />
<SubscribeCommunity
user={user}
username={username}
subStatus={isSubscribe}
OnIsSubscribe={(e) => setIsSubscribe(e)}
/>
<NewPost disabled={!isSubscribe} name={data.name} />
</div>
</CardContent>
</Card>
Expand Down
12 changes: 7 additions & 5 deletions apps/blog/components/new_post_button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,20 @@ const defaultValues = {
author: '',
category: ''
};
const NewPost = ({ name }: { name: string }) => {
const NewPost = ({ name, disabled }: { name: string; disabled: boolean }) => {
const { t } = useTranslation('common_blog');
const [storedPost, storePost] = useLocalStorage<AccountFormValues>('postData', defaultValues);

return (
<Button
size="sm"
className="w-full bg-blue-800 text-center hover:bg-blue-900"
onClick={() => storePost({ ...storedPost, tags: name, category: name })}
className="w-full bg-blue-800 p-0 text-center hover:bg-blue-900"
onClick={() => storePost({ ...storedPost, category: name })}
data-testid="community-new-post-button"
disabled={(disabled && !name.includes('hive-1')) || name.includes('hive-2') || name.includes('hive-3')}
>
<Link href={`/submit.html?category=${name}`}>{t('communities.buttons.new_post')}</Link>
<Link className="w-full p-2" href={`/submit.html?category=${name}`}>
{t('communities.buttons.new_post')}
</Link>
</Button>
);
};
Expand Down
58 changes: 40 additions & 18 deletions apps/blog/components/post-form.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { Button } from '@hive/ui/components/button';
import { Input } from '@hive/ui/components/input';
import Link from 'next/link';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@hive/ui/components/select';
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue
} from '@hive/ui/components/select';
import { Label } from '@radix-ui/react-label';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
Expand All @@ -25,7 +32,7 @@ import { HiveRendererContext } from './hive-renderer-context';
import { transactionService } from '@transaction/index';
import { createPermlink } from '@transaction/lib/utils';
import { useQuery } from '@tanstack/react-query';
import { getSubscriptions } from '@transaction/lib/bridge';
import { getCommunity, getSubscriptions } from '@transaction/lib/bridge';
import { useRouter } from 'next/router';
import { hiveChainService } from '@transaction/lib/hive-chain-service';
import { TFunction } from 'i18next';
Expand All @@ -36,15 +43,15 @@ const defaultValues = {
postSummary: '',
tags: '',
author: '',
category: '',
category: 'blog',
beneficiaries: [],
maxAcceptedPayout: null,
payoutType: '50%'
};

const MAX_TAGS = 8;
function validateTagInput(value: string, required = true, t: TFunction<'common_wallet', undefined>) {
if (!value || value.trim() === '') return required ? t('g.required') : null;
function validateTagInput(value: string, required: boolean, t: TFunction<'common_wallet', undefined>) {
if (!value || value.trim() === '') return required ? t('submit_page.category_selector.required') : null;
const tags = value.trim().replace(/#/g, '').split(/ +/);
return tags.length > MAX_TAGS
? t('submit_page.category_selector.use_limited_amount_of_categories', {
Expand All @@ -64,7 +71,7 @@ function validateTagInput(value: string, required = true, t: TFunction<'common_w
? t('submit_page.category_selector.must_start_with_a_letter')
: tags.find((c) => !/[a-z0-9]$/.test(c))
? t('submit_page.category_selector.must_end_with_a_letter_or_number')
: tags.filter((c) => c.substring(0, 5) === 'hive-').length > 1
: tags.filter((c) => c.substring(0, 5) === 'hive-').length > 0
? t('submit_page.category_selector.must_not_include_hivemind_community_owner')
: tags.reduce((acc, tag, index, array) => {
const isDuplicate = array.slice(index + 1).some((b) => b === tag);
Expand Down Expand Up @@ -100,14 +107,27 @@ export default function PostForm({ username }: { username: string }) {
const { manabarsData } = useManabars(username);
const [storedPost, storePost] = useLocalStorage<AccountFormValues>('postData', defaultValues);
const { t } = useTranslation('common_blog');

const {
data: mySubsData,
isLoading: mySubsIsLoading,
isError: mySubsIsError
} = useQuery([['subscriptions', username]], () => getSubscriptions(username), {
enabled: Boolean(username)
});

const {
data: communityData,
isLoading: communityDataIsLoading,
isFetching: communityDataIsFetching,
error: communityDataError
} = useQuery(
['community', router.query.category, ''],
() =>
getCommunity(router.query.category ? router.query.category.toString() : storedPost.category, username),
{
enabled: Boolean(storedPost.category)
}
);
const accountFormSchema = z.object({
title: z.string().min(2, t('submit_page.string_must_contain', { num: 2 })),
postArea: z.string().min(1, t('submit_page.string_must_contain', { num: 1 })),
Expand Down Expand Up @@ -142,10 +162,9 @@ export default function PostForm({ username }: { username: string }) {
values: getValues(storedPost)
});
const watchedValues = form.watch();
const tagsCheck = validateTagInput(watchedValues.tags, false, t);
const tagsCheck = validateTagInput(watchedValues.tags, watchedValues.category === 'blog', t);
const summaryCheck = validateSummoryInput(watchedValues.postSummary, t);
const altUsernameCheck = validateAltUsernameInput(watchedValues.author, t);

useEffect(() => {
storePost(watchedValues);
}, [JSON.stringify(watchedValues)]);
Expand All @@ -155,9 +174,9 @@ export default function PostForm({ username }: { username: string }) {
const plink = await createPermlink(storedPost?.title ?? '', username, storedPost?.title ?? '');
setPostPermlink(plink);
};

createPostPermlink();
}, [username, storedPost?.title]);

async function onSubmit(data: AccountFormValues) {
const chain = await hiveChainService.getHiveChain();
const tags = storedPost?.tags.replace(/#/g, '').split(' ') ?? [];
Expand All @@ -170,15 +189,15 @@ export default function PostForm({ username }: { username: string }) {
storedPost.beneficiaries,
Number(storedPost.payoutType.slice(0, 2)),
maxAcceptedPayout,
tags
tags,
storedPost.category
);
storePost(defaultValues);
router.push(`/created/${tags[0]}`);
} catch (error) {
console.error(error);
}
}

return (
<div className={clsx({ container: !sideBySide || !preview })}>
<div
Expand Down Expand Up @@ -317,7 +336,7 @@ export default function PostForm({ username }: { username: string }) {
<FormControl>
<Select
defaultValue={storedPost ? storedPost.category : 'blog'}
onValueChange={(e) => storePost({ ...storedPost, tags: e + ' ' + storedPost.tags })}
onValueChange={(e) => storePost({ ...storedPost, category: e })}
>
<FormControl>
<SelectTrigger>
Expand All @@ -326,11 +345,18 @@ export default function PostForm({ username }: { username: string }) {
</FormControl>
<SelectContent>
<SelectItem value="blog">{t('submit_page.my_blog')}</SelectItem>
<SelectGroup>{t('submit_page.my_communities')}</SelectGroup>
{mySubsData?.map((e) => (
<SelectItem key={e[0]} value={e[0]}>
{e[1]}
</SelectItem>
))}
{!mySubsData?.some((e) => e[0] === storedPost.category) ? (
<>
<SelectGroup>{t('submit_page.others_communities')}</SelectGroup>
<SelectItem value={storedPost.category}>{communityData?.title}</SelectItem>
</>
) : null}
</SelectContent>
</Select>
</FormControl>
Expand All @@ -342,11 +368,7 @@ export default function PostForm({ username }: { username: string }) {
type="submit"
variant="redHover"
disabled={
!storedPost?.title ||
storedPost.tags.length === 0 ||
Boolean(tagsCheck) ||
Boolean(summaryCheck) ||
Boolean(altUsernameCheck)
!storedPost?.title || Boolean(tagsCheck) || Boolean(summaryCheck) || Boolean(altUsernameCheck)
}
>
{t('submit_page.submit')}
Expand Down
20 changes: 8 additions & 12 deletions apps/blog/components/subscribe-community.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,34 @@
import { Button } from '@ui/components/button';
import DialogLogin from './dialog-login';
import { useTranslation } from 'next-i18next';
import { useEffect, useState } from 'react';
import { transactionService } from '@transaction/index';
import { User } from '@smart-signer/types/common';

const SubscribeCommunity = ({
user,
username,
subStatus
subStatus,
OnIsSubscribe
}: {
user: User;
username: string;
subStatus: Boolean;
OnIsSubscribe: (e: boolean) => void;
}) => {
const [isSubscribe, setIsSubscribe] = useState(() => subStatus);
const { t } = useTranslation('common_blog');

useEffect(() => {
setIsSubscribe(subStatus);
}, [subStatus]);

return (
<>
{user && user.isLoggedIn ? (
<>
{!isSubscribe ? (
{!subStatus ? (
<Button
size="sm"
className="w-full bg-blue-800 text-center hover:bg-blue-900"
data-testid="community-subscribe-button"
onClick={() => {
const nextIsSubscribe = !isSubscribe;
setIsSubscribe(nextIsSubscribe);
const nextIsSubscribe = !subStatus;
OnIsSubscribe(nextIsSubscribe);
if (nextIsSubscribe) {
transactionService.subscribe(username);
} else {
Expand All @@ -48,8 +44,8 @@ const SubscribeCommunity = ({
variant="outline"
className="group relative w-full text-center text-blue-800 hover:border-red-500 hover:text-red-500"
onClick={() => {
const nextIsSubscribe = !isSubscribe;
setIsSubscribe(nextIsSubscribe);
const nextIsSubscribe = !subStatus;
OnIsSubscribe(nextIsSubscribe);
transactionService.unsubscribe(username);
}}
>
Expand Down
5 changes: 4 additions & 1 deletion apps/blog/locales/en/common_blog.json
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,8 @@
}
},
"submit_page": {
"my_communities": "My Communities",
"others_communities": "Others Communities",
"disable_side": "Disable side-by-side editor",
"enable_side": "Enable side-by-side editor",
"string_must_contain": "String must contain at least {{num}} character(s)",
Expand Down Expand Up @@ -442,7 +444,8 @@
"delete_template": "Delete Template"
},
"category_selector": {
"tag_your_story": "Tag (up to 8 tags), the first tag is your main category.",
"required": "Required when post to My Blog",
"tag_your_story": "Tags up to 8",
"select_a_tag": "Select a tag",
"maximum_tag_length_is_24_characters": "Maximum tag length is 24 characters",
"use_limited_amount_of_categories": "Please use only {{amount}} tags",
Expand Down
5 changes: 4 additions & 1 deletion apps/blog/locales/es/common_blog.json
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,8 @@
}
},
"submit_page": {
"my_communities": "Mis Comunidades",
"others_communities": "Otras Comunidades",
"disable_side": "Deshabilitar el editor en paralelo",
"enable_side": "Habilitar el editor en paralelo",
"string_must_contain": "La cadena debe contener al menos {{num}} caracteres",
Expand Down Expand Up @@ -430,7 +432,8 @@
"delete_template": "Eliminar plantilla"
},
"category_selector": {
"tag_your_story": "Etiqueta (hasta 5 etiquetas), la primera etiqueta es tu principal categoría.",
"required": "Requerido al publicar en Mi Blog",
"tag_your_story": "Etiquetas hasta 8",
"select_a_tag": "Selecciona una etiqueta",
"maximum_tag_length_is_24_characters": "La longitud máxima de la etiqueta es de 24 caracteres",
"use_limited_amount_of_categories": "Por favor usa sólo {{amount}} categorías",
Expand Down
Loading

0 comments on commit 978383f

Please sign in to comment.