# Now.js Framework - Key Findings Summary

## Overview
Comprehensive analysis of the Now.js Framework adminframework project showing a sophisticated pattern of declarative HTML-based configuration with server-side controllers and client-side managers.

## Critical Components

### 1. **FormManager** (141KB - Largest Manager)
- Handles form submission, validation, data binding
- Supports auto-validation, AJAX submission, file uploads
- Integrates with ElementFactory for field types
- Key config: `autoValidate`, `ajaxSubmit`, `preventDoubleSubmit`
- **Use case**: All forms in the application (profile, settings, etc.)

### 2. **TableManager** (236KB - Largest Manager)
- Dynamic data table rendering with sorting/filtering/pagination
- Supports row actions, bulk actions, search across columns
- Dynamic column generation from API responses
- Editable rows with inline editing
- **Use case**: User lists, settings lists, category listings

### 3. **ApiService** (43KB)
- High-level HTTP service with caching, retries, deduplication
- CSRF protection, JWT refresh, bearer auth support
- Request deduplication prevents duplicate API calls
- Cache with memory/session/local storage options
- Exponential backoff retries

### 4. **ReactiveManager** (26KB)
- Reactive data binding using JavaScript Proxies
- Automatic UI updates when data changes
- Batched updates for performance
- Computed properties with caching

### 5. **ComponentManager** (34KB)
- Manages UI components (sidebar, topbar, api-driven components)
- Auto-initialization via CoreObserver
- Template caching
- Lifecycle hooks

### 6. **AuthManager** (41KB)
- Authentication state management
- JWT token handling (HttpOnly + memory hybrid)
- Role-based access control (RBAC)
- Permission checking

## Design Patterns

### Pattern 1: Declarative Data Binding
HTML attributes declare what to do; JavaScript interprets:

```html
<!-- Tables -->
<table data-table="users" 
       data-source="api/index/users"
       data-row-actions='{...}'
       data-actions='{...}'>

<!-- Forms -->
<form data-form="profile"
      data-load-api="api/index/profile/get"
      action="api/index/profile/save">
  <input data-attr="value:username,disabled:!isSuperAdmin">

<!-- Components -->
<aside data-component="sidebar"></aside>
```

### Pattern 2: Manager Pattern
All functionality organized as singletons:
```javascript
Manager = {
  config: {...},
  state: {...},
  async init(options) {...},
  method1() {...}
}
```

### Pattern 3: Convention-Based Routing
- `/api/{module}/{controller}/{action}` pattern
- `GET /api/index/users` → list with pagination/filter
- `GET /api/index/profile/get?id=123` → single record
- `POST /api/index/profile/save` → create/update

### Pattern 4: Factory Pattern for Form Elements
Each input type has a factory:
- TextElementFactory
- SelectElementFactory
- FileElementFactory
- DateElementFactory
- MultiSelectElementFactory
- PasswordElementFactory
- etc.

### Pattern 5: Observer Pattern (CoreObserver)
Automatic component initialization and cleanup:
```javascript
CoreObserver.onAdd('[data-component]', element => {
  ComponentManager.mount(element, name, props);
});
```

### Pattern 6: Event-Driven Architecture
Decoupled component communication:
```javascript
EventManager.emit('user:created', {id, name});
EventManager.on('table:refresh', () => {...});
```

## Data Flow Architecture

### Table Data Flow
```
HTML Template → TableManager.initTable()
  ↓
Read data-* attributes (source, sort, search)
  ↓
ApiService.get(data-source + params)
  ↓
Controller.get() → Model.toDataTable()
  ↓
Database query with filter/sort/pagination
  ↓
JSON Response {success, data: [rows], meta: {total, page}}
  ↓
TableManager.renderTable()
  ↓
Apply templates, format, attach handlers
  ↓
Display in browser
```

