Universal Widget Generator

Generate ANY widget type with full system integration - theme, storage, tests, and more

Universal Widget Generator

The Universal Widget Generator can create any type of widget with complete system integration. From buttons to complex data tables, from forms to charts - all with theme integration, storage support, tests, and production-ready code.

Overview

The Universal Widget Generator extends beyond simple button generation to support 40+ widget types, each with:

Supported Widget Types

Form Widgets

Data Display

Navigation

Feedback

Layout

Quick Start

Basic Usage

import { inject } from '@angular/core';
import {
  UniversalWidgetGeneratorService,
  WidgetType,
  WidgetStyle,
  WidgetSize,
  WidgetVariant
} from '@gograb-ai';

const generator = inject(UniversalWidgetGeneratorService);

// Generate a simple button
generator.generateWidget({
  widgetType: WidgetType.BUTTON,
  purpose: 'Primary action',
  description: 'Call-to-action button for signup',
  style: WidgetStyle.MODERN,
  size: WidgetSize.MEDIUM,
  variant: WidgetVariant.SOLID,
  themeIntegration: {
    useTheme: true,
    colorScheme: 'primary'
  },
  features: [],
  complexity: 'simple',
  accessibility: 'aa',
  responsive: true,
  includeTests: true
}).subscribe(design => {
  console.log('Generated widget:', design);
  console.log('Component code:', design.code.componentTs);
  console.log('Template:', design.code.componentHtml);
  console.log('Tests:', design.code.componentSpec);
});

Generate from Description

The generator can understand natural language descriptions:

// Just describe what you want
generator.generateFromDescription(
  'Create a table showing user data with sorting and filtering'
).subscribe(design => {
  // Automatically detects:
  // - Widget type: TABLE
  // - Features: SORTING, FILTERING
  // - Complexity: intermediate
  console.log('Generated:', design);
});

Widget Types

Data Table

generator.generateWidget({
  widgetType: WidgetType.TABLE,
  purpose: 'Display user data',
  description: 'User management table with sorting, filtering, and pagination',
  style: WidgetStyle.GLASSMORPHISM,
  size: WidgetSize.MEDIUM,
  variant: WidgetVariant.SOLID,
  themeIntegration: {
    useTheme: true,
    colorScheme: 'primary'
  },
  dataIntegration: {
    useStorage: true,
    mockApi: true,
    collection: 'users',
    fields: {
      name: 'string',
      email: 'string',
      role: 'string',
      createdAt: 'Date'
    }
  },
  features: [
    WidgetFeature.SORTING,
    WidgetFeature.FILTERING,
    WidgetFeature.PAGINATION,
    WidgetFeature.SEARCH
  ],
  complexity: 'intermediate',
  accessibility: 'aa',
  responsive: true,
  includeTests: true
}).subscribe(design => {
  // Generated table includes:
  // - Sorting on all columns
  // - Search functionality
  // - Pagination controls
  // - Filter dropdown
  // - Mock API with sample data
  // - Storage integration
  // - Complete unit tests
});

Form Component

generator.generateWidget({
  widgetType: WidgetType.FORM,
  purpose: 'User registration',
  description: 'Registration form with validation and error handling',
  style: WidgetStyle.MODERN,
  size: WidgetSize.MEDIUM,
  variant: WidgetVariant.SOLID,
  themeIntegration: {
    useTheme: true,
    colorScheme: 'primary'
  },
  dataIntegration: {
    useStorage: true,
    mockApi: true,
    collection: 'users'
  },
  features: [
    WidgetFeature.VALIDATION,
    WidgetFeature.ERROR_HANDLING,
    WidgetFeature.ASYNC_LOADING,
    WidgetFeature.KEYBOARD_NAV
  ],
  complexity: 'intermediate',
  accessibility: 'aaa',
  responsive: true,
  includeTests: true
}).subscribe(design => {
  // Generated form includes:
  // - Input fields with validation
  // - Error messages
  // - Loading states
  // - Success feedback
  // - Mock API for submission
  // - Storage integration
  // - Keyboard navigation
  // - Screen reader support
});

Chart Widget

generator.generateWidget({
  widgetType: WidgetType.CHART,
  purpose: 'Display analytics',
  description: 'Line chart showing user growth over time',
  style: WidgetStyle.GLASSMORPHISM,
  size: WidgetSize.LARGE,
  variant: WidgetVariant.GRADIENT,
  themeIntegration: {
    useTheme: true,
    colorScheme: 'accent'
  },
  dataIntegration: {
    useStorage: true,
    mockApi: true,
    collection: 'analytics'
  },
  features: [
    WidgetFeature.ANIMATIONS,
    WidgetFeature.TOOLTIPS,
    WidgetFeature.DARK_MODE
  ],
  complexity: 'complex',
  accessibility: 'aa',
  responsive: true,
  includeTests: true
}).subscribe(design => {
  // Generated chart includes:
  // - Chart.js or similar integration
  // - Animated transitions
  // - Interactive tooltips
  // - Dark mode support
  // - Mock data generator
  // - Responsive sizing
});

