From 958bc5e2d2e5560aa97bfae947541fadf410bad4 Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Fri, 13 Nov 2026 01:09:07 +0800 Subject: [PATCH 1/5] feat(inputtext): sync styles and API with Figma MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Геометрия поля приведена к Figma 1:1 для small, base, large и xlarge: высота, паддинги, радиус, шрифт и line-height; обновлены токены поля и кольцо фокуса. 2. Переработан плавающий лейбл: высота поля 56, лейбл 14/20 в покое и 12/14 поднятым, placeholder скрыт в покое и виден в фокусе под поднятым лейблом. 3. Добавлен вход requiredMark — красная «*» перед лейблом. 4. Добавлен вход captionSeverity (base, success, warning, danger, info); подпись теперь рисует общий компонент extra-caption с иконкой по варианту. 5. readonly оставлен одним входом; крестик остаётся в потоке и скрывается через visibility при readonly и disabled. 6. Сторис переработаны: одна сторис — один пресет Figma, один экземпляр, литералы в Source, Controls для всех 20 входов; старые example-компоненты удалены, остался только пример с reactive forms. 7. API задокументирован в docs/components-api/inputtext.md, соответствие Figma — в inputtext.figma.md. Заметки для ревьюеров: - BREAKING относительно main: labelPosition принимает default | float | left (default — лейбл сверху, float — плавающий лейбл); булев floatLabel, добавленный в main, удалён. Расходится со строками для полей ввода в docs/naming-rules.md — решение владельца. - BREAKING: класс подписи .extra-inputtext-caption заменён на .extra-caption общего компонента; свои стили на старый класс нужно перенести. - Из main сохранены: required (NG_VALIDATORS), name, autocomplete, maxLength, ariaLabel, ariaLabelledBy, autofocus, tabindex и доступный крестик очистки. - Токены: components.inputtext и components.floatlabel обновлены (ключ floatlabel inside переименован в in; extend.iconSize теперь size.450); в tokens.json добавлены дополнительные значения. - Известное отличие от Figma: лейбл float-поля в покое стоит на y=18, в Figma 16 (центрирование по строке 20). - Открытый вопрос к дизайну: в Figma у float-поля в фокусе с placeholder лейбл остаётся 14/20, в коде поднимается до 12/14. Оставлено как есть по решению владельца. --- docs/components-api/inputtext.md | 43 +-- .../inputtext/inputtext.component.ts | 65 +++-- .../components/inputtext/inputtext.figma.md | 96 +++---- .../tokens/components/inputtext.ts | 86 +++++- .../providers/prime-preset/tokens/tokens.json | 43 +-- .../examples/inputtext-clearable.component.ts | 74 ----- .../examples/inputtext-fluid.component.ts | 69 ----- .../examples/inputtext-labels.component.ts | 106 ------- .../inputtext-reactive-forms.component.ts | 2 +- .../examples/inputtext-sizes.component.ts | 58 ---- .../examples/inputtext-states.component.ts | 83 ------ .../examples/inputtext-types.component.ts | 55 ---- .../components/inputtext/inputtext.stories.ts | 265 +++++++++++++----- 13 files changed, 409 insertions(+), 636 deletions(-) delete mode 100644 src/stories/components/inputtext/examples/inputtext-clearable.component.ts delete mode 100644 src/stories/components/inputtext/examples/inputtext-fluid.component.ts delete mode 100644 src/stories/components/inputtext/examples/inputtext-labels.component.ts delete mode 100644 src/stories/components/inputtext/examples/inputtext-sizes.component.ts delete mode 100644 src/stories/components/inputtext/examples/inputtext-states.component.ts delete mode 100644 src/stories/components/inputtext/examples/inputtext-types.component.ts 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-clearable.component.ts b/src/stories/components/inputtext/examples/inputtext-clearable.component.ts deleted file mode 100644 index e22f3ece..00000000 --- a/src/stories/components/inputtext/examples/inputtext-clearable.component.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { ChangeDetectionStrategy, Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { StoryObj } from '@storybook/angular'; -import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; - -const template = ` -
- - -
-`; - -@Component({ - selector: 'app-inputtext-clearable', - standalone: true, - changeDetection: ChangeDetectionStrategy.OnPush, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template -}) -export class InputTextClearableComponent { - filled = new FormControl('Какой-то текст'); - empty = new FormControl(''); -} - -export const Clearable: StoryObj = { - render: () => ({ - template: `` - }), - parameters: { - controls: { disable: true }, - docs: { - description: { - story: - 'Поле с иконкой очистки (clearable). Иконка × доступна с клавиатуры (Enter / Space) и появляется только при наличии значения.' - }, - source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-inputtext-clearable', - standalone: true, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template: \` - - \`, -}) -export class InputTextClearableComponent { - control = new FormControl('Какой-то текст'); -} - ` - } - } - } -}; diff --git a/src/stories/components/inputtext/examples/inputtext-fluid.component.ts b/src/stories/components/inputtext/examples/inputtext-fluid.component.ts deleted file mode 100644 index d584e0e4..00000000 --- a/src/stories/components/inputtext/examples/inputtext-fluid.component.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { ChangeDetectionStrategy, Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { StoryObj } from '@storybook/angular'; -import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; - -const template = ` -
- -
-`; - -@Component({ - selector: 'app-inputtext-fluid', - standalone: true, - changeDetection: ChangeDetectionStrategy.OnPush, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template -}) -export class InputTextFluidComponent { - control = new FormControl(''); -} - -export const Fluid: StoryObj = { - render: () => ({ - template: `` - }), - parameters: { - controls: { disable: true }, - docs: { - description: { - story: - 'Растягивание на всю ширину контейнера (fluid). При `[fluid]="true"` поле занимает 100% ширины родителя вместо собственной ширины по умолчанию. Контейнер в примере — 600px и обведён пунктиром, чтобы было видно, что поле тянется ровно по его границам.' - }, - source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-inputtext-fluid', - standalone: true, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template: \` - -
- -
- \`, -}) -export class InputTextFluidComponent { - control = new FormControl(''); -} - ` - } - } - } -}; diff --git a/src/stories/components/inputtext/examples/inputtext-labels.component.ts b/src/stories/components/inputtext/examples/inputtext-labels.component.ts deleted file mode 100644 index 2e43e0f4..00000000 --- a/src/stories/components/inputtext/examples/inputtext-labels.component.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { ChangeDetectionStrategy, Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { StoryObj } from '@storybook/angular'; -import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; - -const template = ` -
- - - - -
-`; - -@Component({ - selector: 'app-inputtext-labels', - standalone: true, - changeDetection: ChangeDetectionStrategy.OnPush, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template -}) -export class InputTextLabelsComponent { - topControl = new FormControl(''); - floatControl = new FormControl(''); - leftControl = new FormControl(''); - plainControl = new FormControl(''); -} - -export const Labels: StoryObj = { - render: () => ({ - template: `` - }), - parameters: { - controls: { disable: true }, - docs: { - description: { - story: - 'Положения лейбла: labelPosition="top" — сверху, floatLabel — плавающий внутри поля, labelPosition="left" — слева от поля. Info показывается иконкой ti-info-circle с тултипом, caption — пояснение под полем.' - }, - source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-inputtext-labels', - standalone: true, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template: \` - - - - - - - - - \`, -}) -export class InputTextLabelsComponent { - topControl = new FormControl(''); - floatControl = new FormControl(''); - leftControl = new FormControl(''); - plainControl = new FormControl(''); -} - ` - } - } - } -}; 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..bd91b152 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; } diff --git a/src/stories/components/inputtext/examples/inputtext-sizes.component.ts b/src/stories/components/inputtext/examples/inputtext-sizes.component.ts deleted file mode 100644 index 6cbf62c7..00000000 --- a/src/stories/components/inputtext/examples/inputtext-sizes.component.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { ChangeDetectionStrategy, Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { StoryObj } from '@storybook/angular'; -import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; - -const template = ` -
- @for (size of sizes; track size) { - - } -
-`; - -@Component({ - selector: 'app-inputtext-sizes', - standalone: true, - changeDetection: ChangeDetectionStrategy.OnPush, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template -}) -export class InputTextSizesComponent { - sizes = ['small', 'base', 'large', 'xlarge']; - control = new FormControl(''); -} - -export const Sizes: StoryObj = { - render: () => ({ - template: `` - }), - parameters: { - controls: { disable: true }, - docs: { - description: { - story: 'Размеры поля: small, base, large, xlarge.' - }, - source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-inputtext-sizes', - standalone: true, - imports: [ExtraInputTextComponent], - template: \` - - - - - \`, -}) -export class InputTextSizesComponent {} - ` - } - } - } -}; diff --git a/src/stories/components/inputtext/examples/inputtext-states.component.ts b/src/stories/components/inputtext/examples/inputtext-states.component.ts deleted file mode 100644 index 66d1ae0e..00000000 --- a/src/stories/components/inputtext/examples/inputtext-states.component.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { ChangeDetectionStrategy, Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; -import { StoryObj } from '@storybook/angular'; -import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; - -const template = ` -
- - - -
-`; - -@Component({ - selector: 'app-inputtext-states', - standalone: true, - changeDetection: ChangeDetectionStrategy.OnPush, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template -}) -export class InputTextStatesComponent { - control = new FormControl(''); - disabled = new FormControl({ value: '', disabled: true }); - invalid = new FormControl('', Validators.required); -} - -export const States: StoryObj = { - render: () => ({ - template: `` - }), - parameters: { - controls: { disable: true }, - docs: { - description: { - story: - 'Состояния disabled и invalid управляются через FormControl: disable() / Validators (invalid вычисляется из NgControl автоматически).' - }, - source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; -import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-inputtext-states', - standalone: true, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template: \` - - - - - - - - \`, -}) -export class InputTextStatesComponent { - control = new FormControl(''); - disabled = new FormControl({ value: '', disabled: true }); - invalid = new FormControl('', Validators.required); -} - ` - } - } - } -}; diff --git a/src/stories/components/inputtext/examples/inputtext-types.component.ts b/src/stories/components/inputtext/examples/inputtext-types.component.ts deleted file mode 100644 index f8006c3c..00000000 --- a/src/stories/components/inputtext/examples/inputtext-types.component.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { ChangeDetectionStrategy, Component } from '@angular/core'; -import { FormControl, ReactiveFormsModule } from '@angular/forms'; -import { StoryObj } from '@storybook/angular'; -import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; - -const template = ` -
- - -
-`; - -@Component({ - selector: 'app-inputtext-types', - standalone: true, - changeDetection: ChangeDetectionStrategy.OnPush, - imports: [ExtraInputTextComponent, ReactiveFormsModule], - template -}) -export class InputTextTypesComponent { - text = new FormControl(''); - password = new FormControl(''); -} - -export const Types: StoryObj = { - render: () => ({ - template: `` - }), - parameters: { - controls: { disable: true }, - docs: { - description: { - story: 'Типы поля: text (по умолчанию) и password.' - }, - source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-inputtext-types', - standalone: true, - imports: [ExtraInputTextComponent], - template: \` - - - \`, -}) -export class InputTextTypesComponent {} - ` - } - } - } -}; diff --git a/src/stories/components/inputtext/inputtext.stories.ts b/src/stories/components/inputtext/inputtext.stories.ts index 233e7fa6..a97c34af 100644 --- a/src/stories/components/inputtext/inputtext.stories.ts +++ b/src/stories/components/inputtext/inputtext.stories.ts @@ -1,15 +1,9 @@ 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'; -type InputTextArgs = ExtraInputTextComponent & { disabled: boolean; invalid: boolean }; +type InputTextArgs = ExtraInputTextComponent & { disabled: boolean; invalid: boolean; value: string }; const meta: Meta = { title: 'Components/Form/InputText', @@ -17,17 +11,7 @@ const meta: Meta = { tags: ['autodocs'], decorators: [ moduleMetadata({ - imports: [ - ExtraInputTextComponent, - ReactiveFormsModule, - InputTextLabelsComponent, - InputTextSizesComponent, - InputTextClearableComponent, - InputTextTypesComponent, - InputTextStatesComponent, - InputTextFluidComponent, - InputTextReactiveFormsComponent - ] + imports: [ExtraInputTextComponent, ReactiveFormsModule, InputTextReactiveFormsComponent] }) ], parameters: { @@ -67,17 +51,17 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; }, labelPosition: { control: 'select', - options: ['top', 'left'], - description: 'Положение лейбла', + 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 +77,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 +95,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 +143,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 +202,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 +227,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 +248,178 @@ 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 parts: string[] = []; + + if (args.placeholder) parts.push(`placeholder="${args.placeholder}"`); + if (args.label) parts.push(`label="${args.label}"`); + if (args.labelPosition && args.labelPosition !== 'default') parts.push(`labelPosition="${args.labelPosition}"`); + if (args.requiredMark) parts.push(`[requiredMark]="true"`); + if (args.clearable) parts.push(`clearable`); + if (args.readonly) parts.push(`readonly`); + if (args.caption) parts.push(`caption="${args.caption}"`); + if (args.captionSeverity && args.captionSeverity !== 'base') parts.push(`captionSeverity="${args.captionSeverity}"`); + if (args.info) parts.push(`info="${args.info}"`); + if (args.size && args.size !== 'base') parts.push(`size="${args.size}"`); + if (args.fluid) parts.push(`[fluid]="true"`); + if (args.type && args.type !== 'text') parts.push(`type="${args.type}"`); + if (args.required) parts.push(`required`); + if (args.name) parts.push(`name="${args.name}"`); + if (args.autocomplete) parts.push(`autocomplete="${args.autocomplete}"`); + if (args.maxLength != null) parts.push(`[maxLength]="${args.maxLength}"`); + if (args.ariaLabel) parts.push(`ariaLabel="${args.ariaLabel}"`); + if (args.ariaLabelledBy) parts.push(`ariaLabelledBy="${args.ariaLabelledBy}"`); + if (args.autofocus) parts.push(`autofocus`); + if (args.tabindex != null) parts.push(`[tabindex]="${args.tabindex}"`); + + const validators = args.invalid ? [Validators.required] : []; + const control = new FormControl( + { value: args.invalid ? '' : (args.value ?? ''), disabled: !!args.disabled }, + validators + ); + + const template = ``; + + // В 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.' + }, + source: { + language: 'html', + code: `` + } + } + } +}; + +export const Error: Story = { + name: 'Error', + args: { invalid: true }, + render: (args) => renderInputText(args), + parameters: { + docs: { + description: { + story: + 'Невалидное состояние: invalid вычисляется из NgControl автоматически (Validators), красная рамка появляется без отдельного пропа.' + }, + source: { + language: 'html', + code: `` + } + } + } +}; - 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), + parameters: { + docs: { + description: { story: 'Отключённое состояние управляется через FormControl: disable() / enable().' }, + source: { + language: 'html', + code: `` + } + } + } +}; - 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), + parameters: { + docs: { + description: { story: 'Режим только для чтения (readonly): значение видно и выделяется, но не редактируется.' }, + source: { + language: 'html', + code: `` + } + } + } +}; - const template = ``; +export const FloatLabel: Story = { + name: 'FloatLabel', + args: { labelPosition: 'float', label: 'FloatLabel' }, + render: (args) => renderInputText(args), + parameters: { + docs: { + description: { + story: + 'Плавающий лейбл (labelPosition="float"): в покое лежит внутри поля, при фокусе и наличии значения поднимается вверх и уменьшается.' + }, + source: { + language: 'html', + code: `` + } + } + } +}; - // 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) и появляется только при наличии значения; клик очищает поле и вызывает onClear.' + }, + source: { + language: 'html', + code: `` } } } }; -// ── Комбинаторные истории ──────────────────────────────────────────────────── +export const Fluid: Story = { + name: 'Fluid', + args: { fluid: true }, + render: (args) => renderInputText(args), + parameters: { + docs: { + description: { + story: + 'Растягивание на всю ширину контейнера (fluid). При `[fluid]="true"` поле занимает 100% ширины родителя вместо собственной ширины по умолчанию.' + }, + source: { + language: 'html', + code: `` + } + } + } +}; -export { Labels, Sizes, Clearable, Types, States, Fluid, ReactiveForms }; +export { ReactiveForms }; From f5205db5a6386b861b6e521471ce0e090594c7f0 Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Tue, 17 Nov 2026 03:18:53 +0800 Subject: [PATCH 2/5] fix(inputtext): restore standalone example components MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Восстановить 6 исходных example-файлов компонента вместо лишнего удаления. 2. Согласовать примеры с актуальными типами и API, сохранив исходные описания. 3. Проверить snippets текущих stories, изменённые Controls и строгую Angular-компиляцию восстановленных примеров. Заметки для ревьюеров: - Область: только примеры и stories inputtext; производственные компоненты и токены в этом коммите не меняются. - Stories: сохранён текущий список отдельных примеров; исходные example-файлы доступны рядом с ним. - Проверки: Angular-компиляция восстановленных примеров и обязательные gates snippets и описаний проходят. --- .../examples/inputtext-clearable.component.ts | 74 ++++++++++ .../examples/inputtext-fluid.component.ts | 69 +++++++++ .../examples/inputtext-labels.component.ts | 106 ++++++++++++++ .../inputtext-reactive-forms.component.ts | 46 ++---- .../examples/inputtext-sizes.component.ts | 58 ++++++++ .../examples/inputtext-states.component.ts | 83 +++++++++++ .../examples/inputtext-types.component.ts | 55 +++++++ .../components/inputtext/inputtext.stories.ts | 136 ++++-------------- 8 files changed, 482 insertions(+), 145 deletions(-) create mode 100644 src/stories/components/inputtext/examples/inputtext-clearable.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-fluid.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-labels.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-sizes.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-states.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-types.component.ts diff --git a/src/stories/components/inputtext/examples/inputtext-clearable.component.ts b/src/stories/components/inputtext/examples/inputtext-clearable.component.ts new file mode 100644 index 00000000..e22f3ece --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-clearable.component.ts @@ -0,0 +1,74 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ + +
+`; + +@Component({ + selector: 'app-inputtext-clearable', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template +}) +export class InputTextClearableComponent { + filled = new FormControl('Какой-то текст'); + empty = new FormControl(''); +} + +export const Clearable: StoryObj = { + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: + 'Поле с иконкой очистки (clearable). Иконка × доступна с клавиатуры (Enter / Space) и появляется только при наличии значения.' + }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; + +@Component({ + selector: 'app-inputtext-clearable', + standalone: true, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template: \` + + \`, +}) +export class InputTextClearableComponent { + control = new FormControl('Какой-то текст'); +} + ` + } + } + } +}; diff --git a/src/stories/components/inputtext/examples/inputtext-fluid.component.ts b/src/stories/components/inputtext/examples/inputtext-fluid.component.ts new file mode 100644 index 00000000..d584e0e4 --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-fluid.component.ts @@ -0,0 +1,69 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ +
+`; + +@Component({ + selector: 'app-inputtext-fluid', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template +}) +export class InputTextFluidComponent { + control = new FormControl(''); +} + +export const Fluid: StoryObj = { + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: + 'Растягивание на всю ширину контейнера (fluid). При `[fluid]="true"` поле занимает 100% ширины родителя вместо собственной ширины по умолчанию. Контейнер в примере — 600px и обведён пунктиром, чтобы было видно, что поле тянется ровно по его границам.' + }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; + +@Component({ + selector: 'app-inputtext-fluid', + standalone: true, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template: \` + +
+ +
+ \`, +}) +export class InputTextFluidComponent { + control = new FormControl(''); +} + ` + } + } + } +}; diff --git a/src/stories/components/inputtext/examples/inputtext-labels.component.ts b/src/stories/components/inputtext/examples/inputtext-labels.component.ts new file mode 100644 index 00000000..a51dc180 --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-labels.component.ts @@ -0,0 +1,106 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ + + + +
+`; + +@Component({ + selector: 'app-inputtext-labels', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template +}) +export class InputTextLabelsComponent { + topControl = new FormControl(''); + floatControl = new FormControl(''); + leftControl = new FormControl(''); + plainControl = new FormControl(''); +} + +export const Labels: StoryObj = { + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: + 'Положения лейбла: labelPosition="top" — сверху, floatLabel — плавающий внутри поля, labelPosition="left" — слева от поля. Info показывается иконкой ti-info-circle с тултипом, caption — пояснение под полем.' + }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; + +@Component({ + selector: 'app-inputtext-labels', + standalone: true, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template: \` + + + + + + + + + \`, +}) +export class InputTextLabelsComponent { + topControl = new FormControl(''); + floatControl = new FormControl(''); + leftControl = new FormControl(''); + plainControl = new FormControl(''); +} + ` + } + } + } +}; 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 bd91b152..70187c2d 100644 --- a/src/stories/components/inputtext/examples/inputtext-reactive-forms.component.ts +++ b/src/stories/components/inputtext/examples/inputtext-reactive-forms.component.ts @@ -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 new file mode 100644 index 00000000..fd440078 --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-sizes.component.ts @@ -0,0 +1,58 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ @for (size of sizes; track size) { + + } +
+`; + +@Component({ + selector: 'app-inputtext-sizes', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template +}) +export class InputTextSizesComponent { + sizes = ['small', 'base', 'large', 'xlarge'] as const; + control = new FormControl(''); +} + +export const Sizes: StoryObj = { + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: 'Размеры поля: small, base, large, xlarge.' + }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; + +@Component({ + selector: 'app-inputtext-sizes', + standalone: true, + imports: [ExtraInputTextComponent], + template: \` + + + + + \`, +}) +export class InputTextSizesComponent {} + ` + } + } + } +}; diff --git a/src/stories/components/inputtext/examples/inputtext-states.component.ts b/src/stories/components/inputtext/examples/inputtext-states.component.ts new file mode 100644 index 00000000..66d1ae0e --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-states.component.ts @@ -0,0 +1,83 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ + + +
+`; + +@Component({ + selector: 'app-inputtext-states', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template +}) +export class InputTextStatesComponent { + control = new FormControl(''); + disabled = new FormControl({ value: '', disabled: true }); + invalid = new FormControl('', Validators.required); +} + +export const States: StoryObj = { + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: + 'Состояния disabled и invalid управляются через FormControl: disable() / Validators (invalid вычисляется из NgControl автоматически).' + }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; +import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; + +@Component({ + selector: 'app-inputtext-states', + standalone: true, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template: \` + + + + + + + + \`, +}) +export class InputTextStatesComponent { + control = new FormControl(''); + disabled = new FormControl({ value: '', disabled: true }); + invalid = new FormControl('', Validators.required); +} + ` + } + } + } +}; diff --git a/src/stories/components/inputtext/examples/inputtext-types.component.ts b/src/stories/components/inputtext/examples/inputtext-types.component.ts new file mode 100644 index 00000000..f8006c3c --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-types.component.ts @@ -0,0 +1,55 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { FormControl, ReactiveFormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { ExtraInputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ + +
+`; + +@Component({ + selector: 'app-inputtext-types', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraInputTextComponent, ReactiveFormsModule], + template +}) +export class InputTextTypesComponent { + text = new FormControl(''); + password = new FormControl(''); +} + +export const Types: StoryObj = { + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: 'Типы поля: text (по умолчанию) и password.' + }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; + +@Component({ + selector: 'app-inputtext-types', + standalone: true, + imports: [ExtraInputTextComponent], + template: \` + + + \`, +}) +export class InputTextTypesComponent {} + ` + } + } + } +}; diff --git a/src/stories/components/inputtext/inputtext.stories.ts b/src/stories/components/inputtext/inputtext.stories.ts index a97c34af..6c77fcde 100644 --- a/src/stories/components/inputtext/inputtext.stories.ts +++ b/src/stories/components/inputtext/inputtext.stories.ts @@ -8,7 +8,7 @@ type InputTextArgs = ExtraInputTextComponent & { disabled: boolean; invalid: boo const meta: Meta = { title: 'Components/Form/InputText', component: ExtraInputTextComponent, - tags: ['autodocs'], + tags: ['autodocs', 'inputtext'], decorators: [ moduleMetadata({ imports: [ExtraInputTextComponent, ReactiveFormsModule, InputTextReactiveFormsComponent] @@ -16,6 +16,7 @@ const meta: Meta = { ], parameters: { docs: { + source: { language: 'html', transform: (_code: string, context: { args: Partial> }) => renderInputText(context.args).template }, description: { component: `Текстовое поле для ввода данных. @@ -52,7 +53,7 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; labelPosition: { control: 'select', options: ['default', 'float', 'left'], - description: 'Положение лейбла: сверху, плавающий внутри поля или слева', + description: 'Положение лейбла', table: { category: 'Свойства', defaultValue: { summary: 'default' }, @@ -79,7 +80,7 @@ import { ExtraInputTextComponent } from '@cdek-it/angular-ui-kit'; }, readonly: { control: 'boolean', - description: 'Режим только для чтения: значение видно и выделяется, но не редактируется', + description: 'Только чтение; очистка поля недоступна', table: { category: 'Свойства', defaultValue: { summary: 'false' }, @@ -260,27 +261,28 @@ type Story = StoryObj; // Каждая сторис — пресет варианта Figma (comp-json/FORM/InputText/STORIES.md): в args задана // только её ось, остальное равно варианту Figma по умолчанию и меняется в Controls. const renderInputText = (args: Partial>) => { + const escape = (value: string) => value.replace(/&/g, '&').replace(/"/g, '"').replace(/>) => { export const Default: Story = { name: 'Default', render: (args) => renderInputText(args), - parameters: { - docs: { - description: { - story: - 'Интерактивное поле со всеми свойствами спецификации. Используйте Controls для изменения пропсов; disabled и invalid управляются через FormControl.' - }, - source: { - language: 'html', - code: `` - } - } - } + parameters: { docs: { description: { story: 'Интерактивное поле со всеми свойствами спецификации. Используйте Controls для изменения пропсов; disabled и invalid управляются через FormControl.' } } } }; export const Error: Story = { name: 'Error', args: { invalid: true }, - render: (args) => renderInputText(args), - parameters: { - docs: { - description: { - story: - 'Невалидное состояние: invalid вычисляется из NgControl автоматически (Validators), красная рамка появляется без отдельного пропа.' - }, - source: { - language: 'html', - code: `` - } - } - } + render: (args) => renderInputText(args) }; export const Disabled: Story = { name: 'Disabled', args: { disabled: true }, - render: (args) => renderInputText(args), - parameters: { - docs: { - description: { story: 'Отключённое состояние управляется через FormControl: disable() / enable().' }, - source: { - language: 'html', - code: `` - } - } - } + render: (args) => renderInputText(args) }; export const Readonly: Story = { name: 'Readonly', args: { readonly: true }, - render: (args) => renderInputText(args), - parameters: { - docs: { - description: { story: 'Режим только для чтения (readonly): значение видно и выделяется, но не редактируется.' }, - source: { - language: 'html', - code: `` - } - } - } + render: (args) => renderInputText(args) }; export const FloatLabel: Story = { name: 'FloatLabel', args: { labelPosition: 'float', label: 'FloatLabel' }, - render: (args) => renderInputText(args), - parameters: { - docs: { - description: { - story: - 'Плавающий лейбл (labelPosition="float"): в покое лежит внутри поля, при фокусе и наличии значения поднимается вверх и уменьшается.' - }, - source: { - language: 'html', - code: `` - } - } - } + render: (args) => renderInputText(args) }; export const Clearable: Story = { name: 'Clearable', args: { clearable: true, value: 'InputText' }, render: (args) => renderInputText(args), - parameters: { - docs: { - description: { - story: - 'Поле с иконкой очистки (clearable). Иконка × доступна с клавиатуры (Enter / Space) и появляется только при наличии значения; клик очищает поле и вызывает onClear.' - }, - source: { - language: 'html', - code: `` - } - } - } + parameters: { docs: { description: { story: 'Поле с иконкой очистки (clearable). Иконка × доступна с клавиатуры (Enter / Space) и появляется только при наличии значения.' } } } }; export const Fluid: Story = { name: 'Fluid', args: { fluid: true }, render: (args) => renderInputText(args), - parameters: { - docs: { - description: { - story: - 'Растягивание на всю ширину контейнера (fluid). При `[fluid]="true"` поле занимает 100% ширины родителя вместо собственной ширины по умолчанию.' - }, - source: { - language: 'html', - code: `` - } - } - } + parameters: { docs: { description: { story: 'Растягивание на всю ширину контейнера (fluid). При `[fluid]="true"` поле занимает 100% ширины родителя вместо собственной ширины по умолчанию. Контейнер в примере — 600px и обведён пунктиром, чтобы было видно, что поле тянется ровно по его границам.' } } } }; export { ReactiveForms }; From 36d545f01e93f704261f3d4a8d20d88c06552be0 Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Tue, 17 Nov 2026 18:53:00 +0200 Subject: [PATCH 3/5] fix(inputtext): keep reactive-forms story indexable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Ре-экспорт story из example-файла заменён на объект с дословным описанием из main: Storybook не индексировал ветку (Could not parse import/exports with acorn) и не отдавал index.json. 2. Заметки для ревьюеров: поведение story не изменилось, описания и snippets PASS. --- .../components/inputtext/inputtext.stories.ts | 58 ++++++++++++++++--- 1 file changed, 50 insertions(+), 8 deletions(-) diff --git a/src/stories/components/inputtext/inputtext.stories.ts b/src/stories/components/inputtext/inputtext.stories.ts index 6c77fcde..3984b83d 100644 --- a/src/stories/components/inputtext/inputtext.stories.ts +++ b/src/stories/components/inputtext/inputtext.stories.ts @@ -1,7 +1,10 @@ import { Meta, moduleMetadata, StoryObj } from '@storybook/angular'; import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; import { ExtraInputTextComponent } from '../../../lib/components/inputtext/inputtext.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; value: string }; @@ -16,7 +19,11 @@ const meta: Meta = { ], parameters: { docs: { - source: { language: 'html', transform: (_code: string, context: { args: Partial> }) => renderInputText(context.args).template }, + source: { + language: 'html', + transform: (_code: string, context: { args: Partial> }) => + renderInputText(context.args).template + }, description: { component: `Текстовое поле для ввода данных. @@ -266,12 +273,14 @@ const renderInputText = (args: Partial>) => { if (args.placeholder) parts.push(`placeholder="${escape(args.placeholder)}"`); if (args.label) parts.push(`label="${escape(args.label)}"`); - if (args.labelPosition && args.labelPosition !== 'default') parts.push(`labelPosition="${escape(args.labelPosition)}"`); + if (args.labelPosition && args.labelPosition !== 'default') + parts.push(`labelPosition="${escape(args.labelPosition)}"`); if (args.requiredMark) parts.push(`[requiredMark]="true"`); if (args.clearable) parts.push(`[clearable]="true"`); if (args.readonly) parts.push(`[readonly]="true"`); if (args.caption) parts.push(`caption="${escape(args.caption)}"`); - if (args.captionSeverity && args.captionSeverity !== 'base') parts.push(`captionSeverity="${escape(args.captionSeverity)}"`); + if (args.captionSeverity && args.captionSeverity !== 'base') + parts.push(`captionSeverity="${escape(args.captionSeverity)}"`); if (args.info) parts.push(`info="${escape(args.info)}"`); if (args.size && args.size !== 'base') parts.push(`size="${escape(args.size)}"`); if (args.fluid) parts.push(`[fluid]="true"`); @@ -301,7 +310,14 @@ const renderInputText = (args: Partial>) => { export const Default: Story = { name: 'Default', render: (args) => renderInputText(args), - parameters: { docs: { description: { story: 'Интерактивное поле со всеми свойствами спецификации. Используйте Controls для изменения пропсов; disabled и invalid управляются через FormControl.' } } } + parameters: { + docs: { + description: { + story: + 'Интерактивное поле со всеми свойствами спецификации. Используйте Controls для изменения пропсов; disabled и invalid управляются через FormControl.' + } + } + } }; export const Error: Story = { @@ -332,14 +348,40 @@ export const Clearable: Story = { name: 'Clearable', args: { clearable: true, value: 'InputText' }, render: (args) => renderInputText(args), - parameters: { docs: { description: { story: 'Поле с иконкой очистки (clearable). Иконка × доступна с клавиатуры (Enter / Space) и появляется только при наличии значения.' } } } + parameters: { + docs: { + description: { + story: + 'Поле с иконкой очистки (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 и обведён пунктиром, чтобы было видно, что поле тянется ровно по его границам.' } } } + parameters: { + docs: { + description: { + story: + 'Растягивание на всю ширину контейнера (fluid). При `[fluid]="true"` поле занимает 100% ширины родителя вместо собственной ширины по умолчанию. Контейнер в примере — 600px и обведён пунктиром, чтобы было видно, что поле тянется ровно по его границам.' + } + } + } }; -export { 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, без отдельного пропа.' + } + } + } +}; From 314456275c4e90dc3522b6dccbecd826a48770e0 Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Wed, 18 Nov 2026 13:49:50 +0200 Subject: [PATCH 4/5] chore(inputtext): show control descriptions in Controls panel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. parameters.controls.expanded = true — панель Controls в Storybook 10 показывает описание, тип, дефолт и группы категорий (в компактном режиме их нет). 2. Гейты: controls 20/20, descriptions 26/26, source 8/8. --- src/stories/components/inputtext/inputtext.stories.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/stories/components/inputtext/inputtext.stories.ts b/src/stories/components/inputtext/inputtext.stories.ts index 3984b83d..cc1a6235 100644 --- a/src/stories/components/inputtext/inputtext.stories.ts +++ b/src/stories/components/inputtext/inputtext.stories.ts @@ -18,6 +18,7 @@ const meta: Meta = { }) ], parameters: { + controls: { expanded: true }, docs: { source: { language: 'html', From 07a6e8ee52e12eb4d2e89f57c79165055260a5e6 Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Wed, 18 Nov 2026 15:43:59 +0300 Subject: [PATCH 5/5] chore(inputtext): show control descriptions in Controls panel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Включает глобальный controls.expanded в .storybook/preview.ts (иначе на ветке панель Controls остаётся компактной до мержа инфраструктурной ветки). --- .storybook/preview.ts | 3 +++ src/stories/components/inputtext/inputtext.stories.ts | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) 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/src/stories/components/inputtext/inputtext.stories.ts b/src/stories/components/inputtext/inputtext.stories.ts index cc1a6235..3984b83d 100644 --- a/src/stories/components/inputtext/inputtext.stories.ts +++ b/src/stories/components/inputtext/inputtext.stories.ts @@ -18,7 +18,6 @@ const meta: Meta = { }) ], parameters: { - controls: { expanded: true }, docs: { source: { language: 'html',