Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

4.1 KB
Raw Blame
/** A hidden mirror measures soft-wrap heights while numbering each logical line once. */

import type { BoxProps } from '@chakra-ui/react';
import type { CSSProperties } from 'react';

import { Box } from '@chakra-ui/react';
import { useLayoutEffect, useMemo, useRef, useState } from 'react';

const TABULAR_NUMS: CSSProperties = { fontVariantNumeric: 'tabular-nums' };
/** Enough for the digits plus breathing room on either side, in `ch`. */
const GUTTER_PADDING_CH = 2;

export interface PromptLineNumbersMetrics {
  fontFamily: BoxProps['fontFamily'];
  fontSize: BoxProps['fontSize'];
  lineHeight: BoxProps['lineHeight'];
  paddingInline: string;
  paddingBlock: string;
  scrollTop: number;
  /** The textarea's unrounded wrap width (`getTextareaWrapWidth`), so the mirror wraps identically. */
  wrapWidth: number | null;
}

/** Width the textarea must reserve on its leading edge for `lineCount` numbers. */
export const getLineNumberGutterCh = (lineCount: number): number =>
  String(Math.max(lineCount, 1)).length + GUTTER_PADDING_CH;

export const PromptLineNumbers = ({ metrics, value }: { metrics: PromptLineNumbersMetrics; value: string }) => {
  const mirrorRef = useRef<HTMLDivElement | null>(null);
  const [lineHeights, setLineHeights] = useState<number[]>([]);
  const lines = useMemo(() => value.split('\n'), [value]);
  const gutterWidth = `${getLineNumberGutterCh(lines.length)}ch`;
  const gutterLaneWidth = `calc(${metrics.paddingInline} + ${gutterWidth})`;

  useLayoutEffect(() => {
    const mirror = mirrorRef.current;

    if (!mirror) {
      return;
    }

    const measure = () => {
      const heights = [...mirror.children].map((child) => child.getBoundingClientRect().height);

      setLineHeights((current) =>
        current.length === heights.length && current.every((height, index) => height === heights[index])
          ? current
          : heights
      );
    };
    const resizeObserver = new ResizeObserver(measure);

    measure();
    resizeObserver.observe(mirror);

    return () => resizeObserver.disconnect();
  }, [lines, metrics.wrapWidth, metrics.fontSize, metrics.lineHeight]);

  const sharedTextStyles = {
    fontFamily: metrics.fontFamily,
    fontSize: metrics.fontSize,
    lineHeight: metrics.lineHeight,
    overflowWrap: 'break-word',
    whiteSpace: 'pre-wrap',
  } as const;

  return (
    <>
      {/* visibility:hidden preserves measurable layout. */}
      <Box aria-hidden="true" inset="0" overflow="hidden" pointerEvents="none" position="absolute" visibility="hidden">
        <Box
          ref={mirrorRef}
          m="0"
          paddingBlock={metrics.paddingBlock}
          paddingInline={metrics.paddingInline}
          paddingInlineStart={`calc(${metrics.paddingInline} + ${gutterWidth})`}
          w={metrics.wrapWidth ? `${metrics.wrapWidth}px` : '100%'}
          {...sharedTextStyles}
        >
          {lines.map((line, index) => (
            // Zero-width space so a blank line still occupies one row.
            <Box key={index} as="div" {...sharedTextStyles}>
              {line === '' ? '​' : line}
            </Box>
          ))}
        </Box>
      </Box>

      {/* ch units use the gutter container's own font metrics. */}
      <Box
        aria-hidden="true"
        bottom="0"
        fontFamily={metrics.fontFamily}
        fontSize={metrics.fontSize}
        left="0"
        overflow="hidden"
        pointerEvents="none"
        position="absolute"
        top="0"
        w={gutterLaneWidth}
        zIndex={2}
      >
        <Box
          color="fg.subtle"
          paddingBlock={metrics.paddingBlock}
          textAlign="end"
          transform={`translateY(${-metrics.scrollTop}px)`}
          w="full"
          {...sharedTextStyles}
          paddingInlineEnd="0.75ch"
          style={TABULAR_NUMS}
        >
          {lines.map((_, index) => (
            <Box
              key={index}
              data-line-number={index + 1}
              h={lineHeights[index] ? `${lineHeights[index]}px` : undefined}
              {...sharedTextStyles}
            >
              {index + 1}
            </Box>
          ))}
        </Box>
      </Box>
    </>
  );
};