1596 lines · 52.2 KB · TypeScript
RawDownload
import * as Haptics from "expo-haptics";import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";import { type LegendListRef } from "@legendapp/list/react-native";import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";import { SymbolView } from "expo-symbols";import { useNavigation } from "@react-navigation/native";import {  memo,  useCallback,  useEffect,  useMemo,  useRef,  useState,  type ReactNode,  type RefObject,} from "react";import {  Markdown,  type CustomRenderers,  type NodeStyleOverrides,  type PartialMarkdownTheme,} from "react-native-nitro-markdown";import {  ActivityIndicator,  Image,  Linking,  Platform,  type LayoutChangeEvent,  type NativeScrollEvent,  type NativeSyntheticEvent,  Pressable,  ScrollView,  StyleSheet,  Text as NativeText,  type ColorValue,  useColorScheme,  useWindowDimensions,  View,} from "react-native";import { TouchableOpacity } from "react-native-gesture-handler";import ImageViewing from "react-native-image-viewing";import { useSafeAreaInsets } from "react-native-safe-area-context";import { type SharedValue } from "react-native-reanimated";import { useThemeColor } from "../../lib/useThemeColor";import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";import {  hasNativeSelectableMarkdownText,  SelectableMarkdownText,  type NativeMarkdownTextStyle,  type SelectableMarkdownSkill,} from "../../native/SelectableMarkdownText"; import { AppText as Text } from "../../components/AppText";import { CopyTextButton } from "../../components/CopyTextButton";import {  parseReviewCommentMessageSegments,  type ReviewInlineComment,} from "../review/reviewCommentSelection";import { resolveNativeReviewDiffView } from "../diffs/nativeReviewDiffSurface";import {  buildNativeReviewDiffData,  createNativeReviewDiffTheme,  NATIVE_REVIEW_DIFF_CONTENT_WIDTH,} from "../review/nativeReviewDiffAdapter";import { buildReviewParsedDiff } from "../review/reviewModel";import { cn } from "../../lib/cn";import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";import {  resolveMarkdownFontSizes,  resolveNativeMarkdownTypography,} from "../../lib/appearancePreferences";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";import {  deriveThreadFeedPresentation,  type ThreadFeedEntry,  type ThreadFeedLatestTurn,} from "../../lib/threadActivity";import type { ThreadContentPresentation } from "./threadContentPresentation";import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";import { useAssetUrl } from "../../state/assets";import { resolveWorkspaceRelativeFilePath } from "../files/filePath"; const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {  hour: "numeric",  minute: "2-digit",});function formatMessageTime(input: string): string {  const timestamp = Date.parse(input);  if (Number.isNaN(timestamp)) {    return "";  }  return MESSAGE_TIME_FORMATTER.format(timestamp);} export interface ThreadFeedProps {  readonly environmentId: EnvironmentId;  readonly threadId: ThreadId;  readonly workspaceRoot?: string | null;  readonly feed: ReadonlyArray<ThreadFeedEntry>;  readonly contentPresentation: ThreadContentPresentation;  readonly agentLabel: string;  readonly latestTurn: ThreadFeedLatestTurn | null;  readonly listRef: RefObject<LegendListRef | null>;  readonly freeze: SharedValue<boolean>;  readonly anchorMessageId: MessageId | null;  readonly contentInsetEndAdjustment: SharedValue<number>;  readonly contentTopInset?: number;  readonly contentBottomInset?: number;  readonly contentMaxWidth?: number;  readonly layoutVariant?: LayoutVariant;  readonly usesAutomaticContentInsets?: boolean;  readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;  readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;} function MessageAttachmentImage(props: {  readonly environmentId: EnvironmentId;  readonly attachmentId: string;  readonly className: string;  readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;}) {  const uri = useAssetUrl(props.environmentId, {    _tag: "attachment",    attachmentId: props.attachmentId,  });   if (uri === null) {    return (      <View className={`${props.className} items-center justify-center`}>        <ActivityIndicator />      </View>    );  }   return (    <TouchableOpacity activeOpacity={0.7} onPress={() => props.onPressImage(uri)}>      <Image source={{ uri }} className={props.className} resizeMode="cover" />    </TouchableOpacity>  );} const MARKDOWN_COLORS = {  light: {    body: "#111111",    strong: "#000000",    link: "#2563eb",    blockquoteBorder: "rgba(0, 0, 0, 0.08)",    blockquoteBackground: "rgba(0, 0, 0, 0.02)",    codeBackground: "rgba(0, 0, 0, 0.04)",    codeText: "#262626",    inlineCodeText: "#5f6368",    horizontalRule: "rgba(0, 0, 0, 0.08)",    userBody: "#ffffff",    userCodeBackground: "rgba(255, 255, 255, 0.22)",    userCodeText: "#ffffff",    userInlineCodeText: "rgba(255, 255, 255, 0.82)",    userFenceBackground: "rgba(0, 0, 0, 0.16)",    userFenceText: "#ffffff",  },  dark: {    body: "#e5e5e5",    strong: "#f5f5f5",    link: "#60a5fa",    blockquoteBorder: "rgba(255, 255, 255, 0.1)",    blockquoteBackground: "rgba(255, 255, 255, 0.03)",    codeBackground: "rgba(255, 255, 255, 0.06)",    codeText: "#e5e5e5",    inlineCodeText: "#b8bcc2",    horizontalRule: "rgba(255, 255, 255, 0.08)",    userBody: "#ffffff",    userCodeBackground: "rgba(255, 255, 255, 0.18)",    userCodeText: "#ffffff",    userInlineCodeText: "rgba(255, 255, 255, 0.82)",    userFenceBackground: "rgba(0, 0, 0, 0.28)",    userFenceText: "#ffffff",  },} as const; interface MarkdownStyleSets {  readonly user: MarkdownStyleSet;  readonly assistant: MarkdownStyleSet;} interface MarkdownStyleSet {  readonly theme: PartialMarkdownTheme;  readonly styles: NodeStyleOverrides;  readonly renderers: CustomRenderers;  readonly nativeTextStyle: NativeMarkdownTextStyle;} interface ReviewCommentColors {  readonly background: ColorValue;  readonly border: ColorValue;  readonly mutedBackground: ColorValue;  readonly text: ColorValue;  readonly mutedText: ColorValue;  readonly codeBackground: ColorValue;} const failedMarkdownFaviconHosts = new Set<string>();const markdownLinkStyles = StyleSheet.create({  inlineIcon: {    width: 14,    height: 14,    marginHorizontal: 3,    transform: [{ translateY: 2 }],  },  favicon: {    borderRadius: 3,  },  file: {    fontFamily: "DMSans_700Bold",    fontWeight: "700",  },}); const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {  readonly children: ReactNode;  readonly color: string;  readonly host: string;  readonly href: string;}) {  const [failed, setFailed] = useState(() => failedMarkdownFaviconHosts.has(props.host));   return (    <NativeText      onPress={() => {        void Linking.openURL(props.href);      }}      style={{        color: props.color,        fontFamily: "DMSans_400Regular",        textDecorationLine: "none",      }}    >      {!failed ? (        <Image          source={{            uri: `https://www.google.com/s2/favicons?domain=${encodeURIComponent(props.host)}&sz=32`,          }}          style={[markdownLinkStyles.inlineIcon, markdownLinkStyles.favicon]}          onError={() => {            failedMarkdownFaviconHosts.add(props.host);            setFailed(true);          }}        />      ) : (        <NativeText style={{ color: props.color }}>{" ◉ "}</NativeText>      )}      {props.children}    </NativeText>  );}); function useReviewCommentColors(): ReviewCommentColors {  const colorScheme = useColorScheme();  const isDark = colorScheme === "dark";  const background = isDark ? "#151515" : "#ffffff";  const border = isDark ? "#2a2a2a" : "#d7d7d7";  const mutedBackground = isDark ? "#242424" : "#f2f2f2";  const text = isDark ? "#f3f3f3" : "#111111";  const mutedText = isDark ? "#8f8f8f" : "#666666";  const codeBackground = isDark ? "#0f0f0f" : "#ffffff";   return useMemo(    () => ({      background,      border,      mutedBackground,      text,      mutedText,      codeBackground,    }),    [background, border, codeBackground, mutedBackground, mutedText, text],  );} function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets {  const colorScheme = useColorScheme();  const { appearance } = useAppearancePreferences();  const markdownFontSizes = useMemo(    () => resolveMarkdownFontSizes(appearance.baseFontSize),    [appearance.baseFontSize],  );  const nativeMarkdownTypography = useMemo(    () => resolveNativeMarkdownTypography(appearance.baseFontSize),    [appearance.baseFontSize],  );  const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"];  const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground"));   return useMemo(() => {    const markdownBodyColor = colors.body;    const markdownStrongColor = colors.strong;    const markdownLinkColor = colors.link;    const markdownBlockquoteBg = colors.blockquoteBackground;    const markdownBlockquoteBorder = colors.blockquoteBorder;    const markdownCodeBg = colors.codeBackground;    const markdownCodeText = colors.codeText;    const markdownInlineCodeText = colors.inlineCodeText;    const markdownHrColor = colors.horizontalRule;    const markdownUserBodyColor = colors.userBody;    const markdownUserCodeBg = colors.userCodeBackground;    const markdownUserCodeText = colors.userCodeText;    const markdownUserInlineCodeText = colors.userInlineCodeText;    const markdownUserFenceBg = colors.userFenceBackground;    const markdownUserFenceText = colors.userFenceText;     const baseTheme: PartialMarkdownTheme = {      colors: {        text: markdownBodyColor,        heading: markdownStrongColor,        link: markdownLinkColor,        blockquote: markdownBlockquoteBorder,        border: markdownHrColor,        surfaceLight: markdownBlockquoteBg,        accent: markdownLinkColor,        tableBorder: markdownHrColor,        tableHeader: markdownBlockquoteBg,        tableHeaderText: markdownStrongColor,        tableRowOdd: "transparent",        tableRowEven: "transparent",      },      spacing: {        xs: 4,        s: 4,        m: 8,        l: 8,        xl: 16,      },      fontSizes: {        s: markdownFontSizes.s,        m: markdownFontSizes.m,        h1: markdownFontSizes.h1,        h2: markdownFontSizes.h2,        h3: markdownFontSizes.h3,        h4: markdownFontSizes.h4,        h5: markdownFontSizes.h5,        h6: markdownFontSizes.h6,      },      fontFamilies: {        regular: "DMSans_400Regular",        heading: "DMSans_700Bold",        mono: "ui-monospace",      },      headingWeight: "700",      borderRadius: {        s: 4,        m: 8,        l: 12,      },      showCodeLanguage: false,    };     const baseStyles: NodeStyleOverrides = {      document: { flexShrink: 1 },      paragraph: { marginTop: 0, marginBottom: 10 },      list: { marginTop: 4, marginBottom: 8 },      list_item: { marginTop: 0, marginBottom: 4 },      task_list_item: { marginTop: 0, marginBottom: 4 },      text: { lineHeight: markdownFontSizes.bodyLineHeight },      bold: {        fontWeight: "700",        color: markdownStrongColor,        fontFamily: "DMSans_700Bold",      },      italic: { fontStyle: "italic" },      link: {        color: markdownLinkColor,        textDecorationLine: "underline" as const,      },      blockquote: {        borderLeftWidth: 2,        borderLeftColor: markdownBlockquoteBorder,        paddingLeft: 11,        paddingVertical: 2,        marginLeft: 0,        marginVertical: 10,      },      heading: {        fontFamily: "DMSans_700Bold",        color: markdownStrongColor,        marginTop: 18,        marginBottom: 8,      },      horizontal_rule: {        backgroundColor: markdownHrColor,        height: 1,        marginVertical: 12,      },    };     const createMarkdownRenderers = (      inlineTextColor: string,      inlineCodeTextColor: string,      blockBackgroundColor: string,      blockTextColor: string,      preserveSoftBreaks: boolean,    ): CustomRenderers => ({      link: ({ children, href = "" }) => {        const presentation = resolveMarkdownLinkPresentation(href);        if (presentation.kind === "file") {          return (            <NativeText              onPress={() => onLinkPress(href)}              style={[markdownLinkStyles.file, { color: inlineTextColor }]}            >              <Image                source={markdownFileIconSource(presentation.icon)}                style={markdownLinkStyles.inlineIcon}              />              {presentation.label}            </NativeText>          );        }        if (presentation.kind === "external") {          return (            <MarkdownExternalLink              href={presentation.href}              host={presentation.host}              color={markdownLinkColor}            >              {children}            </MarkdownExternalLink>          );        }        const linkHref = presentation.href;        return (          <NativeText            onPress={              linkHref                ? () => {                    void Linking.openURL(linkHref);                  }                : undefined            }            style={{              color: markdownLinkColor,              textDecorationLine: "underline",            }}          >            {children}          </NativeText>        );      },      list: ({ node, Renderer, ordered = false, start = 1 }) => (        <View style={{ marginTop: 2, marginBottom: 8 }}>          {node.children?.map((child, index) => {            const childKey = `${child.type}:${child.beg ?? "unknown"}:${child.end ?? "unknown"}`;            if (child.type === "task_list_item") {              return (                <Renderer key={childKey} node={child} depth={1} inListItem parentIsText={false} />              );            }            return (              <View                key={childKey}                style={{                  flexDirection: "row",                  alignItems: "flex-start",                  marginBottom: 3,                }}              >                <NativeText                  style={{                    width: ordered ? 22 : 12,                    marginRight: 5,                    color: inlineTextColor,                    fontFamily: "DMSans_400Regular",                    fontSize: markdownFontSizes.m,                    lineHeight: markdownFontSizes.bodyLineHeight,                    textAlign: ordered ? "right" : "center",                  }}                >                  {ordered ? `${start + index}.` : "•"}                </NativeText>                <View style={{ flex: 1, minWidth: 0 }}>                  <Renderer node={child} depth={1} inListItem parentIsText={false} />                </View>              </View>            );          })}        </View>      ),      code_inline: ({ content }) => {        const value = content ?? "";        return (          <NativeText            style={{              color: inlineCodeTextColor,              fontFamily: "ui-monospace",              fontSize: markdownFontSizes.codeBlockFontSize,              lineHeight: markdownFontSizes.bodyLineHeight,            }}          >            {value}

Lines 1–500 of 1596.