# CTT Web Components

A modern web components library for CTT built with Lit and TypeScript. This library provides reusable UI components following the CTT design system, with comprehensive documentation and testing via Storybook.

## 🚀 Features

- **Modern Web Components**: Built with Lit framework for excellent performance and compatibility
- **TypeScript Support**: Full TypeScript support with type definitions
- **Design System**: Consistent design tokens and styling
- **Storybook Integration**: Interactive component documentation and testing
- **Accessibility**: Built with accessibility best practices
- **Testing**: Comprehensive test coverage with Vitest and Playwright

## 🌐 Live Documentation

**📚 Storybook**: https://ctt-design-system-storybook.netlify.app

Browse and interact with all components, view documentation, and test different states in our live Storybook deployment.

## 📦 Installation

```bash
npm install ctt-web-components
```

## 🤖 AI Assistants (MCP)

The published package ships a [Model Context Protocol](https://modelcontextprotocol.io) server that lets AI coding assistants — GitHub Copilot, Cursor, Claude Desktop, Claude Code — answer questions about CTT components and generate correct, target-aware code (typed React wrappers, custom elements, or plain HTML) for your project.

Wire it into your client with a single command: `npx --package ctt-web-components ctt-mcp-server`.

<details>
<summary><strong>GitHub Copilot (VS Code)</strong> — add to <code>settings.json</code></summary>

```json
{
  "github.copilot.chat.agent.mcpServers": [
    {
      "name": "ctt-design-system",
      "command": "npx",
      "args": ["--package", "ctt-web-components", "ctt-mcp-server"]
    }
  ]
}
```

</details>

<details>
<summary><strong>Cursor</strong> — Settings → MCP → Add MCP Server</summary>

```json
{
  "name": "CTT Design System",
  "type": "command",
  "command": "npx --package ctt-web-components ctt-mcp-server"
}
```

</details>

<details>
<summary><strong>Claude Desktop</strong> — add to <code>claude_desktop_config.json</code></summary>

```json
{
  "mcpServers": {
    "ctt-design-system": {
      "command": "npx",
      "args": ["--package", "ctt-web-components", "ctt-mcp-server"]
    }
  }
}
```

</details>

Once wired, ask your agent *"List all CTT components"* or *"Show me the CTT Button API"* and it will query the server directly. Target detection is automatic when the agent passes a workspace file path.

- **Setup & contributor docs:** [`mcp-server/QUICKSTART.md`](./mcp-server/QUICKSTART.md)
- **Consumer guide & troubleshooting:** [`mcp-server/CONSUMER_GUIDE.md`](./mcp-server/CONSUMER_GUIDE.md)
- **End-to-end example:** [`mcp-server/USAGE_STORY.md`](./mcp-server/USAGE_STORY.md)

## 🛠️ Development

### Prerequisites

- Node.js (v18 or higher)
- npm

### Getting Started

1. **Clone the repository**

   ```bash
   git clone https://github.com/ctt/pt.dni.design-system.git
   cd pt.dni.design-system
   ```

2. **Install dependencies**

   The project requires installing dependencies for both the core library and the Storybook environment.

   ```bash
   # Install core dependencies
   npm install

   # Install Storybook dependencies
   cd src/storybook
   npm install
   cd ../..
   ```

3. **Start development server**

   ```bash
   npm run dev
   ```

4. **Start Storybook**
   ```bash
   npm run storybook
   ```

### Available Scripts

| Command                    | Description                        |
| -------------------------- | ---------------------------------- |
| `npm run dev`              | Start development server           |
| `npm run build`            | Build for production               |
| `npm run preview`          | Preview production build           |
| `npm run storybook`        | Start Storybook development server |
| `npm run build-storybook`  | Build static Storybook site        |
| `npm run test`             | Run tests                          |
| `npm run test:watch`       | Run tests in watch mode            |
| `npm run create-component` | Create a new component             |

## 🧩 Components

The library includes the following components:

### Form Controls

- **Button** - Interactive button component with various styles
- **Checkbox** - Checkbox input with label support
- **DropdownInput** - Dropdown selection input
- **InputText** - Text input field with validation
- **InputMoney** - Currency input field
- **InputCounter** - Numeric counter input
- **IbanInput** - IBAN input with validation
- **PhoneInput** - Phone number input
- **RadioButton** - Radio button input with grouping
- **TextareaInput** - Multi-line text input
- **ToggleSwitch** - Toggle switch component
- **ZipCodeInput** - Zip Code input
- **Chip** - Compact elements that represent an input, attribute, or action
- **Tag** - Label for categorization

### Navigation

- **Breadcrumbs** - Navigation breadcrumb component
- **Pagination** - Pagination component for content navigation
- **SidePanel** - Side navigation panel

### Feedback

- **ToasterAlert** - Toast notification component
- **Tooltip** - Tooltip component for additional information
- **Loading** - Loading state indicators
- **Modal** - Dialogs and modal windows

### Data Display

- **Table** - Data table with various features
- **Accordion** - Expandable content sections
- **Card** - Container for content
- **Icon** - Icon component

### Design System

- **Colors** - Design system color tokens
- **Typography** - Typography styles and tokens
- **Utils** - Utility classes and mixins

## 📚 Usage

### Basic Usage

```html
<!-- Import the component -->
<script type="module" src="path/to/ctt-web-components.js"></script>

<!-- Use the component -->
<ctt-button variant="primary">Click me</ctt-button>
```

### With TypeScript

```typescript
import { CttButton } from 'ctt-web-components';

// Use in your application
const button = document.createElement('ctt-button');
button.variant = 'primary';
button.textContent = 'Click me';
document.body.appendChild(button);
```

### Component Properties

Each component comes with comprehensive properties and events. Check the individual component documentation in Storybook for detailed usage examples.

- **Storybook:** https://storybook.js.org/
- **Vitest:** https://vitest.dev/
- **Playwright:** https://playwright.dev/
- **JSDoc:** https://jsdoc.app/

## 🎨 Design System

The components follow the CTT design system with:

- **Color Tokens**: Consistent color palette across all components
- **Typography**: Standardized font sizes, weights, and line heights
- **Spacing**: Consistent spacing values
- **Layout**: Grid and flexbox utilities

### Design Tokens

```css
/* Example design tokens */
:root {
  --ctt-color-primary: #007bff;
  --ctt-color-secondary: #6c757d;
  --ctt-spacing-xs: 0.25rem;
  --ctt-spacing-sm: 0.5rem;
  --ctt-font-size-base: 1rem;
}
```

## 🔧 Creating New Components

Use the built-in component generator to create new components:

```bash
npm run create-component MyNewComponent
```

This will generate:

- Component TypeScript implementation
- CSS file with design tokens
- Storybook stories
- Unit tests
- README documentation

## 🧪 Testing

### Running Tests

```bash
# Run all tests - script already prepared
npm run test

# Run tests in watch mode
npm run test:watch
```

### Linting & Formatting

The project uses ESLint for code quality and Prettier for code formatting.

```bash
# Check for linting errors
npm run lint

# Fix auto-fixable linting errors
npm run lint:fix

# Format code with Prettier
npm run format
```

### Accessibility Testing

Accessibility is a core principle of the CTT Design System. We are committed to ensuring our components are usable by everyone, regardless of their abilities or the devices they use.

**Tools & Standards:**
We utilize **Playwright** combined with **axe-core** to perform automated accessibility audits. Our tests are configured to strictly enforce **WCAG 2.1 Level A and AA** standards.

**What we test:**
The `npm run test:a11y` command executes a suite that:
1.  **Scans Storybook Stories**: Navigates to the default story of each component.
2.  **Validates Compliance**: Checks against rulesets for:
    -   ❌ Color Contrast ratios
    -   ⌨️ Keyboard navigation and focus management
    -   🏷️ ARIA attributes and labels
    -   🏗️ Semantic HTML structure
3.  **Reports Violations**: Fails the build if any violations are detected, ensuring no accessibility regressions are merged.

**Why verify?**
-   **Legal Compliance**: Meets EU and national accessibility directives.
-   **Inclusivity**: Ensures a seamless experience for users relying on screen readers and assistive technologies.
-   **Quality Code**: Accessible code is often cleaner, more semantic, and better structured.

```bash
# Run accessibility tests
npm run test:a11y
```

### Test Structure

Tests and Stories are located in `src/storybook/stories/[ComponentName]/` directories, separate from the component implementation in `src/components/`:

- `*.test.ts` - Unit and interaction tests
- `*.stories.ts` - Storybook stories (also serve as integration tests)

### Browser Testing

The project uses Playwright for browser testing to ensure components work correctly across different browsers.

## 📖 Documentation

### Storybook

Access comprehensive component documentation at:

```bash
npm run storybook
# Opens at http://localhost:6006
```

### Component READMEs

Each component has its own README with:

- Usage examples
- API documentation
- Design considerations
- Accessibility notes

## 🚀 Build and Deployment

### Production Build

```bash
npm run build
```

This creates optimized bundles in the `dist/` directory.

### MCP Server Build

```bash
npm --prefix mcp-server run build
```

Bundles the MCP server into `mcp-server/dist/index.js`. This is included automatically during publish.

### Build Everything Locally

To replicate exactly what CI does before publishing:

```bash
# 1. Install all dependencies
npm ci
npm --prefix mcp-server ci

# 2. Build the design system library
npm run build

# 3. Build the MCP server
npm --prefix mcp-server run build
```

### Storybook Build

```bash
npm run build-storybook
```

Creates a static Storybook site in `storybook-static/`.

---

## 🚢 Releasing a New Version

Both the design system library (`ctt-web-components`) and the MCP server are published together as a **single npm package**. You only need to bump the version once.

### Step-by-step release guide

**1. Make sure you are on the `main` branch and your working tree is clean.**

```bash
git checkout main
git pull origin main
```

**2. Bump the version in `package.json`.**

Open `package.json` at the root and increment the `"version"` field following [semver](https://semver.org):

| Change type | Example | When to use |
|---|---|---|
| Patch `x.x.Y` | `3.3.6` → `3.3.7` | Bug fixes, no API changes |
| Minor `x.Y.0` | `3.3.6` → `3.4.0` | New components or features, backwards-compatible |
| Major `X.0.0` | `3.3.6` → `4.0.0` | Breaking changes |

```json
// package.json
{
  "version": "3.3.7"
}
```

**3. Build everything locally to verify there are no errors.**

```bash
npm ci
npm --prefix mcp-server ci
npm run build
npm --prefix mcp-server run build
```

Fix any build errors before continuing.

**4. Commit your changes.**

The publish CI workflow triggers on pushes to `main` **only when the commit message contains `[publish]`**.

```bash
git add package.json
git commit -m "chore: release v3.3.7 [publish]"
```

If you have other file changes included in this release, stage and commit them in the same commit or before it.

**5. Push to `main`.**

```bash
git push origin main
```

**6. CI takes over.**

The `npm-publish.yml` workflow will:
1. Install root dependencies (`npm ci`)
2. Install MCP server dependencies (`npm --prefix mcp-server ci`)
3. Build the library (`npm run build`)
4. Build the MCP server (`npm --prefix mcp-server run build`)
5. Run the MCP server tests
6. Publish to npm (`npm publish`)

Monitor the run at: `https://github.com/ctt/pt.dni.design-system/actions`

**7. Verify the release.**

```bash
npm view ctt-web-components version
# Should print the version you just published
```

### Trigger publish without a version bump

If you need to re-trigger publish (e.g. a flaky CI run) without changing the version, add `[publish]` anywhere in any commit message and push to `main`. Note: npm will reject a publish if the version already exists in the registry — you must bump the version in that case.

---

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-component`
3. Make your changes
4. Add tests for your changes
5. Run tests: `npm run test`
6. Build and test Storybook: `npm run build-storybook`
7. Commit your changes: `git commit -m 'Add new component'`
8. Push to the branch: `git push origin feature/new-component`
9. Submit a pull request

### Code Style

- Follow TypeScript best practices
- Use consistent naming conventions
- Add JSDoc comments for public APIs
- Ensure accessibility compliance
- Write comprehensive tests

## 📋 Browser Support

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)

## 📄 License

[Add your license information here]

## 🆘 Support

For questions and support:

- [Create an issue](https://magic-ticket-forge.lovable.app/)
- [Documentation](https://ctt-design-system-storybook.netlify.app/)
- [Contact the team](mailto:rafael.cabrita@integer.pt)

## 🗺️ Roadmap

- [ ] Additional form components
- [ ] Data visualization components
- [ ] Advanced layout components
- [ ] Theme customization system
- [ ] Performance optimizations

---

Built with ❤️ by the CTT team using [Lit](https://lit.dev/) and [Storybook](https://storybook.js.org/).
