🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
💄 style(sidebar): scroll clipped topic titles on hover instead of a tooltip (#23062)
YuTengjing7cb42100c58a
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsxindex eaae8fd3388..5f21648ebc4 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx@@ -635,6 +635,7 @@ const TopicItemRow = memo<TopicItemRowProps>(<TopicItemContextMenu fav={fav} id={id} status={status} title={title}><NavItemdraggable+ titleMarqueeactive={isTopicActive}description={workingDirectoryNode}href={href}diff --git a/src/features/NavPanel/components/NavItem.tsx b/src/features/NavPanel/components/NavItem.tsxindex 328c4f67f0b..835908bc70f 100644--- a/src/features/NavPanel/components/NavItem.tsx+++ b/src/features/NavPanel/components/NavItem.tsx@@ -19,6 +19,15 @@ import { memo } from 'react';import { isModifierClick } from '@/utils/navigation';import { type LazyActions, useLazyActions } from './useLazyActions';+import {+ NAV_ITEM_ACTIONS_INSET_VAR,+ NAV_ITEM_CONTENT_FADE,+ TITLE_MARQUEE_FADE,+ TITLE_MARQUEE_FADE_END_VAR,+ TITLE_MARQUEE_FADE_START_VAR,+ useTitleMarquee,+ useTitleMarqueeAvailable,+} from './useTitleMarquee';const ACTION_CLASS_NAME = 'nav-item-actions';const CONTENT_CLASS_NAME = 'nav-item-content';@@ -29,14 +38,14 @@ const styles = createStaticStyles(({ css }) => ({Each extra icon adds its 24px plus the 2px gap. The focus guards and thearia-owns portal marker an open menu inserts beside its trigger are noticons, so they are not counted. */- --nav-item-actions-inset: 28px;+ ${NAV_ITEM_ACTIONS_INSET_VAR}: 28px;user-select: none;overflow: hidden;min-width: 32px;&:has(.${ACTION_CLASS_NAME} > :nth-child(2 of :not([data-base-ui-focus-guard], [aria-owns]))) {- --nav-item-actions-inset: 54px;+ ${NAV_ITEM_ACTIONS_INSET_VAR}: 54px;}/* focus-visible, not focus-within: closing a dropdown hands focus back to its@@ -54,8 +63,8 @@ const styles = createStaticStyles(({ css }) => ({.${CONTENT_CLASS_NAME} {mask-image: linear-gradient(to right,- black calc(100% - var(--nav-item-actions-inset) - 28px),- transparent calc(100% - var(--nav-item-actions-inset))+ black calc(100% - var(${NAV_ITEM_ACTIONS_INSET_VAR}) - ${NAV_ITEM_CONTENT_FADE}px),+ transparent calc(100% - var(${NAV_ITEM_ACTIONS_INSET_VAR})));}}@@ -73,6 +82,29 @@ const styles = createStaticStyles(({ css }) => ({opacity: 0;}`,+ marqueeText: css`+ display: block;+ width: max-content;+ `,+ /* Clipped titles fade out at the right edge instead of ending in an ellipsis,+ which spends ~3ch of row width on punctuation. The box is as wide as the+ row, so a title that fits never reaches the fade. While hovered, the+ marquee animates both edge widths (see useTitleMarquee). */+ marqueeViewport: css`+ ${TITLE_MARQUEE_FADE_END_VAR}: ${TITLE_MARQUEE_FADE}px;++ overflow: hidden;+ display: block;+ white-space: nowrap;++ mask-image: linear-gradient(+ to right,+ transparent,+ #000 var(${TITLE_MARQUEE_FADE_START_VAR}, 0px),+ #000 calc(100% - var(${TITLE_MARQUEE_FADE_END_VAR})),+ transparent+ );+ `,}));export interface NavItemSlots {@@ -123,6 +155,15 @@ export interface NavItemProps extends Omit<BlockProps, 'children' | 'title'> {* fully emphasized regardless of active state (e.g. topic titles).*/titleColor?: string;+ /**+ * Reveal an overflowing title by sliding it to its tail while the row is+ * hovered, instead of showing it in a tooltip. Use for rows whose titles are+ * long free text (topic titles); at rest a clipped title fades out at its+ * right edge instead of ending in an ellipsis. Under reduced motion or an+ * RTL locale the row keeps the ellipsis and tooltip, since the slide and the+ * edge fades assume left-to-right text.+ */+ titleMarquee?: boolean;}const NavItem = memo<NavItemProps>(@@ -137,6 +178,7 @@ const NavItem = memo<NavItemProps>(iconSize = compact ? 16 : 18,title,titleColor,+ titleMarquee,description,onClick,disabled,@@ -146,15 +188,30 @@ const NavItem = memo<NavItemProps>(style,onFocus,onPointerEnter,+ onPointerLeave,...rest}) => {const { mount: mountLazyActions, node: renderedActions } = useLazyActions(actions);+ const marqueeAvailable = useTitleMarqueeAvailable();+ const marquee = !!titleMarquee && marqueeAvailable;+ const {+ start: startTitleMarquee,+ stop: stopTitleMarquee,+ textRef: titleTextRef,+ viewportRef: titleViewportRef,+ } = useTitleMarquee(marquee, typeof title === 'string' ? title : undefined);const handlePointerEnter = (e: PointerEvent<HTMLDivElement>) => {mountLazyActions();+ startTitleMarquee();onPointerEnter?.(e);};+ const handlePointerLeave = (e: PointerEvent<HTMLDivElement>) => {+ stopTitleMarquee();+ onPointerLeave?.(e);+ };+// Focus, not just the pointer: a keyboard user reaches the row by tabbing,// which never fires `pointerenter`. Without this the actions would be absent// from the tab order entirely rather than merely invisible.@@ -188,6 +245,26 @@ const NavItem = memo<NavItemProps>(: undefined;const titleFontSize = compact ? 13 : undefined;+ // A description stacks the title in a column, where `flex: 1` would grow it vertically.+ const titleStyle = description ? undefined : { flex: 1 };+ const titleNode = marquee ? (+ <Text color={textColor} fontSize={titleFontSize} style={{ ...titleStyle, minWidth: 0 }}>+ <span className={styles.marqueeViewport} ref={titleViewportRef}>+ <span className={styles.marqueeText} ref={titleTextRef}>+ {title}+ </span>+ </span>+ </Text>+ ) : (+ <Text+ color={textColor}+ ellipsis={{ tooltipWhenOverflow: true }}+ fontSize={titleFontSize}+ style={titleStyle}+ >+ {title}+ </Text>+ );const iconNode = icon && (<Center@@ -213,6 +290,7 @@ const NavItem = memo<NavItemProps>(align={'center'}className={cx(styles.container, className)}clickable={!disabled}+ data-nav-item=""gap={8}height={description ? undefined : compact ? 28 : 36}paddingBlock={description ? 8 : undefined}@@ -232,6 +310,7 @@ const NavItem = memo<NavItemProps>({...rest}onFocus={handleFocus}onPointerEnter={handlePointerEnter}+ onPointerLeave={handlePointerLeave}>{iconNode && iconBelow ? (<Flexbox@@ -255,6 +334,7 @@ const NavItem = memo<NavItemProps>(horizontalalign={'center'}className={CONTENT_CLASS_NAME}+ data-nav-item-content=""flex={1}gap={8}style={{ overflow: 'hidden' }}@@ -262,26 +342,11 @@ const NavItem = memo<NavItemProps>({titlePrefix}{description ? (<Flexbox flex={1} gap={3} style={{ overflow: 'hidden' }}>- <Text- color={textColor}- ellipsis={{ tooltipWhenOverflow: true }}- fontSize={titleFontSize}- >- {title}- </Text>+ {titleNode}{description}</Flexbox>) : (- <Text- color={textColor}- fontSize={titleFontSize}- style={{ flex: 1 }}- ellipsis={{- tooltipWhenOverflow: true,- }}- >- {title}- </Text>+ titleNode)}{extra && (<Flexboxdiff --git a/src/features/NavPanel/components/useTitleMarquee.test.ts b/src/features/NavPanel/components/useTitleMarquee.test.tsnew file mode 100644index 00000000000..d136a565ebb--- /dev/null+++ b/src/features/NavPanel/components/useTitleMarquee.test.ts@@ -0,0 +1,168 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ getTitleMarqueeTimeline,+ useTitleMarquee,+ useTitleMarqueeAvailable,+} from './useTitleMarquee';++const mocks = vi.hoisted(() => ({ reduceMotion: false }));++vi.mock('motion/react', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useReducedMotion: () => mocks.reduceMotion,+}));++describe('getTitleMarqueeTimeline', () => {+ it.each([+ [3, 16],+ [32, 16],+ [400, 16],+ [10, 0],+ ])('keeps keyframe offsets non-decreasing for distance %i and fade %i', (distance, fade) => {+ const { duration, fadeIn, fadeOut, slideEnd, slideStart } = getTitleMarqueeTimeline(+ distance,+ fade,+ );++ expect(duration).toBeGreaterThan(0);+ const offsets = [0, slideStart, fadeIn, fadeOut, slideEnd, 1];+ for (let i = 1; i < offsets.length; i++) {+ expect(offsets[i]).toBeGreaterThanOrEqual(offsets[i - 1]);+ }+ });++ it('slides at a constant speed, so a longer overflow takes longer', () => {+ expect(getTitleMarqueeTimeline(200, 16).duration).toBeGreaterThan(+ getTitleMarqueeTimeline(100, 16).duration,+ );+ });+});++const mountTitle = ({ textWidth, viewportWidth }: { textWidth: number; viewportWidth: number }) => {+ const viewport = document.createElement('span');+ const text = document.createElement('span');+ viewport.append(text);+ document.body.append(viewport);++ viewport.getBoundingClientRect = () => ({ left: 0, right: viewportWidth }) as DOMRect;+ Object.defineProperty(text, 'scrollWidth', { configurable: true, value: textWidth });++ const animations: { cancel: ReturnType<typeof vi.fn>; keyframes: Keyframe[] }[] = [];+ const animate = vi.fn((keyframes: Keyframe[]) => {+ const animation = { cancel: vi.fn(), keyframes };+ animations.push(animation);+ return animation as unknown as Animation;+ });+ text.animate = animate;+ viewport.animate = animate;++ return { animate, animations, text, viewport };+};++const renderMarquee = (elements: ReturnType<typeof mountTitle>, enabled = true) => {+ const hook = renderHook(() => useTitleMarquee(enabled, 'title'));+ hook.result.current.viewportRef.current = elements.viewport;+ hook.result.current.textRef.current = elements.text;+ return hook;+};++describe('useTitleMarquee', () => {+ beforeEach(() => {+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ callback(0);+ return 1;+ });+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ document.body.innerHTML = '';+ });++ it('slides an overflowing title by exactly its clipped width', () => {+ const elements = mountTitle({ textWidth: 300, viewportWidth: 200 });+ const { result } = renderMarquee(elements);++ act(() => result.current.start());++ const slide = elements.animations[0].keyframes;+ expect(slide.at(-1)?.transform).toBe('translateX(-100px)');+ });++ it('stops the tail where the hovered row starts fading under its actions', () => {+ const elements = mountTitle({ textWidth: 300, viewportWidth: 200 });+ const row = document.createElement('div');+ row.dataset.navItem = '';+ row.style.setProperty('--nav-item-actions-inset', '54px');+ const content = document.createElement('div');+ content.dataset.navItemContent = '';+ content.getBoundingClientRect = () => ({ right: 200 }) as DOMRect;+ content.append(elements.viewport);+ row.append(content);+ document.body.append(row);+ const { result } = renderMarquee(elements);++ act(() => result.current.start());++ // Readable up to 200 - 54 (actions) - 28 (content fade) = 118px.+ expect(elements.animations[0].keyframes.at(-1)?.transform).toBe('translateX(-182px)');+ });++ it('leaves a title that fits in place', () => {+ const elements = mountTitle({ textWidth: 150, viewportWidth: 200 });+ const { result } = renderMarquee(elements);++ act(() => result.current.start());++ expect(elements.animate).not.toHaveBeenCalled();+ });++ it('returns the title to its resting position when the pointer leaves', () => {+ const elements = mountTitle({ textWidth: 300, viewportWidth: 200 });+ const { result } = renderMarquee(elements);++ act(() => result.current.start());+ act(() => result.current.stop());++ for (const animation of elements.animations) expect(animation.cancel).toHaveBeenCalled();+ });++ it('does nothing for rows that did not opt in', () => {+ const elements = mountTitle({ textWidth: 300, viewportWidth: 200 });+ const { result } = renderMarquee(elements, false);++ act(() => result.current.start());++ expect(elements.animate).not.toHaveBeenCalled();+ });+});++describe('useTitleMarqueeAvailable', () => {+ beforeEach(() => {+ document.documentElement.dir = 'ltr';+ mocks.reduceMotion = false;+ });++ afterEach(() => {+ document.documentElement.dir = '';+ });++ it('replaces the tooltip in a left-to-right locale with motion allowed', () => {+ expect(renderHook(() => useTitleMarqueeAvailable()).result.current).toBe(true);+ });++ it('keeps the tooltip when the user prefers reduced motion', () => {+ mocks.reduceMotion = true;++ expect(renderHook(() => useTitleMarqueeAvailable()).result.current).toBe(false);+ });++ it('keeps the tooltip when the document is right-to-left', () => {+ document.documentElement.dir = 'rtl';++ expect(renderHook(() => useTitleMarqueeAvailable()).result.current).toBe(false);+ });+});diff --git a/src/features/NavPanel/components/useTitleMarquee.ts b/src/features/NavPanel/components/useTitleMarquee.tsnew file mode 100644index 00000000000..1bd557ae3d6--- /dev/null+++ b/src/features/NavPanel/components/useTitleMarquee.ts@@ -0,0 +1,212 @@+import { useReducedMotion } from 'motion/react';+import { useCallback, useEffect, useRef } from 'react';++/** Reading speed of the reveal, in pixels per second. */+const SCROLL_SPEED = 35;+/** Pause before the title starts moving, and hold at its tail, in milliseconds. */+const START_DELAY = 600;+const END_HOLD = 1200;+/** Width of the edge fade the text dissolves under while it slides. */+export const TITLE_MARQUEE_FADE = 16;++/** Width of the fade `NavItem` lays over its content just before the action overlay. */+export const NAV_ITEM_CONTENT_FADE = 28;++export const TITLE_MARQUEE_FADE_START_VAR = '--nav-title-marquee-fade-start';+export const TITLE_MARQUEE_FADE_END_VAR = '--nav-title-marquee-fade-end';+/** Set by `NavItem`: the width its hover action overlay covers. */+export const NAV_ITEM_ACTIONS_INSET_VAR = '--nav-item-actions-inset';++export interface TitleMarqueeTimeline {+ /** Total animation duration in milliseconds. */+ duration: number;+ /** Offset where the left edge fade reaches full width. */+ fadeIn: number;+ /** Offset where the right edge fade starts clearing. */+ fadeOut: number;+ /** Offset where the text reaches its tail. */+ slideEnd: number;+ /** Offset where the text starts sliding. */+ slideStart: number;+}++/**+ * Keyframe offsets for revealing a title clipped by `distance` pixels behind an+ * edge fade of `fade` pixels. `Element.animate` throws when offsets decrease,+ * and when the ramp is half the travel the two sides of `fadeIn <= fadeOut` are+ * equal in exact arithmetic but can round apart, so each offset is clamped to+ * the previous one.+ */+export const getTitleMarqueeTimeline = (distance: number, fade: number): TitleMarqueeTimeline => {+ const travel = (distance / SCROLL_SPEED) * 1000;+ const duration = START_DELAY + travel + END_HOLD;+ const ramp = (Math.min(Math.max(fade, 0), distance / 2) / SCROLL_SPEED) * 1000;+ const slideStart = START_DELAY / duration;+ const fadeIn = Math.max(slideStart, (START_DELAY + ramp) / duration);+ const fadeOut = Math.max(fadeIn, (START_DELAY + travel - ramp) / duration);+ const slideEnd = Math.min(1, Math.max(fadeOut, (START_DELAY + travel) / duration));+ return { duration, fadeIn, fadeOut, slideEnd, slideStart };+};++let fadePropertiesRegistered = false;++/**+ * Registered so the edge widths interpolate inside `Element.animate`; an+ * unregistered custom property would jump between keyframes instead.+ */+const registerFadeProperties = () => {+ if (fadePropertiesRegistered) return;+ fadePropertiesRegistered = true;+ if (typeof CSS === 'undefined' || typeof CSS.registerProperty !== 'function') return;+ for (const name of [TITLE_MARQUEE_FADE_START_VAR, TITLE_MARQUEE_FADE_END_VAR]) {+ try {+ CSS.registerProperty({ inherits: false, initialValue: '0px', name, syntax: '<length>' });+ } catch {+ // Already registered (e.g. after HMR re-evaluated this module).+ }+ }+};++/**+ * Right edge the title text stays readable up to. On hover the NavItem fades+ * its content out under the action overlay (see `NavItem` styles); the tail+ * has to stop where that fade begins, or the last characters slide out of+ * sight right as they are revealed.+ */+const getReadableRight = (viewport: HTMLElement, container: HTMLElement | null) => {+ const viewportRight = viewport.getBoundingClientRect().right;+ const content = viewport.closest<HTMLElement>('[data-nav-item-content]');+ if (!content || !container) return viewportRight;+ const inset = Number.parseFloat(+ getComputedStyle(container).getPropertyValue(NAV_ITEM_ACTIONS_INSET_VAR),+ );+ if (!Number.isFinite(inset)) return viewportRight;+ const contentFadeStart = content.getBoundingClientRect().right - inset - NAV_ITEM_CONTENT_FADE;+ return Math.min(viewportRight, contentFadeStart);+};++/**+ * Whether the marquee can replace the title tooltip here. The slide, the+ * readable-edge math and the edge fades are left-to-right, and under reduced+ * motion there is no slide to reveal the title; both keep the tooltip.+ *+ * Direction is read from the document, which the locale setup flips on a+ * language change: it is the direction the layout actually uses.+ */+export const useTitleMarqueeAvailable = () => {+ const reduceMotion = useReducedMotion();+ const rtl = typeof document !== 'undefined' && document.documentElement.dir === 'rtl';+ return !reduceMotion && !rtl;+};++/**+ * Slides an overflowing title to its tail while the row is hovered, at a+ * constant reading speed, instead of showing the full title in a tooltip.+ * The edge fades animate with it: the left edge fades in as text slides under+ * it and the right edge clears once the tail is revealed. At rest the title+ * only carries the right-edge fade (`NavItem` styles), no ellipsis.+ * Titles that fit never move. Observers and animations exist only while the+ * row is hovered, so an idle list installs nothing per row.+ */+export const useTitleMarquee = (enabled: boolean, titleKey: unknown) => {+ const viewportRef = useRef<HTMLSpanElement>(null);+ const textRef = useRef<HTMLSpanElement>(null);+ const stopRef = useRef<(() => void) | null>(null);++ const stop = useCallback(() => {+ stopRef.current?.();+ stopRef.current = null;+ }, []);++ const start = useCallback(() => {+ if (!enabled || stopRef.current) return;+ const viewport = viewportRef.current;+ const text = textRef.current;+ if (!viewport || !text || typeof text.animate !== 'function') return;++ registerFadeProperties();+ const container = viewport.closest<HTMLElement>('[data-nav-item]');+ let animations: Animation[] = [];++ const reset = () => {+ for (const animation of animations) animation.cancel();+ animations = [];+ };++ const reveal = () => {+ reset();+ const readableWidth =+ getReadableRight(viewport, container) - viewport.getBoundingClientRect().left;+ const distance = Math.ceil(text.scrollWidth - readableWidth);+ if (distance <= 1) return;++ const fade = `${TITLE_MARQUEE_FADE}px`;+ const { duration, fadeIn, fadeOut, slideEnd, slideStart } = getTitleMarqueeTimeline(+ distance,+ TITLE_MARQUEE_FADE,+ );+ const timing: KeyframeAnimationOptions = { duration, easing: 'linear', fill: 'forwards' };+ const shifted = `translateX(-${distance}px)`;++ animations.push(+ text.animate(+ [+ { offset: 0, transform: 'translateX(0)' },+ { offset: slideStart, transform: 'translateX(0)' },+ { offset: slideEnd, transform: shifted },+ { offset: 1, transform: shifted },+ ],+ timing,+ ),+ );++ const edges = (startWidth: string, endWidth: string, offset: number): Keyframe => ({+ [TITLE_MARQUEE_FADE_END_VAR]: endWidth,+ [TITLE_MARQUEE_FADE_START_VAR]: startWidth,+ offset,+ });+ animations.push(+ viewport.animate(+ [+ edges('0px', fade, 0),+ edges('0px', fade, slideStart),+ edges(fade, fade, fadeIn),+ edges(fade, fade, fadeOut),+ edges(fade, '0px', slideEnd),+ edges(fade, '0px', 1),+ ],+ timing,+ ),+ );+ };++ // Observing keeps sidebar resizing and font loading accurate while hovered.+ const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(reveal);+ // Wait a frame: the hover mounts the row's lazy actions, which can widen+ // the action overlay the readable width is measured against.+ let frame: number | undefined;+ frame = requestAnimationFrame(() => {+ frame = undefined;+ reveal();+ observer?.observe(viewport);+ observer?.observe(text);+ });++ stopRef.current = () => {+ if (frame !== undefined) cancelAnimationFrame(frame);+ observer?.disconnect();+ reset();+ };+ }, [enabled]);++ // A title renamed (or generated) mid-hover restarts from its head.+ useEffect(() => {+ if (!stopRef.current) return;+ stop();+ start();+ }, [titleKey, start, stop]);++ useEffect(() => stop, [stop]);++ return { start, stop, textRef, viewportRef };+};diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsxindex 31e8919085e..a920d8bd42b 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx@@ -328,6 +328,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, statreturn (<Flexbox style={{ position: 'relative' }}><NavItem+ titleMarqueeactions={<Actions dropdownMenu={dropdownMenu} />}active={active && !threadId}contextMenuItems={dropdownMenu}