Skip to content
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
6 changes: 6 additions & 0 deletions .changeset/dark-pots-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@lg-chat/message-feed': minor
---

- [LG-5932](https://jira.mongodb.org/browse/LG-5932): Refactor to use `CompoundComponent` pattern
- [LG-5934](https://jira.mongodb.org/browse/LG-5934): add `MessageFeedProvider` and `useMessageFeedContext`
1 change: 1 addition & 0 deletions chat/message-feed/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
},
"dependencies": {
"@leafygreen-ui/button": "workspace:^",
"@leafygreen-ui/compound-component": "workspace:^",
"@leafygreen-ui/emotion": "workspace:^",
"@leafygreen-ui/icon": "workspace:^",
"@leafygreen-ui/lib": "workspace:^",
Expand Down
212 changes: 111 additions & 101 deletions chat/message-feed/src/MessageFeed/MessageFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import React, {
} from 'react';
import { useInView } from 'react-intersection-observer';

import { CompoundComponent } from '@leafygreen-ui/compound-component';
import LeafyGreenProvider, {
useDarkMode,
} from '@leafygreen-ui/leafygreen-provider';
Expand All @@ -21,109 +22,118 @@ import {
} from './MessageFeed.styles';
import { MessageFeedProps } from '.';

export const MessageFeed = forwardRef(
(
{ children, darkMode: darkModeProp, className, ...rest }: MessageFeedProps,
ref: ForwardedRef<HTMLDivElement>,
) => {
const { darkMode, theme } = useDarkMode(darkModeProp);

const scrollContainerRef = useRef<HTMLDivElement | null>(null);
const scrollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

const [showScrollButton, setShowScrollButton] = useState(false);

const { ref: topInterceptRef, inView: isTopInView } = useInView({
initialInView: true,
root: scrollContainerRef.current,
threshold: 0,
});
const { ref: bottomInterceptRef, inView: isBottomInView } = useInView({
initialInView: true,
root: scrollContainerRef.current,
threshold: 0,
});

const scrollToLatest = useCallback(() => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTo(
0,
scrollContainerRef.current.scrollHeight,
);
}
}, []);

useEffect(() => {
const scrollElement = scrollContainerRef.current;
if (!scrollElement) return;

const isScrolledToEnd = () => {
if (!scrollContainerRef.current) return true;
const { scrollHeight, scrollTop, clientHeight } =
scrollContainerRef.current;
// Add a small buffer (2px) to account for floating point differences
return scrollHeight - scrollTop - clientHeight <= 2;
};

// Handle scroll events
const handleScroll = () => {
// Clear any existing timeout
if (scrollTimerRef.current) {
clearTimeout(scrollTimerRef.current);
export const MessageFeed = CompoundComponent(
// eslint-disable-next-line react/display-name
forwardRef(
(
{
children,
darkMode: darkModeProp,
className,
...rest
}: MessageFeedProps,
ref: ForwardedRef<HTMLDivElement>,
) => {
const { darkMode, theme } = useDarkMode(darkModeProp);

const scrollContainerRef = useRef<HTMLDivElement | null>(null);
const scrollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

const [showScrollButton, setShowScrollButton] = useState(false);

const { ref: topInterceptRef, inView: isTopInView } = useInView({
initialInView: true,
root: scrollContainerRef.current,
threshold: 0,
});
const { ref: bottomInterceptRef, inView: isBottomInView } = useInView({
initialInView: true,
root: scrollContainerRef.current,
threshold: 0,
});

const scrollToLatest = useCallback(() => {
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTo(
0,
scrollContainerRef.current.scrollHeight,
);
}

// Wait until scroll animation completes This avoids a brief flicker
// when the user scrolls to the bottom
const scrollDuration = 100;
scrollTimerRef.current = setTimeout(() => {
setShowScrollButton(!isScrolledToEnd());
}, scrollDuration);
};

scrollElement.addEventListener('scroll', handleScroll);

return () => {
scrollElement.removeEventListener('scroll', handleScroll);
if (scrollTimerRef.current) {
clearTimeout(scrollTimerRef.current);
}, []);

useEffect(() => {
const scrollElement = scrollContainerRef.current;
if (!scrollElement) return;

const isScrolledToEnd = () => {
if (!scrollContainerRef.current) return true;
const { scrollHeight, scrollTop, clientHeight } =
scrollContainerRef.current;
// Add a small buffer (2px) to account for floating point differences
return scrollHeight - scrollTop - clientHeight <= 2;
};

// Handle scroll events
const handleScroll = () => {
// Clear any existing timeout
if (scrollTimerRef.current) {
clearTimeout(scrollTimerRef.current);
}

// Wait until scroll animation completes This avoids a brief flicker
// when the user scrolls to the bottom
const scrollDuration = 100;
scrollTimerRef.current = setTimeout(() => {
setShowScrollButton(!isScrolledToEnd());
}, scrollDuration);
};

scrollElement.addEventListener('scroll', handleScroll);

return () => {
scrollElement.removeEventListener('scroll', handleScroll);
if (scrollTimerRef.current) {
clearTimeout(scrollTimerRef.current);
}
};
}, []);

useEffect(() => {
if (!showScrollButton) {
scrollToLatest();
}
};
}, []);

useEffect(() => {
if (!showScrollButton) {
scrollToLatest();
}
}, [children, showScrollButton, scrollToLatest]);

return (
<LeafyGreenProvider darkMode={darkMode}>
<div
{...rest}
className={getWrapperStyles({
className,
hasBottomShadow: !isBottomInView,
hasTopShadow: !isTopInView,
theme,
})}
ref={ref}
>
<div className={scrollContainerStyles} ref={scrollContainerRef}>
{/* Empty span element used to track if container can scroll up */}
<span className={interceptStyles} ref={topInterceptRef} />
{children}
{/* Empty span element used to track if container can scroll down */}
<span className={interceptStyles} ref={bottomInterceptRef} />
}, [children, showScrollButton, scrollToLatest]);

return (
<LeafyGreenProvider darkMode={darkMode}>
<div
{...rest}
className={getWrapperStyles({
className,
hasBottomShadow: !isBottomInView,
hasTopShadow: !isTopInView,
theme,
})}
ref={ref}
>
<div className={scrollContainerStyles} ref={scrollContainerRef}>
{/* Empty span element used to track if container can scroll up */}
<span className={interceptStyles} ref={topInterceptRef} />
{children}
{/* Empty span element used to track if container can scroll down */}
<span className={interceptStyles} ref={bottomInterceptRef} />
</div>
<ScrollToLatestButton
darkMode={darkMode}
onClick={scrollToLatest}
visible={showScrollButton}
/>
</div>
<ScrollToLatestButton
darkMode={darkMode}
onClick={scrollToLatest}
visible={showScrollButton}
/>
</div>
</LeafyGreenProvider>
);
</LeafyGreenProvider>
);
},
),
{
displayName: 'MessageFeed',
Copy link
Collaborator

Choose a reason for hiding this comment

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

do we need to add a key here? I dont have too much context on the larger project but im not sure where MessageFeedSubcomponentProperty.InitialMessage should be going

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes! I will add it in the next PR.

},
);

MessageFeed.displayName = 'MessageFeed';
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import React from 'react';

import { isReact17, renderHook } from '@leafygreen-ui/testing-lib';

import {
MessageFeedProvider,
useMessageFeedContext,
} from './MessageFeedContext';
import { MessageFeedProviderProps } from './MessageFeedContext.types';

const renderMessageFeedProvider = (
props?: Partial<MessageFeedProviderProps>,
) => {
const defaultProps: MessageFeedProviderProps = {
shouldHideInitialMessage: false,
};

const { result } = renderHook(() => useMessageFeedContext(), {
wrapper: ({ children }: { children?: React.ReactNode }) => (
<MessageFeedProvider {...defaultProps} {...props}>
{children}
</MessageFeedProvider>
),
});

return { result };
};
describe('useMessageFeedContext', () => {
test('should return the correct context', () => {
const { result } = renderMessageFeedProvider();
expect(result.current.shouldHideInitialMessage).toBe(false);
});

test('should return the correct context when props are provided', () => {
const { result } = renderMessageFeedProvider({
shouldHideInitialMessage: true,
});
expect(result.current.shouldHideInitialMessage).toBe(true);
});

test('should throw an error when used outside the provider', () => {
/**
* The version of `renderHook` imported from "@testing-library/react-hooks" (used in React 17)
* has an error boundary, and doesn't throw errors as expected:
* https://github.com/testing-library/react-hooks-testing-library/blob/main/src/index.ts#L5
*/
if (isReact17()) {
const { result } = renderHook(() => useMessageFeedContext());
expect(result.error.message).toEqual(
'useMessageFeedContext must be used within a MessageFeedProvider',
);
} else {
expect(() => {
renderHook(() => useMessageFeedContext());
}).toThrow(
'useMessageFeedContext must be used within a MessageFeedProvider',
);
}
});
});
33 changes: 33 additions & 0 deletions chat/message-feed/src/MessageFeedContext/MessageFeedContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React, { createContext, useContext } from 'react';

import {
MessageFeedContextType,
MessageFeedProviderProps,
} from './MessageFeedContext.types';

export const MessageFeedContext = createContext<MessageFeedContextType | null>(
null,
);

export const MessageFeedProvider = ({
children,
shouldHideInitialMessage = false,
}: MessageFeedProviderProps) => {
return (
<MessageFeedContext.Provider value={{ shouldHideInitialMessage }}>
{children}
</MessageFeedContext.Provider>
);
};

export const useMessageFeedContext = () => {
const context = useContext(MessageFeedContext);

if (!context) {
throw new Error(
'useMessageFeedContext must be used within a MessageFeedProvider',
);
}

return context;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { PropsWithChildren } from 'react';

export interface MessageFeedContextType {
shouldHideInitialMessage: boolean;
}

export interface MessageFeedProviderProps
extends PropsWithChildren<MessageFeedContextType> {}
8 changes: 8 additions & 0 deletions chat/message-feed/src/MessageFeedContext/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export {
MessageFeedProvider,
useMessageFeedContext,
} from './MessageFeedContext';
export type {
MessageFeedContextType,
MessageFeedProviderProps,
} from './MessageFeedContext.types';
13 changes: 13 additions & 0 deletions chat/message-feed/src/shared.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Static property names used to identify MessageFeed compound components.
* These are implementation details for the compound component pattern and should not be exported.
*/
export const MessageFeedSubcomponentProperty = {
InitialMessage: 'isLGMessageFeedInitialMessage',
} as const;

/**
* Type representing the possible static property names for MessageFeed subcomponents.
*/
export type MessageFeedSubcomponentProperty =
(typeof MessageFeedSubcomponentProperty)[keyof typeof MessageFeedSubcomponentProperty];
3 changes: 3 additions & 0 deletions chat/message-feed/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
{
"path": "../../packages/button"
},
{
"path": "../../packages/compound-component"
},
{
"path": "../../packages/emotion"
},
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading