# useFieldControl

`useFieldControl(props, options)` связывает ваш контрол с подписью, подсказкой и ошибкой поля.
Используйте его, когда пишете свой контрол для `NuiField` и форм.

Композабл возвращает `attrs` с `id`, `aria-describedby`, `aria-invalid`, `required` и `disabled`.
Повесьте их на элемент ввода. Оберните разметку контрола в `NuiFieldFrame`: вне `NuiField` он сам
выведет подпись, подсказку и ошибку.

`index.vue`

```vue
<template>
  <NuiField label="Оценка" description="От 1 до 5" class="max-w-sm">
    <RatingControl v-model="rating" />
    <p class="m-0 text-sm text-muted-foreground">Поставлена оценка {{ rating }} из 5.</p>
  </NuiField>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { NuiField } from '@numior/kit';
import RatingControl from './RatingControl.vue';

const rating = ref(4);
</script>
```

`RatingControl.vue`

```vue
<template>
  <div :id="attrs.id" :aria-describedby="attrs['aria-describedby']" role="group" class="flex gap-1">
    <NuiButton
      v-for="score in SCORES"
      :key="score"
      size="sm"
      :variant="score <= rating ? 'solid' : 'outline'"
      :tone="score <= rating ? 'primary' : 'neutral'"
      :aria-pressed="score <= rating"
      @click="rating = score"
    >
      {{ score }}
    </NuiButton>
  </div>
</template>

<script setup lang="ts">
import { NuiButton, useFieldControl } from '@numior/kit';

const SCORES = [1, 2, 3, 4, 5];

const rating = defineModel<number>({ required: true });

const { attrs } = useFieldControl(() => ({}), { group: true });
</script>
```

## Сигнатура

```ts
import { useFieldControl } from '@numior/kit';

useFieldControl: (props: MaybeRefOrGetter<FieldControlProps>, options?: FieldControlOptions) => FieldControl
```

```ts
import type { FieldControlProps } from '@numior/kit';

interface FieldControlProps {
  readonly id?: string | undefined;
  readonly invalid?: boolean | undefined;
  readonly required?: boolean | undefined;
  readonly disabled?: boolean | undefined;
  readonly readonly?: boolean | undefined;
  readonly label?: string | undefined;
  readonly description?: string | undefined;
  readonly error?: string | undefined;
}
```

```ts
import type { FieldControlOptions } from '@numior/kit';

interface FieldControlOptions {
  readonly group?: boolean | undefined;
  readonly detached?: boolean | undefined;
  readonly inlineLabel?: boolean | undefined;
  readonly readonlyAttr?: FieldReadonlyAttr | undefined;
  readonly commit?: (() => void) | undefined;
}
```

```ts
import type { FieldControl } from '@numior/kit';

interface FieldControl {
  readonly id: ComputedRef<string>;
  readonly invalid: ComputedRef<boolean>;
  readonly required: ComputedRef<boolean>;
  readonly disabled: ComputedRef<boolean>;
  readonly readonly: ComputedRef<boolean>;
  readonly describedBy: ComputedRef<string | undefined>;
  readonly attrs: ComputedRef<FieldControlAttrs>;
  readonly field: ComputedRef<FieldContext | null>;
  readonly own: ComputedRef<boolean>;
  readonly frame: ComputedRef<FieldFrame>;
}
```

```ts
import { useFieldContext } from '@numior/kit';

useFieldContext: () => FieldContext | null
```

```ts
import type { FieldContext } from '@numior/kit';

interface FieldContext {
  readonly id: ComputedRef<string>;
  readonly labelId: ComputedRef<string>;
  readonly labelledBy: ComputedRef<string | undefined>;
  readonly descriptionId: ComputedRef<string>;
  readonly errorId: ComputedRef<string>;
  readonly describedBy: ComputedRef<string | undefined>;
  readonly invalid: ComputedRef<boolean>;
  readonly required: ComputedRef<boolean>;
  readonly disabled: ComputedRef<boolean>;
  readonly readonly: ComputedRef<boolean>;
  readonly labelable: ComputedRef<boolean>;
}
```

```ts
import { useControlId } from '@numior/kit';

useControlId: (explicit?: MaybeRefOrGetter<string | undefined>) => ComputedRef<string>
```

```ts
import { useRadioGroup } from '@numior/kit';

useRadioGroup: () => RadioGroupContext | null
```

```ts
import type { RadioGroupContext } from '@numior/kit';

interface RadioGroupContext<T = unknown> {
  readonly name: ComputedRef<string>;
  readonly modelValue: Ref<T | undefined>;
  readonly selectedKey: ComputedRef<string | undefined>;
  readonly disabled: ComputedRef<boolean>;
  readonly readonly: ComputedRef<boolean>;
  readonly invalid: ComputedRef<boolean>;
  keyOf(value: T): string;
  select(value: T): void;
}
```

```ts
import { useSplitAttrs } from '@numior/kit';

useSplitAttrs: (rootKeys?: ReadonlySet<string>) => SplitAttrs
```

```ts
import type { SplitAttrs } from '@numior/kit';

interface SplitAttrs {
  rootAttrs(): AttrRecord;
  controlAttrs(): AttrRecord;
}
```

## Поведение

`props` — геттер, который возвращает `id`, `invalid`, `required`, `disabled`, `label`,
`description` и `error` контрола. Опции:

- `commit` — функция, которая сохраняет недописанное значение перед отправкой формы, например
  дату, набранную не до конца;
- `group` — контрол состоит из нескольких элементов, как группа радиокнопок;
- `detached` — контрол не связывается с внешним `NuiField`.

Вспомогательные функции:

- `useFieldContext()` возвращает поле, внутри которого стоит контрол;
- `useControlId()` даёт id, который совпадает на сервере и в браузере;
- `useRadioGroup()` возвращает группу, в которой стоит радиокнопка;
- `useSplitAttrs()` делит `$attrs` на атрибуты корневого элемента и элемента ввода.
