Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Active post modes #560

Merged
merged 4 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 47 additions & 17 deletions src/components/Tabber/Tabber.tsx
Luiginicoletti marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/* eslint-disable @typescript-eslint/no-unnecessary-condition -- to avoid lint error that will be remove soon on a changhe of how the data will be dealed */
import { ChangeEvent, ReactNode, useState } from 'react';
import { ChangeEvent, ReactNode, useEffect, useState } from 'react';

import { Account } from '~services/api/accounts/accounts.types';
import { PostMode } from '~services/api/social-media/social-media.types';
import { AccountPost, useAccountStore } from '~stores/useAccountStore';
import { useSocialMediaStore } from '~stores/useSocialMediaStore/useSocialMediaStore';

import { accountsToTabs } from './utils';
Expand All @@ -15,27 +17,49 @@ import Tabs from './Tabs/Tabs';

import { Tab, TabId, Tabs as TabsType } from './Tabber.types';

const makeId = (account: AccountPost): `${string}-${string}` =>
`${account.id}-${account.socialMediaId}`;

function Tabber(): ReactNode {
const { accounts, socialMedias } = useSocialMediaStore();
const { accounts } = useAccountStore();
const { socialMedias } = useSocialMediaStore();

const [currentTab, setCurrentTab] = useState<TabId>(
`${accounts.data?.[0]?.id}-${accounts.data?.[0]?.socialMediaId}`
);

const [tabs, setTabs] = useState<TabsType>(
accountsToTabs(accounts.data ?? [], socialMedias)
makeId(accounts[0] || {})
);

const currentPostMode = socialMedias
.get(currentTab.split('-')[1])
?.postModes.find(
(postMode: PostMode) => postMode.id === tabs[currentTab].postModeOnView
const [tabs, setTabs] = useState<TabsType>({});

useEffect(() => {
if (accounts.length > 0) {
const initialTabId = accounts.length > 0 ? makeId(accounts[0]) : '';
setCurrentTab(initialTabId as TabId);
Comment on lines +33 to +35
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Se há o if para cair no initialTabId, o accounts.length > 0 vai ser sempre true, não há necessidade de fazer a mesma verificação dentro do if

Suggested change
if (accounts.length > 0) {
const initialTabId = accounts.length > 0 ? makeId(accounts[0]) : '';
setCurrentTab(initialTabId as TabId);
if (accounts.length > 0) {
const initialTabId = makeId(accounts[0]);
setCurrentTab(initialTabId);

setTabs(accountsToTabs(accounts, socialMedias));
} else {
setTabs({});
setCurrentTab('' as unknown as TabId);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Necessário esse unknown? Por que?

Suggested change
setCurrentTab('' as unknown as TabId);
setCurrentTab('' as TabId);

}
}, [accounts, socialMedias]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O socialMedias precisa ficar nas dependências do useEffect? O tab não tem que ser setado apenas quando accounts mudar, que é na troca do activateSocialTab?


const getCurrentPostMode = (): PostMode | undefined => {
if (!currentTab) return;
const [, socialMediaId] = currentTab.split('-');
const socialMedia = socialMedias.get(socialMediaId);
if (!socialMedia) return;
const postModeOnView = tabs[currentTab]?.postModeOnView;
return socialMedia.postModes.find(
(postMode: PostMode) => postMode.id === postModeOnView
);
};

const currentPostMode = getCurrentPostMode();

const handleContentChange = (e: ChangeEvent<HTMLTextAreaElement>): void => {
if (!currentTab || !tabs[currentTab]) return;
const tab = { ...tabs[currentTab] };
const postId = tab.postModeOnView;
tab.posts[postId].text = e.target.value;
if (tab.posts[postId]) {
tab.posts[postId].text = e.target.value;
}

setTabs({
...tabs,
Expand All @@ -48,6 +72,7 @@ function Tabber(): ReactNode {
};

const changePostMode = (postMode: PostMode): void => {
if (!currentTab || !tabs[currentTab]) return;
const tab = { ...tabs[currentTab] };
tab.postModeOnView = postMode.id;

Expand All @@ -61,6 +86,10 @@ function Tabber(): ReactNode {
});
};

if (!currentTab || !tabs[currentTab]) {
return <div>No tabs available</div>;
}

return (
<div>
<Tabs
Expand All @@ -72,21 +101,22 @@ function Tabber(): ReactNode {
<div className={scss.postModesContainer}>
<PostModes
currentPostModeId={tabs[currentTab].postModeOnView}
currentTab={tabs[currentTab].account}
currentTab={tabs[currentTab].account as Account}
onChangePostMode={changePostMode}
/>
<MainComposerBase
accountId={tabs[currentTab].account.id.toString()}
onChange={handleContentChange}
postMode={currentPostMode}
postMode={currentPostMode ?? undefined}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aqui já vai ser retornado PostMode ou undefined

Suggested change
postMode={currentPostMode ?? undefined}
postMode={currentPostMode}

value={
tabs[currentTab].posts[tabs[currentTab].postModeOnView].text ?? ''
tabs[currentTab].posts[tabs[currentTab].postModeOnView]?.text ??
''
Comment on lines +112 to +113
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seria desejável colocar tabs[currentTab].posts[tabs[currentTab].postModeOnView]?.text ?? em uma variável e trocar os locais onde é chamada, seria uma sugestão, algo como:

Suggested change
tabs[currentTab].posts[tabs[currentTab].postModeOnView]?.text ??
''
postModeOnViewText ?? ''

(reveja o nome da variável)

}
/>
</div>
<div className={scss.previewContainer}>
<Preview>
{tabs[currentTab].posts[tabs[currentTab].postModeOnView].text}
{tabs[currentTab].posts[tabs[currentTab].postModeOnView]?.text}
</Preview>
</div>
</div>
Expand Down
3 changes: 2 additions & 1 deletion src/components/Tabber/Tabber.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import {
Post,
SocialMedia,
} from '~services/api/social-media/social-media.types';
import { AccountPost } from '~stores/useAccountStore';

export type TabId = `${Account['socialMediaId']}-${SocialMedia['id']}`;

export type Tab = {
account: Account;
account: AccountPost;
id: TabId;
postModeOnView: SocialMedia['postModes'][number]['id'];
posts: Record<SocialMedia['postModes'][number]['id'], Post['data']>;
Expand Down
2 changes: 1 addition & 1 deletion src/components/Tabber/Tabs/Tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function Tabs(props: TabsProps): ReactNode {
key={tabId}
onClick={() => props.onChangeTab(tab, tabId)}
>
{renderSocialMediaIcon(tab.account)}
{renderSocialMediaIcon(tab.account as Account)}
<span className={scss.tabTitle}>{tab.account.userName}</span>
</div>
);
Expand Down
34 changes: 25 additions & 9 deletions src/components/Tabber/utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
import { Account } from '~services/api/accounts/accounts.types';
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
// @ts-nocheck
import { Account } from '~services/api/accounts/accounts.types';
import { SocialMedia } from '~services/api/social-media/social-media.types';
import { AccountPost } from '~stores/useAccountStore';
import { SocialMediaState } from '~stores/useSocialMediaStore/useSocialMediaStore.types';

import { Tab, TabId, Tabs } from './Tabber.types';

export const getFirstPostModeId = (
socialMedia: SocialMedia
): SocialMedia['postModes'][number]['id'] => socialMedia.postModes[0].id;
): SocialMedia['postModes'][number]['id'] => {
if (!socialMedia.postModes || socialMedia.postModes.length === 0) {
throw new Error('Invalid social media or no post modes available');
}
return socialMedia.postModes[0].id;
};

export const createTabId = (account: Account): TabId =>
`${account.id}-${account.socialMediaId}`;
export const createTabId = (account: Account): TabId => {
if (!account) throw new Error('Account is required to create a TabId');
return `${account.id}-${account.socialMediaId}`;
};

export const accountsToTabs = (
accounts: Account[],
accounts: AccountPost[],
socialMedias: SocialMediaState['socialMedias']
): Record<TabId, Tab> =>
accounts.reduce<Tabs>((acc, account) => {
const tabId = createTabId(account);
): Record<TabId, Tab> => {
if (!accounts || accounts.length === 0) {
return {};
}

return accounts.reduce<Tabs>((acc, account) => {
const tabId = createTabId(account as Account);
const socialMedia = socialMedias.get(account.socialMediaId);
if (!socialMedia) throw new Error('No social media found');
if (!socialMedia) throw new Error('No social media found for the account');

const postModeOnView = getFirstPostModeId(socialMedia);

Expand All @@ -33,3 +48,4 @@ export const accountsToTabs = (

return acc;
}, {});
};
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const mockList: StoreAccount[] = [
avatar: 'https://example.com/avatar1.jpg',
expiresAt: '2022-12-31T23:59:59Z',
generatedAt: '2022-01-01T00:00:00Z',
id: 1,
id: '1',
socialMediaId: 'social1',
token: 'token1',
userName: 'User 1',
Expand All @@ -20,7 +20,7 @@ const mockList: StoreAccount[] = [
avatar: 'https://example.com/avatar2.jpg',
expiresAt: '2023-12-31T23:59:59Z',
generatedAt: '2023-01-01T00:00:00Z',
id: 2,
id: '2',
socialMediaId: 'social2',
token: 'token2',
userName: 'User 2',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const accounts: SocialAccordionProps['accounts'] = [
avatar: 'http://someurl.com',
expiresAt: '2022-12-31T23:59:59Z',
generatedAt: '2022-01-01T00:00:00Z',
id: 21_231,
id: '21_231',
socialMediaId: '123',
token: 'token1',
userName: 'jhon doe',
Expand All @@ -19,7 +19,7 @@ const accounts: SocialAccordionProps['accounts'] = [
avatar: 'http://someurl.com',
expiresAt: '2022-12-31T23:59:59Z',
generatedAt: '2022-01-01T00:00:00Z',
id: 1234,
id: '1234',
socialMediaId: '456',
token: 'token2',
userName: 'joão da silva',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { ReactNode, useState } from 'react';

import { useAccountStore } from '~stores/useAccountStore';
import { useSocialMediaStore } from '~stores/useSocialMediaStore/useSocialMediaStore';
import { StoreAccount } from '~stores/useSocialMediaStore/useSocialMediaStore.types';

import Accordion from '~components/Accordion/Accordion';
import { AccountCard } from '~components/AccountCard/AccountCard';
Expand All @@ -15,9 +17,15 @@ import { SocialAccordionProps } from './SocialAccordion.type';
function SocialAccordion(props: SocialAccordionProps): ReactNode {
const [isOpen, setIsOpen] = useState(false);
const { socialMedias } = useSocialMediaStore();
const { addAccount, removeAccount } = useAccountStore();

const handleOpenAccordion = (): void => setIsOpen((prev) => !prev);

const activateSocialTab = (enabled: boolean, account: StoreAccount): void => {
if (enabled) addAccount(account);
if (!enabled) removeAccount(account.id);
};

const renderError = (): ReactNode => (
<span className={scss.error}>error!!!!</span>
);
Expand All @@ -28,6 +36,7 @@ function SocialAccordion(props: SocialAccordionProps): ReactNode {
<AccountCard
avatarURL={account.avatar}
isEnabled={account.valid}
onEnableChange={(enable) => activateSocialTab(enable, account)}
username={account.userName}
/>
</li>
Expand Down
2 changes: 1 addition & 1 deletion src/services/api/accounts/accounts.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export type Account = {
avatar: string;
expiresAt: string;
generatedAt: string;
id: number;
id: string;
socialMediaId: string;
token: string;
userName: string;
Expand Down
37 changes: 37 additions & 0 deletions src/stores/useAccountStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { create } from './zustand';

import { StoreAccount } from './useSocialMediaStore/useSocialMediaStore.types';

export type AccountPost = Pick<
StoreAccount,
'id' | 'socialMediaId' | 'userName'
>;

type StoreState = {
accounts: AccountPost[];
addAccount: (account: StoreAccount) => void;
removeAccount: (accountId: string) => void;
Alecell marked this conversation as resolved.
Show resolved Hide resolved
};

export const useAccountStore = create<StoreState>((set) => ({
accounts: [],

addAccount: (account: StoreAccount): void => {
set((state) => ({
accounts: [
...state.accounts,
{
id: account.id,
socialMediaId: account.socialMediaId,
userName: account.userName,
},
],
}));
},

removeAccount: (accountId: string): void => {
Alecell marked this conversation as resolved.
Show resolved Hide resolved
set((state) => ({
accounts: state.accounts.filter((account) => account.id !== accountId),
}));
},
}));
Loading