docs: migration,fakemui,icons (16 files)

This commit is contained in:
Richard Ward
2025-12-31 00:33:03 +00:00
parent 6ac998b4f8
commit 2db0bf49ed
16 changed files with 358 additions and 6319 deletions

View File

@@ -1,348 +0,0 @@
# Dependency Cleanup Plan
**Created:** 2025-12-30
**Status:** Planning Phase
**Goal:** Remove unnecessary dependencies from package.json
---
## Current Dependencies Analysis
### MUI Dependencies (TO REMOVE)
**Location:** `frontends/nextjs/package.json`
```json
"@emotion/react": "^11.14.0", // MUI peer dependency
"@emotion/styled": "^11.14.1", // MUI peer dependency
"@mui/icons-material": "^7.3.6", // ~500KB - Replace with fakemui icons
"@mui/material": "^7.3.6", // ~1MB - Replace with fakemui
"@mui/x-data-grid": "^8.23.0", // Replace with custom table
"@mui/x-date-pickers": "^8.23.0", // Replace with native date input
```
**Total Size:** ~2-3 MB
**Status:** ❌ Ready to remove after migration complete
---
## Dependencies to Keep
### Essential Next.js & React
```json
"next": "16.1.1", // ✅ Core framework
"react": "19.2.3", // ✅ Core library
"react-dom": "19.2.3", // ✅ Core library
```
### Icons
```json
"@phosphor-icons/react": "^2.1.10", // ❌ Remove - Using fakemui custom icons
```
**✅ DECISION:** Full fakemui custom SVG icon system
**Action:** Remove @phosphor-icons/react after icon migration complete
### Form Handling
```json
"@hookform/resolvers": "^5.2.2", // ✅ Keep - Zod integration
"react-hook-form": "^7.69.0", // ✅ Keep - Form state management
"zod": "^4.2.1", // ✅ Keep - Schema validation
```
### Data Fetching & State
```json
"@tanstack/react-query": "^5.90.12", // ✅ Keep - Server state
```
### Database
```json
"@prisma/client": "^7.2.0", // ✅ Keep - Database ORM
"@prisma/adapter-better-sqlite3": "^7.2.0", // ✅ Keep - SQLite adapter
"better-sqlite3": "^12.5.0", // ✅ Keep - SQLite driver
```
### Code Editor
```json
"@monaco-editor/react": "^4.7.0", // ✅ Keep - Code editor
```
### Utilities
```json
"date-fns": "^4.1.0", // ✅ Keep - Date utilities
"marked": "^17.0.1", // ✅ Keep - Markdown parsing
"uuid": "^13.0.0", // ✅ Keep - UUID generation
"jszip": "^3.10.1", // ✅ Keep - ZIP handling
```
### Animation & Visualization
```json
"motion": "^12.6.2", // ✅ Keep - Animation library
"recharts": "^3.6.0", // ✅ Keep - Charts
"d3": "^7.9.0", // ✅ Keep - Data visualization
"three": "^0.182.0", // ✅ Keep - 3D graphics
```
### Lua Integration
```json
"fengari-web": "^0.1.4", // ✅ Keep - Lua in browser
"fengari-interop": "^0.1.4", // ✅ Keep - Lua/JS interop
```
### AWS S3
```json
"@aws-sdk/client-s3": "^3.958.0", // ✅ Keep - S3 client
"@aws-sdk/lib-storage": "^3.958.0", // ✅ Keep - Multipart upload
"@aws-sdk/s3-request-presigner": "^3.958.0", // ✅ Keep - Presigned URLs
```
### GitHub Integration
```json
"@octokit/core": "^7.0.6", // ✅ Keep - GitHub API
"octokit": "^5.0.5", // ✅ Keep - GitHub SDK
"@github/spark": ">=0.43.1 <1", // ⚠️ Evaluate - What is this?
```
**Action Needed:** Verify any remaining @github/spark runtime usage (useKV imports replaced with local hook).
### Error Handling & Notifications
```json
"react-error-boundary": "^6.0.0", // ✅ Keep - Error boundaries
"sonner": "^2.0.7", // ✅ Keep - Toast notifications
```
### Misc
```json
"@next/third-parties": "^16.1.1", // ⚠️ Evaluate - Scripts loader
"server-only": "^0.0.1", // ✅ Keep - Server-only marker
"sharp": "^0.34.5", // ✅ Keep - Image optimization
```
---
## Removal Plan
### Phase 1: Immediate Removal (After fakemui complete)
**Remove:**
- `@mui/material` ^7.3.6
- `@mui/icons-material` ^7.3.6
- `@emotion/react` ^11.14.0
- `@emotion/styled` ^11.14.1
**Bundle Size Savings:** ~1.5-2 MB
**Prerequisites:**
- ✅ All MUI components migrated to fakemui
- ✅ All MUI icons replaced with fakemui icons
- ✅ Theme system migrated to CSS variables
- ✅ CssBaseline replaced with fakemui reset
### Phase 2: Advanced Components (After Lua packages)
**Remove:**
- `@mui/x-data-grid` ^8.23.0
- `@mui/x-date-pickers` ^8.23.0
**Bundle Size Savings:** ~500 KB
**Prerequisites:**
- ✅ DataGrid replaced with fakemui Table or Lua package
- ✅ DatePickers replaced with native HTML5 or Lua package
### Phase 3: Icon Consolidation ✅ APPROVED
**Remove:**
- `@phosphor-icons/react` ^2.1.10
**Bundle Size Savings:** ~200 KB
**Decision:** Using fakemui custom SVG icons only (no third-party icon library)
**Prerequisites:**
- ✅ All icons migrated to fakemui/icons
- ✅ Icon inventory complete (50-100 icons)
- ✅ Pattern established for adding new icons as needed
---
## Dependencies to Evaluate
### @github/spark
**Current Version:** >=0.43.1 <1
**Purpose:** Previously for `useKV` hook usage
**Action:** Runtime imports replaced with local `@/hooks/data/useKV`; remaining references are docs and a module override type stub
**Decision:** Candidate for removal once no other Spark features are needed
### @next/third-parties
**Current Version:** ^16.1.1
**Purpose:** Third-party script loading (Google Analytics, etc.)
**Action:** Check if actively used
**Decision:** Keep if used, remove if not
---
## Post-Migration package.json
**Estimated Dependencies After Cleanup:** 35-40 packages (down from 45)
**Estimated Bundle Size Reduction:** 2-3 MB (15-25%)
### Final State
```json
{
"dependencies": {
// Core
"next": "16.1.1",
"react": "19.2.3",
"react-dom": "19.2.3",
// Forms & Validation
"@hookform/resolvers": "^5.2.2",
"react-hook-form": "^7.69.0",
"zod": "^4.2.1",
// Data & State
"@tanstack/react-query": "^5.90.12",
"@prisma/client": "^7.2.0",
"@prisma/adapter-better-sqlite3": "^7.2.0",
"better-sqlite3": "^12.5.0",
// Editor & Code
"@monaco-editor/react": "^4.7.0",
// Utilities
"date-fns": "^4.1.0",
"marked": "^17.0.1",
"uuid": "^13.0.0",
"jszip": "^3.10.1",
// Visualization
"motion": "^12.6.2",
"recharts": "^3.6.0",
"d3": "^7.9.0",
"three": "^0.182.0",
// Lua
"fengari-web": "^0.1.4",
"fengari-interop": "^0.1.4",
// AWS
"@aws-sdk/client-s3": "^3.958.0",
"@aws-sdk/lib-storage": "^3.958.0",
"@aws-sdk/s3-request-presigner": "^3.958.0",
// GitHub
"@octokit/core": "^7.0.6",
"octokit": "^5.0.5",
// UI & Feedback
"react-error-boundary": "^6.0.0",
"sonner": "^2.0.7",
// Misc
"server-only": "^0.0.1",
"sharp": "^0.34.5"
}
}
```
---
## Removal Commands
### Phase 1: MUI Removal
```bash
cd frontends/nextjs
npm uninstall @mui/material @mui/icons-material @emotion/react @emotion/styled
```
### Phase 2: MUI X Components
```bash
npm uninstall @mui/x-data-grid @mui/x-date-pickers
```
### Phase 3: Phosphor Icons
```bash
npm uninstall @phosphor-icons/react
```
---
## Verification Steps
After each removal phase:
1. **Build Test**
```bash
npm run build
```
2. **Type Check**
```bash
npm run typecheck
```
3. **Unit Tests**
```bash
npm run test:unit
```
4. **E2E Tests**
```bash
npm run test:e2e
```
5. **Bundle Analysis**
```bash
# Check bundle size
npm run build
# Compare .next/static/chunks sizes
```
---
## Risk Mitigation
### Backup Strategy
```bash
# Before removal
git checkout -b mui-removal-phase-1
cp package.json package.json.backup
npm list > installed-packages.txt
```
### Rollback Plan
```bash
# If issues arise
git checkout main
npm install
```
### Staged Rollout
1. Remove MUI deps but keep code
2. Test thoroughly
3. If successful, proceed
4. If issues, restore deps and investigate
---
## Success Metrics
- ✅ Zero MUI imports in codebase
- ✅ All tests passing
- ✅ No build errors
- ✅ Bundle size reduced 15-25%
- ✅ No visual regressions
- ✅ Performance metrics maintained or improved
---
**Next Actions:**
1. Complete MUI migration (see MUI_ELIMINATION_PLAN.md)
2. Search for @github/spark usage
3. Check @next/third-parties usage
4. Execute Phase 1 removal
5. Verify and test
6. Proceed to Phase 2
**Last Updated:** 2025-12-30

View File

@@ -1,411 +0,0 @@
# MetaBuilder Execution Tracker
**Live Progress Dashboard**
**Started:** 2025-12-30
**Status:** 🚀 Active Execution
**Last Updated:** 2025-12-30 22:00 UTC
---
## Quick Status Overview
| Phase | Name | Status | Progress |
|-------|------|--------|----------|
| 1 | fakemui Gaps | ✅ Complete | 100% |
| 2 | Lua Type Annotations | ✅ Complete | 95% |
| 3 | Package Structure | ✅ Complete | 95% |
| 4 | fakemui Enhancements | ✅ Complete | 98% |
| 5 | Permissions System | ✅ Complete | 100% |
| 6 | Dependency Cleanup | ✅ Complete | 100% |
| 7 | TSX → Lua (Part 1) | ✅ Complete | 95% |
| 8 | TSX → Lua (Part 2) | 🟡 In Progress | 60% |
| 9 | CSS Designer | ✅ Complete | 100% |
| 10 | Parameterized Tests | ✅ Complete | 95% |
| 11 | Package Validator | ✅ Complete | 100% |
| 12 | Multi-Frontend | 🟡 In Progress | 65% |
| 13 | E2E Verification | 🟡 In Progress | 70% |
| 14 | Documentation | 🟡 In Progress | 65% |
| 15 | Package Schema System | ✅ Complete | 95% |
---
## Current State Summary
### ✅ Test Suite Health
- **138 test files** all passing
- **802 tests passed** (3 skipped - waiting for Lua UI packages)
- **vitest aliases fixed** for @/fakemui and @/dbal
- **bun:test → vitest** migration complete
### ✅ Already Complete
- **MUI eliminated from source code** (100% - no @mui imports found)
- **MUI removed from package.json** (100% - dependencies gone)
- **421+ fakemui icons** created
- **155+ fakemui components** available (including DataGrid, DatePicker in x/)
- **44 Lua packages** all validated with package validator
- **127+ test files** across packages
- **723+ Lua files** in packages folder
- **Permissions system** fully implemented in shared/permissions/
- **CSS Designer package** complete with colors, fonts, spacing, borders, shadows, export
- **Package Validator CLI** complete - validates metadata.json, components.json, folder structure
### 🔧 Recent Fixes (This Session)
- Fixed vitest.config.ts alias resolution for @/fakemui
- Fixed TextField htmlFor/id accessibility for labels
- Added aria-labels to Pagination component
- Fixed TextField select mode (supports children for MenuItem)
- Fixed bun:test imports → vitest
- Fixed @/dbal import paths
- Fixed 7 packages missing packageId fields
- Created validate-packages.cjs CLI tool
- Created E2E tests for package rendering (17 tests)
- **Fixed Prisma schema** `startedAt` syntax error
- **Added 15+ new Prisma models**: IRC, Streaming, Codegen
- **Created package-local schema system** with checksum validation
- **Created schema migration queue** for admin approval workflow
- **Created Qt6/QML DBAL bridge** (DBALClient.h/cpp, DBALProvider.qml)
- **Added schema:* npm scripts** for CLI management
- **Created Lua DB operations** for 4 packages (audit_log, notification_center, forum_forge, irc_webchat)
- **Added CLI DBAL commands** with create/read/update/delete/list/execute support
- **Extended HttpClient** with PATCH and DELETE methods
### 🎯 Active Work Items
1. Multi-frontend support (Qt6/QML, CLI) - **80% complete**
2. E2E verification with Playwright - **75% complete**
3. Documentation completion - **70% complete**
4. **Lua DBAL operations** - **22 packages complete**
---
## Phase 15: Package Schema System (NEW)
### Features
- [x] Package-local schemas in `seed/schema/entities.yaml`
- [x] Checksum validation across packages
- [x] Migration queue with admin approval
- [x] Prisma codegen from YAML definitions
- [x] Docker startup hook for migrations
- [x] CLI tools (`npm run schema:*`)
- [x] Lua DBAL operations for packages
- [ ] WebSocket real-time sync
- [ ] Schema versioning & rollback
### Packages with Schema
- [x] audit_log (AuditLog) + Lua operations
- [x] notification_center (Notification) + Lua operations
- [x] forum_forge (ForumCategory, ForumThread, ForumPost) + Lua operations
- [x] irc_webchat (IRCChannel, IRCMessage, IRCMembership) + Lua operations
- [x] media_center (MediaAsset, MediaJob) + Lua operations
- [x] stream_cast (StreamChannel, StreamSchedule, StreamScene) + Lua operations
### Packages with DBAL Operations (Using Core Entities)
- [x] user_manager - User CRUD, permissions, search, bulk ops
- [x] role_editor - Role management, user-role assignment, permissions
- [x] workflow_editor - Workflow CRUD, execution, step logging
- [x] codegen_studio - Project, Blueprint, Template management
- [x] github_tools - GitHub connection, repos, webhooks, PR tracking
- [x] smtp_config - SMTP config, email templates, email logs
- [x] data_table - Generic CRUD helpers, table config, user preferences
- [x] dashboard - Layout, widget, cache operations
- [x] arcade_lobby - Game, Leaderboard, Session operations
- [x] form_builder - Form, Field, Submission operations
- [x] css_designer - Theme, Style Component, CSS generation
- [x] schema_editor - Entity Schema CRUD, field/index/relation management
- [x] code_editor - Snippets, Sessions, Revisions, Language config
- [x] package_validator - Validation runs, issues, rules
- [x] screenshot_analyzer - Screenshot, Analysis, Components, Colors
- [x] social_hub - Profiles, Connections, Activity, Likes
### Multi-Frontend DBAL Support
- [x] Qt6/QML DBALClient (C++ + QML provider)
- [x] CLI DBAL commands (create, read, update, delete, list, execute)
- [x] CMakeLists.txt updated for Qt6 and CLI
- [ ] CLI auth token management
- [ ] Qt6 WebSocket subscriptions
---
## Phase 1: fakemui Component & Icon Gaps
### Icons (421+ available)
- [x] Basic icons (arrows, checks, close, etc.)
- [x] Media icons (play, pause, volume, etc.)
- [x] File icons (folder, document, etc.)
- [x] Social icons (github, google, etc.)
- [x] Admin icons (settings, users, etc.)
- [x] Rich text icons (bold, italic, lists, etc.)
- [x] Device icons (smartphone, tablet, desktop)
- [ ] Additional domain-specific icons (as needed)
### Components (155+ available)
- [x] Input components (Button, TextField, Select, Checkbox, Radio, etc.)
- [x] Feedback components (Alert, Dialog, Snackbar, Progress, etc.)
- [x] Navigation components (Menu, Tabs, Breadcrumbs, Pagination, etc.)
- [x] Data display components (Table, List, Card, Chip, etc.)
- [x] Layout components (Box, Stack, Grid, Container, etc.)
- [x] Form components (FormControl, FormLabel, RadioGroup, etc.)
- [x] Date/Time pickers (DatePicker, TimePicker)
- [x] Color picker
- [x] File upload
- [ ] LoadingButton (Button with loading state)
- [ ] VirtualList (optional - low priority)
---
## Phase 2: Lua Type Annotations
### Package Type Coverage Status
| Package | types.lua | Inline Types | Status |
|---------|-----------|--------------|--------|
| admin_dialog | ✅ | ⏳ | Needs review |
| arcade_lobby | ✅ | ⏳ | Needs review |
| audit_log | ✅ | ✅ | Complete |
| code_editor | ✅ | ⏳ | Needs review |
| codegen_studio | ✅ | ⏳ | Needs review |
| config_summary | ✅ | ⏳ | Needs review |
| dashboard | ✅ | ✅ | Complete |
| data_table | ✅ | ⏳ | Needs review |
| dbal_demo | ✅ | ✅ | Complete |
| form_builder | ✅ | ⏳ | Needs review |
| forum_forge | ✅ | ⏳ | Needs review |
| github_tools | ✅ | ✅ | Complete |
| irc_webchat | ✅ | ⏳ | Needs review |
| lua_test | ✅ | ✅ | Complete |
| media_center | ✅ | ⏳ | Needs review |
| nav_menu | ✅ | ⏳ | Needs review |
| notification_center | ✅ | ⏳ | Needs review |
| package_validator | ✅ | ✅ | Complete |
| quick_guide | ✅ | ⏳ | Needs review |
| role_editor | ✅ | ⏳ | Needs review |
| schema_editor | ✅ | ⏳ | Needs review |
| screenshot_analyzer | ✅ | ✅ | Complete |
| shared | ✅ | ✅ | Complete |
| smtp_config | ✅ | ⏳ | Needs review |
| social_hub | ✅ | ✅ | Complete |
| stats_grid | ✅ | ⏳ | Needs review |
| stream_cast | ✅ | ✅ | Complete |
| ui_auth | ✅ | ⏳ | Needs review |
| ui_dialogs | ✅ | ⏳ | Needs review |
| ui_footer | ✅ | ⏳ | Needs review |
| ui_header | ✅ | ⏳ | Needs review |
| ui_home | ✅ | ⏳ | Needs review |
| ui_intro | ✅ | ⏳ | Needs review |
| ui_level2 | ✅ | ⏳ | Needs review |
| ui_level3 | ✅ | ⏳ | Needs review |
| ui_level4 | ✅ | ⏳ | Needs review |
| ui_level5 | ✅ | ⏳ | Needs review |
| ui_level6 | ✅ | ⏳ | Needs review |
| ui_login | ✅ | ⏳ | Needs review |
| ui_pages | ✅ | ⏳ | Needs review |
| ui_permissions | ✅ | ⏳ | Needs review |
| user_manager | ✅ | ⏳ | Needs review |
| workflow_editor | ✅ | ⏳ | Needs review |
---
## Phase 3: Package Structure Refinement
### Large Files to Split (>150 lines)
- [ ] Audit all packages for large files
- [ ] Split files with multiple unrelated functions
- [ ] Update exports after splitting
- [ ] Verify tests still pass
---
## Phase 4: fakemui Enhancements
### Component Upgrades
- [ ] Add micro-interactions to all components
- [ ] Review accessibility (ARIA labels)
- [ ] Add animation polish
- [ ] Enhance error states
### Styling Review
- [ ] Review all 64 SCSS modules
- [ ] Ensure consistent spacing
- [ ] Test all 5 theme variants
---
## Phase 5: Permissions System
### Design
```lua
---@class PackagePermissions
---@field enabled boolean
---@field minLevel PermissionLevel (0-6)
---@field databaseRequired boolean
---@field components table<string, ComponentPermission>
```
### Implementation
- [ ] Create permissions.lua in shared package
- [ ] Update package renderer to check permissions
- [ ] Add database toggle support
- [ ] Add component-level toggles
- [ ] Create permission management UI
---
## Phase 6: Dependency Cleanup
### Status: ✅ COMPLETE
**Removed:**
- @mui/material
- @mui/icons-material ✅
- @mui/x-data-grid ✅
- @mui/x-date-pickers ✅
- @emotion/react
- @emotion/styled
- @phosphor-icons/react ✅
**Bundle Size Reduction:** ~2-3MB estimated
---
## Phase 7-8: TSX → Lua Conversion
### High Priority Conversions
- [ ] workflow_editor (8 TSX files)
- [ ] schema_editor (~10 TSX files)
- [ ] form_builder (~15 TSX files)
- [ ] component_builder
- [ ] css_manager
### Packages Already in Lua
- [x] audit_log
- [x] dashboard
- [x] github_tools
- [x] media_center
- [x] All ui_* packages
---
## Phase 10: Parameterized Tests
### Packages with Tests
| Package | Test Files | Cases File | Status |
|---------|------------|------------|--------|
| arcade_lobby | ✅ | ✅ | Complete |
| code_editor | ✅ | ✅ | Complete |
| dashboard | ✅ | ⏳ | Needs cases.json |
| forum_forge | ✅ | ✅ | Complete |
| github_tools | ✅ | ⏳ | Needs cases.json |
| irc_webchat | ✅ | ✅ | Complete |
| lua_test | ✅ | ✅ | Complete |
| media_center | ✅ | ✅ | Complete |
| notification_center | ✅ | ✅ | Complete |
| package_validator | ✅ | ⏳ | Needs cases.json |
| ui_level3 | ✅ | ✅ | Complete |
### Packages Needing Tests
- [ ] admin_dialog
- [ ] codegen_studio
- [ ] config_summary
- [ ] data_table
- [ ] dbal_demo
- [ ] form_builder
- [ ] nav_menu
- [ ] quick_guide
- [ ] role_editor
- [ ] schema_editor
- [ ] screenshot_analyzer
- [ ] smtp_config
- [ ] social_hub
- [ ] stats_grid
- [ ] stream_cast
- [ ] user_manager
- [ ] workflow_editor
---
## Phase 11: Package Validator Compliance
### Validation Checks
- [ ] metadata.json complete
- [ ] components.json valid
- [ ] All scripts export correctly
- [ ] types.lua present
- [ ] No circular dependencies
---
## Phase 12: Multi-Frontend Support
### Qt6/QML
- [x] 104 QML components exist in fakemui
- [ ] Test package compatibility
- [ ] Create QML-specific layouts
### CLI
- [ ] Create CLI component mappings
- [ ] Implement text-based UI
- [ ] Test package compatibility
---
## Phase 13: E2E Verification
### Playwright Tests
- [ ] Create package rendering tests
- [ ] Gradually enable packages
- [ ] Visual regression tests
- [ ] Performance benchmarks
---
## Phase 14: Documentation
### Required Docs
- [ ] Package creation guide
- [ ] fakemui component guide
- [ ] Testing guide
- [ ] Permissions guide
- [ ] Multi-frontend guide
---
## Commands Reference
```bash
# Run tests
npm run test:unit
# Build project
npm run build
# Run E2E tests
npm run test:e2e
# Validate packages (when validator ready)
npm run validate:packages -- --all
# Check for leftover MUI imports
grep -r "@mui" frontends/nextjs/src --include="*.tsx"
```
---
## Completion Criteria
- [ ] Zero external UI dependencies
- [ ] 100% Lua type coverage
- [ ] All 43 packages pass validator
- [ ] 200+ parameterized test suites
- [ ] All tests passing
- [ ] Beautiful, polished UI
- [ ] Multi-frontend ready
- [ ] Documentation complete
- [ ] User notified 🎉
---
**Next Actions:**
1. Deploy subagents for parallel work
2. Add type annotations to packages
3. Add parameterized tests
4. Fill fakemui gaps
5. Run full verification

View File

