8 Commits
13 changed files with 8336 additions and 7502 deletions
+212 -9
View File
@@ -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) * Server-side search
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) * 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.
+7669 -7354
View File
File diff suppressed because it is too large Load Diff
+32 -39
View File
@@ -25,8 +25,8 @@
"@mui/lab": "7.0.0-beta.14", "@mui/lab": "7.0.0-beta.14",
"@mui/material": "^7.3.5", "@mui/material": "^7.3.5",
"@mui/system": "7.2.0", "@mui/system": "7.2.0",
"react": "^18.3.1", "react": "19.1.0",
"react-dom": "^18.3.1" "react-dom": "19.1.0"
} }
}, },
"node_modules/@ant-design/colors": { "node_modules/@ant-design/colors": {
@@ -131,6 +131,13 @@
"url": "https://opencollective.com/babel" "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": { "node_modules/@babel/generator": {
"version": "7.29.1", "version": "7.29.1",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz",
@@ -378,13 +385,6 @@
"stylis": "4.2.0" "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": { "node_modules/@emotion/cache": {
"version": "11.14.0", "version": "11.14.0",
"resolved": "https://registry.npmjs.org/@emotion/cache/-/cache-11.14.0.tgz", "resolved": "https://registry.npmjs.org/@emotion/cache/-/cache-11.14.0.tgz",
@@ -2140,9 +2140,9 @@
} }
}, },
"node_modules/baseline-browser-mapping": { "node_modules/baseline-browser-mapping": {
"version": "2.10.30", "version": "2.10.31",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.30.tgz", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.31.tgz",
"integrity": "sha512-xjOFN16Ha1+Rz4nFYKqHU/LSB+gx/Vi3yQLX7r7sAW+Wa+8hhF2h4pvqTrTMc8+WcDBEunnUurr46Jvv0jk3Vg==", "integrity": "sha512-MujYO3eP72uvmSE0i4wltsodRfIpZATP3jvzRNRGGxgzId7aVocVJJV3nf01qnzzKFGxQVC9bpWxl5cjxTr/7Q==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"bin": { "bin": {
@@ -2260,11 +2260,11 @@
} }
}, },
"node_modules/convert-source-map": { "node_modules/convert-source-map": {
"version": "2.0.0", "version": "1.9.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
"dev": true, "license": "MIT",
"license": "MIT" "peer": true
}, },
"node_modules/cosmiconfig": { "node_modules/cosmiconfig": {
"version": "7.1.0", "version": "7.1.0",
@@ -2342,9 +2342,9 @@
} }
}, },
"node_modules/electron-to-chromium": { "node_modules/electron-to-chromium": {
"version": "1.5.357", "version": "1.5.359",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.357.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.359.tgz",
"integrity": "sha512-NHlTIQDK8fmVwHwuIzmXYEJ1Ewq3D9wDNc0cWXxDGysP6Pb21giwGNkxiTifyKy/4SoPuN5l6GLP1W9Sv7zB2g==", "integrity": "sha512-8lPELWuYZIWk7NDvCNthtmMw/7Q5Wu25NpM4djFMHBmk8DubPAtL4YTOp7ou0e7HyJtwkVlWv8XMLURnrtgJQw==",
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
@@ -2960,30 +2960,26 @@
} }
}, },
"node_modules/react": { "node_modules/react": {
"version": "18.3.1", "version": "19.1.0",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==",
"license": "MIT", "license": "MIT",
"peer": true, "peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/react-dom": { "node_modules/react-dom": {
"version": "18.3.1", "version": "19.1.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "integrity": "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==",
"license": "MIT", "license": "MIT",
"peer": true, "peer": true,
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0", "scheduler": "^0.26.0"
"scheduler": "^0.23.2"
}, },
"peerDependencies": { "peerDependencies": {
"react": "^18.3.1" "react": "^19.1.0"
} }
}, },
"node_modules/react-is": { "node_modules/react-is": {
@@ -3098,14 +3094,11 @@
} }
}, },
"node_modules/scheduler": { "node_modules/scheduler": {
"version": "0.23.2", "version": "0.26.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==",
"license": "MIT", "license": "MIT",
"peer": true, "peer": true
"dependencies": {
"loose-envify": "^1.1.0"
}
}, },
"node_modules/semver": { "node_modules/semver": {
"version": "6.3.1", "version": "6.3.1",
+2 -2
View File
@@ -18,8 +18,8 @@
"@emotion/cache": "11.14.0", "@emotion/cache": "11.14.0",
"@emotion/react": "^11.14.0", "@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1", "@emotion/styled": "^11.14.1",
"react": "^18.3.1", "react": "19.1.0",
"react-dom": "^18.3.1", "react-dom": "19.1.0",
"@mui/base": "5.0.0-beta.70", "@mui/base": "5.0.0-beta.70",
"@mui/icons-material": "^7.3.5", "@mui/icons-material": "^7.3.5",
"@mui/lab": "7.0.0-beta.14", "@mui/lab": "7.0.0-beta.14",
+46
View File
@@ -0,0 +1,46 @@
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"}
]}
multiple
/>
</ApiProvider>
</div>
)
}
export default Testing;
+2 -1
View File
@@ -14,7 +14,8 @@ const createClient = (baseURL, withBaseFormat = false) => {
formatApiResponse({ formatApiResponse({
status: response.status, status: response.status,
data: response.data, data: response.data,
message: response.data?.message ?? response.statusText message: response.data?.message ?? response.statusText,
totalRecord: response.totalRecord ?? 0
}), }),
(error) => Promise.resolve(formatApiResponse(error)) (error) => Promise.resolve(formatApiResponse(error))
); );
+57 -39
View File
@@ -1,3 +1,5 @@
// src/api/request.js
import { formatApiResponse } from '../utils/response'; import { formatApiResponse } from '../utils/response';
import { oslogApi, apiGo } from './axiosClient'; import { oslogApi, apiGo } from './axiosClient';
@@ -10,31 +12,26 @@ const request = async ({
endpoint = '', endpoint = '',
suffix = '', suffix = '',
data = null, data = null,
params = {},
headers = {},
customUrl = '', customUrl = '',
axiosConfig = {}, axiosConfig = {}
}) => { }) => {
const url = customUrl || `${endpoint}${suffix}`; const url = customUrl || `${endpoint}${suffix}`;
try { try {
const client = isApiGo ? apiGo : oslogApi; const client = isApiGo ? apiGo : oslogApi;
const response = await client({ const response = await client({
method, method,
url, url,
data, data,
params,
headers, // highest priority
...axiosConfig, ...axiosConfig
}); });
return formatApiResponse(response); return response
} catch (error) { } catch (error) {
const responseError = formatApiResponse(error); return formatApiResponse(error);
//logError(`at endpoint: ${url} error: `, responseError);
return responseError;
} }
}; };
@@ -42,65 +39,86 @@ const request = async ({
* CREATE NEW * CREATE NEW
* POST /endpoint/new * POST /endpoint/new
*/ */
export const newRequest = (endpoint, data = null, config = {}) => export const newRequest = (
endpoint,
data = null,
axiosConfig = {}
) =>
request({ request({
method: 'post', method: 'post',
endpoint, endpoint,
suffix: '/new', suffix: '/new',
data, data,
...config, axiosConfig
}); });
/** /**
* ADD * ADD
* POST /endpoint/add * POST /endpoint/add
*/ */
export const addRequest = (endpoint, data = null, config = {}) => export const addRequest = (
endpoint,
data = null,
axiosConfig = {}
) =>
request({ request({
method: 'post', method: 'post',
endpoint, endpoint,
suffix: '/add', suffix: '/add',
data, data,
...config, axiosConfig
}); });
/** /**
* GET BY ID * GET BY ID
* GET /endpoint/:id * GET /endpoint/:id
*/ */
export const getByIdRequest = (id, endpoint, params = {}, config = {}) => export const getByIdRequest = (
id,
endpoint,
axiosConfig = {}
) =>
request({ request({
method: 'get', method: 'get',
endpoint, endpoint,
suffix: `/${id}`, suffix: `/${id}`,
params, axiosConfig
...config,
}); });
/** /**
* EDIT * EDIT
* PUT /endpoint/edit/:id * PUT /endpoint/edit/:id
*/ */
export const editRequest = (id, endpoint, data = null, config = {}) => export const editRequest = (
id,
endpoint,
data = null,
axiosConfig = {}
) =>
request({ request({
method: 'put', method: 'put',
endpoint, endpoint,
suffix: `/edit/${id}`, suffix: `/edit/${id}`,
data, data,
...config, axiosConfig
}); });
/** /**
* DELETE * DELETE
* DELETE /endpoint/delete/:id * DELETE /endpoint/delete/:id
*/ */
export const deleteRequest = (id, endpoint, data = null, config = {}) => export const deleteRequest = (
id,
endpoint,
data = null,
axiosConfig = {}
) =>
request({ request({
method: 'delete', method: 'delete',
endpoint, endpoint,
suffix: `/delete/${id}`, suffix: `/delete/${id}`,
data, data,
...config, axiosConfig
}); });
/** /**
@@ -110,8 +128,7 @@ export const deleteRequest = (id, endpoint, data = null, config = {}) =>
export const searchRequest = ( export const searchRequest = (
endpoint, endpoint,
data = null, data = null,
params = {}, axiosConfig = {}
config = {},
) => { ) => {
const timezone = -new Date().getTimezoneOffset() / 60; const timezone = -new Date().getTimezoneOffset() / 60;
@@ -120,37 +137,38 @@ export const searchRequest = (
endpoint, endpoint,
suffix: '/search', suffix: '/search',
data, data,
params: {
tz: timezone, axiosConfig: {
...params, ...axiosConfig,
},
...config, params: {
tz: timezone,
...(axiosConfig.params || {})
}
}
}); });
}; };
/** /**
* CUSTOM REQUEST * CUSTOM REQUEST
* untuk endpoint bebas / beda sendiri
*/ */
export const customRequest = ({ export const customRequest = ({
method = 'get', method = 'get',
url = '', url = '',
data = null, data = null,
params = {}, isApiGo = false,
headers = {}, axiosConfig = {}
axiosConfig = {},
}) => }) =>
request({ request({
method, method,
customUrl: url, customUrl: url,
data, data,
params, isApiGo,
headers, axiosConfig
axiosConfig,
}); });
/** /**
* Optional Export Object * EXPORT OBJECT
*/ */
export const apiRequest = { export const apiRequest = {
new: newRequest, new: newRequest,
@@ -159,5 +177,5 @@ export const apiRequest = {
edit: editRequest, edit: editRequest,
delete: deleteRequest, delete: deleteRequest,
search: searchRequest, search: searchRequest,
custom: customRequest, custom: customRequest
}; };
+39
View File
@@ -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;
}
+194 -56
View File
@@ -11,11 +11,13 @@ import {
ListItemText, ListItemText,
Typography, Typography,
InputAdornment, InputAdornment,
IconButton IconButton,
Checkbox
} from "@mui/material"; } from "@mui/material";
import ClearIcon from "@mui/icons-material/Clear"; import ClearIcon from "@mui/icons-material/Clear";
import FilterTableBuilder from "../utils/filterTableBuilder"; import FilterTableBuilder from "../utils/filterTableBuilder";
import { apiRequest } from "../api/request"; import { apiRequest } from "../api/request";
import { useApiHeaders } from "./ApiContext";
export default function ListVirtual({ export default function ListVirtual({
id, id,
@@ -33,8 +35,10 @@ export default function ListVirtual({
helperText, helperText,
filter, filter,
isApiGo = false, isApiGo = false,
headersRequest, multiple,
customSxTextField = {}
}) { }) {
const headersRequest = useApiHeaders();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [rows, setRows] = useState([]); const [rows, setRows] = useState([]);
@@ -65,18 +69,21 @@ export default function ListVirtual({
if (keyword) payload.like(name, keyword); if (keyword) payload.like(name, keyword);
if (filter && filter.length > 0) { 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"]);
} }
try { try {
const res = await apiRequest.search( const res = await apiRequest.search(
url, url,
payload.build(), payload.build(),
{},
{ {
isApiGo,
headers: headersRequest headers: headersRequest
} },
isApiGo,
); );
const incomingData = res.data || []; const incomingData = res.data || [];
@@ -92,12 +99,13 @@ export default function ListVirtual({
const handleScroll = (e) => { const handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget; const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
const isAtBottom = scrollHeight - scrollTop <= clientHeight + 20; const isAtBottom = scrollHeight - scrollTop <= clientHeight + 20;
if (isAtBottom && !loading && rows.length < totalRecord) { if (isAtBottom && !loading && rows.length < totalRecord) {
const nextOffset = offset + lengthData; const nextOffset = offset + lengthData;
fetchData(search, nextOffset, true);
fetchData(search, nextOffset, true);
} }
}; };
@@ -117,60 +125,158 @@ export default function ListVirtual({
} }
}, [open]); }, [open]);
const fetchById = async (id) => { const fetchDefaultValue = async (value) => {
setLoading(true); setLoading(true);
const payload = new FilterTableBuilder() const payload = new FilterTableBuilder().setPaging(0, lengthData);
.setPaging(0, 1)
.equal("id", id);
try { if (multiple) {
const res = await apiRequest.search( payload.in("id", value); // value = [1,2,3]
url, } else {
payload.build(), payload.equal("id", value); // value = 1
{},
{
isApiGo,
headers: headersRequest
}
);
const data = res.data?.[0];
if (data) {
setSelected(data);
}
} catch (err) {
console.error(err);
} }
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(() => { useEffect(() => {
if (!defaultValue) return; if (defaultValue == null) return;
if (typeof defaultValue === "object") { if (multiple) {
setSelected(defaultValue); // 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 { } else {
fetchById(defaultValue); if (typeof defaultValue === "object" && !Array.isArray(defaultValue)) {
setSelected(defaultValue);
return;
}
} }
}, [defaultValue]);
fetchDefaultValue(defaultValue);
}, [defaultValue, multiple]);
const handleSelect = (row) => { const handleSelect = (row) => {
setSelected(row); if (!multiple) {
setOpen(false); setSelected(row);
setSearch(""); setOpen(false);
getData && getData(row); 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 = () => { const handleClear = () => {
setSelected(null); setSelected(multiple ? [] : null);
setSearch(""); setSearch("");
setRows([]); setRows([]);
getData && getData(null);
getData?.(multiple ? [] : null);
};
const displayValue = multiple
? `${selected?.length || 0} ${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
)
);
}
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 ( return (
<> <>
@@ -186,6 +292,7 @@ export default function ListVirtual({
error={!!error} error={!!error}
onClick={() => !disabled && setOpen(true)} onClick={() => !disabled && setOpen(true)}
sx={{ sx={{
...customSxTextField,
'& .MuiOutlinedInput-root.Mui-error .MuiOutlinedInput-notchedOutline': { '& .MuiOutlinedInput-root.Mui-error .MuiOutlinedInput-notchedOutline': {
borderColor: 'error.main', borderColor: 'error.main',
} }
@@ -217,7 +324,20 @@ export default function ListVirtual({
<DialogTitle sx={{ fontSize: 14 }}>Search {label}</DialogTitle> <DialogTitle sx={{ fontSize: 14 }}>Search {label}</DialogTitle>
<DialogContent <DialogContent
onScroll={handleScroll} 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 <TextField
fullWidth fullWidth
@@ -233,17 +353,35 @@ export default function ListVirtual({
/> />
<List disablePadding> <List disablePadding>
{rows.map((row, i) => ( <>
<ListItemButton key={`${row.id}-${i}`} onClick={() => handleSelect(row)}> {multiple && (
<ListItemText primary={row[name]} slotProps={{ primary: { fontSize: 14 } }} /> <ListItemButton
</ListItemButton> onClick={handleSelectAll}
))} sx={{ fontSize: 14 }}
>
{loading && ( Select All
<Typography variant="caption" sx={{ display: 'block', textAlign: 'center', p: 1 }}> </ListItemButton>
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> </List>
{!loading && rows.length === 0 && ( {!loading && rows.length === 0 && (
+2
View File
@@ -0,0 +1,2 @@
export { default as ListVirtual } from "./ListVirtual";
export * from "./ApiContext";
+3 -1
View File
@@ -1 +1,3 @@
export { default as ListVirtual } from './components/ListVirtual.jsx'; export * from './api/request';
export * from './components';
//export * from './utils';
+77
View File
@@ -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>
);
+1 -1
View File
@@ -1,7 +1,7 @@
export const formatApiResponse = (responseOrError) => { export const formatApiResponse = (responseOrError) => {
if (responseOrError?.status) { if (responseOrError?.status) {
const { status, data, message } = responseOrError; const { status, data, message } = responseOrError;
if (status >= 200 && status < 300) { if (status >= 200 && status < 300) {
return { return {
code: data.code ?? status, code: data.code ?? status,