Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/develop' into release/v4.0.0-b…
Browse files Browse the repository at this point in the history
…eta.16
  • Loading branch information
ChayanitBm committed Oct 25, 2024
2 parents 35a204c + 55dd372 commit ae33279
Show file tree
Hide file tree
Showing 33 changed files with 284 additions and 49 deletions.
74 changes: 73 additions & 1 deletion .storybook/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import path from 'path';
import { readdirSync } from 'fs';
import type { InlineConfig, Plugin } from 'vite';
import type { StorybookConfig } from '@storybook/react-vite';

const config: StorybookConfig = {
Expand All @@ -9,11 +12,80 @@ const config: StorybookConfig = {
'@storybook/addon-controls',
'@storybook/addon-viewport',
'@storybook/addon-toolbars',

'@storybook/addon-a11y',
],
framework: '@storybook/react-vite',
staticDirs: ['../static'],
viteFinal: async (config) => {
config.plugins?.push(
assetPlugin(config, {
markup: `[ICONS]`,
exclude: [/.*stories.*/],
assetDir: 'src/v4/icons',
storyFileName: 'icons.stories.tsx',
}),
);
return config;
},
};

export default config;

const assetPlugin: (
config: InlineConfig,
options: {
assetDir: string;
storyFileName: string;
exclude?: Array<RegExp>;
markup: string | RegExp;
},
) => Plugin = (config, { storyFileName, assetDir, exclude, markup }) => {
return {
enforce: 'pre',
name: 'vite-plugin-v4-icons',
transform(code, id) {
const rootDir = config.root!;

if (id.includes(storyFileName)) {
let icons = '',
imports = '';
readdirSync(path.join(rootDir, assetDir)).forEach((file) => {
if (file.match(/.*\.(tsx)/) && exclude?.every((ex) => !file.match(ex))) {
const fileName = file.replace(/.tsx/, '');
const source = {
relativePath: path.join(assetDir.replace(/.*src\//, ''), fileName),
path: path.join(rootDir, assetDir, file),
};

// eslint-disable-next-line @typescript-eslint/no-var-requires
const exportedAssets = require(source.path!);
const entries = Object.entries(exportedAssets);

entries.map(([key, _]) => {
const componentName = key === 'default' ? fileName : key;
imports +=
key == 'default'
? `import ${fileName} from "src/${source?.relativePath}";\n`
: `import {${key}} from "src/${source?.relativePath}";\n`;
icons += `
<button
key="${key}"
data-name="${componentName}"
>
<${componentName} width='25' height='25' />
<div>
<p>${componentName}</p>
<p>${source.relativePath.replace('/src', '')}</p>
</div>
</button>
`;
});
}
});

code = imports + code.replace(markup, icons);
}
return code;
},
};
};
2 changes: 1 addition & 1 deletion src/core/components/Modal/styles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { ReactNode } from 'react';
import styled, { css } from 'styled-components';
import { Close } from '~/icons';

export const CloseIcon = styled(Close).attrs<{ icon?: ReactNode }>({ width: 18, height: 18 })`
export const CloseIcon = styled(Close).attrs<{ icon?: ReactNode }>({ width: 20, height: 20 })`
padding: 0 6px;
cursor: pointer;
margin-left: auto;
Expand Down
34 changes: 32 additions & 2 deletions src/helpers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ import {
} from '@amityco/ts-sdk';
import isEmpty from 'lodash/isEmpty';

export type Mentioned = { userId: string; length: number; index: number; type: string };
export type Mentionees = Parameters<typeof CommentRepository.updateComment>[1]['mentionees'];
export type Mentioned = {
userId: string;
length: number;
index: number;
type: string;
displayName: string;
};
export type Mentionees = Amity.UserMention[];
export type Metadata = {
mentioned?: Mentioned[];
};
Expand Down Expand Up @@ -116,6 +122,7 @@ export function extractMetadata(
length: displayName.length - AT_SIGN_LENGTH,
type: 'user',
userId: id,
displayName,
})),
];

