From 85949ef94ed78136e287c960d3fd349b853c27ad Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Thu, 16 Apr 2026 18:50:33 +0700 Subject: [PATCH 01/20] =?UTF-8?q?feat(inputtext):=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82,=20=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D0=BB=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F,=20=D1=81=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D1=81=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../inputtext/inputtext.component.ts | 116 ++++++++++++ src/prime-preset/map-tokens.ts | 5 + .../tokens/components/inputtext.ts | 31 ++++ .../examples/inputtext-clear.component.ts | 69 +++++++ .../examples/inputtext-disabled.component.ts | 56 ++++++ .../inputtext-float-label.component.ts | 75 ++++++++ .../examples/inputtext-invalid.component.ts | 54 ++++++ .../examples/inputtext-readonly.component.ts | 54 ++++++ .../components/inputtext/inputtext.stories.ts | 173 ++++++++++++++++++ 9 files changed, 633 insertions(+) create mode 100644 src/lib/components/inputtext/inputtext.component.ts create mode 100644 src/prime-preset/tokens/components/inputtext.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-clear.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-disabled.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-float-label.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-invalid.component.ts create mode 100644 src/stories/components/inputtext/examples/inputtext-readonly.component.ts create mode 100644 src/stories/components/inputtext/inputtext.stories.ts diff --git a/src/lib/components/inputtext/inputtext.component.ts b/src/lib/components/inputtext/inputtext.component.ts new file mode 100644 index 00000000..e79f2149 --- /dev/null +++ b/src/lib/components/inputtext/inputtext.component.ts @@ -0,0 +1,116 @@ +import { Component, Input, Output, EventEmitter, forwardRef } from '@angular/core'; +import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; +import { NgClass } from '@angular/common'; +import { InputText } from 'primeng/inputtext'; +import { IconField } from 'primeng/iconfield'; +import { InputIcon } from 'primeng/inputicon'; + +export type InputTextSize = 'small' | 'base' | 'large' | 'xlarge'; +export type InputTextVariant = 'outlined' | 'filled'; + +@Component({ + selector: 'input-text', + standalone: true, + imports: [InputText, IconField, InputIcon, NgClass], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => InputTextComponent), + multi: true, + }, + ], + template: ` + @if (showClear) { + + + @if (modelValue) { + + } + + } @else { + + } + `, +}) +export class InputTextComponent implements ControlValueAccessor { + @Input() placeholder = ''; + @Input() size: InputTextSize = 'base'; + @Input() disabled = false; + @Input() readonly = false; + @Input() invalid = false; + @Input() showClear = false; + @Input() fluid = false; + @Input() variant: InputTextVariant = 'outlined'; + + @Output() onClear = new EventEmitter(); + + modelValue = ''; + + private _onChange: (value: string) => void = () => {}; + + get primeSize(): 'small' | 'large' | undefined { + if (this.size === 'small') return 'small'; + if (this.size === 'large' || this.size === 'xlarge') return 'large'; + return undefined; + } + + get sizeClass(): Record { + return { 'p-inputtext-xlg': this.size === 'xlarge' }; + } + + onInput(event: Event): void { + const value = (event.target as HTMLInputElement).value; + this.modelValue = value; + this._onChange(value); + } + + onTouched: () => void = () => {}; + + clearValue(): void { + this.modelValue = ''; + this._onChange(''); + this.onClear.emit(); + } + + writeValue(value: string): void { + this.modelValue = value ?? ''; + } + + registerOnChange(fn: (value: string) => void): void { + this._onChange = fn; + } + + registerOnTouched(fn: () => void): void { + this.onTouched = fn; + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + } +} diff --git a/src/prime-preset/map-tokens.ts b/src/prime-preset/map-tokens.ts index 0194af83..09d9449d 100644 --- a/src/prime-preset/map-tokens.ts +++ b/src/prime-preset/map-tokens.ts @@ -6,6 +6,7 @@ import tokens from './tokens/tokens.json'; import { avatarCss } from './tokens/components/avatar'; import { buttonCss } from './tokens/components/button'; import { checkboxCss } from './tokens/components/checkbox'; +import { inputtextCss } from './tokens/components/inputtext'; import { progressspinnerCss } from './tokens/components/progressspinner'; import { tagCss } from './tokens/components/tag'; import { tooltipCss } from './tokens/components/tooltip'; @@ -31,6 +32,10 @@ const presetTokens: Preset = { ...(tokens.components.progressspinner as unknown as ComponentsDesignTokens['progressspinner']), css: progressspinnerCss, }, + inputtext: { + ...(tokens.components.inputtext as unknown as ComponentsDesignTokens['inputtext']), + css: inputtextCss, + }, tag: { ...(tokens.components.tag as unknown as ComponentsDesignTokens['tag']), css: tagCss, diff --git a/src/prime-preset/tokens/components/inputtext.ts b/src/prime-preset/tokens/components/inputtext.ts new file mode 100644 index 00000000..39c2be35 --- /dev/null +++ b/src/prime-preset/tokens/components/inputtext.ts @@ -0,0 +1,31 @@ +export const inputtextCss = ({ dt }: { dt: (token: string) => string }): string => ` + +/* ─── Базовые стили ─── */ +.p-inputtext { + border-width: ${dt('inputtext.extend.borderWidth')}; + line-height: ${dt('fonts.lineHeight.250')}; +} + +/* ─── Readonly ─── */ +.p-inputtext:enabled:read-only { + background: ${dt('inputtext.extend.readonlyBackground')}; +} + +/* ─── Extra Large ─── */ +.p-inputtext.p-inputtext-xlg { + font-size: ${dt('inputtext.extend.extXlg.fontSize')}; + padding: ${dt('inputtext.extend.extXlg.paddingY')} ${dt('inputtext.extend.extXlg.paddingX')}; +} + +/* ─── IconField ─── */ +.p-iconfield[data-pc-name="iconfield"] { + width: fit-content; +} + +.p-iconfield .p-inputicon { + font-size: ${dt('inputtext.extend.iconSize')}; + width: ${dt('inputtext.extend.iconSize')}; + height: ${dt('inputtext.extend.iconSize')}; + cursor: pointer; +} +`; diff --git a/src/stories/components/inputtext/examples/inputtext-clear.component.ts b/src/stories/components/inputtext/examples/inputtext-clear.component.ts new file mode 100644 index 00000000..9179bd05 --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-clear.component.ts @@ -0,0 +1,69 @@ +import { Component } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { InputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ + +
+`; +const styles = ''; + +@Component({ + selector: 'app-inputtext-clear', + standalone: true, + imports: [InputTextComponent, FormsModule], + template, + styles, +}) +export class InputTextClearComponent { + value = 'Начальное значение'; + value2 = ''; +} + +export const ClearButton: StoryObj = { + render: () => ({ + template: ``, + }), + parameters: { + controls: { disable: true }, + docs: { + description: { story: 'Поле с кнопкой очистки через `showClear`. Иконка × появляется при наличии значения.' }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { InputTextComponent } from '@cdek-it/angular-ui-kit'; +import { FormsModule } from '@angular/forms'; + +@Component({ + selector: 'app-inputtext-clear', + standalone: true, + imports: [InputTextComponent, FormsModule], + template: \` + + \`, +}) +export class InputTextClearComponent { + value = ''; +} + `, + }, + }, + }, +}; diff --git a/src/stories/components/inputtext/examples/inputtext-disabled.component.ts b/src/stories/components/inputtext/examples/inputtext-disabled.component.ts new file mode 100644 index 00000000..af2bef37 --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-disabled.component.ts @@ -0,0 +1,56 @@ +import { Component } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { InputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ + +
+`; +const styles = ''; + +@Component({ + selector: 'app-inputtext-disabled', + standalone: true, + imports: [InputTextComponent, FormsModule], + template, + styles, +}) +export class InputTextDisabledComponent { + empty = ''; + value = 'Disabled с текстом'; +} + +export const Disabled: StoryObj = { + render: () => ({ + template: ``, + }), + parameters: { + controls: { disable: true }, + docs: { + description: { story: 'Отключённое состояние: пустое поле и поле со значением.' }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { InputTextComponent } from '@cdek-it/angular-ui-kit'; +import { FormsModule } from '@angular/forms'; + +@Component({ + selector: 'app-inputtext-disabled', + standalone: true, + imports: [InputTextComponent, FormsModule], + template: \` + + \`, +}) +export class InputTextDisabledComponent { + value = 'Disabled'; +} + `, + }, + }, + }, +}; diff --git a/src/stories/components/inputtext/examples/inputtext-float-label.component.ts b/src/stories/components/inputtext/examples/inputtext-float-label.component.ts new file mode 100644 index 00000000..d6058c9e --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-float-label.component.ts @@ -0,0 +1,75 @@ +import { Component } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { FloatLabel } from 'primeng/floatlabel'; +import { InputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ + + + + + + + +
+`; +const styles = ''; + +@Component({ + selector: 'app-inputtext-float-label', + standalone: true, + imports: [InputTextComponent, FloatLabel, FormsModule], + template, + styles, +}) +export class InputTextFloatLabelComponent { + value1 = ''; + value2 = ''; +} + +export const FloatLabelStory: StoryObj = { + name: 'FloatLabel', + render: () => ({ + template: ``, + }), + parameters: { + controls: { disable: true }, + docs: { + description: { story: 'Интеграция с `p-floatlabel` — плавающая метка внутри поля.' }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { InputTextComponent } from '@cdek-it/angular-ui-kit'; +import { FloatLabel } from 'primeng/floatlabel'; +import { FormsModule } from '@angular/forms'; + +@Component({ + selector: 'app-inputtext-float-label', + standalone: true, + imports: [InputTextComponent, FloatLabel, FormsModule], + template: \` + + + + + \`, +}) +export class InputTextFloatLabelComponent { + value = ''; +} + `, + }, + }, + }, +}; diff --git a/src/stories/components/inputtext/examples/inputtext-invalid.component.ts b/src/stories/components/inputtext/examples/inputtext-invalid.component.ts new file mode 100644 index 00000000..09f28329 --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-invalid.component.ts @@ -0,0 +1,54 @@ +import { Component } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { InputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ +
+`; +const styles = ''; + +@Component({ + selector: 'app-inputtext-invalid', + standalone: true, + imports: [InputTextComponent, FormsModule], + template, + styles, +}) +export class InputTextInvalidComponent { + value = ''; +} + +export const Invalid: StoryObj = { + render: () => ({ + template: ``, + }), + parameters: { + controls: { disable: true }, + docs: { + description: { story: 'Невалидное состояние поля.' }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { InputTextComponent } from '@cdek-it/angular-ui-kit'; +import { FormsModule } from '@angular/forms'; + +@Component({ + selector: 'app-inputtext-invalid', + standalone: true, + imports: [InputTextComponent, FormsModule], + template: \` + + \`, +}) +export class InputTextInvalidComponent { + value = ''; +} + `, + }, + }, + }, +}; diff --git a/src/stories/components/inputtext/examples/inputtext-readonly.component.ts b/src/stories/components/inputtext/examples/inputtext-readonly.component.ts new file mode 100644 index 00000000..3ce90c9f --- /dev/null +++ b/src/stories/components/inputtext/examples/inputtext-readonly.component.ts @@ -0,0 +1,54 @@ +import { Component } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { StoryObj } from '@storybook/angular'; +import { InputTextComponent } from '../../../../lib/components/inputtext/inputtext.component'; + +const template = ` +
+ +
+`; +const styles = ''; + +@Component({ + selector: 'app-inputtext-readonly', + standalone: true, + imports: [InputTextComponent, FormsModule], + template, + styles, +}) +export class InputTextReadonlyComponent { + value = 'Только для чтения'; +} + +export const Readonly: StoryObj = { + render: () => ({ + template: ``, + }), + parameters: { + controls: { disable: true }, + docs: { + description: { story: 'Поле только для чтения — фон отличается от обычного.' }, + source: { + language: 'ts', + code: ` +import { Component } from '@angular/core'; +import { InputTextComponent } from '@cdek-it/angular-ui-kit'; +import { FormsModule } from '@angular/forms'; + +@Component({ + selector: 'app-inputtext-readonly', + standalone: true, + imports: [InputTextComponent, FormsModule], + template: \` + + \`, +}) +export class InputTextReadonlyComponent { + value = 'Только для чтения'; +} + `, + }, + }, + }, +}; diff --git a/src/stories/components/inputtext/inputtext.stories.ts b/src/stories/components/inputtext/inputtext.stories.ts new file mode 100644 index 00000000..52a65861 --- /dev/null +++ b/src/stories/components/inputtext/inputtext.stories.ts @@ -0,0 +1,173 @@ +import { Meta, StoryObj, moduleMetadata } from '@storybook/angular'; +import { FormsModule } from '@angular/forms'; +import { InputTextComponent } from '../../../lib/components/inputtext/inputtext.component'; +import { InputTextClearComponent, ClearButton } from './examples/inputtext-clear.component'; +import { InputTextFloatLabelComponent, FloatLabelStory } from './examples/inputtext-float-label.component'; +import { InputTextDisabledComponent, Disabled } from './examples/inputtext-disabled.component'; +import { InputTextReadonlyComponent, Readonly } from './examples/inputtext-readonly.component'; +import { InputTextInvalidComponent, Invalid } from './examples/inputtext-invalid.component'; + +type InputTextArgs = InputTextComponent; + +const meta: Meta = { + title: 'Components/Form/InputText', + component: InputTextComponent, + tags: ['autodocs'], + decorators: [ + moduleMetadata({ + imports: [ + InputTextComponent, + FormsModule, + InputTextClearComponent, + InputTextFloatLabelComponent, + InputTextDisabledComponent, + InputTextReadonlyComponent, + InputTextInvalidComponent, + ], + }), + ], + parameters: { + designTokens: { prefix: '--p-inputtext' }, + docs: { + description: { + component: `Текстовое поле для ввода данных. Поддерживает размеры \`small\`, \`base\`, \`large\`, \`xlarge\`, очистку значения и FloatLabel.`, + }, + }, + }, + argTypes: { + // ── Props ──────────────────────────────────────────────── + placeholder: { + control: 'text', + description: 'Подсказка при пустом поле', + table: { + category: 'Props', + defaultValue: { summary: "''" }, + type: { summary: 'string' }, + }, + }, + size: { + control: 'select', + options: ['small', 'base', 'large', 'xlarge'], + description: 'Размер поля', + table: { + category: 'Props', + defaultValue: { summary: "'base'" }, + type: { summary: "'small' | 'base' | 'large' | 'xlarge'" }, + }, + }, + disabled: { + control: 'boolean', + description: 'Отключает взаимодействие', + table: { + category: 'Props', + defaultValue: { summary: 'false' }, + type: { summary: 'boolean' }, + }, + }, + readonly: { + control: 'boolean', + description: 'Только для чтения', + table: { + category: 'Props', + defaultValue: { summary: 'false' }, + type: { summary: 'boolean' }, + }, + }, + invalid: { + control: 'boolean', + description: 'Невалидное состояние', + table: { + category: 'Props', + defaultValue: { summary: 'false' }, + type: { summary: 'boolean' }, + }, + }, + showClear: { + control: 'boolean', + description: 'Показывает иконку очистки при наличии значения', + table: { + category: 'Props', + defaultValue: { summary: 'false' }, + type: { summary: 'boolean' }, + }, + }, + fluid: { + control: 'boolean', + description: 'Растягивает поле на всю ширину контейнера', + table: { + category: 'Props', + defaultValue: { summary: 'false' }, + type: { summary: 'boolean' }, + }, + }, + variant: { + control: 'select', + options: ['outlined', 'filled'], + description: 'Визуальный вариант поля', + table: { + category: 'Props', + defaultValue: { summary: "'outlined'" }, + type: { summary: "'outlined' | 'filled'" }, + }, + }, + // Hidden props + modelValue: { table: { disable: true } }, + primeSize: { table: { disable: true } }, + sizeClass: { table: { disable: true } }, + + // ── Events ─────────────────────────────────────────────── + onClear: { + control: false, + description: 'Событие очистки поля (при showClear)', + table: { + category: 'Events', + type: { summary: 'EventEmitter' }, + }, + }, + }, + args: { + placeholder: 'Введите текст...', + size: 'base', + disabled: false, + readonly: false, + invalid: false, + showClear: false, + fluid: false, + variant: 'outlined', + }, +}; + +export default meta; +type Story = StoryObj; + +// ── Default ────────────────────────────────────────────────────────────────── +export const Default: Story = { + name: 'Default', + render: (args) => { + const parts: string[] = []; + + if (args.placeholder) parts.push(`placeholder="${args.placeholder}"`); + if (args.size && args.size !== 'base') parts.push(`size="${args.size}"`); + if (args.disabled) parts.push(`[disabled]="true"`); + if (args.readonly) parts.push(`[readonly]="true"`); + if (args.invalid) parts.push(`[invalid]="true"`); + if (args.showClear) parts.push(`[showClear]="true"`); + if (args.fluid) parts.push(`[fluid]="true"`); + if (args.variant && args.variant !== 'outlined') parts.push(`variant="${args.variant}"`); + parts.push(`[(ngModel)]="value"`); + + const template = ``; + + return { props: { ...args, value: '' }, template }; + }, + parameters: { + docs: { + description: { + story: 'Базовый пример компонента. Используйте Controls для интерактивного изменения пропсов.', + }, + }, + }, +}; + +// ── Re-exports from example components ──────────────────────────────────── +export { ClearButton, FloatLabelStory as FloatLabel, Disabled, Readonly, Invalid }; From cbe6ed8f8a9a89f0c60ab95c509edbd24e0f44be Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Thu, 16 Apr 2026 20:31:07 +0700 Subject: [PATCH 02/20] =?UTF-8?q?=D1=81=D1=82=D0=B8=D0=BB=D0=B8=D0=B7?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D1=80=D0=B0=D0=B7=D0=BC=D0=B5=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=20=D0=BA=D0=BE=D0=BC=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/CLAUDE-v1.6.md | 751 ------------------ .../inputtext/inputtext.component.ts | 9 +- src/prime-preset/tokens/tokens.json | 22 +- .../examples/inputtext-clear.component.ts | 3 +- .../inputtext-float-label.component.ts | 31 +- 5 files changed, 32 insertions(+), 784 deletions(-) delete mode 100644 .claude/CLAUDE-v1.6.md diff --git a/.claude/CLAUDE-v1.6.md b/.claude/CLAUDE-v1.6.md deleted file mode 100644 index 2cf230a4..00000000 --- a/.claude/CLAUDE-v1.6.md +++ /dev/null @@ -1,751 +0,0 @@ -# CLAUDE.md — Angular UI Kit (@cdek-it/angular-ui-kit) - -Инструкции для Claude Code по генерации компонентов, обёрток и сторисов. - ---- - -## Стек и версии - -| Технология | Версия | -|----------------|---------| -| Angular | 20 | -| PrimeNG | 20 | -| Storybook | 10 | -| Tailwind CSS | 3 | -| TypeScript | 5 | - ---- - -## Структура проекта - -``` -src/ -├── lib/ -│ └── components/ -│ └── {name}/ -│ └── {name}.component.ts ← компонент-обёртка -├── stories/ -│ └── components/ -│ └── {name}/ -│ ├── {name}.stories.ts ← сторисы -│ └── examples/ ← примеры для сторисов -├── prime-preset/ -│ └── tokens/ -│ └── components/ -│ └── {name}.ts ← CSS-токены компонента -└── styles.scss ← Tailwind + иконки + шрифты -``` - ---- - -## Паттерн компонента-обёртки - -Каждый компонент — standalone Angular-компонент, оборачивающий PrimeNG. - -### Правила - -1. Файл: `src/lib/components/{name}/{name}.component.ts` -2. `selector` — с приставкой `extra-` + имя компонента строчными буквами (например `selector: 'extra-button'`) -3. Импортировать PrimeNG-компонент и указать его в `imports: []` -4. Для каждого типа Input создавать отдельный `type`-алиас -5. Все `@Input()` отражают **свой** API обёртки, не PrimeNG напрямую -6. Computed-геттеры маппят API обёртки → PrimeNG API -7. Шаблон компонента использует только геттеры, не сырые инпуты - -### Эталон — ButtonComponent - -```typescript -import { Component, Input } from '@angular/core'; -import { Button, ButtonSeverity as PrimeButtonSeverity } from 'primeng/button'; - -// Типы — отдельные алиасы, не inline union -export type ButtonVariant = 'primary' | 'secondary' | 'outlined' | 'text' | 'link'; -export type ButtonSeverity = 'success' | 'warning' | 'danger' | 'info' | null; -export type ButtonSize = 'small' | 'base' | 'large' | 'xlarge'; -export type ButtonIconPos = 'prefix' | 'postfix' | null; -export type BadgeSeverity = 'success' | 'info' | 'warning' | 'danger' | 'secondary' | 'contrast' | null; - -@Component({ - selector: 'extra-button', - standalone: true, - imports: [Button], - template: ` - - ` -}) -export class ButtonComponent { - @Input() label = 'Button'; - @Input() variant: ButtonVariant = 'primary'; - @Input() severity: ButtonSeverity = null; - @Input() size: ButtonSize = 'base'; - @Input() rounded = false; - @Input() iconPos: ButtonIconPos = null; - @Input() iconOnly = false; - @Input() icon = ''; - @Input() disabled = false; - @Input() loading = false; - @Input() badge = ''; - @Input() badgeSeverity: BadgeSeverity = null; - @Input() showBadge = false; - @Input() fluid = false; - @Input() ariaLabel: string | undefined = undefined; - @Input() autofocus = false; - @Input() tabindex: number | undefined = undefined; - @Input() text = false; - - // Геттеры — маппинг в PrimeNG API - get primeSize(): 'small' | 'large' | undefined { - if (this.size === 'small') return 'small'; - if (this.size === 'large') return 'large'; - return undefined; - } - - get primeIconPos(): 'left' | 'right' { - return this.iconPos === 'postfix' ? 'right' : 'left'; - } - - get primeSeverity(): PrimeButtonSeverity | null { - if (this.variant === 'secondary') return 'secondary'; - if (this.severity === 'warning') return 'warn'; - return this.severity; - } - - get primeBadgeSeverity() { - if (this.badgeSeverity === 'warning') return 'warn'; - return this.badgeSeverity; - } -} -``` - ---- - -## Паттерн сторисов - -### Файл: `src/stories/components/{name}/{name}.stories.ts` - -**Все тексты описаний — на русском языке.** - -### Правило: title сториса - -Формат: `Components/{Category}/{ComponentName}` - -Категории соответствуют группировке на [primeng.org](https://primeng.org/): - -| Категория | Компоненты | -|-----------|-----------------------------------------------------------------------------------------------| -| Button | Button, SpeedDial, SplitButton | -| Data | DataTable, DataView, OrderList, OrgChart, Paginator, PickList, Timeline, Tree, TreeTable | -| Form | AutoComplete, Checkbox, ColorPicker, DatePicker, InputMask, InputNumber, InputOtp, InputText, Knob, Listbox, MultiSelect, Password, RadioButton, Rating, Select, SelectButton, Slider, Textarea, ToggleButton, ToggleSwitch, TreeSelect | -| Menu | Breadcrumb, ContextMenu, Dock, Menu, Menubar, MegaMenu, PanelMenu, Steps, TabMenu, TieredMenu | -| Messages | Message, Toast | -| Misc | Avatar, Badge, BlockUI, Chip, Inplace, MeterGroup, ProgressBar, ProgressSpinner, ScrollTop, Skeleton, Tag | -| Overlay | ConfirmDialog, ConfirmPopup, Dialog, Drawer, Popover, Tooltip | -| Panel | Accordion, Card, Divider, Fieldset, Panel, ScrollPanel, Splitter, Stepper, Tabs | -| Media | Carousel, Galleria, Image, ImageCompare | - -```typescript -// ❌ Запрещено -title: 'Prime/Button' -title: 'Components/Button' - -// ✅ Правильно -title: 'Components/Button/Button' -title: 'Components/Panel/Card' -title: 'Components/Panel/Divider' -title: 'Components/Form/InputText' -``` - -### Полный шаблон сториса - -```typescript -import { Meta, StoryObj, moduleMetadata } from '@storybook/angular'; -import { XxxComponent } from '../../../lib/components/xxx/xxx.component'; - -// Расширяем тип для Events, которых нет в @Output() -type XxxArgs = XxxComponent & { onClick?: (event: MouseEvent) => void }; - -const meta: Meta = { - title: 'Components/{Category}/Xxx', - component: XxxComponent, - tags: ['autodocs'], - decorators: [ - moduleMetadata({ imports: [XxxComponent] }) - ], - parameters: { - docs: { - description: { - // 1. Одна строка — для чего компонент - // 2. Ссылка на Figma - // 3. Блок импорта - component: `Описание компонента. [Figma Design](https://www.figma.com/design/...). - -\`\`\`typescript -import { XxxModule } from 'primeng/xxx'; -\`\`\``, - }, - }, - }, - argTypes: { - // ── Props ──────────────────────────────────────────────── - propName: { - control: 'text' | 'boolean' | 'select' | 'number', - options: [...], // только для select - description: 'Описание на русском', - table: { - category: 'Props', - defaultValue: { summary: 'значение' }, - type: { summary: "'тип1' | 'тип2'" }, - }, - }, - // ── Badge ──────────────────────────────────────────────── - badge: { - // ... category: 'Badge' - }, - // ── Events ─────────────────────────────────────────────── - onClick: { - control: false, - description: 'Событие клика', - table: { - category: 'Events', - type: { summary: 'EventEmitter' }, - }, - }, - }, - args: { - // Дефолты для полей, которые нужно явно инициализировать - }, -}; - -// commonTemplate — для сторисов-вариаций (НЕ для Default) -const commonTemplate = ` - -`; - -export default meta; -type Story = StoryObj; - -// ── Default ────────────────────────────────────────────────────────────────── -// Динамический render: template генерируется из текущих args. -// Storybook Angular захватывает template как source code → -// при смене controls сниппет обновляется автоматически. - -export const Default: Story = { - name: 'Default', - render: (args) => { - const parts: string[] = []; - - if (args.label) parts.push(`label="${args.label}"`); - if (args.variant) parts.push(`variant="${args.variant}"`); - if (args.severity) parts.push(`severity="${args.severity}"`); - // ... остальные пропсы - if (args.rounded) parts.push(`[rounded]="true"`); - if (args.disabled) parts.push(`[disabled]="true"`); - - const template = parts.length - ? `` - : ``; - - return { props: args, template }; - }, - args: { label: 'Label' }, - parameters: { - docs: { - description: { - story: 'Базовый пример компонента. Используйте Controls для интерактивного изменения пропсов.', - }, - }, - }, -}; - -// ── Сторисы-вариации ───────────────────────────────────────────────────────── -// Каждая сторис — ОДИН вариант компонента. -// Используют commonTemplate + props: args → controls работают. -// source.code — статичный минимальный пример. - -export const Sizes: Story = { - render: (args) => ({ props: args, template: commonTemplate }), - args: { label: 'Button', size: 'large' }, - parameters: { - docs: { - description: { story: 'Описание вариации.' }, - source: { - code: ``, - }, - }, - }, -}; -``` - ---- - -## Паттерн examples/ - -### Назначение - -Папка `src/stories/components/{name}/examples/` содержит **standalone Angular-компоненты** — каждый инкапсулирует один вариант использования компонента. -В блоке **Source** в Storybook показывается полноценный Angular-компонент (TypeScript), который пользователь библиотеки может скопировать к себе как есть. - -Это принципиально отличается от подхода в `{name}.stories.ts`, где `source.code` показывает просто HTML-шаблон. - -### Структура файла - -```typescript -import { Component } from '@angular/core'; -import { StoryObj } from '@storybook/angular'; -import { XxxComponent } from '../../../../lib/components/xxx/xxx.component'; - -// 1. Шаблон выносится в const — чтобы переиспользовать в source.code -const template = ` -
- -
-`; -const styles = ''; - -// 2. Standalone-компонент с реальным шаблоном -@Component({ - selector: 'app-xxx-variant', - standalone: true, - imports: [XxxComponent], - template, - styles, -}) -export class XxxVariantComponent {} - -// 3. StoryObj — рендерит компонент; source.code — код компонента для копирования -export const Variant: StoryObj = { - render: () => ({ - template: ``, - }), - parameters: { - docs: { - description: { story: 'Описание на русском.' }, - source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { XxxComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-xxx-variant', - standalone: true, - imports: [XxxComponent], - template: \` - - \`, -}) -export class XxxVariantComponent {} - `, - }, - }, - }, -}; -``` - -### Правила - -1. Каждый файл — **одна вариация**, один `@Component` + один `StoryObj` -2. Шаблон выносится в `const template` — чтобы использовать в `source.code` -3. `render: () => ({ template: '' })` — **только** для статичных примеров, где controls не нужны (форм-контролы с `ngModel`, группы компонентов). Для простых prop-вариаций controls не будут работать при таком подходе — см. правило ниже. -4. `source.code` содержит полный TypeScript-код компонента с импортами из `@cdek-it/angular-ui-kit` -5. Обёртка `
` — фон preview; **`p-4` не добавлять** -6. Именование файлов: `{name}-{variant}.component.ts` (например `avatar-label.component.ts`) -7. Именование selector компонента: `app-{name}-{variant}` (например `app-avatar-label`) -8. Класс компонента: `{Name}{Variant}Component` (например `AvatarLabelComponent`) - -### Когда создавать examples/ - -`examples/` создаётся **обязательно для каждого компонента** — для всех вариационных сторисов (кроме `Default`). - -`Default` (интерактивный playground) в examples/ **не дублируется** — он живёт только в `{name}.stories.ts`. - -Каждая вариационная сторис (`WithIcon`, `Removable`, `Disabled` и т.д.) имеет соответствующий файл в `examples/`. - ---- - -## Структура сторисов — обязательные разделы - -| Порядок | Сторис | Описание | -|---------|-------------|-----------------------------------------------------------------------| -| 1 | **Default** | Интерактивный playground. Динамический render. Все пропсы в Controls. | -| 2+ | Вариации | По одному варианту: Sizes, Icons, Rounded, Loading, Disabled, и т.д. | - -### Правило: один экземпляр компонента на сторис - -**Каждая сторис показывает ровно один вариант компонента. Все остальные виды компонента настраиваются с помощью пропсов через `args`.** - -В каждой вариационной сторис шаблон содержит **ровно один** экземпляр компонента. -Это правило распространяется как на сторисы в `{name}.stories.ts`, так и на компоненты в `examples/`. -Вариация демонстрируется через `args` (пропсы), а не через дублирование тегов. - -```typescript -// ❌ Запрещено — несколько экземпляров компонента в шаблоне -export const Sizes: Story = { - render: (args) => ({ - props: args, - template: ` - - - - `, - }), -}; - -// ❌ Запрещено — то же нарушение внутри examples/ -@Component({ template: ` - - - -` }) -export class TagSeveritiesComponent {} - -// ✅ Правильно — один экземпляр, вариация задаётся через args -export const Sizes: Story = { - render: (args) => ({ props: args, template: commonTemplate }), - args: { label: 'Button', size: 'large' }, -}; - -export const Severity: Story = { - render: (args) => ({ props: args, template: commonTemplate }), - args: { value: 'Success', severity: 'success' }, -}; -``` - -**Исключение**: составные компоненты (например группа радиокнопок / чекбоксов), где несколько дочерних элементов — это **сам смысл компонента**, а не визуальное перечисление вариантов. - -### Обязательные вариации для большинства компонентов -- `Sizes` — один компонент с нужным `size` в `args` -- `Icons` — один компонент с иконкой в `args` -- `Loading` — один компонент с `loading: true` в `args` -- `Rounded` — один компонент с `rounded: true` в `args` -- `Severity` — один компонент с нужным `severity` в `args` -- `Disabled` — один компонент с `disabled: true` в `args` - -### Правило: controls (пропсы) работают во всех вариационных сторисах - -**Вариационные сторисы ВСЕГДА рендерят через `commonTemplate + args`** — это единственный способ, при котором Storybook передаёт значения controls в компонент. - -`render: () => ({ template: '' })` — статичный рендер, controls **не работают**. Такой подход применим только для форм-контролов с `ngModel` и групп компонентов. - -```typescript -// ❌ Controls не работают — props не передаются в статичный компонент -export const Rounded: Story = { - render: () => ({ - template: ``, - }), -}; - -// ✅ Controls работают — props передаются через args -export const Rounded: Story = { - render: (args) => ({ props: args, template: commonTemplate }), - args: { value: 'Rounded', severity: 'success', rounded: true }, - parameters: { - docs: { - source: { - language: 'ts', - code: ` -import { Component } from '@angular/core'; -import { TagComponent } from '@cdek-it/angular-ui-kit'; - -@Component({ - selector: 'app-tag-rounded', - standalone: true, - imports: [TagComponent], - template: \\\` - - \\\`, -}) -export class TagRoundedComponent {} - `, - }, - }, - }, -}; -``` - -**Если для вариации существует example-файл:** example-компонент регистрируется в `moduleMetadata`, но сторис рендерит через `commonTemplate + args`. В `source.code` сторис показывает TypeScript-код из example-файла (дублируется вручную). - ---- - -## Ключевые технические решения - -### Почему Default story использует динамический render - -В Storybook 10 Angular `source.transform` **не реактивен** — вызывается один раз. -Единственный способ обновлять code-сниппет при смене controls: -генерировать `template` строку прямо в `render(args)`. -Storybook Angular использует `template` из render как source code. - -```typescript -// ✅ Правильно — template обновляется при смене controls -render: (args) => { - const template = ``; - return { props: args, template }; -}, - -// ❌ Неправильно — source.transform не реактивен -parameters: { - docs: { source: { transform: (src, ctx) => ... } } -} -``` - -### Почему НЕ используется самозакрывающийся тег - -Angular JIT-компилятор запрещает ``. -` - -``` - -Поиск иконок: https://tabler.io/icons - ---- - -## Стилизация компонентов - -### Порядок слоёв - -``` -Компонент-обёртка → PrimeNG (p-button) → PrimeNG Aura тема -→ Токены (src/prime-preset/tokens/components/{name}.ts) -→ Tailwind CSS -``` - -### Добавление CSS-токенов - -Файл: `src/prime-preset/tokens/components/{name}.ts` - -Структура токенов соответствует PrimeNG Aura preset. -Кастомные расширения — через префикс `--p-{name}-extend-*`. - -### Tailwind в шаблонах сторисов - -```html - -
- -
-``` - ---- - -## Референс Vue UI Kit - -Vue UI Kit (PrimeVue) — источник референса по структуре сторисов и вариациям компонентов: - -- **Репозиторий**: `~/Downloads/vue-ui-kit-3/src/plugins/prime/stories/` -- **Запущен локально**: `http://localhost:6006` - -### Что брать как референс - -| Vue файл | Что переносить в Angular | -|-----------------------------------|--------------------------------------------------| -| `Button/Button.stories.js` | argTypes, stories args, описания | -| `Button/Button.template.js` | Шаблоны вариаций (grid-матрица размеров/severity)| -| `Button/Button.mdx` | Структура документации, порядок сторисов | - -### Как адаптировать Vue → Angular - -| Vue | Angular | -|-----------------------------|----------------------------------------------| -| `v-bind="args"` | `[prop]="prop"` (через `props: args`) | -| `variant="text"` | Остаётся `variant="text"` (статичный шаблон) | -| `