diff --git a/.storybook/preview.ts b/.storybook/preview.ts index bd5a1c5f..78c56666 100644 --- a/.storybook/preview.ts +++ b/.storybook/preview.ts @@ -68,6 +68,9 @@ const preview: Preview = { globals: { theme: 'light' }, }, controls: { + // Полная таблица в панели Controls: имя, описание, тип, дефолт и группы категорий. + // В компактном режиме Storybook 10 описание пропса не отображается. + expanded: true, matchers: { color: /(background|color)$/i, date: /Date$/i diff --git a/docs/components-api/inputtext.md b/docs/components-api/inputtext.md index 9103c14b..6ca8f124 100644 --- a/docs/components-api/inputtext.md +++ b/docs/components-api/inputtext.md @@ -4,27 +4,28 @@ > ✅ **Реализован**: `ExtraInputTextComponent` (`@cdek-it/angular-ui-kit`) соответствует спецификации. -| Свойство | Описание | Типизация | По умолчанию | -| ---------------- | ----------------------------------------------------------------------------- | ---------------------------------- | ------------ | -| `placeholder` | текст подсказки внутри поля | `string` | `''` | -| `label` | текст названия поля | `string` | `''` | -| `labelPosition` | положение лейбла | `top \| left` | `top` | -| `floatLabel` | плавающий лейбл внутри поля (перекрывает `labelPosition`) | `boolean` | `false` | -| `clearable` | отображение иконки для очистки поля | `boolean` | `false` | -| `caption` | текст пояснения под полем | `string` | `''` | -| `info` | текст с доп. информацией (показывается в тултипе иконки ti-info-circle) | `string` | `''` | -| `size` | размер поля | `small \| base \| large \| xlarge` | `base` | -| `fluid` | растягивает поле на всю ширину контейнера | `boolean` | `false` | -| `type` | тип поля input | `text \| password` | `text` | -| `readonly` | только для чтения | `boolean` | `false` | -| `required` | поле обязательно для заполнения | `boolean` | `false` | -| `name` | имя поля (нативный атрибут `name`); используется браузером для автозаполнения | `string` | — | -| `autocomplete` | значение нативного атрибута `autocomplete` | `string` | — | -| `maxLength` | максимальное количество символов | `number` | — | -| `ariaLabel` | метка для программ экранного доступа | `string` | — | -| `ariaLabelledBy` | `id` внешнего элемента-метки для доступности | `string` | — | -| `autofocus` | автофокус при монтировании компонента | `boolean` | `false` | -| `tabindex` | порядок перехода по Tab | `number` | — | +| Свойство | Описание | Типизация | По умолчанию | +| ----------------- | ------------------------------------------------------------------------------- | ---------------------------------- | ------------ | +| `placeholder` | текст подсказки внутри поля | `string` | `''` | +| `label` | текст названия поля | `string` | `''` | +| `labelPosition` | положение лейбла: сверху, плавающий внутри поля или слева | `default \| float \| left` | `default` | +| `requiredMark` | маркер «\*» перед лейблом (только визуальный, валидацию не включает) | `boolean` | `false` | +| `clearable` | отображение иконки для очистки поля | `boolean` | `false` | +| `caption` | текст пояснения под полем | `string` | `''` | +| `captionSeverity` | вариант подписи (цвет и иконка): `base`, `success`, `warning`, `danger`, `info` | `ExtraCaptionSeverity` | `base` | +| `info` | текст с доп. информацией (показывается в тултипе иконки ti-info-circle) | `string` | `''` | +| `size` | размер поля | `small \| base \| large \| xlarge` | `base` | +| `fluid` | растягивает поле на всю ширину контейнера | `boolean` | `false` | +| `type` | тип поля input | `text \| password` | `text` | +| `readonly` | только для чтения | `boolean` | `false` | +| `required` | поле обязательно для заполнения | `boolean` | `false` | +| `name` | имя поля (нативный атрибут `name`); используется браузером для автозаполнения | `string` | — | +| `autocomplete` | значение нативного атрибута `autocomplete` | `string` | — | +| `maxLength` | максимальное количество символов | `number` | — | +| `ariaLabel` | метка для программ экранного доступа | `string` | — | +| `ariaLabelledBy` | `id` внешнего элемента-метки для доступности | `string` | — | +| `autofocus` | автофокус при монтировании компонента | `boolean` | `false` | +| `tabindex` | порядок перехода по Tab | `number` | — | # Стекозависимые пропсы diff --git a/src/lib/components/inputtext/inputtext.component.ts b/src/lib/components/inputtext/inputtext.component.ts index 4a80cd7a..5880679c 100644 --- a/src/lib/components/inputtext/inputtext.component.ts +++ b/src/lib/components/inputtext/inputtext.component.ts @@ -27,9 +27,10 @@ import { IconField } from 'primeng/iconfield'; import { InputIcon } from 'primeng/inputicon'; import { FloatLabel } from 'primeng/floatlabel'; import { ExtraTooltipDirective } from '@cdek-it/angular-ui-kit/components/tooltip'; +import { ExtraCaptionComponent, ExtraCaptionSeverity } from '@cdek-it/angular-ui-kit/components/caption'; export type ExtraInputTextSize = 'small' | 'base' | 'large' | 'xlarge'; -export type ExtraInputTextLabelPosition = 'top' | 'left'; +export type ExtraInputTextLabelPosition = 'default' | 'float' | 'left'; export type ExtraInputTextType = 'text' | 'password'; let nextInputId = 0; @@ -37,7 +38,16 @@ let nextInputId = 0; @Component({ selector: 'extra-input-text', standalone: true, - imports: [InputText, IconField, InputIcon, FloatLabel, NgClass, NgTemplateOutlet, ExtraTooltipDirective], + imports: [ + InputText, + IconField, + InputIcon, + FloatLabel, + NgClass, + NgTemplateOutlet, + ExtraTooltipDirective, + ExtraCaptionComponent + ], host: { style: 'display: contents' }, providers: [ { @@ -55,13 +65,12 @@ let nextInputId = 0; @if (label || caption) { - -
- @if (label && labelPosition === 'left' && !floatLabel) { +
+ @if (label && labelPosition === 'left') { }
- @if (floatLabel) { + @if (labelPosition === 'float') { @if (label) { @@ -69,13 +78,13 @@ let nextInputId = 0; } } @else { - @if (label && labelPosition === 'top') { + @if (label && labelPosition === 'default') { } } @if (caption) { -
{{ caption }}
+ {{ caption }} }
@@ -85,8 +94,11 @@ let nextInputId = 0; @@ -103,8 +115,8 @@ let nextInputId = 0; [fluid]="fluid" [type]="type" [disabled]="disabled" - [invalid]="invalid" [readOnly]="readonly" + [invalid]="invalid" [autofocus]="autofocus" [attr.placeholder]="placeholder || null" [attr.name]="name || null" @@ -118,17 +130,17 @@ let nextInputId = 0; (input)="onInput($event)" (blur)="onTouched()" /> - @if (modelValue && !readonly && !disabled) { - - } + } @else { ` (nodeId `15:13444`, fileKey `Khh7arsuXss3ncqy1Dz3OZ`, библиотека «UI Kit (DS) v2.0»). Лейбл, плавающий лейбл и подпись (caption) компонент рисует сам (`label` / `labelPosition` / `floatLabel` / `caption` / `info`); без них рендерится голое поле без обёртки. +Компонент соответствует Figma-компоненту `` (nodeId `15:13444`, fileKey `Khh7arsuXss3ncqy1Dz3OZ`, библиотека «UI Kit (DS) v2.0»). Лейбл, плавающий лейбл и подпись (caption) компонент рисует сам (`label` / `labelPosition` / `caption` / `info`); без них рендерится голое поле без обёртки. ## Props mapping -| Свойство | Тип | По умолчанию | Описание | -|----------|-----|--------------|---------| -| `placeholder` | `string` | `''` | Подсказка при пустом поле — соответствует Figma-свойству `text-placeholder` / `has-placeholder` | -| `label` | `string` | `''` | Текст лейбла; при пустых `label`/`caption` поле рендерится без обёртки | -| `labelPosition` | `'top' \| 'left'` | `'top'` | Положение лейбла относительно поля; игнорируется при `floatLabel=true` | -| `floatLabel` | `boolean` | `false` | Плавающий лейбл внутри поля (PrimeNG `p-floatlabel` variant="in"); перекрывает `labelPosition` — соответствует Figma-свойству `has-floatlabel` | -| `caption` | `string` | `''` | Подпись под полем | -| `info` | `string` | `''` | Текст всплывающей подсказки (иконка ℹ рядом с лейблом) | -| `size` | `'small' \| 'base' \| 'large' \| 'xlarge'` | `'base'` | Размер поля; `large` и `xlarge` маппируются на PrimeNG `pSize="large"` | -| `readonly` | `boolean` | `false` | Только для чтения: ввод и очистка недоступны — соответствует Figma-состоянию `state=readonly` | -| `required` | `boolean` | `false` | Поле обязательно для заполнения: контрол невалиден, пока значение не введено/не выбрано; работает как NG_VALIDATORS-валидатор | -| `clearable` | `boolean` | `false` | Показывает иконку очистки (×) при наличии значения — соответствует Figma-свойству `show-clear` | -| `fluid` | `boolean` | `false` | Растягивает поле на всю ширину контейнера | -| `name` | `string \| undefined` | `undefined` | Имя внутреннего input для браузерного автозаполнения | -| `autocomplete` | `string \| undefined` | `undefined` | Нативный атрибут autocomplete | -| `maxLength` | `number \| undefined` | `undefined` | Максимальное количество символов | -| `ariaLabel` | `string \| undefined` | `undefined` | Доступное имя поля | -| `ariaLabelledBy` | `string \| undefined` | `undefined` | ID внешнего элемента-метки | -| `autofocus` | `boolean` | `false` | Автофокус при монтировании поля | -| `tabindex` | `number \| undefined` | `undefined` | Порядок перехода по Tab | -| `disabled` | `boolean` | `false` | Отключённое состояние — управляется через `FormControl.disable()` или `ControlValueAccessor.setDisabledState`; соответствует Figma-состоянию `state=disabled` | -| `(onClear)` | `EventEmitter` | — | Событие при нажатии на иконку очистки (только при `clearable=true`) | -| `[(ngModel)]` / `[formControl]` | `string` | `''` | Значение поля через ControlValueAccessor — соответствует Figma-свойству `text-input` | +| Свойство | Тип | По умолчанию | Описание | +| ------------------------------- | -------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `placeholder` | `string` | `''` | Подсказка при пустом поле — соответствует Figma-свойству `text-placeholder` / `has-placeholder` | +| `label` | `string` | `''` | Текст лейбла; при пустых `label`/`caption` поле рендерится без обёртки | +| `labelPosition` | `'default' \| 'float' \| 'left'` | `'default'` | Положение лейбла: сверху, внутри поля (`float`, Figma `has-float-label=true`) или слева | +| `caption` | `string` | `''` | Подпись под полем | +| `captionSeverity` | `'base' \| 'success' \| 'warning' \| 'danger' \| 'info'` | `'base'` | Вариант подписи (цвет и иконка), Figma `_` variant | +| `requiredMark` | `boolean` | `false` | Маркер «\*» перед лейблом (Figma `is-required`), валидацию не включает | +| `info` | `string` | `''` | Текст всплывающей подсказки (иконка ℹ рядом с лейблом) | +| `size` | `'small' \| 'base' \| 'large' \| 'xlarge'` | `'base'` | Размер поля; `large` и `xlarge` маппируются на PrimeNG `pSize="large"` | +| `readonly` | `boolean` | `false` | Только для чтения: ввод и очистка недоступны — соответствует Figma-состоянию `state=readonly` | +| `required` | `boolean` | `false` | Поле обязательно для заполнения: контрол невалиден, пока значение не введено/не выбрано; работает как NG_VALIDATORS-валидатор | +| `clearable` | `boolean` | `false` | Показывает иконку очистки (×) при наличии значения — соответствует Figma-свойству `show-clear` | +| `fluid` | `boolean` | `false` | Растягивает поле на всю ширину контейнера | +| `name` | `string \| undefined` | `undefined` | Имя внутреннего input для браузерного автозаполнения | +| `autocomplete` | `string \| undefined` | `undefined` | Нативный атрибут autocomplete | +| `maxLength` | `number \| undefined` | `undefined` | Максимальное количество символов | +| `ariaLabel` | `string \| undefined` | `undefined` | Доступное имя поля | +| `ariaLabelledBy` | `string \| undefined` | `undefined` | ID внешнего элемента-метки | +| `autofocus` | `boolean` | `false` | Автофокус при монтировании поля | +| `tabindex` | `number \| undefined` | `undefined` | Порядок перехода по Tab | +| `disabled` | `boolean` | `false` | Отключённое состояние — управляется через `FormControl.disable()` или `ControlValueAccessor.setDisabledState`; соответствует Figma-состоянию `state=disabled` | +| `(onClear)` | `EventEmitter` | — | Событие при нажатии на иконку очистки (только при `clearable=true`) | +| `[(ngModel)]` / `[formControl]` | `string` | `''` | Значение поля через ControlValueAccessor — соответствует Figma-свойству `text-input` | > `invalid` — вычисляемое свойство: берётся автоматически из связанного `NgControl` (соответствует Figma-состоянию `state=danger`). Устанавливать вручную нельзя. @@ -54,11 +55,7 @@ updated: '2026-06-22' Figma: ``, state=default, has-placeholder=true, has-floatlabel=false — nodeId `15:13443` ```html - + ``` ### С кнопкой очистки (show-clear) @@ -66,12 +63,7 @@ Figma: ``, state=default, has-placeholder=true, has-floatlabel=false Figma: ``, state=default, show-clear=true — nodeId `15:13443` ```html - + ``` ### Disabled (отключённое поле) @@ -79,10 +71,7 @@ Figma: ``, state=default, show-clear=true — nodeId `15:13443` Figma: ``, state=disabled — nodeId `15:13439` ```html - + ``` ```ts @@ -113,10 +102,7 @@ emailControl = new FormControl('', [Validators.required, Validators.email]); ``` ```html - + ``` ### Readonly (только для чтения) @@ -124,13 +110,25 @@ emailControl = new FormControl('', [Validators.required, Validators.email]); Figma: ``, state=readonly — nodeId `14978:17413` ```html - + ``` +## Геометрия (Figma 1:1) + +Размеры в px. В Figma размер задаёт мод коллекции `sizing` (`form.*`), а не ось компонента: small / base / large / xlarge. + +| `size` | Высота | Шрифт / межстрочный | padding Y / X | Радиус | Иконка | +| -------- | ------ | ------------------- | ------------- | ------ | ------ | +| `small` | 36 | 14 / 14 | 10 / 12 | 10 | 14 | +| `base` | 42 | 16 / 16 | 12 / 12 | 10 | 16 | +| `large` | 50 | 18 / 20 | 14 / 12 | 10 | 18 | +| `xlarge` | 56 | 20 / 26 | 14 / 12 | 10 | 20 | + +- Высота задана явно: Chrome не делает текстовый input ниже собственной высоты строки, поэтому одним `line-height` 36 и 42 не получить. +- Label: Noto Sans 14 / 14, иконка `info` 14. Caption: Noto Sans 14 / 14, letter-spacing −0.32. Размер поля на них не влияет. +- Рамка поля при ошибке — `border.status.danger.strong`, кольцо фокуса — `border.status.danger.focus`. +- В Figma у Label есть маркер обязательности (`*`, 12 / 14), в API его нет. + ## Slots Нет — поле атомарное. Проекция содержимого не поддерживается. Для добавления prefix/suffix-иконок используйте `` — см. [inputgroup.figma.md](../inputgroup/inputgroup.figma.md). @@ -144,6 +142,7 @@ Figma: ``, state=readonly — nodeId `14978:17413` ## Do / Don't **Do:** + - Используйте `[(ngModel)]` или `[formControl]` — компонент реализует `ControlValueAccessor` и именно через них передаётся значение. - Управляйте состоянием `disabled` через `FormControl.disable()` / `FormControl.enable()` — это сохраняет dirty/touched-флаги. - Для сброса поля через иконку × включайте `[clearable]="true"` и подписывайтесь на `(onClear)` при необходимости пост-обработки. @@ -151,6 +150,7 @@ Figma: ``, state=readonly — nodeId `14978:17413` - Оберните поле в `` или `` для добавления label, подсказки и prefix/suffix. **Don't:** + - Не подменяйте `value` через прямой DOM (`document.querySelector('input').value = ...`) — теряется `dirty`-state и Angular-реактивность. - Не задавайте `[disabled]="true"` как Input-атрибут напрямую — компонент не объявляет `@Input() disabled`; передавайте через `FormControl` или `ControlValueAccessor`. - Не используйте поле без `[(ngModel)]` / `[formControl]` — без привязки значение не синхронизируется с моделью. diff --git a/src/lib/providers/prime-preset/tokens/components/inputtext.ts b/src/lib/providers/prime-preset/tokens/components/inputtext.ts index 670f8374..d6a57e34 100644 --- a/src/lib/providers/prime-preset/tokens/components/inputtext.ts +++ b/src/lib/providers/prime-preset/tokens/components/inputtext.ts @@ -52,25 +52,21 @@ export const inputtextCss = ({ dt }: { dt: (token: string) => string }): string gap: ${dt('dimension.space.100')}; color: ${dt('color.fg.default')}; font-family: ${dt('fonts.fontFamily.base')}; - font-size: ${dt('fonts.fontSize.300')}; + font-size: ${dt('fonts.fontSize.200')}; font-weight: ${dt('fonts.fontWeight.regular')}; - line-height: ${dt('fonts.lineHeight.300')}; + line-height: ${dt('fonts.lineHeight.200')}; cursor: pointer; } .extra-inputtext-label-icon { color: ${dt('color.fg.subtle')}; - font-size: ${dt('inputtext.extend.iconSize')}; + font-size: ${dt('dimension.size.400')}; cursor: help; } -/* ─── Caption ─── */ -.extra-inputtext-caption { - color: ${dt('color.fg.subtle')}; - font-family: ${dt('fonts.fontFamily.heading')}; - font-size: ${dt('fonts.fontSize.200')}; - font-weight: ${dt('fonts.fontWeight.regular')}; - line-height: ${dt('fonts.lineHeight.250')}; +/* ─── Маркер обязательности ─── */ +.extra-inputtext-required { + color: ${dt('color.fg.status.danger.default')}; } /* Внутри p-floatlabel лейбл лежит поверх поля — курсор должен быть как у ввода */ @@ -115,9 +111,34 @@ export const inputtextCss = ({ dt }: { dt: (token: string) => string }): string box-shadow: 0 0 0 ${dt('inputtext.root.focusRing.width')} ${dt('color.border.status.danger.focus')}; } +/* ─── Высота по размерам ─── + Chrome не даёт текстовому input стать ниже собственной высоты строки (normal ≈ 1.36 от шрифта), + поэтому line-height 14 и 16 высоту не задают: 36 и 42 из макета держим явно. */ +.p-inputtext { + height: ${dt('inputtext.extend.height')}; +} +.p-inputtext.p-inputtext-sm { + height: ${dt('inputtext.extend.extSm.height')}; +} +.p-inputtext.p-inputtext-lg { + height: ${dt('inputtext.extend.extLg.height')}; +} +.p-inputtext.p-inputtext-xlg { + height: ${dt('inputtext.extend.extXlg.height')}; +} + +/* ─── Межстрочный интервал по размерам (Figma: form.lineHeight в модах small / large / xlarge) ─── */ +.p-inputtext.p-inputtext-sm { + line-height: ${dt('fonts.lineHeight.200')}; +} +.p-inputtext.p-inputtext-lg { + line-height: ${dt('fonts.lineHeight.400')}; +} + /* ─── Extra Large ─── */ .p-inputtext.p-inputtext-xlg { font-size: ${dt('inputtext.extend.extXlg.fontSize')}; + line-height: ${dt('fonts.lineHeight.550')}; padding: ${dt('inputtext.extend.extXlg.paddingY')} ${dt('inputtext.extend.extXlg.paddingX')}; } @@ -132,4 +153,49 @@ export const inputtextCss = ({ dt }: { dt: (token: string) => string }): string height: ${dt('inputtext.extend.iconSize')}; cursor: pointer; } + +/* Размер иконки в поле зависит от размера поля (Figma: form.iconSize в модах sizing) */ +.p-iconfield:has(.p-inputtext-sm) .p-inputicon { + font-size: ${dt('inputtext.extend.extSm.iconSize')}; + width: ${dt('inputtext.extend.extSm.iconSize')}; + height: ${dt('inputtext.extend.extSm.iconSize')}; +} +.p-iconfield:has(.p-inputtext-lg) .p-inputicon { + font-size: ${dt('inputtext.extend.extLg.iconSize')}; + width: ${dt('inputtext.extend.extLg.iconSize')}; + height: ${dt('inputtext.extend.extLg.iconSize')}; +} +.p-iconfield:has(.p-inputtext-xlg) .p-inputicon { + font-size: ${dt('inputtext.extend.extXlg.iconSize')}; + width: ${dt('inputtext.extend.extXlg.iconSize')}; + height: ${dt('inputtext.extend.extXlg.iconSize')}; +} + +/* ─── Float label (Figma: has-float-label=true) ─── + Поле выше обычного (min-height 56) и с радиусом 14; контент центрируется внутри min-height, + поэтому поднятый лейбл стоит на 2px выше значения floatlabel.in.active.top, а текст ввода — на 2px + выше paddingTop (Figma: лейбл y=12, ввод y=26 при paddingTop 10 и контенте 28 в поле 56). */ +.p-floatlabel:has(> .p-inputtext) > .p-inputtext { + height: ${dt('inputtext.extend.extXlg.height')}; + border-radius: ${dt('dimension.borderRadius.400')}; + padding-top: calc(${dt('floatlabel.in.input.paddingTop')} - ${dt('dimension.space.50')}); +} +/* В покое лейбл остаётся «лейблом» и при заданном placeholder (Figma: has-placeholder=true); + PrimeNG в этом случае поднимает его правилом :has(input[placeholder]), поэтому селектор усилен :not() */ +.p-floatlabel:has(> .p-inputtext:not(:focus):not(.p-filled):not(:-webkit-autofill)) > label { + top: 50%; + margin-top: calc(${dt('fonts.lineHeight.400')} / -2); + font-size: ${dt('fonts.fontSize.200')}; + line-height: ${dt('fonts.lineHeight.400')}; +} +.p-floatlabel:has(> .p-inputtext:not(:focus)) > .p-inputtext::placeholder { + color: transparent; +} +.p-floatlabel:has(> .p-inputtext:focus) > label, +.p-floatlabel:has(> .p-inputtext.p-filled) > label, +.p-floatlabel:has(> .p-inputtext:-webkit-autofill) > label { + top: calc(${dt('floatlabel.in.active.top')} - ${dt('dimension.space.50')}); + font-size: ${dt('floatlabel.root.active.fontSize')}; + line-height: ${dt('fonts.lineHeight.150')}; +} `; diff --git a/src/lib/providers/prime-preset/tokens/tokens.json b/src/lib/providers/prime-preset/tokens/tokens.json index c8cb9366..e3537b9a 100644 --- a/src/lib/providers/prime-preset/tokens/tokens.json +++ b/src/lib/providers/prime-preset/tokens/tokens.json @@ -3164,7 +3164,7 @@ "floatlabel": { "extend": { "height": "{dimension.size.1400}", - "iconSize": "{dimension.size.600}" + "iconSize": "{dimension.size.450}" }, "root": { "color": "{color.fg.muted}", @@ -3185,7 +3185,7 @@ "top": "{dimension.space.400}" } }, - "inside": { + "in": { "input": { "paddingTop": "{dimension.space.800}", "paddingBottom": "{dimension.space.400}" @@ -3446,10 +3446,21 @@ "iconSize": "{dimension.size.450}", "borderWidth": "{dimension.borderWidth.100}", "extXlg": { - "fontSize": "{fonts.fontSize.300}", - "paddingX": "{dimension.space.300}", - "paddingY": "{dimension.space.600}" - } + "fontSize": "{fonts.fontSize.500}", + "paddingX": "{dimension.space.350}", + "paddingY": "{dimension.space.400}", + "iconSize": "{dimension.size.600}", + "height": "{dimension.size.1300}" + }, + "extSm": { + "iconSize": "{dimension.size.400}", + "height": "{dimension.size.1000}" + }, + "extLg": { + "iconSize": "{dimension.size.500}", + "height": "{dimension.size.1250}" + }, + "height": "{dimension.size.1150}" }, "root": { "background": "{color.bg.surface.default.default}", @@ -3460,24 +3471,24 @@ "borderColor": "{color.border.neutral.strong}", "hoverBorderColor": "{color.border.brand.strong}", "focusBorderColor": "{color.border.brand.strong}", - "invalidBorderColor": "{color.border.status.danger.subtle}", + "invalidBorderColor": "{color.border.status.danger.strong}", "color": "{color.fg.default}", "disabledColor": "{color.fg.muted}", "placeholderColor": "{color.fg.muted}", "invalidPlaceholderColor": "{color.fg.status.danger.hover}", "shadow": "{effects.elevation.none}", - "paddingX": "{dimension.space.300}", - "paddingY": "{dimension.space.300}", - "borderRadius": "{dimension.borderRadius.400}", + "paddingX": "{dimension.space.350}", + "paddingY": "{dimension.space.350}", + "borderRadius": "{dimension.borderRadius.300}", "transitionDuration": "{effects.transition.duration.200}", "sm": { - "fontSize": "{fonts.fontSize.300}", - "paddingX": "{dimension.space.300}", - "paddingY": "{dimension.space.200}" + "fontSize": "{fonts.fontSize.200}", + "paddingX": "{dimension.space.350}", + "paddingY": "{dimension.space.300}" }, "lg": { - "fontSize": "{fonts.fontSize.300}", - "paddingX": "{dimension.space.300}", + "fontSize": "{fonts.fontSize.400}", + "paddingX": "{dimension.space.350}", "paddingY": "{dimension.space.400}" }, "focusRing": { @@ -3485,7 +3496,7 @@ "style": "none", "color": "{color.border.focus}", "offset": "{dimension.focusRing.offset}", - "shadow": "{effects.elevation.none}" + "shadow": "{effects.focusRing.none}" } } }, diff --git a/src/stories/components/inputtext/examples/inputtext-labels.component.ts b/src/stories/components/inputtext/examples/inputtext-labels.component.ts index 2e43e0f4..a51dc180 100644 --- a/src/stories/components/inputtext/examples/inputtext-labels.component.ts +++ b/src/stories/components/inputtext/examples/inputtext-labels.component.ts @@ -14,7 +14,7 @@ const template = ` > @@ -76,7 +76,7 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; diff --git a/src/stories/components/inputtext/examples/inputtext-reactive-forms.component.ts b/src/stories/components/inputtext/examples/inputtext-reactive-forms.component.ts index 09960510..70187c2d 100644 --- a/src/stories/components/inputtext/examples/inputtext-reactive-forms.component.ts +++ b/src/stories/components/inputtext/examples/inputtext-reactive-forms.component.ts @@ -55,7 +55,7 @@ const styles = ` margin: 0; padding: 0.75rem 1rem; border-radius: 0.5rem; - background: var(--p-surface-100); + border: 1px solid color-mix(in srgb, currentColor 15%, transparent); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.8125rem; } @@ -98,43 +98,15 @@ export const ReactiveForms: StoryObj = { 'Компонент реализует ControlValueAccessor, поэтому `[formControl]` работает в обе стороны. Ввод с клавиатуры и очистка иконкой × пишут значение в контрол (value, dirty), blur помечает его touched, а `setValue()`, `reset()`, `disable()` / `enable()` со стороны формы обновляют само поле. Состояние invalid берётся из NgControl — красная рамка появляется по Validators, без отдельного пропа.' }, source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; -import { ExtraInputTextComponent, ExtraButtonComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-inputtext-reactive-forms', - standalone: true, - imports: [ExtraInputTextComponent, ExtraButtonComponent, ReactiveFormsModule], - template: \` - - - - - - - -

value: {{ email.value }} / status: {{ email.status }} / touched: {{ email.touched }}

- \`, -}) -export class InputTextReactiveFormsComponent { - email = new FormControl('', [Validators.required, Validators.email]); - - toggleDisabled(): void { - if (this.email.disabled) this.email.enable(); - else this.email.disable(); - } -} - ` + language: 'html', + transform: () => `` } } } diff --git a/src/stories/components/inputtext/examples/inputtext-sizes.component.ts b/src/stories/components/inputtext/examples/inputtext-sizes.component.ts index 6cbf62c7..fd440078 100644 --- a/src/stories/components/inputtext/examples/inputtext-sizes.component.ts +++ b/src/stories/components/inputtext/examples/inputtext-sizes.component.ts @@ -19,7 +19,7 @@ const template = ` template }) export class InputTextSizesComponent { - sizes = ['small', 'base', 'large', 'xlarge']; + sizes = ['small', 'base', 'large', 'xlarge'] as const; control = new FormControl(''); } diff --git a/src/stories/components/inputtext/inputtext.stories.ts b/src/stories/components/inputtext/inputtext.stories.ts index 233e7fa6..3984b83d 100644 --- a/src/stories/components/inputtext/inputtext.stories.ts +++ b/src/stories/components/inputtext/inputtext.stories.ts @@ -1,37 +1,29 @@ import { Meta, moduleMetadata, StoryObj } from '@storybook/angular'; import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; import { ExtraInputTextComponent } from '../../../lib/components/inputtext/inputtext.component'; -import { InputTextClearableComponent, Clearable } from './examples/inputtext-clearable.component'; -import { InputTextLabelsComponent, Labels } from './examples/inputtext-labels.component'; -import { InputTextSizesComponent, Sizes } from './examples/inputtext-sizes.component'; -import { InputTextStatesComponent, States } from './examples/inputtext-states.component'; -import { InputTextTypesComponent, Types } from './examples/inputtext-types.component'; -import { InputTextFluidComponent, Fluid } from './examples/inputtext-fluid.component'; -import { InputTextReactiveFormsComponent, ReactiveForms } from './examples/inputtext-reactive-forms.component'; +import { + InputTextReactiveFormsComponent, + ReactiveForms as ReactiveFormsStory +} from './examples/inputtext-reactive-forms.component'; -type InputTextArgs = ExtraInputTextComponent & { disabled: boolean; invalid: boolean }; +type InputTextArgs = ExtraInputTextComponent & { disabled: boolean; invalid: boolean; value: string }; const meta: Meta = { title: 'Components/Form/InputText', component: ExtraInputTextComponent, - tags: ['autodocs'], + tags: ['autodocs', 'inputtext'], decorators: [ moduleMetadata({ - imports: [ - ExtraInputTextComponent, - ReactiveFormsModule, - InputTextLabelsComponent, - InputTextSizesComponent, - InputTextClearableComponent, - InputTextTypesComponent, - InputTextStatesComponent, - InputTextFluidComponent, - InputTextReactiveFormsComponent - ] + imports: [ExtraInputTextComponent, ReactiveFormsModule, InputTextReactiveFormsComponent] }) ], parameters: { docs: { + source: { + language: 'html', + transform: (_code: string, context: { args: Partial> }) => + renderInputText(context.args).template + }, description: { component: `Текстовое поле для ввода данных. @@ -67,17 +59,17 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; }, labelPosition: { control: 'select', - options: ['top', 'left'], + options: ['default', 'float', 'left'], description: 'Положение лейбла', table: { category: 'Свойства', - defaultValue: { summary: 'top' }, - type: { summary: "'top' | 'left'" } + defaultValue: { summary: 'default' }, + type: { summary: "'default' | 'float' | 'left'" } } }, - floatLabel: { + requiredMark: { control: 'boolean', - description: 'Плавающий лейбл внутри поля (перекрывает labelPosition)', + description: 'Маркер «*» перед лейблом (только визуальный)', table: { category: 'Свойства', defaultValue: { summary: 'false' }, @@ -93,6 +85,15 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; type: { summary: 'boolean' } } }, + readonly: { + control: 'boolean', + description: 'Только чтение; очистка поля недоступна', + table: { + category: 'Свойства', + defaultValue: { summary: 'false' }, + type: { summary: 'boolean' } + } + }, caption: { control: 'text', description: 'Текст пояснения под полем', @@ -102,6 +103,16 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; type: { summary: 'string' } } }, + captionSeverity: { + control: 'select', + options: ['base', 'success', 'warning', 'danger', 'info'], + description: 'Вариант подписи под полем: меняет цвет и иконку', + table: { + category: 'Свойства', + defaultValue: { summary: "'base'" }, + type: { summary: "'base' | 'success' | 'warning' | 'danger' | 'info'" } + } + }, info: { control: 'text', description: 'Текст с доп. информацией (показывается в тултипе иконки ti-info-circle)', @@ -140,11 +151,6 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; type: { summary: "'text' | 'password'" } } }, - readonly: { - control: 'boolean', - description: 'Только чтение; очистка поля недоступна', - table: { category: 'Свойства', defaultValue: { summary: 'false' }, type: { summary: 'boolean' } } - }, required: { control: 'boolean', description: 'Пустое поле делает FormControl невалидным', @@ -204,6 +210,15 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; type: { summary: 'boolean' } } }, + value: { + control: 'text', + description: 'Значение FormControl', + table: { + category: 'Состояния', + defaultValue: { summary: "''" }, + type: { summary: 'string' } + } + }, // ── События ─────────────────────────────────────────────────── onClear: { control: false, @@ -220,17 +235,18 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; inputId: { table: { disable: true } } }, args: { - placeholder: 'Введите текст...', - label: '', - labelPosition: 'top', - floatLabel: false, + placeholder: 'Placeholder', + label: 'Label', + labelPosition: 'default', + requiredMark: true, clearable: false, - caption: '', - info: '', + readonly: false, + caption: 'Caption', + captionSeverity: 'base', + info: 'Info', size: 'base', fluid: false, type: 'text', - readonly: false, required: false, name: undefined, autocomplete: undefined, @@ -240,59 +256,132 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; autofocus: false, tabindex: undefined, disabled: false, - invalid: false + invalid: false, + value: '' } }; export default meta; type Story = StoryObj; -// ── Default (интерактивная) ────────────────────────────────────────────────── +// ── Один рендер компонента ─────────────────────────────────────────────────── +// Каждая сторис — пресет варианта Figma (comp-json/FORM/InputText/STORIES.md): в args задана +// только её ось, остальное равно варианту Figma по умолчанию и меняется в Controls. +const renderInputText = (args: Partial>) => { + const escape = (value: string) => value.replace(/&/g, '&').replace(/"/g, '"').replace(/`; + + // В props уходит только control: Storybook присваивает «не-@Input» пропсы прямо на инстанс, + // а invalid у компонента — геттер из NgControl, и присваивание роняет сторис с TypeError. + return { props: { control }, template }; +}; export const Default: Story = { name: 'Default', - render: (args) => { - const parts: string[] = []; + render: (args) => renderInputText(args), + parameters: { + docs: { + description: { + story: + 'Интерактивное поле со всеми свойствами спецификации. Используйте Controls для изменения пропсов; disabled и invalid управляются через FormControl.' + } + } + } +}; + +export const Error: Story = { + name: 'Error', + args: { invalid: true }, + render: (args) => renderInputText(args) +}; - if (args.placeholder) parts.push('[placeholder]="placeholder"'); - if (args.label) parts.push('[label]="label"'); - if (args.labelPosition && args.labelPosition !== 'top') parts.push('[labelPosition]="labelPosition"'); - if (args.floatLabel) parts.push('[floatLabel]="floatLabel"'); - if (args.clearable) parts.push('[clearable]="clearable"'); - if (args.caption) parts.push('[caption]="caption"'); - if (args.info) parts.push('[info]="info"'); - if (args.size && args.size !== 'base') parts.push('[size]="size"'); - if (args.fluid) parts.push('[fluid]="fluid"'); - if (args.type && args.type !== 'text') parts.push('[type]="type"'); - if (args.readonly) parts.push('[readonly]="readonly"'); - if (args.required) parts.push('[required]="required"'); - if (args.name) parts.push('[name]="name"'); - if (args.autocomplete) parts.push('[autocomplete]="autocomplete"'); - if (args.maxLength != null) parts.push('[maxLength]="maxLength"'); - if (args.ariaLabel) parts.push('[ariaLabel]="ariaLabel"'); - if (args.ariaLabelledBy) parts.push('[ariaLabelledBy]="ariaLabelledBy"'); - if (args.autofocus) parts.push('[autofocus]="autofocus"'); - if (args.tabindex != null) parts.push('[tabindex]="tabindex"'); +export const Disabled: Story = { + name: 'Disabled', + args: { disabled: true }, + render: (args) => renderInputText(args) +}; - const validators = args.invalid ? [Validators.required] : []; - const control = new FormControl({ value: '', disabled: args.disabled }, validators); +export const Readonly: Story = { + name: 'Readonly', + args: { readonly: true }, + render: (args) => renderInputText(args) +}; - const template = ``; +export const FloatLabel: Story = { + name: 'FloatLabel', + args: { labelPosition: 'float', label: 'FloatLabel' }, + render: (args) => renderInputText(args) +}; - // invalid — геттер компонента, disabled меняется через CVA: передаём эти состояния только форме. - const { disabled, invalid, ...inputs } = args; - return { props: { ...inputs, control }, template }; - }, +export const Clearable: Story = { + name: 'Clearable', + args: { clearable: true, value: 'InputText' }, + render: (args) => renderInputText(args), parameters: { docs: { description: { story: - 'Интерактивное поле со всеми свойствами спецификации. Используйте Controls для изменения пропсов; disabled и invalid управляются через FormControl.' + 'Поле с иконкой очистки (clearable). Иконка × доступна с клавиатуры (Enter / Space) и появляется только при наличии значения.' } } } }; -// ── Комбинаторные истории ──────────────────────────────────────────────────── +export const Fluid: Story = { + name: 'Fluid', + args: { fluid: true }, + render: (args) => renderInputText(args), + parameters: { + docs: { + description: { + story: + 'Растягивание на всю ширину контейнера (fluid). При `[fluid]="true"` поле занимает 100% ширины родителя вместо собственной ширины по умолчанию. Контейнер в примере — 600px и обведён пунктиром, чтобы было видно, что поле тянется ровно по его границам.' + } + } + } +}; -export { Labels, Sizes, Clearable, Types, States, Fluid, ReactiveForms }; +export const ReactiveForms: Story = { + ...(ReactiveFormsStory as Story), + parameters: { + ...ReactiveFormsStory.parameters, + docs: { + ...(ReactiveFormsStory.parameters?.['docs'] ?? {}), + description: { + story: + 'Компонент реализует ControlValueAccessor, поэтому `[formControl]` работает в обе стороны. Ввод с клавиатуры и очистка иконкой × пишут значение в контрол (value, dirty), blur помечает его touched, а `setValue()`, `reset()`, `disable()` / `enable()` со стороны формы обновляют само поле. Состояние invalid берётся из NgControl — красная рамка появляется по Validators, без отдельного пропа.' + } + } + } +};