Expand Down Expand Up @@ -160,3 +167,26 @@ export function parseMentionsMarkup(
export function isNonNullable<TValue>(value: TValue | undefined | null): value is TValue {
return value != null;
}

export function reconstructMentions(
metadata?: Metadata,
mentionees?: Mentionees,
): { plainTextIndex: number; id: string; display: string }[] {
if (!metadata?.mentioned || mentionees?.length === 0) {
return [];
}

const userIds = mentionees?.find((mentionee) => mentionee.type === 'user')?.userIds || [];

return metadata?.mentioned?.map((mention, index) => {
const id = userIds[index];
const displayName = mention.displayName;
const display = '@' + (displayName ?? id);

return {
plainTextIndex: mention.index,
id,
display,
};
});
}
7 changes: 3 additions & 4 deletions src/social/components/post/Editor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,19 @@ import { PostEditorContainer, Footer, ContentContainer, PostButton } from './sty
import { usePostEditor } from './usePostEditor';

interface PostEditorProps {
postId?: string;
post: Amity.Post;
onSave: () => void;
className?: string;
placeholder?: string;
}

const PostEditor = ({
postId,
post,
placeholder = "What's going on...",
className,
onSave,
}: PostEditorProps) => {
const {
post,
markup,
onChange,
queryMentionees,
Expand All @@ -30,7 +29,7 @@ const PostEditor = ({
isEmpty,
handleSave,
} = usePostEditor({
postId,
post,
onSave,
});

Expand Down
6 changes: 3 additions & 3 deletions src/social/components/post/Editor/usePostEditor.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { PostRepository } from '@amityco/ts-sdk';
import { useMemo, useState } from 'react';
import { parseMentionsMarkup } from '~/helpers/utils';
import { parseMentionsMarkup, reconstructMentions } from '~/helpers/utils';
import usePost from '~/social/hooks/usePost';
import usePostByIds from '~/social/hooks/usePostByIds';
import useSocialMention from '~/social/hooks/useSocialMention';

export const usePostEditor = ({ postId, onSave }: { postId?: string; onSave: () => void }) => {
const post = usePost(postId);
export const usePostEditor = ({ post, onSave }: { post: Amity.Post; onSave: () => void }) => {
const initialChildrenPosts = usePostByIds(post?.children);
const { text, markup, mentions, mentionees, metadata, clearAll, onChange, queryMentionees } =
useSocialMention({
Expand All @@ -18,6 +17,7 @@ export const usePostEditor = ({ postId, onSave }: { postId?: string; onSave: ()
typeof post?.data === 'string' ? post?.data : (post?.data as Amity.ContentDataText)?.text,
post?.metadata,
),
remoteMentions: reconstructMentions(post?.metadata, post?.mentionees),
});

// List of the children posts removed - these will be deleted on save.
Expand Down
4 changes: 2 additions & 2 deletions src/social/components/post/Post/DefaultPostRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -320,13 +320,13 @@ const DefaultPostRenderer = (props: DefaultPostRendererProps) => {
</ReviewButtonsContainer>
)}

{isEditing && (
{isEditing && post && (
<Modal
data-qa-anchor="post-editor-modal"
title={formatMessage({ id: 'post.editPost' })}
onCancel={closeEditingPostModal}
>
<PostEditor postId={post?.postId} onSave={closeEditingPostModal} />
<PostEditor post={post} onSave={closeEditingPostModal} />
</Modal>
)}
</>
Expand Down
7 changes: 4 additions & 3 deletions src/social/hooks/useSocialMention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ interface UseSocialMentionProps {
targetType?: 'user' | 'community' | string;
remoteText?: string;
remoteMarkup?: string;
remoteMentions?: { plainTextIndex: number; id: string; display: string }[];
}

export type QueryMentioneesFnType = (query?: string) => Promise<
Expand All @@ -24,15 +25,15 @@ const useSocialMention = ({
targetType,
remoteText,
remoteMarkup,
remoteMentions = [],
}: UseSocialMentionProps) => {
const isCommunityFeed = targetType === 'community';
const community = useCommunity(targetId);

const [text, setText] = useState(remoteText ?? '');
const [markup, setMarkup] = useState(remoteMarkup ?? remoteText);
const [mentions, setMentions] = useState<
{ plainTextIndex: number; id: string; display: string }[]
>([]);
const [mentions, setMentions] =
useState<{ plainTextIndex: number; id: string; display: string }[]>(remoteMentions);

useEffect(() => {
setText(remoteText || '');
Expand Down
28 changes: 28 additions & 0 deletions src/v4/icons/icons.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import React from 'react';
import styles from './icons.style.module.css';

export default {
title: 'V4/Icons',
};

export const Default = {
render: () => {
return (
<section
className={styles.container}
onClick={(e) => {
if (e.target instanceof HTMLButtonElement) {
const iconName = e.target.getAttribute('data-name');
if (iconName) {
navigator.clipboard.writeText(iconName).then(() => {
alert(`${iconName} copied.`);
});
}
}
}}
>
[ICONS]
</section>
);
},
};
26 changes: 26 additions & 0 deletions src/v4/icons/icons.style.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
.container {
gap: 2rem;
width: 100%;
padding: 3rem;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr));
background: var(--asc-color-background-default);
}

.container button {
width: 100%;
padding: 1rem;
display: flex;
cursor: pointer;
align-items: center;
border-radius: 0.5rem;
flex-direction: column;
justify-content: center;
color: var(--asc-color-base-default);
background: var(--asc-color-secondary-shade5);
border: 1px solid var(--asc-color-secondary-shade4);
}

.container button svg {
fill: var(--asc-color-base-default);
}
4 changes: 3 additions & 1 deletion src/v4/social/components/Comment/Comment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,9 @@ export const Comment = ({
componentId={componentId}
timestamp={comment.createdAt}
/>
{comment.createdAt !== comment.editedAt && ' (edited)'}
<span data-qa-anchor={`${pageId}/${componentId}/comment_edited_text`}>
{comment.createdAt !== comment.editedAt && ' (edited)'}
</span>
</Typography.Caption>

<div onClick={handleLike}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export const CommentComposer = ({
data-qa-anchor={`${pageId}/${componentId}/comment_composer_post`}
isDisabled={!textValue?.data?.text}
className={styles.commentComposer__button}
onPress={() => mutateAsync({ params: textValue })}
onPressStart={() => mutateAsync({ params: textValue })}
>
<Typography.Body>Post</Typography.Body>
</Button>
Expand Down
11 changes: 9 additions & 2 deletions src/v4/social/components/CommentComposer/CommentInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ export const CommentInput = forwardRef<CommentInputRef, CommentInputProps>(
const root = $getRoot();
root.clear();
});
setTimeout(() => {
editorRef.current?.blur();
}, 500);
};

useImperativeHandle(ref, () => ({
Expand All @@ -202,7 +205,6 @@ export const CommentInput = forwardRef<CommentInputRef, CommentInputProps>(
}}
>
<div
data-qa-anchor={accessibilityId}
className={styles.editorContainer}
style={
{
Expand All @@ -211,7 +213,12 @@ export const CommentInput = forwardRef<CommentInputRef, CommentInputProps>(
}
>
<RichTextPlugin
contentEditable={<ContentEditable className={styles.editorEditableContent} />}
contentEditable={
<ContentEditable
data-qa-anchor={accessibilityId}
className={styles.editorEditableContent}
/>
}
placeholder={
placehoder ? <div className={styles.editorPlaceholder}>{placehoder}</div> : null
}
Expand Down
5 changes: 4 additions & 1 deletion src/v4/social/components/PostContent/PostContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,10 @@ export const PostContent = ({
) : null}
<Timestamp timestamp={post.createdAt} />
{post.createdAt !== post.editedAt && (
<Typography.Caption className={styles.postContent__bar__information__editedTag}>
<Typography.Caption
data-qa-anchor={`${pageId}/${componentId}/post_edited_text`}
className={styles.postContent__bar__information__editedTag}
>
(edited)
</Typography.Caption>
)}
Expand Down
4 changes: 3 additions & 1 deletion src/v4/social/components/ReplyComment/ReplyComment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,9 @@ const PostReplyComment = ({ pageId = '*', community, comment }: ReplyCommentProp
componentId={componentId}
timestamp={comment.createdAt}
/>
{comment.createdAt !== comment.editedAt && ' (edited)'}
<span data-qa-anchor={`${pageId}/${componentId}/reply_comment_edited_text`}>
{comment.createdAt !== comment.editedAt && ' (edited)'}
</span>
</Typography.Caption>
<div onClick={handleLike}>
<Typography.CaptionBold
Expand Down
2 changes: 1 addition & 1 deletion src/v4/social/components/StoryTab/StoryTabCommunity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const StoryTabCommunityFeed: React.FC<StoryTabCommunityFeedProps> = ({
const { community } = useCommunityInfo(communityId);

const { currentUserId, client } = useSDK();
const { user } = useUser(currentUserId);
const { user } = useUser({ userId: currentUserId });
const isGlobalAdmin = isAdmin(user?.roles);
const hasStoryPermission = isGlobalAdmin || checkStoryPermission(client, communityId);
const hasStories = stories?.length > 0;
Expand Down
Loading

0 comments on commit ae33279

Please sign in to comment.