Card Widget

generator.generateWidget({
  widgetType: WidgetType.CARD,
  purpose: 'User profile display',
  description: 'User profile card with avatar, stats, and action buttons',
  style: WidgetStyle.GLASSMORPHISM,
  size: WidgetSize.MEDIUM,
  variant: WidgetVariant.SOLID,
  themeIntegration: {
    useTheme: true,
    colorScheme: 'primary'
  },
  dataIntegration: {
    useStorage: true,
    mockApi: true,
    collection: 'users'
  },
  features: [
    WidgetFeature.ICONS,
    WidgetFeature.ANIMATIONS,
    WidgetFeature.TOOLTIPS
  ],
  complexity: 'simple',
  accessibility: 'aa',
  responsive: true,
  includeTests: true
}).subscribe(design => {
  // Generated card includes:
  // - Header with avatar
  // - User info section
  // - Stats display
  // - Action buttons
  // - Hover effects
  // - Mock user data
});

Widget Features

Sorting

features: [WidgetFeature.SORTING]

// Generates:
// - Sort indicators in headers
// - Click handlers for sorting
// - Multi-column sort support
// - Sort state management with signals

Filtering

features: [WidgetFeature.FILTERING]

// Generates:
// - Filter controls
// - Filter state management
// - Multiple filter criteria
// - Clear filters button

Pagination

features: [WidgetFeature.PAGINATION]

// Generates:
// - Page controls
// - Page size selector
// - Total count display
// - Navigation buttons

Search

features: [WidgetFeature.SEARCH]

// Generates:
// - Search input
// - Debounced search
// - Search across fields
// - Clear search button

Drag and Drop

features: [WidgetFeature.DRAG_DROP]

// Generates:
// - Draggable items
// - Drop zones
// - Drag state indicators
// - Reorder functionality

Animations

features: [WidgetFeature.ANIMATIONS]

// Generates:
// - Entrance animations
// - Transition effects
// - Hover animations
// - Loading animations

Validation

features: [WidgetFeature.VALIDATION]

// Generates:
// - Field validators
// - Error messages
// - Success indicators
// - Real-time validation

Dark Mode

features: [WidgetFeature.DARK_MODE]

// Generates:
// - Dark theme styles
// - Theme toggle logic
// - Automatic theme detection
// - Smooth transitions

Accessibility

features: [
  WidgetFeature.KEYBOARD_NAV,
  WidgetFeature.SCREEN_READER
]

// Generates:
// - Keyboard shortcuts
// - Focus management
// - ARIA labels
// - Screen reader announcements

Widget Styles

Glassmorphism

style: WidgetStyle.GLASSMORPHISM

// Applies:
// - Semi-transparent background
// - Backdrop blur effect
// - Subtle borders
// - Elegant shadows

Modern

style: WidgetStyle.MODERN

// Applies:
// - Clean lines
// - Proper spacing
// - Smooth corners
// - Contemporary colors

Minimal

style: WidgetStyle.MINIMAL

// Applies:
// - Maximum simplicity
// - Essential elements only
// - Subtle effects
// - Clean design

Rounded

style: WidgetStyle.ROUNDED

// Applies:
// - Large border radius
// - Soft appearance
// - Friendly feel
// - Bubble-like design

Widget Variants

Solid

variant: WidgetVariant.SOLID

// Filled background with solid color

Outline

variant: WidgetVariant.OUTLINE

// Transparent background with border

Ghost

variant: WidgetVariant.GHOST

// Minimal styling, no background or border

Soft

variant: WidgetVariant.SOFT

// Subtle colored background

Gradient

variant: WidgetVariant.GRADIENT

// Gradient background effect

Theme Integration

Using Theme Colors

themeIntegration: {
  useTheme: true,
  colorScheme: 'primary' // or 'secondary', 'accent', etc.
}

// Generates code using:
// - .ux-bg-primary utility class
// - .ux-text-primary for text
// - CSS variables for dynamic colors
// - Automatic dark mode support

Custom Colors

themeIntegration: {
  useTheme: false,
  customColors: {
    primary: '#667eea',
    secondary: '#764ba2'
  }
}

// Generates code with inline colors

Data Integration

Storage Integration

dataIntegration: {
  useStorage: true,
  collection: 'users',
  fields: {
    name: 'string',
    email: 'string',
    age: 'number',
    active: 'boolean'
  }
}

// Generates:
// - StorageService injection
// - CRUD operations
// - Offline-first logic
// - MongoDB sync configuration

Mock API

dataIntegration: {
  mockApi: true,
  collection: 'users'
}

// Generates:
// - Mock endpoints
// - Sample data generator
// - Request/response types
// - HTTP interceptor setup

Advanced Features

Multiple Variations

Generate multiple variations at once:

