6 Commits

Author SHA1 Message Date
8300e43e14 feat: add date field overrides for fetch-requests and allow type/label in overrides 2026-06-10 00:40:19 +05:30
386297dc1e fix: date rendering now shows only date for date fields 2026-06-10 00:29:19 +05:30
a227c14e0a removed displayField 2026-06-08 01:03:00 +05:30
58df11c623 refactor: replace all displayField usages with displayFormat 2026-06-08 00:55:54 +05:30
9771816cf9 getDisplayString fix to use displayFormat 2026-06-08 00:37:17 +05:30
7bd946ec7a Refactor the React OpenAPI admin framework to support fully customizable field rendering and UI composition. (#11)
# Summary

Refactor the React OpenAPI admin framework to support fully customizable field rendering and UI composition.

## Changes

### Admin UI Customization

* Added support for custom:

  * Dashboard component
  * Layout component
  * Login page component
* Introduced `AdminAppProps` and extended `Admin` configuration API.
* Renamed internal dashboard implementation to `DefaultDashboard`.

### Field Component Architecture

* Extracted field rendering into dedicated field components:

  * TextField
  * NumberField
  * BooleanField
  * DateField
  * EnumField
  * RelationField
  * ObjectField
  * FallbackField
  * DateRangeField
  * NumberRangeField
* Added `defaultFieldComponents` registry.
* Refactored `FormField` to resolve components dynamically from a component map instead of hardcoded field type handling.

### Resource Customization

* Added `FieldComponents` support across:

  * Admin
  * ResourceView
  * GenericForm
  * useResource
* Introduced wrapped `FormField` and `GenericForm` components generated from configured field overrides.

### Table Customization

* Added `EnhancedTableComponents`.
* Added support for custom cell renderers per field type.
* Enabled custom rendering for both desktop and mobile table layouts.

### Filter Improvements

* Exported `FilterAutocomplete`.
* Added support for custom date-range and number-range filter components.
* Added filter component extension points.
* Updated filter option label resolution to support `displayFormat`.

### Display Formatting

* Replaced `displayField` usage with `displayFormat`.
* Added template-based display rendering support through `resolveTemplate`.
* Improved relation display configuration handling.

### TypeScript Improvements

* Added TypeScript as a project dependency.
* Removed multiple `@ts-ignore` usages.
* Added strongly typed Axios wrapper methods with generic response support.
* Improved typing across hooks and component interfaces.

### OpenAPI Configuration Validation

* Added validation for enum fields without enum values.
* Added validation for relation resources missing `referenceOptions.enumOption`.
* Improved relation metadata propagation during schema parsing.

### Library Exports

* Exported:

  * Field component types
  * Override types
  * EnhancedTable
  * GenericForm
  * ResourceView
  * Field components and defaults
* Expanded public API surface for consumers extending the framework.

## Benefits

* Enables complete UI customization without modifying framework internals.
* Simplifies creation of custom field types and renderers.
* Improves type safety and developer experience.
* Provides consistent extension points for forms, tables, filters, and admin layouts.
* Makes the framework more suitable for reusable library distribution.

Reviewed-on: #11
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
2026-06-07 12:35:52 +00:00
13 changed files with 517 additions and 26 deletions

40
.dockerignore Normal file
View File

@@ -0,0 +1,40 @@
# Node modules
node_modules
**/node_modules
# Logs
*.log
logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Build outputs
build
dist
out
.next
.cache
.parcel-cache
# Environment files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# OS files
.DS_Store
Thumbs.db
# IDE / Editor folders
.vscode
.idea
*.sublime-workspace
*.sublime-project
# Temporary files
*.swp
*.bak
*.tmp

140
.drone.yml Normal file
View File

@@ -0,0 +1,140 @@
---
kind: pipeline
type: docker
name: default
platform:
os: linux
arch: arm64
workspace:
path: /drone/src
volumes:
- name: dockersock
host:
path: /var/run/docker.sock
steps:
- name: fetch-tags
image: docker:24
volumes:
- name: dockersock
path: /var/run/docker.sock
commands:
- apk add --no-cache git
- git fetch --tags
- |
# Get latest Git tag and trim newline
LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null | tr -d '\n')
echo "Latest Git tag fetched: $LATEST_TAG"
# Save to file for downstream steps
echo "$LATEST_TAG" > /drone/src/LATEST_TAG.txt
# Read back for verification
IMAGE_TAG=$(cat /drone/src/LATEST_TAG.txt | tr -d '\n')
echo "Image tag read from file: $IMAGE_TAG"
# Validate
if [ -z "$IMAGE_TAG" ]; then
echo "❌ No git tags found! Cannot continue."
exit 1
fi
- name: check-remote-image
image: docker:24
volumes:
- name: dockersock
path: /var/run/docker.sock
commands:
- IMAGE_TAG=$(cat /drone/src/LATEST_TAG.txt | tr -d '\n')
- echo "Checking if apps/khata:$IMAGE_TAG exists on remote Docker..."
- echo "Existing Docker tags for apps/khata:"
- docker images --format "{{.Repository}}:{{.Tag}}" | grep "^apps/khata" || echo "(none)"
- |
if docker image inspect apps/khata:$IMAGE_TAG > /dev/null 2>&1; then
echo "✅ Docker image apps/khata:$IMAGE_TAG already exists — skipping build"
exit 78
else
echo "⚙️ Docker image apps/khata:$IMAGE_TAG not found — proceeding to build..."
fi
- name: build-image
image: docker:24
environment:
API_BASE_URL:
from_secret: API_BASE_URL
AUTH_BASE_URL:
from_secret: AUTH_BASE_URL
volumes:
- name: dockersock
path: /var/run/docker.sock
commands:
- IMAGE_TAG=$(cat /drone/src/LATEST_TAG.txt | tr -d '\n')
- echo "🔨 Building Docker image apps/khata:$IMAGE_TAG ..."
- |
docker build --network=host \
--build-arg VITE_API_BASE_URL="$API_BASE_URL" \
--build-arg VITE_AUTH_BASE_URL="$AUTH_BASE_URL" \
-t apps/khata:$IMAGE_TAG \
-t apps/khata:latest \
/drone/src
- name: push-image
image: docker:24
environment:
REGISTRY_HOST:
from_secret: REGISTRY_HOST
REGISTRY_USER:
from_secret: REGISTRY_USER
REGISTRY_PASS:
from_secret: REGISTRY_PASS
volumes:
- name: dockersock
path: /var/run/docker.sock
commands:
- IMAGE_TAG=$(cat /drone/src/LATEST_TAG.txt | tr -d '\n')
- echo "🔑 Logging into registry $REGISTRY_HOST ..."
- echo "$REGISTRY_PASS" | docker login $REGISTRY_HOST -u "$REGISTRY_USER" --password-stdin
- echo "🏷️ Tagging images with registry prefix..."
- docker tag apps/khata:$IMAGE_TAG $REGISTRY_HOST/apps/khata:$IMAGE_TAG
- docker tag apps/khata:$IMAGE_TAG $REGISTRY_HOST/apps/khata:latest
- echo "📤 Pushing apps/khata:$IMAGE_TAG ..."
- docker push $REGISTRY_HOST/apps/khata:$IMAGE_TAG
- echo "📤 Pushing apps/khata:latest ..."
- docker push $REGISTRY_HOST/apps/khata:latest
- name: stop-old
image: docker:24
volumes:
- name: dockersock
path: /var/run/docker.sock
commands:
- echo "🛑 Stopping old container..."
- docker rm -f khata || true
- name: run-container
image: docker:24
volumes:
- name: dockersock
path: /var/run/docker.sock
commands:
- IMAGE_TAG=$(cat /drone/src/LATEST_TAG.txt | tr -d '\n')
- echo "🚀 Starting container apps/khata:$IMAGE_TAG ..."
- |
docker run -d \
--name khata \
-p 3002:3000 \
-e NODE_ENV=production \
--restart always \
apps/khata:$IMAGE_TAG
# Trigger rules
trigger:
event:
- tag

