sailfork / t3code-github / apps/ mobile/ src/ features/ review/ ReviewCommentComposerSheet.tsx

import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { TextInputWrapper } from "expo-paste-input";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useMemo, useState } from "react";
import { Platform, ScrollView, View, useWindowDimensions } from "react-native";
import { KeyboardAvoidingView, KeyboardStickyView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";

import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
import { SheetHeader } from "../../components/ui/SheetHeader";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
import { ControlPill } from "../../components/ui/ControlPill";
import { cn } from "../../lib/cn";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { useNativePaste } from "../../lib/useNativePaste";
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state";
import {
  clearReviewCommentTarget,
  formatReviewCommentContext,
  getReviewUnifiedLineNumber,
  getSelectedReviewCommentLines,
  useReviewCommentTarget,
} from "./reviewCommentSelection";
import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { changeTone, DiffTokenText, ReviewChangeBar } from "./reviewDiffRendering";
import { highlightReviewSelectedLines } from "./highlightReviewSelectedLines";

const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
const NO_LINES: ReturnType<typeof getSelectedReviewCommentLines> = [];
const NO_HIGHLIGHTS: ReturnType<typeof highlightReviewSelectedLines> = {};

type ReviewCommentComposerSheetProps = StaticScreenProps<{
  readonly environmentId: EnvironmentId;
  readonly threadId: ThreadId;
}>;

export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProps) {
  const isAndroid = Platform.OS === "android";
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();
  const { width } = useWindowDimensions();
  const { themeAppearance: selectedTheme } = useAppearancePreferences();
  const target = useReviewCommentTarget();
  const { codeSurface } = useAppearanceCodeSurface();
  const { environmentId, threadId } = props.route.params;
  const [commentText, setCommentText] = useState("");
  const [attachments, setAttachments] = useState<ReadonlyArray<DraftComposerImageAttachment>>([]);
  const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);

  const { selectedLines, highlightedLinesById } = useMemo(() => {
    if (!target) return { selectedLines: NO_LINES, highlightedLinesById: NO_HIGHLIGHTS };
    const lines = getSelectedReviewCommentLines(target);
    return {
      selectedLines: lines,
      highlightedLinesById: highlightReviewSelectedLines({
        filePath: target.filePath,
        lines,
        theme: selectedTheme,
      }),
    };
  }, [selectedTheme, target]);
  const firstLine = selectedLines[0] ?? null;
  const lastLine = selectedLines[selectedLines.length - 1] ?? null;
  const firstNumber = firstLine ? getReviewUnifiedLineNumber(firstLine) : null;
  const lastNumber = lastLine ? getReviewUnifiedLineNumber(lastLine) : null;
  const canSubmit =
    commentText.trim().length > 0 && target !== null && !!environmentId && !!threadId;
  const selectionLabel =
    selectedLines.length === 1
      ? firstNumber !== null
        ? `Line ${firstNumber}`
        : "File comment"
      : firstNumber !== null && lastNumber !== null
        ? `Lines ${firstNumber}-${lastNumber}`
        : `${selectedLines.length} lines selected`;
  const previewHeight = Math.max(
    Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * codeSurface.rowHeight,
    codeSurface.rowHeight,
  );
  const previewViewportWidth = Math.max(width - 40, 280);
  const dismissComposer = () => {
    clearReviewCommentTarget();
    navigation.goBack();
  };
  const handleNativePaste = useNativePaste((uris) => {
    void (async () => {
      try {
        const images = await convertPastedImagesToAttachments({
          uris,
          existingCount: attachments.length,
        });
        if (images.length > 0) {
          setAttachments((current) => [...current, ...images]);
        }
      } catch (error) {
        console.error("[review comment] error converting pasted images", error);
      }
    })();
  });

  async function handlePickImages(): Promise<void> {
    const result = await pickComposerImages({ existingCount: attachments.length });
    if (result.images.length > 0) {
      setAttachments((current) => [...current, ...result.images]);
    }
    if (result.error) {
      setPendingConnectionError(result.error);
    }
  }

  const handleSubmit = () => {
    if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
      return;
    }

    appendReviewCommentToDraft({
      environmentId,
      threadId,
      text: formatReviewCommentContext(target, commentText),
      attachments,
    });
    setAttachments([]);
    dismissComposer();
  };

  return (
    <View className="flex-1 bg-sheet">
      <SheetHeader title="Add Comment" onClose={dismissComposer} />
      <KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
        <View
          className="flex-1 px-5"
          style={{
            paddingTop: 8,
            paddingBottom: target ? (isAndroid ? 72 : 0) : Math.max(insets.bottom, 18),
          }}
        >
          {!target ? (
            <View className="rounded-[22px] border border-border bg-card px-4 py-5">
              <Text className="text-base font-t3-bold text-foreground">No selection</Text>
              <Text className="mt-1 text-sm leading-normal text-foreground-muted">
                Select a diff line or range first.
              </Text>
            </View>
          ) : (
            <View className="min-h-0 flex-1 gap-4">
              <View className="gap-1 px-1">
                <Text className="text-2xs font-t3-bold uppercase text-foreground-muted">
                  {selectionLabel}
                </Text>
                <Text
                  className="font-mono text-xs leading-snug text-foreground-muted"
                  ellipsizeMode="middle"
                  numberOfLines={2}
                >
                  {target.filePath}
                </Text>
              </View>

              <View className="overflow-hidden rounded-[22px] border border-border bg-card">
                <ScrollView
                  horizontal
                  bounces={false}
                  keyboardShouldPersistTaps="always"
                  showsHorizontalScrollIndicator={false}
                >
                  <ScrollView
                    bounces={false}
                    scrollEnabled={selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES}
                    nestedScrollEnabled
                    keyboardShouldPersistTaps="always"
                    showsVerticalScrollIndicator={
                      selectedLines.length > REVIEW_COMMENT_PREVIEW_MAX_LINES
                    }
                    style={{ height: previewHeight }}
                  >
                    <View style={{ minWidth: previewViewportWidth }}>
                      {selectedLines.map((line) => {
                        const lineNumber = getReviewUnifiedLineNumber(line);

                        return (
                          <View
                            key={line.id}
                            className={cn("flex-row items-start", changeTone(line.change))}
                            style={{ height: codeSurface.rowHeight }}
                          >
                            <ReviewChangeBar change={line.change} height={codeSurface.rowHeight} />
                            <Text className="w-9 py-1 pr-1 text-right text-2xs font-mono text-foreground-muted">
                              {lineNumber ?? ""}
                            </Text>
                            <View className="min-w-0 flex-1 shrink-0 px-1 py-1">
                              <DiffTokenText
                                fallback={line.content}
                                tokens={highlightedLinesById[line.id] ?? null}
                                change={line.change}
                                fontSize={codeSurface.fontSize}
                                lineHeight={codeSurface.rowHeight}
                              />
                            </View>
                          </View>
                        );
                      })}
                    </View>
                  </ScrollView>
                </ScrollView>
              </View>

              <View className="min-h-0 flex-1 gap-2">
                <Text className="text-sm font-t3-bold text-foreground">Comment</Text>
                <View className="min-h-[132px] flex-1 overflow-hidden rounded-[20px] border border-border bg-card">
                  <View className="min-h-0 flex-1 px-4 pt-3.5">
                    <TextInputWrapper onPaste={handleNativePaste} style={{ flex: 1, minHeight: 0 }}>
                      <TextInput
                        autoFocus
                        multiline
                        scrollEnabled
                        placeholder="Leave a comment..."
                        textAlignVertical="top"
                        value={commentText}
                        onChangeText={setCommentText}
                        className="h-full min-h-0 flex-1 border-0 bg-transparent px-0 py-0 font-sans text-base"
                      />
                    </TextInputWrapper>
                  </View>
                  {attachments.length > 0 ? (
                    <View className="px-4 pb-3 pt-2">
                      <ComposerAttachmentStrip
                        attachments={attachments}
                        imageBorderRadius={16}
                        imageSize={60}
                        onPressPreview={setPreviewFile}
                        removeButtonPlacement="gutter"
                        onRemove={(imageId) => {
                          setAttachments((current) =>
                            current.filter((image) => image.id !== imageId),
                          );
                        }}
                      />
                    </View>
                  ) : null}
                </View>
              </View>
            </View>
          )}
        </View>
        {!isAndroid && target ? (
          <View className="flex-row items-center gap-3 bg-sheet px-5 py-2">
            <ControlPill
              accessibilityLabel="Add image"
              icon="plus"
              onPress={() => void handlePickImages()}
            />
            <View className="flex-1" />
            <ControlPill
              accessibilityLabel="Comment"
              icon="arrow.up"
              label="Comment"
              variant="primary"
              disabled={!canSubmit}
              onPress={handleSubmit}
            />
          </View>
        ) : null}
      </KeyboardAvoidingView>
      {isAndroid && target ? (
        <KeyboardStickyView
          className="absolute inset-x-0 bottom-0"
          offset={{ closed: 0, opened: 0 }}
        >
          <View
            className="flex-row items-center gap-3 border-t border-border bg-sheet px-5 pt-2"
            style={{ paddingBottom: Math.max(insets.bottom, 10) }}
          >
            <ControlPill
              accessibilityLabel="Add image"
              icon="plus"
              onPress={() => void handlePickImages()}
            />
            <View className="flex-1" />
            <ControlPill
              accessibilityLabel="Comment"
              icon="arrow.up"
              label="Comment"
              variant="primary"
              disabled={!canSubmit}
              onPress={handleSubmit}
            />
          </View>
        </KeyboardStickyView>
      ) : null}
      <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
    </View>
  );
}