Skip to content

Commit

Permalink
feat(mention-list): Add useRef hook and scroll selected item into vie…
Browse files Browse the repository at this point in the history
…w in MentionList component
  • Loading branch information
cannarocks committed Jan 24, 2024
1 parent 088c911 commit 320d42a
Showing 1 changed file with 30 additions and 5 deletions.
35 changes: 30 additions & 5 deletions src/stories/chat/parts/mentionList.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
useState,
} from "react";
import type { SuggestionOptions, SuggestionProps } from "@tiptap/suggestion";
import { Card } from "../../cards";
import { Button } from "../../buttons/button";
import { styled } from "styled-components";
import { SuggestedUser } from "../_types";
import { MD } from "../../typography/typescale";
import { theme } from "../../theme";
import { ButtonArgs } from "../../buttons/button/_types";
import { getColor } from "../../theme/utils";

export type MentionListRef = {
onKeyDown: NonNullable<
Expand All @@ -31,20 +39,30 @@ const List = styled.div`
overflow-y: auto;
`;

const Item = styled(Button)`
const Item = styled(Button)<ButtonArgs & { isActive?: boolean }>`
display: flex;
align-items: flex-start;
justify-content: center;
flex-direction: column;
`;
${({ isActive }) =>
isActive &&
`
background-color: ${getColor(
theme.colors.primaryHue,
600,
undefined,
0.08
)};
`}
`;

type MentionListProps = SuggestionProps<SuggestedUser>;

export const MentionList = forwardRef<MentionListRef, MentionListProps>(
(props, ref) => {
const [selectedIndex, setSelectedIndex] = useState<number>(0);

const selectedRef = useRef<HTMLButtonElement>(null);
const selectItem = (index: number) => {
const item = props.items[index];

Expand All @@ -68,6 +86,11 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(
};

useEffect(() => setSelectedIndex(0), [props.items]);
useEffect(() => {
if (selectedRef.current) {
selectedRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [selectedIndex]);

useImperativeHandle(ref, () => ({
onKeyDown: ({ event }) => {
Expand Down Expand Up @@ -96,12 +119,14 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(
<List>
{props.items.length ? (
props.items.map((item, index) => (
<div className={index === selectedIndex ? 'selected' : ''}>
<div>
<Item
ref={index === selectedIndex ? selectedRef : undefined}
isBasic
isStretched
isAccent
isPill={false}
isActive={index === selectedIndex}
key={index}
onClick={() => selectItem(index)}
>
Expand Down

0 comments on commit 320d42a

Please sign in to comment.