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。

9.2 KB
Raw Blame
import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import { iconSize, useTheme } from '@/theme';
import { NativeErrorNotice } from '@/components/NativeErrorNotice.ios';
import { ComposerNativeSection as Section } from './ComposerNativeSection';
import { useNativeTextDraft } from './nativeTextDraft';
import {
  createContext,
  useContext,
  useEffect,
  useRef,
} from "react";
import { Button, HStack, Image, Picker, RNHostView, ProgressView, Spacer, Text, TextField, VStack } from '@expo/ui/swift-ui';
import {
  accessibilityAddTraits,
  accessibilityHint,
  accessibilityLabel,
  buttonStyle,
  contentShape,
  disabled as disable,
  font,
  frame,
  foregroundStyle,
  lineLimit,
  listRowInsets,
  onLongPressGesture,
  onTapGesture,
  pickerStyle,
  shapes,
  tag,
  tint,
} from "@expo/ui/swift-ui/modifiers";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import type {
  ContextSheetChoiceRowProps,
  ContextSheetGroupProps,
  ContextSheetSelectRowProps,
  ContextSheetProps,
  ContextSheetRowProps,
  ContextSheetFooterButtonProps,
  ContextSheetTextFieldProps,
} from "./ContextSheet";
import { ComposerSheet } from "./ComposerSheet";
import { ComposerSectionSettingsHeader } from './composerSectionHeader';
const DismissAction = createContext<(action: () => void) => void>((action) =>
  action(),
);

export function ContextSheet(props: ContextSheetProps) {
  const { t } = useTranslation();
  const pending = useRef<(() => void) | null>(null);
  const { colors } = useTheme();
  // Reopening during the dismiss animation drops the previous row action, so a later
  // ordinary close cannot replay a stale picker.
  useEffect(() => {
    if (props.visible) pending.current = null;
  }, [props.visible]);
  return (
    <DismissAction.Provider
      value={(action) => {
        pending.current = action;
        props.onClose();
      }}
    >
      <ComposerSectionSettingsHeader.Provider value>
        <ComposerSheet
          {...props}
          title={props.onBack ? props.title : ''}
          aboveContent={props.media}
          aboveContentTitle={t("session.common.groupAdd")}
          nativeContent
          onClosed={() => {
            const action = pending.current;
            pending.current = null;
            action?.();
          }}
          footer={props.footer}
        >
          {props.children}
          {props.error ? (
            <Section>
              <NativeErrorNotice message={props.error} />
            </Section>
          ) : null}
        </ComposerSheet>
      </ComposerSectionSettingsHeader.Provider>
    </DismissAction.Provider>
  );
}
export function ContextSheetGroup({
  label,
  children,
  footer,
  footerTone,
  footerTestID,
}: ContextSheetGroupProps) {
  // 说明写在卡片下方(原生 Section footer)。
  return (
    <Section
      title={label || undefined}
      footer={footer ? <ContextSheetNote text={footer} tone={footerTone} testID={footerTestID} /> : undefined}
    >
      {children}
    </Section>
  );
}
export function ContextSheetRow(props: ContextSheetRowProps) {
  const dismiss = useContext(DismissAction);
  const { colors } = useTheme();
  const labelModifiers = props.destructive ? [foregroundStyle(colors.destructive)] : [];
  const press = () => (props.dismissBeforePress ? dismiss(props.onPress) : props.onPress());
  const inactive = !!props.disabled || !!props.busy;
  const content = (extraModifiers: ReturnType<typeof frame>[]) => (
    <HStack
      modifiers={[
        frame({ maxWidth: Infinity, minHeight: 44 }),
        contentShape(shapes.rectangle()),
        ...extraModifiers,
      ]}
    >
      {props.icon ? (
        <RNHostView matchContents>
          <View style={{ width: 28, height: 28, justifyContent: "center" }}>
            {props.icon}
          </View>
        </RNHostView>
      ) : null}
      {props.detail ? (
        <VStack alignment="leading" spacing={2}>
          <Text modifiers={[...labelModifiers, lineLimit(1)]}>{props.label}</Text>
          <Text modifiers={[font({ textStyle: 'footnote' }), foregroundStyle(colors.textSecondary), lineLimit(1)]}>{props.detail}</Text>
        </VStack>
      ) : (
        <Text modifiers={labelModifiers}>{props.label}</Text>
      )}
      <Spacer />
      {props.value && !props.busy ? (
        <Text modifiers={[foregroundStyle(colors.textSecondary), lineLimit(1)]}>{props.value}</Text>
      ) : null}
      {props.busy ? (
        <ProgressView />
      ) : props.trailing && props.trailing !== "chevron" ? (
        <RNHostView matchContents>
          {/* matchContents reads this RN View's bounds, not the nested icon's size. */}
          <View style={props.trailingSize != null ? {
            width: props.trailingSize,
            height: props.trailingSize,
            alignItems: 'center',
            justifyContent: 'center',
          } : undefined}>{props.trailing}</View>
        </RNHostView>
      ) : props.trailing === "chevron" ? (
        <Image size={iconSize.lg} systemName="chevron.right" color={colors.textTertiary} />
      ) : null}
    </HStack>
  );
  const accessibility = props.accessibilityHint ? [accessibilityHint(props.accessibilityHint)] : [];
  if (props.onLongPress) {
    // 带长按的行(协同 Worker):SwiftUI Button 与长按手势会互相抢,改用同一视图上的
    // 点按 + 长按手势,点按直接执行,长按弹出管理操作。
    const longPress = props.onLongPress;
    return content([
      listRowInsets({ top: 4, bottom: 4, leading: 16, trailing: 16 }),
      disable(inactive),
      accessibilityAddTraits(['isButton']),
      ...accessibility,
      ...(inactive ? [] : [onTapGesture(press), onLongPressGesture(longPress)]),
    ]);
  }
  return (
    <Button
      onPress={press}
      testID={props.testID}
      modifiers={[
        buttonStyle("plain"),
        listRowInsets({ top: 4, bottom: 4, leading: 16, trailing: 16 }),
        disable(inactive),
        ...accessibility,
      ]}
    >
      {content([])}
    </Button>
  );
}
export function ContextSheetFooterButton(props: ContextSheetFooterButtonProps) {
  const { colors } = useTheme();
  const glassStyle = useNativeGlassButtonStyle({ prominent: true });
  return (
    <Button
      onPress={props.onPress}
      testID={props.testID}
      modifiers={[
        ...glassStyle,
        disable(!!props.disabled || !!props.busy),
      ]}
    >
      {/* 撑满宽度的 frame 放在标签里:放在 Button 上只会放大点击区,胶囊仍按文字收缩。 */}
      {props.busy
        ? <ProgressView modifiers={[tint(colors.ctaText), frame({ maxWidth: Infinity, minHeight: 44 })]} />
        : <Text modifiers={[foregroundStyle(colors.ctaText), frame({ maxWidth: Infinity, minHeight: 44 })]}>{props.label}</Text>}
    </Button>
  );
}

