-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo-async.html
More file actions
405 lines (346 loc) · 13.5 KB
/
demo-async.html
File metadata and controls
405 lines (346 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTMLTableKit Async Demo</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
h1, h2 {
color: #333;
}
.demo-section {
background: white;
padding: 20px;
margin-bottom: 30px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px;
}
button:hover {
background-color: #45a049;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.loading {
display: inline-block;
margin-left: 10px;
color: #666;
}
.error {
color: #f44336;
margin-top: 10px;
}
.success {
color: #4CAF50;
margin-top: 10px;
}
input[type="text"], input[type="number"] {
padding: 8px;
margin: 5px;
border: 1px solid #ddd;
border-radius: 4px;
}
.api-simulator {
background-color: #e3f2fd;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
pre {
background-color: #f5f5f5;
padding: 10px;
border-radius: 3px;
overflow-x: auto;
}
</style>
</head>
<body>
<h1>HTMLTableKit Async Demo</h1>
<div class="api-simulator">
<h3>🔧 API Simulator</h3>
<p>This demo simulates API calls with a 1-second delay to demonstrate async functionality.</p>
<label>
<input type="checkbox" id="simulateError" /> Simulate API errors
</label>
</div>
<div class="demo-section">
<h2>Products Table with Async Operations</h2>
<table id="productsTable">
<thead>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
<th>Stock</th>
</tr>
</thead>
<tbody>
<tr data-id="prod_1">
<td>prod_1</td>
<td>Laptop</td>
<td>999.99</td>
<td>15</td>
</tr>
<tr data-id="prod_2">
<td>prod_2</td>
<td>Mouse</td>
<td>29.99</td>
<td>50</td>
</tr>
</tbody>
</table>
<h3>Add Product (with API call)</h3>
<input type="text" id="newProduct" placeholder="Product Name">
<input type="number" id="newPrice" placeholder="Price" step="0.01">
<input type="number" id="newStock" placeholder="Stock">
<button id="addProductBtn" onclick="addProductAsync()">Add Product</button>
<span id="addLoading" class="loading" style="display:none;">Adding to database...</span>
<h3>Update Product Price (with API call)</h3>
<input type="text" id="updateId" placeholder="Product ID">
<input type="number" id="updatePrice" placeholder="New Price" step="0.01">
<button id="updateProductBtn" onclick="updateProductAsync()">Update Price</button>
<span id="updateLoading" class="loading" style="display:none;">Updating database...</span>
<h3>Delete Product (with API call)</h3>
<input type="text" id="deleteId" placeholder="Product ID">
<button id="deleteProductBtn" onclick="deleteProductAsync()">Delete Product</button>
<span id="deleteLoading" class="loading" style="display:none;">Deleting from database...</span>
<div id="message"></div>
</div>
<div class="demo-section">
<h2>Code Example</h2>
<pre><code>// Async add with API call
const newProduct = await tableKit.addRowAsync(
{ product: name, price: price, stock: stock },
async (row) => {
// Make API call
const response = await fetch('/api/products', {
method: 'POST',
body: JSON.stringify(row)
});
if (!response.ok) {
return null; // Cancel operation
}
const savedProduct = await response.json();
return savedProduct; // Return updated data from server
}
);
// Async update with validation
const success = await tableKit.updateRowAsync(
productId,
{ price: newPrice },
async (row, updates) => {
// Validate on server
const response = await fetch(`/api/products/${row.id}/validate-price`, {
method: 'POST',
body: JSON.stringify({ price: updates.price })
});
if (!response.ok) {
return null; // Cancel if validation fails
}
return updates; // Proceed with update
}
);
// Async delete with confirmation
const deleted = await tableKit.deleteRowAsync(
productId,
async (row) => {
// Delete from server
const response = await fetch(`/api/products/${row.id}`, {
method: 'DELETE'
});
return response.ok; // Only delete locally if server deletion succeeds
}
);</code></pre>
</div>
<script src="dist/HTMLTableKit.standalone.js"></script>
<script>
// Initialize table
const tableKit = new HTMLTableKit('productsTable');
let productIdCounter = 3;
// Simulate API call with delay
function simulateApiCall(success = true, delay = 1000) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (success && !document.getElementById('simulateError').checked) {
resolve({ success: true });
} else {
reject(new Error('API Error: Operation failed'));
}
}, delay);
});
}
function showMessage(message, isError = false) {
const messageEl = document.getElementById('message');
messageEl.textContent = message;
messageEl.className = isError ? 'error' : 'success';
setTimeout(() => {
messageEl.textContent = '';
}, 3000);
}
async function addProductAsync() {
const name = document.getElementById('newProduct').value;
const price = document.getElementById('newPrice').value;
const stock = document.getElementById('newStock').value;
if (!name || !price || !stock) {
showMessage('Please fill all fields', true);
return;
}
const btn = document.getElementById('addProductBtn');
const loading = document.getElementById('addLoading');
btn.disabled = true;
loading.style.display = 'inline';
try {
const newProduct = await tableKit.addRowAsync(
{
id: `prod_${productIdCounter}`,
product: name,
price: parseFloat(price),
stock: parseInt(stock)
},
async (row) => {
// Simulate API call to save product
console.log('Sending to API:', row);
await simulateApiCall();
// Simulate server returning the saved product with server-generated ID
const serverProduct = {
...row,
id: `prod_${productIdCounter++}`
};
console.log('Received from API:', serverProduct);
return serverProduct;
}
);
if (newProduct) {
showMessage(`Product "${name}" added successfully!`);
// Clear form
document.getElementById('newProduct').value = '';
document.getElementById('newPrice').value = '';
document.getElementById('newStock').value = '';
}
} catch (error) {
showMessage(`Failed to add product: ${error.message}`, true);
console.error('Add error:', error);
} finally {
btn.disabled = false;
loading.style.display = 'none';
}
}
async function updateProductAsync() {
const id = document.getElementById('updateId').value;
const price = document.getElementById('updatePrice').value;
if (!id || !price) {
showMessage('Please provide product ID and new price', true);
return;
}
const btn = document.getElementById('updateProductBtn');
const loading = document.getElementById('updateLoading');
btn.disabled = true;
loading.style.display = 'inline';
try {
const success = await tableKit.updateRowAsync(
id,
{ price: parseFloat(price) },
async (row, updates) => {
// Simulate API call to validate and update
console.log('Validating price update:', { row, updates });
// Simulate price validation
if (updates.price < 0) {
throw new Error('Price cannot be negative');
}
await simulateApiCall();
console.log('Price update approved by server');
return updates;
}
);
if (success) {
showMessage(`Product ${id} price updated successfully!`);
document.getElementById('updateId').value = '';
document.getElementById('updatePrice').value = '';
} else {
showMessage('Product not found', true);
}
} catch (error) {
showMessage(`Failed to update product: ${error.message}`, true);
console.error('Update error:', error);
} finally {
btn.disabled = false;
loading.style.display = 'none';
}
}
async function deleteProductAsync() {
const id = document.getElementById('deleteId').value;
if (!id) {
showMessage('Please provide product ID', true);
return;
}
const btn = document.getElementById('deleteProductBtn');
const loading = document.getElementById('deleteLoading');
btn.disabled = true;
loading.style.display = 'inline';
try {
const success = await tableKit.deleteRowAsync(
id,
async (row) => {
// Simulate API call to delete
console.log('Deleting from server:', row);
if (!confirm(`Are you sure you want to delete "${row.product}"?`)) {
return false; // Cancel deletion
}
await simulateApiCall();
console.log('Product deleted from server');
return true; // Proceed with local deletion
}
);
if (success) {
showMessage(`Product ${id} deleted successfully!`);
document.getElementById('deleteId').value = '';
} else {
showMessage('Product not found or deletion cancelled', true);
}
} catch (error) {
showMessage(`Failed to delete product: ${error.message}`, true);
console.error('Delete error:', error);
} finally {
btn.disabled = false;
loading.style.display = 'none';
}
}
// Log initial state
console.log('Initial table data:', tableKit.getTable());
</script>
</body>
</html>