24
CONCEPT.md Normal file
View File

@@ -0,0 +1,24 @@
# Concept Overview
The application is a **metadatadriven admin UI** built on top of an OpenAPI description. By describing each resource in a small JSON config (type `ResourceConfig`), the UI automatically generates:
1. **Data tables** (with pagination, sorting, and actions) `EnhancedTable`.
2. **Dynamic filters** `FilterBar` creates appropriate filter widgets (autocomplete, numberrange, daterange) based on field metadata.
3. **Forms for create/edit** A generic form component can render inputs for every `ResourceField`, handling relations via the `displayFormat` template.
4. **Authentication layer** `reactauth` supplies a central `AuthProvider`, a `useAuth` hook, and route guarding, ensuring only authenticated users reach the admin pages.
### Core Principles
- **Declarative configuration**: Adding a new resource is just a JSON entry; no handcoded tables or forms.
- **Templatebased display**: `displayFormat` (e.g. `"{{firstName}} {{lastName}}"`) defines how related objects are shown across the UI, eliminating the need for separate `displayField` props.
- **Extensible UI**: Consumers can plug custom components (`components` prop) to override cell renderers, filter widgets, or action buttons without altering core logic.
- **Unified state**: TanStack Query caches server data, while `reactauth` manages JWTs and user info. Both are provided via React context for easy access.
- **Responsive design**: The UI automatically switches to a cardbased layout on mobile, preserving functionality with a consistent look.
### Migration Goal for Lovable
The current repo implements these ideas with a solid foundation but could benefit from:
- **Improved UI/UX** (e.g., better loading states, richer snackbars, darkmode toggle).
- **More robust error handling** (centralized toast system, retry logic on auth failures).
- **Enhanced theming** (customizable palette, brand colors).
- **Accessibility** (ARIA roles, keyboard navigation).
By reusing the existing `ResourceConfig` schema and `displayFormat` logic, the Lovable implementation can focus on UI polish and advanced handling while keeping the powerful codegeneration approach intact.

