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。

12.9 KB
Raw Blame
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { PanResponder } from 'react-native';
import Constants, { ExecutionEnvironment } from 'expo-constants';
import { runOnJS, runOnUI, useAnimatedReaction, useAnimatedStyle, useDerivedValue, useSharedValue } from 'react-native-reanimated';
import { Gesture } from '@/platform/gestureHandler';
import { COMPOSER_TEXT_LINE_HEIGHT, COMPOSER_TEXT_VERTICAL_PADDING } from '@/session/composerTextMetrics';
import {
  COMPOSER_RESIZE_DRAG_ACTIVATION_THRESHOLD,
  applyComposerResizeDrag,
  composerCollapseProgress,
  buildComposerResizeGestureConfig,
  buildComposerResizeTouchHandlers,
  computeComposerResizeBounds,
  resolveComposerInputHeight,
  settleComposerResizeDrag,
  shouldDismissComposerDuringDrag,
  shouldDismissComposerOnRelease,
} from '@/session/composerResize';
import { composerPullTranslation, type ComposerPullEvent, type ComposerPullThroughBridge } from '@/session/composerPullThrough';

const isStoreClient = Constants.executionEnvironment === ExecutionEnvironment.StoreClient;

export interface UseComposerResizeInput {
  contentHeight: number;
  autoMaxContentHeight: number;
  windowHeight: number;
  keyboardHeight: number;
  singleLineContentHeight: number;
  composerChromeHeight: number;
  collapsed?: boolean;
  minFrameHeight?: number;
  onSnapToAuto?: () => void;
  /** Only gesture boundaries cross to JS; never publish per-frame heights. */
  onGrabberTouchActiveChange?: (active: boolean) => void;
  /** 聊天记录拖进输入框时由列表侧接手;与按住顶边拖动走同一套调高逻辑。 */
  pullThrough?: ComposerPullThroughBridge;
}

