6 Commits
7 changed files with 4803 additions and 3795 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.
+4386 -3740
View File
File diff suppressed because it is too large Load Diff
+20 -1
View File
@@ -1,9 +1,12 @@
import ListVirtual from "./components/ListVirtual"; import ListVirtual from "./components/ListVirtual";
import { ApiProvider } from "./components/ApiContext"; import { ApiProvider } from "./components/ApiContext";
import { API_TOKEN } from "./config/constants"; import { API_TOKEN } from "./config/constants";
import { useState } from "react";
const Testing = () => { const Testing = () => {
const token = API_TOKEN; const token = API_TOKEN;
const [selectedVehicle, setSelectedVehicle] = useState([]);
return ( return (
<div style={{ padding: 8, marginTop: 12 }}> <div style={{ padding: 8, marginTop: 12 }}>
<ApiProvider <ApiProvider
@@ -16,8 +19,24 @@ const Testing = () => {
label="Company" label="Company"
name="name" name="name"
url="/company" url="/company"
defaultValue={"442"} defaultValue={[442,722]}
size="small" 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> </ApiProvider>
</div> </div>
+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))
); );
+1 -1
View File
@@ -29,7 +29,7 @@ const request = async ({
...axiosConfig ...axiosConfig
}); });
return formatApiResponse(response); return response
} catch (error) { } catch (error) {
return formatApiResponse(error); return formatApiResponse(error);
} }
+181 -42
View File
@@ -11,7 +11,8 @@ 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";
@@ -34,6 +35,8 @@ export default function ListVirtual({
helperText, helperText,
filter, filter,
isApiGo = false, isApiGo = false,
multiple,
customSxTextField = {}
}) { }) {
const headersRequest = useApiHeaders(); const headersRequest = useApiHeaders();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@@ -69,6 +72,10 @@ 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)); 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,
@@ -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,59 +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); if (multiple) {
payload.in("id", value); // value = [1,2,3]
} else {
payload.equal("id", value); // value = 1
}
try { try {
const res = await apiRequest.search( const res = await apiRequest.search(
url, url,
payload.build(), payload.build(),
{ {
headers: headersRequest headers: headersRequest,
}, },
isApiGo, isApiGo,
); );
const data = res.data?.[0]; const data = res.data || [];
if (data) { setSelected(multiple ? data : data[0] || null);
setSelected(data);
}
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} finally {
setLoading(false);
} }
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 (
<> <>
@@ -185,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',
} }
@@ -216,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
@@ -232,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 && (
+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,