export function ContextSheetNote({ text, tone = 'secondary', testID }: {
  text: string;
  tone?: 'secondary' | 'error';
  testID?: string;
}) {
  const { colors } = useTheme();
  return (
    <Text testID={testID} modifiers={[font({ textStyle: 'footnote' }), foregroundStyle(tone === 'error' ? colors.errorText : colors.textSecondary)]}>
      {text}
    </Text>
  );
}

/** 由现有 Section 提供独立操作失败的卡片容器。 */
export function ContextSheetError({ text, testID }: { text: string; testID?: string }) {
  return <NativeErrorNotice message={text} testID={testID} />;
}

export function ContextSheetChoiceRow<T extends string>(props: ContextSheetChoiceRowProps<T>) {
  return (
    <Picker
      label={props.label}
      selection={props.value ?? ''}
      onSelectionChange={(next: string | number) => {
        const option = props.options.find((item) => item.id === String(next));
        if (option) props.onChange(option.id);
      }}
      modifiers={[pickerStyle(props.options.length <= 3 ? 'segmented' : 'menu'), disable(!!props.disabled)]}
      testID={props.testID}
    >
      {props.options.map((option) => (
        <Text key={option.id} modifiers={[tag(option.id)]}>{option.label}</Text>
      ))}
    </Picker>
  );
}

export function ContextSheetSelectRow(props: ContextSheetSelectRowProps) {
  return (
    <Picker
      label={props.label}
      selection={props.value}
      onSelectionChange={(next: string | number) => {
        if (!props.disabled && props.options.some((option) => option.id === String(next) && !option.disabled)) {
          props.onChange(String(next));
        }
      }}
      modifiers={[pickerStyle('menu'), disable(!!props.disabled)]}
      testID={props.testID}
    >
      {props.options.map((option) => (
        <Text key={option.id} modifiers={[tag(option.id), disable(!!option.disabled)]}>
          {option.detail ? `${option.label} · ${option.detail}` : option.label}
        </Text>
      ))}
    </Picker>
  );
}

export function ContextSheetTextField(props: ContextSheetTextFieldProps) {
  const draft = useNativeTextDraft(props.value, props.onChange);
  return (
    <TextField
      text={draft.text}
      onTextChange={draft.onTextChange}
      axis={props.multiline ? 'vertical' : 'horizontal'}
      placeholder={props.placeholder}
      maxLength={props.maxLength}
      testID={props.testID}
      modifiers={[
        disable(!!props.disabled),
        accessibilityLabel(props.accessibilityLabel),
        ...(props.multiline ? [lineLimit({ min: 3, max: 6 })] : []),
      ]}
    />
  );
}