Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

34.3 KB
Raw Blame
import { ComposerFrame, nativeComposerFrameAvailable } from './ComposerFrame';
import {
  Animated,
  Platform,
  Pressable,
  ScrollView,
  Easing,
  StyleSheet,
  View,
  type GestureResponderHandlers,
  type StyleProp,
  type TextInputProps,
  type TextStyle,
  type ViewProps,
  type ViewStyle,
} from 'react-native';
import { TextInput } from '@/components/AppText';
import Reanimated, { useAnimatedStyle, useSharedValue, type AnimatedRef, type SharedValue } from 'react-native-reanimated';
import { GestureDetector } from '@/platform/gestureHandler';
import type { NativeGesture, PanGesture } from 'react-native-gesture-handler';
import Constants, { ExecutionEnvironment } from 'expo-constants';
import { TextInputWrapper, type PasteEventPayload } from 'expo-paste-input';
import { Mic } from 'lucide-react-native';
import { useCallback, useEffect, useRef, type MutableRefObject, type ReactNode, type Ref } from 'react';
import { useTranslation } from 'react-i18next';
import { iconSize, iconStroke, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { motionDuration, motionEasing, radius, spacing } from '@/theme/tokens';
import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
import { useVoicePillWidthStyle } from './voicePillWidthMotion';
import {
  COMPOSER_SINGLE_LINE_HEIGHT,
  COMPOSER_TEXT_HORIZONTAL_PADDING,
  COMPOSER_TEXT_LINE_HEIGHT,
  COMPOSER_TEXT_STYLE,
  COMPOSER_TEXT_VERTICAL_PADDING,
} from '@/session/composerTextMetrics';
import {
  COMPOSER_TEXT_GEOMETRIC_PADDING_BOTTOM,
  COMPOSER_TEXT_GEOMETRIC_PADDING_TOP,
  COMPOSER_TEXT_PADDING_BOTTOM,
  COMPOSER_TEXT_PADDING_TOP,
} from '@/session/composerTextPlatformMetrics';
import {
  MOBILE_COMPOSER_CONTROL_SIZE,
  MOBILE_COMPOSER_TOOL_GAP,
  MOBILE_COMPOSER_VOICE_ANCHOR_CARD_BOTTOM,
  resolveMobileComposerVoiceButtonAnchorStyle,
  type MobileComposerVoiceButtonPlacement,
} from '@/session/composerVoiceButtonAnchor';

export {
  MOBILE_COMPOSER_CONTROL_SIZE,
  MOBILE_COMPOSER_TOOL_GAP,
  MOBILE_COMPOSER_VOICE_ANCHOR_CARD_BOTTOM,
  MOBILE_COMPOSER_VOICE_ANCHOR_RIGHT,
  resolveMobileComposerVoiceButtonAnchorStyle,
  resolveMobileComposerVoiceButtonPlacement,
  type MobileComposerVoiceButtonPlacement,
} from '@/session/composerVoiceButtonAnchor';

/**
 * Composer 草稿文本的排版档。正本在 `composerTextMetrics`——原生输入框、WebView 富文本
 * 编辑器与语音听写覆盖层共用同一档,任一处漂移都会让听写文字与真实输入框换行位置错开
 * (详见该文件注释)。此处只做转出,页面按既有名字引用。
 */
export const MOBILE_COMPOSER_DRAFT_TEXT_STYLE = COMPOSER_TEXT_STYLE;

/**
 * 输入区的单行**内容高度**(不含上下内边距) = 单行文字行高:两者同源,保证「单行」
 * 正好装一行文字。含内边距的单行可视高度是 MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT。
 */
export const MOBILE_COMPOSER_INPUT_LINE_HEIGHT = COMPOSER_TEXT_LINE_HEIGHT;
export const MOBILE_COMPOSER_INPUT_VERTICAL_PADDING = COMPOSER_TEXT_VERTICAL_PADDING;
export const MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT = COMPOSER_SINGLE_LINE_HEIGHT;
export const MOBILE_COMPOSER_INPUT_MAX_VISIBLE_LINES = 12;
export const MOBILE_COMPOSER_INPUT_MAX_HEIGHT = (MOBILE_COMPOSER_INPUT_LINE_HEIGHT * MOBILE_COMPOSER_INPUT_MAX_VISIBLE_LINES)
  + (MOBILE_COMPOSER_INPUT_VERTICAL_PADDING * 2);
/**
 * 触控目标下限(mobile-design-guide「主操作命中区 ≥ 44×44」,iOS HIG 同值)。
 * 语音听写期间「点输入区停止听写」的命中层用它撑起 inputFrame(见 inputFrameMinHeight)。
 */
export const MOBILE_COMPOSER_MIN_TOUCH_TARGET = 44;
/** 聚焦卡片的顶部留白:iOS 原生卡片 / 其它平台。拖拽热区高度与它相等。 */
const COMPOSER_CARD_PADDING_TOP_IOS = spacing.md;
const COMPOSER_CARD_PADDING_TOP = 26;
const RESIZE_GRABBER_HIT_HEIGHT = Platform.OS === 'ios' ? COMPOSER_CARD_PADDING_TOP_IOS : COMPOSER_CARD_PADDING_TOP;
const isExpoGo =
  Constants.executionEnvironment === ExecutionEnvironment.StoreClient;

export interface MobileComposerInputRowProps {
  entryTransitionId?: string;
  onEntryTransitionComplete?(): void;
  /** Compact (non-card) outer height; on the iOS composer dock it matches the new-task button. */
  collapsedHeight?: number;
  /** When set, a tap on the compact input calls this instead of focusing directly. */
  onCollapsedPress?(): void;
  /** See ComposerFrame; changes when onCollapsedPress opens the pill. */
  expandToken?: string;
  accessibilityHint?: string;
  accessibilityLabel: string;
  /**
   * 卡片内、输入行上方的附加内容(附件缩略图托盘等,对照 Cursor 图片在输入卡内)。
   * 仅 cardActive 形态渲染;简洁态的对应物是 leading 插槽的迷你徽标。
   */
  accessoryAbove?: ReactNode;
  /**
   * accessoryAbove 的自然高度(未显示时为 0)。页面把它计入输入区高度上限:
   * 内容超出时由输入框自身滚动裁掉上方文字,附件保持可见。
   */
  onAccessoryAboveHeightChange?: (height: number) => void;
  /**
   * 聚焦卡片形态开关。true 时输入区独占整行、底部工具排展开;
   * false 时保持单行简洁态,工具排折叠为 0 高(保持挂载,展开时按钮
   * 像抽屉滑出而非淡入重建,配合 useComposerCardTransition 的布局动画)。
   */
  cardActive?: boolean;
  collapseProgress?: SharedValue<number>;
  /** The enclosing scroll surface owns the native glass frame. */
  frameOutside?: boolean;
  /** Scroll attachments/text independently; the toolbar remains outside this viewport. */
  bodyScrollGesture?: NativeGesture;
  bodyScrollRef?: Ref<ScrollView>;
  bodyScrollEnabled?: boolean;
  bodyScrollTestID?: string;
  caretHidden?: boolean;
  compact?: boolean;
  autoFocus?: TextInputProps['autoFocus'];
  cursorColor?: TextInputProps['cursorColor'];
  editable?: boolean;
  /**
   * 语音按钮 render。语音按钮是简洁态与卡片态都存在的常驻控件,
   * 由定位壳包成同一实例:简洁态在输入行右侧垂直居中、卡片态落在底部
   * 工具排(工具排里放 ComposerToolbarVoiceSlot 占位)。壳的样式走
   * resolveMobileComposerVoiceButtonAnchorStyle(数字 top/bottom +
   * justifyContent),并由 voiceButtonTouchTarget 保住至少 44pt 横向命中区;
   * 按钮本身不再吃 absolute inset,避免百分比 top 残留把麦克风停在卡片
   * 中部挡住文字。
   */
  floatingVoiceButton?: (style: StyleProp<ViewStyle>) => ReactNode;
  floatingVoiceButtonStyle?: StyleProp<ViewStyle>;
  /**
   * 输入区(inputFrame)的显式高度:拖拽跟手时传 Animated 值、manual 定高时传数值,
   * null / undefined 走内容自动增长(现状行为)。
   */
  inputFrameHeight?: number | Animated.Value | null;
  inputFrameAnimatedStyle?: ReturnType<typeof useAnimatedStyle>;
  /**
   * 输入区(inputFrame)的最小高度。给语音听写用:听写期间「点输入区停止听写」的命中层
   * 盖在 inputFrame 上,而单行听写时 inputFrame 只有 28pt,不满足触控目标 44pt;
   * hitSlop 解决不了——RN 的命中区不会越过父视图边界,必须让父容器本身够高。
   */
  inputFrameMinHeight?: number;
  /** Rich composer replacement for the plain TextInput. */
  inputElement?: ReactNode;
  inputOverlay?: ReactNode;
  inputRef?: unknown;
  inputStyle?: StyleProp<TextStyle>;
  inputTestID: string;
  leading?: ReactNode;
  maxHeight?: number;
  multiline?: boolean;
  multilineShape?: boolean;
  onBlur?: TextInputProps['onBlur'];
  onChangeText: (value: string) => void;
  onKeyPress?: TextInputProps['onKeyPress'];
  onSelectionChange?: TextInputProps['onSelectionChange'];
  onContentSizeChange?: TextInputProps['onContentSizeChange'];
  onFocus?: TextInputProps['onFocus'];
  /**
   * 粘贴图片回调(expo-paste-input):长按输入框 Paste 剪贴板图片时收到
   * file:// 临时文件 uri 列表,原生侧已阻止图片以默认方式插入文本;
   * 纯文本粘贴不经此回调、行为不变。有值时 TextInput 外包 TextInputWrapper——
   * 本 prop 必须在页面挂载期恒定(恒有值或恒无值),中途 undefined⇄有值切换
   * 会改变子树形状导致 TextInput remount(丢焦点 / 选区)。
   */
  onPasteImages?: (uris: string[]) => void;
  /**
   * 粘贴占位回调(expo-paste-input 本仓 patch 扩展):原生检测到图片粘贴意图时
   * **立即**上抛 count(只查剪贴板类型元数据,不读数据),此时数据读取 / 转码 /
   * 写盘还在原生后台进行——页面用它先画 N 张转圈占位卡,等 onPasteImages 兑现。
   * 旧原生层(未带 patch 的 OTA 场景)不会发这个事件,占位逻辑必须可缺席。
   */
  onPasteImagesLoading?: (count: number) => void;
  /** 粘贴占位失败回调:原生后台读取 / 写盘失败,页面撤掉占位卡。 */
  onPasteImagesLoadFailed?: () => void;
  onPressIn?: TextInputProps['onPressIn'];
  placeholder: string;
  placeholderTextColor: string;
  selection?: TextInputProps['selection'];
  /** 顶部居中的拖拽调高 grabber(ComposerResizeGrabber),absolute 定位不占布局空间。 */
  resizeHandle?: ReactNode;
  rowStyle?: StyleProp<ViewStyle>;
  scrollEnabled?: boolean;
  selectionColor?: TextInputProps['selectionColor'];
  testID?: string;
  /**
   * 底部工具排内容(参考 Cursor 移动端聚焦态)。仅 cardActive 时挂载,
   * 配合 useComposerCardTransition 的 create / delete(opacity)段,
   * 按钮在最终位置原地渐显 / 渐隐,没有位移感;常驻的语音按钮不在此排
   * 渲染(走 floatingVoiceButton 的 absolute 锚点保证位置连续)。
   * card 形态下 leading / trailing 不渲染(工具应放本插槽)。
   */
  toolbar?: ReactNode;
  trailing?: ReactNode;
  value: string;
  voicePlacement?: MobileComposerVoiceButtonPlacement;
}

/**
 * Shared mobile chat composer row.
 *
 * Both the active session composer and the new-session composer use this for
 * the one-layer capsule, text input metrics, and inline-vs-floating voice
 * button placement. Page-specific actions stay injected as slots.
 */
export function MobileComposerInputRow({
  entryTransitionId,
  onEntryTransitionComplete,
  collapsedHeight,
  onCollapsedPress,
  expandToken,
  accessibilityHint,
  accessibilityLabel,
  accessoryAbove,
  onAccessoryAboveHeightChange,
  autoFocus,
  cardActive,
  frameOutside,
  bodyScrollGesture,
  bodyScrollRef,
  bodyScrollEnabled = true,
  bodyScrollTestID,
  collapseProgress,
  caretHidden,
  compact,
  cursorColor,
  editable = true,
  floatingVoiceButton,
  floatingVoiceButtonStyle,
  inputFrameHeight,
  inputFrameAnimatedStyle,
  inputFrameMinHeight,
  inputElement,
  inputOverlay,
  inputRef,
  inputStyle,
  inputTestID,
  leading,
  maxHeight = MOBILE_COMPOSER_INPUT_MAX_HEIGHT,
  multiline = true,
  multilineShape,
  onBlur,
  onChangeText,
  onKeyPress,
  onSelectionChange,
  onContentSizeChange,
  onFocus,
  onPasteImages,
  onPasteImagesLoading,
  onPasteImagesLoadFailed,
  onPressIn,
  placeholder,
  placeholderTextColor,
  selection,
  resizeHandle,
  rowStyle,
  scrollEnabled,
  selectionColor,
  testID,
  toolbar,
  trailing,
  value,
  voicePlacement,
}: MobileComposerInputRowProps) {
  const styles = useThemedStyles(makeMobileComposerInputRowStyles);
  const cardLayout = cardActive === true;
  // 几何居中只看当前是不是收起展示态。resize 在 collapsed 下会把可见高度钉成单行,
  // 但 mode/manual 与多行草稿判定仍会让 multilineShape 为 true;若据此关掉几何居中,
  // 收起态文字会继续走 iOS 6/0 光学偏移,对不齐新增的 34pt +。
  const geometricSingleLine = !cardLayout;
  // iOS composer dock pill: every end control sits concentric with the pill,
  // i.e. its visible circle is as far from the pill edge as from the top and
  // bottom. The leading attachment keeps its 44pt hit area (its visible 34pt
  // circle is centred in it), so the row's left padding gives back that slack.
  const concentricInset = geometricSingleLine && collapsedHeight != null
    ? Math.max(0, (collapsedHeight - MOBILE_COMPOSER_CONTROL_SIZE) / 2) : null;
  // RN 里显式 height 压过 minHeight:manual 定高(用户拖过高度)时 frameHeight 可能小于
  // inputFrameMinHeight,直接铺开会把听写停止命中区又压回不足 44pt。数值高度在这里
  // 先 clamp;拖拽中的 Animated 值无法在 JS 侧 clamp(会打断跟手),那一瞬保持动画值,
  // 松手结算成数值后重新受本 clamp 约束。
  const resolvedInputFrameHeight = typeof inputFrameHeight === 'number' && inputFrameMinHeight != null
    ? Math.max(inputFrameHeight, inputFrameMinHeight)
    : inputFrameHeight;
  // useCallback 稳定引用,避免每次 render 都向原生 TextInputWrapper diff 新函数 prop。
  // images-loading:原生刚检测到图片粘贴意图(数据还在后台读),先画占位;
  // images:原生侧已阻止默认粘贴,上抛进附件链路(占位在此兑现);
  // images-load-failed:后台读取失败,撤占位;
  // text:默认插入已发生;unsupported:无可处理内容——都忽略。
  const handleNativePaste = useCallback((payload: PasteEventPayload) => {
    if (payload.type === 'images' && payload.uris.length > 0) {
      onPasteImages?.(payload.uris);
    } else if (payload.type === 'images-loading' && payload.count > 0) {
      onPasteImagesLoading?.(payload.count);
    } else if (payload.type === 'images-load-failed') {
      onPasteImagesLoadFailed?.();
    }
  }, [onPasteImages, onPasteImagesLoading, onPasteImagesLoadFailed]);
  const bodyScrollNodeRef = useRef<ScrollView | null>(null);
  const setBodyScrollRef = useCallback((node: ScrollView | null) => {
    bodyScrollNodeRef.current = node;
    if (typeof bodyScrollRef === 'function') bodyScrollRef(node);
    else if (bodyScrollRef) (bodyScrollRef as MutableRefObject<ScrollView | null>).current = node;
  }, [bodyScrollRef]);
  // 输入区上限已扣除附件高度,正常不会溢出;极端情况(附件多行、屏幕很矮)仍溢出时贴底,
  // 保证正在输入的文字不被裁掉。
  const pinBodyScrollToEnd = useCallback(() => {
    if (cardLayout) bodyScrollNodeRef.current?.scrollToEnd({ animated: false });
  }, [cardLayout]);
  const showAccessoryAbove = cardLayout && !!accessoryAbove;
  useEffect(() => {
    if (!showAccessoryAbove) onAccessoryAboveHeightChange?.(0);
  }, [showAccessoryAbove, onAccessoryAboveHeightChange]);
  const textInputElement = (
    <TextInput
      ref={inputRef as never}
      accessibilityLabel={accessibilityLabel}
      accessibilityHint={accessibilityHint}
      autoFocus={autoFocus}
      caretHidden={caretHidden}
      cursorColor={cursorColor}
      editable={editable}
      multiline={multiline}
      onBlur={onBlur}
      onChangeText={onChangeText}
      onSelectionChange={onSelectionChange}
      onKeyPress={onKeyPress}
      onContentSizeChange={onContentSizeChange}
      onFocus={onFocus}
      onPressIn={onPressIn}
      placeholder={placeholder}
      placeholderTextColor={placeholderTextColor}
      scrollEnabled={scrollEnabled}
      selection={selection}
      selectionColor={selectionColor}
      style={[
        styles.input,
        geometricSingleLine && styles.inputGeometricSingleLine,
        { maxHeight },
        inputStyle,
      ]}
      testID={inputTestID}
      value={value}
    />
  );
  const inputBody = (
    <>
      {showAccessoryAbove ? (
        <ComposerFoldingSection onNaturalHeight={onAccessoryAboveHeightChange} progress={collapseProgress}>
          {accessoryAbove}
        </ComposerFoldingSection>
      ) : null}
      <View
        style={[
          styles.mainRow,
          geometricSingleLine && styles.mainRowCollapsedTouch,
          !geometricSingleLine && multilineShape && styles.mainRowMultiline,
          !cardLayout && voicePlacement?.inline && styles.mainRowVoiceInset,
        ]}
      >
        {cardLayout ? null : leading}
        <Reanimated.View
          style={[
            styles.inputFrame,
            // 收起单行与 34pt + 并排:输入盒在行内居中。
            geometricSingleLine && inputFrameMinHeight == null && styles.inputFrameSingleLine,
            inputFrameMinHeight != null && { minHeight: inputFrameMinHeight },
            resolvedInputFrameHeight != null && { height: resolvedInputFrameHeight },
            inputFrameAnimatedStyle,
          ]}
        >
          {inputElement ?? (onPasteImages && !isExpoGo ? (
            <TextInputWrapper onPaste={handleNativePaste} style={styles.pasteWrapper}>
              {textInputElement}
            </TextInputWrapper>
          ) : textInputElement)}
          {inputOverlay}
          {!cardLayout && onCollapsedPress ? (
            // VoiceOver still reaches the input itself and focuses it directly.
            <Pressable accessible={false} importantForAccessibility="no-hide-descendants"
              onPress={onCollapsedPress} style={StyleSheet.absoluteFill} testID={testID ? `${testID}.collapsedOpen` : undefined} />
          ) : null}
        </Reanimated.View>
        {cardLayout ? null : trailing}
      </View>
    </>
  );
  return (
    <ComposerFrame
      entryTransitionId={entryTransitionId}
      onEntryTransitionComplete={onEntryTransitionComplete}
      expandToken={expandToken}
      expanded={cardLayout}
      unframed={frameOutside}
      style={[
        styles.row,
        compact && styles.rowCompact,
        geometricSingleLine && styles.rowCollapsedTouch,
        geometricSingleLine && collapsedHeight != null && { minHeight: collapsedHeight },
        concentricInset != null && {
          paddingLeft: Math.max(0, concentricInset - (MOBILE_COMPOSER_MIN_TOUCH_TARGET - MOBILE_COMPOSER_CONTROL_SIZE) / 2),
          paddingRight: concentricInset,
        },
        !geometricSingleLine && multilineShape && styles.rowMultiline,
        cardLayout && styles.rowCard,
        Platform.OS === 'ios' && cardLayout && styles.rowNativeCard,
        // The native frame owns the contour; its child must not add a second corner.
        nativeComposerFrameAvailable && { backgroundColor: 'transparent', borderWidth: 0, borderRadius: 0 },
        rowStyle,
      ]}
      testID={testID}
    >
      {resizeHandle}
      {bodyScrollGesture ? (
        <GestureDetector gesture={bodyScrollGesture}>
          <ScrollView
            ref={setBodyScrollRef}
            onContentSizeChange={pinBodyScrollToEnd}
            onLayout={pinBodyScrollToEnd}
            style={[styles.bodyScroll, geometricSingleLine && styles.bodyScrollCollapsed]}
            contentContainerStyle={[styles.bodyScrollContent, geometricSingleLine && styles.bodyScrollCollapsed]}
            keyboardShouldPersistTaps="handled"
            bounces={false}
            scrollEnabled={cardLayout && bodyScrollEnabled}
            showsVerticalScrollIndicator={cardLayout && bodyScrollEnabled}
            testID={bodyScrollTestID ?? (testID ? `${testID}.bodyScroll` : undefined)}
          >
            {inputBody}
          </ScrollView>
        </GestureDetector>
      ) : inputBody}
      {cardLayout && toolbar != null ? (
        <ComposerFoldingSection progress={collapseProgress}>
        <View
          style={styles.toolbarRow}
          testID={testID ? `${testID}.toolbar` : undefined}
        >
          {toolbar}
        </View>
        </ComposerFoldingSection>
      ) : null}
      {voicePlacement?.inline || voicePlacement?.floating ? (
        <View
          pointerEvents="box-none"
          style={[
            styles.voiceButtonTouchTarget,
            resolveMobileComposerVoiceButtonAnchorStyle({
              cardLayout,
              floating: voicePlacement.floating,
            }),
            // Same concentric inset as the leading control; when floating it
            // steps left of the trailing send / create button.
            concentricInset != null && {
              right: voicePlacement.floating
                ? concentricInset + MOBILE_COMPOSER_CONTROL_SIZE + MOBILE_COMPOSER_TOOL_GAP
                : concentricInset,
            },
          ]}
        >
          {floatingVoiceButton?.(floatingVoiceButtonStyle)}
        </View>
      ) : null}
    </ComposerFrame>
  );
}

/** card 工具排左侧组:[+][权限][计划][模型]。包成一行内组,药丸贴着权限而不是被 spacer 推到右侧。 */
export function ComposerToolbarLeftGroup({
  children,
  testID,
}: {
  children: ReactNode;
  testID?: string;
}) {
  const styles = useThemedStyles(makeMobileComposerInputRowStyles);
  return (
    <View style={styles.toolbarLeftGroup} testID={testID}>
      {children}
    </View>
  );
}

/** card 工具排中把右侧按钮组推向行尾的弹性占位。 */
export function ComposerToolbarSpacer() {
  const styles = useThemedStyles(makeMobileComposerInputRowStyles);
  return <View style={styles.toolbarSpacer} />;
}

/**
 * 工具排 / 输入行 flex 流中语音按钮的等宽占位。真实语音按钮由
 * MobileComposerInputRow 以 absolute 锚点渲染(保证两态同一实例、位置平滑
 * 过渡),流内用本占位为它留出位置。录音中胶囊(红点+计时)比常态宽,由
 * `width` 传入当前胶囊宽度(useMobileVoiceRecordingTimer.pillWidth),占位随
 * 之变宽把左邻按钮推开——胶囊只向左生长,右缘(与发送键的邻接关系)不动。
 */
export function ComposerToolbarVoiceSlot({ width }: { width?: number }) {
  const styles = useThemedStyles(makeMobileComposerInputRowStyles);
  // 与语音按钮外框(VoicePillWidthFrame)同一条宽度过渡,左邻按钮随之平滑让位。
  const widthStyle = useVoicePillWidthStyle(width ?? MOBILE_COMPOSER_CONTROL_SIZE);
  return <Reanimated.View style={[styles.toolbarVoiceSlot, widthStyle]} />;
}

export interface ComposerResizeGrabberProps {
  /** 屏幕阅读器的 increment / decrement 步进调高(useComposerResize.adjustByLine)。 */
  onAdjust?: (direction: 1 | -1) => void;
  /**
   * useComposerResize 输出的 PanResponder handlers + 原生触摸监听
   * (onTouchStart/End/Cancel 驱动 grabberTouchActive,页面据此关闭外壳
   * ScrollView 滚动,防止原生滚动抢走拖拽手势)。
   */
  panHandlers: GestureResponderHandlers & Pick<ViewProps, 'onTouchStart' | 'onTouchEnd' | 'onTouchCancel'>;
  gesture: PanGesture;
  /** 不可见时淡出且不响应触摸,布局位置保持不变(避免出现/消失跳变)。 */
  visible: boolean;
  /** 「聊天记录拖进输入框」在 UI 线程测量顶边位置用(composerPullThrough)。 */
  measureRef?: AnimatedRef<View>;
  testID?: string;
}

function ComposerFoldingSection({ progress, onNaturalHeight, children }: {
  progress?: SharedValue<number>;
  onNaturalHeight?: (height: number) => void;
  children: ReactNode;
}) {
  const measuredHeight = useSharedValue(0);
  const style = useAnimatedStyle(() => {
    const amount = progress?.value ?? 0;
    return {
      height: amount > 0 ? measuredHeight.value * (1 - amount) : 'auto' as const,
      opacity: 1 - amount,
      overflow: 'hidden' as const,
      flexShrink: 0,
    };
  });
  return <Reanimated.View style={style}>
    <View style={{ flexShrink: 0 }} onLayout={event => {
      // Never feed an animated/constrained measurement back into its own height.
      // Keep the natural expanded size until the gesture has fully reversed.
      if ((progress?.value ?? 0) === 0) {
        measuredHeight.value = event.nativeEvent.layout.height;
        onNaturalHeight?.(event.nativeEvent.layout.height);
      }
    }}>
      {children}
    </View>
  </Reanimated.View>;
}

/**
 * Composer 顶部居中的拖拽调高 grabber。
 *
 * absolute 贴在卡片顶部内侧,不参与布局,因此显示 / 隐藏只有透明度变化、
 * 不会引起输入行高度跳变。触摸命中区横跨整条卡片顶边(不只是可见横条附近);
 * 只在聚焦卡片态渲染,此时顶边没有其它按钮;高度不超过卡片顶部留白,
 * 不覆盖下面的附件或文字。
 */
export function ComposerResizeGrabber({ onAdjust, panHandlers, gesture, visible, measureRef, testID }: ComposerResizeGrabberProps) {
  const { colors, mode } = useTheme();
  const { t } = useTranslation();
  const styles = useThemedStyles(makeMobileComposerInputRowStyles);
  const opacity = useRef(new Animated.Value(visible ? 1 : 0)).current;
  const reduceMotion = useReduceMotionEnabled();

  useEffect(() => {
    // 透明度状态切换档 motionDuration.fast(§14.4);出现用 out、消失用 in;减弱动态效果直接到位。
    if (reduceMotion !== false) {
      opacity.setValue(visible ? 1 : 0);
      return undefined;
    }
    const animation = Animated.timing(opacity, {
      duration: motionDuration.fast,
      easing: visible ? Easing.bezier(...motionEasing.out) : Easing.bezier(...motionEasing.in),
      toValue: visible ? 1 : 0,
      useNativeDriver: true,
    });
    animation.start();
    return () => animation.stop();
  }, [opacity, reduceMotion, visible]);

  return (
    <Animated.View
      pointerEvents={visible ? 'box-none' : 'none'}
      style={[styles.resizeGrabberTouch, { opacity }]}
    >
      <GestureDetector gesture={gesture}>
      <Reanimated.View
        ref={measureRef}
        collapsable={false}
        accessibilityActions={[
          { label: t('composer.input.resize.increaseHeight'), name: 'increment' },
          { label: t('composer.input.resize.decreaseHeight'), name: 'decrement' },
        ]}
        accessibilityHint={t('composer.input.resize.hint')}
        accessibilityLabel={t('composer.input.resize.label')}
        accessibilityRole="adjustable"
        onAccessibilityAction={(event) => {
          onAdjust?.(event.nativeEvent.actionName === 'increment' ? 1 : -1);
        }}
        style={styles.resizeGrabberHit}
        testID={testID}
        {...panHandlers}
      >
        <View style={[styles.resizeGrabberBar, mode === 'dark' && { backgroundColor: colors.sheetGrabber, opacity: 0.62 }]} />
      </Reanimated.View>
      </GestureDetector>
    </Animated.View>
  );
}

/** 语音波形:常驻「正在听」状态信号,非交互过渡,不套 motionDuration 交互档位。 */
const VOICE_WAVE_HALF_CYCLE_MS = 550;
const VOICE_WAVE_STAGGER_MS = 180;

export function VoiceMicWaveCaret({ color, testID, viewRef }: { color: string; testID?: string; viewRef?: Ref<View> }) {
  const styles = useThemedStyles(makeMobileComposerInputRowStyles);
  const bar1 = useRef(new Animated.Value(0)).current;
  const bar2 = useRef(new Animated.Value(0)).current;
  const bar3 = useRef(new Animated.Value(0)).current;
  const reduceMotion = useReduceMotionEnabled();

  useEffect(() => {
    const bars = [bar1, bar2, bar3] as const;
    // 常驻循环:减弱动态效果(含未查询到的首帧)下静止在满幅,侧短中长的静态波形。
    if (reduceMotion !== false) {
      bars.forEach((bar) => bar.setValue(1));
      return undefined;
    }
    const loops = bars.map((bar, index) => Animated.loop(
      Animated.sequence([
        Animated.delay(index * VOICE_WAVE_STAGGER_MS),
        Animated.timing(bar, {
          duration: VOICE_WAVE_HALF_CYCLE_MS,
          easing: Easing.inOut(Easing.ease),
          toValue: 1,
          useNativeDriver: true,
        }),
        Animated.timing(bar, {
          duration: VOICE_WAVE_HALF_CYCLE_MS,
          easing: Easing.inOut(Easing.ease),
          toValue: 0,
          useNativeDriver: true,
        }),
      ]),
    ));
    loops.forEach((loop) => loop.start());
    return () => {
      loops.forEach((loop) => loop.stop());
    };
  }, [bar1, bar2, bar3, reduceMotion]);

  const animatedBarStyle = (bar: Animated.Value) => ({
    opacity: bar.interpolate({
      inputRange: [0, 1],
      outputRange: [0.5, 1],
    }),
    transform: [{
      scaleY: bar.interpolate({
        inputRange: [0, 1],
        outputRange: [0.42, 1],
      }),
    }],
  });

  return (
    <View
      pointerEvents="none"
      style={styles.voiceMicCaret}
      ref={viewRef}
      collapsable={false}
      testID={testID}
    >
      <Mic color={color} size={iconSize.lg} strokeWidth={iconStroke.regular} />
      <View style={styles.voiceMicBars}>
        <Animated.View
          style={[
            styles.voiceMicBar,
            styles.voiceMicBarSide,
            { backgroundColor: color },
            animatedBarStyle(bar1),
          ]}
        />
        <Animated.View
          style={[
            styles.voiceMicBar,
            styles.voiceMicBarMiddle,
            { backgroundColor: color },
            animatedBarStyle(bar2),
          ]}
        />
        <Animated.View
          style={[
            styles.voiceMicBar,
            styles.voiceMicBarSide,
            { backgroundColor: color },
            animatedBarStyle(bar3),
          ]}
        />
      </View>
    </View>
  );
}

const makeMobileComposerInputRowStyles = (colors: ThemeColors) => ({
  // 外壳是纵向容器:mainRow(输入行)在上、toolbarRow(工具排)在下;
  // 简洁态工具排折叠为 0 高,外壳看起来就是单行 capsule。
  row: {
    alignItems: 'stretch',
    backgroundColor: colors.chatCodeSurface,
    borderColor: colors.sheetActionBorder,
    borderRadius: radius.pill,
    borderWidth: StyleSheet.hairlineWidth,
    flexDirection: 'column',
    flexShrink: 1,
    minHeight: 50,
    overflow: 'visible',
    paddingHorizontal: spacing.md,
    paddingVertical: 10,
    position: 'relative',
  },
  // 收起态给 leading 的 44pt 热区留出父边界,避免溢出子节点点不到。
  rowCollapsedTouch: {
    minHeight: MOBILE_COMPOSER_MIN_TOUCH_TARGET + 6,
    paddingVertical: 3,
  },
  rowMultiline: {
    borderRadius: 30, // 组件几何:composer 聚焦形态专用,非通用圆角档
  },
  rowCompact: {
    gap: MOBILE_COMPOSER_TOOL_GAP,
  },
  // 聚焦卡片形态:大圆角,paddingTop 给常驻的 grabber 留出呼吸空间
  // (grabber 横条距顶约 8pt、距输入内容约 14pt,参考 Cursor 移动端)。
  rowCard: {
    borderRadius: radius.control,
    paddingBottom: MOBILE_COMPOSER_VOICE_ANCHOR_CARD_BOTTOM,
    paddingTop: COMPOSER_CARD_PADDING_TOP,
  },
  // iOS composer uses the existing 30pt multiline geometry with a native glass surface.
  rowNativeCard: { borderRadius: 30, paddingTop: COMPOSER_CARD_PADDING_TOP_IOS },
  // 水平输入行:简洁态装 [输入][发送],card 态只剩全宽输入区;
  // 语音按钮不在流内(absolute 锚点),简洁态无发送时给它留出右侧空间。
  mainRow: {
    alignItems: 'center',
    flexDirection: 'row',
    flexGrow: 1,
    gap: MOBILE_COMPOSER_TOOL_GAP,
    minWidth: 0,
    overflow: 'visible',
  },
  mainRowCollapsedTouch: {
    minHeight: MOBILE_COMPOSER_MIN_TOUCH_TARGET,
  },
  mainRowMultiline: {
    alignItems: 'flex-end',
  },
  mainRowVoiceInset: {
    paddingRight: MOBILE_COMPOSER_CONTROL_SIZE + MOBILE_COMPOSER_TOOL_GAP,
  },
  inputFrame: {
    alignItems: 'stretch',
    flex: 1,
    flexDirection: 'row',
    minWidth: 0,
    position: 'relative',
  },
  inputFrameSingleLine: {
    alignItems: 'center',
  },
  // TextInputWrapper(expo-paste-input)接管 TextInput 在 inputFrame row 里的
  // flex:1 位置;内部保持 row + stretch,TextInput 自身 flex:1 继续填满,
  // 内容自动增长与显式 inputFrameHeight(拖高)两条高度链都不经它中断。
  pasteWrapper: {
    flex: 1,
    flexDirection: 'row',
    minWidth: 0,
  },
  // Size the viewport to its current children. ScrollView's default flexGrow=1
  // otherwise keeps the old attachment height and absorbs input resize changes.
  bodyScroll: { flexGrow: 0, flexShrink: 1 },
  bodyScrollContent: { flexGrow: 0 },
  // 收起态胶囊(collapsedHeight)比 44pt 输入行高;viewport 与内容都要铺满胶囊,
  // mainRow 才能在胶囊里垂直居中,否则 + 与停止钮贴顶、比浮动语音钮偏上。
  bodyScrollCollapsed: { flexGrow: 1 },
  toolbarRow: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: MOBILE_COMPOSER_TOOL_GAP,
    justifyContent: 'flex-start',
    marginTop: 8,
  },
  toolbarLeftGroup: {
    alignItems: 'center',
    flexDirection: 'row',
    flexShrink: 1,
    gap: MOBILE_COMPOSER_TOOL_GAP,
    justifyContent: 'flex-start',
    minWidth: 0,
  },
  toolbarSpacer: {
    flex: 1,
    minWidth: 0,
  },
  toolbarVoiceSlot: {
    height: MOBILE_COMPOSER_CONTROL_SIZE,
    width: MOBILE_COMPOSER_CONTROL_SIZE,
  },
  // hitSlop 不会越过直接父边界:普通 34pt 麦克风需要至少 44pt 的横向父层。
  // 用 minWidth 而非 width,录音计时胶囊仍可向左自然增宽;alignItems:flex-end
  // 保持按钮右缘和原锚点不变。
  voiceButtonTouchTarget: {
    minWidth: MOBILE_COMPOSER_MIN_TOUCH_TARGET,
  },
  // 字号 / 行高 / 水平内边距全部走 composerTextMetrics:WebView 富文本编辑器与语音
  // 听写覆盖层用同一份度量,三边换行位置必须逐字一致(见该文件注释)。
  input: {
    backgroundColor: 'transparent',
    borderWidth: 0,
    color: colors.textPrimary,
    flex: 1,
    ...COMPOSER_TEXT_STYLE,
    maxHeight: MOBILE_COMPOSER_INPUT_MAX_HEIGHT,
    minHeight: MOBILE_COMPOSER_INPUT_SINGLE_LINE_HEIGHT,
    paddingBottom: COMPOSER_TEXT_PADDING_BOTTOM,
    paddingHorizontal: COMPOSER_TEXT_HORIZONTAL_PADDING,
    paddingTop: COMPOSER_TEXT_PADDING_TOP,
    textAlignVertical: 'top',
  },
  inputGeometricSingleLine: {
    paddingBottom: COMPOSER_TEXT_GEOMETRIC_PADDING_BOTTOM,
    paddingTop: COMPOSER_TEXT_GEOMETRIC_PADDING_TOP,
    textAlignVertical: 'center',
  },
  // 整条卡片顶边都接管拖动,高度恰好等于卡片顶部留白:留白之下是附件托盘或
  // 输入框,热区越界就会抢走缩略图预览 / 移除按钮,或编辑器的点击、选中与系统
  // 粘贴长按。
  resizeGrabberTouch: {
    alignItems: 'stretch',
    height: RESIZE_GRABBER_HIT_HEIGHT,
    left: 0,
    position: 'absolute',
    right: 0,
    top: 0,
    zIndex: 3,
  },
  resizeGrabberHit: {
    alignItems: 'center',
    height: RESIZE_GRABBER_HIT_HEIGHT,
  },
  resizeGrabberBar: {
    backgroundColor: colors.borderTranslucent,
    borderRadius: radius.pill,
    height: 4.5,
    marginTop: 8,
    width: 40,
  },
  voiceMicCaret: {
    alignItems: 'center',
    height: MOBILE_COMPOSER_INPUT_LINE_HEIGHT,
    justifyContent: 'center',
    marginLeft: 2,
    marginRight: 5,
    width: 18,
  },
  voiceMicBars: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: 1.1,
    height: 8,
    justifyContent: 'center',
    left: 5.9,
    overflow: 'hidden',
    position: 'absolute',
    top: 6.8,
    width: 6.2,
  },
  voiceMicBar: {
    borderRadius: radius.pill,
    width: 1.15,
  },
  voiceMicBarSide: {
    height: 3.4,
  },
  voiceMicBarMiddle: {
    height: 6.4,
  },
} satisfies Record<string, ViewStyle | TextStyle>);