34
DESIGN.md Normal file
View File

@@ -0,0 +1,34 @@
# Design Overview
## ReactAuth
- **Purpose**: Centralize authentication flows (login, logout, token refresh) for the UI.
- **Key Concepts**
- **AuthProvider** React context that stores `user`, `accessToken`, and `isAuthenticated`.
- **useAuth hook** Exposes `login`, `logout`, `refreshToken`, and state values.
- **Route Guard** HOC/Component (`ProtectedRoute`) that redirects unauthenticated users to the login page.
- **UI**: Simple MUI forms, error handling with snackbars, and a loading spinner while the auth request is pending.
- **Extensibility**: Plugin point for additional providers (OAuth, SSO) via a `providers` map.
## ReactOpenAPI
- **Purpose**: Generate UI components directly from an OpenAPI spec (tables, filters, forms).
- **Core Modules**
- `ResourceConfig` & `ResourceField` Typed definitions that describe each endpoint and its fields, including `displayFormat` for rendering.
- `EnhancedTable` Datagrid component that renders rows according to the config, supports relation rendering, sorting, pagination, and custom cell renderers.
- `FilterBar` Dynamically builds filter controls (autocomplete, numberrange, daterange) based on the same config.
- **Data Flow**
1. Load OpenAPI spec → transform to `ResourceConfig` objects.
2. `useQuery` (TanStack) fetches data.
3. UI components consume the config to render tables and filter UI without handwritten column definitions.
- **Design Goals**
- **Zero boilerplate** Adding a new resource only requires a JSON config.
- **Consistency** All tables share pagination, actions, and styling.
- **Extensibility** Override components via `components` prop.
## src (Root Application)
- **Entry Point** `main.tsx` mounts the React app with `BrowserRouter` and wraps it with `AuthProvider`.
- **Routing** Routes are defined perresource (`/admin/:resource`, `/admin/:resource/edit/:id`). `ProtectedRoute` ensures auth.
- **State Management** TanStack Query handles server state; React Context handles auth state.
- **Theming** MUI theming with light/dark mode toggle (future enhancement).
---
These design notes serve as a concise reference for developers preparing a richer UI/UX implementation on the **lovable** platform.

