@kareemelbalshe/any-table 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +998 -0
- package/dist/adapters/apiAdapter.d.ts +2 -0
- package/dist/adapters/index.d.ts +5 -0
- package/dist/adapters/objectUtils.d.ts +18 -0
- package/dist/adapters/paginationAdapter.d.ts +2 -0
- package/dist/adapters/searchAdapter.d.ts +4 -0
- package/dist/adapters/sortAdapter.d.ts +7 -0
- package/dist/columns/autoColumns.d.ts +5 -0
- package/dist/columns/columnResolver.d.ts +13 -0
- package/dist/columns/index.d.ts +3 -0
- package/dist/columns/typeDetector.d.ts +7 -0
- package/dist/components/AnyTable.d.ts +8 -0
- package/dist/components/TableBody.d.ts +17 -0
- package/dist/components/TableConfirmDialog.d.ts +13 -0
- package/dist/components/TableEmptyState.d.ts +8 -0
- package/dist/components/TableErrorState.d.ts +6 -0
- package/dist/components/TableHeader.d.ts +16 -0
- package/dist/components/TablePagination.d.ts +14 -0
- package/dist/components/TableSearch.d.ts +9 -0
- package/dist/components/TableSkeleton.d.ts +7 -0
- package/dist/components/index.d.ts +9 -0
- package/dist/favicon.svg +65 -0
- package/dist/hooks/index.d.ts +5 -0
- package/dist/hooks/useAnyTableController.d.ts +18 -0
- package/dist/hooks/useAnyTableData.d.ts +22 -0
- package/dist/hooks/useAnyTablePagination.d.ts +24 -0
- package/dist/hooks/useAnyTableSearch.d.ts +14 -0
- package/dist/hooks/useAnyTableSorting.d.ts +15 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +1930 -0
- package/dist/index.js.map +1 -0
- package/dist/logo.svg +65 -0
- package/dist/renderers/ActionRenderer.d.ts +8 -0
- package/dist/renderers/CellRenderer.d.ts +8 -0
- package/dist/renderers/DefaultRenderers.d.ts +52 -0
- package/dist/renderers/index.d.ts +3 -0
- package/dist/style.css +1 -0
- package/dist/theme/defaultTheme.d.ts +3 -0
- package/dist/theme/index.d.ts +2 -0
- package/dist/theme/themeContext.d.ts +8 -0
- package/dist/types/action.types.d.ts +117 -0
- package/dist/types/api.types.d.ts +99 -0
- package/dist/types/column.types.d.ts +101 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/table.types.d.ts +252 -0
- package/dist/types/theme.types.d.ts +51 -0
- package/package.json +80 -0
package/README.md
ADDED
|
@@ -0,0 +1,998 @@
|
|
|
1
|
+
# 🚀 AnyTable — Smart Data Table Library for React
|
|
2
|
+
|
|
3
|
+
> **A developer-facing, smart data table library for React (18 & 19) & TypeScript with 3-Tier API auto-detection, dynamic column extraction, autonomous server/client search, sorting & pagination, interactive row actions with instant PATCH switches, and zero business logic coupling.**
|
|
4
|
+
|
|
5
|
+
[](https://npmjs.org/package/@kareemelbalshe/any-table)
|
|
6
|
+
[](https://kareemelbalshe.github.io/anyTable/)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
[](https://www.typescriptlang.org/)
|
|
9
|
+
[](https://react.dev/)
|
|
10
|
+
[](https://vitest.dev/)
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 📑 Table of Contents (فهرس المحتويات)
|
|
15
|
+
|
|
16
|
+
- [🌟 Core Philosophy & Architecture](#-core-philosophy--architecture)
|
|
17
|
+
- [📦 Installation & Setup](#-installation--setup)
|
|
18
|
+
- [⚡ Quick Start Guide (دليل البدء السريع)](#-quick-start-guide)
|
|
19
|
+
- [1. Minimal Local Data (Zero Config)](#1-minimal-local-data-zero-config)
|
|
20
|
+
- [2. Smart Remote API with Server Pagination, Search & Sorting](#2-smart-remote-api-with-server-pagination-search--sorting)
|
|
21
|
+
- [🧠 3-Tier Smart API Adapter](#-3-tier-smart-api-adapter)
|
|
22
|
+
- [Level 1: Auto (Zero-Config Array Detection)](#level-1-auto-zero-config-array-detection)
|
|
23
|
+
- [Level 2: Dot-Notation Path Mapping](#level-2-dot-notation-path-mapping)
|
|
24
|
+
- [Level 3: Custom Response Transformer](#level-3-custom-response-transformer)
|
|
25
|
+
- [🎯 Row Actions & Instant PATCH Switches](#-row-actions--instant-patch-switches)
|
|
26
|
+
- [Action Buttons & Modal Triggers](#1-action-buttons)
|
|
27
|
+
- [Instant PATCH / PUT Toggle Switch](#2-instant-patch--put-toggle-switch)
|
|
28
|
+
- [Destructive Actions with Confirmation Modal](#3-destructive-actions-with-confirmation-modal)
|
|
29
|
+
- [🛠️ Column Types & Smart Renderers](#️-column-types--smart-renderers)
|
|
30
|
+
- [🕹️ Imperative Controller API (`tableRef`)](#️-imperative-controller-api-tableref)
|
|
31
|
+
- [☑️ Selection & Batch Operations](#️-selection--batch-operations)
|
|
32
|
+
- [🎨 Theming & Dark Mode](#-theming--dark-mode)
|
|
33
|
+
- [🌐 Integration Guides (Next.js & Vite)](#-integration-guides-nextjs--vite)
|
|
34
|
+
- [📋 Props & Types Reference](#-props--types-reference)
|
|
35
|
+
- [🇪🇬 دليل المبرمج باللغة العربية (Arabic Developer Guide)](#-دليل-المبرمج-باللغة-العربية-arabic-developer-guide)
|
|
36
|
+
- [📄 License](#-license)
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 🌟 Core Philosophy & Architecture
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
┌────────────────────────────────────────────────────────────────────────┐
|
|
44
|
+
│ AnyTable = Presentation + State Management + API Normalizer + Callbacks │
|
|
45
|
+
└──────────────────────────────────┬─────────────────────────────────────┘
|
|
46
|
+
│
|
|
47
|
+
┌────────────────────────────┴────────────────────────────┐
|
|
48
|
+
▼ ▼
|
|
49
|
+
[ WHAT ANYTABLE DOES ] [ WHAT DEVELOPER DOES ]
|
|
50
|
+
• Renders responsive, accessible tables • Implements REST / GraphQL APIs
|
|
51
|
+
• Auto-detects columns & data types • Manages Auth, JWT & Headers
|
|
52
|
+
• Normalizes 99% of REST API response shapes • Handles PATCH / DELETE in callbacks
|
|
53
|
+
• Manages debounced search, sort & pagination UI • Controls business logic & permissions
|
|
54
|
+
• Handles loading, empty, and error retry states • Navigates routes and opens modals
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
AnyTable is intentionally designed to **never lock you into specific backend conventions or proprietary UI frameworks**. It acts as an autonomous smart presentation layer that consumes data, coordinates user interactions, and exposes clean callback hooks for your business logic.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## 📦 Installation & Setup
|
|
62
|
+
|
|
63
|
+
### 1. Install via Package Manager
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# Using NPM
|
|
67
|
+
npm install @kareemelbalshe/any-table react-icons
|
|
68
|
+
|
|
69
|
+
# Using Yarn
|
|
70
|
+
yarn add @kareemelbalshe/any-table react-icons
|
|
71
|
+
|
|
72
|
+
# Using PNPM
|
|
73
|
+
pnpm add @kareemelbalshe/any-table react-icons
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 2. Import CSS Styles
|
|
77
|
+
|
|
78
|
+
Import the library stylesheet once in your main application entry point:
|
|
79
|
+
|
|
80
|
+
```tsx
|
|
81
|
+
// In main.tsx / App.tsx (Vite / CRA) or app/layout.tsx (Next.js)
|
|
82
|
+
import "@kareemelbalshe/any-table/style.css";
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## ⚡ Quick Start Guide
|
|
88
|
+
|
|
89
|
+
### 1. Minimal Local Data (Zero Config)
|
|
90
|
+
|
|
91
|
+
Pass any plain JavaScript array without defining columns. AnyTable automatically extracts keys, converts camelCase/snake_case to readable headers, detects data types (e.g. currency, boolean, date), and provides search, sorting, and pagination:
|
|
92
|
+
|
|
93
|
+
```tsx
|
|
94
|
+
import React from "react";
|
|
95
|
+
import { AnyTable } from "@kareemelbalshe/any-table";
|
|
96
|
+
import "@kareemelbalshe/any-table/style.css";
|
|
97
|
+
|
|
98
|
+
const orders = [
|
|
99
|
+
{ id: "ORD-101", customerName: "Ahmed Ali", total: 4500, isPaid: true, createdAt: "2026-08-15T10:30:00Z" },
|
|
100
|
+
{ id: "ORD-102", customerName: "Sara Mansour", total: 1250, isPaid: false, createdAt: "2026-08-16T14:15:00Z" },
|
|
101
|
+
{ id: "ORD-103", customerName: "Omar Khaled", total: 8900, isPaid: true, createdAt: "2026-08-18T09:00:00Z" },
|
|
102
|
+
];
|
|
103
|
+
|
|
104
|
+
export default function OrdersPage() {
|
|
105
|
+
return (
|
|
106
|
+
<div className="p-6">
|
|
107
|
+
<AnyTable
|
|
108
|
+
title="Recent Orders"
|
|
109
|
+
subtitle="Overview of all transactions"
|
|
110
|
+
data={orders}
|
|
111
|
+
/>
|
|
112
|
+
</div>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
### 2. Smart Remote API with Server Pagination, Search & Sorting
|
|
120
|
+
|
|
121
|
+
Pass your `fetcher` function. AnyTable will automatically pass `{ page, pageSize, search, sortBy, sortOrder }` parameters, debounce search input (350ms default), and handle loading/error states:
|
|
122
|
+
|
|
123
|
+
```tsx
|
|
124
|
+
import React from "react";
|
|
125
|
+
import { AnyTable } from "@kareemelbalshe/any-table";
|
|
126
|
+
import axios from "axios";
|
|
127
|
+
|
|
128
|
+
interface User {
|
|
129
|
+
id: string;
|
|
130
|
+
name: string;
|
|
131
|
+
email: string;
|
|
132
|
+
role: "admin" | "editor" | "user";
|
|
133
|
+
spend: number;
|
|
134
|
+
isActive: boolean;
|
|
135
|
+
createdAt: string;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export default function UsersPage() {
|
|
139
|
+
return (
|
|
140
|
+
<AnyTable<User>
|
|
141
|
+
title="Platform Users"
|
|
142
|
+
subtitle="Connected directly to remote backend API"
|
|
143
|
+
rowKey="id"
|
|
144
|
+
api={{
|
|
145
|
+
fetcher: async ({ page, pageSize, search, sortBy, sortOrder }) => {
|
|
146
|
+
const response = await axios.get("/api/v1/users", {
|
|
147
|
+
params: { page, limit: pageSize, q: search, sortBy, sortOrder },
|
|
148
|
+
});
|
|
149
|
+
return response.data; // e.g. { data: [...], total: 150, page: 1 }
|
|
150
|
+
},
|
|
151
|
+
}}
|
|
152
|
+
columns={[
|
|
153
|
+
{ key: "name", title: "Full Name", sortable: true },
|
|
154
|
+
{ key: "email", title: "Email Address", type: "email" },
|
|
155
|
+
{ key: "role", title: "Role", type: "status" },
|
|
156
|
+
{ key: "spend", title: "Total Spend", type: "currency", currency: "EGP", sortable: true },
|
|
157
|
+
{ key: "createdAt", title: "Registered At", type: "date", sortable: true },
|
|
158
|
+
]}
|
|
159
|
+
/>
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## 🧠 3-Tier Smart API Adapter
|
|
167
|
+
|
|
168
|
+
Backend response formats vary widely across organizations. AnyTable provides a **3-Tier Adapter** that handles 99% of APIs effortlessly:
|
|
169
|
+
|
|
170
|
+
```
|
|
171
|
+
┌─────────────────────────┐
|
|
172
|
+
│ Smart API Adapter │
|
|
173
|
+
└────────────┬────────────┘
|
|
174
|
+
┌────────────────────────────┼────────────────────────────┐
|
|
175
|
+
▼ ▼ ▼
|
|
176
|
+
[ Level 1: Auto ] [ Level 2: Config ] [ Level 3: Control ]
|
|
177
|
+
Automatic detection of Explicit dot-notation Custom transformResponse
|
|
178
|
+
data array & pagination path mapping function
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Level 1: Auto (Zero-Config Array Detection)
|
|
182
|
+
Automatically extracts arrays from root `[...]` or keys named `data`, `items`, `results`, `rows`, `records`, `payload`, `users`, `orders`, `products`. Total count is detected from `total`, `totalRecords`, `meta.total`, `count`, etc.
|
|
183
|
+
|
|
184
|
+
```tsx
|
|
185
|
+
<AnyTable
|
|
186
|
+
api={{
|
|
187
|
+
fetcher: (params) => axios.get("/api/users", { params }).then(res => res.data)
|
|
188
|
+
}}
|
|
189
|
+
/>
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### Level 2: Dot-Notation Path Mapping
|
|
193
|
+
For structured responses with custom nested keys (e.g. `{ responsePayload: { userList: [...], pagination: { totalCount: 200 } } }`):
|
|
194
|
+
|
|
195
|
+
```tsx
|
|
196
|
+
<AnyTable
|
|
197
|
+
api={{
|
|
198
|
+
fetcher: getUsersApi,
|
|
199
|
+
response: {
|
|
200
|
+
dataPath: "responsePayload.userList",
|
|
201
|
+
totalPath: "responsePayload.pagination.totalCount",
|
|
202
|
+
pagePath: "responsePayload.pagination.currentPage",
|
|
203
|
+
pageSizePath: "responsePayload.pagination.perPage",
|
|
204
|
+
},
|
|
205
|
+
}}
|
|
206
|
+
/>
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### Level 3: Custom Response Transformer
|
|
210
|
+
For legacy endpoints or GraphQL formats that require custom parsing:
|
|
211
|
+
|
|
212
|
+
```tsx
|
|
213
|
+
<AnyTable
|
|
214
|
+
api={{
|
|
215
|
+
fetcher: getCustomDataApi,
|
|
216
|
+
transformResponse: (raw) => ({
|
|
217
|
+
data: raw.graphql.users.nodes,
|
|
218
|
+
meta: {
|
|
219
|
+
total: raw.graphql.users.aggregate.totalCount,
|
|
220
|
+
page: raw.graphql.users.pageInfo.currentPage,
|
|
221
|
+
pageSize: 20,
|
|
222
|
+
},
|
|
223
|
+
}),
|
|
224
|
+
}}
|
|
225
|
+
/>
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## 🌐 Real-World External Public API Recipes
|
|
231
|
+
|
|
232
|
+
AnyTable connects seamlessly to any external public REST API with zero boilerplate:
|
|
233
|
+
|
|
234
|
+
### 🛍️ 1. DummyJSON Products Inventory (E-Commerce)
|
|
235
|
+
```tsx
|
|
236
|
+
import { AnyTable } from "@kareemelbalshe/any-table";
|
|
237
|
+
|
|
238
|
+
export default function ProductsTable() {
|
|
239
|
+
return (
|
|
240
|
+
<AnyTable
|
|
241
|
+
title="E-Commerce Products Inventory"
|
|
242
|
+
rowKey="id"
|
|
243
|
+
api={{
|
|
244
|
+
fetcher: async ({ page, pageSize, search, sortBy, sortOrder }) => {
|
|
245
|
+
const skip = (page - 1) * pageSize;
|
|
246
|
+
const url = search
|
|
247
|
+
? `https://dummyjson.com/products/search?q=${encodeURIComponent(search)}&limit=${pageSize}&skip=${skip}`
|
|
248
|
+
: `https://dummyjson.com/products?limit=${pageSize}&skip=${skip}`;
|
|
249
|
+
return fetch(url).then((res) => res.json());
|
|
250
|
+
},
|
|
251
|
+
response: {
|
|
252
|
+
dataPath: "products",
|
|
253
|
+
totalPath: "total",
|
|
254
|
+
},
|
|
255
|
+
}}
|
|
256
|
+
columns={[
|
|
257
|
+
{ key: "thumbnail", title: "Image", type: "image", width: 70, align: "center" },
|
|
258
|
+
{ key: "title", title: "Product Title", sortable: true },
|
|
259
|
+
{ key: "category", title: "Category", type: "status" },
|
|
260
|
+
{ key: "price", title: "Price", type: "currency", currency: "$", sortable: true },
|
|
261
|
+
{ key: "rating", title: "Rating", render: (val) => <span>⭐ {val} / 5</span> },
|
|
262
|
+
]}
|
|
263
|
+
/>
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### 🐙 2. GitHub Search Repositories API
|
|
269
|
+
```tsx
|
|
270
|
+
import { AnyTable } from "@kareemelbalshe/any-table";
|
|
271
|
+
|
|
272
|
+
export default function GitHubSearchTable() {
|
|
273
|
+
return (
|
|
274
|
+
<AnyTable
|
|
275
|
+
title="GitHub Open-Source Repositories"
|
|
276
|
+
rowKey="id"
|
|
277
|
+
api={{
|
|
278
|
+
fetcher: async ({ page, pageSize, search }) => {
|
|
279
|
+
const q = search?.trim() ? search : "react stars:>1000";
|
|
280
|
+
const res = await fetch(
|
|
281
|
+
`https://api.github.com/search/repositories?q=${encodeURIComponent(q)}&page=${page}&per_page=${pageSize}&sort=stars`
|
|
282
|
+
);
|
|
283
|
+
return res.json();
|
|
284
|
+
},
|
|
285
|
+
response: {
|
|
286
|
+
dataPath: "items",
|
|
287
|
+
totalPath: "total_count",
|
|
288
|
+
},
|
|
289
|
+
}}
|
|
290
|
+
columns={[
|
|
291
|
+
{ key: "owner.avatar_url", title: "Owner", type: "image", width: 60, align: "center" },
|
|
292
|
+
{ key: "full_name", title: "Repository", sortable: true },
|
|
293
|
+
{ key: "language", title: "Language", type: "status" },
|
|
294
|
+
{ key: "stargazers_count", title: "Stars", render: (v) => <span>⭐ {v.toLocaleString()}</span> },
|
|
295
|
+
{ key: "forks_count", title: "Forks", render: (v) => <span>🍴 {v.toLocaleString()}</span> },
|
|
296
|
+
]}
|
|
297
|
+
actions={[
|
|
298
|
+
{
|
|
299
|
+
id: "open-repo",
|
|
300
|
+
label: "View on GitHub",
|
|
301
|
+
variant: "primary",
|
|
302
|
+
onClick: (row) => window.open(row.html_url, "_blank"),
|
|
303
|
+
},
|
|
304
|
+
]}
|
|
305
|
+
/>
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
---
|
|
311
|
+
|
|
312
|
+
## 🏢 Ultimate Enterprise Logistics & Orders Management (Real-World Pattern)
|
|
313
|
+
|
|
314
|
+
This production-grade pattern demonstrates nested customer records, VAT computations, multi-tier status badges, instant PATCH switches, and invoice popups:
|
|
315
|
+
|
|
316
|
+
```tsx
|
|
317
|
+
import React, { useState } from "react";
|
|
318
|
+
import { AnyTable } from "@kareemelbalshe/any-table";
|
|
319
|
+
|
|
320
|
+
export default function EnterpriseOrdersDashboard() {
|
|
321
|
+
const [selectedInvoice, setSelectedInvoice] = useState<any>(null);
|
|
322
|
+
|
|
323
|
+
return (
|
|
324
|
+
<div>
|
|
325
|
+
<AnyTable
|
|
326
|
+
title="Enterprise Fulfillment & Orders"
|
|
327
|
+
subtitle="Live multi-carrier logistics tracking with instant PATCH switches and invoice modals"
|
|
328
|
+
rowKey="id"
|
|
329
|
+
api={{ fetcher: fetchOrdersApi }}
|
|
330
|
+
columns={[
|
|
331
|
+
{ key: "orderNumber", title: "Order #", width: 110, sortable: true },
|
|
332
|
+
{
|
|
333
|
+
key: "customer.name",
|
|
334
|
+
title: "Customer Profile",
|
|
335
|
+
sortable: true,
|
|
336
|
+
render: (_, row) => (
|
|
337
|
+
<div className="flex items-center gap-3">
|
|
338
|
+
<img src={row.customer.avatar} className="w-9 h-9 rounded-full object-cover" />
|
|
339
|
+
<div>
|
|
340
|
+
<div className="font-bold text-xs">{row.customer.name}</div>
|
|
341
|
+
<div className="text-[11px] text-gray-400">{row.customer.phone}</div>
|
|
342
|
+
</div>
|
|
343
|
+
</div>
|
|
344
|
+
),
|
|
345
|
+
},
|
|
346
|
+
{ key: "totalAmount", title: "Total Amount", type: "currency", currency: "EGP", sortable: true },
|
|
347
|
+
{
|
|
348
|
+
key: "paymentStatus",
|
|
349
|
+
title: "Payment",
|
|
350
|
+
type: "status",
|
|
351
|
+
statusMap: {
|
|
352
|
+
Paid: { label: "Paid", variant: "success" },
|
|
353
|
+
Pending: { label: "Pending", variant: "warning" },
|
|
354
|
+
Refunded: { label: "Refunded", variant: "neutral" },
|
|
355
|
+
Failed: { label: "Failed", variant: "danger" },
|
|
356
|
+
},
|
|
357
|
+
},
|
|
358
|
+
{
|
|
359
|
+
key: "fulfillmentStatus",
|
|
360
|
+
title: "Fulfillment",
|
|
361
|
+
type: "status",
|
|
362
|
+
statusMap: {
|
|
363
|
+
Delivered: { label: "Delivered", variant: "success" },
|
|
364
|
+
"In Transit": { label: "In Transit", variant: "info" },
|
|
365
|
+
Processing: { label: "Processing", variant: "warning" },
|
|
366
|
+
Cancelled: { label: "Cancelled", variant: "danger" },
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
]}
|
|
370
|
+
actions={[
|
|
371
|
+
// Instant PATCH Switch for Express Dispatch
|
|
372
|
+
{
|
|
373
|
+
id: "express-toggle",
|
|
374
|
+
type: "switch",
|
|
375
|
+
label: "Express",
|
|
376
|
+
checked: (row) => row.isExpressShipping,
|
|
377
|
+
onChange: async (row, nextChecked, context) => {
|
|
378
|
+
await axios.patch(`/api/orders/${row.id}`, { isExpressShipping: nextChecked });
|
|
379
|
+
context.refresh();
|
|
380
|
+
},
|
|
381
|
+
},
|
|
382
|
+
// View Invoice Action
|
|
383
|
+
{
|
|
384
|
+
id: "view-invoice",
|
|
385
|
+
label: "Invoice",
|
|
386
|
+
variant: "primary",
|
|
387
|
+
onClick: (row) => setSelectedInvoice(row),
|
|
388
|
+
},
|
|
389
|
+
// Destructive Cancel with Confirmation
|
|
390
|
+
{
|
|
391
|
+
id: "cancel",
|
|
392
|
+
label: "Cancel",
|
|
393
|
+
variant: "danger",
|
|
394
|
+
confirmation: {
|
|
395
|
+
title: "Cancel Order",
|
|
396
|
+
message: (row) => `Are you sure you want to cancel order ${row.orderNumber}?`,
|
|
397
|
+
},
|
|
398
|
+
onClick: async (row, context) => {
|
|
399
|
+
await axios.post(`/api/orders/${row.id}/cancel`);
|
|
400
|
+
context.refresh();
|
|
401
|
+
},
|
|
402
|
+
},
|
|
403
|
+
]}
|
|
404
|
+
selectable
|
|
405
|
+
/>
|
|
406
|
+
</div>
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
---
|
|
412
|
+
|
|
413
|
+
## 🎯 Row Actions & Instant PATCH Switches
|
|
414
|
+
|
|
415
|
+
Define clean actions per row without mixing UI code with data rendering:
|
|
416
|
+
|
|
417
|
+
### 1. Action Buttons
|
|
418
|
+
|
|
419
|
+
```tsx
|
|
420
|
+
<AnyTable<User>
|
|
421
|
+
data={users}
|
|
422
|
+
actions={[
|
|
423
|
+
{
|
|
424
|
+
id: "view",
|
|
425
|
+
label: "View Profile",
|
|
426
|
+
variant: "primary",
|
|
427
|
+
onClick: (row) => navigate(`/users/${row.id}`),
|
|
428
|
+
},
|
|
429
|
+
{
|
|
430
|
+
id: "edit",
|
|
431
|
+
label: "Edit",
|
|
432
|
+
variant: "neutral",
|
|
433
|
+
onClick: (row) => openEditModal(row),
|
|
434
|
+
},
|
|
435
|
+
]}
|
|
436
|
+
/>
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
### 2. Instant PATCH / PUT Toggle Switch
|
|
440
|
+
|
|
441
|
+
Perfect for toggling active status, ban status, or feature flags directly with auto-refresh:
|
|
442
|
+
|
|
443
|
+
```tsx
|
|
444
|
+
<AnyTable<User>
|
|
445
|
+
api={{ fetcher: fetchUsers }}
|
|
446
|
+
actions={[
|
|
447
|
+
{
|
|
448
|
+
id: "status-toggle",
|
|
449
|
+
type: "switch",
|
|
450
|
+
label: "Active",
|
|
451
|
+
checked: (row) => row.isActive,
|
|
452
|
+
onChange: async (row, nextChecked, context) => {
|
|
453
|
+
// 1. Send update to your backend
|
|
454
|
+
await axios.patch(`/api/users/${row.id}`, { isActive: nextChecked });
|
|
455
|
+
|
|
456
|
+
// 2. Refresh the table data seamlessly
|
|
457
|
+
context.refresh();
|
|
458
|
+
},
|
|
459
|
+
},
|
|
460
|
+
]}
|
|
461
|
+
/>
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
### 3. Destructive Actions with Confirmation Modal
|
|
465
|
+
|
|
466
|
+
Built-in modal confirmation with custom title and messages:
|
|
467
|
+
|
|
468
|
+
```tsx
|
|
469
|
+
<AnyTable<User>
|
|
470
|
+
api={{ fetcher: fetchUsers }}
|
|
471
|
+
actions={[
|
|
472
|
+
{
|
|
473
|
+
id: "delete",
|
|
474
|
+
label: "Delete",
|
|
475
|
+
variant: "danger",
|
|
476
|
+
confirmation: {
|
|
477
|
+
title: "Delete Account",
|
|
478
|
+
message: (row) => `Are you sure you want to permanently delete "${row.name}"?`,
|
|
479
|
+
confirmText: "Yes, Delete",
|
|
480
|
+
cancelText: "Cancel",
|
|
481
|
+
},
|
|
482
|
+
onClick: async (row, context) => {
|
|
483
|
+
await axios.delete(`/api/users/${row.id}`);
|
|
484
|
+
context.refresh();
|
|
485
|
+
},
|
|
486
|
+
},
|
|
487
|
+
]}
|
|
488
|
+
/>
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
---
|
|
492
|
+
|
|
493
|
+
## 🛠️ Column Types & Smart Renderers
|
|
494
|
+
|
|
495
|
+
AnyTable supports built-in type renderers:
|
|
496
|
+
|
|
497
|
+
| Type | Description | Example Configuration |
|
|
498
|
+
| :--- | :--- | :--- |
|
|
499
|
+
| `string` | Regular text string | `{ key: "name", title: "Name" }` |
|
|
500
|
+
| `number` | Formatted number with locale separators | `{ key: "quantity", type: "number" }` |
|
|
501
|
+
| `currency` | Formatted currency with symbol | `{ key: "price", type: "currency", currency: "EGP" }` |
|
|
502
|
+
| `date` | Formatted date (DD/MM/YYYY) | `{ key: "birthDate", type: "date" }` |
|
|
503
|
+
| `datetime` | Date with time formatting | `{ key: "createdAt", type: "datetime" }` |
|
|
504
|
+
| `status` | Colored badge for statuses | `{ key: "status", type: "status" }` |
|
|
505
|
+
| `image` | Rounded avatar image with fallback | `{ key: "avatarUrl", type: "image", width: 70 }` |
|
|
506
|
+
| `email` | Clickable `mailto:` link | `{ key: "email", type: "email" }` |
|
|
507
|
+
| `phone` | Clickable `tel:` link | `{ key: "phone", type: "phone" }` |
|
|
508
|
+
| `url` | External web link | `{ key: "website", type: "url" }` |
|
|
509
|
+
| `custom` / `render` | Total control JSX renderer | `{ key: "tags", render: (val, row) => <div>...</div> }` |
|
|
510
|
+
|
|
511
|
+
### Custom Status Badges & Custom Renderers:
|
|
512
|
+
|
|
513
|
+
```tsx
|
|
514
|
+
columns={[
|
|
515
|
+
// Custom status badge mapping
|
|
516
|
+
{
|
|
517
|
+
key: "status",
|
|
518
|
+
title: "Order Status",
|
|
519
|
+
type: "status",
|
|
520
|
+
statusMap: {
|
|
521
|
+
completed: { label: "Completed", variant: "success" },
|
|
522
|
+
pending: { label: "Pending Payment", variant: "warning" },
|
|
523
|
+
cancelled: { label: "Cancelled", variant: "danger" },
|
|
524
|
+
},
|
|
525
|
+
},
|
|
526
|
+
|
|
527
|
+
// Custom JSX renderer
|
|
528
|
+
{
|
|
529
|
+
key: "customer",
|
|
530
|
+
title: "Customer",
|
|
531
|
+
render: (_, row) => (
|
|
532
|
+
<div className="flex items-center gap-3">
|
|
533
|
+
<img src={row.avatar} className="w-8 h-8 rounded-full" />
|
|
534
|
+
<div>
|
|
535
|
+
<div className="font-bold text-sm">{row.name}</div>
|
|
536
|
+
<div className="text-xs text-gray-500">{row.email}</div>
|
|
537
|
+
</div>
|
|
538
|
+
</div>
|
|
539
|
+
),
|
|
540
|
+
},
|
|
541
|
+
]}
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
---
|
|
545
|
+
|
|
546
|
+
## 🕹️ Imperative Controller API (`tableRef`)
|
|
547
|
+
|
|
548
|
+
Control search, pagination, and data refreshing programmatically from any external button:
|
|
549
|
+
|
|
550
|
+
```tsx
|
|
551
|
+
import React, { useRef } from "react";
|
|
552
|
+
import { AnyTable, TableInstance } from "@kareemelbalshe/any-table";
|
|
553
|
+
|
|
554
|
+
export default function Dashboard() {
|
|
555
|
+
const tableRef = useRef<TableInstance<User>>(null);
|
|
556
|
+
|
|
557
|
+
return (
|
|
558
|
+
<div>
|
|
559
|
+
<div className="flex gap-2 mb-4">
|
|
560
|
+
<button onClick={() => tableRef.current?.refresh()}>🔄 Refresh</button>
|
|
561
|
+
<button onClick={() => tableRef.current?.setPage(1)}>⏮️ First Page</button>
|
|
562
|
+
<button onClick={() => tableRef.current?.setSearch("VIP")}>🔍 Search VIP</button>
|
|
563
|
+
<button onClick={() => tableRef.current?.reset()}>⚡ Reset Table</button>
|
|
564
|
+
</div>
|
|
565
|
+
|
|
566
|
+
<AnyTable<User>
|
|
567
|
+
tableRef={tableRef}
|
|
568
|
+
api={{ fetcher: fetchUsers }}
|
|
569
|
+
/>
|
|
570
|
+
</div>
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
```
|
|
574
|
+
|
|
575
|
+
---
|
|
576
|
+
|
|
577
|
+
## ☑️ Selection & Batch Operations
|
|
578
|
+
|
|
579
|
+
Enable multi-row checkboxes to perform batch deletes or status updates:
|
|
580
|
+
|
|
581
|
+
```tsx
|
|
582
|
+
export default function BatchTable() {
|
|
583
|
+
const [selected, setSelected] = useState<User[]>([]);
|
|
584
|
+
|
|
585
|
+
return (
|
|
586
|
+
<div>
|
|
587
|
+
{selected.length > 0 && (
|
|
588
|
+
<div className="bg-blue-50 dark:bg-slate-800 p-3 rounded-lg flex items-center justify-between mb-4">
|
|
589
|
+
<span>{selected.length} items selected</span>
|
|
590
|
+
<button
|
|
591
|
+
onClick={() => handleBatchDelete(selected.map(u => u.id))}
|
|
592
|
+
className="bg-red-600 text-white px-3 py-1.5 rounded"
|
|
593
|
+
>
|
|
594
|
+
Delete Selected
|
|
595
|
+
</button>
|
|
596
|
+
</div>
|
|
597
|
+
)}
|
|
598
|
+
|
|
599
|
+
<AnyTable<User>
|
|
600
|
+
data={users}
|
|
601
|
+
selectable
|
|
602
|
+
onSelectionChange={(selectedRows, selectedKeys) => {
|
|
603
|
+
setSelected(selectedRows);
|
|
604
|
+
}}
|
|
605
|
+
/>
|
|
606
|
+
</div>
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
---
|
|
612
|
+
|
|
613
|
+
## 🛡️ Graceful Error Handling & Skeleton States
|
|
614
|
+
|
|
615
|
+
AnyTable includes built-in resilience for real-world network conditions:
|
|
616
|
+
|
|
617
|
+
- **Automated Error State**: If an API endpoint returns a 500 error or network disconnect, AnyTable presents a clean error card with the error message and an automated **"Retry Request"** button.
|
|
618
|
+
- **Race Condition Prevention**: Rapid keystrokes in the search bar or fast pagination clicks automatically abort stale requests using `AbortController`.
|
|
619
|
+
- **Skeleton Shimmer Loaders**: Smooth pulsing skeletons during fetching rather than abrupt layout shifts.
|
|
620
|
+
- **Custom Error UI**: You can override the default error state with your own component using `errorComponent`:
|
|
621
|
+
|
|
622
|
+
```tsx
|
|
623
|
+
<AnyTable<User>
|
|
624
|
+
api={{ fetcher: fetchUsers }}
|
|
625
|
+
// Optional: Custom error UI with retry callback
|
|
626
|
+
errorComponent={(error, retry) => (
|
|
627
|
+
<div className="p-8 text-center bg-rose-500/10 rounded-2xl border border-rose-500/20">
|
|
628
|
+
<p className="text-rose-500 font-bold mb-3">⚠️ Failed to connect: {error.message}</p>
|
|
629
|
+
<button
|
|
630
|
+
onClick={retry}
|
|
631
|
+
className="px-4 py-2 bg-rose-600 text-white font-bold rounded-xl shadow-md hover:bg-rose-700"
|
|
632
|
+
>
|
|
633
|
+
🔄 Try Again
|
|
634
|
+
</button>
|
|
635
|
+
</div>
|
|
636
|
+
)}
|
|
637
|
+
/>
|
|
638
|
+
```
|
|
639
|
+
|
|
640
|
+
---
|
|
641
|
+
|
|
642
|
+
## 🎨 Theming & Dark Mode
|
|
643
|
+
|
|
644
|
+
AnyTable is built with CSS variables and seamlessly adapts to light & dark modes. You can customize colors via the `theme` prop:
|
|
645
|
+
|
|
646
|
+
```tsx
|
|
647
|
+
<AnyTable
|
|
648
|
+
theme={{
|
|
649
|
+
colors: {
|
|
650
|
+
primary: "#2667EC", // Wasel Electric Blue
|
|
651
|
+
background: "#0f172a", // Custom Dark Background
|
|
652
|
+
text: "#f8fafc", // Custom Light Text
|
|
653
|
+
borderRadius: "0.75rem", // Border Radius
|
|
654
|
+
},
|
|
655
|
+
}}
|
|
656
|
+
/>
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
---
|
|
660
|
+
|
|
661
|
+
## 🌐 Integration Guides (Next.js & Vite)
|
|
662
|
+
|
|
663
|
+
### In Next.js (App Router `app/page.tsx`)
|
|
664
|
+
|
|
665
|
+
Because AnyTable utilizes client-side state and interactive events, mark your component with `'use client'`:
|
|
666
|
+
|
|
667
|
+
```tsx
|
|
668
|
+
"use client";
|
|
669
|
+
|
|
670
|
+
import { AnyTable } from "@kareemelbalshe/any-table";
|
|
671
|
+
import "@kareemelbalshe/any-table/style.css";
|
|
672
|
+
|
|
673
|
+
export default function AdminPage() {
|
|
674
|
+
return (
|
|
675
|
+
<main className="container mx-auto py-8">
|
|
676
|
+
<AnyTable
|
|
677
|
+
title="Next.js App Router Table"
|
|
678
|
+
api={{
|
|
679
|
+
fetcher: (params) => fetch(`/api/users?${new URLSearchParams(params as any)}`).then(r => r.json()),
|
|
680
|
+
}}
|
|
681
|
+
/>
|
|
682
|
+
</main>
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
---
|
|
688
|
+
|
|
689
|
+
## 📋 Props & Types Reference
|
|
690
|
+
|
|
691
|
+
### `AnyTableProps<TData>`
|
|
692
|
+
|
|
693
|
+
| Prop | Type | Default | Description |
|
|
694
|
+
| :--- | :--- | :--- | :--- |
|
|
695
|
+
| `data` | `TData[]` | `undefined` | Direct local array of items. |
|
|
696
|
+
| `api` | `ApiConfig<TData>` | `undefined` | Remote REST API configuration. |
|
|
697
|
+
| `columns` | `ColumnDef<TData>[]` | `auto` | Explicit column configurations. |
|
|
698
|
+
| `autoColumns` | `boolean` | `true` | Automatically extract columns if not provided. |
|
|
699
|
+
| `rowKey` | `keyof TData \| ((row, idx) => string \| number)` | `'id' \| '_id'` | Unique identifier for row keys. |
|
|
700
|
+
| `title` | `ReactNode` | `undefined` | Section title in table header. |
|
|
701
|
+
| `subtitle` | `ReactNode` | `undefined` | Section subtitle / description. |
|
|
702
|
+
| `actions` | `TableAction<TData>[]` | `[]` | Action buttons, switches, and modals. |
|
|
703
|
+
| `search` | `boolean \| SearchConfig<TData>` | `true` | Debounced search bar. |
|
|
704
|
+
| `sorting` | `boolean \| SortingConfig<TData>` | `true` | Column sorting configuration. |
|
|
705
|
+
| `pagination` | `boolean \| PaginationConfig` | `true` | Pagination and page size controls. |
|
|
706
|
+
| `selectable` | `boolean` | `false` | Enables row selection checkboxes. |
|
|
707
|
+
| `onSelectionChange` | `(rows, keys) => void` | `undefined` | Selection listener callback. |
|
|
708
|
+
| `onRowClick` | `(row, idx, event) => void` | `undefined` | Row click handler. |
|
|
709
|
+
| `tableRef` | `Ref<TableInstance<TData>>` | `undefined` | Imperative controller ref. |
|
|
710
|
+
| `theme` | `Partial<AnyTableTheme>` | `default` | Custom color and style overrides. |
|
|
711
|
+
| `headerActions` | `ReactNode` | `undefined` | Custom JSX buttons placed in top header. |
|
|
712
|
+
| `bordered` | `boolean` | `true` | Show borders around table and cells. |
|
|
713
|
+
| `striped` | `boolean` | `false` | Alternating zebra stripe row backgrounds. |
|
|
714
|
+
| `hoverable` | `boolean` | `true` | Highlight rows on hover. |
|
|
715
|
+
| `compact` | `boolean` | `false` | Compact row padding density. |
|
|
716
|
+
|
|
717
|
+
---
|
|
718
|
+
|
|
719
|
+
## 🇪🇬 دليل المبرمج الشامل باللغة العربية (All Use Cases Guide)
|
|
720
|
+
|
|
721
|
+
مكتبة **AnyTable** مصممة لتجعل بناء الجداول في تطبيقات **React 18/19** و **Next.js** و **TypeScript** سريعة وخالية من أي كود متكرر (Boilerplate)، مع فصل كامل لمنطق العمل (Business Logic) عن واجهة العرض.
|
|
722
|
+
|
|
723
|
+
---
|
|
724
|
+
|
|
725
|
+
### 📦 الخطوة 1: التثبيت والاستيراد الأساسي
|
|
726
|
+
```bash
|
|
727
|
+
npm install @kareemelbalshe/any-table react-icons
|
|
728
|
+
```
|
|
729
|
+
في ملف المدخل الأساسي لتطبيقك (`main.tsx` أو `App.tsx` أو `app/layout.tsx`):
|
|
730
|
+
```tsx
|
|
731
|
+
import "@kareemelbalshe/any-table/style.css";
|
|
732
|
+
```
|
|
733
|
+
|
|
734
|
+
---
|
|
735
|
+
|
|
736
|
+
### 💡 الحالة 1: جدول فوري بدون أي إعداد للأعمدة (Zero Configuration)
|
|
737
|
+
مرر مصفوفة بيانات خام مباشرة، وسيقوم الجدول باستخراج الحقول وتحويل العناوين وضبط البحث والترقيم تلقائياً:
|
|
738
|
+
```tsx
|
|
739
|
+
import { AnyTable } from "@kareemelbalshe/any-table";
|
|
740
|
+
|
|
741
|
+
const users = [
|
|
742
|
+
{ id: 1, fullName: "كريم البلسي", email: "kareem@example.com", balance: 5000, isActive: true },
|
|
743
|
+
{ id: 2, fullName: "أحمد علي", email: "ahmed@example.com", balance: 3200, isActive: false },
|
|
744
|
+
];
|
|
745
|
+
|
|
746
|
+
export default function SimplePage() {
|
|
747
|
+
return <AnyTable title="قائمة المستخدمين" data={users} />;
|
|
748
|
+
}
|
|
749
|
+
```
|
|
750
|
+
|
|
751
|
+
---
|
|
752
|
+
|
|
753
|
+
### 💡 الحالة 2: جدول مخصص بأنواع بيانات ذكية (Smart Column Types)
|
|
754
|
+
يدعم الجدول تلقائياً عرض العملات، الصور، شارات الحالات، والروابط:
|
|
755
|
+
```tsx
|
|
756
|
+
<AnyTable
|
|
757
|
+
title="العملاء المميزين"
|
|
758
|
+
data={clients}
|
|
759
|
+
rowKey="id"
|
|
760
|
+
columns={[
|
|
761
|
+
// صورة الأفاتار
|
|
762
|
+
{ key: "avatar", title: "الصورة", type: "image", width: 70, align: "center" },
|
|
763
|
+
// نص مع خاصية الترتيب
|
|
764
|
+
{ key: "name", title: "اسم العميل", sortable: true },
|
|
765
|
+
// بريد إلكتروني قابل للنقر
|
|
766
|
+
{ key: "email", title: "البريد", type: "email" },
|
|
767
|
+
// عملة مع رمز الجنيه المصري
|
|
768
|
+
{ key: "walletBalance", title: "الرصيد", type: "currency", currency: "EGP", sortable: true },
|
|
769
|
+
// شارة حالة ملونة مخصصة
|
|
770
|
+
{
|
|
771
|
+
key: "status",
|
|
772
|
+
title: "الحالة",
|
|
773
|
+
type: "status",
|
|
774
|
+
statusMap: {
|
|
775
|
+
active: { label: "نشط", variant: "success" },
|
|
776
|
+
pending: { label: "قيد المراجعة", variant: "warning" },
|
|
777
|
+
banned: { label: "محظور", variant: "danger" },
|
|
778
|
+
},
|
|
779
|
+
},
|
|
780
|
+
// مخرج JSX مخصص بالكامل
|
|
781
|
+
{
|
|
782
|
+
key: "rating",
|
|
783
|
+
title: "التقييم",
|
|
784
|
+
render: (val) => <span>⭐ {val} / 5</span>,
|
|
785
|
+
},
|
|
786
|
+
]}
|
|
787
|
+
/>
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
---
|
|
791
|
+
|
|
792
|
+
### 💡 الحالة 3: الربط مع REST API خارجي بالسيرفر (Server-Side Pagination & Search)
|
|
793
|
+
عند تمرير `api.fetcher`، يتولى الجدول إرسال المتغيرات `{ page, pageSize, search, sortBy, sortOrder }` تلقائياً مع فلترة البحث (Debounce) لمنع تكرار الطلبات:
|
|
794
|
+
```tsx
|
|
795
|
+
import axios from "axios";
|
|
796
|
+
|
|
797
|
+
<AnyTable
|
|
798
|
+
title="المستخدمين من السيرفر"
|
|
799
|
+
rowKey="id"
|
|
800
|
+
api={{
|
|
801
|
+
fetcher: async ({ page, pageSize, search, sortBy, sortOrder }) => {
|
|
802
|
+
const response = await axios.get("/api/v1/users", {
|
|
803
|
+
params: {
|
|
804
|
+
page,
|
|
805
|
+
limit: pageSize,
|
|
806
|
+
search,
|
|
807
|
+
sortBy,
|
|
808
|
+
sortOrder,
|
|
809
|
+
},
|
|
810
|
+
});
|
|
811
|
+
return response.data; // e.g. { data: [...], meta: { total: 100 } }
|
|
812
|
+
},
|
|
813
|
+
}}
|
|
814
|
+
/>
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
---
|
|
818
|
+
|
|
819
|
+
### 💡 الحالة 4: التعامل مع ردود الـ API غير القياسية (3-Tier Normalizer)
|
|
820
|
+
إذا كان الباك إند يرجع بيانات بهيكل مخصص (مثل `{ payload: { records: [...], recordCount: 150 } }`):
|
|
821
|
+
```tsx
|
|
822
|
+
<AnyTable
|
|
823
|
+
api={{
|
|
824
|
+
fetcher: getCustomBackendData,
|
|
825
|
+
response: {
|
|
826
|
+
dataPath: "payload.records", // مسار مصفوفة البيانات
|
|
827
|
+
totalPath: "payload.recordCount", // مسار إجمالي السجلات للترقيم
|
|
828
|
+
pagePath: "payload.currentPage", // مسار رقم الصفحة الحالية
|
|
829
|
+
},
|
|
830
|
+
}}
|
|
831
|
+
/>
|
|
832
|
+
```
|
|
833
|
+
|
|
834
|
+
---
|
|
835
|
+
|
|
836
|
+
### 💡 الحالة 5: مفاتيح الـ PATCH الفورية وأزرار العمليات (Actions & Switches)
|
|
837
|
+
تعديل حالة السجل مباشرة بمفتاح Toggle دون مغادرة الجدول مع التحديث الفوري:
|
|
838
|
+
```tsx
|
|
839
|
+
actions={[
|
|
840
|
+
// 1. مفتاح تبديل يرسل طلب PATCH للباك إند ويحدث الجدول فوراً
|
|
841
|
+
{
|
|
842
|
+
id: "active-switch",
|
|
843
|
+
type: "switch",
|
|
844
|
+
label: "تفعيل",
|
|
845
|
+
checked: (row) => row.isActive,
|
|
846
|
+
onChange: async (row, nextState, context) => {
|
|
847
|
+
await axios.patch(`/api/users/${row.id}`, { isActive: nextState });
|
|
848
|
+
context.refresh(); // يعيد جلب البيانات بسلاسة
|
|
849
|
+
},
|
|
850
|
+
},
|
|
851
|
+
// 2. زر عرض التفاصيل
|
|
852
|
+
{
|
|
853
|
+
id: "view",
|
|
854
|
+
label: "عرض",
|
|
855
|
+
variant: "primary",
|
|
856
|
+
onClick: (row) => router.push(`/users/${row.id}`),
|
|
857
|
+
},
|
|
858
|
+
]}
|
|
859
|
+
```
|
|
860
|
+
|
|
861
|
+
---
|
|
862
|
+
|
|
863
|
+
### 💡 الحالة 6: نوافذ التأكيد الذكية لعمليات الحذف (Confirmation Dialogs)
|
|
864
|
+
نافذة تأكيد مدمجة تنبثق قبل تنفيذ الإجراء:
|
|
865
|
+
```tsx
|
|
866
|
+
actions={[
|
|
867
|
+
{
|
|
868
|
+
id: "delete-btn",
|
|
869
|
+
label: "حذف",
|
|
870
|
+
variant: "danger",
|
|
871
|
+
confirmation: {
|
|
872
|
+
title: "تأكيد حذف الحساب",
|
|
873
|
+
message: (row) => `هل أنت متأكد من رغبتك في حذف "${row.name}" نهائياً؟`,
|
|
874
|
+
confirmText: "نعم، احذف",
|
|
875
|
+
cancelText: "إلغاء",
|
|
876
|
+
},
|
|
877
|
+
onClick: async (row, context) => {
|
|
878
|
+
await axios.delete(`/api/users/${row.id}`);
|
|
879
|
+
context.refresh();
|
|
880
|
+
},
|
|
881
|
+
},
|
|
882
|
+
]}
|
|
883
|
+
```
|
|
884
|
+
|
|
885
|
+
---
|
|
886
|
+
|
|
887
|
+
### 💡 الحالة 7: التحكم البرمجي عبر الـ Ref (`tableRef`)
|
|
888
|
+
للتحكم في الجدول من أزرار خارجية في صفحتك:
|
|
889
|
+
```tsx
|
|
890
|
+
import { useRef } from "react";
|
|
891
|
+
import { AnyTable, TableInstance } from "@kareemelbalshe/any-table";
|
|
892
|
+
|
|
893
|
+
export default function AdminPage() {
|
|
894
|
+
const tableRef = useRef<TableInstance>(null);
|
|
895
|
+
|
|
896
|
+
return (
|
|
897
|
+
<div>
|
|
898
|
+
<div className="flex gap-2 mb-4">
|
|
899
|
+
<button onClick={() => tableRef.current?.refresh()}>🔄 تحديث البيانات</button>
|
|
900
|
+
<button onClick={() => tableRef.current?.setPage(1)}>⏮️ الصفحة الأولى</button>
|
|
901
|
+
<button onClick={() => tableRef.current?.setSearch("القاهرة")}>🔍 بحث عن القاهرة</button>
|
|
902
|
+
<button onClick={() => tableRef.current?.reset()}>⚡ إعادة ضبط الجدول</button>
|
|
903
|
+
</div>
|
|
904
|
+
|
|
905
|
+
<AnyTable tableRef={tableRef} api={{ fetcher: fetchUsers }} />
|
|
906
|
+
</div>
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
```
|
|
910
|
+
|
|
911
|
+
---
|
|
912
|
+
|
|
913
|
+
### 💡 الحالة 8: التحديد المتعدد والعمليات الجماعية (Batch Operations)
|
|
914
|
+
```tsx
|
|
915
|
+
export default function SelectionPage() {
|
|
916
|
+
const [selectedUsers, setSelectedUsers] = useState([]);
|
|
917
|
+
|
|
918
|
+
return (
|
|
919
|
+
<div>
|
|
920
|
+
{selectedUsers.length > 0 && (
|
|
921
|
+
<button onClick={() => handleBulkDelete(selectedUsers.map(u => u.id))}>
|
|
922
|
+
🗑️ حذف {selectedUsers.length} مستخدمين محددين
|
|
923
|
+
</button>
|
|
924
|
+
)}
|
|
925
|
+
|
|
926
|
+
<AnyTable
|
|
927
|
+
data={users}
|
|
928
|
+
selectable
|
|
929
|
+
onSelectionChange={(selectedRows, selectedKeys) => {
|
|
930
|
+
setSelectedUsers(selectedRows);
|
|
931
|
+
}}
|
|
932
|
+
/>
|
|
933
|
+
</div>
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
---
|
|
939
|
+
|
|
940
|
+
### 💡 الحالة 9: التعامل مع أخطاء الشبكة وزر إعادة المحاولة التلقائي (Error Handling)
|
|
941
|
+
عند انقطاع الاتصال أو إرجاع خطأ 500، يظهر الجدول شاشة خطأ منسقة مع زر **"🔄 Retry Request"** التلقائي:
|
|
942
|
+
```tsx
|
|
943
|
+
<AnyTable
|
|
944
|
+
api={{ fetcher: fetchUsersApi }}
|
|
945
|
+
// اختياري: تخصيص واجهة الخطأ وزر الإعادة بالكامل
|
|
946
|
+
errorComponent={(error, retry) => (
|
|
947
|
+
<div className="p-6 text-center text-red-500">
|
|
948
|
+
<p>حدث خطأ: {error.message}</p>
|
|
949
|
+
<button onClick={retry}>إعادة المحاولة</button>
|
|
950
|
+
</div>
|
|
951
|
+
)}
|
|
952
|
+
/>
|
|
953
|
+
```
|
|
954
|
+
|
|
955
|
+
---
|
|
956
|
+
|
|
957
|
+
### 💡 الحالة 10: تخصيص الألوان والثيم والوضع الليلي (Theming & Dark Mode)
|
|
958
|
+
```tsx
|
|
959
|
+
<AnyTable
|
|
960
|
+
theme={{
|
|
961
|
+
colors: {
|
|
962
|
+
primary: "#2667EC", // اللون الأساسي
|
|
963
|
+
borderRadius: "0.75rem", // انحناء الحواف
|
|
964
|
+
},
|
|
965
|
+
}}
|
|
966
|
+
/>
|
|
967
|
+
```
|
|
968
|
+
|
|
969
|
+
---
|
|
970
|
+
|
|
971
|
+
### 💡 الحالة 11: التوافق الكامل مع Next.js (App Router)
|
|
972
|
+
في مسار `app/users/page.tsx` داخل Next.js 13/14/15، أضف `'use client'` في أعلى الملف:
|
|
973
|
+
```tsx
|
|
974
|
+
"use client";
|
|
975
|
+
|
|
976
|
+
import { AnyTable } from "@kareemelbalshe/any-table";
|
|
977
|
+
import "@kareemelbalshe/any-table/style.css";
|
|
978
|
+
|
|
979
|
+
export default function UsersPage() {
|
|
980
|
+
return (
|
|
981
|
+
<main className="p-8">
|
|
982
|
+
<AnyTable
|
|
983
|
+
title="مستخدمي تطبيق Next.js"
|
|
984
|
+
api={{
|
|
985
|
+
fetcher: (params) => fetch(`/api/users?${new URLSearchParams(params as any)}`).then(r => r.json()),
|
|
986
|
+
}}
|
|
987
|
+
/>
|
|
988
|
+
</main>
|
|
989
|
+
);
|
|
990
|
+
}
|
|
991
|
+
```
|
|
992
|
+
|
|
993
|
+
---
|
|
994
|
+
|
|
995
|
+
## 📄 License
|
|
996
|
+
|
|
997
|
+
Distributed under the **MIT License**. Created with ❤️ by [Kareem Elbalshe](https://github.com/kareemelbalshe).
|
|
998
|
+
|