langfuse

Форк
0
176 строк · 4.1 Кб
1
import * as React from "react";
2
import type * as LabelPrimitive from "@radix-ui/react-label";
3
import { Slot } from "@radix-ui/react-slot";
4
import {
5
  Controller,
6
  type ControllerProps,
7
  type FieldPath,
8
  type FieldValues,
9
  FormProvider,
10
  useFormContext,
11
} from "react-hook-form";
12

13
import { cn } from "@/src/utils/tailwind";
14
import { Label } from "@/src/components/ui/label";
15

16
const Form = FormProvider;
17

18
type FormFieldContextValue<
19
  TFieldValues extends FieldValues = FieldValues,
20
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
21
> = {
22
  name: TName;
23
};
24

25
const FormFieldContext = React.createContext<FormFieldContextValue>(
26
  {} as FormFieldContextValue,
27
);
28

29
const FormField = <
30
  TFieldValues extends FieldValues = FieldValues,
31
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
32
>({
33
  ...props
34
}: ControllerProps<TFieldValues, TName>) => {
35
  return (
36
    <FormFieldContext.Provider value={{ name: props.name }}>
37
      <Controller {...props} />
38
    </FormFieldContext.Provider>
39
  );
40
};
41

42
const useFormField = () => {
43
  const fieldContext = React.useContext(FormFieldContext);
44
  const itemContext = React.useContext(FormItemContext);
45
  const { getFieldState, formState } = useFormContext();
46

47
  const fieldState = getFieldState(fieldContext.name, formState);
48

49
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
50
  if (!fieldContext) {
51
    throw new Error("useFormField should be used within <FormField>");
52
  }
53

54
  const { id } = itemContext;
55

56
  return {
57
    id,
58
    name: fieldContext.name,
59
    formItemId: `${id}-form-item`,
60
    formDescriptionId: `${id}-form-item-description`,
61
    formMessageId: `${id}-form-item-message`,
62
    ...fieldState,
63
  };
64
};
65

66
type FormItemContextValue = {
67
  id: string;
68
};
69

70
const FormItemContext = React.createContext<FormItemContextValue>(
71
  {} as FormItemContextValue,
72
);
73

74
const FormItem = React.forwardRef<
75
  HTMLDivElement,
76
  React.HTMLAttributes<HTMLDivElement>
77
>(({ className, ...props }, ref) => {
78
  const id = React.useId();
79

80
  return (
81
    <FormItemContext.Provider value={{ id }}>
82
      <div ref={ref} className={cn("space-y-2", className)} {...props} />
83
    </FormItemContext.Provider>
84
  );
85
});
86
FormItem.displayName = "FormItem";
87

88
const FormLabel = React.forwardRef<
89
  React.ElementRef<typeof LabelPrimitive.Root>,
90
  React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
91
>(({ className, ...props }, ref) => {
92
  const { error, formItemId } = useFormField();
93

94
  return (
95
    <Label
96
      ref={ref}
97
      className={cn(error && "text-destructive", className)}
98
      htmlFor={formItemId}
99
      {...props}
100
    />
101
  );
102
});
103
FormLabel.displayName = "FormLabel";
104

105
const FormControl = React.forwardRef<
106
  React.ElementRef<typeof Slot>,
107
  React.ComponentPropsWithoutRef<typeof Slot>
108
>(({ ...props }, ref) => {
109
  const { error, formItemId, formDescriptionId, formMessageId } =
110
    useFormField();
111

112
  return (
113
    <Slot
114
      ref={ref}
115
      id={formItemId}
116
      aria-describedby={
117
        !error ? formDescriptionId : `${formDescriptionId} ${formMessageId}`
118
      }
119
      aria-invalid={!!error}
120
      {...props}
121
    />
122
  );
123
});
124
FormControl.displayName = "FormControl";
125

126
const FormDescription = React.forwardRef<
127
  HTMLParagraphElement,
128
  React.HTMLAttributes<HTMLParagraphElement>
129
>(({ className, ...props }, ref) => {
130
  const { formDescriptionId } = useFormField();
131

132
  return (
133
    <p
134
      ref={ref}
135
      id={formDescriptionId}
136
      className={cn("text-sm text-muted-foreground", className)}
137
      {...props}
138
    />
139
  );
140
});
141
FormDescription.displayName = "FormDescription";
142

143
const FormMessage = React.forwardRef<
144
  HTMLParagraphElement,
145
  React.HTMLAttributes<HTMLParagraphElement>
146
>(({ className, children, ...props }, ref) => {
147
  const { error, formMessageId } = useFormField();
148
  const body = error ? String(error.message) : children;
149

150
  if (!body) {
151
    return null;
152
  }
153

154
  return (
155
    <p
156
      ref={ref}
157
      id={formMessageId}
158
      className={cn("text-sm font-medium text-destructive", className)}
159
      {...props}
160
    >
161
      {body}
162
    </p>
163
  );
164
});
165
FormMessage.displayName = "FormMessage";
166

167
export {
168
  useFormField,
169
  Form,
170
  FormItem,
171
  FormLabel,
172
  FormControl,
173
  FormDescription,
174
  FormMessage,
175
  FormField,
176
};
177

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.