33
Dockerfile Normal file
View File

@@ -0,0 +1,33 @@
# Stage 1: Build
FROM node:20-alpine AS builder
# Set working directory
WORKDIR /app
# Copy package.json and package-lock.json (or yarn.lock)
COPY package*.json ./
# Install dependencies
RUN npm ci
# Copy the rest of the app
COPY . .
# Build the app
ARG VITE_API_BASE_URL
ARG VITE_AUTH_BASE_URL
RUN VITE_API_BASE_URL=$VITE_API_BASE_URL VITE_AUTH_BASE_URL=$VITE_AUTH_BASE_URL npm run build
# Stage 2: Static file server (BusyBox)
FROM busybox:latest
WORKDIR /app
# Copy only build frontend files
COPY --from=builder /app/dist /app
# Expose port
EXPOSE 3000
# Default command
CMD ["busybox", "httpd", "-f", "-p", "3000"]

49
IMPLEMENTATION.md Normal file
View File

@@ -0,0 +1,49 @@
# Implementation Details
## ReactAuth
- **File Structure**
- `src/auth/AuthContext.tsx` Provides `AuthContext` and `AuthProvider`.
- `src/auth/useAuth.ts` Custom hook returning context values and actions.
- `src/auth/ProtectedRoute.tsx` Wrapper component that checks `isAuthenticated` and redirects.
- `src/auth/api.ts` Thin wrapper around `axios` for login, logout, refresh.
- **Logic**
1. On `login`, POST credentials → store `accessToken` & user info in context and `localStorage`.
2. An `axios` interceptor attaches the token to every request.
3. `refreshToken` runs on 401 responses; it attempts a silent refresh and updates the context.
4. `logout` clears context and storage, navigating back to `/login`.
- **UI Components**
- `LoginForm` MUI `TextField`s, validation, and submit handling.
- `AuthLoading` Fullscreen spinner displayed while session restoration runs on app boot.
## ReactOpenAPI
- **Core Files**
- `src/react-openapi/types/config.ts` Already defines `ResourceField` with `displayFormat`.
- `src/react-openapi/utils/options.ts` Helper `resolveTemplate` parses `{{field}}` placeholders using the item data.
- `src/react-openapi/components/EnhancedTable.tsx` Renders a MUI `DataGrid`. Uses `getFormattedDisplayValue` to compute readable labels for relation fields based on `displayFormat`.
- `src/react-openapi/components/FilterBar.tsx` Generates filter inputs; extracts option labels using the same `displayFormat` logic.
- **Data Fetching**
- `useResource(resourceName)` TanStack `useQuery` hook that builds the endpoint URL from `config.endpoint` and fetches data via the shared Axios instance.
- **Customization**
- `components` prop passed to `EnhancedTable`/`FilterBar` allows overriding cell renderers, filter widgets, and action buttons.
- **Error Handling**
- Centralized error toast (`useToast`) displays API errors.
- Table shows “No data” state when an empty array is returned.
## src (Application Core)
- **src/main.tsx** Sets up MUI theme, React Router, `AuthProvider`, and `QueryClientProvider`.
- **src/App.tsx** Defines routes:
```tsx
<Routes>
<Route path="/login" element={<LoginForm />} />
<Route element={<ProtectedRoute />}>
<Route path="/admin/:resource" element={<ResourceList />} />
<Route path="/admin/:resource/edit/:id" element={<ResourceForm />} />
</Route>
</Routes>
```
- **src/pages/ResourceList.tsx** Reads `resource` from URL, loads its `ResourceConfig`, calls `useResource`, and renders `EnhancedTable` + `FilterBar`.
- **src/pages/ResourceForm.tsx** Dynamically builds a form based on `ResourceField` definitions, using `displayFormat` for default values.
- **State Management** TanStack Query caches paginated results; `AuthProvider` ensures all API calls include a valid JWT.
- **Theming** `ThemeProvider` toggles light/dark mode via a context hook that persists the preference in `localStorage`.
These implementation notes detail the concrete file layout, data flow, and core logic that power the UI generated from OpenAPI specifications while maintaining authenticated access. They can be directly adapted for the **lovable** platform to provide a richer UI and better handling of auth and data rendering.