### Form Data Flow (Load)
```
HTML Form → FormManager.initForm()
  ↓
data-load-api → ApiService.get()
  ↓
Controller.get() → Model.get()
  ↓
FormManager._bindFormData()
  ↓
Parse data-attr bindings
  ↓
Element.value = data.field
  ↓
Load options for selects from response.options
  ↓
Form displayed with data
```

### Form Data Flow (Submit)
```
User modifies and submits form
  ↓
FormManager validates (client-side)
  ↓
FormManager.serializeFormData()
  ↓
ApiService.post(action, formData)
  ↓
Controller.save() → Model.save() → DB update
  ↓
Response {success, message, redirect, formErrors}
  ↓
FormManager.handleResponse()
  ↓
Show notification, reset, redirect, or show errors
```

## Controller/Model Pattern

### Controllers (/modules/index/controllers/)
```php
class Controller extends ApiController {
  public function get(Request $request) {
    // Validate auth
    // Get params
    // Call Model::toDataTable() or Model::get()
    // Return successResponse()
  }
  
  public function save(Request $request) {
    // Validate input
    // Call Model::save()
    // Return success/error with formErrors
  }
  
  public function action(Request $request) {
    // Perform bulk action
    // Return success/error
  }
}
```

### Models (/modules/index/models/)
```php
class Model extends \Kotchasan\Model {
  public static function toDataTable($params) {
    // Handle search, filters, sort, pagination
    // Return array of records
  }
  
  public static function get($id) {
    // Single record query
  }
  
  public static function save($request) {
    // Insert/update database
  }
  
  public static function performAction($id, $action) {
    // Bulk action (approve, delete, activate, etc.)
  }
}
```

## Template Patterns

### Table Template Pattern
```html
<table data-table="users" 
       data-source="api/index/users"
       data-default-sort="created_at desc"
       data-page-size="25"
       data-search-columns="name,phone,username"
       data-show-checkbox="true"
       data-actions='{"approval":"...","delete":"..."}'
       data-action-url="api/index/users/action"
       data-row-actions='{...}'>
  <thead>
    <tr>
      <th data-field="id" data-sort="id">ID</th>
      <th data-field="name" data-sort="name"
          data-template="<span>${name}</span>"
          data-format="uppercase">Name</th>
      <th data-field="status" data-sort="status"
          data-filter="true" data-type="select">Status</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
```

### Form Template Pattern
```html
<form data-form="profile"
      data-validate="true"
      data-reset="true"
      action="api/index/profile/save"
      method="post"
      data-ajax-submit="true"
      data-load-api="api/index/profile/get"
      data-load-query-params="true">
  
  <input data-attr="value:username" required>
  <input data-attr="value:email,disabled:isReadOnly">
  <select data-attr="value:status" data-options-key="status">
    <option>...</option>
  </select>
  <input type="file" data-files="avatar" data-preview="true">
  
  <button type="submit">Save</button>
</form>
```

### Component Template Pattern
```html
<aside data-component="sidebar"></aside>
<header data-component="topbar"></header>
<div data-component="api"
     data-api-url="api/stats"
     data-template="<p>${message}</p>"></div>
```

## Key Files & Their Roles

| File | Size | Purpose |
|------|------|---------|
| TableManager.js | 236KB | Table rendering, pagination, filtering, actions |
| FormManager.js | 141KB | Form submission, validation, data binding |
| ApiService.js | 43KB | HTTP requests, caching, auth, retries |
| TemplateManager.js | 127KB | Template loading, directives, expression eval |
| Now.js | Core entry, manager registration |
| ElementFactory.js | 26KB | Base class for form element factories |
| Component factories | Various | TextElementFactory, SelectElementFactory, etc. |
| AuthManager.js | 41KB | Auth state, login/logout, RBAC |
| RouterManager.js | 55KB | Client-side routing, auth guards |

## Real Examples from Codebase

### Example 1: Users Table (`/templates/users.html`)
- Displays users with avatar, name, status
- Supports sorting by ID, name, created date
- Supports searching by name, phone, username
- Supports filtering by department and status
- Bulk actions: approval, sendactivation, activate, deactivate, delete
- Row actions: edit, impersonate (conditional on id != 1)

