# Copper UI

Modern React UI components library with TypeScript support, built on top of Ant Design.

## Installation

```bash
npm install copper-ui
```

## Peer Dependencies

Make sure you have these peer dependencies installed:

```bash
npm install react react-dom @types/node class-variance-authority clsx nuqs
```

## Usage

Import the package CSS once in the consuming app entrypoint:

```tsx
import 'copper-ui/css';
```

### Table Component

```tsx
import { Table, useTableStates } from 'copper-ui';

function MyComponent() {
  const tableStates = useTableStates();

  return (
    <Table
      data={yourData}
      columns={yourColumns}
      {...tableStates}
      rowClassName={(record) =>
        record.isExpired ? "bg-red-10" : undefined
      }
    />
  );
}
```

### App Shell / Workspace Navigation

Use the high-level workspace shell path for Clara-like and Inside-like consumers:

```tsx
import {
  AppShellLayout,
  AppShellProvider,
  SidebarInset,
  WorkspaceNavigationSidebar,
  WorkspaceSectionShell,
  type NavigationItem,
} from 'copper-ui';
import 'copper-ui/css';

const items: NavigationItem[] = [
  {
    id: 'committees',
    label: 'Committees',
    href: '/committees',
    match: 'prefix',
    badge: { value: 5, tone: 'attention', label: '5 urgent committee items' },
    children: [{ id: 'committees-active', label: 'Active committee', href: '/committees/active' }],
  },
];

export function WorkspaceShell() {
  return (
    <AppShellProvider sidebarWidth="260px">
      <AppShellLayout
        sidebar={
          <WorkspaceNavigationSidebar
            items={items}
            pathname="/committees/active"
            defaultExpandedItemIds={['committees']}
            renderLink={({ href, children }) => <a href={href}>{children}</a>}
            logo={{ brandName: 'Workspace' }}
            support={{ label: 'Support' }}
            user={{ name: 'User', avatar: <span>U</span> }}
          />
        }
      >
        <SidebarInset>
          <WorkspaceSectionShell
            header={{ id: 'committees', label: 'Committees', href: '/committees' }}
            items={[]}
            pathname="/committees/active"
            renderLink={({ href, children }) => <a href={href}>{children}</a>}
          />
        </SidebarInset>
      </AppShellLayout>
    </AppShellProvider>
  );
}
```

Consumers pass data, route adapters, visibility decisions, logo/support/user config, badges, and sidebar state policy. Use `defaultExpandedItemIds` for uncontrolled initial expansion. Use `expandedItemIds` together with `onExpandedItemIdsChange` only when the app owns or persists expanded state.

`NavigationItem.badge` accepts either a React node or `{ value, tone, label, ariaLabel, hideWhenZero }`. Supported tones are `neutral`, `attention`, `danger`, `warning`, and `success`; zero and empty values are hidden by default.

`copper-ui` owns shell geometry, sidebar row layout, nested spacing, badge placement, collapsed behavior, chrome spacing, and package CSS. The collapsed sidebar popover renders nested branches recursively, preserves badges, indents levels up to depth 10, keeps branch rows non-link rows, and renders leaf rows through `renderLink`.

Use `AppShellProvider.sidebarWidth` when an app needs a wider sidebar for longer labels and badges. Keep text truncation and right/left row spacing package-owned instead of adding consumer CSS overrides.

Do not style package internals, depend on `data-cu-*`, or use row/branch render hooks for standard sidebar rows. The low-level `NavigationSidebar` API has been removed; use `WorkspaceNavigationSidebar`.

### Conditional Rendering Component

```tsx
import { If } from 'copper-ui';

function MyComponent() {
  return (
    <If condition={someCondition}>
      <div>This will render only if condition is true</div>
    </If>
  );
}
```

## Components

- **Table** - Advanced data table with sorting, filtering, and pagination
- **FilterTags** - Filter tags for table component
- **If** - Conditional rendering component
- **useTableStates** - Hook for managing table state

## Development

```bash
# Install dependencies
npm install

# Start development server
npm run dev

# Build library
npm run build

# Run Storybook
npm run storybook
```

## CI/CD и Релизы

### Общий процесс
```
feature branch → main (PR + review) → auto release → manual Storybook deploy
```

### Conventional Commits

