Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions src/lib/components/checkbox/checkbox.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { Component, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Checkbox, CheckboxChangeEvent } from 'primeng/checkbox';

export type CheckboxSize = 'small' | 'base' | 'large';
export type CheckboxVariant = 'outlined' | 'filled';

@Component({
selector: 'checkbox',
standalone: true,
imports: [Checkbox],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxComponent),
multi: true,
},
],
template: `
<p-checkbox
[value]="value"
[binary]="binary"
[(ngModel)]="modelValue"
[disabled]="disabled"
[readonly]="readonly"
[indeterminate]="indeterminate"
[styleClass]="indeterminate ? 'p-checkbox-indeterminate' : ''"
[invalid]="invalid"
[size]="primeSize"
[variant]="primeVariant"
[checkboxIcon]="checkboxIcon"
[ariaLabel]="ariaLabel"
[ariaLabelledBy]="ariaLabelledBy"
[tabindex]="tabindex"
[inputId]="inputId"
[trueValue]="trueValue"
[falseValue]="falseValue"
[autofocus]="autofocus"
(onChange)="onChangeHandler($event)"
(onFocus)="onFocus.emit($event)"
(onBlur)="onBlur.emit($event)"
></p-checkbox>
`,
})
export class CheckboxComponent implements ControlValueAccessor {
@Input() value: any = null;
@Input() binary = false;
@Input() disabled = false;
@Input() readonly = false;
@Input() indeterminate = false;
@Input() invalid = false;
@Input() size: CheckboxSize = 'base';
@Input() variant: CheckboxVariant = 'outlined';
@Input() checkboxIcon: string | undefined = undefined;
@Input() ariaLabel: string | undefined = undefined;
@Input() ariaLabelledBy: string | undefined = undefined;
@Input() tabindex: number | undefined = undefined;
@Input() inputId: string | undefined = undefined;
@Input() trueValue: any = true;
@Input() falseValue: any = false;
@Input() autofocus = false;

@Output() onChange = new EventEmitter<CheckboxChangeEvent>();
@Output() onFocus = new EventEmitter<Event>();
@Output() onBlur = new EventEmitter<Event>();

modelValue: any = false;

private _onChange: (value: any) => void = () => {};
private _onTouched: () => void = () => {};

// Геттеры — маппинг в PrimeNG API
get primeSize(): 'small' | 'large' | undefined {
if (this.size === 'small') return 'small';
if (this.size === 'large') return 'large';
return undefined;
}

get primeVariant(): 'filled' | 'outlined' | undefined {
if (this.variant === 'filled') return 'filled';
return undefined;
}

onChangeHandler(event: CheckboxChangeEvent): void {
this._onChange(event.checked);
this._onTouched();
this.onChange.emit(event);
}

// ControlValueAccessor
writeValue(value: any): void {
this.modelValue = value;
}

registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}

registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}

setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
}
5 changes: 5 additions & 0 deletions src/prime-preset/map-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { AuraBaseDesignTokens } from '@primeuix/themes/aura/base';
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 { tooltipCss } from './tokens/components/tooltip';

