Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ceeef16de9 | ||
|
|
74250261f2 | ||
|
|
1d7370e557 | ||
|
|
77110e1e9a | ||
|
|
401eb26458 | ||
|
|
4e0c6e12f4 | ||
|
|
a6371b64fa | ||
|
|
1797af7ba9 | ||
|
|
25c9bc21b3 |
@@ -1,16 +1,219 @@
|
||||
# React + Vite
|
||||
# ListVirtual
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
A searchable dropdown component with server-side filtering, infinite scrolling, and support for both single and multiple selection.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
## Features
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
* Server-side search
|
||||
* Infinite scrolling
|
||||
* Single select mode
|
||||
* Multiple select mode
|
||||
* Custom request headers via `ApiProvider`
|
||||
* Default value support
|
||||
* Material UI integration
|
||||
|
||||
## React Compiler
|
||||
---
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
## Installation
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
```bash
|
||||
npm install your-library-name
|
||||
```
|
||||
|
||||
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
|
||||
## Import
|
||||
|
||||
```jsx
|
||||
import { ApiProvider, ListVirtual } from "your-library-name";
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Setup
|
||||
|
||||
Wrap your application or component with `ApiProvider` to provide API headers.
|
||||
|
||||
```jsx
|
||||
<ApiProvider
|
||||
headers={{
|
||||
Authorization: `Bearer ${token}`,
|
||||
}}
|
||||
>
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
/>
|
||||
</ApiProvider>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Single Selection
|
||||
|
||||
```jsx
|
||||
const [company, setCompany] = useState(null);
|
||||
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
getData={(row) => {
|
||||
setCompany(row);
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Selected Value
|
||||
|
||||
```js
|
||||
{
|
||||
id: 123,
|
||||
name: "My Company"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Multiple Selection
|
||||
|
||||
```jsx
|
||||
const [companies, setCompanies] = useState([]);
|
||||
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
multiple
|
||||
getData={(rows) => {
|
||||
setCompanies(rows);
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Selected Value
|
||||
|
||||
```js
|
||||
[
|
||||
{
|
||||
id: 1,
|
||||
name: "Company A"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Company B"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Using Default Value
|
||||
|
||||
### Single Selection
|
||||
|
||||
```jsx
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
defaultValue={{
|
||||
id: 123,
|
||||
name: "My Company"
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Multiple Selection
|
||||
|
||||
```jsx
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
multiple
|
||||
defaultValue={[
|
||||
{
|
||||
id: 1,
|
||||
name: "Company A"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Company B"
|
||||
}
|
||||
]}
|
||||
/>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Props
|
||||
|
||||
| Prop | Type | Default | Description |
|
||||
| ------------ | -------------- | --------- | ----------------------------------------- |
|
||||
| id | string | - | Unique component identifier |
|
||||
| label | string | - | TextField label |
|
||||
| name | string | - | Property name used for display |
|
||||
| url | string | - | API endpoint used to fetch data |
|
||||
| getData | function | undefined | Callback triggered when selection changes |
|
||||
| defaultValue | object | array | undefined | Initial selected value |
|
||||
| multiple | boolean | false | Enable multiple selection mode |
|
||||
| disabled | boolean | false | Disable the component |
|
||||
| required | boolean | false | Mark field as required |
|
||||
| error | boolean | false | Error state |
|
||||
| helperText | string | undefined | Helper text displayed below the field |
|
||||
| size | string | "medium" | TextField size (`small` or `medium`) |
|
||||
| lengthData | number | 100 | Number of records fetched per request |
|
||||
| filter | array | [] | Additional API filters |
|
||||
| isApiGo | boolean | false | Use Go API request mode |
|
||||
|
||||
---
|
||||
|
||||
## Custom Filters
|
||||
|
||||
```jsx
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
filter={[
|
||||
{
|
||||
name: "status",
|
||||
value: 1,
|
||||
logic_operator: "="
|
||||
}
|
||||
]}
|
||||
/>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API Response Format
|
||||
|
||||
The component expects the API response to have the following structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Company A"
|
||||
}
|
||||
],
|
||||
"totalRecord": 100
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
* The property specified in the `name` prop is used as the displayed label.
|
||||
* Infinite scrolling automatically loads additional records when the user reaches the bottom of the list.
|
||||
* In multiple mode, the `getData` callback returns an array of selected objects.
|
||||
* In single mode, the `getData` callback returns a single selected object.
|
||||
|
||||
Vendored
+7683
-7363
File diff suppressed because it is too large
Load Diff
Generated
+32
-39
@@ -25,8 +25,8 @@
|
||||
"@mui/lab": "7.0.0-beta.14",
|
||||
"@mui/material": "^7.3.5",
|
||||
"@mui/system": "7.2.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
"react": "19.1.0",
|
||||
"react-dom": "19.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@ant-design/colors": {
|
||||
@@ -131,6 +131,13 @@
|
||||
"url": "https://opencollective.com/babel"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/core/node_modules/convert-source-map": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
||||
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@babel/generator": {
|
||||
"version": "7.29.1",
|
||||
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz",
|
||||
@@ -378,13 +385,6 @@
|
||||
"stylis": "4.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emotion/babel-plugin/node_modules/convert-source-map": {
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",
|
||||
"integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@emotion/cache": {
|
||||
"version": "11.14.0",
|
||||
"resolved": "https://registry.npmjs.org/@emotion/cache/-/cache-11.14.0.tgz",
|
||||
@@ -2140,9 +2140,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.10.30",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.30.tgz",
|
||||
"integrity": "sha512-xjOFN16Ha1+Rz4nFYKqHU/LSB+gx/Vi3yQLX7r7sAW+Wa+8hhF2h4pvqTrTMc8+WcDBEunnUurr46Jvv0jk3Vg==",
|
||||
"version": "2.10.31",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.31.tgz",
|
||||
"integrity": "sha512-MujYO3eP72uvmSE0i4wltsodRfIpZATP3jvzRNRGGxgzId7aVocVJJV3nf01qnzzKFGxQVC9bpWxl5cjxTr/7Q==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
@@ -2260,11 +2260,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/convert-source-map": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
||||
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",
|
||||
"integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/cosmiconfig": {
|
||||
"version": "7.1.0",
|
||||
@@ -2342,9 +2342,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/electron-to-chromium": {
|
||||
"version": "1.5.357",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.357.tgz",
|
||||
"integrity": "sha512-NHlTIQDK8fmVwHwuIzmXYEJ1Ewq3D9wDNc0cWXxDGysP6Pb21giwGNkxiTifyKy/4SoPuN5l6GLP1W9Sv7zB2g==",
|
||||
"version": "1.5.359",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.359.tgz",
|
||||
"integrity": "sha512-8lPELWuYZIWk7NDvCNthtmMw/7Q5Wu25NpM4djFMHBmk8DubPAtL4YTOp7ou0e7HyJtwkVlWv8XMLURnrtgJQw==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
@@ -2960,30 +2960,26 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"version": "19.1.0",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz",
|
||||
"integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"version": "19.1.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz",
|
||||
"integrity": "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
"scheduler": "^0.26.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18.3.1"
|
||||
"react": "^19.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
@@ -3098,14 +3094,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.23.2",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
|
||||
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
|
||||
"version": "0.26.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz",
|
||||
"integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
}
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "6.3.1",
|
||||
|
||||
+2
-2
@@ -18,8 +18,8 @@
|
||||
"@emotion/cache": "11.14.0",
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react": "19.1.0",
|
||||
"react-dom": "19.1.0",
|
||||
"@mui/base": "5.0.0-beta.70",
|
||||
"@mui/icons-material": "^7.3.5",
|
||||
"@mui/lab": "7.0.0-beta.14",
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import ListVirtual from "./components/ListVirtual";
|
||||
import { ApiProvider } from "./components/ApiContext";
|
||||
import { API_TOKEN } from "./config/constants";
|
||||
import { useState } from "react";
|
||||
|
||||
const Testing = () => {
|
||||
const token = API_TOKEN;
|
||||
const [selectedVehicle, setSelectedVehicle] = useState([]);
|
||||
|
||||
return (
|
||||
<div style={{ padding: 8, marginTop: 12 }}>
|
||||
<ApiProvider
|
||||
headers={{
|
||||
Authorization: `Bearer ${token}`,
|
||||
}}
|
||||
>
|
||||
<ListVirtual
|
||||
id="company-select"
|
||||
label="Company"
|
||||
name="name"
|
||||
url="/company"
|
||||
defaultValue={[442,722]}
|
||||
size="small"
|
||||
multiple
|
||||
/>
|
||||
<ListVirtual
|
||||
label="License Plate"
|
||||
name="license_plate"
|
||||
url="/vehicle"
|
||||
defaultValue={selectedVehicle}
|
||||
getData={(data) => {
|
||||
const ids = data.map(item => item.id);
|
||||
setSelectedVehicle(ids);
|
||||
}}
|
||||
size="small"
|
||||
filter={[
|
||||
{name:"company_id",value: "442,722","logic_operator":"IN","operator":"AND"}
|
||||
]}
|
||||
joins={[
|
||||
{
|
||||
table: "vehicle_type",
|
||||
columns: ["min_speed", "max_speed"],
|
||||
},
|
||||
]}
|
||||
multiple
|
||||
/>
|
||||
</ApiProvider>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Testing;
|
||||
@@ -14,7 +14,8 @@ const createClient = (baseURL, withBaseFormat = false) => {
|
||||
formatApiResponse({
|
||||
status: response.status,
|
||||
data: response.data,
|
||||
message: response.data?.message ?? response.statusText
|
||||
message: response.data?.message ?? response.statusText,
|
||||
totalRecord: response.totalRecord ?? 0
|
||||
}),
|
||||
(error) => Promise.resolve(formatApiResponse(error))
|
||||
);
|
||||
|
||||
+57
-39
@@ -1,3 +1,5 @@
|
||||
// src/api/request.js
|
||||
|
||||
import { formatApiResponse } from '../utils/response';
|
||||
import { oslogApi, apiGo } from './axiosClient';
|
||||
|
||||
@@ -10,31 +12,26 @@ const request = async ({
|
||||
endpoint = '',
|
||||
suffix = '',
|
||||
data = null,
|
||||
params = {},
|
||||
headers = {},
|
||||
customUrl = '',
|
||||
axiosConfig = {},
|
||||
axiosConfig = {}
|
||||
}) => {
|
||||
const url = customUrl || `${endpoint}${suffix}`;
|
||||
|
||||
try {
|
||||
const client = isApiGo ? apiGo : oslogApi;
|
||||
|
||||
const response = await client({
|
||||
method,
|
||||
url,
|
||||
data,
|
||||
params,
|
||||
headers,
|
||||
...axiosConfig,
|
||||
|
||||
// highest priority
|
||||
...axiosConfig
|
||||
});
|
||||
|
||||
return formatApiResponse(response);
|
||||
return response
|
||||
} catch (error) {
|
||||
const responseError = formatApiResponse(error);
|
||||
|
||||
//logError(`at endpoint: ${url} error: `, responseError);
|
||||
|
||||
return responseError;
|
||||
return formatApiResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -42,65 +39,86 @@ const request = async ({
|
||||
* CREATE NEW
|
||||
* POST /endpoint/new
|
||||
*/
|
||||
export const newRequest = (endpoint, data = null, config = {}) =>
|
||||
export const newRequest = (
|
||||
endpoint,
|
||||
data = null,
|
||||
axiosConfig = {}
|
||||
) =>
|
||||
request({
|
||||
method: 'post',
|
||||
endpoint,
|
||||
suffix: '/new',
|
||||
data,
|
||||
...config,
|
||||
axiosConfig
|
||||
});
|
||||
|
||||
/**
|
||||
* ADD
|
||||
* POST /endpoint/add
|
||||
*/
|
||||
export const addRequest = (endpoint, data = null, config = {}) =>
|
||||
export const addRequest = (
|
||||
endpoint,
|
||||
data = null,
|
||||
axiosConfig = {}
|
||||
) =>
|
||||
request({
|
||||
method: 'post',
|
||||
endpoint,
|
||||
suffix: '/add',
|
||||
data,
|
||||
...config,
|
||||
axiosConfig
|
||||
});
|
||||
|
||||
/**
|
||||
* GET BY ID
|
||||
* GET /endpoint/:id
|
||||
*/
|
||||
export const getByIdRequest = (id, endpoint, params = {}, config = {}) =>
|
||||
export const getByIdRequest = (
|
||||
id,
|
||||
endpoint,
|
||||
axiosConfig = {}
|
||||
) =>
|
||||
request({
|
||||
method: 'get',
|
||||
endpoint,
|
||||
suffix: `/${id}`,
|
||||
params,
|
||||
...config,
|
||||
axiosConfig
|
||||
});
|
||||
|
||||
/**
|
||||
* EDIT
|
||||
* PUT /endpoint/edit/:id
|
||||
*/
|
||||
export const editRequest = (id, endpoint, data = null, config = {}) =>
|
||||
export const editRequest = (
|
||||
id,
|
||||
endpoint,
|
||||
data = null,
|
||||
axiosConfig = {}
|
||||
) =>
|
||||
request({
|
||||
method: 'put',
|
||||
endpoint,
|
||||
suffix: `/edit/${id}`,
|
||||
data,
|
||||
...config,
|
||||
axiosConfig
|
||||
});
|
||||
|
||||
/**
|
||||
* DELETE
|
||||
* DELETE /endpoint/delete/:id
|
||||
*/
|
||||
export const deleteRequest = (id, endpoint, data = null, config = {}) =>
|
||||
export const deleteRequest = (
|
||||
id,
|
||||
endpoint,
|
||||
data = null,
|
||||
axiosConfig = {}
|
||||
) =>
|
||||
request({
|
||||
method: 'delete',
|
||||
endpoint,
|
||||
suffix: `/delete/${id}`,
|
||||
data,
|
||||
...config,
|
||||
axiosConfig
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -110,8 +128,7 @@ export const deleteRequest = (id, endpoint, data = null, config = {}) =>
|
||||
export const searchRequest = (
|
||||
endpoint,
|
||||
data = null,
|
||||
params = {},
|
||||
config = {},
|
||||
axiosConfig = {}
|
||||
) => {
|
||||
const timezone = -new Date().getTimezoneOffset() / 60;
|
||||
|
||||
@@ -120,37 +137,38 @@ export const searchRequest = (
|
||||
endpoint,
|
||||
suffix: '/search',
|
||||
data,
|
||||
params: {
|
||||
tz: timezone,
|
||||
...params,
|
||||
},
|
||||
...config,
|
||||
|
||||
axiosConfig: {
|
||||
...axiosConfig,
|
||||
|
||||
params: {
|
||||
tz: timezone,
|
||||
...(axiosConfig.params || {})
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* CUSTOM REQUEST
|
||||
* untuk endpoint bebas / beda sendiri
|
||||
*/
|
||||
export const customRequest = ({
|
||||
method = 'get',
|
||||
url = '',
|
||||
data = null,
|
||||
params = {},
|
||||
headers = {},
|
||||
axiosConfig = {},
|
||||
isApiGo = false,
|
||||
axiosConfig = {}
|
||||
}) =>
|
||||
request({
|
||||
method,
|
||||
customUrl: url,
|
||||
data,
|
||||
params,
|
||||
headers,
|
||||
axiosConfig,
|
||||
isApiGo,
|
||||
axiosConfig
|
||||
});
|
||||
|
||||
/**
|
||||
* Optional Export Object
|
||||
* EXPORT OBJECT
|
||||
*/
|
||||
export const apiRequest = {
|
||||
new: newRequest,
|
||||
@@ -159,5 +177,5 @@ export const apiRequest = {
|
||||
edit: editRequest,
|
||||
delete: deleteRequest,
|
||||
search: searchRequest,
|
||||
custom: customRequest,
|
||||
custom: customRequest
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import React, { createContext, useContext } from "react";
|
||||
|
||||
// Sentinel value to reliably detect if the hook is called outside the provider
|
||||
const sentinel = {};
|
||||
|
||||
/**
|
||||
* ApiContext created using the React Context API.
|
||||
* Defaults to a sentinel value to detect out-of-provider usage.
|
||||
*/
|
||||
export const ApiContext = createContext(sentinel);
|
||||
|
||||
/**
|
||||
* ApiProvider component that accepts a `headers` prop and provides it through context.
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {Object} props.headers - The headers to provide to API requests
|
||||
* @param {React.ReactNode} props.children - Child components
|
||||
*/
|
||||
export function ApiProvider({ headers, children }) {
|
||||
return React.createElement(
|
||||
ApiContext.Provider,
|
||||
{ value: headers },
|
||||
children
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom hook `useApiHeaders()` that returns the current headers from context.
|
||||
* Throws a clear error if called outside of `ApiProvider`.
|
||||
*
|
||||
* @returns {Object} The current headers from context
|
||||
*/
|
||||
export function useApiHeaders() {
|
||||
const context = useContext(ApiContext);
|
||||
if (context === sentinel) {
|
||||
throw new Error("useApiHeaders must be used within an ApiProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
+201
-52
@@ -11,11 +11,13 @@ import {
|
||||
ListItemText,
|
||||
Typography,
|
||||
InputAdornment,
|
||||
IconButton
|
||||
IconButton,
|
||||
Checkbox
|
||||
} from "@mui/material";
|
||||
import ClearIcon from "@mui/icons-material/Clear";
|
||||
import FilterTableBuilder from "../utils/filterTableBuilder";
|
||||
import { apiRequest } from "../api/request";
|
||||
import { useApiHeaders } from "./ApiContext";
|
||||
|
||||
export default function ListVirtual({
|
||||
id,
|
||||
@@ -33,8 +35,11 @@ export default function ListVirtual({
|
||||
helperText,
|
||||
filter,
|
||||
isApiGo = false,
|
||||
headersRequest,
|
||||
multiple,
|
||||
customSxTextField = {},
|
||||
joins = [],
|
||||
}) {
|
||||
const headersRequest = useApiHeaders();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const [rows, setRows] = useState([]);
|
||||
@@ -65,18 +70,25 @@ export default function ListVirtual({
|
||||
if (keyword) payload.like(name, keyword);
|
||||
|
||||
if (filter && filter.length > 0) {
|
||||
filter.forEach(f => payload.where(f.logic_operator || "=", f.name, f.value, f.operator || "AND", f.value1 || null, f.table_name || null));
|
||||
filter.forEach(f => payload.where(f.logic_operator || "=", f.name, f.value, f.operator || "AND", f.value1 || null, f.table_name || null));
|
||||
}
|
||||
|
||||
if (Array.isArray(filter) && filter.some(f => f.name === "company_id")) {
|
||||
payload.addJoin("company", ["name"]);
|
||||
}
|
||||
|
||||
joins.forEach(join => {
|
||||
payload.addJoin(join.table, join.columns);
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await apiRequest.search(
|
||||
url,
|
||||
payload.build(),
|
||||
{},
|
||||
{
|
||||
isApiGo,
|
||||
headers: headersRequest
|
||||
}
|
||||
},
|
||||
isApiGo,
|
||||
);
|
||||
const incomingData = res.data || [];
|
||||
|
||||
@@ -97,6 +109,7 @@ export default function ListVirtual({
|
||||
|
||||
if (isAtBottom && !loading && rows.length < totalRecord) {
|
||||
const nextOffset = offset + lengthData;
|
||||
|
||||
fetchData(search, nextOffset, true);
|
||||
}
|
||||
};
|
||||
@@ -117,60 +130,164 @@ export default function ListVirtual({
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const fetchById = async (id) => {
|
||||
const fetchDefaultValue = async (value) => {
|
||||
setLoading(true);
|
||||
|
||||
const payload = new FilterTableBuilder()
|
||||
.setPaging(0, 1)
|
||||
.equal("id", id);
|
||||
const payload = new FilterTableBuilder().setPaging(0, lengthData);
|
||||
|
||||
try {
|
||||
const res = await apiRequest.search(
|
||||
url,
|
||||
payload.build(),
|
||||
{},
|
||||
{
|
||||
isApiGo,
|
||||
headers: headersRequest
|
||||
}
|
||||
);
|
||||
|
||||
const data = res.data?.[0];
|
||||
|
||||
if (data) {
|
||||
setSelected(data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (multiple) {
|
||||
payload.in("id", value); // value = [1,2,3]
|
||||
} else {
|
||||
payload.equal("id", value); // value = 1
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
try {
|
||||
const res = await apiRequest.search(
|
||||
url,
|
||||
payload.build(),
|
||||
{
|
||||
headers: headersRequest,
|
||||
},
|
||||
isApiGo,
|
||||
);
|
||||
|
||||
const data = res.data || [];
|
||||
|
||||
setSelected(multiple ? data : data[0] || null);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!defaultValue) return;
|
||||
if (defaultValue == null) return;
|
||||
|
||||
if (typeof defaultValue === "object") {
|
||||
setSelected(defaultValue);
|
||||
if (multiple) {
|
||||
// kosong, jangan request
|
||||
if (Array.isArray(defaultValue) && defaultValue.length === 0) {
|
||||
setSelected([]);
|
||||
return;
|
||||
}
|
||||
|
||||
// object
|
||||
if (
|
||||
Array.isArray(defaultValue) &&
|
||||
typeof defaultValue[0] === "object"
|
||||
) {
|
||||
setSelected(defaultValue);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
fetchById(defaultValue);
|
||||
if (typeof defaultValue === "object" && !Array.isArray(defaultValue)) {
|
||||
setSelected(defaultValue);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}, [defaultValue]);
|
||||
|
||||
fetchDefaultValue(defaultValue);
|
||||
}, [defaultValue, multiple]);
|
||||
|
||||
const handleSelect = (row) => {
|
||||
setSelected(row);
|
||||
setOpen(false);
|
||||
setSearch("");
|
||||
getData && getData(row);
|
||||
if (!multiple) {
|
||||
setSelected(row);
|
||||
setOpen(false);
|
||||
setSearch("");
|
||||
getData?.(row);
|
||||
return;
|
||||
}
|
||||
|
||||
setSelected((prev) => {
|
||||
const current = Array.isArray(prev) ? prev : [];
|
||||
|
||||
const exists = current.some((x) => x.id === row.id);
|
||||
|
||||
const result = exists
|
||||
? current.filter((x) => x.id !== row.id)
|
||||
: [...current, row];
|
||||
|
||||
getData?.(result);
|
||||
|
||||
return result;
|
||||
});
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
setSelected(null);
|
||||
setSelected(multiple ? [] : null);
|
||||
setSearch("");
|
||||
setRows([]);
|
||||
getData && getData(null);
|
||||
|
||||
getData?.(multiple ? [] : null);
|
||||
};
|
||||
|
||||
const displayValue = multiple
|
||||
? (selected?.length > 0
|
||||
? `${selected.length} ${label} selected`
|
||||
: "")
|
||||
: selected?.[name] || "";
|
||||
|
||||
const isSelected = (row) => {
|
||||
if (!multiple) {
|
||||
return selected?.id === row.id;
|
||||
}
|
||||
|
||||
return (selected || []).some((x) => x.id === row.id);
|
||||
};
|
||||
|
||||
const handleSelectAll = async () => {
|
||||
setLoading(true);
|
||||
|
||||
const pageSize = 1000;
|
||||
const requests = [];
|
||||
|
||||
for (let offset = 0; offset < totalRecord; offset += pageSize) {
|
||||
const payload = new FilterTableBuilder()
|
||||
.setPaging(offset, pageSize)
|
||||
.setOrder([name], true);
|
||||
|
||||
if (search) {
|
||||
payload.like(name, search);
|
||||
}
|
||||
|
||||
if (filter?.length) {
|
||||
filter.forEach(f =>
|
||||
payload.where(
|
||||
f.logic_operator || "=",
|
||||
f.name,
|
||||
f.value,
|
||||
f.operator || "AND",
|
||||
f.value1 || null,
|
||||
f.table_name || null
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
joins.forEach(join => {
|
||||
payload.addJoin(join.table, join.columns);
|
||||
});
|
||||
|
||||
requests.push(
|
||||
apiRequest.search(
|
||||
url,
|
||||
payload.build(),
|
||||
{
|
||||
headers: headersRequest,
|
||||
},
|
||||
isApiGo
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const responses = await Promise.all(requests);
|
||||
|
||||
const allRows = responses.flatMap(res => res.data || []);
|
||||
|
||||
setSelected(allRows);
|
||||
getData?.(allRows);
|
||||
|
||||
setLoading(false);
|
||||
};
|
||||
const displayValue = selected ? selected[name] : value || "";
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -186,6 +303,7 @@ export default function ListVirtual({
|
||||
error={!!error}
|
||||
onClick={() => !disabled && setOpen(true)}
|
||||
sx={{
|
||||
...customSxTextField,
|
||||
'& .MuiOutlinedInput-root.Mui-error .MuiOutlinedInput-notchedOutline': {
|
||||
borderColor: 'error.main',
|
||||
}
|
||||
@@ -217,7 +335,20 @@ export default function ListVirtual({
|
||||
<DialogTitle sx={{ fontSize: 14 }}>Search {label}</DialogTitle>
|
||||
<DialogContent
|
||||
onScroll={handleScroll}
|
||||
sx={{ height: 400, overflowY: "auto", py: 0 }}
|
||||
sx={{
|
||||
'& .MuiTypography-root': {
|
||||
fontSize: 14,
|
||||
},
|
||||
'& .MuiInputBase-input': {
|
||||
fontSize: 14,
|
||||
},
|
||||
'& .MuiInputLabel-root': {
|
||||
fontSize: 14,
|
||||
},
|
||||
'& .MuiButton-root': {
|
||||
fontSize: 14,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<TextField
|
||||
fullWidth
|
||||
@@ -233,17 +364,35 @@ export default function ListVirtual({
|
||||
/>
|
||||
|
||||
<List disablePadding>
|
||||
{rows.map((row, i) => (
|
||||
<ListItemButton key={`${row.id}-${i}`} onClick={() => handleSelect(row)}>
|
||||
<ListItemText primary={row[name]} slotProps={{ primary: { fontSize: 14 } }} />
|
||||
</ListItemButton>
|
||||
))}
|
||||
<>
|
||||
{multiple && (
|
||||
<ListItemButton
|
||||
onClick={handleSelectAll}
|
||||
sx={{ fontSize: 14 }}
|
||||
>
|
||||
Select All
|
||||
</ListItemButton>
|
||||
)}
|
||||
|
||||
{loading && (
|
||||
<Typography variant="caption" sx={{ display: 'block', textAlign: 'center', p: 1 }}>
|
||||
Loading more...
|
||||
</Typography>
|
||||
)}
|
||||
{rows.map((row, i) => (
|
||||
<ListItemButton
|
||||
key={`${row.id}-${i}`}
|
||||
onClick={() => handleSelect(row)}
|
||||
>
|
||||
{multiple && (
|
||||
<Checkbox checked={isSelected(row)} />
|
||||
)}
|
||||
|
||||
<ListItemText primary={row[name]} secondary={row.join?.company_name} />
|
||||
</ListItemButton>
|
||||
))}
|
||||
|
||||
{loading && (
|
||||
<Typography variant="caption" sx={{ display: 'block', textAlign: 'center', p: 1 }}>
|
||||
Loading more...
|
||||
</Typography>
|
||||
)}
|
||||
</>
|
||||
</List>
|
||||
|
||||
{!loading && rows.length === 0 && (
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as ListVirtual } from "./ListVirtual";
|
||||
export * from "./ApiContext";
|
||||
+3
-1
@@ -1 +1,3 @@
|
||||
export { default as ListVirtual } from './components/ListVirtual.jsx';
|
||||
export * from './api/request';
|
||||
export * from './components';
|
||||
//export * from './utils';
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// src/main.jsx
|
||||
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
|
||||
import { ThemeProvider, createTheme } from '@mui/material/styles';
|
||||
import { CssBaseline } from '@mui/material';
|
||||
|
||||
import App from './App'
|
||||
|
||||
const theme = createTheme({
|
||||
palette: {
|
||||
mode: 'light',
|
||||
|
||||
primary: {
|
||||
main: '#2563eb'
|
||||
},
|
||||
|
||||
background: {
|
||||
default: '#f8fafc'
|
||||
}
|
||||
},
|
||||
|
||||
shape: {
|
||||
borderRadius: 12
|
||||
},
|
||||
|
||||
typography: {
|
||||
fontFamily:
|
||||
'"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
|
||||
|
||||
h5: {
|
||||
fontWeight: 700
|
||||
},
|
||||
|
||||
button: {
|
||||
textTransform: 'none',
|
||||
fontWeight: 600
|
||||
}
|
||||
},
|
||||
|
||||
components: {
|
||||
MuiPaper: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
borderRadius: 16
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
MuiButton: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
borderRadius: 10,
|
||||
paddingInline: 16
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
MuiOutlinedInput: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
borderRadius: 12
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<ThemeProvider theme={theme}>
|
||||
<CssBaseline />
|
||||
<App />
|
||||
</ThemeProvider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
Reference in New Issue
Block a user