-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathftable.js
More file actions
5623 lines (4798 loc) · 198 KB
/
ftable.js
File metadata and controls
5623 lines (4798 loc) · 198 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global) {
const FTABLE_DEFAULT_MESSAGES = {
serverCommunicationError: 'An error occurred while communicating to the server.',
loadingMessage: 'Loading records...',
noDataAvailable: 'No data available!',
addNewRecord: 'Add new record',
editRecord: 'Edit record',
areYouSure: 'Are you sure?',
deleteConfirmation: 'This record will be deleted. Are you sure?',
yes: 'Yes',
no: 'No',
save: 'Save',
saving: 'Saving',
cancel: 'Cancel',
deleteText: 'Delete',
deleting: 'Deleting',
error: 'An error has occured',
warning: 'Warning',
close: 'Close',
cannotLoadOptionsFor: 'Cannot load options for field {0}!',
pagingInfo: 'Showing {0}-{1} of {2}',
canNotDeletedRecords: 'Can not delete {0} of {1} records!',
deleteProgress: 'Deleting {0} of {1} records, processing...',
pageSizeChangeLabel: 'Row count',
gotoPageLabel: 'Go to page',
sortingInfoPrefix: 'Sorting applied: ',
sortingInfoSuffix: '', // optional
ascending: 'Ascending',
descending: 'Descending',
sortingInfoNone: 'No sorting applied',
resetSorting: 'Reset sorting',
csvExport: 'CSV',
printTable: '🖨️ Print',
cloneRecord: 'Clone Record',
resetTable: 'Reset table',
resetTableConfirm: 'This will reset column visibility, column widths and page size to their defaults. Do you want to continue?',
resetTableTooltip: 'Resets column visibility, column widths and page size to defaults. Sorting is not affected.',
resetSearch: 'Reset'
};
class FTableOptionsCache {
constructor() {
this.cache = new Map();
this.pendingRequests = new Map(); // Track ongoing requests
}
generateKey(url, params) {
const sortedParams = Object.keys(params || {})
.sort()
.map(key => `${key}=${params[key]}`)
.join('&');
return `${url}?${sortedParams}`;
}
get(url, params) {
const key = this.generateKey(url, params);
return this.cache.get(key);
}
set(url, params, data) {
const key = this.generateKey(url, params);
this.cache.set(key, data);
}
clear(url = null, params = null) {
if (url) {
if (params) {
const key = this.generateKey(url, params);
this.cache.delete(key);
} else {
// Clear all entries that start with this URL
const urlPrefix = url.split('?')[0];
for (const [key] of this.cache) {
if (key.startsWith(urlPrefix)) {
this.cache.delete(key);
}
}
}
} else {
this.cache.clear();
}
}
async getOrCreate(url, params, fetchFn) {
const key = this.generateKey(url, params);
// Return cached result if available
const cached = this.cache.get(key);
if (cached) return cached;
// Check if same request is already in progress
if (this.pendingRequests.has(key)) {
// Wait for the existing request to complete
return await this.pendingRequests.get(key);
}
// Create new request
const requestPromise = (async () => {
try {
const result = await fetchFn();
this.cache.set(key, result);
return result;
} finally {
// Clean up pending request tracking
this.pendingRequests.delete(key);
}
})();
// Track this request
this.pendingRequests.set(key, requestPromise);
return await requestPromise;
}
size() {
return this.cache.size;
}
}
class FTableEventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
return this;
}
once(event, callback) {
// Create a wrapper that removes itself after first call
const wrapper = (...args) => {
this.off(event, wrapper);
callback.apply(this, args);
};
// Store reference to wrapper so it can be removed
wrapper.fn = callback; // for off() to match
this.on(event, wrapper);
return this;
}
emit(event, data = {}) {
if (this.events[event]) {
this.events[event].forEach(callback => callback(data));
}
return this;
}
off(event, callback) {
if (this.events[event]) {
this.events[event] = this.events[event].filter(cb => cb !== callback);
}
return this;
}
}
class FTableLogger {
static LOG_LEVELS = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
NONE: 4
};
constructor(level = FTableLogger.LOG_LEVELS.WARN) {
this.level = level;
}
log(level, message) {
if (!window.console || level < this.level) return;
const levelName = Object.keys(FTableLogger.LOG_LEVELS)
.find(key => FTableLogger.LOG_LEVELS[key] === level);
//console.trace();
console.log(`fTable ${levelName}: ${message}`);
}
debug(message) { this.log(FTableLogger.LOG_LEVELS.DEBUG, message); }
info(message) { this.log(FTableLogger.LOG_LEVELS.INFO, message); }
warn(message) { this.log(FTableLogger.LOG_LEVELS.WARN, message); }
error(message) { this.log(FTableLogger.LOG_LEVELS.ERROR, message); }
}
class FTableDOMHelper {
static PROPERTY_ATTRIBUTES = new Set([
'value', 'checked', 'selected', 'disabled', 'readOnly',
'name', 'id', 'type', 'placeholder', 'min', 'max',
'step', 'required', 'multiple', 'accept', 'className',
'textContent', 'innerHTML', 'title'
]);
static create(tag, options = {}) {
const element = document.createElement(tag);
// Handle special cases first
if (options.style !== undefined) {
element.style.cssText = options.style;
}
FTableDOMHelper.PROPERTY_ATTRIBUTES.forEach(prop => {
if (prop in options && options[prop] !== null) {
element[prop] = options[prop];
}
});
if (options.parent !== undefined) {
options.parent.appendChild(element);
}
// the attributes last, so we can override stuff if needed
if (options.attributes) {
Object.entries(options.attributes).forEach(([key, value]) => {
if (value !== null) {
// Use property if it exists on the element, otherwise use setAttribute
if (FTableDOMHelper.PROPERTY_ATTRIBUTES.has(key)) {
element[key] = value;
} else {
element.setAttribute(key, value);
}
}
});
}
return element;
}
static find(selector, parent = document) {
return parent.querySelector(selector);
}
static findAll(selector, parent = document) {
return Array.from(parent.querySelectorAll(selector));
}
static addClass(element, className) {
element.classList.add(...className.split(' '));
}
static removeClass(element, className) {
element.classList.remove(...className.split(' '));
}
static toggleClass(element, className) {
element.classList.toggle(className);
}
static show(element) {
element.style.display = '';
}
static hide(element) {
element.style.display = 'none';
}
static escapeHtml(text) {
if (!text) return text;
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, m => map[m]);
}
}
class FTableHttpClient {
static async request(url, options = {}) {
const defaults = {
method: 'GET',
headers: {}
};
const config = { ...defaults, ...options };
// Merge headers properly
if (options.headers) {
config.headers = { ...defaults.headers, ...options.headers };
}
try {
const response = await fetch(url, config);
if (response.status === 401) {
throw new Error('Unauthorized');
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Try to parse as JSON, fallback to text
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return await response.json();
} else {
const text = await response.text();
try {
return JSON.parse(text);
} catch {
return { Result: 'OK', Message: text };
}
}
} catch (error) {
throw error;
}
}
static async get(url, params = {}) {
// Handle relative URLs by using the current page's base
let fullUrl = new URL(url, window.location.href);
Object.entries(params).forEach(([key, value]) => {
if (value === null || value === undefined) {
return; // Skip null or undefined values
}
if (Array.isArray(value)) {
const keyName = key.endsWith('[]') ? key : key + '[]';
// Append each item in the array with the same key
// This generates query strings like `key=val1&key=val2&key=val3`
value.forEach(item => {
if (item !== null && item !== undefined) { // Ensure array items are also not null/undefined
fullUrl.searchParams.append(keyName, item);
}
});
} else {
// Append single values normally
fullUrl.searchParams.append(key, value);
}
});
return this.request(fullUrl.toString(), {
method: 'GET',
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
});
}
static async post(url, data = {}) {
// Handle relative URLs
let fullUrl = new URL(url, window.location.href);
let formData = new FormData();
Object.entries(data).forEach(([key, value]) => {
if (value === null || value === undefined) {
return; // Skip null or undefined values
}
if (Array.isArray(value)) {
const keyName = key.endsWith('[]') ? key : key + '[]';
// Append each item in the array with the same key
// This generates query strings like `key=val1&key=val2&key=val3`
value.forEach(item => {
if (item !== null && item !== undefined) { // Ensure array items are also not null/undefined
formData.append(keyName, item);
}
});
} else {
// Append single values normally
formData.append(key, value);
}
});
return this.request(fullUrl.toString(), {
method: 'POST',
body: formData
});
}
}
class FTableUserPreferences {
constructor(prefix, method = 'localStorage') {
this.prefix = prefix;
this.method = method;
}
set(key, value) {
const fullKey = `${this.prefix}${key}`;
if (this.method === 'localStorage') {
localStorage.setItem(fullKey, value);
} else {
// Cookie fallback
const expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 30);
document.cookie = `${fullKey}=${value}; expires=${expireDate.toUTCString()}; path=/`;
}
}
get(key) {
const fullKey = `${this.prefix}${key}`;
if (this.method === 'localStorage') {
return localStorage.getItem(fullKey);
} else {
// Cookie fallback
const name = fullKey + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const ca = decodedCookie.split(';');
for (let c of ca) {
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return null;
}
}
remove(key) {
const fullKey = `${this.prefix}${key}`;
if (this.method === 'localStorage') {
localStorage.removeItem(fullKey);
} else {
document.cookie = `${fullKey}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
}
generatePrefix(tableId, fieldNames) {
const simpleHash = (value) => {
let hash = 0;
if (value.length === 0) return hash;
for (let i = 0; i < value.length; i++) {
const ch = value.charCodeAt(i);
hash = ((hash << 5) - hash) + ch;
hash = hash & hash;
}
return hash;
};
let strToHash = tableId ? `${tableId}#` : '';
strToHash += fieldNames.join('$') + '#c' + fieldNames.length;
return `ftable#${simpleHash(strToHash)}`;
}
}
class FtableModal {
constructor(options = {}) {
this.options = {
title: 'Modal',
content: '',
buttons: [],
className: 'ftable-modal',
parent: document.body,
...options
};
this.overlay = null;
this.modal = null;
this.isOpen = false;
}
create() {
// Create overlay
this.overlay = FTableDOMHelper.create('div', {
className: 'ftable-modal-overlay',
parent: this.options.parent
});
// Create modal
this.modal = FTableDOMHelper.create('div', {
className: `ftable-modal ${this.options.className}`,
parent: this.overlay
});
// Header
const header = FTableDOMHelper.create('h2', {
className: 'ftable-modal-header',
textContent: this.options.title,
parent: this.modal
});
// Close button
const closeBtn = FTableDOMHelper.create('span', {
className: 'ftable-modal-close',
innerHTML: '×',
parent: this.modal
});
closeBtn.addEventListener('click', () => this.close());
// Body
const body = FTableDOMHelper.create('div', {
className: 'ftable-modal-body',
parent: this.modal
});
if (typeof this.options.content === 'string') {
body.innerHTML = this.options.content;
} else {
body.appendChild(this.options.content);
}
// Footer with buttons
if (this.options.buttons.length > 0) {
const footer = FTableDOMHelper.create('div', {
className: 'ftable-modal-footer',
parent: this.modal
});
this.options.buttons.forEach(button => {
const btn = FTableDOMHelper.create('button', {
className: `ftable-dialog-button ${button.className || ''}`,
innerHTML: `<span>${button.text}</span>`,
parent: footer
});
if (button.onClick) {
// Store original handler
btn._originalOnClick = button.onClick;
// Attach wrapped handler
btn.addEventListener('click', this._createWrappedClickHandler(btn));
}
});
}
// Close on overlay click
if (this.options.closeOnOverlayClick) {
this.overlay.addEventListener('click', (e) => {
if (e.target === this.overlay) {
this.close();
}
});
}
this.hide();
return this;
}
show() {
if (!this.modal) this.create();
this.overlay.style.display = 'flex';
this.isOpen = true;
// Enable all ftable-dialog-button buttons
const buttons = this.modal.querySelectorAll('.ftable-dialog-button');
buttons.forEach(btn => {
btn.disabled = false;
});
return this;
}
hide() {
if (this.overlay) {
this.overlay.style.display = 'none';
}
this.isOpen = false;
return this;
}
close() {
this.hide();
if (this.options.onClose) {
this.options.onClose();
}
return this;
}
destroy() {
if (this.overlay) {
this.overlay.remove();
}
this.isOpen = false;
return this;
}
setContent(content) {
this.options.content = content;
const body = this.modal.querySelector('.ftable-modal-body');
if (!body) return;
// Clear old content
body.innerHTML = '';
if (typeof content === 'string') {
body.innerHTML = /<(div|ul|ol|table|p|h[1-6]|blockquote)/i.test(content)
? content
: `<p>${content}</p>`;
} else {
body.appendChild(content);
}
}
_createWrappedClickHandler(buttonElement) {
return async (event) => {
// Disable immediately
buttonElement.disabled = true;
try {
const handler = buttonElement._originalOnClick;
if (typeof handler === 'function') {
const result = handler.call(buttonElement, event);
if (result instanceof Promise) {
await result;
}
}
} catch (error) {
console.error('Modal button action failed:', error);
} finally {
// Re-enable regardless of outcome
buttonElement.disabled = false;
}
};
}
}
class FTableFormBuilder {
constructor(options) {
this.options = options;
this.dependencies = new Map(); // Track field dependencies
this.optionsCache = new FTableOptionsCache();
}
// Get options for a field, respecting context ('search' prefers searchOptions over options).
// URL-level caching and concurrent-request deduplication is handled by FTableOptionsCache
// inside resolveOptions
async getFieldOptions(fieldName, context = 'table', params = {}) {
const field = this.options.fields[fieldName];
// For search context, prefer searchOptions and fall back to options
const optionsSource = (context === 'search')
? (field.searchOptions ?? field.options)
: field.options;
if (!optionsSource) return null;
const noCache = this.shouldSkipCache(field, context, params);
try {
return await this.resolveOptions(
{ ...field, options: optionsSource },
params,
context,
noCache
);
} catch (err) {
console.error(`Failed to resolve options for ${fieldName} (${context}):`, err);
return optionsSource;
}
}
// Determine whether to bypass the URL cache for this field/context
shouldSkipCache(field, context, params) {
if (params.forceRefresh) return true;
if (!field.noCache) return false;
if (typeof field.noCache === 'boolean') return field.noCache;
if (typeof field.noCache === 'function') return field.noCache({ context, ...params });
if (typeof field.noCache === 'object') return field.noCache[context] === true;
return false;
}
shouldIncludeField(field, formType) {
if (formType === 'create') {
return field.create !== false && !(field.key === true && field.create !== true);
} else if (formType === 'edit') {
return field.edit !== false;
}
return true;
}
createFieldContainer(fieldName, field, record, formType) {
// in this function, field.options already contains the resolved values
const container = FTableDOMHelper.create('div', {
className: (field.type != 'hidden' ? 'ftable-input-field-container' : ''),
attributes: {
id: `ftable-input-field-container-div-${fieldName}`,
}
});
if (field.type != 'hidden') {
// Label
const label = FTableDOMHelper.create('div', {
className: 'ftable-input-label',
textContent: field.inputTitle || field.title,
parent: container
});
}
// Input
const inputContainer = this.createInput(fieldName, field, record[fieldName], formType);
container.appendChild(inputContainer);
return container;
}
async createForm(formType = 'create', record = {}) {
this.currentFormRecord = record;
const form = FTableDOMHelper.create('form', {
className: `ftable-dialog-form ftable-${formType}-form`
});
// Build dependency map first
this.buildDependencyMap();
// Create form fields using for...of instead of forEach, this allows the await to work
for (const [fieldName, field] of Object.entries(this.options.fields)) {
if (this.shouldIncludeField(field, formType)) {
let fieldWithOptions = { ...field };
if (!field.dependsOn) {
const contextOptions = await this.getFieldOptions(fieldName, formType, {
record,
source: formType
});
fieldWithOptions.options = contextOptions;
} else {
// For dependent fields, use placeholder or original options
// They will be resolved when dependencies change
fieldWithOptions.options = field.options;
}
const fieldContainer = this.createFieldContainer(fieldName, fieldWithOptions, record, formType);
form.appendChild(fieldContainer);
}
}
// Set up dependency listeners after all fields are created
this.setupDependencyListeners(form);
return form;
}
buildDependencyMap() {
this.dependencies.clear();
Object.entries(this.options.fields).forEach(([fieldName, field]) => {
if (field.dependsOn) {
// Normalize dependsOn to array
let dependsOnFields;
if (typeof field.dependsOn === 'string') {
// Handle CSV: 'field1, field2' → ['field1', 'field2']
dependsOnFields = field.dependsOn
.split(',')
.map(name => name.trim())
.filter(name => name);
} else {
return; // Invalid type
}
// Register this field as dependent on each master
dependsOnFields.forEach(dependsOnField => {
if (!this.dependencies.has(dependsOnField)) {
this.dependencies.set(dependsOnField, []);
}
this.dependencies.get(dependsOnField).push(fieldName);
});
}
});
}
setupDependencyListeners(form) {
// Collect all master fields (any field that is depended on)
const masterFieldNames = Array.from(this.dependencies.keys());
masterFieldNames.forEach(masterFieldName => {
const masterInput = form.querySelector(`[name="${masterFieldName}"]`);
if (!masterInput) return;
// Listen for changes
masterInput.addEventListener('change', () => {
// Re-evaluate dependent fields (they’ll check their own dependsOn)
this.handleDependencyChange(form, masterFieldName);
});
});
// Trigger initial update
this.handleDependencyChange(form);
}
async resolveOptions(field, params = {}, source = '', noCache = false) {
if (!field.options) return [];
// Case 1: Direct options (array or object)
if (Array.isArray(field.options) || typeof field.options === 'object') {
return field.options;
}
let result;
// Enhance params with clearCache() method
const enhancedParams = {
...params,
source: source,
clearCache: () => {
noCache = true;
// Also update the field's noCache setting for future calls
this.updateFieldCacheSetting(field, source, true);
}
};
if (typeof field.options === 'function') {
result = await field.options(enhancedParams);
//result = await field.options(params); // Can return string or { url, noCache }
} else if (typeof field.options === 'string') {
result = field.options;
} else {
return [];
}
// --- Handle result ---
const isObjectResult = result && typeof result === 'object' && result.url;
const url = isObjectResult ? result.url : result;
noCache = isObjectResult && result.noCache !== undefined ? result.noCache : noCache;
if (typeof url !== 'string') return [];
// Only use cache if noCache is NOT set
if (noCache) {
try {
const response = this.options.forcePost
? await FTableHttpClient.post(url)
: await FTableHttpClient.get(url);
return response.Options || response.options || response || [];
} catch (error) {
console.error(`Failed to load options from ${url}:`, error);
return [];
}
} else {
// Use getOrCreate to prevent duplicate requests
return await this.optionsCache.getOrCreate(url, {}, async () => {
try {
const response = this.options.forcePost
? await FTableHttpClient.post(url)
: await FTableHttpClient.get(url);
return response.Options || response.options || response || [];
} catch (error) {
console.error(`Failed to load options from ${url}:`, error);
return [];
}
});
}
}
updateFieldCacheSetting(field, context, skipCache) {
if (!field.noCache) {
// Initialize noCache as object for this context
field.noCache = { [context]: skipCache };
} else if (typeof field.noCache === 'boolean') {
// Convert boolean to object, preserving existing behavior for other contexts
field.noCache = {
'table': field.noCache,
'create': field.noCache,
'edit': field.noCache,
[context]: skipCache // Override for this context
};
} else if (typeof field.noCache === 'object') {
// Update specific context
field.noCache[context] = skipCache;
}
// Function-based noCache remains unchanged (runtime decision)
}
clearOptionsCache(url = null, params = null) {
this.optionsCache.clear(url, params);
}
getFormValues(form) {
const values = {};
// Get all form elements
const elements = form.elements;
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
const name = element.name;
if (!name || element.disabled) continue;
switch (element.type) {
case 'checkbox':
values[name] = element.checked ? element.value || '1' : '0';
break;
case 'radio':
if (element.checked) {
values[name] = element.value;
}
break;
case 'select-multiple':
values[name] = Array.from(element.selectedOptions).map(option => option.value);
break;
default:
values[name] = element.value;
break;
}
}
return values;
}
async handleDependencyChange(form, changedFieldname = '') {
// Build dependedValues: { field1: value1, field2: value2 }
const dependedValues = this.getFormValues(form);
const formType = form.classList.contains('ftable-create-form') ? 'create' : 'edit';
const record = this.currentFormRecord || {};
const baseParams = {
record,
source: formType,
form,
dependedValues
};
for (const [fieldName, field] of Object.entries(this.options.fields)) {
if (!field.dependsOn) continue;
if (changedFieldname !== '') {
let dependsOnFields = field.dependsOn
.split(',')
.map(name => name.trim())
.filter(name => name);
if (!dependsOnFields.includes(changedFieldname)) {
continue;
}
}
const input = form.querySelector(`[name="${fieldName}"]`);
if (!input || !this.shouldIncludeField(field, formType)) continue;
try {
// Clear current options
if (input.tagName === 'SELECT') {
input.innerHTML = '<option value="">Loading...</option>';
} else if (input.tagName === 'INPUT' && input.list) {
const datalist = document.getElementById(input.list.id);
if (datalist) datalist.innerHTML = '';
}
// Get current field value BEFORE resolving new options
const currentValue = input.value || record[fieldName] || '';
// Resolve options with current context
const params = {
...baseParams,
dependsOnField: field.dependsOn,
dependsOnValue: dependedValues[field.dependsOn]
};
const newOptions = await this.getFieldOptions(fieldName, formType, params);
// Populate the input
if (input.tagName === 'SELECT') {
this.populateSelectOptions(input, newOptions, currentValue);
} else if (input.tagName === 'INPUT' && input.list) {
this.populateDatalistOptions(input.list, newOptions);
// For datalist, set the value directly
if (currentValue) input.value = currentValue;
}
setTimeout(() => {
input.dispatchEvent(new Event('change', { bubbles: true }));
}, 0);
} catch (error) {
console.error(`Error loading options for ${fieldName}:`, error);
if (input.tagName === 'SELECT') {
input.innerHTML = '<option value="">Error</option>';
}
}
}
}
parseInputAttributes(inputAttributes) {
if (typeof inputAttributes === 'string') {
const parsed = {};
const regex = /(\w+)(?:=("[^"]*"|'[^']*'|\S+))?/g;
let match;
while ((match = regex.exec(inputAttributes)) !== null) {
const key = match[1];
const value = match[2] ? match[2].replace(/^["']|["']$/g, '') : '';
parsed[key] = value === '' ? 'true' : value;
}
return parsed;
}
return inputAttributes || {};
}
createInput(fieldName, field, value, formType) {
const container = FTableDOMHelper.create('div', {
className: `ftable-input ftable-${field.type || 'text'}-input`