const presetTokens: Preset<AuraBaseDesignTokens> = {
Expand All @@ -16,6 +17,10 @@ const presetTokens: Preset<AuraBaseDesignTokens> = {
...(tokens.components.avatar as unknown as ComponentsDesignTokens['avatar']),
css: avatarCss,
},
checkbox: {
...(tokens.components.checkbox as unknown as ComponentsDesignTokens['checkbox']),
css: checkboxCss,
},
button: {
...(tokens.components.button as unknown as ComponentsDesignTokens['button']),
css: buttonCss,
Expand Down
74 changes: 74 additions & 0 deletions src/prime-preset/tokens/components/checkbox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
export const checkboxCss = ({ dt }: { dt: (token: string) => string }): string => `
/* ─── Label типографика ─── */
.checkbox-label {
display: flex;
align-items: center;
color: ${dt('text.color')};
font-family: ${dt('fonts.fontFamily.base')};
font-size: ${dt('fonts.fontSize.300')};
font-weight: ${dt('fonts.fontWeight.regular')};
line-height: normal;
cursor: pointer;
}

.checkbox-label--hover {
color: ${dt('text.primaryColor')};
}

.checkbox-label--disabled {
color: ${dt('text.mutedColor')};
cursor: default;
}

.checkbox-caption {
color: ${dt('text.secondaryColor')};
font-family: ${dt('fonts.fontFamily.heading')};
font-size: ${dt('fonts.fontSize.200')};
font-weight: ${dt('fonts.fontWeight.regular')};
line-height: normal;
}

.checkbox-caption--hover {
color: ${dt('text.primaryColor')};
}

.checkbox-caption--disabled {
color: ${dt('text.disabledColor')};
}

/* Переопределение ширины border для checkbox */
.p-checkbox-box {
border-width: ${dt('checkbox.root.extend.borderWidth')};
}

/* Состояние indeterminate - фон и border как у checked */
.p-checkbox-indeterminate .p-checkbox-box {
background: ${dt('checkbox.root.checkedBackground')};
border-color: ${dt('checkbox.root.checkedBorderColor')};
}

/* Состояние indeterminate - цвет иконки как у checked */
.p-checkbox-indeterminate .p-checkbox-icon {
color: ${dt('checkbox.icon.checkedColor')};
}

/* Состояние hover для indeterminate */
.p-checkbox-indeterminate:not(.p-disabled):has(.p-checkbox-input:hover) .p-checkbox-box {
background: ${dt('checkbox.root.checkedHoverBackground')};
border-color: ${dt('checkbox.root.checkedHoverBorderColor')};
}

/* Focus ring с зеленым цветом для валидных состояний */
.p-checkbox:not(.p-disabled):not(.p-checkbox-checked):not(.p-invalid):has(.p-checkbox-input:focus-visible) .p-checkbox-box,
.p-checkbox-checked:not(.p-disabled):not(.p-invalid):has(.p-checkbox-input:focus-visible) .p-checkbox-box,
.p-checkbox-indeterminate:not(.p-disabled):not(.p-invalid):has(.p-checkbox-input:focus-visible) .p-checkbox-box {
box-shadow: 0 0 0 ${dt('checkbox.root.focusRing.focusRing')} ${dt('focusRing.extend.success')};
}

/* Focus ring с красным цветом для состояний с ошибкой */
.p-checkbox.p-invalid .p-checkbox-box,
.p-checkbox-checked.p-invalid .p-checkbox-box,
.p-checkbox-indeterminate.p-invalid .p-checkbox-box {
box-shadow: 0 0 0 ${dt('focusRing.width')} ${dt('focusRing.extend.invalid')};
}
`;
146 changes: 146 additions & 0 deletions src/stories/components/checkbox/checkbox.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { Meta, StoryObj, moduleMetadata } from '@storybook/angular';
import { CheckboxComponent } from '../../../lib/components/checkbox/checkbox.component';
import { FormsModule } from '@angular/forms';
import { CheckboxGroupComponent, Group } from './examples/checkbox-group.component';
import { CheckboxIndeterminateComponent, Indeterminate } from './examples/checkbox-indeterminate.component';
import { CheckboxDisabledComponent, Disabled } from './examples/checkbox-disabled.component';
import { CheckboxInvalidComponent, Invalid } from './examples/checkbox-invalid.component';
import { CheckboxLabelComponent, Label } from './examples/checkbox-label.component';
import { CheckboxCustomLabelComponent, CustomLabel } from './examples/checkbox-custom-label.component';

type CheckboxArgs = CheckboxComponent & { label?: string };

const meta: Meta<CheckboxArgs> = {
title: 'Components/Form/Checkbox',
component: CheckboxComponent,
tags: ['autodocs'],
decorators: [
moduleMetadata({
imports: [
CheckboxComponent,
FormsModule,
CheckboxGroupComponent,
CheckboxIndeterminateComponent,
CheckboxDisabledComponent,
CheckboxInvalidComponent,
CheckboxLabelComponent,
CheckboxCustomLabelComponent,
]
})
],
parameters: {
designTokens: { prefix: '--p-checkbox' },
docs: {
description: {
component: `Компонент для выбора одного или нескольких вариантов.`,
},
},
},
argTypes: {
// ── Props ────────────────────────────────────────────────
binary: { table: { disable: true } },
invalid: {
control: 'boolean',
description: 'Подсвечивает поле как невалидное',
table: {
category: 'Props',
defaultValue: { summary: 'false' },
type: { summary: 'boolean' },
},
},
disabled: {
control: 'boolean',
description: 'Отключает возможность взаимодействия',
table: {
category: 'Props',
defaultValue: { summary: 'false' },
type: { summary: 'boolean' },
},
},
indeterminate: {
control: 'boolean',
description: 'Устанавливает неопределенное состояние',
table: {
category: 'Props',
defaultValue: { summary: 'false' },
type: { summary: 'boolean' },
},
},
// Hidden props
size: { table: { disable: true } },
readonly: { table: { disable: true } },
checkboxIcon: { table: { disable: true } },
ariaLabel: { table: { disable: true } },
ariaLabelledBy: { table: { disable: true } },
tabindex: { table: { disable: true } },
inputId: { table: { disable: true } },
trueValue: { table: { disable: true } },
falseValue: { table: { disable: true } },
autofocus: { table: { disable: true } },
variant: { table: { disable: true } },
value: { table: { disable: true } },
label: { table: { disable: true } },

// ── Events ───────────────────────────────────────────────
onChange: {
control: false,
description: 'Событие изменения значения',
table: {
category: 'Events',
type: { summary: 'EventEmitter<CheckboxChangeEvent>' },
},
},
onFocus: {
control: false,
description: 'Событие фокуса',
table: {
category: 'Events',
type: { summary: 'EventEmitter<Event>' },
},
},
onBlur: {
control: false,
description: 'Событие потери фокуса',
table: {
category: 'Events',
type: { summary: 'EventEmitter<Event>' },
},
},
},
args: {
binary: true,
disabled: false,
invalid: false,
indeterminate: false,
},
};

export default meta;
type Story = StoryObj<CheckboxArgs>;

// ── Default ──────────────────────────────────────────────────────────────────
export const Default: Story = {
name: 'Default',
render: (args) => {
const parts: string[] = [];
if (args.binary) parts.push(`[binary]="true"`);
if (args.disabled) parts.push(`[disabled]="true"`);
if (args.invalid) parts.push(`[invalid]="true"`);
if (args.indeterminate) parts.push(`[indeterminate]="true"`);
parts.push(`[(ngModel)]="checked"`);

const template = `<checkbox\n ${parts.join('\n ')}\n></checkbox>`;

return { props: { ...args, checked: false }, template };
},
parameters: {
docs: {
description: {
story: 'Базовый пример компонента. Используйте Controls для интерактивного изменения пропсов.',
},
},
},
};

// ── Re-exports from example components ────────────────────────────────────
export { Invalid, Disabled, Indeterminate, Group, Label, CustomLabel };
Loading
Loading