generator.generateWidgetVariations(request, 3).subscribe(designs => {
  // Returns 3 variations:
  // - Solid variant
  // - Outline variant
  // - Ghost variant
  
  designs.forEach((design, index) => {
    console.log(`Variation ${index + 1}:`, design.name);
  });
});

Export to Apps

// Export widget for use in other apps
generator.exportWidget(design, 'editor-web');

// Widget is saved to localStorage
// Can be imported in target app

Widget Templates

// Get a basic template for any widget type
const template = generator.getWidgetTemplate(WidgetType.TABLE);

// Use template as starting point
// Customize as needed

Generated Code Structure

Component TypeScript

// Generated component follows best practices:
import { Component, input, output, signal, computed } from '@angular/core';
import { StorageService } from '@storage-system';

@Component({
  selector: 'app-user-table',
  standalone: true,
  templateUrl: './user-table.component.html',
  styleUrls: ['./user-table.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserTableComponent {
  private storage = inject(StorageService);

  // Inputs
  data: InputSignal<User[]> = input([]);
  sortable: InputSignal<boolean> = input(true);

  // State signals
  private readonly _sortColumn = signal<string>('name');
  private readonly _sortDirection = signal<'asc' | 'desc'>('asc');

  // Computed
  readonly sortedData = computed(() => {
    // Sorting logic using signals
  });

  // Methods
  handleSort(column: string): void {
    // Sort logic
  }
}

Component HTML

<!-- Generated template uses utility classes -->
<div class="ux-card glass-card ux-p-md">
  <div class="ux-flex ux-justify-between ux-items-center ux-mb-md">
    <h2 class="ux-text-lg ux-font-semibold">Users</h2>
    <button class="btn-primary ux-btn-sm">Add User</button>
  </div>

  <table class="ux-table ux-w-full">
    <thead>
      <tr>
        @for (column of columns(); track column.key) {
          <th 
            class="ux-text-left ux-p-sm cursor-pointer"
            (click)="handleSort(column.key)"
          >
            {{ column.label }}
            @if (sortColumn() === column.key) {
              <i class="fas fa-sort-{{ sortDirection() }}"></i>
            }
          </th>
        }
      </tr>
    </thead>
    <tbody>
      @for (item of sortedData(); track item.id) {
        <tr class="ux-hover-bg-surface">
          <td class="ux-p-sm">{{ item.name }}</td>
          <td class="ux-p-sm">{{ item.email }}</td>
          <td class="ux-p-sm">
            <span class="status-badge" 
                  [class.badge-success]="item.active"
                  [class.badge-error]="!item.active">
              {{ item.active ? 'Active' : 'Inactive' }}
            </span>
          </td>
        </tr>
      }
    </tbody>
  </table>
</div>

Component SCSS

// Generated SCSS is minimal - utilities handle most styling
:host {
  display: block;
}

// Component-specific overrides only
.ux-table {
  th {
    font-weight: 600;
  }

  tbody tr:hover {
    @apply ux-transition-colors;
  }
}

Component Tests

// Generated tests use vitest
import { describe, it, expect, beforeEach } from 'vitest';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UserTableComponent } from './user-table.component';

describe('UserTableComponent', () => {
  let component: UserTableComponent;
  let fixture: ComponentFixture<UserTableComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [UserTableComponent]
    }).compileComponents();

    fixture = TestBed.createComponent(UserTableComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should sort data when column header is clicked', () => {
    const mockData = [
      { id: 1, name: 'Bob', email: '[email protected]', active: true },
      { id: 2, name: 'Alice', email: '[email protected]', active: true }
    ];
    
    component.data = signal(mockData);
    component.handleSort('name');
    
    const sorted = component.sortedData();
    expect(sorted[0].name).toBe('Alice');
  });

  it('should toggle sort direction on second click', () => {
    component.handleSort('name');
    expect(component.sortDirection()).toBe('asc');
    
    component.handleSort('name');
    expect(component.sortDirection()).toBe('desc');
  });
});

Best Practices

1. Start Simple

// Start with basic widget
{ complexity: 'simple', features: [] }

// Add features as needed

2. Use Theme Integration

// Always enable theme integration
themeIntegration: { useTheme: true }

// For consistency across app

3. Generate Tests

// Always generate tests
includeTests: true

// Ensures code quality

4. Review Generated Code

5. Provide Feedback

// After using generated widget, provide feedback
await aiStorage.storeGenerationWithLearning(design, {
  rating: 4.5,
  modifications: [...]
});

Troubleshooting

Widget Too Complex

// If generated widget is too complex:
{ complexity: 'simple', features: [] }

// Add features incrementally

Missing Features

// Ensure features are explicitly requested
features: [
  WidgetFeature.SORTING,
  WidgetFeature.FILTERING,
  // ... etc
]

Theme Not Applied

// Verify theme integration is enabled
themeIntegration: {
  useTheme: true,
  colorScheme: 'primary' // must specify scheme
}

Mock API Not Generated

// Ensure mock API is requested
dataIntegration: {
  mockApi: true,
  collection: 'users' // must specify collection
}

Next Steps

Related