From d199df911b1b5c431a1fc3e4a19e6071c52dbcb4 Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Wed, 15 Apr 2026 14:28:17 +0700 Subject: [PATCH 1/2] =?UTF-8?q?toast:=20=D1=81=D1=82=D0=B8=D0=BB=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8F,=20=D1=81=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D0=B8=D1=81=D1=8B,=20=D0=BE=D0=B1=D1=91=D1=80=D1=82=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/CLAUDE-v1.6.md | 751 ------------------ src/lib/components/toast/toast.component.ts | 51 ++ src/prime-preset/map-tokens.ts | 6 + src/prime-preset/tokens/components/toast.ts | 144 ++++ .../toast/examples/toast-default.component.ts | 79 ++ .../examples/toast-position.component.ts | 83 ++ .../examples/toast-severities.component.ts | 117 +++ .../toast/examples/toast-width.component.ts | 97 +++ .../toast-with-close-button.component.ts | 105 +++ .../examples/toast-with-content.component.ts | 123 +++ src/stories/components/toast/toast.stories.ts | 123 +++ 11 files changed, 928 insertions(+), 751 deletions(-) delete mode 100644 .claude/CLAUDE-v1.6.md create mode 100644 src/lib/components/toast/toast.component.ts create mode 100644 src/prime-preset/tokens/components/toast.ts create mode 100644 src/stories/components/toast/examples/toast-default.component.ts create mode 100644 src/stories/components/toast/examples/toast-position.component.ts create mode 100644 src/stories/components/toast/examples/toast-severities.component.ts create mode 100644 src/stories/components/toast/examples/toast-width.component.ts create mode 100644 src/stories/components/toast/examples/toast-with-close-button.component.ts create mode 100644 src/stories/components/toast/examples/toast-with-content.component.ts create mode 100644 src/stories/components/toast/toast.stories.ts diff --git a/.claude/CLAUDE-v1.6.md b/.claude/CLAUDE-v1.6.md deleted file mode 100644 index 2cf230a..0000000 --- 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"` (статичный шаблон) | -| ` + \`, +}) +export class ExampleComponent { + constructor(private messageService: MessageService) {} + + show(): void { + this.messageService.add({ + group: 'my-toast', + severity: 'info', + summary: 'Сообщение', + detail: 'Подпись', + life: 5000, + icon: 'ti ti-info-circle', + }); + } +} + `, + }, + }, + }, +}; diff --git a/src/stories/components/toast/examples/toast-width.component.ts b/src/stories/components/toast/examples/toast-width.component.ts new file mode 100644 index 0000000..70e8159 --- /dev/null +++ b/src/stories/components/toast/examples/toast-width.component.ts @@ -0,0 +1,97 @@ +import { Component } from '@angular/core'; +import { StoryObj } from '@storybook/angular'; +import { Toast } from 'primeng/toast'; +import { Button } from 'primeng/button'; +import { MessageService, SharedModule } from 'primeng/api'; + +const SIZES = [ + { key: 'sm', label: 'Small (20rem)', width: '20rem' }, + { key: 'base', label: 'Base (25rem)', width: '25rem' }, + { key: 'lg', label: 'Large (30rem)', width: '30rem' }, + { key: 'xlg', label: 'X-Large (45rem)', width: '45rem' }, +] as const; + +@Component({ + selector: 'app-toast-width', + standalone: true, + imports: [Toast, Button, SharedModule], + providers: [MessageService], + template: ` + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
+
+ +
+ @for (s of sizes; track s.key) { +
+
+
+ +
+ Сообщение +
Ширина {{ s.key }}: {{ s.width }}
+
+
+
+ } +
+ +
+ @for (s of sizes; track s.key) { + + } +
+ `, +}) +export class ToastWidthComponent { + readonly sizes = SIZES; + currentWidth = '25rem'; + + constructor(private readonly messageService: MessageService) {} + + show(width: string): void { + this.currentWidth = width; + this.messageService.clear('width-preview'); + this.messageService.add({ + key: 'width-preview', + severity: 'info', + summary: 'Сообщение', + detail: 'Ширина: ' + width, + life: 3000, + icon: 'ti ti-info-circle', + }); + } +} + +export const Width: StoryObj = { + render: () => ({ + template: ``, + }), + parameters: { + docs: { + description: { story: 'Ширина задаётся через CSS-переменную `--p-toast-width` с помощью пропа `pt`.' }, + source: { + language: 'html', + code: ` + + ... + + `, + }, + }, + }, +}; diff --git a/src/stories/components/toast/examples/toast-with-close-button.component.ts b/src/stories/components/toast/examples/toast-with-close-button.component.ts new file mode 100644 index 0000000..821a75e --- /dev/null +++ b/src/stories/components/toast/examples/toast-with-close-button.component.ts @@ -0,0 +1,105 @@ +import { Component } from '@angular/core'; +import { StoryObj } from '@storybook/angular'; +import { Toast } from 'primeng/toast'; +import { Button } from 'primeng/button'; +import { MessageService, SharedModule } from 'primeng/api'; + +const SEVERITIES = [ + { type: 'info', icon: 'ti ti-info-circle', label: 'Информация' }, + { type: 'success', icon: 'ti ti-circle-check', label: 'Успех' }, + { type: 'warn', icon: 'ti ti-alert-triangle', label: 'Предупреждение' }, + { type: 'error', icon: 'ti ti-alert-circle', label: 'Ошибка' }, +] as const; + +@Component({ + selector: 'app-toast-with-close-button', + standalone: true, + imports: [Toast, Button, SharedModule], + providers: [MessageService], + template: ` + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
+
+ +
+ @for (s of severities; track s.type) { +
+
+
+ +
+ Сообщение +
Подпись
+
+ +
+
+ } +
+ +
+ @for (s of severities; track s.type) { + + } +
+ `, +}) +export class ToastWithCloseButtonComponent { + readonly severities = SEVERITIES; + + constructor(private readonly messageService: MessageService) {} + + show(severity: string, icon: string): void { + this.messageService.add({ + key: 'with-close', + severity, + summary: 'Сообщение', + detail: 'Подпись', + life: 5000, + icon, + closable: true, + }); + } +} + +export const WithCloseButton: StoryObj = { + render: () => ({ + template: ``, + }), + parameters: { + docs: { + description: { story: 'Уведомления с кнопкой закрытия (closable: true).' }, + source: { + language: 'ts', + code: ` +this.messageService.add({ + group: 'my-toast', + severity: 'info', + summary: 'Сообщение', + detail: 'Подпись', + life: 5000, + icon: 'ti ti-info-circle', + closable: true, +}); + `, + }, + }, + }, +}; diff --git a/src/stories/components/toast/examples/toast-with-content.component.ts b/src/stories/components/toast/examples/toast-with-content.component.ts new file mode 100644 index 0000000..6f4453a --- /dev/null +++ b/src/stories/components/toast/examples/toast-with-content.component.ts @@ -0,0 +1,123 @@ +import { Component } from '@angular/core'; +import { StoryObj } from '@storybook/angular'; +import { Toast } from 'primeng/toast'; +import { Button } from 'primeng/button'; +import { MessageService, SharedModule } from 'primeng/api'; + +const SEVERITIES = [ + { type: 'info', icon: 'ti ti-info-circle', label: 'Информация' }, + { type: 'success', icon: 'ti ti-circle-check', label: 'Успех' }, + { type: 'warn', icon: 'ti ti-alert-triangle', label: 'Предупреждение' }, + { type: 'error', icon: 'ti ti-alert-circle', label: 'Ошибка' }, +] as const; + +@Component({ + selector: 'app-toast-with-content', + standalone: true, + imports: [Toast, Button, SharedModule], + providers: [MessageService], + template: ` + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
Дополнительный контент
+
+
+
Ячейка 1
+
Ячейка 2
+
+
+
+
+ +
+ @for (s of severities; track s.type) { +
+
+
+ +
+ Сообщение +
Подпись
+
+
Дополнительный контент
+
+
+
Ячейка 1
+
Ячейка 2
+
+
+ +
+
+ } +
+ +
+ @for (s of severities; track s.type) { + + } +
+ `, +}) +export class ToastWithContentComponent { + readonly severities = SEVERITIES; + + constructor(private readonly messageService: MessageService) {} + + show(severity: string, icon: string): void { + this.messageService.add({ + key: 'with-content', + severity, + summary: 'Сообщение', + detail: 'Подпись', + life: 5000, + icon, + closable: true, + }); + } +} + +export const WithContent: StoryObj = { + render: () => ({ + template: ``, + }), + parameters: { + docs: { + description: { story: 'Уведомления с дополнительным контентом под заголовком.' }, + source: { + language: 'html', + code: ` + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
Дополнительный контент
+
+
+
+
+ `, + }, + }, + }, +}; diff --git a/src/stories/components/toast/toast.stories.ts b/src/stories/components/toast/toast.stories.ts new file mode 100644 index 0000000..74f3aca --- /dev/null +++ b/src/stories/components/toast/toast.stories.ts @@ -0,0 +1,123 @@ +import { Meta, StoryObj, moduleMetadata } from '@storybook/angular'; +import { MessageService } from 'primeng/api'; +import { Toast } from 'primeng/toast'; +import { Button } from 'primeng/button'; +import { ToastComponent } from '../../../lib/components/toast/toast.component'; +import { ToastDefaultComponent } from './examples/toast-default.component'; +import { ToastSeveritiesComponent, Severities } from './examples/toast-severities.component'; +import { ToastWithCloseButtonComponent, WithCloseButton } from './examples/toast-with-close-button.component'; +import { ToastWithContentComponent, WithContent } from './examples/toast-with-content.component'; +import { ToastWidthComponent, Width } from './examples/toast-width.component'; +import { ToastPositionComponent, Position } from './examples/toast-position.component'; + +const meta: Meta = { + title: 'Components/Feedback/Toast', + component: ToastComponent, + tags: ['autodocs'], + decorators: [ + moduleMetadata({ + imports: [ + ToastComponent, + ToastDefaultComponent, + ToastSeveritiesComponent, + ToastWithCloseButtonComponent, + ToastWithContentComponent, + ToastWidthComponent, + ToastPositionComponent, + Toast, + Button, + ], + providers: [MessageService], + }), + ], + parameters: { + designTokens: { prefix: '--p-toast' }, + docs: { + description: { + component: `Компонент для отображения всплывающих уведомлений поверх интерфейса. Требует подключения \`MessageService\`. + +\`\`\`typescript +import { ToastComponent } from '@cdek-it/angular-ui-kit'; +import { MessageService } from 'primeng/api'; + +@Component({ + providers: [MessageService], +}) +export class MyComponent { + constructor(private messageService: MessageService) {} + + show(): void { + this.messageService.add({ + severity: 'info', + summary: 'Сообщение', + detail: 'Подпись', + life: 5000, + icon: 'ti ti-info-circle', + }); + } +} +\`\`\``, + }, + }, + }, + argTypes: { + position: { + control: 'select', + options: ['top-right', 'top-left', 'top-center', 'bottom-right', 'bottom-left', 'bottom-center', 'center'], + description: 'Позиция тоста на экране.', + table: { + category: 'Props', + defaultValue: { summary: 'top-right' }, + type: { summary: "'top-right' | 'top-left' | 'top-center' | 'bottom-right' | 'bottom-left' | 'bottom-center' | 'center'" }, + }, + }, + key: { + control: 'text', + description: 'Ключ для адресной отправки сообщений через MessageService.', + table: { + category: 'Props', + type: { summary: 'string' }, + }, + }, + life: { + control: 'number', + description: 'Время (мс) до автоматического закрытия тоста.', + table: { + category: 'Props', + defaultValue: { summary: '5000' }, + type: { summary: 'number' }, + }, + }, + }, + args: { + position: 'top-right', + key: undefined, + life: 5000, + }, +}; + +export default meta; +type Story = StoryObj; + +// ── Default ────────────────────────────────────────────────────────────────── + +export const Default: Story = { + name: 'Default', + render: (args) => ({ + props: { + position: args.position, + life: args.life, + }, + template: ``, + }), + parameters: { + docs: { + description: { + story: 'Базовый пример компонента. Используйте Controls для изменения позиции и времени жизни тоста.', + }, + }, + }, +}; + +// ── Re-exports from example components ──────────────────────────────────── +export { Severities, WithCloseButton, WithContent, Width, Position }; From 97e61d74a74cf507ee24c4b0c66a490b8ed7bb36 Mon Sep 17 00:00:00 2001 From: Danil Khaliulin Date: Wed, 15 Apr 2026 14:54:06 +0700 Subject: [PATCH 2/2] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=20=D1=81=D1=82?= =?UTF-8?q?=D0=B8=D0=BB=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B8=20?= =?UTF-8?q?=D1=81=D1=82=D0=BE=D1=80=D0=B8=D1=81=D0=BE=D0=B2=20=D1=81=D0=BE?= =?UTF-8?q?=D0=B3=D0=BB=D0=B0=D1=81=D0=BD=D0=BE=20=D0=BF=D0=B0=D1=82=D1=82?= =?UTF-8?q?=D0=B5=D1=80=D0=BD=D0=BE=D0=B2=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../toast/examples/toast-default.component.ts | 79 ----------- .../examples/toast-position.component.ts | 68 ++++----- .../examples/toast-severities.component.ts | 99 +++++++------ .../toast/examples/toast-width.component.ts | 101 +++++++------- .../toast-with-close-button.component.ts | 94 +++++++------ .../examples/toast-with-content.component.ts | 130 +++++++++--------- src/stories/components/toast/toast.stories.ts | 53 +------ 7 files changed, 262 insertions(+), 362 deletions(-) delete mode 100644 src/stories/components/toast/examples/toast-default.component.ts diff --git a/src/stories/components/toast/examples/toast-default.component.ts b/src/stories/components/toast/examples/toast-default.component.ts deleted file mode 100644 index 969a1ea..0000000 --- a/src/stories/components/toast/examples/toast-default.component.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { Component, Input, OnChanges } from '@angular/core'; -import { Toast } from 'primeng/toast'; -import { Button } from 'primeng/button'; -import { MessageService, SharedModule } from 'primeng/api'; - -const SEVERITIES = [ - { type: 'info', icon: 'ti ti-info-circle', label: 'Информация' }, - { type: 'success', icon: 'ti ti-circle-check', label: 'Успех' }, - { type: 'warn', icon: 'ti ti-alert-triangle', label: 'Предупреждение' }, - { type: 'error', icon: 'ti ti-alert-circle', label: 'Ошибка' }, -] as const; - -@Component({ - selector: 'app-toast-default', - standalone: true, - imports: [Toast, Button, SharedModule], - providers: [MessageService], - template: ` - - -
- -
- {{ message.summary }} -
{{ message.detail }}
-
-
-
- -
- @for (s of severities; track s.type) { -
-
-
- -
- Сообщение -
Подпись
-
-
-
- } -
- -
- @for (s of severities; track s.type) { - - } -
- `, -}) -export class ToastDefaultComponent implements OnChanges { - @Input() position = 'top-right'; - @Input() life = 5000; - - readonly severities = SEVERITIES; - - constructor(private readonly messageService: MessageService) {} - - ngOnChanges(): void { - this.messageService.clear('default-story'); - } - - show(severity: string, icon: string): void { - this.messageService.add({ - key: 'default-story', - severity, - summary: 'Сообщение', - detail: 'Подпись', - life: this.life, - icon, - }); - } -} diff --git a/src/stories/components/toast/examples/toast-position.component.ts b/src/stories/components/toast/examples/toast-position.component.ts index 49a8738..4b6492f 100644 --- a/src/stories/components/toast/examples/toast-position.component.ts +++ b/src/stories/components/toast/examples/toast-position.component.ts @@ -13,35 +13,39 @@ const POSITIONS = [ { position: 'bottom-right', label: 'Вниз справа', key: 'pos-bottom-right' }, ] as const; +const template = ` +@for (p of positions; track p.key) { + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
+
+} + +
+ @for (p of positions; track p.key) { + + } +
+`; +const styles = ''; + @Component({ selector: 'app-toast-position', standalone: true, imports: [Toast, Button, SharedModule], providers: [MessageService], - template: ` - @for (p of positions; track p.key) { - - -
- -
- {{ message.summary }} -
{{ message.detail }}
-
-
-
- } - -
- @for (p of positions; track p.key) { - - } -
- `, + template, + styles, }) export class ToastPositionComponent { readonly positions = POSITIONS; @@ -66,16 +70,16 @@ export const Position: StoryObj = { }), parameters: { docs: { - description: { story: 'Расположение тоста задаётся через `position` и `group`.' }, + description: { story: 'Расположение тоста задаётся через `position` и `key`.' }, source: { - language: 'html', + language: 'ts', code: ` - - - - - - + + + + + + `, }, }, diff --git a/src/stories/components/toast/examples/toast-severities.component.ts b/src/stories/components/toast/examples/toast-severities.component.ts index 5b6e6f2..9dbbe33 100644 --- a/src/stories/components/toast/examples/toast-severities.component.ts +++ b/src/stories/components/toast/examples/toast-severities.component.ts @@ -11,49 +11,53 @@ const SEVERITIES = [ { type: 'error', icon: 'ti ti-alert-circle', label: 'Ошибка' }, ] as const; -@Component({ - selector: 'app-toast-severities', - standalone: true, - imports: [Toast, Button, SharedModule], - providers: [MessageService], - template: ` - - +const template = ` + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
+
+ +
+ @for (s of severities; track s.type) { +
+
- +
- {{ message.summary }} -
{{ message.detail }}
+ Сообщение +
Подпись
- - - -
- @for (s of severities; track s.type) { -
-
-
- -
- Сообщение -
Подпись
-
-
-
- } +
+ } +
-
- @for (s of severities; track s.type) { - - } -
- `, +
+ @for (s of severities; track s.type) { + + } +
+`; +const styles = ''; + +@Component({ + selector: 'app-toast-severities', + standalone: true, + imports: [Toast, Button, SharedModule], + providers: [MessageService], + template, + styles, }) export class ToastSeveritiesComponent { readonly severities = SEVERITIES; @@ -83,16 +87,25 @@ export const Severities: StoryObj = { language: 'ts', code: ` import { Component } from '@angular/core'; -import { MessageService } from 'primeng/api'; -import { ToastComponent } from '@cdek-it/angular-ui-kit'; +import { MessageService, SharedModule } from 'primeng/api'; +import { Toast } from 'primeng/toast'; @Component({ selector: 'app-example', standalone: true, - imports: [ToastComponent], + imports: [Toast, SharedModule], providers: [MessageService], template: \` - + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
+
\`, }) @@ -101,7 +114,7 @@ export class ExampleComponent { show(): void { this.messageService.add({ - group: 'my-toast', + key: 'my-toast', severity: 'info', summary: 'Сообщение', detail: 'Подпись', diff --git a/src/stories/components/toast/examples/toast-width.component.ts b/src/stories/components/toast/examples/toast-width.component.ts index 70e8159..7c78814 100644 --- a/src/stories/components/toast/examples/toast-width.component.ts +++ b/src/stories/components/toast/examples/toast-width.component.ts @@ -5,57 +5,64 @@ import { Button } from 'primeng/button'; import { MessageService, SharedModule } from 'primeng/api'; const SIZES = [ - { key: 'sm', label: 'Small (20rem)', width: '20rem' }, - { key: 'base', label: 'Base (25rem)', width: '25rem' }, - { key: 'lg', label: 'Large (30rem)', width: '30rem' }, - { key: 'xlg', label: 'X-Large (45rem)', width: '45rem' }, + { key: 'sm', label: 'Small (20rem)', width: '20rem', cssVar: '20rem' }, + { key: 'base', label: 'Base (25rem)', width: '25rem', cssVar: '25rem' }, + { key: 'lg', label: 'Large (30rem)', width: '30rem', cssVar: '30rem' }, + { key: 'xlg', label: 'X-Large (45rem)', width: '45rem', cssVar: '45rem' }, ] as const; -@Component({ - selector: 'app-toast-width', - standalone: true, - imports: [Toast, Button, SharedModule], - providers: [MessageService], - template: ` - + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
+
+ +
+ @for (s of sizes; track s.key) { +
- +
- +
- {{ message.summary }} -
{{ message.detail }}
-
- - - -
- @for (s of sizes; track s.key) { -
-
-
- -
- Сообщение -
Ширина {{ s.key }}: {{ s.width }}
-
-
+ Сообщение +
Ширина {{ s.key }}: {{ s.width }}
- } +
+ } +
-
- @for (s of sizes; track s.key) { - - } -
- `, +
+ @for (s of sizes; track s.key) { + + } +
+`; +const styles = ''; + +@Component({ + selector: 'app-toast-width', + standalone: true, + imports: [Toast, Button, SharedModule], + providers: [MessageService], + template, + styles, }) export class ToastWidthComponent { readonly sizes = SIZES; @@ -63,14 +70,14 @@ export class ToastWidthComponent { constructor(private readonly messageService: MessageService) {} - show(width: string): void { - this.currentWidth = width; + show(cssVar: string): void { + this.currentWidth = cssVar; this.messageService.clear('width-preview'); this.messageService.add({ key: 'width-preview', severity: 'info', summary: 'Сообщение', - detail: 'Ширина: ' + width, + detail: 'Ширина: ' + cssVar, life: 3000, icon: 'ti ti-info-circle', }); @@ -85,7 +92,7 @@ export const Width: StoryObj = { docs: { description: { story: 'Ширина задаётся через CSS-переменную `--p-toast-width` с помощью пропа `pt`.' }, source: { - language: 'html', + language: 'ts', code: ` ... diff --git a/src/stories/components/toast/examples/toast-with-close-button.component.ts b/src/stories/components/toast/examples/toast-with-close-button.component.ts index 821a75e..eabd523 100644 --- a/src/stories/components/toast/examples/toast-with-close-button.component.ts +++ b/src/stories/components/toast/examples/toast-with-close-button.component.ts @@ -11,55 +11,59 @@ const SEVERITIES = [ { type: 'error', icon: 'ti ti-alert-circle', label: 'Ошибка' }, ] as const; -@Component({ - selector: 'app-toast-with-close-button', - standalone: true, - imports: [Toast, Button, SharedModule], - providers: [MessageService], - template: ` - - +const template = ` + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
+
+ +
+ @for (s of severities; track s.type) { +
+
- +
- {{ message.summary }} -
{{ message.detail }}
-
- - - -
- @for (s of severities; track s.type) { -
-
-
- -
- Сообщение -
Подпись
-
- -
+ Сообщение +
Подпись
- } + +
+ } +
-
- @for (s of severities; track s.type) { - - } -
- `, +
+ @for (s of severities; track s.type) { + + } +
+`; +const styles = ''; + +@Component({ + selector: 'app-toast-with-close-button', + standalone: true, + imports: [Toast, Button, SharedModule], + providers: [MessageService], + template, + styles, }) export class ToastWithCloseButtonComponent { readonly severities = SEVERITIES; @@ -90,7 +94,7 @@ export const WithCloseButton: StoryObj = { language: 'ts', code: ` this.messageService.add({ - group: 'my-toast', + key: 'my-toast', severity: 'info', summary: 'Сообщение', detail: 'Подпись', diff --git a/src/stories/components/toast/examples/toast-with-content.component.ts b/src/stories/components/toast/examples/toast-with-content.component.ts index 6f4453a..5aadaf6 100644 --- a/src/stories/components/toast/examples/toast-with-content.component.ts +++ b/src/stories/components/toast/examples/toast-with-content.component.ts @@ -11,19 +11,34 @@ const SEVERITIES = [ { type: 'error', icon: 'ti ti-alert-circle', label: 'Ошибка' }, ] as const; -@Component({ - selector: 'app-toast-with-content', - standalone: true, - imports: [Toast, Button, SharedModule], - providers: [MessageService], - template: ` - - +const template = ` + + +
+ +
+ {{ message.summary }} +
{{ message.detail }}
+
+
Дополнительный контент
+
+
+
Ячейка 1
+
Ячейка 2
+
+
+
+
+ +
+ @for (s of severities; track s.type) { +
+
- +
- {{ message.summary }} -
{{ message.detail }}
+ Сообщение +
Подпись
Дополнительный контент
@@ -32,48 +47,37 @@ const SEVERITIES = [
Ячейка 2
- - - -
- @for (s of severities; track s.type) { -
-
-
- -
- Сообщение -
Подпись
-
-
Дополнительный контент
-
-
-
Ячейка 1
-
Ячейка 2
-
-
- -
-
- } + +
+ } +
-
- @for (s of severities; track s.type) { - - } -
- `, +
+ @for (s of severities; track s.type) { + + } +
+`; +const styles = ''; + +@Component({ + selector: 'app-toast-with-content', + standalone: true, + imports: [Toast, Button, SharedModule], + providers: [MessageService], + template, + styles, }) export class ToastWithContentComponent { readonly severities = SEVERITIES; @@ -101,21 +105,17 @@ export const WithContent: StoryObj = { docs: { description: { story: 'Уведомления с дополнительным контентом под заголовком.' }, source: { - language: 'html', + language: 'ts', code: ` - - -
- -
- {{ message.summary }} -
{{ message.detail }}
-
-
Дополнительный контент
-
-
-
-
+this.messageService.add({ + key: 'my-toast', + severity: 'info', + summary: 'Сообщение', + detail: 'Подпись', + life: 5000, + icon: 'ti ti-info-circle', + closable: true, +}); `, }, }, diff --git a/src/stories/components/toast/toast.stories.ts b/src/stories/components/toast/toast.stories.ts index 74f3aca..6ca7b62 100644 --- a/src/stories/components/toast/toast.stories.ts +++ b/src/stories/components/toast/toast.stories.ts @@ -1,9 +1,6 @@ import { Meta, StoryObj, moduleMetadata } from '@storybook/angular'; import { MessageService } from 'primeng/api'; -import { Toast } from 'primeng/toast'; -import { Button } from 'primeng/button'; import { ToastComponent } from '../../../lib/components/toast/toast.component'; -import { ToastDefaultComponent } from './examples/toast-default.component'; import { ToastSeveritiesComponent, Severities } from './examples/toast-severities.component'; import { ToastWithCloseButtonComponent, WithCloseButton } from './examples/toast-with-close-button.component'; import { ToastWithContentComponent, WithContent } from './examples/toast-with-content.component'; @@ -18,14 +15,11 @@ const meta: Meta = { moduleMetadata({ imports: [ ToastComponent, - ToastDefaultComponent, ToastSeveritiesComponent, ToastWithCloseButtonComponent, ToastWithContentComponent, ToastWidthComponent, ToastPositionComponent, - Toast, - Button, ], providers: [MessageService], }), @@ -39,23 +33,6 @@ const meta: Meta = { \`\`\`typescript import { ToastComponent } from '@cdek-it/angular-ui-kit'; import { MessageService } from 'primeng/api'; - -@Component({ - providers: [MessageService], -}) -export class MyComponent { - constructor(private messageService: MessageService) {} - - show(): void { - this.messageService.add({ - severity: 'info', - summary: 'Сообщение', - detail: 'Подпись', - life: 5000, - icon: 'ti ti-info-circle', - }); - } -} \`\`\``, }, }, @@ -72,12 +49,7 @@ export class MyComponent { }, }, key: { - control: 'text', - description: 'Ключ для адресной отправки сообщений через MessageService.', - table: { - category: 'Props', - type: { summary: 'string' }, - }, + table: { disable: true }, }, life: { control: 'number', @@ -97,27 +69,6 @@ export class MyComponent { }; export default meta; -type Story = StoryObj; - -// ── Default ────────────────────────────────────────────────────────────────── - -export const Default: Story = { - name: 'Default', - render: (args) => ({ - props: { - position: args.position, - life: args.life, - }, - template: ``, - }), - parameters: { - docs: { - description: { - story: 'Базовый пример компонента. Используйте Controls для изменения позиции и времени жизни тоста.', - }, - }, - }, -}; // ── Re-exports from example components ──────────────────────────────────── -export { Severities, WithCloseButton, WithContent, Width, Position }; +export { Severities as Default, WithCloseButton, WithContent, Width, Position };