172
REFRACTOR_GUIDE.md Normal file
View File

@@ -0,0 +1,172 @@
# Refactor Guide Deep Dive into the KhataUI Codebase
> This document walks through the entire repository, explains the current architecture, and provides a stepbystep refactor plan that will improve maintainability, type safety, and UI/UX while preserving the existing functional behavior.
---
## 1. Repository Layout (highlevel)
```
khata-ui/
├─ react-openapi/ # Core UI generated from OpenAPI configs
│ ├─ components/ # UI pieces: EnhancedTable, FilterBar, etc.
│ ├─ types/ # TypeScript interfaces (config, overrides)
│ └─ utils/ # Helper utilities (options, template resolution)
├─ src/ # Application entry point and pages
│ ├─ auth/ # Authentication context, hooks, and protected routes
│ ├─ pages/ # Dynamic resources (list, form)
│ └─ main.tsx # React root, providers, theming
├─ public/ # Static assets (favicon, index.html)
├─ index.html
├─ package.json
└─ tsconfig.json
```
### Key Concepts
| Area | Responsibility |
|------|-----------------|
| **Auth** | Central JWT handling, `AuthProvider`, `useAuth`, route guarding. |
| **OpenAPIdriven UI** | Describes each resource via `ResourceConfig`/`ResourceField`. Generates tables, filters, and forms automatically. |
| **Data Layer** | TanStack Query (`useQuery`) fetches data; Axios instance carries auth token via interceptor. |
| **Theming** | MUI theme with light/dark mode toggle (future). |
| **Extensibility** | `components` prop on `EnhancedTable` / `FilterBar` lets callers inject custom cell renderers, filter widgets, or action buttons. |
---
## 2. Detailed Module Walkthrough
### 2.1 `react-openapi/types/config.ts`
```ts
export interface ResourceField {
displayFormat: string; // <- single source of truth for rendering
type: FieldType;
label: string;
required?: boolean;
options?: string[];
readOnly?: boolean;
schema?: Record<string, ResourceField>;
formatter?: (value: any) => string;
relation?: string;
filterType?: "autocomplete" | "multiselect" | "number-range" | "date-range";
enumOption?: EnumOption;
enumLabels?: Record<string, string>;
}
```
- `displayFormat` replaces the legacy `displayField`. It can be a **template string** (`"{{first}} {{last}}"`) or an **array of keys** for concatenation.
- All UI components now rely exclusively on this field.
### 2.2 `react-openapi/utils/options.ts`
- `resolveTemplate(format: string, item: any)` interpolates `{{key}}` placeholders.
- `getFieldOptions`, `toGridValueOptions` convert enum definitions into MUIcompatible arrays.
- **Refactor idea**: Move the `displayFormat` resolution logic from `EnhancedTable`/`FilterBar` into a dedicated helper (`formatDisplay(item, field)`), reducing duplication.
### 2.3 `react-openapi/components/EnhancedTable.tsx`
- **Core responsibilities**
1. Build column definitions from `config.fields`.
2. Render each cell via `FieldRenderer`.
3. Provide serverside or clientside pagination.
4. Add a static "Actions" column.
- **Key functions**
- `getFormattedDisplayValue(item, displayFormat?, enumValue?)` now uses `resolveTemplate` and falls back to generic fields.
- `FieldRenderer` decides how to render a cell based on `field.type`, `field.relation`, custom renderers, and `displayFormat`.
- **Duplication**: Both `EnhancedTable` and `FilterBar` perform very similar `displayFormat` extraction. Extracting this into a shared utility will shrink the component size and make testing easier.
### 2.4 `react-openapi/components/FilterBar.tsx`
- Generates filter controls for each **filterable** field.
- Uses `extractOptions` to populate autocomplete lists, falling back to `displayFormat` for label generation.
- **Opportunity**: Replace the inline `pull` helper with the shared formatter from `utils/options`.
### 2.5 Authentication (`src/auth`)
- `AuthContext.tsx` provides `user`, `accessToken`, `isAuthenticated` plus actions.
- `useAuth.ts` thin wrapper exposing the context values.
- `ProtectedRoute.tsx` guards routes, redirects to `/login` when unauthenticated.
- `api.ts` thin Axios wrapper (`login`, `logout`, `refresh`).
- **Refactor suggestions**
- Consolidate token storage (localStorage ↔ sessionStorage) behind a small `tokenStore` service.
- Add automatic token refresh using an interceptor that retries the original request.
- Provide a hook (`useAuthorizedQuery`) that injects the auth token into TanStack Query automatically.
### 2.6 Application Core (`src/pages`, `src/main.tsx`)
- `ResourceList.tsx` reads `resource` param, loads the related `ResourceConfig` from a central map, fetches data, and renders `EnhancedTable` + `FilterBar`.
- `ResourceForm.tsx` builds a dynamic form based on `ResourceField` definitions; uses `displayFormat` for default values on relation fields.
- `main.tsx` wraps the app with `AuthProvider`, `QueryClientProvider`, and MUI `ThemeProvider`.
- **Future work**: Extract the “resource loader” into a hook (`useResourceConfig(resourceName)`) that also validates the config at runtime.
---
## 3. Refactor Roadmap StepbyStep
### Phase1 Consolidate Formatting Logic
1. **Create utility** `src/react-openapi/utils/formatDisplay.ts`
```ts
export const formatDisplay = (item: any, field: ResourceField, enumValue?: string) => {
if (enumValue) return resolveTemplate(enumValue, item);
const fmt = field.displayFormat;
if (!fmt) return item.name ?? item.title ?? item.label ?? item.id ?? JSON.stringify(item);
if (Array.isArray(fmt)) {
return fmt.map(k => item[k]).filter(Boolean).join(' ');
}
return resolveTemplate(fmt, item) || item.id || JSON.stringify(item);
};
```
2. Replace *all* inline calls to `getFormattedDisplayValue` in `EnhancedTable` and `FilterBar` with `formatDisplay`.
3. Remove `getFormattedDisplayValue` from `EnhancedTable.tsx` (or keep it as a thin wrapper for backward compatibility).
4. Update imports accordingly.
5. Run TypeScript check no errors.
### Phase2 Decouple UI from Config Loading
- Introduce **`configLoader.ts`** under `src/react-openapi/utils` that reads a JSON file (or fetches a remote spec) and produces a `Record<string, ResourceConfig>`.
- Replace hardcoded imports in `src/pages/ResourceList.tsx` with a call to `useResourceConfig(resourceName)`.
- Add runtime validation (e.g., using `zod`) to ensure required fields (`displayFormat`, `type`, `label`) are present; surface errors via a toast.
### Phase3 Centralize Error & Loading UI
- Create `src/components/LoadingSpinner.tsx` and `src/components/ErrorToast.tsx`.
- Wrap all datafetching hooks (`useResource`, `useAuth` actions) with a HOC that automatically displays these components.
- Migrate the scattered `if (loading) …` checks into the new components.
### Phase4 Theming & Dark Mode
1. Add a `ThemeContext` that stores `mode: 'light' | 'dark'` and persists the preference.
2. Expose a toggle button (e.g., in the topright corner of `App.tsx`).
3. Update component styles to use themeaware colors (via `theme.palette`), ensuring the `Chip` variants already respect the palette.
### Phase5 Testing & CI
- **Unit tests** using `vitest` for:
- `formatDisplay` utility (various template & array cases).
- `AuthProvider` behavior (login, logout, token refresh).
- **Component tests** (`@testing-library/react`) for `EnhancedTable` and `FilterBar` verifying that `displayFormat` rendering matches expectations.
- Add a GitHub Actions workflow that runs `npm run lint && npx tsc --noEmit && vitest run` on each PR.
### Phase6 Documentation (the files you will publish)
- **DESIGN.md** highlevel architecture (already present).
- **IMPLEMENTATION.md** detailed filebyfile breakdown (already present).
- **CONCEPT.md** why the metadatadriven approach works (already present).
- **REFRACTOR_GUIDE.md** the detailed guide you are reading now (this file).
- Keep these files in the repo root; they can be exported to the **lovable** platform directly.
---
## 4. Migration Checklist (what to verify after refactor)
- [ ] All UI components compile with TypeScript (`npx tsc --noEmit`).
- [ ] No runtime references to `displayField` remain (search `\.displayField`).
- [ ] `formatDisplay` correctly resolves:
- Template strings with multiple placeholders.
- Array of keys.
- Fallback to generic fields.
- [ ] Auth flow works (login ➜ token stored ➜ API requests succeed, protected routes guarded).
- [ ] Pagination works both client and serverside.
- [ ] Mobile layout (card view) still renders correctly.
- [ ] Darkmode toggle persists across reloads.
- [ ] Lint passes (`npm run lint` if configured) and tests pass.
---
## 5. Potential Future Enhancements
| Feature | Benefit | Rough Implementation |
|---------|---------|----------------------|
| **Bulk actions** (delete, export) | Improves admin productivity | Add a toolbar with selection model in `EnhancedTable`. |
| **Inline editing** | Faster data tweaks | Replace `onEdit` dialog with celllevel edit mode using MUI `TextField`. |
| **GraphQL fallback** | Flexibility for backends | Abstract data fetching behind an adapter interface (`useDataProvider`). |
| **Internationalisation** | Multilanguage UI | Wrap all static strings with `i18n.t()` and provide locale files. |
| **Performance profiling** | Identify render bottlenecks | Use React Profiler and memoize expensive formatters (`useMemo`). |
---
### Closing Note
The current codebase already demonstrates a powerful pattern: **declare once, render everywhere**. By consolidating the display logic, adding a small utility layer, and strengthening the authentication and theming foundations, the project will become easier to extend, test, and handoff to the **lovable** UI platform while retaining its lowcode advantage.

