1 "use client"
2
3 import React, { useEffect, useId, useRef, useState } from "react"
4 import { createPortal } from "react-dom"
5 import clsx from "clsx"
6 import { Tooltip as ReactTooltip } from "react-tooltip"
7 import "react-tooltip/dist/react-tooltip.css"
8
9 export type SidebarItemTitleProps = {
10 title: string
11 isTitleOneWord: boolean
12 } & React.HTMLAttributes<HTMLSpanElement>
13
14 /**
15 * Renders a sidebar item's title. Single-word titles are truncated with an
16 * ellipsis, and when a title is actually truncated a tooltip showing the full
17 * title is displayed after hovering over it for a second.
18 */
19 export const SidebarItemTitle = ({
20 title,
21 isTitleOneWord,
22 className,
23 ...props
24 }: SidebarItemTitleProps) => {
25 const titleRef = useRef<HTMLSpanElement>(null)
26 const tooltipId = useId()
27 const [isTruncated, setIsTruncated] = useState(false)
28
29 useEffect(() => {
30 const element = titleRef.current
31 if (!element || !isTitleOneWord) {
32 setIsTruncated(false)
33 return
34 }
35
36 const checkTruncation = () => {
37 setIsTruncated(element.scrollWidth > element.clientWidth)
38 }
39
40 checkTruncation()
41
42 if (typeof ResizeObserver === "undefined") {
43 return
44 }
45
46 const resizeObserver = new ResizeObserver(checkTruncation)
47 resizeObserver.observe(element)
48
49 return () => resizeObserver.disconnect()
50 }, [title, isTitleOneWord])
51
52 return (
53 <>
54 <span
55 ref={titleRef}
56 // `truncate` sets `overflow: hidden`, which makes this span a scroll
57 // container. Combined with the sidebar's `aside * { overscroll-behavior-y:
58 // contain }` rule, hovering a truncated title would trap the wheel and
59 // prevent the sidebar from scrolling, so reset overscroll behavior here.
60 className={clsx(
61 isTitleOneWord && "truncate overscroll-y-auto",
62 className
63 )}
64 data-testid="sidebar-item-title"
65 data-tooltip-id={isTruncated ? tooltipId : undefined}
66 data-tooltip-content={isTruncated ? title : undefined}
67 {...props}
68 >
69 {title}
70 </span>
71 {isTruncated &&
72 typeof document !== "undefined" &&
73 createPortal(
74 <ReactTooltip
75 id={tooltipId}
76 delayShow={500}
77 place="right"
78 className={clsx(
79 "!text-compact-x-small !shadow-elevation-tooltip dark:!shadow-elevation-tooltip-dark !rounded-docs_DEFAULT",
80 "!py-docs_0.25 !z-[399] hidden !px-docs_0.5 lg:block",
81 "!bg-medusa-bg-component",
82 "!text-medusa-fg-base text-center",
83 "!max-w-[240px] !break-words"
84 )}
85 wrapper="span"
86 noArrow={true}
87 positionStrategy="fixed"
88 opacity={1}
89 />,
90 document.body
91 )}
92 </>
93 )
94 }