admin_lsac
v2.0.34
Published
Generic Admin Panel created for storing events' data
Readme
Generic Admin Panel
⚠️ Do not use React@19 while using this project!
For configuring your own admin panel, follow the next instructions.
How to install it?
The following command will download and install the specified package and its dependencies into your project's node_modules directory, making it available for use in your project.
npm install admin_lsac
What do you need to import?
You can import these in App.js / App.ts or wherever your routes to the pages are located.
import { pageToUrl } from 'admin_lsac'import { AdminPage } from 'admin_lsac'
If your project is TypeScript-based, you need to use the line from below as well. Import the component where you want to write your schemas. (See below for details about schemas)
import { PageSchema } from 'admin_lsac'
How to add routes to the admin panel's pages?
You will need to create an array of schemas (if more than one schema) for your own admin panel.
{your_array.map((page, index) => (
<Route
key={index}
path={`${your_url_to_admin_panel}/${pageToUrl(page)}`}
element={
<AdminPage
pages={your_array}
selectedPage={page} // 'page' param from above
basePath={your_url_to_admin_panel} // use '', NOT '/' if at root
apiURL={your_url_to_backend} // optional, for websockets
/>
}
/>
))}
{your_array[0] ? ( // recommended default route when accessing admin panel
<Route
path={`${your_url_to_admin_panel}/*`}
element={
<AdminPage
pages={your_array}
selectedPage={your_array[0]}
basePath={your_url_to_admin_panel} // use '', NOT '/' if at root
apiURL={your_url_to_backend} // optional, for websockets
/>
}
/>
) : null}More info
Declarative Mode (Standard SPA)
This mode represents the classic Single Page Application (SPA) approach, using standard JSX components to define the routing context. It is the most straightforward way to integrate the admin panel into an existing React application.
How to Implement
To set up the Declarative Mode, you must wrap your component tree (or just the admin section) inside a <BrowserRouter>. The AdminPage component requires four main props to function correctly:
pages: An array of your data schemas.selectedPage: The specific schema object to render.basePath: The URL prefix where the admin panel will reside (e.g.,/admin).apiURL: The base URL of your backend API.
The AdminPage will automatically handle internal navigation and path matching based on these props.
Implementation Example
Below is a minimal setup showing how to wrap the AdminPage and pass the required configuration:
import { BrowserRouter } from 'react-router';
import { AdminPage } from 'admin_lsac';
// Import your defined schemas
import { coursesPage } from './testSchemas/course';
export default function App() {
return (
<BrowserRouter>
<AdminPage
apiURL="http://localhost:3001/"
basePath="/admin"
pages="{[coursesPage]}"
selectedPage="{coursesPage}"
/>
</BrowserRouter>
);
}Data Mode (Data Router)
This mode utilizes an object-based routing configuration rather than a declarative JSX component tree. It is the recommended approach for modern React applications, as it decouples the route definitions from the UI, enabling advanced data fetching and performance optimizations.
How to Implement
To implement Data Mode, you will transition away from <BrowserRouter>. Instead, you define your routes as an array of objects using the createBrowserRouter function. This router instance is then passed to a <RouterProvider> component at the root of your application.
The AdminPage must be assigned to the element property of a route object. It is crucial to append a wildcard (*) to the path string (e.g., /admin/*) so the admin panel can successfully catch and manage its own internal sub-routes.
Implementation Example
Below is the standard setup for integrating the admin panel using the Data Router approach:
import { createBrowserRouter, RouterProvider } from 'react-router';
import { AdminPage } from 'admin_lsac';
// Import your defined schemas
import { coursesPage } from './testSchemas/course';
const router = createBrowserRouter([
{
path: '/admin/*', // The wildcard (*) is required for internal navigation
element: (
<AdminPage
apiURL="http://localhost:3001/"
basePath="/admin"
pages="{[coursesPage]}"
selectedPage="{coursesPage}"
/>
),
},
]);
export default function App() {
// Provide the router configuration to the application
return <RouterProvider router="{router}" />;
}Framework Mode (Vite Plugin / App Directory)
This mode is used when your project takes advantage of React Router v7's framework capabilities, utilizing the Vite plugin and file-based routing within an app/ directory.
How to Implement
To integrate the admin panel in Framework Mode, you need to configure file-based routing. You achieve this by defining a wildcard route in your route configuration file (routes.ts) that delegates traffic to a dedicated wrapper component.
The wrapper component is responsible for extracting the dynamic URL parameters (using the useParams hook) and determining which schema to render before returning the AdminPage component.
Implementation Example
Below are the two files required to set up the Framework Mode:
1. Define the Route Configuration (app/routes.ts)
Map the base path followed by a wildcard (*) directly to your wrapper component.
import { type RouteConfig, route } from '@react-router/dev/routes';
export default [route('admin/*', './wrapper.tsx')] satisfies RouteConfig;2. Create the Wrapper Component (app/wrapper.tsx)
This component handles the logic for matching the URL to your data schema.
import { useParams } from 'react-router';
import { AdminPage, pageToUrl } from 'admin_lsac';
// Import your defined schemas
import { coursesPage } from '../src/testSchemas/course';
export default function AdminWrapper() {
const params = useParams();
const splitPath = params['*'];
const pages = [coursesPage];
const basePath = '/admin';
// Dynamically resolve the selected page or fallback to the first one
const selectedPage = pages.find((page) => pageToUrl(page) === splitPath);
const currentPage = selectedPage || pages[0];
return (
<AdminPage
pages={pages}
selectedPage={currentPage}
basePath={basePath}
apiURL="http://localhost:3001/"
/>
);
}What is a schema?
export interface TableField {
name: string;
access: (obj: any) => any;
}
export interface SimpleField {
name: string;
label: string;
type: 'string' | 'number' | 'file' | 'date' | 'datetime-local' | 'time';
validationSchema?: any;
}
export interface Option {
value: string | number | boolean;
display: string;
}
export interface DropdownField {
name: string;
label: string;
type: 'dropdown';
validationSchema?: any;
options?: Option[];
getOptions?: () => Promise<Option[]>;
}
export interface ObjectField {
name: string;
label: string;
type: 'object';
fields: FormField[];
}
export interface ArrayField {
name: string;
label: string;
type: 'array';
element: Exclude<FormField, ArrayField>;
}
export type FormField = SimpleField | DropdownField | ObjectField | ArrayField;
export interface Action {
name: string;
fields?: FormField[];
onSubmit: (obj1?: any, obj2?: any, obj3?: any) => Promise<any>;
}
export interface RowAction {
name: string;
fields?: FormField[];
initialise?: (rowId: any) => Promise<any>;
onSubmit: (obj1: any, obj2?: any, obj3?: any) => Promise<any>;
}
export interface PageSchema {
name: string;
actions: Action[];
rowActions: RowAction[];
getRequest: () => Promise<any[]>;
tableFields: TableField[];
}A page schema is based on these interfaces, and it describes how one table of your admin panel would need to be structured to accomplish what the user needs to do regarding an entity. (i.e. users, teams, companies, quizzes)
The most important interface is PageSchema, as it stands at the top of the relations between all these interfaces.
What do the fields of PageSchema refer to?
- name = name of the table
- actions = these are operations that can affect all entries in the table (like updating all or some of the entries in the table) or operations that envolve creating new entries (one by one)
- rowActions = these are operations that can affect just one entry/row (like updating or deleting an entry)
- getRequest = this is a field containg the function that will retrieve all the entries from one table in the database
- tableFields = these are the 'definitions' of the displayed table's columns
The operations for the rowActions and actions will generally (not mandatory) have a form to complete before executing it. There are 4 types of inputs for the form part:
- simpleField = simple data like numbers, strings, files and dates
- dropdownField = enable the user to choose an option from a predefined list
- arrayField = arrays of data
- objectField = an object containing more fields/inputs, or even other objects (some cool recursion)
Websockets Support
For real-time changes, this NPM module uses socket.io-client library to implement WebSockets. So, on the server-side, you will have to use socket.io library, and provide an apiURL as shown above.
In order for it to work, emit an event 'updateData' from the server for every route associated with an action/rowAction. You can also send a message that the client will receive (the message will be shown in the web console).
Other Specifications
Due to some corrupt dependencies, you will need a Node version >= 20.5.0 to use this NPM package (it may work in some cases, but we still recommend updating Node to a newer version).
For every entity you describe through a page schema, getRequest and onSubmit functions use routes created for the entity. getRequest function makes a GET request, while onSumbit function generally makes a POST, PATCH or DELETE request.
Learn More
For more details, especially about page schemas, contact the owner (LSAC Bucuresti). :)