Проект использует **Conventional Commits** для автоматического управления версиями.

#### Формат коммитов
```
<type>[optional scope]: <description>
```

#### Типы коммитов с версионированием
- `feat:` - новая функциональность (**minor** версия: 1.2.3 → 1.3.0)
- `fix:` - исправление багов (**patch** версия: 1.2.3 → 1.2.4)
- `feat!:` - breaking changes (**major** версия: 1.2.3 → 2.0.0)
- `fix!:` - breaking fix (**major** версия: 1.2.3 → 2.0.0)

#### Типы коммитов без версионирования
- `docs:` - документация
- `style:` - форматирование кода
- `refactor:` - рефакторинг без изменения API
- `test:` - тесты
- `build:` - конфигурация сборки
- `ci:` - настройки CI/CD
- `chore:` - прочие изменения
- `perf:` - оптимизации

#### Примеры коммитов
```bash
# Версионирование (автоматическое)
git commit -m "feat: add DatePicker component"
git commit -m "fix: resolve Table sorting issue"
git commit -m "feat!: change Table API structure"

# Без версионирования
git commit -m "docs: update README"
git commit -m "refactor: optimize Table code"
git commit -m "test: add filter tests"
```

### Workflow разработки

#### 1. Создание feature ветки
```bash
git checkout -b feature/add-datepicker
```

#### 2. Разработка
- Внесите изменения
- Проверьте работу в Storybook
- Добавьте тесты при необходимости

#### 3. Коммит изменений
```bash
# Автоматически запустится линтинг и валидация формата Conventional Commits
git commit -m "feat: add DatePicker component"
```

#### 4. Создание Pull Request
```bash
git push origin feature/add-datepicker
# Создайте PR в main через GitHub interface
```

#### 5. Merge в main
```bash
# После ревью и аппрува PR будет смержен в main
# Автоматически:
# - Проанализируются коммиты
# - Определится новая версия
# - Опубликуется в NPM
# - Создастся GitHub Release
```

### CI/CD Pipeline

#### Build workflow (PR проверка)
**Триггер:** Pull Request в `main` или `test`
**Что делает:**
- Линтинг кода
- Сборка библиотеки
- Сборка Storybook
- Проверка что все работает

#### Publish workflow (автоматический релиз)
**Триггер:** Push в ветку `main`
**Алгоритм:**
1. Анализ коммитов с последнего git tag
2. Определение новой версии по Conventional Commits
3. Линтинг и сборка библиотеки
4. Обновление `package.json` с новой версией
5. Создание git tag `v{version}`
6. Публикация в NPM с тегом `latest`
7. Создание GitHub Release с changelog

**Результат:**
- Автоматический NPM релиз
- Git tag с версией
- GitHub Release с описанием изменений
- Обновленный CHANGELOG.md

#### Storybook deploy (ручной)
**Триггер:** Ручной запуск через GitHub Actions
**Параметры:**
- **Branch name**: любая ветка (main, develop, feature/name)
- **Environment**: test или staging

**Как запустить:**
1. Перейти в **Actions** → **Deploy Storybook**
2. Нажать **Run workflow**
3. Ввести название ветки
4. Выбрать окружение

### Pre-commit хуки

При каждом коммите автоматически выполняются:
1. **ESLint проверка** - код должен соответствовать стандартам (с автофиксом)
2. **Валидация Conventional Commits** - проверка формата коммита

Если есть ошибки линтинга или неверный формат коммита, коммит будет отклонён.

### Что НЕ делать

1. **Не меняйте версию в package.json вручную** - это делает автоматический workflow
2. **Не создавайте git теги вручную** - это делает CI/CD
3. **Не используйте старые префиксы** (`patch:`, `minor:`, `major:`)
4. **Не пушьте в main напрямую** - только через PR

### Troubleshooting

#### Релиз не создался
- Проверьте формат коммитов (Conventional Commits)
- Убедитесь, что есть коммиты с `feat:` или `fix:`
- Проверьте, что CI/CD прошел без ошибок

#### Ошибка в pre-commit
```bash
# Автофикс линтинга
npm run lint -- --fix
```

#### Нужно изменить уже опубликованную версию
1. Создайте hotfix коммит с `fix:`
2. Сделайте PR в main
3. Релиз будет создан автоматически

## License

MIT