@@ -1,425 +0,0 @@
# FakeMUI Icons Implementation Summary
## Overview
This document summarizes the implementation of fakemui icons integration into Lua packages, enabling declarative icon usage without direct React imports.
## What Was Implemented
### 1. Icon Registry System
**File:** `frontends/nextjs/src/lib/rendering/icon-registry.ts`
- Created centralized icon name resolution system
- Supports 390+ icons from fakemui library
- Provides flexible name resolution (PascalCase, kebab-case, lowercase)
- Includes 140+ common icon aliases for backwards compatibility
- Type-safe icon component retrieval
**Key Functions:**
```typescript
resolveIconName(luaIconName: string): IconName | undefined
getIconComponent(iconName: string): ComponentType | undefined
isValidIconName(iconName: string): boolean
getAllIconNames(): IconName[]
```
### 2. Component Registry Update
**File:** `frontends/nextjs/src/lib/rendering/component-registry.ts`
- Registered `Icon` component from `@/components/atoms/display/Icon`
- Enables Lua packages to use `type = "Icon"` in component trees
- Icon component accepts props: `name`, `size`, `className`, `style`, `sx`
### 3. Package-Specific Icon Modules
Created icon constant modules for each package with semantic naming:
#### Dashboard Package
**File:** `packages/dashboard/seed/scripts/icons.lua`
- Stats & analytics icons (CHART_LINE, TREND_UP, BAR_CHART, etc.)
- Status icons (CHECK_CIRCLE, WARNING, ERROR)
- Time icons (CLOCK, CALENDAR, SCHEDULE)
- User icons (USER, USERS, USER_CIRCLE)
#### Navigation Menu Package
**File:** `packages/nav_menu/seed/scripts/icons.lua`
- Navigation icons (HOME, DASHBOARD, MENU, SIDEBAR)
- Page icons (SETTINGS, PROFILE, USERS)
- Admin icons (ADMIN_PANEL, MANAGE_ACCOUNTS, SECURITY)
- Data icons (DATABASE, TABLE, LIST, GRID)
#### Data Table Package
**File:** `packages/data_table/seed/scripts/icons.lua`
- Sorting icons (SORT, SORT_ASCENDING, SORT_DESCENDING)
- Filtering icons (FILTER, FILTER_CLEAR, FILTER_OFF)
- Action icons (EDIT, DELETE, ADD, REMOVE)
- Export icons (CSV, JSON, DOWNLOAD, UPLOAD)
- Selection icons (CHECKBOX, SELECT_ALL, ROW_SELECT)
#### Workflow Editor Package
**File:** `packages/workflow_editor/seed/scripts/icons.lua`
- Workflow icons (WORKFLOW, GIT_BRANCH, CALL_SPLIT)
- Control icons (PLAY, STOP, PAUSE)
- Status icons (CHECK_CIRCLE, ERROR, WARNING)
- Tool icons (BUILD, CODE, TERMINAL)
- View icons (ZOOM_IN, ZOOM_OUT, FULLSCREEN)
#### Form Builder Package
**File:** `packages/form_builder/seed/scripts/icons.lua`
- Validation icons (CHECK_CIRCLE, ERROR, WARNING, INFO)
- Field type icons (TEXT_FIELDS, EMAIL, LOCK, CALENDAR)
- Visibility icons (VISIBILITY, VISIBILITY_OFF)
- File icons (ATTACH_FILE, INSERT_PHOTO, UPLOAD)
- Rich text icons (FORMAT_BOLD, FORMAT_ITALIC, INSERT_LINK)
### 4. Package Type Definition Updates
Updated Lua type definitions to include icon support:
**Dashboard:**
- `StatCardProps` now includes `icon?: string`
- Updated `stats/card.lua` to render icons when provided
**Navigation Menu:**
- `SidebarItem` now includes `icon?: string`
- Updated `sidebar.lua` to render icons in navigation items
**Data Table:**
- `Action` now includes `icon?: string`
- Updated `columns/action.lua` type definitions
**Workflow Editor:**
- `ActionNodeDefinition` now includes `icon?: string`
- Updated `nodes/action.lua` to accept icon parameter
**Form Builder:**
- `ValidationRule` now includes `icon?: string` for validation feedback
### 5. Example Files
Created comprehensive example files for each package:
- `packages/dashboard/seed/scripts/examples/stats_with_icons.lua`
- `packages/nav_menu/seed/scripts/examples/sidebar_with_icons.lua`
- `packages/data_table/seed/scripts/examples/table_with_icons.lua`
- `packages/workflow_editor/seed/scripts/examples/workflow_with_icons.lua`
- `packages/form_builder/seed/scripts/examples/form_with_icons.lua`
Each example demonstrates:
- Importing and using the icons module
- Creating components with icons
- Real-world usage patterns
- Best practices
### 6. Documentation
Created three documentation files:
#### Complete Integration Guide
**File:** `docs/fakemui-icons-integration.md`
- Architecture overview
- Detailed usage instructions
- All package icon modules documented
- Complete examples for each package
- Best practices and troubleshooting
- Type definitions and API reference
#### Quick Reference
**File:** `docs/fakemui-icons-quick-reference.md`
- Quick start guide
- Icon size reference
- All package icon constants listed
- Common patterns and examples
- Top 50 most useful icons
- Accessibility guidelines
#### Implementation Summary
**File:** `docs/FAKEMUI_ICONS_IMPLEMENTATION_SUMMARY.md` (this file)
- High-level overview of changes
- Files modified/created
- Testing recommendations
- Migration guide
## Files Created
### Frontend (TypeScript/React)
1. `frontends/nextjs/src/lib/rendering/icon-registry.ts` - Icon name resolution system
### Package Icon Modules (Lua)
2. `packages/dashboard/seed/scripts/icons.lua`
3. `packages/nav_menu/seed/scripts/icons.lua`
4. `packages/data_table/seed/scripts/icons.lua`
5. `packages/workflow_editor/seed/scripts/icons.lua`
6. `packages/form_builder/seed/scripts/icons.lua`
### Example Files (Lua)
7. `packages/dashboard/seed/scripts/examples/stats_with_icons.lua`
8. `packages/nav_menu/seed/scripts/examples/sidebar_with_icons.lua`
9. `packages/data_table/seed/scripts/examples/table_with_icons.lua`
10. `packages/workflow_editor/seed/scripts/examples/workflow_with_icons.lua`
11. `packages/form_builder/seed/scripts/examples/form_with_icons.lua`
### Documentation (Markdown)
12. `docs/fakemui-icons-integration.md`
13. `docs/fakemui-icons-quick-reference.md`
14. `docs/FAKEMUI_ICONS_IMPLEMENTATION_SUMMARY.md`
## Files Modified
### Frontend
1. `frontends/nextjs/src/lib/rendering/component-registry.ts`
- Added Icon component import
- Registered Icon in component registry
### Package Type Definitions (Lua)
2. `packages/dashboard/seed/scripts/stats/types.lua`
- Added `icon?: string` to StatCardProps
3. `packages/dashboard/seed/scripts/stats/card.lua`
- Updated to render icon when provided
4. `packages/nav_menu/seed/scripts/sidebar.lua`
- Added `icon?: string` to SidebarItem
- Updated item rendering to include icons
5. `packages/data_table/seed/scripts/columns/action.lua`
- Added `icon?: string` to Action type
6. `packages/workflow_editor/seed/scripts/nodes/action.lua`
- Added `icon?: string` to ActionNodeDefinition
- Updated function signature to accept icon parameter
7. `packages/form_builder/seed/scripts/validate/required.lua`
- Added `icon?: string` to ValidationRule
## How It Works
### 1. Lua Package Specifies Icon
```lua
local icons = require("icons")
local component = {
type = "Icon",
props = {
name = icons.get("DASHBOARD"), -- Returns "Dashboard"
size = "medium"
}
}
```
### 2. Component Registry Resolves Type
When the renderer encounters `type = "Icon"`, it looks up the Icon component in the component registry.
```typescript
// component-registry.ts
import { Icon } from '@/components/atoms/display/Icon'
componentRegistry = {
// ...
Icon,
}
```
### 3. Icon Component Resolves Name
The Icon component uses the icon registry to resolve the icon name to the actual fakemui icon component.
```typescript
// Icon.tsx
const IconComponent = FakeMuiIcons[name] // e.g., FakeMuiIcons["Dashboard"]
```
### 4. FakeMUI Icon Renders
The resolved fakemui icon component renders as an SVG.
```tsx
<Dashboard size={24} className="..." />
```
## Usage Patterns
### Pattern 1: Direct Icon Component
```lua
{
type = "Icon",
props = {
name = "CheckCircle",
size = "medium",
className = "text-green-500"
}
}
```
### Pattern 2: Button with Icon
```lua
{
type = "Button",
children = {
{ type = "Icon", props = { name = "Add", className = "mr-2" } },
{ type = "Typography", props = { text = "Add Item" } }
}
}
```
### Pattern 3: Icon in Component Props
```lua
local stat_card = require("stats.card")
stat_card.create({
label = "Revenue",
value = "$45,231",
icon = "ChartLine" -- Icon name in props
})
```
### Pattern 4: Using Package Icon Constants
```lua
local icons = require("icons")
local item = {
label = "Dashboard",
path = "/dashboard",
icon = icons.get("DASHBOARD") -- Type-safe constant
}
```
## Benefits
1. **Declarative** - Icons specified as simple strings in Lua
2. **Type-Safe** - Package icon modules provide semantic constants
3. **Flexible** - Supports multiple name formats (PascalCase, kebab-case, lowercase)
4. **Discoverable** - Icon constants documented per package
5. **Consistent** - All icons from single fakemui library
6. **No Imports** - Lua code doesn't need to know about React
7. **Extensible** - Easy to add new icons or aliases
## Testing Recommendations
### 1. Unit Tests
Test icon resolution:
```typescript
import { resolveIconName, isValidIconName } from './icon-registry'
describe('Icon Registry', () => {
it('resolves PascalCase names', () => {
expect(resolveIconName('CheckCircle')).toBe('CheckCircle')
})
it('resolves kebab-case aliases', () => {
expect(resolveIconName('check-circle')).toBe('CheckCircle')
})
it('validates icon names', () => {
expect(isValidIconName('CheckCircle')).toBe(true)
expect(isValidIconName('InvalidIcon')).toBe(false)
})
})
```
### 2. Integration Tests
Test Lua package icon usage:
```lua
-- Test dashboard icons
local icons = require("icons")
local stat_card = require("stats.card")
local card = stat_card.create({
label = "Test",
value = 100,
icon = icons.get("CHART_LINE")
})
assert(card.children[1].children[1].type == "Icon")
assert(card.children[1].children[1].props.name == "ChartLine")
```
### 3. Visual Tests
Render examples and verify icons display correctly:
- Dashboard stats with icons
- Sidebar navigation with icons
- Data table actions with icons
- Workflow nodes with icons
- Form validation icons
### 4. Manual Testing
1. Load each package example
2. Verify icons render correctly
3. Check icon sizes (small, medium, large)
4. Verify icon colors and styling
5. Test different icon name formats
## Migration Guide
### For Existing Packages
If you have existing packages using hardcoded icon names:
**Before:**
```lua
local component = {
icon = "dashboard" -- Lowercase, might not work
}
```
**After:**
```lua
local icons = require("icons")
local component = {
icon = icons.get("DASHBOARD") -- Type-safe constant
}
```
### For New Packages
1. Create `icons.lua` module with package-specific constants
2. Export common icons with semantic names
3. Create examples showing icon usage
4. Document available icons in package README
## Future Enhancements
Potential improvements:
1. **Icon Search Tool** - Build a UI to browse and search available icons
2. **Auto-completion** - IDE support for icon name completion in Lua
3. **Custom Icons** - Allow packages to register custom SVG icons
4. **Icon Variants** - Support outlined, filled, rounded variants
5. **Icon Packs** - Group related icons into themed packs
6. **Dynamic Loading** - Load icons on-demand for performance
7. **Icon Preview** - Generate visual catalog of all available icons
## Support
For questions or issues:
1. Check `docs/fakemui-icons-integration.md` for detailed documentation
2. Review `docs/fakemui-icons-quick-reference.md` for common patterns
3. See package examples in `packages/{package}/seed/scripts/examples/`
4. Browse available icons in `fakemui/icons/index.ts`
## Summary
The fakemui icons integration successfully enables Lua packages to use icons declaratively through:
- ✅ Icon registry for name resolution
- ✅ Component registry integration
- ✅ Package-specific icon constants
- ✅ Updated type definitions
- ✅ Comprehensive examples
- ✅ Complete documentation
All 5 reference packages (dashboard, nav_menu, data_table, workflow_editor, form_builder) now support icon usage with clear examples and documentation.

View File

@@ -1,416 +0,0 @@
# Fakemui Strategy - Zero Dependency UI System
**Created:** 2025-12-30
**Status:** Active Development
**Goal:** Complete UI independence with zero third-party UI dependencies
---
## Executive Summary
**Decision:** ✅ Full fakemui UI system
- Zero MUI dependencies
- Zero Phosphor Icons dependency
- Zero Emotion/styled-components
- Custom SVG icon system
- SCSS-based styling with CSS variables
**Bundle Size Target:** Reduce by 2-3 MB (15-25%)
---
## Architecture
```
fakemui/
├── icons/ # Custom SVG icon system (~1KB per icon)
│ ├── Icon.tsx # Base icon component
│ ├── Plus.tsx # Individual icon components
│ ├── Trash.tsx
│ └── ...
├── fakemui/ # React/TypeScript components
│ ├── inputs/ # Form inputs, buttons
│ ├── surfaces/ # Cards, papers, dialogs
│ ├── layout/ # Box, Stack, Grid, Container
│ ├── data-display/ # Typography, tables, lists
│ ├── feedback/ # Alerts, progress, skeletons
│ ├── navigation/ # Tabs, breadcrumbs, menus
│ ├── utils/ # Modals, portals, transitions
│ ├── atoms/ # Text, Label, Panel
│ ├── lab/ # Experimental components
│ └── x/ # Advanced components
├── styles/ # SCSS styling system
│ ├── _variables.scss # CSS custom properties
│ ├── base.scss # Base element styles
│ ├── components.scss # Component styles
│ ├── atoms/ # Atomic component styles
│ ├── global/ # Global styles, reset
│ ├── mixins/ # Reusable SCSS mixins
│ └── themes/ # Theme variants
└── index.ts # Barrel export
Total: ~150 components, ~80 SCSS files
```
---
## Icon Strategy
### ✅ APPROVED: Custom SVG System
**Approach:**
- Create SVG components as needed
- Source from Heroicons, Lucide, Phosphor
- ~1KB per icon (gzipped)
- Zero runtime dependencies
- Full TypeScript support
**Current Icons:** 332+ ✅✅ Far exceeds target!
**Target Phase 3:** 100+ ✅ ACHIEVED
**See:** [fakemui/icons/README.md](fakemui/icons/README.md)
---
## Component Migration Path
### From MUI → Fakemui
| MUI Component | Fakemui Replacement | Status |
|---------------|---------------------|--------|
| `@mui/material/Button` | `fakemui/inputs/Button` | ✅ Ready |
| `@mui/material/TextField` | `fakemui/inputs/TextField` | ✅ Ready |
| `@mui/material/Card` | `fakemui/surfaces/Card` | ✅ Ready |
| `@mui/material/Box` | `fakemui/layout/Box` | ✅ Ready |
| `@mui/material/Stack` | `fakemui/layout/Stack` | ✅ Ready |
| `@mui/material/Typography` | `fakemui/data-display/Typography` | ✅ Ready |
| `@mui/icons-material/*` | `fakemui/icons/*` | ✅ **332+ icons** |
| `@mui/x-data-grid` | Lua package or custom | ⏳ Planned |
| `@mui/x-date-pickers` | `fakemui/inputs/DatePicker` | ✅ **Ready** |
### From @mui/icons-material → Fakemui Icons
**Status: ✅ COMPLETE - All source code migrated!**
| Category | Icons Added | Examples |
|----------|-------------|----------|
| Navigation | 25+ | ChevronLeft, ChevronRight, FirstPage, LastPage, ExpandMore, ExpandLess, Menu |
| Actions | 20+ | Plus, Trash, Copy, Save, Edit, Delete, Close, Check, Clear |
| Status | 15+ | CheckCircle, ErrorOutline, WarningAmber, InfoOutlined, Cancel |
| File/Folder | 10+ | Folder, FolderOpen, File, Article, Description |
| Rich Text | 10+ | FormatBold, FormatItalic, FormatUnderline, FormatStrikethrough, FormatListBulleted |
| Date/Time | 5+ | DateRange, AccessTime, Calendar, Clock |
| Devices | 5+ | Smartphone, Tablet, Desktop |
| UI Controls | 15+ | Visibility, VisibilityOff, Search, FilterList, KeyboardArrowDown |
| Media | 10+ | PlayArrow, Pause, Stop, Volume, Camera, Video |
| Social | 10+ | Email, Chat, Send, ThumbUp, ThumbDown, Share |
| Security | 8+ | Lock, LockOpen, Key, Shield, Verified |
| Components | 15+ | TableChart, GridView, ViewColumn, ViewStream, ToggleOn, Checkbox |
### From Phosphor → Fakemui
| Phosphor Icon | Fakemui Icon | Status |
|---------------|--------------|--------|
| `<Plus />` | `<Plus />` | ✅ Done |
| `<Trash />` | `<Trash />` | ✅ Done |
| `<Copy />` | `<Copy />` | ✅ Done |
| `<ArrowUp />` | `<ArrowUp />` | ✅ Done |
| `<ArrowDown />` | `<ArrowDown />` | ✅ Done |
| `<ArrowClockwise />` | `<ArrowClockwise />` | ✅ Done |
| `<FloppyDisk />` | `<FloppyDisk />` | ✅ Done |
| Others (100+) | Add as needed | ⏳ Ongoing |
---
## Styling Strategy
### CSS Variables (Theme System)
**Current:** `fakemui/styles/_variables.scss`
- 70+ CSS custom properties
- 5 theme variants (light, dark, midnight, forest, ocean)
- Runtime theme switching
- No JavaScript required
**Example:**
```scss
:root {
--color-primary: #1976d2;
--color-bg: #ffffff;
--color-text: #000000;
--font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto;
--spacing-md: 16px;
--radius-md: 8px;
--shadow-sm: 0 2px 4px rgba(0,0,0,0.1);
}
```
### SCSS Modules
**Pattern:**
```tsx
// Component.tsx
import styles from './Component.module.scss'
export const Component = () => (
<div className={styles.root}>
<h2 className={styles.title}>Title</h2>
</div>
)
// Component.module.scss
.root {
padding: var(--spacing-md);
background: var(--color-bg-paper);
}
.title {
color: var(--color-text);
font-size: var(--font-size-lg);
}
```
### Reset (Replaces CssBaseline)
**Location:** `fakemui/styles/global/_reset.scss`
- Modern CSS reset
- Typography defaults
- Form element normalization
- Focus visible styles
- Accessibility defaults
---
## Import Strategy
### Before (MUI)
```tsx
import { Button, Card, Stack, Box } from '@mui/material'
import { Add, Delete, Edit } from '@mui/icons-material'
import { DataGrid } from '@mui/x-data-grid'
```
### After (Fakemui)
```tsx
import { Button, Card, Stack, Box, Plus, Trash, Edit } from '@/fakemui'
// DataGrid becomes Lua package
```
**Benefits:**
- Single import path
- No version conflicts
- Full control over API
- Tree-shakeable
- TypeScript native
---
## Lua Package Strategy
### Components → Lua Packages
**Workflow Editor:**
- Package: `@packages/workflow_editor`
- Components: WorkflowEditor, WorkflowNodeCard, WorkflowSidebar, etc.
- UI: Uses fakemui for basic components
**GitHub Viewer:**
- Package: `@packages/github_actions_viewer`
- Components: GitHubActionsFetcher, RunList, AnalysisPanel, etc.
- UI: Custom table with fakemui primitives
**Data Grid:**
- Package: `@packages/data_grid` (TBD)
- Replaces: `@mui/x-data-grid`
- Features: Sorting, filtering, pagination, virtual scrolling
**Date Picker:**
- Option 1: Native HTML5 `<input type="date">`
- Option 2: Lua package `@packages/date_picker`
- Decision: Start with native, create package if needed
---
## Migration Phases
### Phase 1: Foundation ✅ 75% Complete
- [x] Create fakemui icon system (27 icons)
- [x] Migrate LuaBlocksEditor
- [x] Enhance CSS reset
- [x] Document strategy
- [ ] Update providers (remove MUI)
- [ ] Finalize theme system
### Phase 2: Atomic Components 🚧 Ready
Target: 20 components
- Button, IconButton, Fab
- Input, Textarea, Select
- Checkbox, Radio, Switch, Slider
- Avatar, Badge, Icon, Label, Link, Text
- Skeleton, Spinner, Progress, Tooltip, Separator
### Phase 3: Molecules ⏳ Planned
Target: 18 components
- Card, Alert, Accordion
- Breadcrumb, NavGroup, NavItem, NavLink
- Dialog, DropdownMenu, Popover
- RadioGroup, Select, ToggleGroup
- Tabs components
### Phase 4: Organisms ⏳ Planned
Target: 22 components
- Navigation, Sidebar, Pagination
- AlertDialog, Command, Sheet
- Form, Table
### Phase 5: Lua Packages ⏳ Planned
- workflow_editor
- github_actions_viewer
- (others as needed)
### Phase 6: Cleanup ⏳ Planned
- Remove all MUI dependencies
- Remove Phosphor dependency
- Final verification
---
## Performance Targets
### Bundle Size
| Phase | Current | Target | Savings |
|-------|---------|--------|---------|
| Before | ~12 MB | - | - |
| After Phase 1 | ~11.5 MB | ~11.5 MB | 500 KB |
| After Phase 2 | ~11 MB | ~10.5 MB | 1.5 MB |
| After Phase 3 | ~10 MB | ~9.5 MB | 2.5 MB |
### Load Time
- First Contentful Paint (FCP): < 1.5s
- Largest Contentful Paint (LCP): < 2.5s
- Time to Interactive (TTI): < 3.5s
### Runtime Performance
- Zero styled-components runtime overhead
- No Emotion runtime
- Pure CSS for styling
- Minimal JavaScript
---
## Developer Experience
### Type Safety
```tsx
import { Button, ButtonProps } from '@/fakemui'
// Full TypeScript support
const MyButton: React.FC<ButtonProps> = (props) => (
<Button {...props} primary />
)
```
### Customization
```tsx
// CSS variables for theming
<Button style={{ '--color-primary': 'red' }} />
// Class names for custom styling
<Button className="my-custom-button" />
// SCSS modules
<Button className={styles.customButton} />
```
### Documentation
- Component props in TypeScript
- README for icon system
- Migration guides
- Code examples
---
## Success Metrics
**Technical:**
- Zero `@mui/*` imports
- Zero `@phosphor-icons/react` imports
- Zero `@emotion/*` imports
- 100% TypeScript coverage
- All tests passing
- No build errors
**Performance:**
- 15-25% bundle size reduction
- Maintained or improved load times
- No visual regressions
- Accessibility maintained
**Developer:**
- Simple import pattern
- Easy to extend
- Well documented
- Type-safe
---
## Risk Mitigation
### Testing Strategy
1. Unit tests for all components
2. Visual regression tests
3. Integration tests
4. E2E tests
5. Performance benchmarks
### Rollback Plan
```bash
# Create backup branch
git checkout -b mui-backup
# If issues arise
git checkout mui-backup
npm install
```
### Staged Migration
- Keep MUI installed during migration
- Migrate page by page or component by component
- Feature flags for new components
- Gradual rollout
---
## Next Actions
**Immediate:**
1. ✅ Approve icon strategy (DONE)
2. Update app providers to remove MUI
3. Start Phase 2: Atomic components
**This Week:**
1. Migrate Button component
2. Migrate Input component
3. Add 10 more icons
**This Month:**
1. Complete Phase 2 (atoms)
2. Start Phase 3 (molecules)
3. Create first Lua package
---
## References
- [MUI_ELIMINATION_PLAN.md](MUI_ELIMINATION_PLAN.md) - Detailed migration plan
- [DEPENDENCY_CLEANUP.md](DEPENDENCY_CLEANUP.md) - Package.json cleanup
- [fakemui/icons/README.md](fakemui/icons/README.md) - Icon system guide
- [fakemui/SCSS_REVIEW.md](fakemui/SCSS_REVIEW.md) - SCSS architecture review
- [fakemui/TYPESCRIPT_MIGRATION.md](fakemui/TYPESCRIPT_MIGRATION.md) - TypeScript patterns
---
**Last Updated:** 2025-12-30
**Status:** Active - Phase 1 in progress
**Next Review:** After Phase 2 completion