/** UI-thread resize. React remembers the settled height, not the pointer stream. */
export function useComposerResize(input: UseComposerResizeInput) {
  const [userContentHeight, setUserContentHeight] = useState<number | null>(null);
  const [dragging, setDragging] = useState(false);
  const [completedGesture, setCompletedGesture] = useState(0);
  const mounted = useRef(true);
  const latest = useRef(input);
  latest.current = input;
  const bounds = computeComposerResizeBounds(input);
  const model = resolveComposerInputHeight({ ...input, bounds, userContentHeight });
  const geometry = useSharedValue({ bounds, visibleHeight: model.visibleContentHeight, explicit: input.collapsed === true || model.mode === 'manual', minFrameHeight: input.minFrameHeight ?? 0, autoMaxHeight: input.autoMaxContentHeight });
  const active = useSharedValue(false);
  const awaitingCollapse = useSharedValue(false);
  const gestureId = useSharedValue(0);
  const startHeight = useSharedValue(model.visibleContentHeight);
  const dragHeight = useSharedValue(model.visibleContentHeight);
  const dragTranslation = useSharedValue(0);
  const startAbsoluteY = useSharedValue(0);
  const dismissedGestureId = useSharedValue(0);
  useLayoutEffect(() => {
    const nextGeometry = { collapsed: input.collapsed === true, bounds, visibleHeight: model.visibleContentHeight, explicit: input.collapsed === true || model.mode === 'manual', minFrameHeight: input.minFrameHeight ?? 0, autoMaxHeight: input.autoMaxContentHeight };
    // Check the generation and publish together on UI: another gesture may
    // begin between React's commit and delivery of this geometry update.
    runOnUI((next: typeof nextGeometry, completed: number) => {
      'worklet';
      geometry.value = next;
      if (completed === gestureId.value && (!awaitingCollapse.value || next.collapsed)) {
        active.value = false;
        awaitingCollapse.value = false;
      }
    })(nextGeometry, completedGesture);
  }, [active, awaitingCollapse, bounds.minContentHeight, bounds.maxContentHeight, completedGesture, gestureId, input.autoMaxContentHeight, input.collapsed, input.minFrameHeight, model.mode, model.visibleContentHeight, geometry]);

  const begin = useCallback((id: number) => {
    if (!mounted.current || id !== gestureId.value) return;
    latest.current.onGrabberTouchActiveChange?.(true);
    setDragging(true);
  }, [gestureId]);
  const finish = useCallback((height: number, initialHeight: number, translationY: number, successful: boolean, id: number) => {
    if (!mounted.current || id !== gestureId.value) return;
    const current = latest.current;
    const currentBounds = computeComposerResizeBounds(current);
    if (successful) {
      if (Math.abs(height - initialHeight) >= COMPOSER_RESIZE_DRAG_ACTIVATION_THRESHOLD) {
        setUserContentHeight(settleComposerResizeDrag({ bounds: currentBounds, contentHeight: current.contentHeight, draggedContentHeight: height }));
      }
      if (shouldDismissComposerOnRelease({ bounds: currentBounds, draggedContentHeight: height, translationY })) {
        awaitingCollapse.value = !!current.onSnapToAuto;
        current.onSnapToAuto?.();
      }
    }
    setDragging(false);
    setCompletedGesture(id);
    current.onGrabberTouchActiveChange?.(false);
  }, [awaitingCollapse, gestureId]);

  // 手柄拖动与「聊天记录拖进输入框」共用的三段 UI 线程逻辑。
  const drag = useMemo(() => {
    const beginAt = (absoluteY: number) => {
      'worklet';
      startAbsoluteY.value = absoluteY;
      awaitingCollapse.value = false;
      gestureId.value += 1;
      // A second drag can begin before the first JS completion is delivered.
      startHeight.value = active.value ? dragHeight.value : geometry.value.visibleHeight;
      active.value = true;
      dragHeight.value = startHeight.value;
      dragTranslation.value = 0;
      runOnJS(begin)(gestureId.value);
    };
    const moveBy = (translationY: number) => {
      'worklet';
      if (dismissedGestureId.value === gestureId.value) return;
      dragTranslation.value = translationY;
      dragHeight.value = applyComposerResizeDrag({ bounds: geometry.value.bounds, startContentHeight: startHeight.value, translationY });
      // 拖到一行、折叠完工具栏后再多拉一段即收起,不等松手。
      if (shouldDismissComposerDuringDrag({ bounds: geometry.value.bounds, startContentHeight: startHeight.value, translationY })) {
        dismissedGestureId.value = gestureId.value;
        runOnJS(finish)(dragHeight.value, startHeight.value, translationY, true, gestureId.value);
      }
    };
    const finalize = (translationY: number, successful: boolean) => {
      'worklet';
      // 已在拖动途中收起:之后的抬手或取消不再结算。
      if (dismissedGestureId.value === gestureId.value) return;
      if (!successful) {
        // Cancellation must restore the settled frame even while JS is busy,
        // so a new gesture cannot inherit the canceled temporary height.
        dragHeight.value = geometry.value.visibleHeight;
        active.value = false;
      }
      runOnJS(finish)(dragHeight.value, startHeight.value, translationY, successful, gestureId.value);
    };
    return { beginAt, moveBy, finalize };
  }, [active, awaitingCollapse, begin, dismissedGestureId, dragHeight, dragTranslation, finish, geometry, gestureId, startAbsoluteY, startHeight]);

  const scrollGesture = useMemo(() => Gesture.Native(), []);
  const gesture = useMemo(() => Gesture.Pan()
    // Dedicated grabber: own the touch before the keyboard's ancestor ScrollView.
    .minDistance(0)
    .blocksExternalGesture(scrollGesture)
    .onBegin((event) => {
      'worklet';
      drag.beginAt(event.absoluteY);
    })
    .onUpdate((event) => {
      'worklet';
      // The grabber itself moves with the resizing frame. Use screen coordinates
      // so its changing origin cannot feed back into the drag distance.
      drag.moveBy(Number.isFinite(event.absoluteY)
        ? event.absoluteY - startAbsoluteY.value
        : event.translationY);
    })
    .onFinalize((event, successful) => {
      'worklet';
      drag.finalize(Number.isFinite(event.absoluteY)
        ? event.absoluteY - startAbsoluteY.value
        : event.translationY, successful);
    }), [drag, scrollGesture, startAbsoluteY]);

  // 列表侧接手:event 每次都带完整位置,同一帧内合并的 begin / move / end 也能按状态补齐。
  const pullThroughEvent = input.pullThrough?.event;
  const pullThroughId = useSharedValue(0);
  const pullThroughOpen = useSharedValue(false);
  useAnimatedReaction(
    () => pullThroughEvent?.value ?? null,
    (event: ComposerPullEvent | null) => {
      if (event === null || event.id <= 0) return;
      if (event.active) {
        if (event.id > pullThroughId.value) {
          pullThroughId.value = event.id;
          pullThroughOpen.value = true;
          drag.beginAt(event.startY);
        }
        if (event.id === pullThroughId.value && pullThroughOpen.value) drag.moveBy(composerPullTranslation(event));
        return;
      }
      // 只收尾已经开始的那次接手;开始与结束挤在同一帧时什么都没发生,无需收尾。
      if (event.id !== pullThroughId.value || !pullThroughOpen.value) return;
      pullThroughOpen.value = false;
      const translationY = composerPullTranslation(event);
      drag.moveBy(translationY);
      drag.finalize(translationY, event.successful);
    },
    [drag, pullThroughEvent],
  );

  useLayoutEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      latest.current.onGrabberTouchActiveChange?.(false);
    };
  }, []);

  // Expo Go deliberately disables RNGH in the platform adapter. Keep its
  // existing JS fallback; installed apps never attach a PanResponder.
  const panHandlers = useMemo(() => {
    if (!isStoreClient) return {};
    let initial = 0;
    let height = 0;
    let id = 0;
    const responder = PanResponder.create(buildComposerResizeGestureConfig({
      onGrant: () => {
        awaitingCollapse.value = false;
        initial = geometry.value.visibleHeight;
        startHeight.value = initial;
        dragTranslation.value = 0;
        height = initial;
        dragHeight.value = height;
        active.value = true;
        id = ++gestureId.value;
        begin(id);
      },
      onMove: (translationY) => {
        dragTranslation.value = translationY;
        height = applyComposerResizeDrag({ bounds: geometry.value.bounds, startContentHeight: initial, translationY });
        dragHeight.value = height;
      },
      onEnd: (translationY) => finish(height, initial, translationY, true, id),
    }));
    responder.panHandlers.onResponderTerminate = () => {
      dragHeight.value = geometry.value.visibleHeight;
      active.value = false;
      finish(height, initial, 0, false, id);
    };
    return { ...responder.panHandlers, ...buildComposerResizeTouchHandlers((value) => latest.current.onGrabberTouchActiveChange?.(value)) };
  }, [active, awaitingCollapse, begin, dragHeight, dragTranslation, finish, geometry, gestureId, startHeight]);

  const collapseProgress = useDerivedValue(() => active.value
    ? composerCollapseProgress({ bounds: geometry.value.bounds, startContentHeight: startHeight.value, translationY: dragTranslation.value })
    : 0);

  const contentHeight = useDerivedValue(() => active.value
    ? Math.max(geometry.value.bounds.minContentHeight, Math.min(dragHeight.value, geometry.value.bounds.maxContentHeight))
    : geometry.value.visibleHeight);
  const frameStyle = useAnimatedStyle(() => ({
    // Native animated updates omit undefined props, retaining the previous
    // height/cap. Explicitly restore intrinsic sizing with 'auto' and replace
    // the auto cap with the drag ceiling before begin can reach JS.
    maxHeight: active.value || geometry.value.explicit
      ? Math.max(geometry.value.minFrameHeight, geometry.value.bounds.maxContentHeight + COMPOSER_TEXT_VERTICAL_PADDING * 2)
      : geometry.value.autoMaxHeight,
    height: active.value || geometry.value.explicit
      ? Math.max(geometry.value.minFrameHeight, contentHeight.value + COMPOSER_TEXT_VERTICAL_PADDING * 2)
      : 'auto' as const,
  }));
  const reset = useCallback(() => setUserContentHeight(null), []);
  const adjustByLine = useCallback((direction: 1 | -1) => {
    const current = latest.current;
    const currentBounds = computeComposerResizeBounds(current);
    const height = applyComposerResizeDrag({ bounds: currentBounds, startContentHeight: geometry.value.visibleHeight, translationY: -direction * COMPOSER_TEXT_LINE_HEIGHT });
    setUserContentHeight(settleComposerResizeDrag({ bounds: currentBounds, contentHeight: current.contentHeight, draggedContentHeight: height }));
  }, [geometry]);

  return {
    adjustByLine,
    active,
    contentHeight,
    collapseProgress,
    dragging,
    frameStyle,
    gesture,
    // The inner TextInput/WebView must be ready to fill any UI-driven frame;
    // waiting for React dragging here would clip it during a busy JS thread.
    inputMaxHeight: Math.max(input.autoMaxContentHeight, bounds.maxContentHeight + COMPOSER_TEXT_VERTICAL_PADDING * 2),
    maxFrameHeight: bounds.maxContentHeight + COMPOSER_TEXT_VERTICAL_PADDING * 2,
    mode: model.mode,
    panHandlers,
    reset,
    scrollEnabled: model.scrollEnabled,
    scrollGesture,
    visibleContentHeight: model.visibleContentHeight,
  };
}