diff --git a/.storybook/preview.ts b/.storybook/preview.ts index bd5a1c5f..78c56666 100644 --- a/.storybook/preview.ts +++ b/.storybook/preview.ts @@ -68,6 +68,9 @@ const preview: Preview = { globals: { theme: 'light' }, }, controls: { + // Полная таблица в панели Controls: имя, описание, тип, дефолт и группы категорий. + // В компактном режиме Storybook 10 описание пропса не отображается. + expanded: true, matchers: { color: /(background|color)$/i, date: /Date$/i diff --git a/docs/components-api/image.md b/docs/components-api/image.md new file mode 100644 index 00000000..545c5898 --- /dev/null +++ b/docs/components-api/image.md @@ -0,0 +1,54 @@ +# Image + +Обёртка над PrimeNG Image: изображение с предпросмотром (маска, тулбар, зум, поворот). + +> **Эталон Figma отсутствует.** Компонент добавлен как обёртка над `p-image`; токены `components.image` +> собраны из семантического уровня и не сверяются с макетом. Подробности — `src/lib/components/image/image.figma.md`. + +## Импорт + +```typescript +import { ExtraImageComponent } from '@cdek-it/angular-ui-kit/components/image'; +``` + +## Входы + +| Вход | Тип | По умолчанию | Описание | +|---|---|---|---| +| `src` | `string` | — (обязательный) | URL изображения | +| `alt` | `string` | `''` | Альтернативный текст | +| `width` | `string` | `undefined` | Ширина (как HTML-атрибут) | +| `height` | `string` | `undefined` | Высота (как HTML-атрибут) | +| `preview` | `boolean` | `false` | Предпросмотр по клику | +| `imageClass` | `string` | `undefined` | CSS-класс изображения | +| `styleClass` | `string` | `undefined` | CSS-класс корневого элемента | + +## Пример + +```html + +``` + +## Слоты панели предпросмотра + +Иконки кнопок тулбара заменяются шаблонами `extraImageTemplate`: + +| Слот | Кнопка | +|---|---| +| `rotateRightIcon` | поворот вправо | +| `rotateLeftIcon` | поворот влево | +| `zoomOutIcon` | уменьшить | +| `zoomInIcon` | увеличить | +| `closeIcon` | закрыть | + +```html + + + +``` + +Шаблоны импортируются через `ExtraImageTemplateDirective` из `@cdek-it/angular-ui-kit/components/image`. + +## Доступность + +`alt` обязателен по смыслу: без него изображение озвучивается как декоративное. diff --git a/src/lib/components/image/image-template.directive.ts b/src/lib/components/image/image-template.directive.ts new file mode 100644 index 00000000..b7ac967b --- /dev/null +++ b/src/lib/components/image/image-template.directive.ts @@ -0,0 +1,13 @@ +import { Directive, Input, TemplateRef } from '@angular/core'; + +export type ExtraImageTemplateName = 'rotateRightIcon' | 'rotateLeftIcon' | 'zoomOutIcon' | 'zoomInIcon' | 'closeIcon'; + +/** Именованный шаблон иконки панели предпросмотра. */ +@Directive({ + selector: '[extraImageTemplate]' +}) +export class ExtraImageTemplateDirective { + @Input({ required: true }) extraImageTemplate!: ExtraImageTemplateName; + + constructor(public template: TemplateRef) {} +} diff --git a/src/lib/components/image/image.component.spec.ts b/src/lib/components/image/image.component.spec.ts new file mode 100644 index 00000000..9eef262f --- /dev/null +++ b/src/lib/components/image/image.component.spec.ts @@ -0,0 +1,52 @@ +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideNoopAnimations } from '@angular/platform-browser/animations'; +import { providePrimeNG } from 'primeng/config'; + +import { ExtraImageComponent } from './image.component'; + +@Component({ + standalone: true, + imports: [ExtraImageComponent], + template: ` + @if (show) { + + } + ` +}) +class HostComponent { + show = true; +} + +describe('ExtraImageComponent', () => { + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [HostComponent], + providers: [provideNoopAnimations(), providePrimeNG({})] + }).compileComponents(); + + fixture = TestBed.createComponent(HostComponent); + fixture.detectChanges(); + }); + + afterEach(() => { + document.body.classList.remove('p-overflow-hidden'); + document.body.style.removeProperty('--scrollbar-width'); + }); + + it('снимает блокировку прокрутки при уничтожении с открытым предпросмотром', () => { + const previewButton: HTMLElement | null = fixture.nativeElement.querySelector('.p-image-preview-mask'); + expect(previewButton).withContext('кнопка предпросмотра').toBeTruthy(); + + previewButton!.click(); + fixture.detectChanges(); + expect(document.body.classList.contains('p-overflow-hidden')).withContext('прокрутка заблокирована').toBeTrue(); + + fixture.componentInstance.show = false; + fixture.detectChanges(); + + expect(document.body.classList.contains('p-overflow-hidden')).withContext('прокрутка разблокирована').toBeFalse(); + }); +}); diff --git a/src/lib/components/image/image.component.ts b/src/lib/components/image/image.component.ts new file mode 100644 index 00000000..758b052f --- /dev/null +++ b/src/lib/components/image/image.component.ts @@ -0,0 +1,119 @@ +import { + AfterContentInit, + ChangeDetectionStrategy, + ChangeDetectorRef, + Component, + ContentChildren, + Input, + OnDestroy, + QueryList, + ViewChild +} from '@angular/core'; +import { NgTemplateOutlet } from '@angular/common'; +import { Image } from 'primeng/image'; +import { unblockBodyScroll } from 'primeng/dom'; +import { PrimeTemplate } from 'primeng/api'; +import { ExtraImageTemplateDirective, ExtraImageTemplateName } from './image-template.directive'; + +/** + * Обёртка над PrimeNG Image: картинка с предпросмотром (маска, тулбар, зум, поворот). + * + * Эталона в Figma нет, токены `components.image` собраны вручную (см. `image.figma.md`). + */ +@Component({ + selector: 'extra-image', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [Image, PrimeTemplate, NgTemplateOutlet], + template: ` + + @if (rotateRightTpl) { + + + + } + @if (rotateLeftTpl) { + + + + } + @if (zoomOutTpl) { + + + + } + @if (zoomInTpl) { + + + + } + @if (closeTpl) { + + + + } + + ` +}) +export class ExtraImageComponent implements AfterContentInit, OnDestroy { + /** URL изображения. */ + @Input({ required: true }) src = ''; + /** Альтернативный текст. */ + @Input() alt = ''; + /** Ширина изображения (строка, как в HTML-атрибуте). */ + @Input() width: string | undefined; + /** Высота изображения (строка, как в HTML-атрибуте). */ + @Input() height: string | undefined; + /** Включает предпросмотр по клику. */ + @Input() preview = false; + /** CSS-класс самого изображения. */ + @Input() imageClass: string | undefined; + /** CSS-класс корневого элемента. */ + @Input() styleClass: string | undefined; + + @ContentChildren(ExtraImageTemplateDirective) templates!: QueryList; + + @ViewChild(Image) private image?: Image; + + /** Открыт ли предпросмотр: нужен, чтобы снять блокировку прокрутки при уничтожении. */ + previewOpen = false; + + rotateRightTpl?: ExtraImageTemplateDirective; + rotateLeftTpl?: ExtraImageTemplateDirective; + zoomOutTpl?: ExtraImageTemplateDirective; + zoomInTpl?: ExtraImageTemplateDirective; + closeTpl?: ExtraImageTemplateDirective; + + constructor(private cdr: ChangeDetectorRef) {} + + ngAfterContentInit(): void { + this.rotateRightTpl = this.findTemplate('rotateRightIcon'); + this.rotateLeftTpl = this.findTemplate('rotateLeftIcon'); + this.zoomOutTpl = this.findTemplate('zoomOutIcon'); + this.zoomInTpl = this.findTemplate('zoomInIcon'); + this.closeTpl = this.findTemplate('closeIcon'); + this.cdr.detectChanges(); + } + + ngOnDestroy(): void { + // PrimeNG блокирует прокрутку body на открытом preview и снимает блокировку только + // в closePreview(). При уничтожении обёртки предпросмотр нужно закрыть самим. + if (!this.previewOpen && !this.image?.previewVisible) return; + this.image?.closePreview(); + unblockBodyScroll(); + } + + private findTemplate(name: ExtraImageTemplateName): ExtraImageTemplateDirective | undefined { + return this.templates.find((tpl) => tpl.extraImageTemplate === name); + } +} diff --git a/src/lib/components/image/image.figma.md b/src/lib/components/image/image.figma.md new file mode 100644 index 00000000..0cd3a9a0 --- /dev/null +++ b/src/lib/components/image/image.figma.md @@ -0,0 +1,44 @@ +--- +component: ExtraImage +selector: extra-image +import: + symbol: ExtraImageComponent + from: '@cdek-it/angular-ui-kit/components/image' +figma: + fileKey: 'Q1BWgZ7zoV5UzlBOnjW0cM' + nodeId: '' + name: '' +status: experimental +updated: '2026-11-19' +--- + +# Image + +**Эталон в Figma отсутствует.** В UI Kit DS v3.0 нет набора ``, поэтому компонент добавлен как обёртка над +PrimeNG `p-image` и **не сверяется** гейтом `check-figma-values`. + +Токены `components.image` собраны вручную из семантического уровня (не из макета): + +| Токен | Значение (семантика) | Где применён | +|---|---|---| +| `root.borderRadius` | `dimension.borderRadius.300` | скругление изображения | +| `preview.mask.background` | `color.bg.neutral.medium.default` | маска предпросмотра | +| `preview.mask.color` | `color.fg.default` | иконка предпросмотра | +| `mask.background` | `color.bg.surface.backdrop` | фон оверлея предпросмотра | +| `toolbar.background` | `color.bg.surface.raised.default` | тулбар предпросмотра | +| `toolbar.borderColor` | `color.border.neutral.default` | рамка тулбара | +| `toolbar.borderWidth` | `dimension.borderWidth.100` | толщина рамки тулбара | +| `toolbar.borderRadius` | `dimension.borderRadius.300` | радиус тулбара | +| `toolbar.padding` | `dimension.space.200` | внутренние отступы тулбара | +| `toolbar.gap` | `dimension.space.200` | расстояние между кнопками | +| `toolbar.shadow` | `effects.elevation.300` | тень тулбара | +| `action.size` | `dimension.size.1000` | размер кнопки (36px) | +| `action.iconSize` | `dimension.size.450` | размер иконки (16px) | +| `action.borderRadius` | `dimension.borderRadius.max` | скругление кнопки | +| `action.color` | `color.fg.default` | цвет иконки | +| `action.hoverBackground` | `color.bg.neutral.medium.default` | фон кнопки при наведении | +| `action.hoverColor` | `color.fg.default` | цвет иконки при наведении | +| `action.focusRing.width` | `dimension.focusRing.width` | толщина кольца фокуса | +| `action.focusRing.color` | `color.fg.brand.active` | цвет кольца фокуса | + +Когда появится эталон в Figma — заменить значения на макетные и прогнать `check-figma-values`. diff --git a/src/lib/components/image/ng-package.json b/src/lib/components/image/ng-package.json new file mode 100644 index 00000000..3a74fd76 --- /dev/null +++ b/src/lib/components/image/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "public_api.ts" + } +} diff --git a/src/lib/components/image/public_api.ts b/src/lib/components/image/public_api.ts new file mode 100644 index 00000000..1cabd6cc --- /dev/null +++ b/src/lib/components/image/public_api.ts @@ -0,0 +1,2 @@ +export * from './image.component'; +export * from './image-template.directive'; diff --git a/src/lib/providers/prime-preset/map-tokens.ts b/src/lib/providers/prime-preset/map-tokens.ts index 929e6bde..e2854279 100644 --- a/src/lib/providers/prime-preset/map-tokens.ts +++ b/src/lib/providers/prime-preset/map-tokens.ts @@ -53,12 +53,17 @@ import { autocompleteCss } from './tokens/components/autocomplete'; import { popoverCss } from './tokens/components/popover'; import { selectbuttonCss } from './tokens/components/selectbutton'; import { fileuploadCss } from './tokens/components/fileupload'; +import { imageCss } from './tokens/components/image'; const presetTokens: Preset = { primitive: tokens.primitive as unknown as AuraBaseDesignTokens['primitive'], semantic: tokens.semantic as unknown as AuraBaseDesignTokens['semantic'], components: { ...(tokens.components as unknown as ComponentsDesignTokens), + image: { + ...((tokens.components as unknown as Record)['image'] ?? {}), + css: imageCss + }, avatar: { ...(tokens.components.avatar as unknown as ComponentsDesignTokens['avatar']), css: avatarCss diff --git a/src/lib/providers/prime-preset/tokens/components/image.ts b/src/lib/providers/prime-preset/tokens/components/image.ts new file mode 100644 index 00000000..eabdd94f --- /dev/null +++ b/src/lib/providers/prime-preset/tokens/components/image.ts @@ -0,0 +1,74 @@ +export const imageCss = ({ dt }: { dt: (token: string) => string }): string => ` +.p-image { + border-radius: ${dt('image.root.borderRadius')}; + overflow: hidden; +} + +.p-image-preview-mask { + background: ${dt('image.preview.mask.background')}; +} + +.p-image-mask { + background: ${dt('image.mask.background')}; +} + +/* Aura задаёт фон маски анимацией с forwards — переопределяем её. */ +.p-image-mask.p-overlay-mask-enter { + animation-name: p-image-mask-enter; +} + +.p-image-mask.p-overlay-mask-leave { + animation-name: p-image-mask-leave; +} + +@keyframes p-image-mask-enter { + from { + background: transparent; + } + to { + background: ${dt('image.mask.background')}; + } +} + +@keyframes p-image-mask-leave { + from { + background: ${dt('image.mask.background')}; + } + to { + background: transparent; + } +} + +.p-image-toolbar { + background: ${dt('image.toolbar.background')}; + border: ${dt('image.toolbar.borderWidth')} solid ${dt('image.toolbar.borderColor')}; + border-radius: ${dt('image.toolbar.borderRadius')}; + padding: ${dt('image.toolbar.padding')}; + gap: ${dt('image.toolbar.gap')}; + box-shadow: ${dt('image.toolbar.shadow')}; +} + +.p-image-toolbar .p-image-action { + width: ${dt('image.action.size')}; + height: ${dt('image.action.size')}; + border-radius: ${dt('image.action.borderRadius')}; + color: ${dt('image.action.color')}; +} + +.p-image-toolbar .p-image-action:hover { + background: ${dt('image.action.hoverBackground')}; + color: ${dt('image.action.hoverColor')}; +} + +.p-image-toolbar .p-image-action:focus-visible { + outline: ${dt('image.action.focusRing.width')} solid ${dt('image.action.focusRing.color')}; + outline-offset: 0; + box-shadow: none; +} + +.p-image-toolbar .p-image-action .p-icon { + width: ${dt('image.action.iconSize')}; + height: ${dt('image.action.iconSize')}; + font-size: ${dt('image.action.iconSize')}; +} +`; diff --git a/src/lib/providers/prime-preset/tokens/tokens.json b/src/lib/providers/prime-preset/tokens/tokens.json index c8cb9366..8b51236e 100644 --- a/src/lib/providers/prime-preset/tokens/tokens.json +++ b/src/lib/providers/prime-preset/tokens/tokens.json @@ -5874,6 +5874,41 @@ "color": "transparent" } } + }, + "image": { + "root": { + "borderRadius": "{dimension.borderRadius.300}" + }, + "preview": { + "mask": { + "background": "{color.bg.neutral.medium.default}", + "color": "{color.fg.default}" + } + }, + "mask": { + "background": "{color.bg.surface.backdrop}" + }, + "toolbar": { + "background": "{color.bg.surface.raised.default}", + "borderColor": "{color.border.neutral.default}", + "borderWidth": "{dimension.borderWidth.100}", + "borderRadius": "{dimension.borderRadius.300}", + "padding": "{dimension.space.200}", + "gap": "{dimension.space.200}", + "shadow": "{effects.elevation.300}" + }, + "action": { + "size": "{dimension.size.1000}", + "iconSize": "{dimension.size.450}", + "borderRadius": "{dimension.borderRadius.max}", + "color": "{color.fg.default}", + "hoverBackground": "{color.bg.neutral.medium.default}", + "hoverColor": "{color.fg.default}", + "focusRing": { + "width": "{dimension.focusRing.width}", + "color": "{color.fg.brand.active}" + } + } } } } diff --git a/src/stories/components/image/examples/image-crop.component.ts b/src/stories/components/image/examples/image-crop.component.ts new file mode 100644 index 00000000..7d728235 --- /dev/null +++ b/src/stories/components/image/examples/image-crop.component.ts @@ -0,0 +1,51 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { StoryObj } from '@storybook/angular'; +import { ExtraImageComponent } from '../../../../lib/components/image/image.component'; + +const SRC = 'assets/images/avatar/avatar.png'; + +const template = ` +
+ +
+`; + +@Component({ + selector: 'app-image-crop', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraImageComponent], + template +}) +export class ImageCropComponent { + readonly src = SRC; +} + +export const Crop: StoryObj = { + name: 'Crop', + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: + '`imageClass` задаёт размер и обрезку самого ``: `h-40 w-60 object-cover` даёт 240 × 160 с обрезкой. Атрибут `height` здесь не фиксирует высоту — её перекрывает глобальный `img { height: auto }` (Tailwind preflight).' + }, + source: { + language: 'html', + type: 'code', + code: `` + } + } + } +}; diff --git a/src/stories/components/image/examples/image-frame.component.ts b/src/stories/components/image/examples/image-frame.component.ts new file mode 100644 index 00000000..d009a507 --- /dev/null +++ b/src/stories/components/image/examples/image-frame.component.ts @@ -0,0 +1,53 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { StoryObj } from '@storybook/angular'; +import { ExtraImageComponent } from '../../../../lib/components/image/image.component'; + +const SRC = 'assets/images/avatar/avatar.png'; + +const template = ` +
+ +
+`; + +@Component({ + selector: 'app-image-frame', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraImageComponent], + template +}) +export class ImageFrameComponent { + readonly src = SRC; +} + +export const Frame: StoryObj = { + name: 'Frame', + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: + '`styleClass` применяется к корневому ``: рамка, фон и внутренние отступы вокруг изображения. Для рамки и padding корню нужен `inline-block` — у inline-элемента с блочным `` граница рисуется полосой.' + }, + source: { + language: 'html', + type: 'code', + code: `` + } + } + } +}; diff --git a/src/stories/components/image/examples/image-preview.component.ts b/src/stories/components/image/examples/image-preview.component.ts new file mode 100644 index 00000000..c56a45d8 --- /dev/null +++ b/src/stories/components/image/examples/image-preview.component.ts @@ -0,0 +1,56 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { StoryObj } from '@storybook/angular'; +import { ExtraImageTemplateDirective } from '../../../../lib/components/image/image-template.directive'; +import { ExtraImageComponent } from '../../../../lib/components/image/image.component'; + +const SRC = 'assets/images/avatar/avatar.png'; + +const template = ` +
+ + + + + + + +
+`; + +@Component({ + selector: 'app-image-preview', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraImageComponent, ExtraImageTemplateDirective], + template +}) +export class ImagePreviewComponent { + readonly src = SRC; +} + +export const Preview: StoryObj = { + name: 'Preview', + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: + '`[preview]="true"` включает предпросмотр: по клику открывается маска и тулбар с зумом, поворотом влево/вправо и закрытием. Иконки заменяются шаблонами `extraImageTemplate`, закрыть можно кнопкой или клавишей Escape.' + }, + source: { + language: 'html', + type: 'code', + code: ` + + + + + +` + } + } + } +}; diff --git a/src/stories/components/image/examples/image-width.component.ts b/src/stories/components/image/examples/image-width.component.ts new file mode 100644 index 00000000..c17c9fc1 --- /dev/null +++ b/src/stories/components/image/examples/image-width.component.ts @@ -0,0 +1,43 @@ +import { ChangeDetectionStrategy, Component } from '@angular/core'; +import { StoryObj } from '@storybook/angular'; +import { ExtraImageComponent } from '../../../../lib/components/image/image.component'; + +const SRC = 'assets/images/avatar/avatar.png'; + +const template = ` +
+ +
+`; + +@Component({ + selector: 'app-image-width', + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ExtraImageComponent], + template +}) +export class ImageWidthComponent { + readonly src = SRC; +} + +export const Width: StoryObj = { + name: 'Width', + render: () => ({ + template: `` + }), + parameters: { + controls: { disable: true }, + docs: { + description: { + story: + '`width` — строка, как HTML-атрибут: задаёт ширину изображения, высота остаётся пропорциональной. Без `width` изображение рисуется в натуральную величину — как в Default.' + }, + source: { + language: 'html', + type: 'code', + code: `` + } + } + } +}; diff --git a/src/stories/components/image/image.stories.ts b/src/stories/components/image/image.stories.ts new file mode 100644 index 00000000..b8cd2ab7 --- /dev/null +++ b/src/stories/components/image/image.stories.ts @@ -0,0 +1,162 @@ +import { Meta, moduleMetadata, StoryObj } from '@storybook/angular'; +import { ExtraImageComponent } from '../../../lib/components/image/image.component'; +import { ImageFrameComponent, Frame } from './examples/image-frame.component'; +import { ImagePreviewComponent, Preview } from './examples/image-preview.component'; +import { ImageWidthComponent, Width } from './examples/image-width.component'; +import { ImageCropComponent, Crop } from './examples/image-crop.component'; + +type ImageArgs = Partial; + +const SRC = 'assets/images/avatar/avatar.png'; + +const meta: Meta = { + title: 'Components/Media/Image', + component: ExtraImageComponent, + tags: ['autodocs'], + decorators: [ + moduleMetadata({ + imports: [ + ExtraImageComponent, + ImagePreviewComponent, + ImageWidthComponent, + ImageCropComponent, + ImageFrameComponent + ] + }) + ], + parameters: { + designTokens: { prefix: '--p-image' }, + docs: { + description: { + component: `Обёртка над PrimeNG \`p-image\`: изображение с необязательным предпросмотром — маска, тулбар, зум и поворот. + +Иконки панели предпросмотра заменяются шаблонами \`extraImageTemplate\`. + +\`alt\` обязателен по смыслу: без него изображение озвучивается как декоративное. + +\`\`\`typescript +import { ExtraImageComponent } from '@cdek-it/angular-ui-kit/components/image'; +\`\`\`` + } + } + }, + argTypes: { + src: { + control: 'text', + description: 'URL изображения (обязательный)', + table: { + category: 'Props', + defaultValue: { summary: "''" }, + type: { summary: 'string' } + } + }, + alt: { + control: 'text', + description: 'Альтернативный текст для скринридеров', + table: { + category: 'Props', + defaultValue: { summary: "''" }, + type: { summary: 'string' } + } + }, + width: { + control: 'text', + description: 'Ширина строкой, как HTML-атрибут; без значения — натуральная', + table: { + category: 'Props', + type: { summary: 'string | undefined' } + } + }, + height: { + control: 'text', + description: 'Высота строкой, как HTML-атрибут; без значения — натуральная', + table: { + category: 'Props', + type: { summary: 'string | undefined' } + } + }, + preview: { + control: 'boolean', + description: 'Предпросмотр по клику: маска, тулбар, зум и поворот', + table: { + category: 'Props', + defaultValue: { summary: 'false' }, + type: { summary: 'boolean' } + } + }, + imageClass: { + control: 'text', + description: 'CSS-класс самого img: обрезка, фильтры, размеры', + table: { + category: 'Props', + type: { summary: 'string | undefined' } + } + }, + styleClass: { + control: 'text', + description: 'CSS-класс корневого span: рамка, фон, отступы; для border/padding нужен inline-block', + table: { + category: 'Props', + type: { summary: 'string | undefined' } + } + } + }, + args: { + src: SRC, + alt: 'Аватар', + preview: false + } +}; + +export default meta; +type Story = StoryObj; + +/** Значения Controls могут содержать кавычки: в HTML-snippet их нужно экранировать. */ +const escapeAttribute = (value: string): string => + value.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<'); + +const sourceFromArgs = (args: ImageArgs): string => { + const attrs = [`src="${escapeAttribute(args.src ?? '')}"`, `alt="${escapeAttribute(args.alt ?? '')}"`]; + + if (args.width) attrs.push(`width="${escapeAttribute(args.width)}"`); + if (args.height) attrs.push(`height="${escapeAttribute(args.height)}"`); + if (args.preview) attrs.push('[preview]="true"'); + if (args.imageClass) attrs.push(`imageClass="${escapeAttribute(args.imageClass)}"`); + if (args.styleClass) attrs.push(`styleClass="${escapeAttribute(args.styleClass)}"`); + + return ``; +}; + +/** Живой шаблон работает через биндинги: кавычки в значениях Controls не ломают JIT. */ +const TEMPLATE = ``; + +export const Default: Story = { + name: 'Default', + render: (args) => ({ + props: args, + template: TEMPLATE + }), + parameters: { + docs: { + description: { + story: + 'Базовое изображение: `src` обязателен, `alt` описывает содержимое. Размеры, классы и предпросмотр меняются в Controls.' + }, + source: { + language: 'html', + type: 'code', + transform: (_code: string, context: { args: ImageArgs }) => sourceFromArgs(context.args ?? {}) + } + } + } +}; + +export { Preview, Width, Crop, Frame };