View File

@@ -278,19 +278,10 @@ function MobileCardRow({ row, config, onDelete, onNavigate, navigate, components
);
}
function getFormattedDisplayValue(item: any, displayField?: string | string[], enumValue?: string) {
function getFormattedDisplayValue(item: any, displayFormat: string) {
if (!item) return "";
if (enumValue) return resolveTemplate(enumValue, item);
if (!displayField) return item.name || item.title || item.label || item.id || JSON.stringify(item);
if (Array.isArray(displayField)) {
return displayField
.map(key => item[key])
.filter(val => val !== undefined && val !== null)
.join(' ');
}
return item[displayField] || item.id || JSON.stringify(item);
return resolveTemplate(displayFormat, item);
}
function FieldRenderer({ params, field, fieldKey, config, onNavigate, navigate, isMobile, components }: any) {
@@ -307,7 +298,7 @@ function FieldRenderer({ params, field, fieldKey, config, onNavigate, navigate,
// 1. Single Relation
if (field.relation && value && !Array.isArray(value)) {
const relationId = typeof value === 'object' ? (value.id || value._id || value.pk) : value;
const displayValue = getFormattedDisplayValue(value, field.displayField, field.enumOption?.value);
const displayValue = getFormattedDisplayValue(value, field.displayFormat);
return (
<Chip
@@ -327,7 +318,7 @@ function FieldRenderer({ params, field, fieldKey, config, onNavigate, navigate,
// 2. Multi-Select (Array of relations or simple strings)
if (field.type === 'array' && Array.isArray(value)) {
const enumValue = field.enumOption?.value;
const tooltipTitle = value.map((item) => getFormattedDisplayValue(item, field.displayField, enumValue)).join(', ');
const tooltipTitle = value.map((item) => getFormattedDisplayValue(item, field.displayFormat)).join(', ');
return (
<Tooltip title={tooltipTitle} arrow placement="top">
@@ -335,7 +326,7 @@ function FieldRenderer({ params, field, fieldKey, config, onNavigate, navigate,
{value.map((item, idx) => (
<Chip
key={idx}
label={getFormattedDisplayValue(item, field.displayField, enumValue)}
label={getFormattedDisplayValue(item, field.displayFormat)}
size="small"
variant="filled"
sx={{ maxWidth: 120 }}
@@ -355,7 +346,7 @@ function FieldRenderer({ params, field, fieldKey, config, onNavigate, navigate,
// 3. Simple Objects
if (field.type === 'object' && value) {
return getFormattedDisplayValue(value, field.displayField, field.enumOption?.value) || (isMobile ? 'Object' : JSON.stringify(value));
return getFormattedDisplayValue(value, field.displayFormat) || (isMobile ? 'Object' : JSON.stringify(value));
}
if (field.type === 'number' && typeof value === 'number') {
@@ -388,7 +379,9 @@ function FieldRenderer({ params, field, fieldKey, config, onNavigate, navigate,
);
}
if (field.type === 'datetime' || field.type === 'date') return value ? new Date(value).toLocaleString() : '';
if (field.type === 'datetime') return value ? new Date(value).toLocaleString() : '';
if (field.type === 'date') return value ? new Date(value).toLocaleDateString() : '';
if (field.type === 'enum') {
const opt = getFieldOptions(field).find(o => o.key === value);

View File

@@ -124,7 +124,7 @@ function extractOptions(
if (field.enumOption?.value) return resolveTemplate(field.enumOption.value, item);
// Use displayFormat if defined, otherwise fall back to displayField logic (for backward compatibility)
// Use displayFormat if defined
if (field.displayFormat) {
return resolveTemplate(field.displayFormat, item);
}

View File

@@ -20,13 +20,8 @@ import { GridPaginationModel } from '@mui/x-data-grid';
function getDisplayString(item: any, field: ResourceField): string {
if (item == null || typeof item !== 'object') return String(item ?? '');
if (field.enumOption?.value) return resolveTemplate(field.enumOption.value, item);
const df = field.displayField;
if (!df) return item.name ?? item.title ?? item.label ?? item.id ?? JSON.stringify(item);
if (Array.isArray(df)) {
const parts = df.map((k: string) => item[k]).filter((v: any) => v != null);
return parts.length > 0 ? parts.join(' ') : '';
}
return String(item[df] ?? '');
if (field.displayFormat) return resolveTemplate(field.displayFormat, item);
throw new Error('cannot get display string')
}
function applyClientFilters(
@@ -119,7 +114,7 @@ export default function ResourceView({ config, onNavigateToResource, fieldCompon
const { useList, useRead, useCreate, useUpdate, useDelete, components } = useResource(config, { fieldComponents });
const queryParams = React.useMemo(() => {
if (!isServer) return { limit: 10 };
if (!isServer) return { limit: 10000 };
return {
skip: paginationModel.page * paginationModel.pageSize,
limit: paginationModel.pageSize,

View File

@@ -14,6 +14,9 @@ export interface FieldOverride {
// New optional properties to support custom config extensions
path?: string;
refers?: string;
// Added support for overriding the base field type and label
type?: FieldType;
label?: string;
}
export interface ResourceOverride {

View File

@@ -26,7 +26,7 @@ export function getFieldOptions(field: ResourceField, relationData?: any[]): Sel
}
return data.map(item => ({
key: String(item[enumOption.key] ?? ''),
key: String(item[enumOption.key]),
value: resolveTemplate(enumOption.value, item),
}));
}

View File

@@ -57,6 +57,14 @@ export const configuration: Record<string, ResourceOverride> = {
format: {
path: 'source.format',
},
start_date: {
type: 'date',
label: 'Start Date',
},
end_date: {
type: 'date',
label: 'End Date',
},
// account: {
// refers: 'accounts',
// },