7 Commits
7 changed files with 5042 additions and 4012 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)
- [@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.
+4608 -3957
View File
File diff suppressed because it is too large Load Diff
+26 -1
View File
@@ -1,9 +1,12 @@
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
@@ -16,8 +19,30 @@ const Testing = () => {
label="Company"
name="name"
url="/company"
defaultValue={"442"}
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>
+2 -1
View File
@@ -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))
);
+1 -1
View File
@@ -29,7 +29,7 @@ const request = async ({
...axiosConfig
});
return formatApiResponse(response);
return response
} catch (error) {
return formatApiResponse(error);
}
+188 -38
View File
@@ -11,7 +11,8 @@ import {
ListItemText,
Typography,
InputAdornment,
IconButton
IconButton,
Checkbox
} from "@mui/material";
import ClearIcon from "@mui/icons-material/Clear";
import FilterTableBuilder from "../utils/filterTableBuilder";
@@ -34,6 +35,9 @@ export default function ListVirtual({
helperText,
filter,
isApiGo = false,
multiple,
customSxTextField = {},
joins = [],
}) {
const headersRequest = useApiHeaders();
const [open, setOpen] = useState(false);
@@ -69,6 +73,14 @@ export default function ListVirtual({
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,
@@ -97,6 +109,7 @@ export default function ListVirtual({
if (isAtBottom && !loading && rows.length < totalRecord) {
const nextOffset = offset + lengthData;
fetchData(search, nextOffset, true);
}
};
@@ -117,59 +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);
if (multiple) {
payload.in("id", value); // value = [1,2,3]
} else {
payload.equal("id", value); // value = 1
}
try {
const res = await apiRequest.search(
url,
payload.build(),
url,
payload.build(),
{
headers: headersRequest
headers: headersRequest,
},
isApiGo,
);
);
const data = res.data?.[0];
const data = res.data || [];
if (data) {
setSelected(data);
}
setSelected(multiple ? data : data[0] || null);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
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 (
<>
@@ -185,6 +303,7 @@ export default function ListVirtual({
error={!!error}
onClick={() => !disabled && setOpen(true)}
sx={{
...customSxTextField,
'& .MuiOutlinedInput-root.Mui-error .MuiOutlinedInput-notchedOutline': {
borderColor: 'error.main',
}
@@ -216,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
@@ -232,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 && (