View File

@@ -1,656 +0,0 @@
# MetaBuilder Implementation Breakdown
**Comprehensive Phase-by-Phase Modernization Plan**
**Created:** 2025-12-30
**Status:** Active Execution (Phase 9+ Complete)
**Goal:** Complete modernization - MUI → fakemui, TSX → Lua packages, Beautiful UI
---
## Executive Summary
### Current State (Updated 2025-12-30)
-**44 Lua packages** with full type annotations (LuaCATS) - css_designer added!
-**421+ fakemui icons** (zero dependency custom SVG system)
-**155+ fakemui components** (React + QML dual platform)
-**DataGrid & DatePicker** added to fakemui/x
-**127+ parameterized test files** across packages
-**MUI eliminated from source code** (100% in imports)
-**MUI removed from package.json** (dependencies gone!)
-**Permissions system** fully implemented in shared/permissions/
-**CSS Designer package** complete with colors, fonts, spacing, borders, shadows, export
### Target State
-**Zero external UI dependencies** (@mui, @phosphor-icons) - COMPLETE
- **Beautiful, delightful UI** powered by fakemui
- **All user-facing UI in Lua packages**
-**Permissions system** for package/component control - COMPLETE
- **Parameterized testing** for all packages
-**Type-annotated** Lua codebase (95%+)
- **Package validator** passing for all packages
- **Multi-frontend support** (React, Qt6/QML, CLI)
---
## Phase Breakdown (14 Micro-Phases)
### ✅ PHASE 1: fakemui Component & Icon Gaps [COMPLETE]
**Goal:** Fill remaining gaps in fakemui library
**Status:** ✅ Complete
#### 1.1 Missing Components
- ✅ ToggleButtonGroup exists in fakemui/inputs
- ✅ LoadingButton exists in fakemui/lab
- ✅ DataGrid added to fakemui/x
- ✅ DatePicker/TimePicker added to fakemui/x
- [ ] VirtualList (optional - low priority)
#### 1.2 Icon Expansion
-**421+ icons** available
- ✅ Add icons on-demand as TSX conversion reveals needs
#### 1.3 Monaco & Markdown Integration
- ✅ Monaco wrapper exists in code_editor package
- ✅ Markdown component exists (uses 'marked')
---
### ✅ PHASE 2: Add Type Comments to All Lua Files [COMPLETE]
**Goal:** 100% LuaCATS type annotation coverage
**Status:** ✅ Complete (95%+)
- ✅ All 44 packages have types.lua
- ✅ Inline type comments present in most files
- ✅ LuaCATS annotations throughout codebase
- Files > 200 lines
- Files with multiple unrelated functions
- Monolithic init.lua files
**Pattern:**
```
scripts/
├── init.lua # Package initialization only
├── types.lua # Type definitions only
├── render.lua # renderComponent() only
├── validate.lua # validateProps() only
└── helpers/
├── format.lua # formatValue() only
└── parse.lua # parseInput() only
```
#### 3.2 Update Exports
- [ ] Update components.json scripts references
- [ ] Verify all exports remain functional
- [ ] Update tests to match new structure
**Deliverables:**
- [ ] All files < 150 lines (target)
- [ ] 1-3 functions per file maximum
- [ ] Clear file naming conventions
---
### 🎨 PHASE 4: fakemui Enhancements [4-8 hours]
**Goal:** Upgrade components, add icons, improve styling
**Priority:** Medium-High (user delight)
#### 4.1 Component Upgrades
- [ ] Add micro-interactions (hover, focus states)
- [ ] Improve accessibility (ARIA labels, keyboard nav)
- [ ] Add animation polish (transitions, loading states)
- [ ] Enhance error states (clear messaging)
#### 4.2 Icon Additions
- [ ] Create icon request process
- [ ] Add icons as TSX conversion reveals needs
- [ ] Maintain icon naming conventions
#### 4.3 Styling Polish
- [ ] Review all SCSS modules (64 files)
- [ ] Ensure consistent spacing/sizing
- [ ] Add dark mode refinements
- [ ] Test all 5 theme variants
#### 4.4 Documentation
- [ ] Component showcase page (Storybook-like)
- [ ] Usage examples for each component
- [ ] Accessibility guide
**Deliverables:**
- [ ] Beautiful, polished components
- [ ] Comprehensive icon library (500+ target)
- [ ] Component documentation complete
---
### 🔐 PHASE 5: Permissions System [4-8 hours]
**Goal:** Enable/disable packages and components, minLevel enforcement
**Priority:** High (security & flexibility)
#### 5.1 Permission Types
```lua
---@class PackagePermissions
---@field enabled boolean Package enabled/disabled
---@field minLevel PermissionLevel (0-6)
---@field databaseRequired boolean Needs DB connection
---@field components table<string, ComponentPermission>
---@class ComponentPermission
---@field enabled boolean Component enabled/disabled
---@field minLevel PermissionLevel
---@field featureFlags string[] Required feature flags
```
#### 5.2 Implementation
- [ ] Create `permissions.lua` in shared package
- [ ] Update package renderer to check permissions
- [ ] Add database toggle support
- [ ] Add component-level toggles
- [ ] Create permission management UI
#### 5.3 Database Control
- [ ] Add `databaseRequired` flag to metadata.json
- [ ] Implement database on/off toggle
- [ ] Handle graceful degradation when DB off
**Deliverables:**
- [ ] Working permissions system
- [ ] Database toggle functional
- [ ] Component on/off switches working
- [ ] minLevel enforcement in renderer
---
### 🧹 PHASE 6: Dependency Cleanup [1-2 hours]
**Goal:** Remove all MUI, Emotion, Phosphor dependencies
**Priority:** High (already ready to execute)
#### 6.1 Remove from package.json
```bash
cd frontends/nextjs
npm uninstall @mui/material @mui/icons-material
npm uninstall @mui/x-data-grid @mui/x-date-pickers
npm uninstall @emotion/react @emotion/styled
npm uninstall @phosphor-icons/react
```
#### 6.2 Verify Removal
- [ ] `npm run build` succeeds
- [ ] `npm run typecheck` passes
- [ ] `npm run test:unit` passes
- [ ] Bundle size reduced 2-3 MB
#### 6.3 Update Documentation
- [ ] Update README with new dependencies
- [ ] Document fakemui usage
**Deliverables:**
- [ ] 7 dependencies removed
- [ ] Build successful
- [ ] Bundle size reduced 15-25%
---
### 🔄 PHASE 7: TSX → Lua Package Conversion (Part 1) [8-16 hours]
**Goal:** Convert high-value TSX components to Lua packages
**Priority:** High (reduces framework code, increases flexibility)
#### 7.1 Workflow Editor → workflow_editor package
**Files:** 8 TSX files
- [ ] Enhance existing package structure
- [ ] Create component definitions (components.json)
- [ ] Implement visual node editor
- [ ] Add drag & drop support
- [ ] Wire to frontend renderer
- [ ] Delete TSX files
#### 7.2 Schema Editor → schema_editor package
**Files:** ~10 TSX files
- [ ] Enhance existing package
- [ ] Create table/field editors
- [ ] Add relationship editor
- [ ] DBAL integration
- [ ] Wire to frontend renderer
- [ ] Delete TSX files
#### 7.3 Form Builder → form_builder package
**Files:** ~15 TSX files
- [ ] Add missing field types (date, color, file)
- [ ] Enhance validation
- [ ] Add conditional logic
- [ ] Wire to frontend renderer
- [ ] Delete TSX files
**Deliverables:**
- [ ] 3 major packages converted
- [ ] ~33 TSX files removed
- [ ] All functionality preserved
---
### 🔄 PHASE 8: TSX → Lua Package Conversion (Part 2) [8-16 hours]
**Goal:** Convert remaining complex TSX to Lua packages
#### 8.1 Nerd IDE → nerd_ide package
**Files:** ~20 TSX files
- [ ] Create package structure
- [ ] Implement file tree
- [ ] Add code panel (Monaco integration)
- [ ] Add console/terminal
- [ ] Wire to frontend renderer
- [ ] Delete TSX files
#### 8.2 Component Managers → Multiple packages
**Files:** ~50 TSX files
- [ ] component_builder package
- [ ] css_manager package
- [ ] dropdown_manager package
- [ ] package_manager package
- [ ] routes_manager package
- [ ] Wire to frontend renderer
- [ ] Delete TSX files
**Deliverables:**
- [ ] 6 new packages created
- [ ] ~70 TSX files removed
- [ ] All manager functionality in Lua
---
### 🎨 PHASE 9: CSS Designer Package [4-8 hours]
**Goal:** Enable style overlays via Lua package
**Priority:** Medium (user customization)
#### 9.1 Create css_designer Package
```
packages/css_designer/
├── metadata.json
├── components.json
└── scripts/
├── init.lua
├── types.lua
├── parser.lua # Parse CSS
├── generator.lua # Generate styles
├── color_picker.lua # Color selection UI
└── style_editor.lua # Visual style editor
```
#### 9.2 Features
- [ ] Visual color picker
- [ ] Font family selection
- [ ] Spacing adjustments
- [ ] Border radius controls
- [ ] Shadow editor
- [ ] Export to SCSS
#### 9.3 Database Integration
- [ ] Store custom styles in DB
- [ ] Load user styles on init
- [ ] Apply style overlays to fakemui
**Deliverables:**
- [ ] css_designer package complete
- [ ] Visual style editor working
- [ ] Database-driven styling functional
---
### 🧪 PHASE 10: Parameterized Tests for All Packages [4-8 hours]
**Goal:** 100% test coverage with data-driven tests
**Priority:** High (quality & reliability)
#### 10.1 Test Template
```lua
-- tests/module.test.lua
local test = require("lua_test")
local module = require("../module")
test.describe("Module Tests", function()
test.it.each("test_cases")("should $description", function(case)
local result = module.function(case.input)
test.expect(result).toEqual(case.expected)
end)
end)
```
```json
// tests/module.cases.json
{
"test_cases": [
{
"description": "handle valid input",
"input": { "value": 42 },
"expected": { "result": 84 }
}
]
}
```
#### 10.2 Per-Package Test Creation
- [ ] Audit existing test coverage (127 test files)
- [ ] Add tests to packages missing them
- [ ] Convert inline data to .cases.json
- [ ] Ensure all exports have tests
#### 10.3 Test Categories
- [ ] Unit tests (functions)
- [ ] Integration tests (components)
- [ ] Permission tests (access control)
- [ ] Validation tests (schema checks)
**Deliverables:**
- [ ] All 43 packages have tests
- [ ] 200+ parameterized test suites
- [ ] 80%+ code coverage
---
### ✅ PHASE 11: Package Validator Compliance [2-4 hours]
**Goal:** All packages pass validator checks
**Priority:** High (quality gate)
#### 11.1 Run Validator
```bash
npm run validate:packages -- --all
```
#### 11.2 Fix Common Issues
- [ ] Missing metadata.json fields
- [ ] Invalid component types
- [ ] Missing exports in scripts/
- [ ] Circular dependencies
- [ ] Invalid semver versions
- [ ] Missing types.lua
- [ ] Missing tests/
#### 11.3 Per-Package Validation
- [ ] Verify all 43 packages pass
- [ ] Document any exceptions
- [ ] Create validation pre-commit hook
**Deliverables:**
- [ ] 100% packages pass validator
- [ ] Validation automated in CI/CD
- [ ] Quality standards enforced
---
### 🖥️ PHASE 12: Multi-Frontend Support [8-16 hours]
**Goal:** Make packages work with Qt6/QML and CLI frontends
**Priority:** Medium (future-proofing)
#### 12.1 Abstract Rendering Layer
```lua
---@class RenderTarget
---@field type "react"|"qt6"|"cli"
---@field capabilities table<string, boolean>
---@class AbstractComponent
---@field render fun(target: RenderTarget): any
```
#### 12.2 Qt6/QML Integration
- [ ] Create QML component mappings
- [ ] Test fakemui QML components (104 exist)
- [ ] Verify package compatibility
- [ ] Create QML-specific layouts
#### 12.3 CLI Frontend
- [ ] Create CLI component mappings
- [ ] Implement text-based UI
- [ ] Handle input/output
- [ ] Test package compatibility
#### 12.4 Generic Package Design
- [ ] Review packages for platform assumptions
- [ ] Refactor to be platform-agnostic
- [ ] Document platform-specific code
**Deliverables:**
- [ ] Qt6/QML frontend working
- [ ] CLI frontend working
- [ ] Packages work across all 3 frontends
---
### 🧪 PHASE 13: Verification & Playwright Tests [4-8 hours]
**Goal:** Verify app renders correctly with Lua packages
**Priority:** High (final quality check)
#### 13.1 Playwright E2E Tests
```typescript
// test/e2e/packages.spec.ts
test.describe('Package Rendering', () => {
const packages = ['audit_log', 'github_tools', 'workflow_editor', ...]
for (const pkg of packages) {
test(`${pkg} renders correctly`, async ({ page }) => {
await page.goto(`/packages/${pkg}`)
await expect(page.locator('[data-package]')).toBeVisible()
await expect(page.locator('[data-error]')).not.toBeVisible()
})
}
})
```
#### 13.2 Gradual Package Enable
- [ ] Start with 1 package enabled
- [ ] Test rendering
- [ ] Enable next package
- [ ] Repeat for all 43 packages
#### 13.3 Smoke Tests
1. shared (types only)
2. lua_test (testing framework)
3. ui_auth (authentication)
4. ui_home (landing page)
5. dashboard (main dashboard)
6. ... all remaining packages
#### 13.4 Visual Regression
- [ ] Screenshot comparison
- [ ] Component snapshot tests
- [ ] Theme variant tests
**Deliverables:**
- [ ] All 43 packages render successfully
- [ ] E2E tests passing
- [ ] Visual regression suite complete
- [ ] No critical bugs
---
### 📝 PHASE 14: Documentation & Completion [2-4 hours]
**Goal:** Finalize documentation, notify completion
**Priority:** Medium (knowledge transfer)
#### 14.1 Package Documentation
- [ ] README for each package
- [ ] API documentation (types)
- [ ] Usage examples
- [ ] Configuration guides
#### 14.2 Developer Guides
- [ ] Creating new Lua packages guide
- [ ] fakemui component guide
- [ ] Testing guide (parameterized tests)
- [ ] Permissions system guide
- [ ] Multi-frontend guide
#### 14.3 Architecture Docs
- [ ] Update architecture diagrams
- [ ] Document package system
- [ ] Document fakemui framework
- [ ] Document type system
#### 14.4 Migration Summary
- [ ] Before/after metrics
- [ ] Bundle size reduction
- [ ] Performance improvements
- [ ] Dependency cleanup summary
#### 14.5 Completion Notification
- [ ] Generate completion report
- [ ] Notify user (you!)
- [ ] Celebrate! 🎉
**Deliverables:**
- [ ] Complete documentation suite
- [ ] Developer onboarding guide
- [ ] Project completion report
- [ ] User notified
---
## Execution Strategy
### Parallel Work (Use Subagents)
- **Type annotation** (Phase 2) + **Package structure** (Phase 3) can run in parallel
- **fakemui enhancements** (Phase 4) + **Permissions** (Phase 5) can run in parallel
- **TSX conversion** (Phases 7-8) can be split across multiple agents (1 package per agent)
### Sequential Work
- Phase 1 → Phase 6 (foundation before cleanup)
- Phase 6 → Phase 7 (cleanup before conversion)
- Phase 13 → Phase 14 (verify before document)
### Quality Gates
After each phase:
1. Run package validator
2. Run all tests
3. Build successfully
4. Visual smoke test
---
## Progress Tracking
### Overall Progress
- **Phases Complete:** 0/14 (0%)
- **fakemui Components:** 155/155 (100%)
- **fakemui Icons:** 421+ (exceeds target)
- **Lua Packages:** 43/43 exist
- **Type Coverage:** 76/43 packages (100%)
- **Test Coverage:** 127 test files (good, needs expansion)
- **MUI Eliminated:** Source code ✅, package.json ⏳
### Phase Checklist
- [ ] Phase 1: fakemui Gaps
- [ ] Phase 2: Type Comments (100%)
- [ ] Phase 3: Package Structure Refinement
- [ ] Phase 4: fakemui Enhancements
- [ ] Phase 5: Permissions System
- [ ] Phase 6: Dependency Cleanup
- [ ] Phase 7: TSX → Lua (Part 1)
- [ ] Phase 8: TSX → Lua (Part 2)
- [ ] Phase 9: CSS Designer Package
- [ ] Phase 10: Parameterized Tests (All)
- [ ] Phase 11: Package Validator (100%)
- [ ] Phase 12: Multi-Frontend Support
- [ ] Phase 13: Verification & E2E
- [ ] Phase 14: Documentation & Notify
---
## Key Principles
### 1 Function Per File (Where Practical)
**Good:**
```
scripts/
├── render.lua # renderComponent()
├── validate.lua # validateProps()
└── format.lua # formatValue()
```
**Avoid:**
```
scripts/
└── utils.lua # 20 unrelated functions
```
### Type Everything
```lua
---@param value string The input value
---@return boolean is_valid
local function validate(value)
return #value > 0
end
```
### Test Everything
```lua
test.it("should validate non-empty strings", function()
test.expect(validate("hello")).toBe(true)
test.expect(validate("")).toBe(false)
end)
```
### Beautiful UI
- Micro-interactions (hover, focus, active states)
- Smooth transitions
- Clear feedback
- Accessible (keyboard nav, ARIA labels)
- Delightful (animations, polish)
---
## Success Criteria
### Technical
- ✅ Zero @mui/* imports
- ✅ Zero @phosphor-icons/* imports
- ✅ 100% Lua type coverage
- ✅ All 43 packages pass validator
- ✅ 200+ parameterized test suites
- ✅ All tests passing
- ✅ Bundle size reduced 15-25%
### User Experience
- ✅ Beautiful, polished UI
- ✅ Smooth animations
- ✅ Fast load times
- ✅ Accessible interface
- ✅ Delightful interactions
### Architecture
- ✅ Small, focused Lua files (1 function per file ideal)
- ✅ Clear separation of concerns
- ✅ Multi-frontend ready
- ✅ Permissions system functional
- ✅ Well-documented codebase
---
## Quick Reference Commands
```bash
# Run all package tests
npm run test:packages
# Validate all packages
npm run validate:packages -- --all
# Check for MUI imports (should be zero)
grep -r "@mui/material" frontends/nextjs/src --include="*.tsx"
# Build and verify
npm run build
# Run E2E tests
npm run test:e2e
# Remove dependencies (Phase 6)
cd frontends/nextjs
npm uninstall @mui/material @mui/icons-material @mui/x-data-grid @mui/x-date-pickers @emotion/react @emotion/styled @phosphor-icons/react
# Verify bundle size
npm run build
# Check .next/static/chunks/ sizes
```
---
**Last Updated:** 2025-12-30
**Status:** Ready to Execute
**Next:** Begin Phase 1 (fakemui Gaps)

View File

@@ -1,440 +0,0 @@
# MetaBuilder Master Migration Plan
**Comprehensive Phased Approach to UI Independence**
**Created:** 2025-12-30
**Updated:** 2025-12-30
**Status:** Active Development - Major Progress!
**Owner:** Automated Migration System
---
## Executive Summary
| Area | Current State | Target State |
|------|---------------|--------------|
| @mui/material | ✅ **ELIMINATED** | ✅ Complete |
| @mui/icons-material | ✅ **ELIMINATED** | ✅ Complete |
| @phosphor-icons/react | ✅ **ELIMINATED** | ✅ Complete |
| @emotion/react | ✅ **ELIMINATED** | ✅ Complete |
| fakemui icons | 357+ icons | ✅ Complete |
| fakemui components | ~180 components | ✅ Full MUI parity |
| Lua packages typed | ✅ All 43 packages | ✅ Complete |
| Lua packages tested | 43/43 packages | ✅ Complete |
| Package validation | ✅ All exports match | ✅ Complete |
| Dependencies | **7 removed from package.json** | ✅ Complete |
### Progress Today (2025-12-30)
-**100+ TSX files migrated** from @mui/material to fakemui
-**All source code MUI-free** - Zero `@mui/material` imports remain
-**Theme system converted** - CSS custom properties instead of MUI theming
-**Missing tests added** - shared, config_summary, lua_test packages
-**ToggleButtonGroup enhanced** - Full value management, exclusive mode
-**40+ SCSS modules created** - Converted sx props to CSS modules
-**14 packages fixed** - Added declarative component definitions
-**7 dependencies removed** - @mui/*, @emotion/*, @phosphor-icons
---
## Phase Overview (12 Micro-Phases)
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ PHASE 1: Missing Tests ✅ COMPLETE │
│ - Add tests to shared, config_summary, lua_test │
│ - Ensure all test files have .cases.json parameterized data │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 2: Fakemui Component Gaps ✅ COMPLETE │
│ - Add ToggleButtonGroup wrapper │
│ - Add missing utility components (VirtualList, etc.) │
│ - Ensure all MUI equivalents exist │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 3: Frontends MUI Elimination ✅ COMPLETE │
│ - Migrate 100+ files from @mui/material to fakemui │
│ - Update workflow/* components │
│ - Update ui/molecules/* components │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 4: Fakemui Icons Expansion ✅ COMPLETE │
│ - 357+ icons available │
│ - All common MUI icons covered │
│ - Icon naming conventions documented │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 5: Package Validator Compliance ✅ COMPLETE │
│ - Fixed 14 packages with empty components.json │
│ - All packages now pass export/component validation │
│ - Added declarative component definitions │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 6: Lua Package Permissions System [Hours: 4-8] │
│ - Add database toggle to packages │
│ - Add component on/off switches │
│ - Implement minLevel enforcement in renderer │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 7: CSS/Style System via Lua [Hours: 4-8] │
│ - Create css_designer Lua package │
│ - Enable style overlays via seed data │
│ - Theme customization via database │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 8: Legacy TSX to Lua Conversion [Hours: 8-16] │
│ - Convert hardcoded TSX to Lua packages │
│ - Create new packages as needed │
│ - Wire components to Lua renderer │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 9: Monaco/Markdown Fakemui Integration [Hours: 4-8] │
│ - Create Monaco wrapper in fakemui │
│ - Create Markdown renderer in fakemui │
│ - Reduce external dependencies │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 10: Multi-Frontend Support [Hours: 8-16] │
│ - Qt6/QML powered by generic packages │
│ - CLI frontend integration │
│ - Abstract package rendering layer │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 11: Dependency Cleanup ✅ COMPLETE │
│ - Removed @mui/material, @mui/icons-material │
│ - Removed @mui/x-data-grid, @mui/x-date-pickers │
│ - Removed @emotion/react, @emotion/styled │
│ - Removed @phosphor-icons/react │
├─────────────────────────────────────────────────────────────────────────────┤
│ PHASE 12: Verification & Polish [Hours: 4-8] │
│ - Playwright E2E tests │
│ - Enable packages one at a time │
│ - Final cleanup and documentation │
│ - Notify completion │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## Phase 1: Missing Tests (3 packages)
### 1.1 shared package
**Status:** ❌ No tests
**Path:** `packages/shared/seed/scripts/`
```
Create:
├── tests/
│ ├── types.test.lua # Test type definitions work
│ └── types.cases.json # Parameterized test data
```
### 1.2 config_summary package
**Status:** ❌ Empty tests folder
**Path:** `packages/config_summary/seed/scripts/tests/`
```
Create:
├── config.test.lua # Test config summary functions
└── config.cases.json # Parameterized test data
```
### 1.3 lua_test package
**Status:** ⚠️ Examples only, no formal tests/
**Path:** `packages/lua_test/seed/scripts/`
```
Create:
├── tests/
│ ├── framework.test.lua # Test the test framework itself
│ └── framework.cases.json # Parameterized test data
```
---
## Phase 2: Fakemui Component Gaps
### Currently Missing Components (compared to MUI)
| Component | MUI Equivalent | Priority | Status |
|-----------|----------------|----------|--------|
| ToggleButtonGroup | ToggleButtonGroup | High | ❌ Need |
| VirtualList | Virtuoso/react-window | Medium | ❌ Need |
| TransferList | TransferList | Low | Optional |
| DataGrid | @mui/x-data-grid | Medium | Lua pkg |
| DesktopDatePicker | @mui/x-date-pickers | Done | ✅ |
| Masonry | Masonry | Low | Optional |
| LoadingButton | LoadingButton | Medium | ❌ Need |
### Components to Add
```typescript
// fakemui/inputs/ToggleButtonGroup.tsx
// fakemui/inputs/LoadingButton.tsx
// fakemui/data-display/VirtualList.tsx
```
---
## Phase 3: Frontends MUI Elimination
### Files Still Using @mui/material (20+ files)
#### Workflow Components (6 files)
- [ ] `workflow/WorkflowEditor.tsx`
- [ ] `workflow/WorkflowRunCard.tsx`
- [ ] `workflow/WorkflowRunStatus.tsx`
- [ ] `workflow/editor/WorkflowSidebar.tsx`
- [ ] `workflow/editor/WorkflowTester.tsx`
#### UI Molecules (14+ files)
- [ ] `ui/molecules/selection/ToggleGroup.tsx`
- [ ] `ui/molecules/selection/Select.tsx`
- [ ] `ui/molecules/selection/RadioGroup.tsx`
- [ ] `ui/molecules/overlay/DropdownMenu.tsx`
- [ ] `ui/molecules/overlay/DropdownMenu/MenuItem.tsx`
- [ ] `ui/molecules/overlay/Popover.tsx`
- [ ] `ui/molecules/overlay/Tooltip.tsx`
- [ ] `ui/molecules/overlay/Dialog.tsx`
- [ ] `ui/molecules/display/Card.tsx`
- [ ] `ui/molecules/display/Alert.tsx`
- [ ] `ui/molecules/tabs/core/Tabs.tsx`
- [ ] `ui/molecules/tabs/components/TabsContent.tsx`
#### Library Files
- [ ] `lib/lua/ui/generate-component-tree.tsx`
---
## Phase 4: Icon Expansion
### Target Icons to Add
Based on common MUI icons not yet in fakemui:
```
Editor:
- [ ] Spellcheck ✅
- [ ] Superscript ✅
- [ ] Subscript ✅
Status:
- [ ] HourglassEmpty ✅
- [ ] HourglassFull ✅
- [ ] Pending ✅
- [ ] PendingActions ✅
- [ ] PublishedWithChanges ✅
Charts:
- [ ] DonutLarge ✅
- [ ] DonutSmall ✅
- [ ] StackedBarChart ✅
- [ ] StackedLineChart ✅
- [ ] TrendDown ✅
- [ ] TrendingFlat ✅
Communication:
- [ ] Forum ✅
- [ ] Comment ✅
- [ ] CommentOutlined ✅
- [ ] Announcement ✅
- [ ] Campaign ✅
```
**Note:** Many of these may already exist - audit needed.
---
## Phase 5: Package Validator Compliance
### Validation Checklist Per Package
```bash
# Run validator
npm run validate:packages
# Expected checks:
✓ Valid metadata.json with required fields
✓ components.json array structure
✓ All exported scripts exist
✓ All component types are valid
✓ No circular dependencies
✓ Version follows semver
✓ minLevel in valid range (0-6)
✓ types.lua present
✓ Test files present
```
---
## Phase 6: Lua Package Permissions System
### Permission Configuration Schema
```lua
---@class PackagePermissions
---@field minLevel PermissionLevel Minimum level to access package
---@field databaseRequired boolean Whether package needs database
---@field components table<string, ComponentPermission> Per-component permissions
---@class ComponentPermission
---@field enabled boolean Whether component is enabled
---@field minLevel PermissionLevel Minimum level for this component
---@field featureFlags string[] Required feature flags
```
### Implementation Plan
1. Add `permissions.lua` to shared package
2. Update renderer to check permissions before rendering
3. Add database toggle support
4. Add component-level on/off switches
---
## Phase 7: CSS/Style System via Lua
### css_designer Package Structure
```
packages/css_designer/
├── seed/
│ ├── metadata.json
│ ├── components.json
│ └── scripts/
│ ├── init.lua
│ ├── types.lua
│ ├── parser/
│ │ └── css_parser.lua
│ ├── generator/
│ │ └── style_generator.lua
│ └── ui/
│ ├── color_picker.lua
│ └── style_editor.lua
```
---
## Phase 8: Legacy TSX to Lua Conversion
### High-Priority Conversions
| TSX Component | Target Lua Package | Status |
|---------------|-------------------|--------|
| WorkflowEditor | workflow_editor | ⏳ |
| GitHubActionsFetcher | github_tools | ✅ Package exists |
| SchemaEditor | schema_editor | ✅ Package exists |
| FormBuilder | form_builder | ✅ Package exists |
---
## Phase 9: Monaco/Markdown Fakemui
### Monaco Wrapper
```typescript
// fakemui/editors/MonacoEditor.tsx
// Wrapper around @monaco-editor/react with fakemui styling
```
### Markdown Component
```typescript
// fakemui/data-display/Markdown.tsx ✅ Already exists!
// Uses 'marked' library internally
```
---
## Phase 10: Multi-Frontend Support
### Abstract Rendering Layer
```lua
---@class RenderTarget
---@field type "react"|"qt6"|"cli" Target platform
---@field capabilities table<string, boolean> Available features
---@class AbstractComponent
---@field render fun(target: RenderTarget): any Platform-specific render
```
---
## Phase 11: Dependency Cleanup
### Dependencies to Remove
```json
{
"remove": [
"@emotion/react",
"@emotion/styled",
"@mui/material",
"@mui/icons-material",
"@mui/x-data-grid",
"@mui/x-date-pickers",
"@phosphor-icons/react"
]
}
```
### Estimated Savings
- Bundle size: -2-3 MB
- Build time: -10-20%
- Dependency tree: -50+ packages
---
## Phase 12: Verification
### Playwright E2E Tests
```typescript
// Test each package renders correctly
test.describe('Package Rendering', () => {
for (const pkg of packages) {
test(`${pkg.name} renders`, async ({ page }) => {
await page.goto(`/packages/${pkg.name}`)
await expect(page.locator('[data-package]')).toBeVisible()
})
}
})
```
### Smoke Test Order
1. ✅ shared (types only)
2. ✅ lua_test (testing framework)
3. ui_auth (authentication)
4. ui_home (landing page)
5. dashboard (main dashboard)
6. ... remaining packages
---
## Tracking
### Daily Progress Log
| Date | Phase | Tasks Completed | Notes |
|------|-------|-----------------|-------|
| 2025-12-30 | Planning | Created master plan | - |
### Completion Criteria
- [ ] All 43 packages pass validator
- [ ] All 43 packages have tests
- [ ] Zero @mui/* imports in codebase
- [ ] Zero @phosphor-icons imports
- [ ] Playwright E2E tests pass
- [ ] Bundle size reduced by 15%+
- [ ] User notified of completion
---
## Quick Reference Commands
```bash
# Run all package tests
npm run test:packages
# Validate all packages
npm run validate:packages
# Check for MUI imports
grep -r "@mui/material" frontends/nextjs/src --include="*.tsx"
# Build and verify
npm run build
# Run E2E tests
npm run test:e2e
```

View File

@@ -1,408 +0,0 @@
# MetaBuilder Migration Phases
**Master Plan for UI Migration & Package Enhancement**
**Created:** 2025-12-30
**Updated:** 2025-12-30
**Status:** Active - Phase 1 & 2 In Progress
**Goal:** Complete migration to fakemui + Lua packages, eliminate dependencies
---
## Executive Summary
| Goal | Current State | Target |
|------|---------------|--------|
| @mui/material | In use | ❌ Removed |
| @mui/icons-material | ✅ Eliminated from source | ✅ Complete |
| @phosphor-icons/react | In package.json | ❌ Removed |
| fakemui icons | 357+ icons | 400+ icons |
| fakemui components | ~155 (TreeView added) | 200+ (full MUI parity) |
| Lua packages typed | 16+ packages | All packages |
| Lua packages tested | 20+ packages | All packages |
| TSX to Lua conversion | ~40% | 95% |
### Recent Progress (2025-12-30)
- ✅ Created types.lua for: admin_dialog, form_builder, schema_editor, data_table, nav_menu, dashboard, workflow_editor, stats_grid
- ✅ Added 25+ new fakemui icons (formatting, charts, communication, status)
- ✅ Added TreeView component to fakemui/data-display
- ✅ Updated fakemui/icons/index.ts with all new exports
---
## Phase Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ PHASE 1: Foundation Enhancement [Week 1] │
│ - Add missing fakemui icons │
│ - Add missing fakemui components │
│ - Create Monaco/Markdown fakemui components │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 2: Lua Package Types [Week 1-2] │
│ - Add LuaCATS annotations to all packages │
│ - Create types.lua for each package │
│ - Cross-reference with shared/types/ │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 3: Parameterized Tests [Week 2] │
│ - Add .test.lua and .cases.json to all packages │
│ - Use lua_test framework │
│ - Achieve 80%+ coverage │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 4: Package Validator Compliance [Week 2-3] │
│ - Run package_validator on all packages │
│ - Fix any validation errors │
│ - Update validator if needed │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 5: TSX to Lua Conversion [Week 3-4] │
│ - Convert hardcoded TSX components to Lua │
│ - Create new packages as needed │
│ - Remove MUI imports │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 6: Dependency Cleanup [Week 4] │
│ - Remove @mui/* from package.json │
│ - Remove @emotion/* from package.json │
│ - Remove @phosphor-icons/react │
│ - Verify app still renders │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 7: Permission System [Week 5] │
│ - Add database toggle to packages │
│ - Add component on/off switches │
│ - Implement minLevel enforcement │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 8: Style System [Week 5-6] │
│ - Create CSS designer Lua package │
│ - Enable style overlays via seed data │
│ - Theme customization via database │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 9: Multi-Frontend Support [Week 6-7] │
│ - QT6/QML powered by packages │
│ - CLI frontend integration │
│ - Abstract package rendering │
├─────────────────────────────────────────────────────────────────┤
│ PHASE 10: Verification & Polish [Week 7-8] │
│ - Playwright E2E tests │
│ - Enable packages one at a time │
│ - Final cleanup and documentation │
└─────────────────────────────────────────────────────────────────┘
```
---
## Phase 1: Foundation Enhancement
### 1.1 Missing fakemui Icons
Add icons that may still be needed:
**Editor Icons:**
- [ ] Spellcheck, FormatClear, FormatIndentIncrease, FormatIndentDecrease
- [ ] FormatAlignCenter, FormatAlignRight, FormatAlignJustify
- [ ] Superscript, Subscript, Strikethrough
**Data/Chart Icons:**
- [ ] TrendDown, TrendingFlat
- [ ] DonutLarge, DonutSmall
- [ ] StackedBarChart, StackedLineChart
**Communication:**
- [ ] Forum, Comment, CommentOutlined
- [ ] Announcement, Campaign
**Status/Progress:**
- [ ] HourglassEmpty, HourglassFull
- [ ] Pending, PendingActions
- [ ] PublishedWithChanges
### 1.2 Missing fakemui Components
**Layout:**
- [ ] AspectRatio (maintains aspect ratio)
- [ ] Center (centers content)
- [ ] Spacer (flexible space)
**Inputs:**
- [ ] SearchInput (input with search icon)
- [ ] PasswordInput (with visibility toggle)
- [ ] TagInput (multiple tags)
- [ ] Autocomplete (suggestions)
**Data Display:**
- [ ] DataList (definition lists)
- [ ] Timeline (event timeline)
- [ ] TreeView (hierarchical tree)
- [ ] VirtualList (virtualized rendering)
**Advanced:**
- [ ] Monaco (code editor wrapper)
- [ ] MarkdownRenderer (markdown display)
- [ ] RichTextEditor (WYSIWYG editor)
### 1.3 Component Gaps Checklist
| Component | fakemui | MUI Equivalent | Status |
|-----------|---------|----------------|--------|
| Autocomplete | ❌ | Autocomplete | Needed |
| TreeView | ❌ | TreeView | Needed |
| Stepper | ❌ | Stepper | Needed |
| SpeedDial | ❌ | SpeedDial | Optional |
| Backdrop | ❌ | Backdrop | Needed |
| ClickAwayListener | ❌ | ClickAwayListener | Needed |
| Popper | ❌ | Popper | Needed |
| Transition | ✅ | Transition | Complete |
---
## Phase 2: Lua Package Type Annotations
### Packages Needing Types
| Package | types.lua | Status |
|---------|-----------|--------|
| admin_dialog | ❌ | Needed |
| arcade_lobby | ❌ | Needed |
| audit_log | ✅ | Complete |
| codegen_studio | ❌ | Needed |
| code_editor | ✅ | Complete |
| config_summary | ❌ | Needed |
| dashboard | ❌ | Needed |
| data_table | ❌ | Needed |
| dbal_demo | ✅ | Complete |
| form_builder | ❌ | Needed |
| forum_forge | ✅ | Complete |
| github_tools | ✅ | Complete |
| irc_webchat | ✅ | Complete |
| lua_test | ✅ | Complete |
| media_center | ✅ | Complete |
| nav_menu | ❌ | Needed |
| notification_center | ✅ | Complete |
| package_validator | ✅ | Complete |
| quick_guide | ❌ | Needed |
| role_editor | ❌ | Needed |
| schema_editor | ❌ | Needed |
| screenshot_analyzer | ✅ | Complete |
| shared | ✅ | Complete |
| smtp_config | ❌ | Needed |
| social_hub | ✅ | Complete |
| stats_grid | ❌ | Needed |
| stream_cast | ✅ | Complete |
| ui_* (all) | ✅ | Complete |
| user_manager | ❌ | Needed |
| workflow_editor | ❌ | Needed |
---
## Phase 3: Parameterized Tests
### Test Structure Pattern
```
package/seed/scripts/tests/
├── {module}.test.lua # Test definitions
└── {module}.cases.json # Test parameters
```
### Example Test Pattern (from lua_test)
```lua
---@param case table Test case data
---@field input any Input value
---@field expected any Expected output
local function testCase(case)
local result = functionUnderTest(case.input)
expect(result).toEqual(case.expected)
end
describe("Module Tests", function()
it.each(testCases)("should handle $description", testCase)
end)
```
### Packages Needing Tests
| Package | Test Files | Status |
|---------|------------|--------|
| admin_dialog | ❌ | Needed |
| config_summary | ❌ | Needed |
| dashboard | ❌ | Needed |
| data_table | ❌ | Needed |
| form_builder | ❌ | Needed |
| nav_menu | ❌ | Needed |
| quick_guide | ❌ | Needed |
| role_editor | ❌ | Needed |
| schema_editor | ❌ | Needed |
| smtp_config | ❌ | Needed |
| stats_grid | ❌ | Needed |
| user_manager | ❌ | Needed |
| workflow_editor | ❌ | Needed |
---
## Phase 4: Package Validator Compliance
### Validation Rules (from package_validator)
1. ✅ Valid metadata.json with required fields
2. ✅ components.json array structure
3. ✅ All exported scripts exist
4. ✅ All component types are valid
5. ✅ No circular dependencies
6. ✅ Version follows semver
7. ✅ minLevel in valid range (0-6)
### Run Command
```bash
npm run package:validate -- --all
```
---
## Phase 5: TSX to Lua Conversion
### Priority Order
1. **Viewers** - Read-only data display (easiest)
2. **Editors** - Form-based editing
3. **Complex** - Multi-step workflows
### Files to Convert
See MUI_ELIMINATION_PLAN.md for full list (~160 files)
---
## Phase 6: Dependency Cleanup
### Dependencies to Remove
```json
{
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.6",
"@mui/material": "^7.3.6",
"@mui/x-data-grid": "^8.23.0",
"@mui/x-date-pickers": "^8.23.0",
"@phosphor-icons/react": "^2.1.10"
}
```
### Estimated Savings
- Bundle size: -2-3 MB
- Install time: -30 seconds
- Build time: -15%
---
## Phase 7: Permission System
### Package-Level Permissions
```json
{
"permissions": {
"minLevel": 3,
"requiresDatabase": true,
"features": {
"editing": { "minLevel": 4 },
"deleting": { "minLevel": 5 },
"admin": { "minLevel": 6 }
}
}
}
```
### Component Toggle System
```lua
-- In package init.lua
local enabled_components = config.get("enabled_components", {})
function is_enabled(component_id)
return enabled_components[component_id] ~= false
end
```
---
## Phase 8: Style System
### CSS Designer Package
```
packages/css_designer/
├── seed/
│ ├── metadata.json
│ ├── components.json
│ └── scripts/
│ ├── init.lua
│ ├── theme_manager.lua
│ ├── color_picker.lua
│ ├── variable_editor.lua
│ └── preview.lua
```
### Theme Override Structure
```lua
---@class ThemeOverride
---@field primary_color string
---@field secondary_color string
---@field background_color string
---@field text_color string
---@field border_radius string
---@field font_family string
```
---
## Phase 9: Multi-Frontend Support
### Package Rendering Abstraction
```lua
---@class RenderTarget
---@field type "react" | "qml" | "cli"
---@field capabilities table<string, boolean>
---@param target RenderTarget
---@param component UIComponent
---@return string Rendered output
function render(target, component)
if target.type == "react" then
return render_react(component)
elseif target.type == "qml" then
return render_qml(component)
elseif target.type == "cli" then
return render_cli(component)
end
end
```
---
## Phase 10: Verification
### E2E Test Plan
1. Enable one package at a time
2. Run Playwright tests
3. Check for visual regressions
4. Verify functionality
5. Document any issues
### Success Criteria
- [ ] All packages pass validation
- [ ] All packages have types
- [ ] All packages have tests
- [ ] Zero MUI imports in codebase
- [ ] App renders correctly
- [ ] E2E tests pass
---
## Progress Tracking
### Weekly Updates
- **Week 1:** Phase 1-2
- **Week 2:** Phase 2-4
- **Week 3:** Phase 4-5
- **Week 4:** Phase 5-6
- **Week 5:** Phase 6-7
- **Week 6:** Phase 7-8
- **Week 7:** Phase 8-9
- **Week 8:** Phase 9-10
### Completion Notification
When all phases complete, create `MIGRATION_COMPLETE.md` with:
- Summary of changes
- Performance metrics
- Breaking changes
- Upgrade guide

View File

@@ -1,731 +0,0 @@
# MUI Dependency Elimination Plan
**Status:** Planning Phase
**Created:** 2025-12-30
**Goal:** Remove @mui/material dependency completely from the codebase
---
## Executive Summary
**Total Files Using MUI:** 160+
**Total MUI Imports:** 24,273+ import statements
**Migration Strategy:** 6 phases over 8 weeks
**Key Approach:** Lua packages for editors, fakemui for basic UI
---
## Phase Overview
```
Phase 1: Foundation (Weeks 1-2) ✅ Complete
Phase 2: Atomic Components (Weeks 2-3) 🔜 Ready to start
Phase 3: Basic UI (Weeks 3-4) ⏳ Pending
Phase 4: Complex UI (Weeks 4-6) ⏳ Pending
Phase 5: Lua Packages (Weeks 6-8) ⏳ Pending
Phase 6: Cleanup (Week 8+) ⏳ Pending
```
## Recent Progress (2025-12-30)
**✅ Completed:**
- Created fakemui icon system (27 icons - full Phase 2!)
- Migrated LuaBlocksEditor to fakemui (8 files)
- Enhanced fakemui CSS reset to replace CssBaseline
- Documented all 160+ MUI files for migration
- Created DEPENDENCY_CLEANUP.md plan
- Audited package.json dependencies
- **Phase 1 fakemui foundation 100% complete** - All atoms, feedback, navigation, and data display components implemented:
- Slider, Toggle/Switch, Rating ✅
- Toast/Snackbar, Dialog, Progress ✅
- Menu, Pagination ✅
- Table, List, Chip ✅
**✅ Additional Progress (Latest Session):**
- Expanded fakemui icons to **70+ icons** including:
- Media controls: Pause, Stop, Maximize, Minimize, Volume, VolumeOff
- Media: Camera, Video, Screen, Broadcast, Image
- Security: Lock, LockOpen, Key, Shield
- Utility: Terminal, Cloud, Globe, Archive, Clipboard, Package, Layers, Tag, Bookmark
- Communication: Chat, Send
- Plus: Refresh, File, Grid, List
- Added LuaCATS type annotations to packages:
- dbal_demo (5 files with full types)
- screenshot_analyzer, social_hub, stream_cast (already typed)
- Verified lua_test and package_validator have comprehensive types
- Verified all ui_* packages have comprehensive types
**✅ Additional Progress (Session 2 - 2025-12-30):**
- Added 11 more icons to fakemui:
- DragIndicator, DragHandle (for sortable items)
- Print, Schedule, Tune (utilities)
- ThumbUp, ThumbDown (feedback)
- Notifications, NotificationsOff (alerts)
- ContentCopy, ContentPaste (clipboard operations)
- Added missing fakemui input components:
- ButtonGroup (grouped buttons with shared styling)
- FormControl with useFormControl hook (form state context)
- RadioGroup with useRadioGroup hook (grouped radios)
- NativeSelect (browser-native select with styling)
- Created SCSS styles for all new components:
- ButtonGroup.module.scss
- FormControl.module.scss
- RadioGroup.module.scss
- NativeSelect.module.scss
- Created shared UI types package:
- packages/shared/types/ui_types.lua (comprehensive type definitions)
- UIComponent, ButtonProps, InputProps, CardProps, etc.
- UserInfo, TenantInfo, RenderContext, ActionResult types
- Added parameterized tests to ui_level3:
- moderation.test.lua with permission level tests
- moderation.cases.json with test data
- **Total fakemui icons now: 80+** (up from 70+)
**✅ Additional Progress (Session 3 - 2025-12-31):**
- **@mui/icons-material completely eliminated from source code!**
- Migrated 40+ component files to fakemui icons
- Created 50+ new fakemui icons including:
- Component icons: Article, Checkbox, CropFree, CropPortrait, GridView, etc.
- Navigation: FirstPage, LastPage, ViewColumn, ViewStream
- Interaction: ToggleOn, TouchApp, FormatAlignLeft
- Display: AccountCircle, Verified, LocalOffer, LooksOne, TextFields, TableChart, Minus
- Updated atoms/display/Icon.tsx to use fakemui icons dynamically
- Migrated get-component-icon.tsx to fakemui
- Updated all test files (NavLink.test.tsx, NavItem.test.tsx, NavGroup.test.tsx)
- **Total fakemui icons now: 130+** (up from 80+)
- Icon mappings complete for all common MUI icon names
**✅ Additional Progress (Session 4 - 2025-12-31):**
- **Added 32 new fakemui icons for media center:**
- Media controls: FastForward, FastRewind, SkipPrevious, SkipNext, Shuffle, Repeat, RepeatOne
- Video: FilmSlate, Tv, Fullscreen, FullscreenExit, AspectRatio, HighQuality, Subtitles, ClosedCaption
- Audio: Headphones, Mic, MicOff, Radio, Volume, VolumeOff
- Gaming: SportsEsports, Gamepad, Joystick
- Utilities: Queue, Transform, PictureAsPdf, Article, MenuBook, People, ArrowUpDown, Timer, Speed, CameraAlt
- **Added new fakemui components:**
- CardTitle, CardDescription, CardFooter (Card subcomponents)
- Heading (Typography alias for headings)
- FormField (Form input wrapper with label/error)
- Iframe (Embedded content)
- Markdown (Markdown renderer)
- Separator (Divider alias)
- **Created github_tools Lua package (Phase 5):**
- Full components.json with GitHubViewer, RunList, RunDetails, AnalysisPanel, RunFilters
- Lua scripts: init.lua, fetch_runs.lua, analyze.lua, filter.lua, status.lua
- Complete LuaCATS type annotations
- Parameterized test suite with github_tools.test.lua
- **Added tests to media_center package:**
- helpers.test.lua with parameterized tests
- helpers.cases.json with 30+ test cases
- **Total fakemui icons now: 162+** (up from 130+)
**✅ Additional Progress (Session 5 - 2025-12-31):**
- **Added 12 new admin/storage/security icons:**
- Admin: AccountTree, AdminPanelSettings, ManageAccounts
- Storage: Backup, Restore, Storage
- Security: Domain, SecurityUpdate, VerifiedUser, VpnKey
- Utility: Policy, Help
- **Added parameterized tests to 4 packages:**
- forum_forge: permissions.test.lua + permissions.cases.json (21 test cases)
- can_post, can_moderate, flag_post, rank_thread functions
- irc_webchat: chat.test.lua + chat.cases.json (20+ test cases)
- help/users/clear/me commands, time formatting, message creation
- arcade_lobby: arcade.test.lua + arcade.cases.json (15+ test cases)
- matchmaking buckets, tournament permissions, queue metrics
- notification_center: notifications.test.lua + notifications.cases.json (20+ test cases)
- calculate_total, severity classes, toast variants, summary preparation
- **Created github_tools Lua package scaffold**
- **Total fakemui icons now: 266+** (up from 162+)
- **Test coverage expanded to 8+ packages with parameterized tests**
**✅ Additional Progress (Session 6 - 2025-12-30):**
- **Added 22 new fakemui icons for rich text editing and UI:**
- Rich Text: FormatBold, FormatItalic, FormatUnderline, FormatStrikethrough
- Lists: FormatListBulleted, FormatListNumbered, FormatQuote
- Insert: InsertLink, InsertPhoto, AttachFile
- Date/Time: DateRange, AccessTime
- Color: ColorPicker
- Devices: Smartphone, Tablet, Desktop
- i18n: Language, QrCode
- Image: RotateLeft, RotateRight
- Theme: DarkMode, LightMode
- **Added 4 new fakemui input components:**
- DatePicker (HTML5 date/datetime/month/week inputs)
- TimePicker (HTML5 time input with step support)
- ColorPicker (with presets, alpha support, text input)
- FileUpload (drag & drop, validation, preview)
- **Added SCSS styles:** Pickers.module.scss for all new picker components
- **Added parameterized test cases to code_editor:**
- editor.cases.json with 50+ test cases for theme, color picker, JSON, Lua, editor modes
- **Updated code_editor metadata.json** with all test files
- **Total fakemui icons now: 288+** (up from 266+)
- **Total fakemui input components now: 28** (up from 24)
**📋 Ready to Execute:**
- ✅ Icon strategy: Full fakemui custom icons (no Phosphor) - 288+ icons!
- ✅ Phase 1: Complete - all foundation components ready
- ✅ Phase 2: ButtonGroup, FormControl, RadioGroup, NativeSelect, DatePicker, TimePicker, ColorPicker, FileUpload added
-@mui/icons-material: ELIMINATED from source code
- ✅ Phase 5: github_tools package created
- ✅ Parameterized tests added to forum_forge, irc_webchat, arcade_lobby, notification_center, code_editor
- Phase 3: Continue MUI core component elimination
---
## Category Breakdown
### 🎯 Category 1: Lua Packages (12 files)
**Components that should become dedicated Lua packages**
#### 1.1 Workflow Editor Suite (8 files)
- **Path:** `frontends/nextjs/src/components/workflow/`
- **Package Name:** `@packages/workflow_editor`
- **Files:**
- WorkflowEditor.tsx
- WorkflowRunCard.tsx
- WorkflowRunStatus.tsx
- editor/WorkflowNodeCard.tsx
- editor/WorkflowSidebar.tsx
- editor/WorkflowTester.tsx
- editor/WorkflowNodesPanel.tsx
- editor/constants.tsx
**Complexity:** Medium-High
**MUI Usage:** Icons (PlayArrow, CheckCircle, Delete), Layout (Card, Stack, Box)
**Recommendation:** Convert to Lua package with JSON-based node system
#### 1.2 GitHub Actions Viewer (10 files)
- **Path:** `frontends/nextjs/src/components/misc/github/`
- **Package Name:** `@packages/github_actions_viewer`
- **Files:**
- GitHubActionsFetcher.tsx
- views/AnalysisPanel.tsx
- views/RunList.tsx
- views/RunDetails.tsx
- views/run-list/* (6 files)
**Complexity:** Medium
**MUI Usage:** Tables, Chips, Alerts, Typography
**Recommendation:** Convert to Lua package with data table component
---
### 🔧 Category 2: Fakemui Migration (66 files)
**Basic UI components that should migrate to fakemui**
#### 2.1 Atomic Components (20 files)
**Path:** `frontends/nextjs/src/components/atoms/`
**Controls (7 files):**
- Button.tsx → fakemui/inputs/Button
- Checkbox.tsx → fakemui/inputs/Checkbox
- Radio.tsx → fakemui/inputs/Radio
- Switch.tsx → fakemui/inputs/Switch
- Slider.tsx → fakemui/inputs/Slider
- Toggle.tsx → fakemui/inputs/ToggleButton
**Display (8 files):**
- Avatar.tsx → fakemui/data-display/Avatar
- Badge.tsx → fakemui/data-display/Badge
- Icon.tsx → fakemui/icons/* (custom system)
- IconButton.tsx → fakemui/inputs/IconButton
- Label.tsx → fakemui/atoms/Label
- Link.tsx → fakemui/navigation/Link
- Text.tsx → fakemui/atoms/Text
**Feedback (5 files):**
- ErrorBoundary.tsx → Keep as-is (React boundary)
- Separator.tsx → fakemui/data-display/Divider
- Skeleton.tsx → fakemui/feedback/Skeleton
- ScrollArea.tsx → Custom CSS implementation
- Tooltip.tsx → fakemui/data-display/Tooltip
- Spinner.tsx → fakemui/feedback/CircularProgress
- Progress.tsx → fakemui/feedback/LinearProgress
**Inputs (3 files):**
- Input.tsx → fakemui/inputs/Input
- TextArea.tsx → fakemui/inputs/Textarea
- Select.tsx → fakemui/inputs/Select
#### 2.2 UI Molecules (15+ files)
**Path:** `frontends/nextjs/src/components/ui/molecules/`
**Display:**
- Accordion.tsx → fakemui/surfaces/Accordion
- Alert.tsx → fakemui/feedback/Alert
- Card.tsx → fakemui/surfaces/Card
**Navigation:**
- Breadcrumb.tsx → fakemui/navigation/Breadcrumbs
- NavGroup.tsx → Custom with fakemui primitives
- NavItem.tsx → fakemui/navigation/ListItem
- NavLink.tsx → fakemui/navigation/Link
**Overlay:**
- Dialog.tsx → fakemui/utils/Dialog
- DropdownMenu.tsx → fakemui/navigation/Menu
- Popover.tsx → fakemui/utils/Popover
- Tooltip.tsx → fakemui/data-display/Tooltip
**Selection:**
- RadioGroup.tsx → fakemui/inputs/Radio with FormGroup
- Select.tsx → fakemui/inputs/Select
- ToggleGroup.tsx → fakemui/inputs/ToggleButtonGroup
**Tabs:**
- Tabs.tsx → fakemui/navigation/Tabs
- TabsContent.tsx → fakemui/navigation/Tab (panel)
- TabsList.tsx → fakemui/navigation/Tabs (container)
- TabsTrigger.tsx → fakemui/navigation/Tab (trigger)
#### 2.3 UI Organisms (15+ files)
**Path:** `frontends/nextjs/src/components/ui/organisms/`
**Dialogs:**
- AlertDialog → fakemui/utils/Dialog with Alert
- Command → Custom with fakemui primitives
- Sheet → fakemui/surfaces/Drawer
**Navigation:**
- Navigation.tsx → Custom with fakemui/surfaces/AppBar
- Sidebar → Custom with fakemui/surfaces/Drawer
- Pagination → fakemui/navigation/Pagination
**Data:**
- Form → Custom with fakemui/inputs
- Table → fakemui/data-display/Table
---
### 🎨 Category 3: Theme & Providers (19 files)
**Configuration files to be cleaned up after migration**
#### 3.1 Theme Files
**Path:** `frontends/nextjs/src/theme/`
**Files to Remove:**
- components.ts (MUI component overrides)
- light-theme.ts (MUI theme)
- dark-theme.ts (MUI theme)
- mui-theme.ts (theme creation)
- modes/light-theme.ts
- modes/dark-theme.ts
- modes/components.ts
**Files to Keep/Convert:**
- colors.ts → CSS variables
- fonts.ts → CSS font definitions
- typography.ts → CSS typography scale
- layout.ts → CSS layout tokens
- tokens.ts → CSS custom properties
#### 3.2 Provider Files
**Path:** `frontends/nextjs/src/app/providers/`
**Updates Needed:**
- providers-component.tsx
- Remove: MuiThemeProvider, CssBaseline
- Keep: ThemeContext for dark/light mode
- Add: CSS variables injection
---
### 🧪 Category 4: Test Files (3 files)
**Update alongside component migrations**
- NavLink.test.tsx
- NavItem.test.tsx
- NavGroup.test.tsx
---
## Detailed Phase Plan
### ✅ Phase 1: Foundation (Weeks 1-2)
**Status:** Partially Complete
**Completed:**
- ✅ Created fakemui icon system (Plus, Trash, Copy, Arrows, etc.)
- ✅ Migrated LuaBlocksEditor to fakemui
- ✅ Created fakemui barrel export
**Remaining:**
1. Choose icon library (Recommendation: Lucide React)
2. Create CSS reset (replace CssBaseline)
3. Create CSS variable theme system
4. Update providers to use new theme
**Deliverables:**
- [ ] Icon system decision + implementation
- [x] fakemui basic structure
- [ ] CSS reset file
- [ ] Theme CSS variables
- [ ] Updated provider component
---
### Phase 2: Atomic Components (Weeks 2-3)
**Priority:** High - Foundation for everything else
#### Week 2: Controls & Inputs
**Files:** 10 files
1. **Day 1-2: Button Components**
- atoms/controls/Button.tsx
- atoms/display/IconButton.tsx
- Reference: fakemui/inputs/Button.tsx
2. **Day 3-4: Form Inputs**
- atoms/inputs/Input.tsx
- atoms/inputs/TextArea.tsx
- atoms/inputs/Select.tsx
- Reference: fakemui/inputs/Input.tsx, Textarea.tsx, Select.tsx
3. **Day 5: Form Controls**
- atoms/controls/Checkbox.tsx
- atoms/controls/Radio.tsx
- atoms/controls/Switch.tsx
- Reference: fakemui/inputs/Checkbox.tsx, Radio.tsx, Switch.tsx
#### Week 3: Display & Feedback
**Files:** 13 files
1. **Day 1-2: Display Components**
- atoms/display/Avatar.tsx
- atoms/display/Badge.tsx
- atoms/display/Icon.tsx (critical - replaces all MUI icons)
- atoms/display/Label.tsx
- atoms/display/Link.tsx
- atoms/display/Text.tsx
2. **Day 3-4: Feedback Components**
- atoms/feedback/Skeleton.tsx
- atoms/feedback/Spinner.tsx
- atoms/feedback/Progress.tsx
- atoms/feedback/Tooltip.tsx
- atoms/feedback/Separator.tsx
3. **Day 5: Testing & Verification**
- Update all atom tests
- Visual regression testing
- Component demo page
**Deliverables:**
- [ ] 20 atom components migrated to fakemui
- [ ] Icon replacement complete
- [ ] All atom tests passing
- [ ] Component showcase page
---
### Phase 3: Basic UI Components (Weeks 3-4)
**Priority:** High - User-facing components
#### Week 3: Display & Navigation Molecules
**Files:** 10 files
1. **Day 1-2: Display Components**
- molecules/display/Card.tsx
- molecules/display/Alert.tsx
- molecules/display/Accordion.tsx
2. **Day 3-4: Navigation Components**
- molecules/navigation/Breadcrumb.tsx
- molecules/navigation/NavGroup.tsx
- molecules/navigation/NavItem.tsx
- molecules/navigation/NavLink.tsx
3. **Day 5: Tabs**
- molecules/tabs/Tabs.tsx
- molecules/tabs/TabsContent.tsx
- molecules/tabs/TabsList.tsx
- molecules/tabs/TabsTrigger.tsx
#### Week 4: Overlay & Selection
**Files:** 8 files
1. **Day 1-2: Overlay Components**
- molecules/overlay/Dialog.tsx
- molecules/overlay/DropdownMenu.tsx
- molecules/overlay/Popover.tsx
- molecules/overlay/Tooltip.tsx
2. **Day 3-4: Selection Components**
- molecules/selection/RadioGroup.tsx
- molecules/selection/Select.tsx
- molecules/selection/ToggleGroup.tsx
3. **Day 5: Testing**
- Update molecule tests
- Integration testing
**Deliverables:**
- [ ] 18 molecule components migrated
- [ ] Navigation components working
- [ ] All overlay components functional
- [ ] Tests passing
---
### Phase 4: Complex UI Components (Weeks 4-6)
**Priority:** Medium - Advanced features
#### Week 5: Navigation Organisms
**Files:** 12 files
1. **Day 1-3: Main Navigation**
- organisms/navigation/Navigation.tsx
- organisms/navigation/NavigationMenuItems.tsx
- organisms/navigation/NavigationResponsive.tsx
- organisms/navigation/Sidebar (6 files)
2. **Day 4-5: Pagination**
- organisms/navigation/pagination/* (5 files)
#### Week 6: Dialogs & Data
**Files:** 10 files
1. **Day 1-2: Dialog System**
- organisms/dialogs/AlertDialog
- organisms/dialogs/Command
- organisms/dialogs/Sheet
2. **Day 3-4: Data Components**
- organisms/data/Form.tsx
- organisms/data/Table.tsx
- data/table/* (Body, Header, EmptyState)
3. **Day 5: Testing & Polish**
- Full UI testing
- Responsive testing
**Deliverables:**
- [ ] 22 organism components migrated
- [ ] Navigation system complete
- [ ] Data components functional
- [ ] Full regression testing
---
### Phase 5: Lua Packages (Weeks 6-8)
**Priority:** Medium - Specialized editors
#### Week 7: Workflow Editor Package
**Package:** `@packages/workflow_editor`
**Files:** 8 files
1. **Day 1-2: Package Structure**
- Create package directory structure
- Create components.json
- Define metadata schema
2. **Day 3-4: Component Migration**
- Migrate WorkflowEditor components
- Replace MUI with fakemui
- Implement node system with JSON
3. **Day 5: Testing**
- Package integration tests
- Visual workflow testing
#### Week 8: GitHub Viewer Package
**Package:** `@packages/github_actions_viewer`
**Files:** 10 files
1. **Day 1-2: Package Structure**
- Create package structure
- Define data schemas
2. **Day 3-4: Component Migration**
- Migrate GitHub viewer components
- Implement custom table with fakemui
- Replace MUI icons
3. **Day 5: Integration**
- Package testing
- Integration with main app
**Deliverables:**
- [ ] workflow_editor package created
- [ ] github_actions_viewer package created
- [ ] Both packages tested and documented
---
### Phase 6: Final Cleanup (Week 8+)
**Priority:** High - Complete removal
#### Cleanup Tasks
1. **Theme System Removal**
- [ ] Remove theme/components.ts
- [ ] Remove theme/*-theme.ts files
- [ ] Remove MUI theme imports
2. **Provider Updates**
- [ ] Remove MuiThemeProvider from providers
- [ ] Remove CssBaseline import
- [ ] Update theme context to use CSS variables
3. **Package.json**
- [ ] Remove @mui/material
- [ ] Remove @mui/icons-material
- [ ] Remove @mui/system
- [ ] Verify no residual MUI dependencies
4. **Testing**
- [ ] Full application smoke test
- [ ] Visual regression testing
- [ ] Performance benchmarking
- [ ] Bundle size analysis
5. **Documentation**
- [ ] Update component documentation
- [ ] Create migration guide for future devs
- [ ] Document new icon system
- [ ] Document theme CSS variables
**Deliverables:**
- [ ] Zero MUI imports remaining
- [ ] All tests passing
- [ ] Bundle size reduced by 15-25%
- [ ] Documentation complete
---
## Icon System Migration
### Current System
- `atoms/display/Icon.tsx` dynamically imports from @mui/icons-material
- Used across entire codebase
- Supports 100+ icon names
### Replacement Options
| Option | Icons | Size | Pros | Cons |
|--------|-------|------|------|------|
| **Lucide React** | 1000+ | ~50KB | Tree-shakeable, modern, well-maintained | Learning curve |
| **Feather Icons** | 286 | ~30KB | Minimal, beautiful | Limited selection |
| **Custom SVG** | Custom | ~5KB | Full control, zero deps | Manual maintenance |
| **Radix Icons** | 300+ | ~25KB | Radix-aligned | Smaller set |
### ✅ DECISION: Custom SVG System (fakemui/icons)
- **Why:** Full control, zero dependencies, already started
- **Approach:** Add icons as needed from Heroicons/Lucide/Phosphor
- **Benefit:** Zero dependencies, full control, tiny bundle (~1KB per icon)
- **Process:** Copy SVG paths when needed, create TSX components
- **Status:** APPROVED - Moving forward with this approach
---
## Migration Metrics
### Success Criteria
- ✅ Zero imports from @mui/material
- ✅ Zero imports from @mui/icons-material
- ✅ Zero imports from @mui/system
- ✅ All theme tests passing
- ✅ All UI component tests passing
- ✅ No visual regressions
- ✅ Bundle size reduced 15-25%
- ✅ Performance improvements
### Current Progress
- **Phase 1:** 40% complete (icon system started, LuaBlocksEditor migrated)
- **Phase 2:** 0% complete
- **Phase 3:** 0% complete
- **Phase 4:** 0% complete
- **Phase 5:** 0% complete
- **Phase 6:** 0% complete
**Overall:** ~7% complete (11/160 files migrated)
---
## Key Files Reference
### Fakemui Examples
- [Button.tsx](fakemui/fakemui/inputs/Button.tsx) - Reference implementation
- [Card.tsx](fakemui/fakemui/surfaces/Card.tsx) - Compound component pattern
- [Table.tsx](fakemui/fakemui/data-display/Table.tsx) - Complex data display
- [Alert.tsx](fakemui/fakemui/feedback/Alert.tsx) - Feedback component
- [index.ts](fakemui/index.ts) - Barrel export pattern
### Migration Examples
- [LuaBlocksEditor.tsx](frontends/nextjs/src/components/editors/lua/LuaBlocksEditor.tsx) - MUI → fakemui complete
- [BlockItem.tsx](frontends/nextjs/src/components/editors/lua/blocks/BlockItem.tsx) - Icon migration example
---
## Risk Assessment
### Low Risk
- Atomic component migration (well-isolated)
- Icon system replacement (centralized)
- CSS variable theme (progressive enhancement)
### Medium Risk
- Complex organism components (navigation, dialogs)
- Form components (validation, error handling)
- Table components (sorting, filtering)
### High Risk
- Workflow editor (complex state, D&D)
- Package creation (new architecture)
- Provider changes (affects entire app)
### Mitigation Strategies
1. **Parallel Development:** Keep MUI versions until replacement tested
2. **Feature Flags:** Toggle between old/new components
3. **Incremental Rollout:** Migrate page-by-page if needed
4. **Testing:** Comprehensive visual regression testing
5. **Rollback Plan:** Git branches for easy reversion
---
## Next Steps
### Immediate (This Week)
1. ✅ Complete MUI elimination plan
2. Choose icon replacement strategy
3. Create CSS reset file
4. Start Phase 2: Migrate Button component
### Short Term (Next 2 Weeks)
1. Complete Phase 2: All atomic components
2. Start Phase 3: Molecule components
3. Set up visual regression testing
### Medium Term (Weeks 3-6)
1. Complete Phase 3 & 4: All UI components
2. Begin Lua package creation
3. Theme cleanup
### Long Term (Weeks 6-8)
1. Complete Lua packages
2. Final MUI removal
3. Documentation and cleanup
---
## Questions & Decisions Needed
1. **Icon System:** Custom SVG vs Lucide React?
- Recommendation: Custom SVG (already started)
2. **CSS Framework:** Pure CSS vs Tailwind utilities?
- Current: Mix of SCSS modules and Tailwind
- Recommendation: Keep current approach
3. **Component Library:** Continue fakemui or use Radix?
- Current: Fakemui + Radix for complex interactions
- Recommendation: Use both (fakemui for display, Radix for behavior)
4. **Lua Packages:** Which components become packages?
- Confirmed: Workflow editor, GitHub viewer
- TBD: Nerd mode IDE, other specialized editors
---
**Last Updated:** 2025-12-30
**Next Review:** After Phase 2 completion

View File

@@ -1,616 +0,0 @@
# Prisma Schema Package Integration Plan
**Created:** 2025-12-30
**Goal:** Wire existing Lua packages to Prisma schema and expand schema for new features
---
## Current Schema Analysis
Your Prisma schema is **excellent** and covers:
- ✅ Core identity & auth (User, Credential, Session)
- ✅ Multi-tenancy (Tenant)
- ✅ Routing & Pages (PageConfig)
- ✅ Workflows & Scripting (Workflow, LuaScript)
- ✅ Data schemas (ModelSchema, DynamicData)
- ✅ App configuration (SystemConfig, FeatureFlag, KeyValue)
- ✅ Components & UI (ComponentNode, ComponentConfig)
- ✅ Packages (InstalledPackage, PackageData)
- ✅ Content (Comment, Forum models)
- ✅ Media (MediaAsset, MediaJob)
- ✅ Notifications
- ✅ Audit & logging
- ✅ Generic entities (Tag, Tagging, EntityRelation, Task, Webhook, etc.)
---
## Package Integration Recommendations
### 1. **audit_log** Package → AuditLog Model ✅ Ready
**Schema:** Already perfect!
```prisma
model AuditLog {
id String @id @default(cuid())
tenantId String
userId String?
username String?
action String // create, update, delete, login, logout
entity String // User, Workflow, Page
entityId String?
oldValue String? // JSON
newValue String? // JSON
ipAddress String?
userAgent String?
details String? // JSON
timestamp BigInt
}
```
**Lua Package Operations:**
- `createAuditLog(tenantId, userId, action, entity, entityId, changes)`
- `listAuditLogs(tenantId, filters)`
- `getAuditLogsByEntity(tenantId, entity, entityId)`
- `getAuditLogsByUser(tenantId, userId)`
---
### 2. **notification_center** Package → Notification Model ✅ Ready
**Schema:** Already excellent!
```prisma
model Notification {
id String @id @default(cuid())
tenantId String
userId String
type String // info, warning, success, error, mention, reply
title String
message String
icon String?
read Boolean @default(false)
data String? // JSON
createdAt BigInt
expiresAt BigInt?
}
```
**Lua Package Operations:**
- `createNotification(userId, type, title, message, data?)`
- `listNotifications(userId, unreadOnly?)`
- `markAsRead(notificationId)`
- `markAllAsRead(userId)`
- `deleteNotification(notificationId)`
---
### 3. **forum_forge** Package → Forum Models ✅ Ready
**Schema:** Perfect forum structure!
```prisma
model ForumCategory {
id String @id @default(cuid())
tenantId String
name String
description String?
slug String
sortOrder Int @default(0)
parentId String? // Nested categories
threads ForumThread[]
}
model ForumThread {
id String @id @default(cuid())
categoryId String
authorId String
title String
slug String
isPinned Boolean @default(false)
isLocked Boolean @default(false)
viewCount Int @default(0)
replyCount Int @default(0)
posts ForumPost[]
}
model ForumPost {
id String @id @default(cuid())
threadId String
authorId String
content String
likes Int @default(0)
}
```
**Lua Package Operations:**
- `listCategories(tenantId)`
- `createThread(categoryId, authorId, title, content)`
- `listThreads(categoryId, filters)`
- `getThread(threadId)`
- `createPost(threadId, authorId, content)`
- `listPosts(threadId, pagination)`
- `likePost(postId, userId)`
---
### 4. **media_center** Package → MediaAsset & MediaJob Models ✅ Ready
**Schema:** Great media handling!
```prisma
model MediaAsset {
id String @id @default(cuid())
tenantId String
filename String
mimeType String
size BigInt
width Int?
height Int?
duration Int?
metadata String? // JSON: EXIF, tags
}
model MediaJob {
id String @id @default(cuid())
type String // transcode, thumbnail, convert
status String // pending, processing, completed, failed
progress Int @default(0)
params String // JSON
}
```
**Lua Package Operations:**
- `uploadMedia(tenantId, userId, file)`
- `listMedia(tenantId, filters)`
- `getMedia(mediaId)`
- `deleteMedia(mediaId)`
- `createMediaJob(type, inputPath, params)`
- `listMediaJobs(tenantId, status?)`
- `updateJobProgress(jobId, progress)`
---
### 5. **data_table** Package → DynamicData Model ✅ Ready
**Schema:** Generic data storage!
```prisma
model DynamicData {
id String @id @default(cuid())
tenantId String
schemaId String // Reference to ModelSchema
data String // JSON: actual record data
createdAt BigInt
updatedAt BigInt?
}
```
**Lua Package Operations:**
- `createRecord(schemaId, data)`
- `listRecords(schemaId, filters, pagination)`
- `getRecord(recordId)`
- `updateRecord(recordId, data)`
- `deleteRecord(recordId)`
- `searchRecords(schemaId, query)`
---
### 6. **workflow_editor** Package → Workflow Model ✅ Ready
**Schema:** Perfect for visual workflows!
```prisma
model Workflow {
id String @id
name String
description String?
nodes String // JSON: WorkflowNode[]
edges String // JSON: WorkflowEdge[]
enabled Boolean
version Int @default(1)
}
```
**Lua Package Operations:**
- `createWorkflow(tenantId, name, description)`
- `listWorkflows(tenantId, enabledOnly?)`
- `getWorkflow(workflowId)`
- `updateWorkflow(workflowId, nodes, edges)`
- `enableWorkflow(workflowId)`
- `disableWorkflow(workflowId)`
- `executeWorkflow(workflowId, input)`
---
### 7. **form_builder** Package → Template Model ✅ Ready
**Recommendation:** Use Template model for form templates
```prisma
model Template {
id String @id @default(cuid())
category String // Use 'form' for form templates
content String // JSON: form schema
variables String? // JSON: field definitions
}
```
**Lua Package Operations:**
- `createFormTemplate(name, fields)`
- `listFormTemplates(tenantId)`
- `getFormTemplate(templateId)`
- `renderForm(templateId, data?)`
- `validateFormData(templateId, data)`
---
### 8. **code_editor** Package → LuaScript Model ✅ Ready
**Schema:** Perfect for code editing!
```prisma
model LuaScript {
id String @id
name String
code String
parameters String // JSON
isSandboxed Boolean @default(true)
timeoutMs Int @default(5000)
}
```
**Lua Package Operations:**
- `createScript(name, code, parameters)`
- `listScripts(tenantId)`
- `getScript(scriptId)`
- `updateScript(scriptId, code)`
- `executeScript(scriptId, args)`
- `validateScript(code)`
---
### 9. **irc_webchat** Package → Message Model ✅ Ready
**Schema:** Generic messaging!
```prisma
model Message {
id String @id @default(cuid())
senderId String?
recipientId String
threadId String? // IRC channel
body String
isRead Boolean @default(false)
}
```
**Lua Package Operations:**
- `sendMessage(channelId, userId, body)`
- `listMessages(channelId, limit?)`
- `joinChannel(userId, channelId)`
- `leaveChannel(userId, channelId)`
---
## Schema Expansions Needed
### 1. **Package Metadata** → Add to InstalledPackage
**Current:**
```prisma
model InstalledPackage {
packageId String @id
tenantId String?
version String
enabled Boolean
config String? // JSON
}
```
**Enhancement:** Perfect as-is! Just wire up the Lua packages
---
### 2. **GitHub Integration** (github_tools package)
**Add New Model:**
```prisma
model GitHubRepository {
id String @id @default(cuid())
tenantId String
name String
owner String
fullName String // "owner/repo"
url String
description String?
isPrivate Boolean @default(false)
lastSync BigInt?
metadata String? // JSON: stars, forks, etc.
createdAt BigInt
}
model GitHubAction {
id String @id @default(cuid())
repositoryId String
workflowName String
runNumber Int
status String // queued, in_progress, completed, failed
conclusion String? // success, failure, cancelled
url String
triggeredBy String?
startedAt BigInt?
completedAt BigInt?
createdAt BigInt
}
```
---
### 3. **Arcade/Gaming** (arcade_lobby package)
**Add New Models:**
```prisma
model Game {
id String @id @default(cuid())
tenantId String
name String
slug String
description String?
thumbnail String?
category String // platformer, puzzle, arcade, etc.
core String // RetroArch core name
romPath String?
metadata String? // JSON: controls, cheats, etc.
enabled Boolean @default(true)
playCount Int @default(0)
createdAt BigInt
@@unique([tenantId, slug])
}
model GameSession {
id String @id @default(cuid())
gameId String
userId String
startedAt BigInt
endedAt BigInt?
duration Int? // seconds
saveState String? // Path to save state
achievements String? // JSON array
}
model GameHighScore {
id String @id @default(cuid())
gameId String
userId String
score BigInt
metadata String? // JSON: level, character, etc.
createdAt BigInt
@@index([gameId, score])
}
```
---
### 4. **CSS Designer** (css_designer package)
**Add New Model:**
```prisma
model CSSTheme {
id String @id @default(cuid())
tenantId String
name String
description String?
variables String // JSON: CSS custom properties
overrides String? // JSON: component-specific styles
isDefault Boolean @default(false)
isPublic Boolean @default(false)
createdAt BigInt
updatedAt BigInt?
createdBy String?
@@unique([tenantId, name])
}
```
---
### 5. **Dashboard** (dashboard package)
**Add New Models:**
```prisma
model DashboardWidget {
id String @id @default(cuid())
tenantId String
userId String
type String // chart, stats, list, calendar, etc.
title String
config String // JSON: data source, refresh rate, etc.
position String // JSON: {x, y, width, height}
sortOrder Int @default(0)
createdAt BigInt
updatedAt BigInt?
}
model Dashboard {
id String @id @default(cuid())
tenantId String
userId String?
name String
description String?
layout String // JSON: grid layout
widgets String // JSON: array of widget IDs
isDefault Boolean @default(false)
isShared Boolean @default(false)
createdAt BigInt
updatedAt BigInt?
@@unique([tenantId, userId, name])
}
```
---
### 6. **Config Summary** (config_summary package)
**Use Existing:**
- SystemConfig for key-value config
- KeyValue for namespaced config
---
### 7. **Quick Guide** (quick_guide package)
**Add New Model:**
```prisma
model Guide {
id String @id @default(cuid())
tenantId String
title String
slug String
content String // Markdown
category String? // getting-started, tutorials, reference
tags String? // JSON array
order Int @default(0)
isPublished Boolean @default(true)
views Int @default(0)
createdAt BigInt
updatedAt BigInt?
createdBy String?
@@unique([tenantId, slug])
}
model GuideStep {
id String @id @default(cuid())
guideId String
title String
content String // Markdown
order Int
actionType String? // click, input, navigate, etc.
actionData String? // JSON: element selector, etc.
createdAt BigInt
}
```
---
## Implementation Priority
### Phase 1: Wire Existing Packages (High Priority)
1.**audit_log** → AuditLog operations
2.**notification_center** → Notification CRUD
3.**forum_forge** → Forum categories, threads, posts
4.**media_center** → MediaAsset & MediaJob management
5.**workflow_editor** → Workflow CRUD
### Phase 2: Add Schema Extensions (Medium Priority)
1. Add GitHub models for **github_tools**
2. Add Game models for **arcade_lobby**
3. Add CSSTheme for **css_designer**
4. Add Dashboard models
5. Add Guide models for **quick_guide**
### Phase 3: Create Lua Operations (Medium Priority)
For each package, create Lua operations in `packages/{name}/seed/scripts/db/`:
- `create.lua` - Create operations
- `read.lua` - List and get operations
- `update.lua` - Update operations
- `delete.lua` - Delete operations
- `queries.lua` - Complex queries
### Phase 4: Create TypeScript Integration (Low Priority)
For each package, create TypeScript helpers in `frontends/nextjs/src/lib/packages/{name}/`:
- `operations.ts` - DB operations
- `types.ts` - TypeScript types matching Prisma
- `hooks.ts` - React hooks (usePackageData, etc.)
---
## Example Implementation: audit_log Package
### 1. Lua Operations
**File:** `packages/audit_log/seed/scripts/db/create.lua`
```lua
---@param tenantId string
---@param userId string|nil
---@param action string
---@param entity string
---@param entityId string|nil
---@param changes table
---@return table
function M.createAuditLog(tenantId, userId, action, entity, entityId, changes)
local db = require('db')
return db.auditLog.create({
data = {
tenantId = tenantId,
userId = userId,
action = action,
entity = entity,
entityId = entityId,
oldValue = changes.old and json.encode(changes.old) or nil,
newValue = changes.new and json.encode(changes.new) or nil,
timestamp = os.time() * 1000,
}
})
end
```
**File:** `packages/audit_log/seed/scripts/db/queries.lua`
```lua
---@param tenantId string
---@param filters table
---@return table[]
function M.listAuditLogs(tenantId, filters)
local db = require('db')
local where = { tenantId = tenantId }
if filters.userId then where.userId = filters.userId end
if filters.entity then where.entity = filters.entity end
if filters.action then where.action = filters.action end
return db.auditLog.findMany({
where = where,
orderBy = { timestamp = 'desc' },
take = filters.limit or 50,
skip = filters.offset or 0,
})
end
```
### 2. Component Integration
**File:** `packages/audit_log/seed/components.json`
```json
[
{
"name": "AuditLogViewer",
"type": "page",
"props": {
"tenantId": "string",
"filters": "object"
},
"script": "ui/audit_log_viewer.lua"
},
{
"name": "AuditLogTable",
"type": "organism",
"props": {
"logs": "array",
"onFilter": "function"
},
"script": "ui/audit_log_table.lua"
}
]
```
---
## Next Steps
1. **Choose a package** to start with (I recommend `audit_log` or `notification_center`)
2. **Create Lua DB operations** in the package's `scripts/db/` folder
3. **Wire up components** to use the DB operations
4. **Test with real data** using the Prisma client
5. **Repeat** for other packages
Would you like me to:
- Implement the audit_log package wiring?
- Add the new schema models for gaming/GitHub/etc.?
- Create a template structure for package DB operations?
- All of the above?

52
docs/README.md Normal file
View File

@@ -0,0 +1,52 @@
# MetaBuilder Documentation
## Quick Links
- [Migration Status](MIGRATION.md) - MUI elimination & Lua package migration
- [Styles System](STYLES.md) - CSS V2 schema & styling architecture
## Architecture
- [architecture/](architecture/) - System architecture & design patterns
- [ARCHITECTURE_DIAGRAM.md](architecture/ARCHITECTURE_DIAGRAM.md)
- [data/](architecture/data/) - Data-driven components & database
- [security-docs/](architecture/security-docs/) - 5-level permission system
- [systems/](architecture/systems/) - CSS, deployment, packages, testing
## Development
- [development/](development/) - Development workflows
- [AGENTS.md](development/AGENTS.md) - AI agent workflows
- [KANBAN_READY.md](development/KANBAN_READY.md) - Ready for dev criteria
- [ISSUE_COMMENT_TEMPLATE.md](development/ISSUE_COMMENT_TEMPLATE.md)
- [guides/](guides/) - Implementation guides
- [UI_STANDARDS.md](guides/UI_STANDARDS.md) - UI component standards
- [ATOMIC_GATED_WORKFLOW.md](guides/ATOMIC_GATED_WORKFLOW.md)
- [ENTERPRISE_GATED_WORKFLOW.md](guides/ENTERPRISE_GATED_WORKFLOW.md)
- [packages/](packages/) - Lua package system documentation
## Testing & Quality
- [testing/](testing/) - Test strategies & frameworks
- [quality-metrics/](quality-metrics/) - Code quality metrics
## Reference
- [api/](api/) - API documentation
- [reference/](reference/) - Technical reference
- [database/](database/) - Database schemas
- [dbal/](dbal/) - Database abstraction layer
## Operations
- [deployments/](deployments/) - Deployment configurations
- [security/](security/) - Security documentation
- [troubleshooting/](troubleshooting/) - Common issues & solutions
## Reports
- [reports/](reports/) - Status reports & summaries
- [audits/](audits/) - Code & security audits
- [archive/](archive/) - Historical documentation

View File

@@ -1,352 +0,0 @@
# Styles System - Complete Implementation
## Summary
Successfully implemented a comprehensive styling system for MetaBuil der based on CSS as an abstract deterministic function rather than a syntax-focused format.
## What Was Done
### 1. Created Stub styles.json for All Packages (40 packages)
Generated stub `seed/styles.json` files for all packages that were missing them:
- admin_dialog, arcade_lobby, audit_log, code_editor, codegen_studio
- config_summary, dashboard, data_table, dbal_demo, form_builder
- forum_forge, github_tools, irc_webchat, lua_test, media_center
- nav_menu, notification_center, package_validator, quick_guide
- role_editor, schema_editor, screenshot_analyzer, smtp_config
- social_hub, stats_grid, stream_cast, ui_auth, ui_dialogs
- ui_intro, ui_level2-6, ui_login, ui_pages, ui_permissions
- user_manager, workflow_editor
### 2. Updated All metadata.json Files
Added `seed` section to all 44 package metadata files:
```json
{
"seed": {
"styles": "seed/styles.json"
}
}
```
### 3. Updated Package Validator
**Files Modified:**
1. **[structure_config.lua](packages/package_validator/seed/scripts/structure_config.lua)**
- Added `seed/styles.json` to optional structure
2. **[validate_metadata.lua](packages/package_validator/seed/scripts/validate_metadata.lua)**
- Added validation for `seed` section
- Validates `seed.styles` as string path
- Validates `seed.data` for future use
3. **[validate_styles.lua](packages/package_validator/seed/scripts/validate_styles.lua)** (NEW)
- Validates styles.json structure
- Checks required fields (id, type, css in V1)
- Validates type enum values
- Detects duplicate IDs
- Provides warnings for empty CSS
4. **[validate_package.lua](packages/package_validator/seed/scripts/validate_package.lua)**
- Integrated styles validation into package validation flow
- Added skipStyles option
### 4. Created Schema V2: CSS as Abstract System
**[CSS_SCHEMA_V2.md](packages/shared/seed/CSS_SCHEMA_V2.md)** - Complete specification
#### Core Abstraction
```
CSS = f(Style Rules, Element Tree, Environment) → Computed Styles
```
#### 10 Layered Systems
1. **Identity Layer** (Object Inspector)
- Objects with ID, type, classes, attributes, states
- GUI: Tree view with property inspector
2. **Selection Layer** (Selector Builder)
- Selectors as predicates, not strings
- GUI: Visual constructor with dropdowns
3. **Cascade Layer** (Rule Priority Stack)
- Rules ordered by importance → specificity → source order
- GUI: Draggable rule cards with priority indicators
4. **Value System** (Typed Property Editors)
- Typed values: color, length, number, enum, transform
- GUI: Type-specific editors (color picker, slider, etc.)
5. **Computed Values** (Debug & Explainability)
- Read-only resolved snapshots with source attribution
- GUI: Computed style panel showing "why"
6. **Layout System** (Constraint Systems)
- Layout as constraint satisfaction (flex, grid, absolute)
- GUI: Layout mode switcher with visual handles
7. **Paint & Effects** (Layer Compositor)
- Painting as stacked effects (background, border, shadow)
- GUI: Layered appearance editor (Photoshop-style)
8. **Environment & Context** (Context Simulator)
- Context-dependent rules (viewport, color scheme, DPI)
- GUI: Environment toolbar with simulators
9. **Tokens & Variables** (Global Palette)
- Design tokens as first-class values
- GUI: Token editor with palettes
10. **Animation & Transitions** (State Machines)
- Animations as state machines with keyframes
- GUI: Timeline editor
### 5. Updated ui_home with V2 Schema
**[packages/ui_home/seed/styles.json](packages/ui_home/seed/styles.json)**
Converted from CSS-syntax format to abstract system with:
- **Tokens**: 7 color tokens, spacing scale, typography
- **Selectors**: 5 predicates (hero title, subtitle, cards, icons)
- **Effects**: 4 effect definitions (typography, transforms)
- **Appearance**: 9 appearance layers (gradients for 6 levels)
- **Layouts**: 2 constraint systems (flex, grid with responsiveness)
- **Transitions**: 1 state-based transition
- **Rules**: 4 cascade rules with priority
- **Environments**: 3 responsive breakpoints
## Schema Comparison
### V1 (CSS-Syntax Focused) ❌
```json
[
{
"id": "hero_title_styles",
"type": "component",
"css": ".hero-title { font-size: 4rem; ... }"
}
]
```
**Problems:**
- CSS syntax in JSON
- Not GUI-editable
- No semantic structure
- No cascade representation
### V2 (Abstract System) ✅
```json
{
"selectors": [{
"predicate": {
"targetType": "Text",
"classes": ["hero-title"]
}
}],
"effects": [{
"properties": {
"fontSize": {
"type": "responsive",
"breakpoints": {
"md": { "value": 4, "unit": "rem" }
}
}
}
}],
"rules": [{
"selector": "hero_title_selector",
"effects": { "ref": "hero_title_typography" },
"priority": { "specificity": {...} }
}]
}
```
**Benefits:**
- Fully GUI-editable
- Semantic structure
- Cascade explicitly modeled
- Type-safe values
- Responsive by design
## GUI Mental Model
Users are **NOT** "writing CSS". They are:
1. **Tagging objects** (identity)
2. **Defining conditions** (selection)
3. **Assigning visual outcomes** (effects + appearance)
4. **Resolving conflicts** (priority stack)
5. **Previewing result** (computed values)
## Compilation to CSS
The system **generates** CSS as output:
```javascript
function compileToCSS(schema) {
// 1. Resolve all tokens
// 2. Build selectors from predicates
// 3. Apply cascade resolution
// 4. Generate CSS text
return cssString;
}
```
CSS is a **compilation target**, not the authoring format.
## Files Created/Modified
### New Files
1. `packages/shared/seed/CSS_SCHEMA_V2.md` - Complete V2 specification
2. `packages/package_validator/seed/scripts/validate_styles.lua` - Styles validator
3. 40x `packages/*/seed/styles.json` - Stub files for all packages
### Modified Files
1. `packages/ui_home/seed/styles.json` - Updated to V2 schema
2. `packages/package_validator/seed/scripts/structure_config.lua` - Added styles to structure
3. `packages/package_validator/seed/scripts/validate_metadata.lua` - Added seed validation
4. `packages/package_validator/seed/scripts/validate_package.lua` - Integrated styles validation
5. 44x `packages/*/seed/metadata.json` - Added seed.styles reference
## Database Integration
The schema supports the original vision of loading CSS from database:
```sql
CREATE TABLE styles (
id VARCHAR(255) PRIMARY KEY,
package_id VARCHAR(255),
schema_version VARCHAR(10),
data JSON, -- Complete V2 schema
compiled_css TEXT, -- Generated CSS
enabled BOOLEAN
);
```
The CSS Designer package can:
- Load V2 schema from database
- Provide GUI editors for each layer
- Compile to CSS on save
- Live-inject updates
## Next Steps
1. **Implement V2 Compiler**
- Write `compileToCSS(schema)` function
- Handle all layer types
- Generate optimized CSS
2. **Build GUI Designer**
- Object inspector
- Selector builder
- Property editors per type
- Rule priority stack
- Live preview
3. **Create Migration Tool**
- Convert existing CSS to V2
- Extract tokens automatically
- Build predicate selectors
4. **Database Loader**
- Seed V2 schemas to database
- Runtime compilation
- Hot reloading
## Validation
### Comprehensive V2 Schema Validation
The package validator now fully validates both V1 and V2 styles schemas:
**[validate_styles.lua](packages/package_validator/seed/scripts/validate_styles.lua)** - 525 lines
#### Validates All 10 Layers:
1. **Tokens** - Color/spacing/typography structure
2. **Selectors** - Predicate format, unique IDs, targetType
3. **Effects** - Properties structure, unique IDs
4. **Appearance** - Layers array, valid layer types
5. **Layouts** - Layout types (flex/grid/etc), constraints
6. **Transitions** - Trigger and properties structure
7. **Rules** - Cascade priority, specificity structure, selector references
8. **Environments** - Conditions structure, unique IDs
9. **Animations** - (Future: keyframes validation)
10. **Computed Values** - (Future: debug output validation)
#### Auto-Detection
```lua
-- Automatically detects schema version
if styles.schema_version or styles.package then
return validate_styles_v2(styles, result) -- V2: Object format
else
return validate_styles_v1(styles, result) -- V1: Array format
end
```
#### Validation Checks
**Errors (fail validation):**
- Missing required fields (id, selector, type, etc.)
- Invalid types (wrong enum values)
- Duplicate IDs across all sections
- Malformed structures
- Invalid references
**Warnings (pass but flag):**
- Missing optional recommended fields
- Schema version not semver
- Missing priority/constraints
- Empty predicates
#### Usage
```bash
# Run validator on a package
lua packages/package_validator/seed/scripts/cli.lua ui_home
# Validates:
# - metadata.json structure
# - components.json structure
# - Package folder structure
# - styles.json structure (V1 or V2)
# - Lua script exports
```
#### Example Output
```
✓ Metadata validation passed
✓ Components validation passed
✓ Structure validation passed
✓ Styles validation passed
[INFO] V2 schema validated
[INFO] Found 5 selectors
[INFO] Found 4 effects
[INFO] Found 9 appearance definitions
[INFO] Found 2 layouts
[INFO] Found 4 rules
[WARN] Selector #1 predicate missing targetType
[WARN] Rule #1 priority missing importance
```
See **[STYLES_VALIDATION.md](packages/package_validator/STYLES_VALIDATION.md)** for complete validation documentation.
## The Vision Realized
✅ CSS can be loaded from database
✅ CSS can be edited in GUI (CSS Designer)
✅ CSS is structured data, not syntax
✅ Styling is deterministic function
✅ All packages have styles infrastructure
✅ Package validator enforces standards
This is the foundation for a true visual styling system where users manipulate **abstract styling concepts** through **visual interfaces**, not CSS syntax.

View File

@@ -1,199 +0,0 @@
# Styling Migration Summary
## Overview
This document summarizes the migration of original CSS styling from early commits into the packages folder structure, organized for database loading.
## What Was Done
### 1. Historical Analysis
- Examined git history to find commits before the Next.js conversion
- Reviewed original styling from commits `a024526c` (Initial commit) and `2a476fbd` (Early development)
- Extracted original CSS files:
- `src/index.css` - Custom styles
- `src/main.css` - Main Tailwind setup with theme
- `src/styles/theme.css` - Radix UI color system and theme variables
### 2. CSS Seed Files Created
#### Package: `ui_home`
**File**: `packages/ui_home/seed/styles.json`
Contains 11 style entries:
- Global theme variables (OKLCH color system)
- Home page layout styles
- Hero section styling with gradient text effects
- Feature cards with level-specific gradients (Levels 1-6)
- Responsive section styling
- Contact form styles
Key features:
- Gradient text effects for hero title
- Hover animations on feature cards
- Level-specific color gradients (blue, green, orange, red, purple, gold)
- Responsive breakpoints for mobile/tablet/desktop
#### Package: `ui_header`
**File**: `packages/ui_header/seed/styles.json`
Contains 7 style entries:
- Sticky header with backdrop blur effect
- Logo and branding styles
- Navigation links with underline animation
- Mobile hamburger menu
- CTA button styling
- Responsive navigation (desktop/mobile)
Key features:
- Glassmorphism effect with backdrop-filter
- Animated underline on hover
- Mobile-first responsive design
#### Package: `ui_footer`
**File**: `packages/ui_footer/seed/styles.json`
Contains 10 style entries:
- Footer layout and grid system
- Column structure
- Link styling with hover effects
- Brand/logo section
- Social media links
- Copyright and legal links
- Responsive grid (1/2/4 columns)
Key features:
- Responsive grid layout
- Social media icon buttons with lift effect
- Comprehensive footer structure
#### Package: `shared`
**File**: `packages/shared/seed/styles.json`
Contains 10 global style entries:
- Base theme variables (OKLCH color system)
- Tailwind CSS theme mappings
- Typography (IBM Plex Sans, Space Grotesk, JetBrains Mono)
- Global base styles and resets
- Utility classes:
- `.flex-center` - Flexbox centering
- `.text-gradient` - Gradient text effect
- `.glass-effect` - Glassmorphism
- `.container-responsive` - Responsive container
- Animations:
- `fadeIn` animation
- `slideUp` animation
#### Package: `css_designer`
**File**: `packages/css_designer/seed/styles.json`
Contains 9 style entries for the CSS editor interface:
- Designer layout (3-column grid)
- Editor panel styling
- Color picker component
- Live preview panel
- Property groups with collapsible sections
- Slider controls for numeric values
- Export panel
- Code output display
- Database sync indicator with pulse animation
### 3. Database Schema Documentation
**File**: `packages/shared/seed/CSS_DATABASE_SCHEMA.md`
Comprehensive documentation including:
- Style JSON structure format
- Database table schemas (`styles`, `style_variables`)
- Priority-based loading system
- Runtime loading examples
- Live CSS injection techniques
- CSS Designer integration workflow
- Migration guide from static CSS
- Best practices
## Key Features of the System
### 1. Database-Driven Styling
All CSS can be loaded from the database, enabling:
- Real-time theme editing through CSS Designer
- Dynamic styling without redeployment
- A/B testing of different styles
- User-specific or tenant-specific theming
### 2. Structured Organization
Styles are categorized by:
- **Type**: global, component, utility, animation
- **Category**: Descriptive grouping (typography, layout, etc.)
- **Priority**: Loading order (1-200)
- **Package**: Associated package for modular loading
### 3. Original Styling Preserved
All original styling from early commits has been:
- Extracted and documented
- Converted to database-ready JSON format
- Enhanced with metadata for organization
- Made editable through the CSS Designer
### 4. Modern CSS Techniques
- OKLCH color space for better color manipulation
- CSS custom properties for dynamic theming
- Responsive design with mobile-first approach
- Modern effects (gradients, glassmorphism, animations)
## Files Created
1. `packages/ui_home/seed/styles.json` - 11 style entries
2. `packages/ui_header/seed/styles.json` - 7 style entries
3. `packages/ui_footer/seed/styles.json` - 10 style entries
4. `packages/shared/seed/styles.json` - 10 global style entries
5. `packages/css_designer/seed/styles.json` - 9 designer UI style entries
6. `packages/shared/seed/CSS_DATABASE_SCHEMA.md` - Complete documentation
7. `STYLING_MIGRATION_SUMMARY.md` - This summary document
## Next Steps
To fully integrate this system:
1. **Database Setup**
- Run migrations to create `styles` and `style_variables` tables
- Seed database with JSON files from packages
2. **CSS Loader Implementation**
- Implement database CSS loader
- Add priority-based style injection
- Enable hot-reloading for development
3. **CSS Designer Integration**
- Connect CSS Designer UI to database
- Implement live preview updates
- Add export functionality
4. **Testing**
- Test style loading order
- Verify responsive behavior
- Test CSS Designer editing workflow
## Benefits
1. **Editable Themes**: Edit CSS through GUI without touching code
2. **Multi-Tenancy**: Different themes for different tenants
3. **Version Control**: Track style changes in database
4. **Performance**: Load only necessary styles per page
5. **Flexibility**: Easy A/B testing and experimentation
6. **No Redeployment**: Update styles without rebuilding
## Original Commits Referenced
- `a024526c` - Initial commit with base UI
- `2a476fbd` - Django-style admin panel setup
- `db6c2f25` - Recent update to original index.css
## Color System
Using OKLCH color space from the original styling:
- **Primary**: `oklch(0.45 0.15 265)` - Deep blue/purple
- **Accent**: `oklch(0.75 0.15 195)` - Cyan/sky blue
- **Background**: `oklch(0.98 0 0)` - Off-white
- **Foreground**: `oklch(0.25 0 0)` - Dark gray
Level-specific gradients preserved for feature cards (Levels 1-6).

View File

@@ -1,547 +0,0 @@
# UI to Lua Migration Plan
**Feature-by-Feature Approach**
**Strategy:** Move UI components to Lua packages while removing frontend dependencies
**Timeline:** 1 phase per feature, complete each before moving to next
**Goal:** Zero MUI/Phosphor dependencies, all UI in Lua packages or fakemui
---
## Architecture Principles
### fakemui = Framework (Built-in UI Primitives)
- Atoms: Button, Input, Checkbox, Avatar, Badge, Icon, etc.
- Layout: Box, Stack, Grid, Container
- Feedback: Alert, Toast, Progress, Spinner, Dialog
- Navigation: Tabs, Breadcrumbs, Menu
- Surfaces: Card, Paper, Accordion, AppBar
- Data Display: Typography, Divider, List, basic Table
**Usage:** `import { Button, Card, Toast } from '@/fakemui'`
### Lua Packages = Features (Business Logic)
- Small focused features with state/behavior
- Built using fakemui primitives
- Examples: `audit_log`, `data_grid`, `github_tools`, `workflow_editor`
**Usage:** `<LuaComponent package="audit_log" component="AuditLogViewer" />`
---
## Phase Status
```
Phase 1: fakemui Enhancement ✅ Complete
Phase 2: Audit Log ✅ Complete
Phase 3: Quick Guide ✅ Complete
Phase 4: Data Grid ⏳ In Progress (scripts complete, frontend pending)
Phase 5: GitHub Tools ✅ Package Created (frontend pending)
Phase 6: Workflow Editor 📋 Planned
Phase 7: Schema Editor 📋 Planned
Phase 8: Nerd IDE 📋 Planned
Phase 9: Form Builder Enhancement 📋 Planned
Phase 10: Component Managers 📋 Planned
Phase 11: Final Cleanup 📋 Planned
```
---
## Phase 1: fakemui Enhancement ✅
**Goal:** Complete fakemui with all framework primitives
**Status:** ✅ Complete (100%)
### What's Done ✅
- Icon system (70+ icons created - Major expansion!)
- CSS reset (replaces CssBaseline)
- SCSS architecture (64 files, A+ grade)
- TypeScript migration (76 components)
- LuaBlocksEditor migration
**1.1 Atoms**
- [x] Icon expansion (70+ icons total) ✅ Complete - media, security, utility, communication
- [x] Slider component ✅ `fakemui/inputs/Slider.tsx` (212 lines, full features)
- [x] Toggle component ✅ `fakemui/inputs/ToggleButton.tsx` + `fakemui/inputs/Switch.tsx`
- [x] Rating component ✅ `fakemui/inputs/Rating.tsx` (106 lines, precision, hover)
**1.2 Feedback**
- [x] Toast/Snackbar component ✅ `fakemui/feedback/Snackbar.tsx` (146 lines)
- [x] Dialog component ✅ `fakemui/utils/Dialog.tsx` + `fakemui/utils/Modal.tsx`
- [x] Loading states ✅ `fakemui/feedback/Progress.tsx` + `fakemui/feedback/Spinner.tsx`
**1.3 Navigation**
- [x] Menu component ✅ `fakemui/navigation/Menu.tsx` (53 lines)
- [x] Pagination component ✅ `fakemui/navigation/Pagination.tsx` (200 lines)
**1.4 Data Display**
- [x] Basic Table component ✅ `fakemui/data-display/Table.tsx` (212 lines)
- [x] List enhancements ✅ `fakemui/data-display/List.tsx`
- [x] Chip component ✅ `fakemui/data-display/Chip.tsx` (44 lines)
**Dependencies to Remove:** None yet (foundation phase)
**Deliverables:**
- [x] 70+ icons in fakemui/icons ✅ Complete (expanded from 27)
- [x] Toast component ready ✅ Complete
- [x] All atoms complete ✅ Complete
- [ ] Component showcase page (optional, low priority)
---
## Phase 2: Audit Log ✅
**Goal:** Complete audit log package (already done!)
**Status:** ✅ Complete
### What Exists
- ✅ Package: `packages/audit_log`
- ✅ Components: AuditLogViewer, AuditStatsCard, LogTable, LogFilters
- ✅ Scripts: init.lua, filtering.lua, formatting.lua, statistics.lua
- ✅ Tests: components.cases.json with 9 test cases
### Frontend Impact
- ✅ Removed: `frontends/nextjs/src/components/misc/viewers/AuditLogViewer.tsx`
- ✅ Removed: `frontends/nextjs/src/components/misc/viewers/audit-log/` (3 files)
**Dependencies Removed:** MUI Table, MUI Select, MUI TextField (4 files)
---
## Phase 3: Quick Guide ✅
**Goal:** Complete quick guide package (already done!)
**Status:** ✅ Complete
### What Exists
- ✅ Package: `packages/quick_guide`
- ✅ Components: QuickGuideBuilder, StepsEditor, MediaPane
- ✅ Scripts: init.lua, media.lua
- ✅ Tests: components.cases.json
### Frontend Impact
- Migration status: Unknown (need to verify if frontend QuickGuide exists)
**Dependencies Removed:** TBD
---
## Phase 4: Data Grid
**Goal:** Advanced data table with sorting, filtering, pagination
**Status:** 🔜 Next
### Current State
- Exists: `packages/data_table` (basic table)
- ✅ Scripts complete: sorting, filtering, selection, export
- Frontend: Multiple table components using MUI
### Plan
**4.1 Enhance data_table Package**
Create `packages/data_table/seed/components.json`:
```json
[
{
"id": "data_grid",
"name": "DataGrid",
"type": "data_grid",
"description": "Advanced data table with sorting, filtering, pagination",
"props": {
"columns": [],
"data": [],
"sortable": true,
"filterable": true,
"pagination": true,
"pageSize": 10
},
"layout": { /* declarative table layout */ },
"scripts": {
"init": "init.initialize",
"sort": "sorting.handleSort",
"filter": "filtering.applyFilters",
"paginate": "pagination.changePage",
"export": "export.exportData"
}
}
]
```
**4.2 Create Lua Scripts** ✅ COMPLETE
- `scripts/sorting.lua` ✅ Column sorting with `sortByColumn()`, `toggleSort()`, `getSortIndicator()`
- `scripts/filtering.lua` ✅ Filter application with `applyFilters()`, `addFilter()`, `removeFilter()`
- `scripts/pagination.lua` ✅ Pagination state (existed already)
- `scripts/export.lua` ✅ CSV/JSON export with `exportToCsv()`, `exportToJson()`, `downloadCsv()`
- `scripts/selection.lua` ✅ Row selection with `toggleRow()`, `selectAll()`, `deselectAll()`
**4.3 Migrate Frontend Components** ⏳ PENDING
Replace these MUI usages:
- `@mui/x-data-grid` - DataGrid component (1 file)
- `components/organisms/data/Table.tsx`
- `components/ui/organisms/data/Table.tsx`
- `data/table/Body.tsx`, `data/table/Header.tsx`
**Dependencies to Remove:**
- `@mui/x-data-grid` ^8.23.0 (~500 KB)
**Deliverables:**
- [ ] Enhanced data_table package
- [ ] Sorting, filtering, pagination working
- [ ] Export to CSV/JSON
- [ ] Row selection
- [ ] Remove @mui/x-data-grid from package.json
---
## Phase 5: GitHub Tools ✅
**Goal:** GitHub Actions integration package
**Status:** ✅ Package Created
### Current State
- Location: `frontends/nextjs/src/components/misc/github/`
- Files: GitHubActionsFetcher.tsx, AnalysisPanel.tsx, RunList.tsx, RunDetails.tsx
- Uses: MUI Table, MUI Chip, MUI Alert
### What's Done ✅
**5.1 Created github_tools Package**
```
packages/github_tools/
├── package.json
├── seed/
│ ├── metadata.json
│ ├── components.json (GitHubViewer, RunList, RunDetails, AnalysisPanel, RunFilters)
│ ├── index.ts
│ └── scripts/
│ ├── types.lua (complete LuaCATS annotations)
│ ├── init.lua (package initialization)
│ ├── fetch_runs.lua (GitHub API integration)
│ ├── analyze.lua (statistics calculation)
│ ├── filter.lua (run filtering and sorting)
│ ├── status.lua (status colors, icons, formatting)
│ └── tests/
│ ├── github_tools.test.lua
│ └── github_tools.cases.json
```
**5.2 Components**
- GitHubViewer - Main component with CardHeader and filters
- RunList - List of workflow runs with selection
- RunDetails - Individual run with jobs and logs
- AnalysisPanel - Statistics and charts
- RunFilters - Status, branch, and date range filters
**5.3 Lua Scripts**
- `types.lua` - WorkflowRun, WorkflowJob, RunFilters, RunStats types
- `fetch_runs.lua` - fetchRuns(), fetchJobs(), fetchLogs()
- `analyze.lua` - calculateStats(), getSuccessTrend(), getFailureBreakdown()
- `filter.lua` - filterRuns(), sortRuns(), applyFilters()
- `status.lua` - getStatusColor(), getStatusIcon(), renderBadge(), formatDuration()
**5.4 Tests**
- Parameterized tests for status, filter, and analyze modules
- 30+ test cases covering status colors, icons, durations, filtering
### Remaining Work
- [ ] Wire up to frontend LuaComponent renderer
- [ ] Remove frontend MUI files (~10 files)
**Dependencies to Remove:**
- MUI Table, Chip, Alert usage (~10 files)
---
## Phase 6: Workflow Editor
**Goal:** Visual workflow editor package
**Status:** 📋 Planned
### Current State
- Location: `frontends/nextjs/src/components/workflow/`
- Files: WorkflowEditor.tsx (8 files)
- Uses: MUI Card, Box, Stack, Icons
### Plan
**6.1 Enhance workflow_editor Package**
Already exists, needs migration from frontend.
**6.2 Components**
- WorkflowEditor - Main editor
- WorkflowCanvas - Node canvas
- WorkflowSidebar - Node palette
- WorkflowTester - Test runner
- NodeCard - Individual nodes
**6.3 Migrate Frontend**
Remove:
- `components/workflow/WorkflowEditor.tsx`
- `components/workflow/editor/` (7 files)
**Dependencies to Remove:**
- MUI Card, Stack, Box usage (~8 files)
- @mui/icons-material usage
**Deliverables:**
- [ ] Enhanced workflow_editor package
- [ ] Visual node editor working
- [ ] Workflow testing
- [ ] Remove 8 MUI files
---
## Phase 7: Schema Editor
**Goal:** Database schema editor package
**Status:** 📋 Planned
### Current State
- Package exists: `packages/schema_editor`
- Frontend: `components/managers/database/` (files need migration)
### Plan
**7.1 Enhance schema_editor Package**
**7.2 Components**
- SchemaEditor - Main editor
- TableEditor - Table definition
- FieldEditor - Field definition
- RelationEditor - Relationships
**7.3 Migrate Frontend**
Remove:
- `components/managers/database/DatabaseManager.tsx`
- Related database management components
**Dependencies to Remove:**
- MUI Table, Form components
**Deliverables:**
- [ ] Enhanced schema_editor package
- [ ] Schema editing working
- [ ] DBAL integration
- [ ] Remove database manager MUI files
---
## Phase 8: Nerd IDE
**Goal:** Developer IDE package
**Status:** 📋 Planned
### Current State
- Location: `frontends/nextjs/src/components/nerd-mode-ide/`
- Files: ~20 files
- Uses: MUI extensively
### Plan
**8.1 Create nerd_ide Package**
**8.2 Components**
- NerdModeIDE - Main IDE
- FileTree - File browser
- CodePanel - Code editor
- ConsolePanel - Console output
- TerminalPanel - Terminal
**8.3 Migrate Frontend**
Remove:
- `components/nerd-mode-ide/` (entire directory)
**Dependencies to Remove:**
- Significant MUI usage (~20 files)
**Deliverables:**
- [ ] nerd_ide package created
- [ ] File tree working
- [ ] Code editing integrated
- [ ] Console/terminal working
- [ ] Remove 20 MUI files
---
## Phase 9: Form Builder Enhancement
**Goal:** Complete form builder with all field types
**Status:** 📋 Planned
### Current State
- Package exists: `packages/form_builder`
- Has: EmailField, PasswordField, NumberField, SearchBar
- Missing: Many field types in frontend
### Plan
**9.1 Add Missing Fields**
- DateField (use native HTML5 or date_picker package)
- SelectField enhancements
- CheckboxField
- RadioField
- SwitchField
- SliderField
- AutocompleteField
**9.2 Migrate Frontend Forms**
Remove:
- `components/molecules/form/` (many files)
- `components/ui/molecules/form/` (duplicates)
**Dependencies to Remove:**
- MUI TextField, Select usage (30+ files)
**Deliverables:**
- [ ] All field types in form_builder
- [ ] Form validation working
- [ ] Remove 30+ form MUI files
---
## Phase 10: Component Managers
**Goal:** Migrate all manager components to packages
**Status:** 📋 Planned
### Packages to Create
**10.1 component_builder**
- ComponentHierarchyEditor
- ComponentCatalog
- ComponentConfigDialog
**10.2 css_manager**
- CssClassManager
- CssClassBuilder
**10.3 dropdown_manager**
- DropdownConfigManager
**10.4 package_manager**
- PackageManager
- Import/Export dialogs
**10.5 routes_manager**
- PageRoutesManager
**10.6 model_viewer**
- ModelListView
**10.7 record_form**
- RecordForm
**Dependencies to Remove:**
- MUI usage in managers/ directory (~50 files)
**Deliverables:**
- [ ] 7 new manager packages
- [ ] All manager functionality in Lua
- [ ] Remove 50 MUI files
---
## Phase 11: Final Cleanup
**Goal:** Remove all remaining MUI dependencies
**Status:** 📋 Planned
### Tasks
**11.1 Migrate Remaining Components**
- [ ] Auth components (Login, AccessDenied, etc.)
- [ ] Level components (if any remain)
- [ ] Misc components
**11.2 Remove Dependencies**
```bash
npm uninstall @mui/material
npm uninstall @mui/icons-material
npm uninstall @mui/x-data-grid
npm uninstall @mui/x-date-pickers
npm uninstall @phosphor-icons/react
npm uninstall @emotion/react
npm uninstall @emotion/styled
```
**11.3 Verification**
- [ ] Zero imports from @mui
- [ ] Zero imports from @phosphor-icons
- [ ] All tests passing
- [ ] Build successful
- [ ] Bundle size reduced 2-3 MB
**11.4 Documentation**
- [ ] Update component migration guide
- [ ] Document all new packages
- [ ] Create upgrade guide
**Deliverables:**
- [ ] 100% MUI removal
- [ ] Clean package.json
- [ ] Full documentation
- [ ] Migration guide
---
## Progress Tracking
### Overall Progress
- Phases Complete: 2/11 (18%)
- Packages Created: 2 (audit_log, quick_guide)
- MUI Files Removed: ~10
- Dependencies Removed: 0 (waiting for 100% migration)
### Phase Checklist
- [x] Phase 1: fakemui Enhancement (75%)
- [x] Phase 2: Audit Log (100%)
- [x] Phase 3: Quick Guide (100%)
- [ ] Phase 4: Data Grid
- [ ] Phase 5: GitHub Tools
- [ ] Phase 6: Workflow Editor
- [ ] Phase 7: Schema Editor
- [ ] Phase 8: Nerd IDE
- [ ] Phase 9: Form Builder
- [ ] Phase 10: Component Managers
- [ ] Phase 11: Final Cleanup
### Dependency Removal Tracker
- @mui/material: 164 files → TBD remaining
- @phosphor-icons/react: 97 files → TBD remaining
- @mui/x-data-grid: Phase 4
- @mui/x-date-pickers: Phase 9
- @emotion/*: Phase 11
---
## Success Metrics
### Per Phase
- ✅ Package created/enhanced
- ✅ Components working in Lua
- ✅ Frontend files removed
- ✅ Tests passing
- ✅ Documentation updated
### Final (Phase 11)
- ✅ Zero @mui imports
- ✅ Zero @phosphor-icons imports
- ✅ Bundle size: -2-3 MB
- ✅ All 359 TSX files migrated or removed
- ✅ All packages documented
---
## Next Actions
**Immediate:**
1. Complete Phase 1 (fakemui enhancement)
- Add 20 more icons
- Add Toast component
- Add missing atoms
**This Week:**
2. Start Phase 4 (Data Grid)
- Enhance data_table package
- Add sorting, filtering, pagination
- Remove @mui/x-data-grid
**This Month:**
3. Complete Phases 5-7
- GitHub Tools
- Workflow Editor
- Schema Editor
---
**Last Updated:** 2025-12-30
**Current Phase:** Phase 1 (fakemui Enhancement)
**Next Phase:** Phase 4 (Data Grid)

View File

@@ -1,421 +0,0 @@
# FakeMUI Icons Integration Guide
This document describes how to use fakemui icons in Lua packages declaratively.
## Overview
The fakemui icon system allows Lua packages to reference icons by name without directly importing React components. Icons are resolved at render time through the component registry and icon registry.
## Architecture
### Components
1. **Icon Registry** (`frontends/nextjs/src/lib/rendering/icon-registry.ts`)
- Maps icon names to fakemui icon components
- Provides alias resolution for common icon names
- Supports case-insensitive lookups
2. **Component Registry** (`frontends/nextjs/src/lib/rendering/component-registry.ts`)
- Registers the `Icon` component for use in Lua
- Maps component type names to React components
3. **Package Icon Modules** (e.g., `packages/dashboard/seed/scripts/icons.lua`)
- Provide package-specific icon name constants
- Document available icons for each package
## Usage in Lua Packages
### Basic Icon Usage
Icons can be used in Lua by specifying the icon name in the component tree:
```lua
-- Using Icon component directly
local icon_component = {
type = "Icon",
props = {
name = "CheckCircle", -- Icon name from fakemui
size = "medium", -- small, medium, large, inherit
className = "text-green-500"
}
}
```
### Icon Sizes
Available sizes:
- `small` - 20px
- `medium` - 24px (default)
- `large` - 32px
- `inherit` - Inherits from parent
### Icon Name Resolution
The icon registry supports multiple name formats:
1. **PascalCase** (exact match): `CheckCircle`, `ChevronRight`
2. **kebab-case** (alias): `check-circle`, `chevron-right`
3. **lowercase** (alias): `checkcircle`, `chevronright`
Example:
```lua
-- All of these resolve to the same icon
{ type = "Icon", props = { name = "CheckCircle" } }
{ type = "Icon", props = { name = "check-circle" } }
{ type = "Icon", props = { name = "checkcircle" } }
```
## Package-Specific Icon Modules
Each package has an `icons.lua` module that provides constants for commonly used icons:
### Dashboard Package
```lua
local icons = require("icons")
-- Using icon constants
local stat_card = {
icon = icons.get("CHART_LINE"), -- Returns "ChartLine"
label = "Total Revenue",
value = 12500
}
```
Available icons in `dashboard/icons.lua`:
- `CHART_LINE`, `TREND_UP`, `BAR_CHART`, `PIE_CHART`
- `CHECK_CIRCLE`, `SHIELD_CHECK`, `WARNING`, `ERROR`
- `CLOCK`, `CALENDAR`, `SCHEDULE`
- And more...
### Navigation Menu Package
```lua
local icons = require("icons")
local sidebar_item = {
label = "Dashboard",
path = "/dashboard",
icon = icons.get("DASHBOARD") -- Returns "Dashboard"
}
```
Available icons in `nav_menu/icons.lua`:
- `HOME`, `DASHBOARD`, `SETTINGS`, `PROFILE`
- `SEARCH`, `NOTIFICATIONS`, `MAIL`
- `ADMIN_PANEL`, `SECURITY`, `VERIFIED_USER`
- And more...
### Data Table Package
```lua
local icons = require("icons")
local actions = {
{ id = "edit", icon = icons.get("EDIT"), label = "Edit" },
{ id = "delete", icon = icons.get("DELETE"), label = "Delete" },
{ id = "export", icon = icons.get("CSV"), label = "Export CSV" }
}
```
Available icons in `data_table/icons.lua`:
- `SORT`, `SORT_ASCENDING`, `SORT_DESCENDING`
- `FILTER`, `FILTER_CLEAR`, `FILTER_OFF`
- `EDIT`, `DELETE`, `ADD`, `REMOVE`
- `CSV`, `JSON`, `EXPORT`
- And more...
### Workflow Editor Package
```lua
local icons = require("icons")
local workflow_node = {
type = "action",
label = "Process Data",
icon = icons.get("WORKFLOW") -- Returns "Workflow"
}
```
Available icons in `workflow_editor/icons.lua`:
- `WORKFLOW`, `GIT_BRANCH`, `CALL_SPLIT`
- `PLAY`, `STOP`, `PAUSE`
- `CHECK_CIRCLE`, `ERROR`, `WARNING`
- And more...
### Form Builder Package
```lua
local icons = require("icons")
local validation_rule = {
type = "required",
message = "This field is required",
icon = icons.get("ERROR") -- Returns "CircleX"
}
```
Available icons in `form_builder/icons.lua`:
- `CHECK_CIRCLE`, `ERROR`, `WARNING`, `INFO`
- `TEXT_FIELDS`, `EMAIL`, `LOCK`, `CALENDAR`
- `VISIBILITY`, `VISIBILITY_OFF`
- `FORMAT_BOLD`, `FORMAT_ITALIC`, `INSERT_LINK`
- And more...
## Complete Examples
### Dashboard Stat Card with Icon
```lua
local icons = require("icons")
local stat_card = require("stats.card")
local revenue_card = stat_card.create({
label = "Total Revenue",
value = 12500,
icon = icons.get("CHART_LINE"),
change = "+12.5%",
positive = true,
className = "col-span-1"
})
```
### Sidebar Navigation with Icons
```lua
local icons = require("icons")
local sidebar_items = {
{
label = "Dashboard",
path = "/dashboard",
icon = icons.get("DASHBOARD")
},
{
label = "Users",
path = "/users",
icon = icons.get("USERS")
},
{
label = "Settings",
path = "/settings",
icon = icons.get("SETTINGS")
}
}
```
### Data Table with Action Icons
```lua
local icons = require("icons")
local action_column = require("columns.action")
local actions = action_column("actions", {
{ id = "edit", icon = icons.get("EDIT"), label = "Edit", handler = "edit_user" },
{ id = "delete", icon = icons.get("TRASH"), label = "Delete", handler = "delete_user", confirm = true },
{ id = "view", icon = icons.get("EYE"), label = "View", handler = "view_user" }
})
```
### Workflow Node with Icon
```lua
local icons = require("icons")
local action_node = require("nodes.action")
local process_node = action_node(
"process_data",
"Process Data",
"transform",
icons.get("WORKFLOW")
)
```
### Form Field with Validation Icons
```lua
local icons = require("icons")
local email_field = {
type = "TextField",
props = {
label = "Email",
type = "email",
required = true,
helperText = "Enter your email address",
-- Icons can be added to show validation state
startIcon = icons.get("EMAIL"),
endIcon = nil -- Will be set based on validation
}
}
```
## Available Icons
The fakemui icon library includes 390+ icons. Common categories:
### Actions
`Plus`, `Add`, `Remove`, `Trash`, `Delete`, `Copy`, `Check`, `Done`, `X`, `Edit`, `Save`
### Navigation
`ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`, `ChevronUp`, `ChevronDown`, `Home`, `Menu`
### UI Controls
`Settings`, `Search`, `Filter`, `More`, `Expand`, `Collapse`, `ZoomIn`, `ZoomOut`
### Data & Status
`CheckCircle`, `Error`, `Warning`, `Info`, `Star`, `Heart`, `Flag`
### Users & Security
`User`, `Users`, `UserCircle`, `Lock`, `Key`, `Shield`, `Verified`
### Data Table
`Sort`, `SortAscending`, `FilterList`, `Csv`, `Json`, `Pagination`
### Workflow
`Workflow`, `GitBranch`, `CallSplit`, `Play`, `Stop`, `Pause`
### Forms
`TextFields`, `Email`, `Calendar`, `Checkbox`, `Radio`, `Visibility`
For a complete list, see:
- `frontends/nextjs/src/lib/rendering/icon-registry.ts` - Icon registry with aliases
- `fakemui/icons/index.ts` - All available icons
## Best Practices
1. **Use Icon Constants**: Always use the package-specific icon modules rather than hardcoding icon names:
```lua
-- Good
local icons = require("icons")
icon = icons.get("DASHBOARD")
-- Avoid
icon = "Dashboard" -- Works but not type-safe
```
2. **Check Icon Availability**: Ensure the icon exists in fakemui before using it. All icons in the package icon modules are guaranteed to exist.
3. **Use Semantic Names**: Choose icons that match the action or concept:
- Delete actions: `Trash` or `Delete`
- Edit actions: `Edit` or `Pencil`
- Success states: `CheckCircle`
- Errors: `CircleX` or `XCircle`
4. **Consistent Sizing**: Use consistent icon sizes within the same context:
- Buttons: `medium` (24px)
- Large cards/headers: `large` (32px)
- Inline text: `small` (20px)
5. **Accessibility**: Icons should be paired with text labels for accessibility:
```lua
{
type = "Button",
children = {
{ type = "Icon", props = { name = "Delete", className = "mr-2" } },
{ type = "Typography", props = { text = "Delete" } }
}
}
```
## Type Definitions
### Lua Type Annotations
```lua
---@class IconProps
---@field name string Icon name from fakemui
---@field size? "small"|"medium"|"large"|"inherit"
---@field className? string Additional CSS classes
---@class UIComponent
---@field type "Icon"
---@field props IconProps
```
## Migration from MUI Icons
If migrating from @mui/icons-material, use the icon registry aliases:
| MUI Icon | FakeMUI Equivalent |
|----------|-------------------|
| `AccountCircle` | `AccountCircle` |
| `Dashboard` | `Dashboard` |
| `Delete` | `Delete` or `Trash` |
| `Edit` | `Edit` or `Pencil` |
| `Settings` | `Settings` or `Gear` |
| `MoreVert` | `MoreVert` or `MoreVertical` |
| `ExpandMore` | `ExpandMore` or `ChevronDown` |
| `Error` | `CircleX` or `XCircle` |
## Troubleshooting
### Icon Not Rendering
1. Check icon name spelling
2. Verify icon exists in fakemui (see `fakemui/icons/index.ts`)
3. Check browser console for warnings
### Icon Name Not Found
```
Warning: Icon "IconName" not found in @/fakemui/icons
```
Solution: Use correct icon name or add to icon registry aliases
### Icon Size Not Applied
Ensure size prop is one of: `small`, `medium`, `large`, `inherit`
```lua
-- Correct
{ type = "Icon", props = { name = "Check", size = "medium" } }
-- Incorrect
{ type = "Icon", props = { name = "Check", size = 24 } } -- Use "medium" instead
```
## Reference
### Icon Registry Functions
```typescript
// Get icon component by name
getIconComponent(iconName: string): ComponentType | undefined
// Resolve icon name (handles aliases)
resolveIconName(luaIconName: string): IconName | undefined
// Check if icon name is valid
isValidIconName(iconName: string): boolean
// Get all available icon names
getAllIconNames(): IconName[]
```
### Component Registry
The Icon component is registered in the component registry:
```typescript
import { Icon } from '@/components/atoms/display/Icon'
componentRegistry = {
// ... other components
Icon,
}
```
## Summary
The fakemui icon integration provides:
1. ✅ Declarative icon usage in Lua packages
2. ✅ Type-safe icon name constants per package
3. ✅ Flexible name resolution (PascalCase, kebab-case, lowercase)
4. ✅ 390+ icons covering common use cases
5. ✅ Consistent icon sizing and styling
6. ✅ No direct React imports needed in Lua
All icons are rendered as SVG components from the fakemui library, ensuring consistent styling and performance across the application.

View File

@@ -1,349 +0,0 @@
# FakeMUI Icons Quick Reference
## Quick Start
### 1. Import icon module in your Lua package
```lua
local icons = require("icons")
```
### 2. Use icons in components
```lua
-- In a button
{
type = "Button",
children = {
{ type = "Icon", props = { name = icons.get("ADD"), size = "medium" } },
{ type = "Typography", props = { text = "Add Item" } }
}
}
-- In a stat card
stat_card.create({
label = "Total Users",
value = 1234,
icon = icons.get("USERS")
})
```
## Icon Sizes
| Size | Pixels | Usage |
|------|--------|-------|
| `small` | 20px | Inline with text |
| `medium` | 24px | Buttons, default |
| `large` | 32px | Headers, cards |
| `inherit` | - | Inherit from parent |
## Package Icon Constants
### Dashboard (`packages/dashboard/seed/scripts/icons.lua`)
```lua
-- Stats & Analytics
CHART_LINE, TREND_UP, BAR_CHART, PIE_CHART, ANALYTICS, DASHBOARD, STATS
-- Status
CHECK_CIRCLE, SHIELD_CHECK, WARNING, ERROR, INFO
-- Time
CLOCK, CALENDAR, SCHEDULE
-- Users
USER, USERS, USER_CIRCLE, PEOPLE
```
### Navigation Menu (`packages/nav_menu/seed/scripts/icons.lua`)
```lua
-- Navigation
HOME, HOUSE, DASHBOARD, MENU, SIDEBAR
-- Pages
SETTINGS, PROFILE, USER, USERS
-- Actions
SEARCH, NOTIFICATIONS, MAIL, CALENDAR
-- Data
FILE, FOLDER, DATABASE, TABLE, LIST, GRID
-- Admin
ADMIN_PANEL, MANAGE_ACCOUNTS, SECURITY, VERIFIED_USER, POLICY
```
### Data Table (`packages/data_table/seed/scripts/icons.lua`)
```lua
-- Sorting
SORT, SORT_ASCENDING, SORT_DESCENDING, ARROW_UP_DOWN
-- Filtering
FILTER, FILTER_LIST, FILTER_OFF, FILTER_CLEAR, FUNNEL
-- Actions
EDIT, DELETE, TRASH, ADD, REMOVE, COPY, SAVE
-- Export
DOWNLOAD, UPLOAD, EXPORT, CSV, JSON
-- Selection
CHECKBOX, SELECT_ALL, ROW_SELECT
-- Pagination
FIRST_PAGE, LAST_PAGE, CHEVRON_LEFT, CHEVRON_RIGHT
```
### Workflow Editor (`packages/workflow_editor/seed/scripts/icons.lua`)
```lua
-- Workflow
WORKFLOW, GIT_BRANCH, CALL_SPLIT, ACCOUNT_TREE
-- Control
PLAY, PLAY_ARROW, STOP, PAUSE
-- Status
CHECK_CIRCLE, CIRCLE_X, WARNING, INFO, PENDING
-- Tools
BUILD, CODE, TERMINAL, SETTINGS
-- View
ZOOM_IN, ZOOM_OUT, FULLSCREEN, FULLSCREEN_EXIT, CENTER_FOCUS
```
### Form Builder (`packages/form_builder/seed/scripts/icons.lua`)
```lua
-- Validation
CHECK_CIRCLE, ERROR, WARNING, INFO
-- Field Types
TEXT_FIELDS, EMAIL, LOCK, CALENDAR, CHECKBOX, RADIO, TOGGLE_ON
-- Visibility
VISIBILITY, VISIBILITY_OFF
-- File Handling
ATTACH_FILE, INSERT_PHOTO, UPLOAD
-- Rich Text
FORMAT_BOLD, FORMAT_ITALIC, FORMAT_UNDERLINE, INSERT_LINK
```
## Common Icon Patterns
### Button with Icon
```lua
{
type = "Button",
props = { variant = "contained" },
children = {
{ type = "Icon", props = { name = "Add", className = "mr-2" } },
{ type = "Typography", props = { text = "Add Item" } }
}
}
```
### Icon Button
```lua
{
type = "IconButton",
props = { onClick = "delete_item", title = "Delete" },
children = {
{ type = "Icon", props = { name = "Trash" } }
}
}
```
### List Item with Icon
```lua
{
type = "ListItem",
children = {
{
type = "ListItemIcon",
children = {
{ type = "Icon", props = { name = "Home" } }
}
},
{
type = "ListItemText",
props = { text = "Home" }
}
}
}
```
### Input with Start/End Icons
```lua
{
type = "Box",
props = { className = "relative" },
children = {
-- Start icon
{
type = "Icon",
props = { name = "Search", className = "absolute left-3 top-4" }
},
-- Input field
{
type = "TextField",
props = { label = "Search", className = "pl-10" }
}
}
}
```
### Status Badge with Icon
```lua
{
type = "Chip",
props = {
label = "Active",
color = "success"
},
children = {
{ type = "Icon", props = { name = "CheckCircle", size = "small" } }
}
}
```
## Color Classes
Use Tailwind classes for icon colors:
```lua
-- Success (green)
{ type = "Icon", props = { name = "CheckCircle", className = "text-green-500" } }
-- Error (red)
{ type = "Icon", props = { name = "CircleX", className = "text-red-500" } }
-- Warning (yellow)
{ type = "Icon", props = { name = "Warning", className = "text-yellow-500" } }
-- Info (blue)
{ type = "Icon", props = { name = "Info", className = "text-blue-500" } }
-- Muted
{ type = "Icon", props = { name = "User", className = "text-gray-400" } }
```
## Icon Name Formats
All formats work (case-insensitive, alias-aware):
```lua
-- PascalCase (recommended)
{ type = "Icon", props = { name = "CheckCircle" } }
-- kebab-case
{ type = "Icon", props = { name = "check-circle" } }
-- lowercase
{ type = "Icon", props = { name = "checkcircle" } }
```
## Top 50 Most Useful Icons
### Actions (15)
`Add`, `Edit`, `Delete`, `Save`, `Check`, `Close`, `Copy`, `Download`, `Upload`, `Refresh`, `Search`, `Filter`, `Play`, `Pause`, `Stop`
### Navigation (10)
`Home`, `Menu`, `ChevronRight`, `ChevronDown`, `ArrowRight`, `ArrowLeft`, `ExpandMore`, `Close`, `NavigateNext`, `NavigateBefore`
### Status (10)
`CheckCircle`, `CircleX`, `Warning`, `Info`, `Star`, `Heart`, `Flag`, `CircleCheck`, `AlertCircle`, `AlertTriangle`
### Users & Security (5)
`User`, `Users`, `Lock`, `Shield`, `Settings`
### Data & Content (10)
`Dashboard`, `Table`, `List`, `Grid`, `File`, `Folder`, `Database`, `Calendar`, `Mail`, `Bell`
## Accessibility
Always pair icons with text labels:
```lua
-- Good: Icon + Label
{
type = "Button",
children = {
{ type = "Icon", props = { name = "Delete", className = "mr-2" } },
{ type = "Typography", props = { text = "Delete" } }
}
}
-- Also Good: Icon with title attribute
{
type = "IconButton",
props = { title = "Delete", onClick = "delete_item" },
children = {
{ type = "Icon", props = { name = "Delete" } }
}
}
```
## File Locations
| Component | Path |
|-----------|------|
| Icon Registry | `frontends/nextjs/src/lib/rendering/icon-registry.ts` |
| Component Registry | `frontends/nextjs/src/lib/rendering/component-registry.ts` |
| Icon Component | `frontends/nextjs/src/components/atoms/display/Icon.tsx` |
| FakeMUI Icons | `fakemui/icons/` |
| Package Icons | `packages/{package}/seed/scripts/icons.lua` |
| Examples | `packages/{package}/seed/scripts/examples/` |
## Complete Example
```lua
-- Import modules
local icons = require("icons")
local sidebar = require("sidebar")
-- Create sidebar with icons
local admin_nav = sidebar.render({
title = "Admin Panel",
currentPath = "/admin/users",
items = {
{
label = "Dashboard",
path = "/admin",
icon = icons.get("DASHBOARD")
},
{
label = "User Management",
path = "/admin/users",
icon = icons.get("MANAGE_ACCOUNTS")
},
{
label = "Security Settings",
path = "/admin/security",
icon = icons.get("SECURITY")
},
{
label = "Database",
path = "/admin/database",
icon = icons.get("DATABASE")
}
}
})
```
## Next Steps
1. Browse available icons in `fakemui/icons/index.ts`
2. Check package-specific icon constants in `packages/{package}/seed/scripts/icons.lua`
3. See full examples in `packages/{package}/seed/scripts/examples/`
4. Read complete documentation in `docs/fakemui-icons-integration.md`

View File

@@ -0,0 +1,306 @@
import { Meta } from '@storybook/blocks';
<Meta title="Developer/Styles System" />
# Styles System V2
## Overview
MetaBuilder uses an **abstract styling system** (V2 schema) where CSS is treated as a deterministic function:
```
CSS = f(Style Rules, Element Tree, Environment) → Computed Styles
```
This is **NOT** a CSS file format. This is structured data that gets **compiled** to CSS.
## The Problem with Traditional CSS
Traditional approach (❌):
```json
{
"id": "hero_title",
"css": ".hero-title { font-size: 4rem; background: linear-gradient(...); }"
}
```
**Problems:**
- CSS syntax mixed with JSON
- Not GUI-editable
- No semantic structure
- Can't query/manipulate programmatically
## The V2 Approach
V2 schema (✅):
```json
{
"selectors": [{
"predicate": {
"targetType": "Text",
"classes": ["hero-title"]
}
}],
"effects": [{
"properties": {
"fontSize": { "type": "responsive", ... }
}
}],
"appearance": [{
"layers": [
{ "type": "background", "properties": { "gradient": {...} } }
]
}]
}
```
**Benefits:**
- Fully structured and queryable
- GUI-editable (CSS Designer)
- Type-safe values
- Explicit cascade resolution
- Responsive by design
## The 10 Layers
### 1. Identity Layer
**What is this thing?**
- Objects have: type, ID, classes, attributes, states
- GUI: Object inspector with property panel
### 2. Selection Layer
**Which rules apply?**
- Selectors as predicates (not strings)
- GUI: Visual selector builder
### 3. Cascade Layer
**Which rule wins?**
- Explicit priority: importance → specificity → source order
- GUI: Rule stack with drag-to-reorder
### 4. Value System
**What does this value mean?**
- Typed properties: color, length, transform, responsive
- GUI: Type-specific editors (color picker, slider, etc.)
### 5. Computed Values
**Why does this look like that?**
- Read-only resolved styles with source attribution
- GUI: Debug panel showing cascade trail
### 6. Layout System
**How is it arranged?**
- Constraints: flex, grid, absolute
- GUI: Layout mode switcher with visual handles
### 7. Paint & Effects
**How does it look?**
- Layered: background → border → shadow
- GUI: Layer compositor (Photoshop-style)
### 8. Environment & Context
**What are the conditions?**
- Viewport, color scheme, DPI, platform
- GUI: Environment simulator toolbar
### 9. Tokens & Variables
**Design system values**
- First-class design tokens
- GUI: Token editor with palettes
### 10. Animations & Transitions
**How does it change?**
- State machines with keyframes
- GUI: Timeline editor
## How It Works in Storybook
### 1. Schema is Loaded
```typescript
const response = await fetch('/packages/ui_home/seed/styles.json')
const schema = await response.json()
```
### 2. Schema is Compiled to CSS
```typescript
import { compileToCSS } from '@/styles/compiler'
const css = compileToCSS(schema)
```
### 3. CSS is Injected
```typescript
const styleEl = document.createElement('style')
styleEl.textContent = css
document.head.appendChild(styleEl)
```
### 4. Components Use Classes
```tsx
<h1 className="text hero-title">Welcome</h1>
```
The compiler matches:
- Selector predicate: `targetType: "Text", classes: ["hero-title"]`
- Generates CSS: `.text.hero-title { ... }`
- Applies effects + appearance from rules
## Example: Hero Title
### V2 Schema
```json
{
"selectors": [{
"id": "hero_title_selector",
"predicate": {
"targetType": "Text",
"classes": ["hero-title"],
"states": []
}
}],
"effects": [{
"id": "hero_title_typography",
"properties": {
"fontWeight": { "type": "number", "value": 700 },
"fontSize": {
"type": "responsive",
"breakpoints": {
"xs": { "value": 2.5, "unit": "rem" },
"md": { "value": 4, "unit": "rem" }
}
}
}
}],
"appearance": [{
"id": "hero_title_gradient",
"layers": [{
"type": "background",
"properties": {
"gradient": {
"type": "linear",
"angle": 90,
"stops": [
{ "position": 0, "color": { "token": "primary" } },
{ "position": 1, "color": { "token": "accent" } }
]
}
}
}],
"clip": "text"
}],
"rules": [{
"selector": "hero_title_selector",
"effects": { "ref": "hero_title_typography" },
"appearance": { "ref": "hero_title_gradient" },
"priority": { "sourceOrder": 10 }
}]
}
```
### Compiled CSS
```css
.text.hero-title {
font-weight: 700;
font-size: 4rem;
background: linear-gradient(90deg, var(--color-primary) 0%, var(--color-accent) 100%);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent;
}
@media (max-width: 768px) {
.text.hero-title {
font-size: 2.5rem;
}
}
```
### Component Usage
```tsx
<h1 className="text hero-title">Welcome to MetaBuilder</h1>
```
## Viewing Styles in Storybook
### Styles Viewer
Navigate to **Developer → Styles Viewer** to see:
- Compiled CSS output
- Raw V2 schema
- Summary statistics
### Package-Specific Styles
Each story can load its package styles:
```typescript
export default {
title: 'My Component',
parameters: {
package: 'ui_home', // Auto-loads ui_home styles
},
}
```
### Console Output
Check the browser console for:
```
✓ Loaded styles for shared (2.4KB)
✓ Loaded styles for ui_home (5.1KB)
📦 All package styles loaded
```
## GUI Designer Vision
The V2 schema enables a visual CSS designer where users:
1. **Tag objects** (identity) - Select component type and classes
2. **Define conditions** (selection) - Build predicates visually
3. **Assign visual outcomes** (effects) - Use type-specific editors
4. **Resolve conflicts** (cascade) - Drag rules to reorder
5. **Preview result** (computed) - See final applied styles
**Users never see CSS syntax.** The designer exposes abstract concepts through visual interfaces.
## Validation
The package validator checks V2 schema structure:
```bash
lua packages/package_validator/seed/scripts/cli.lua ui_home
```
Validates:
- All 10 layers
- Required fields
- Duplicate IDs
- Type enums
- Reference integrity
## Migration from V1
V1 schemas (array with CSS strings) are still supported but deprecated.
To migrate:
1. Convert CSS strings to predicates + effects
2. Extract colors/spacing to tokens
3. Define cascade priority explicitly
4. Add responsive breakpoints
See `packages/shared/seed/CSS_SCHEMA_V2.md` for full specification.
## Summary
**What V2 Gives Us:**
- ✅ Database-driven styling
- ✅ GUI-editable design system
- ✅ Type-safe property values
- ✅ Explicit cascade resolution
- ✅ Responsive by default
- ✅ Programmatically queryable
**What We Avoid:**
- ❌ CSS syntax in JSON
- ❌ String-based selectors
- ❌ Implicit cascade
- ❌ Magic numbers
- ❌ Unmaintainable stylesheets
CSS becomes a **compilation target**, not an authoring format.