npm package: @harlkwin/authflow-platform
Description: Modern, pluggable platform for building enterprise applications with AuthFlow. Pure composition layer with templates, layouts, and plugin system built on @harlkwin/authflow-react components.
Author: HarlKwin
Latest version: 1.2.0

# @harlkwin/authflow-platform

**Modern, pluggable platform for building enterprise applications with AuthFlow**

Build beautiful, production-ready applications with a comprehensive UI library, powerful plugin system, and seamless authentication. Transform your AuthFlow-powered app into an extensible platform where features can be added as plugins with just a few lines of code.

[![npm version](https://badge.fury.io/js/@harlkwin%2Fauthflow-platform.svg)](https://www.npmjs.com/package/@harlkwin/authflow-platform)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## ✨ Features

### 🎨 **Modern UI Library**
- 24+ pre-built, accessible components
- Glassmorphism and modern design aesthetic
- Full dark mode support (150+ dark mode classes)
- TypeScript-first with complete type definitions
- Tailwind CSS with design tokens

### 🔌 **Plugin System**
- Registry-based architecture
- Dynamic route registration
- Automatic sidebar integration
- Permission-based access control
- Lifecycle hooks (onLoad/onUnload)
- Dependency management
- Hot reload support

### 📐 **Page Templates**
- DashboardPageTemplate - Stats and widgets
- ListPageTemplate - Data tables and filtering
- DetailPageTemplate - Item detail views
- FormPageTemplate - Multi-step forms
- SettingsPageTemplate - Configuration pages

### 🎭 **Layout System**
- AppLayout - Minimal root layout
- DashboardLayout - Modern dashboard with glassmorphism
- ModernAdminLayout - Full admin panel
- Responsive and mobile-friendly
- Collapsible sidebars

### 🔐 **Authentication & Authorization**
- Built on @harlkwin/authflow-react
- Keycloak integration
- Role-based access control (RBAC)
- Permission-based routing
- Multi-tenant support

### 🌙 **Dark Mode**
- System-wide dark mode support
- `useDarkMode` hook with localStorage persistence
- Smooth transitions
- 94.4% component coverage

## 📦 Installation

```bash
npm install @harlkwin/authflow-platform @harlkwin/authflow-react
```

### Peer Dependencies

```bash
npm install react react-dom next @tanstack/react-query zustand clsx class-variance-authority
```

## 🚀 Quick Start

### Basic Setup

```tsx
// app/layout.tsx
'use client'
import { AuthFlowPlatform, AppLayout } from '@harlkwin/authflow-platform'
import { Inter } from 'next/font/google'
import './globals.css'

const inter = Inter({ subsets: ['latin'] })

export default function RootLayout({ children }) {
  return (
    <AppLayout fontClassName={inter.className}>
      <AuthFlowPlatform
        config={{
          apiUrl: process.env.NEXT_PUBLIC_API_URL!,
          keycloakUrl: process.env.NEXT_PUBLIC_KEYCLOAK_URL!,
        }}
      >
        {children}
      </AuthFlowPlatform>
    </AppLayout>
  )
}
```

### Using Page Templates

```tsx
// app/dashboard/page.tsx
'use client'
import { DashboardPageTemplate } from '@harlkwin/authflow-platform'

export default function DashboardPage() {
  return (
    <DashboardPageTemplate
      title="Analytics Dashboard"
      subtitle="Overview of your key metrics"
      stats={[
        { title: 'Total Users', value: '1,234', trend: { value: '+12%', direction: 'up' } },
        { title: 'Revenue', value: '$45,678', trend: { value: '+8%', direction: 'up' } },
        { title: 'Active Sessions', value: '89', trend: { value: '-3%', direction: 'down' } },
      ]}
      actions={[
        { label: 'Create Report', onClick: () => {}, variant: 'primary' },
        { label: 'Export Data', onClick: () => {}, variant: 'outline' },
      ]}
    >
      {/* Add your dashboard widgets here */}
    </DashboardPageTemplate>
  )
}
```

### Using UI Components

```tsx
'use client'
import { Button, Card, Badge, Modal } from '@harlkwin/authflow-platform'

export default function MyPage() {
  return (
    <div className="p-6">
      <Card
        title="Welcome"
        variant="glass"
        actions={[
          <Button variant="primary">Get Started</Button>
        ]}
      >
        <p>Build amazing applications with AuthFlow Platform</p>
      </Card>
    </div>
  )
}
```

## 🔌 Plugin System

### Creating a Plugin

```typescript
// plugins/workspace-plugin.tsx
import { AuthFlowPlugin } from '@harlkwin/authflow-platform'
import { WorkspaceIcon } from './icons'

function WorkspacePage() {
  return <div>Workspace Management</div>
}

function WorkspaceSettingsPage() {
  return <div>Workspace Settings</div>
}

export const workspacePlugin: AuthFlowPlugin = {
  // Required fields
  name: 'workspace-management',
  version: '1.0.0',

  // Optional: Require other plugins
  dependencies: ['another-plugin'],

  // Routes to register
  routes: [
    {
      path: '/workspace',
      component: WorkspacePage,
      permission: 'workspace:read',
    },
    {
      path: '/workspace/settings',
      component: WorkspaceSettingsPage,
      permission: 'workspace:write',
    },
  ],

  // Sidebar navigation items
  sidebarItems: [
    {
      label: 'Workspace',
      href: '/workspace',
      icon: <WorkspaceIcon className="h-5 w-5" />,
      permission: 'workspace:read',
    },
  ],

  // Permissions required by this plugin
  permissions: [
    'workspace:read',
    'workspace:write',
    'workspace:delete',
  ],

  // Lifecycle hooks
  onLoad: async () => {
    console.log('Workspace plugin loaded!')
    // Initialize plugin resources
    // - Connect to APIs
    // - Load configuration
    // - Set up event listeners
  },

  onUnload: async () => {
    console.log('Workspace plugin unloaded!')
    // Cleanup plugin resources
    // - Disconnect from APIs
    // - Remove event listeners
    // - Clear state
  },
}
```

### Registering Plugins

```tsx
import { AuthFlowPlatform } from '@harlkwin/authflow-platform'
import { workspacePlugin } from './plugins/workspace-plugin'
import { analyticsPlugin } from './plugins/analytics-plugin'

<AuthFlowPlatform
  config={config}
  plugins={[
    workspacePlugin,
    analyticsPlugin,
  ]}
>
  {children}
</AuthFlowPlatform>
```

### Using Plugin Hooks

```tsx
import {
  usePluginRegistry,
  usePluginRoutes,
  usePluginSidebarItems,
  usePluginPermissions,
  usePluginNavigation,
} from '@harlkwin/authflow-platform'

function MyComponent() {
  // Access plugin registry
  const { plugins, registerPlugin, unregisterPlugin } = usePluginRegistry()

  // Get all registered routes
  const routes = usePluginRoutes()

  // Get all sidebar items
  const sidebarItems = usePluginSidebarItems()

  // Get all permissions
  const permissions = usePluginPermissions()

  // Navigate to plugin routes
  const { navigateToPlugin } = usePluginNavigation()

  return (
    <div>
      <p>Loaded plugins: {plugins.length}</p>
      <button onClick={() => navigateToPlugin('workspace-management', '/workspace')}>
        Go to Workspace
      </button>
    </div>
  )
}
```

## 🎨 UI Components

### Buttons

```tsx
import { Button, ButtonGroup } from '@harlkwin/authflow-platform'

<Button variant="primary" size="md" leftIcon={<Icon />}>
  Primary Button
</Button>

<Button variant="gradient" size="lg">
  Gradient Button
</Button>

<Button variant="glass" size="sm">
  Glass Button
</Button>

<ButtonGroup>
  <Button variant="outline">Option 1</Button>
  <Button variant="outline">Option 2</Button>
  <Button variant="outline">Option 3</Button>
</ButtonGroup>
```

**Variants:** `primary`, `secondary`, `success`, `danger`, `warning`, `info`, `ghost`, `link`, `outline`, `gradient`, `glass`, `glass-light`, `glass-dark`

**Sizes:** `xs`, `sm`, `md`, `lg`, `xl`

### Cards

```tsx
import { Card, CardGrid, CardStat } from '@harlkwin/authflow-platform'

<Card
  variant="glass"
  title="Card Title"
  description="Card description"
  hoverable
  actions={[
    <Button variant="primary">Action</Button>
  ]}
>
  Card content goes here
</Card>

<CardStat
  title="Total Revenue"
  value="$45,678"
  change={{ value: "+12%", trend: "up" }}
  icon={<DollarIcon />}
/>

<CardGrid cols={3}>
  <Card>Card 1</Card>
  <Card>Card 2</Card>
  <Card>Card 3</Card>
</CardGrid>
```

### Form Components

```tsx
import { Input, Textarea, Select } from '@harlkwin/authflow-platform'

<Input
  label="Email"
  type="email"
  placeholder="Enter your email"
  error="Invalid email"
  leftIcon={<EmailIcon />}
/>

<Textarea
  label="Description"
  rows={4}
  placeholder="Enter description"
/>

<Select
  label="Country"
  options={[
    { value: 'us', label: 'United States' },
    { value: 'ca', label: 'Canada' },
  ]}
/>
```

### Badges & Tags

```tsx
import { Badge, Chip, Tag, StatusBadge } from '@harlkwin/authflow-platform'

<Badge variant="primary">New</Badge>
<Badge variant="success" size="lg">Active</Badge>

<Chip
  label="React"
  onRemove={() => {}}
  variant="gradient"
/>

<Tag variant="info">v1.0.0</Tag>

<StatusBadge status="active" />
<StatusBadge status="pending" />
<StatusBadge status="error" />
```

### Modals & Drawers

```tsx
import { Modal, ConfirmDialog, AlertDialog, Drawer } from '@harlkwin/authflow-platform'

<Modal
  isOpen={isOpen}
  onClose={() => setIsOpen(false)}
  title="Modal Title"
  size="lg"
>
  Modal content
</Modal>

<ConfirmDialog
  isOpen={isOpen}
  onClose={() => setIsOpen(false)}
  onConfirm={handleConfirm}
  title="Confirm Action"
  message="Are you sure you want to proceed?"
/>

<Drawer
  isOpen={isOpen}
  onClose={() => setIsOpen(false)}
  position="right"
  title="Drawer Title"
>
  Drawer content
</Drawer>
```

### Tables

```tsx
import { Table } from '@harlkwin/authflow-platform'

<Table
  data={users}
  columns={[
    { key: 'name', label: 'Name', sortable: true },
    { key: 'email', label: 'Email', sortable: true },
    { key: 'role', label: 'Role' },
    { key: 'status', label: 'Status', render: (value) => <Badge>{value}</Badge> },
  ]}
  keyField="id"
  selectable
  onSelectionChange={(selectedRows) => console.log(selectedRows)}
/>
```

### Skeleton Loaders

```tsx
import {
  Skeleton,
  SkeletonText,
  SkeletonCard,
  SkeletonTable,
  SkeletonList,
  SkeletonAvatar,
} from '@harlkwin/authflow-platform'

<Skeleton width="100%" height={40} variant="rounded" />
<SkeletonText lines={3} />
<SkeletonCard avatar lines={4} />
<SkeletonTable rows={5} columns={4} />
<SkeletonList items={3} avatar />
<SkeletonAvatar size="lg" />
```

## 📐 Page Templates

### DashboardPageTemplate

```tsx
import { DashboardPageTemplate } from '@harlkwin/authflow-platform'

<DashboardPageTemplate
  title="Analytics Dashboard"
  subtitle="Overview of your key metrics"
  stats={[
    { title: 'Total Users', value: '1,234', trend: { value: '+12%', direction: 'up' } },
    { title: 'Revenue', value: '$45,678', icon: <DollarIcon /> },
  ]}
  actions={[
    { label: 'Create Report', onClick: () => {}, variant: 'primary' },
  ]}
  isLoading={false}
>
  {/* Dashboard widgets */}
</DashboardPageTemplate>
```

### ListPageTemplate

```tsx
import { ListPageTemplate } from '@harlkwin/authflow-platform'

<ListPageTemplate
  title="Users"
  subtitle="Manage your users"
  data={users}
  columns={[
    { key: 'name', label: 'Name', sortable: true },
    { key: 'email', label: 'Email', sortable: true },
  ]}
  actions={[
    { label: 'Add User', onClick: () => {}, variant: 'primary' },
  ]}
  filterConfig={{
    searchPlaceholder: 'Search users...',
    filters: [
      { key: 'role', label: 'Role', options: [...] },
      { key: 'status', label: 'Status', options: [...] },
    ],
  }}
  isLoading={false}
/>
```

### DetailPageTemplate

```tsx
import { DetailPageTemplate } from '@harlkwin/authflow-platform'

<DetailPageTemplate
  title="User Details"
  subtitle="John Doe"
  breadcrumbs={[
    { label: 'Users', href: '/users' },
    { label: 'John Doe' },
  ]}
  tabs={[
    { id: 'overview', label: 'Overview', content: <Overview /> },
    { id: 'activity', label: 'Activity', content: <Activity /> },
  ]}
  actions={[
    { label: 'Edit', onClick: () => {}, variant: 'primary' },
    { label: 'Delete', onClick: () => {}, variant: 'danger' },
  ]}
  isLoading={false}
/>
```

### FormPageTemplate

```tsx
import { FormPageTemplate } from '@harlkwin/authflow-platform'

<FormPageTemplate
  title="Create User"
  subtitle="Add a new user to your organization"
  steps={[
    { id: 'basic', label: 'Basic Info' },
    { id: 'permissions', label: 'Permissions' },
    { id: 'review', label: 'Review' },
  ]}
  currentStep="basic"
  onStepChange={(step) => setCurrentStep(step)}
  onSubmit={handleSubmit}
  onCancel={() => router.back()}
  isLoading={false}
>
  {/* Form fields */}
</FormPageTemplate>
```

### SettingsPageTemplate

```tsx
import { SettingsPageTemplate, SettingsSection, SettingsRow, Toggle } from '@harlkwin/authflow-platform'

<SettingsPageTemplate
  title="Settings"
  subtitle="Manage your application settings"
  isLoading={false}
>
  <SettingsSection
    title="General"
    description="General application settings"
  >
    <SettingsRow
      label="Application Name"
      description="The name of your application"
    >
      <Input value={name} onChange={(e) => setName(e.target.value)} />
    </SettingsRow>

    <SettingsRow
      label="Dark Mode"
      description="Enable dark mode for the application"
    >
      <Toggle checked={darkMode} onChange={setDarkMode} />
    </SettingsRow>
  </SettingsSection>
</SettingsPageTemplate>
```

## 🎭 Layouts

### DashboardLayout

```tsx
import { DashboardLayout } from '@harlkwin/authflow-platform'

<DashboardLayout
  headerLeft={<Logo />}
  headerCenter={<SearchBar />}
  headerRight={<UserMenu />}
  sidebar={<NavigationSidebar />}
  sidebarCollapsed={collapsed}
  onSidebarToggle={() => setCollapsed(!collapsed)}
>
  {children}
</DashboardLayout>
```

### ModernAdminLayout

```tsx
import { ModernAdminLayout } from '@harlkwin/authflow-platform'

<ModernAdminLayout
  user={currentUser}
  navigationSections={[
    {
      title: 'Main',
      items: [
        { label: 'Dashboard', href: '/dashboard', icon: <DashboardIcon /> },
        { label: 'Users', href: '/users', icon: <UsersIcon /> },
      ],
    },
  ]}
>
  {children}
</ModernAdminLayout>
```

### Header & Sidebar Components

```tsx
import { Header, Sidebar } from '@harlkwin/authflow-platform'

<Header
  left={<Logo />}
  center={<SearchBar />}
  right={<UserMenu />}
  transparent
  blur
/>

<Sidebar
  sections={navigationSections}
  collapsed={false}
  gradient
/>
```

## 🌙 Dark Mode

### Using the useDarkMode Hook

```tsx
import { useDarkMode } from '@harlkwin/authflow-platform'

function DarkModeToggle() {
  const { darkMode, toggle, enable, disable, setDarkMode } = useDarkMode()

  return (
    <button onClick={toggle}>
      {darkMode ? '🌙 Dark' : '☀️ Light'}
    </button>
  )
}
```

The hook provides:
- `darkMode` (boolean) - Current dark mode state
- `toggle` () => void - Toggle dark mode
- `enable` () => void - Enable dark mode
- `disable` () => void - Disable dark mode
- `setDarkMode` (boolean) => void - Set dark mode state

Dark mode state is automatically persisted to localStorage.

## 🎨 Styling & Theming

### Tailwind Configuration

The platform includes a comprehensive Tailwind configuration with:
- Custom color palette (primary, secondary, accent)
- Typography scale
- Spacing system
- Custom shadows
- Border radius tokens
- Animation utilities
- Glassmorphism utilities

### Using Design Tokens

```tsx
// Colors
<div className="bg-primary-500 text-white">Primary Background</div>
<div className="bg-secondary-600">Secondary Background</div>

// Glass effects
<div className="glass-card">Glassmorphism Card</div>
<div className="glass-light">Light Glass</div>

// Gradients
<div className="bg-gradient-to-r from-primary-500 to-secondary-500">
  Gradient Background
</div>

// Dark mode
<div className="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100">
  Adaptive Colors
</div>
```

## 📚 API Reference

### Core Components

#### AuthFlowPlatform
Main platform wrapper component.

**Props:**
- `config` (PlatformConfig) - Platform configuration
  - `apiUrl` (string) - AuthFlow API URL
  - `keycloakUrl` (string) - Keycloak server URL
  - `realm` (string) - Keycloak realm (default: 'authflow')
  - `clientId` (string) - Keycloak client ID (default: 'authflow-client')
- `plugins` (AuthFlowPlugin[]) - Array of plugins to register
- `queryClientConfig` (object) - Custom QueryClient configuration
- `children` (ReactNode) - App content

#### PlatformProvider
Provider for QueryClient, Toast, and Tenant.

**Props:**
- `children` (ReactNode) - App content
- `queryClientConfig` (object) - Custom QueryClient configuration

#### AppLayout
Minimal root layout for Next.js.

**Props:**
- `children` (ReactNode) - Page content
- `fontClassName` (string) - Font className from next/font
- `lang` (string) - HTML lang attribute (default: 'en')

### Plugin Hooks

#### usePluginRegistry()
Access the plugin registry.

**Returns:**
- `plugins` (AuthFlowPlugin[]) - All registered plugins
- `registerPlugin` (plugin: AuthFlowPlugin) => Promise<void>
- `unregisterPlugin` (name: string) => Promise<void>
- `getPlugin` (name: string) => AuthFlowPlugin | undefined

#### usePluginRoutes()
Get all registered plugin routes.

**Returns:** `PluginRoute[]`

#### usePluginSidebarItems()
Get all registered sidebar items.

**Returns:** `SidebarItem[]`

#### usePluginPermissions()
Get all registered permissions.

**Returns:** `string[]`

#### usePluginNavigation()
Navigate to plugin routes.

**Returns:**
- `navigateToPlugin` (pluginName: string, path: string) => void

### Re-exported from @harlkwin/authflow-react

```tsx
import {
  // Components
  ProtectedRoute,
  AdminLayout,
  PermissionGate,
  UserMenu,
  OrganizationSwitcher,

  // Hooks
  useUser,
  useHasPermission,
  useHasRole,
  useIsSingularUser,
  useIsAuthenticated,
  useLogin,
  useLogout,
} from '@harlkwin/authflow-platform'
```

## 🧪 Testing

The platform includes comprehensive test suites:

```bash
# Run all tests
npm test

# Individual test suites
node test-exports.js          # Verify all exports
node test-plugin-system.js    # Test plugin system
node test-templates.js        # Test page templates
node test-dark-mode.js        # Test dark mode support
node test-all.js              # Run all tests
```

## 📦 Package Statistics

- **Build Size:** ~210 KB (CJS + ESM)
- **TypeScript:** Full type safety
- **Components:** 24 UI components
- **Layouts:** 5 layout components
- **Templates:** 5 page templates
- **Dark Mode:** 150+ dark mode classes
- **Coverage:** 94.4% dark mode coverage

## 🏗️ Project Structure

```
my-app/
├── src/
│   ├── app/
│   │   ├── layout.tsx              # Root layout
│   │   ├── page.tsx                # Homepage
│   │   ├── dashboard/
│   │   │   └── page.tsx            # Dashboard
│   │   └── users/
│   │       ├── page.tsx            # Users list
│   │       └── [id]/
│   │           └── page.tsx        # User detail
│   ├── plugins/
│   │   ├── workspace-plugin.tsx    # Workspace plugin
│   │   └── analytics-plugin.tsx    # Analytics plugin
│   └── components/
│       ├── Logo.tsx
│       └── SearchBar.tsx
├── package.json
├── next.config.js
├── tailwind.config.js
└── tsconfig.json
```

## 🔧 Development

```bash
# Install dependencies
npm install

# Build the package
npm run build

# Run tests
npm test

# Lint code
npm run lint
```

## 📝 Examples

Check out the example plugins included in the package:
- `examplePlugin` - Full-featured example with all plugin capabilities
- `mockPluginA` - Simple plugin with one route
- `mockPluginB` - Plugin with permissions
- `mockPluginC` - Plugin with dependencies

```tsx
import { examplePlugin, mockPluginA, mockPluginB } from '@harlkwin/authflow-platform'

<AuthFlowPlatform
  config={config}
  plugins={[examplePlugin, mockPluginA, mockPluginB]}
>
  {children}
</AuthFlowPlatform>
```

## 🤝 Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

## 📄 License

MIT © HarlKwin

## 🔗 Links

- [Documentation](https://docs.authflow.io)
- [GitHub Repository](https://github.com/harlkwin/authflow-platform)
- [Issue Tracker](https://github.com/harlkwin/authflow-platform/issues)
- [NPM Package](https://www.npmjs.com/package/@harlkwin/authflow-platform)

## 🙏 Acknowledgments

Built with:
- [Next.js](https://nextjs.org/)
- [React](https://react.dev/)
- [Tailwind CSS](https://tailwindcss.com/)
- [Radix UI](https://www.radix-ui.com/)
- [Zustand](https://zustand-demo.pmnd.rs/)
- [TanStack Query](https://tanstack.com/query)

---

Made with ❤️ by the AuthFlow team