Skip to content

🤯 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.

2.6 KB
Raw Blame
'use client';

import { Icon } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { kebabCase } from 'es-toolkit/compat';
import { Heading2, Heading3, Heading4, Heading5 } from 'lucide-react';
import { type ComponentProps, type FC, type ReactNode } from 'react';
import { Children, isValidElement, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { sx } from '@/styles/sx';

import { useToc } from './useToc';

const extractTextChildren = (children: ReactNode) => {
  let text = '';

  Children.forEach(children, (child) => {
    if (typeof child === 'string' || typeof child === 'number') {
      text += child;
    } else if (isValidElement(child) && (child as any).props.children) {
      text += extractTextChildren((child as any).props.children);
    }
  });

  return text;
};

const HeadingIcon: any = {
  h2: Heading2,
  h3: Heading3,
  h4: Heading4,
  h5: Heading5,
};

const styles = stylex.create({
  anchor: {
    display: { default: 'none', [stylex.when.ancestor(':hover')]: 'inline' },
    marginInlineStart: '0.5rem',
    color: cssVar.colorTextDescription,
  },
});

const createHeading = (Tag: `h${1 | 2 | 3 | 4 | 5 | 6}`) => {
  const Heading: FC<ComponentProps<'h2'>> = ({ children, className, style, ...props }) => {
    const { t } = useTranslation('discover');
    const { setToc, setFinished } = useToc();
    const text = useMemo(() => extractTextChildren(children), [children]);
    const id = kebabCase(text);

    useEffect(() => {
      if (!setToc) return;
      if (Tag === 'h2' || Tag === 'h3') {
        setToc?.((prev = []) => [
          ...prev,
          {
            href: `#${id}`,
            level: Tag === 'h2' ? 2 : 3,
            title: text,
          },
        ]);
      }
      setFinished();
    }, [id]);

    if (Tag === 'h1')
      return (
        <Tag style={{ color: cssVar.colorText, ...style }} {...props} id={id}>
          {children}
        </Tag>
      );

    return (
      <Tag
        {...sx(stylex.defaultMarker(), className, { color: cssVar.colorText, ...style })}
        {...props}
        id={id}
      >
        {children}
        <a
          aria-label={t('toc.permalink')}
          className={stylex.props(styles.anchor).className}
          href={`#${id}`}
          style={{ scrollMarginTop: 96 }}
        >
          <Icon icon={HeadingIcon[Tag]} />
        </a>
      </Tag>
    );
  };

  return Heading;
};

export const H1 = createHeading('h1');
export const H2 = createHeading('h2');
export const H3 = createHeading('h3');
export const H4 = createHeading('h4');
export const H5 = createHeading('h5');