### Example 2: Profile Form (`/templates/profile.html`)
- Text inputs with data-attr bindings
- File upload with preview (avatar, signature)
- Nested data access: `data-attr="value:metas['department'][0]"`
- Conditional fields: `data-if="isSuperAdmin"`
- Fieldsets organized by section
- Hidden field for ID
- Save button at bottom

### Example 3: Settings with Editable Table (`/templates/settings/categories.html`)
- Form containing an editable table
- Table has `data-editable-rows="true"`
- Form submits both settings and table data
- Dynamic column generation option

## API Response Format

```json
{
  "success": true,
  "data": {
    "id": 1,
    "name": "John",
    "email": "john@example.com",
    "options": {
      "status": [
        {"value": "0", "text": "Inactive"},
        {"value": "1", "text": "Active"}
      ]
    }
  },
  "message": "Operation successful",
  "error": null,
  "formErrors": null,
  "redirect": null
}
```

On error:
```json
{
  "success": false,
  "message": "Validation failed",
  "formErrors": {
    "email": ["Valid email is required"],
    "password": ["Password must be at least 8 characters"]
  }
}
```

## Configuration Examples

### FormManager Init
```javascript
FormManager.init({
  ajaxSubmit: true,
  autoValidate: true,
  resetAfterSubmit: false,
  preventDoubleSubmit: true,
  validateOnInput: true,
  validateOnBlur: true,
  showErrorsInline: true
});
```

### TableManager Init
```javascript
TableManager.init({
  urlParams: true,
  pageSizes: [10, 25, 50, 100],
  showCheckbox: false,
  searchColumns: [],
  dynamicColumns: false,
  cache: false
});
```

### ApiService Init
```javascript
ApiService.init({
  baseURL: '',
  retryCount: 3,
  deduplicate: true,
  security: {
    csrfProtection: true,
    authStrategy: 'hybrid'  // HttpOnly + memory
  },
  cache: {
    enabled: true,
    storageType: 'memory',
    expiry: {default: 60000, get: 60000, post: 0}
  }
});
```

## Security Features

1. **CSRF Protection**: Automatic token injection
2. **Auth Strategies**: HttpOnly cookies + memory tokens (hybrid)
3. **Request Validation**: Server-side input validation in models
4. **Permission Checks**: Controller-level authorization
5. **XSS Prevention**: Template sanitization
6. **SQL Injection Prevention**: Parameterized queries in models
7. **Password Security**: Strength validation, hashing server-side

## Performance Optimizations

1. **Request Deduplication**: Prevents duplicate API calls
2. **Response Caching**: Memory/session/local storage with TTL
3. **Template Caching**: Compiled templates cached
4. **Batched Updates**: ReactiveManager batches changes
5. **Lazy Loading**: Modules loaded on demand
6. **Exponential Backoff**: Smart retry strategy
7. **URL Parameters**: Table state persisted in URL for bookmarkability

## Development Workflow for New Features

1. Create HTML template in `/templates/`
2. Create controller in `/modules/index/controllers/`
3. Create model in `/modules/index/models/`
4. FormManager/TableManager auto-initializes via data-* attributes
5. No JavaScript needed for basic CRUD

## Key Architectural Principles

1. **Declarative over Imperative** - HTML declares intent
2. **Convention over Configuration** - Standard URL patterns
3. **Manager Pattern** - Singleton managers for each feature
4. **Reactive Binding** - Auto UI updates on data change
5. **Event-Driven** - Components communicate via events
6. **Security First** - Auth, CSRF, validation built-in
7. **Separation of Concerns** - Controller/Model/View separation
8. **Progressive Enhancement** - HTML baseline + JS enhancement
9. **Caching Strategy** - Multi-layer caching with TTLs
10. **Observer Pattern** - Auto-init and cleanup via CoreObserver

## Total Line Count
Analysis: 1,859 lines of comprehensive documentation

---

Ready for documentation creation!
