Jake Vanderwerf
2026-01-04 af572745059d37e91696450136182e890b25da71
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
/**********************************************
 PopulateForm extracts saved data and populates the form field accordingly
 **********************************************/
class PopulateForm {
    constructor(form, itemDataOrFields = {}, legacyImages = {}, options = {}) {
        // Support both old signature (fields, images) and new signature (item object)
        this.item = this.normalizeItemData(itemDataOrFields, legacyImages);
        this.form = form;
        this.options = options;
 
        // Populate all fields
        for (let [fieldName, fieldValue] of Object.entries(this.item.fields)) {
            let wrapper = form.querySelector(`[data-field="${fieldName}"]`);
            if (wrapper) {
                this.populateField(wrapper, fieldName, fieldValue);
            }
        }
    }
 
    /**
     * Normalize data to consistent structure
     * Supports both new format (item object) and legacy format (fields, images)
     */
    normalizeItemData(itemDataOrFields, legacyImages) {
        // Check if this is the new format (has a fields property) or legacy format
        if (itemDataOrFields && typeof itemDataOrFields === 'object' && 'fields' in itemDataOrFields) {
            // New format - already structured
            return {
                fields: itemDataOrFields.fields || {},
                images: itemDataOrFields.images || {},
                taxonomies: itemDataOrFields.taxonomies || {}
            };
        } else {
            // Legacy format - fields and images passed separately
            return {
                fields: itemDataOrFields || {},
                images: legacyImages || {},
                taxonomies: {}
            };
        }
    }
 
    /**
     * Check if a field is a taxonomy field
     */
    isTaxonomyField(fieldName) {
        return Object.hasOwn(this.item.taxonomies, fieldName) &&
            Object.keys(this.item.taxonomies[fieldName]).length > 0;
    }
 
    /**
     * Check if a value references image data
     */
    isImageField(value) {
        if (!this.item.images || Object.keys(this.item.images).length === 0) {
            return false;
        }
 
        const ids = this.splitIDs(value);
        return ids.some(id => Object.keys(this.item.images).includes(String(id)));
    }
 
    /**
     * Split comma-separated IDs into array of integers
     */
    splitIDs(value) {
        return String(value).split(',')
            .map(v => parseInt(v.trim()))
            .filter(v => !isNaN(v) && v > 0);
    }
 
    /**
     * Populate a single field with its value
     */
    populateField(fieldWrapper, fieldName, fieldValue, options = {}) {
        if (!fieldWrapper || fieldValue === undefined || fieldValue === null) {
            return;
        }
 
        // Determine field type from classes or data attributes
        const fieldType = this.getFieldType(fieldWrapper);
 
        switch (fieldType) {
            case 'upload':
            case 'gallery':
            case 'image':
                this.populateUploadField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'repeater':
                this.populateRepeaterField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'taxonomy':
                this.populateTaxonomyField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'user':
                this.populateUserField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'location':
                this.populateLocationField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'set':
            case 'checkbox':
                this.populateSetField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'select':
            case 'radio':
                this.populateSelectField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'true_false':
                this.populateBooleanField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'date':
            case 'time':
            case 'datetime':
                this.populateDateField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'number':
                this.populateNumberField(fieldWrapper, fieldName, fieldValue);
                break;
 
            case 'textarea':
                if (fieldWrapper.querySelector('.editor-container')) {
                    this.populateEditorField(fieldWrapper, fieldName, fieldValue);
                } else {
                    this.populateTextareaField(fieldWrapper, fieldName, fieldValue);
                }
                break;
 
            case 'text':
            case 'email':
            case 'url':
            case 'tel':
            case 'phone':
            default:
                this.populateTextField(fieldWrapper, fieldName, fieldValue);
                break;
        }
    }
 
    /**
     * Populate taxonomy fields with visual display
     */
    populateTaxonomyField(fieldWrapper, fieldName, fieldValue) {
        // Handle different value formats
        let termIds = [];
 
        if (Array.isArray(fieldValue)) {
            termIds = fieldValue.map(v => String(v));
        } else if (typeof fieldValue === 'string') {
            try {
                const parsed = JSON.parse(fieldValue);
                termIds = Array.isArray(parsed) ? parsed.map(v => String(v)) : [String(parsed)];
            } catch (e) {
                termIds = fieldValue.split(',').map(v => v.trim()).filter(v => v);
            }
        } else if (fieldValue) {
            termIds = [String(fieldValue)];
        }
 
        if (termIds.length === 0) {
            return;
        }
 
        // Update hidden input
        const hiddenInput = fieldWrapper.querySelector(`input[type="hidden"][name="${fieldName}"]`);
        if (hiddenInput) {
            hiddenInput.value = termIds.join(',');
 
            // Trigger TaxonomySelector to update visual display
            const toggle = fieldWrapper.querySelector('.taxonomy-toggle');
            if (toggle && toggle.dataset.fieldId && window.jvbTaxonomy) {
                // Use requestAnimationFrame to ensure DOM is ready
                requestAnimationFrame(() => {
                    window.jvbTaxonomy.updateFieldFromInput(toggle.dataset.fieldId);
                });
            }
        }
    }
 
    /**
     * Populate upload fields (images, videos, files)
     */
    populateUploadField(fieldWrapper, fieldName, fieldValue) {
        // Check if this is a timeline gallery
        const isTimeline = fieldWrapper.dataset.subtype === 'timeline' || fieldName === 'timeline';
 
        if (isTimeline) {
            this.populateTimelineGallery(fieldWrapper, fieldName, fieldValue);
            return;
        }
 
        if (!fieldValue) {
            return;
        }
 
        // Handle comma-separated IDs or single ID
        const itemIds = this.splitIDs(fieldValue);
        if (itemIds.length === 0) {
            return;
        }
 
        // Update hidden input
        const hiddenInput = fieldWrapper.querySelector(`input[type="hidden"][name="${fieldName}"]`);
        if (hiddenInput) {
            hiddenInput.value = itemIds.join(',');
        }
 
        // Update display grid
        const grid = fieldWrapper.querySelector('.item-grid');
        const uploadContainer = fieldWrapper.querySelector('.file-upload-container');
 
        // Clear existing items first
        if (grid) {
            window.removeChildren(grid);
        }
 
        fieldWrapper.querySelector('.progress')?.remove();
 
        if (grid) {
            itemIds.forEach(itemId => {
                const template = window.getTemplate('uploadItem');
                if (!template) {
                    console.warn('uploadItem template not found');
                    return;
                }
 
                this.populateUploadItem(template, itemId);
                grid.append(template);
            });
 
            // Hide upload container if items exist
            if (itemIds.length > 0 && uploadContainer) {
                uploadContainer.hidden = true;
            }
        }
    }
 
    /**
     * Populate a single upload item
     */
    populateUploadItem(template, itemId) {
        let input = template.querySelector('input[name="select-item"]');
        let label = template.querySelector('label[for="select-item"]');
 
        template.dataset.id = itemId;
        input.name = `select-item-${itemId}`;
        input.id = input.name;
        label.htmlFor = input.name;
 
        const img = template.querySelector('img');
        template.querySelector('video')?.remove();
 
        // Populate with data from item.images
        if (this.item.images[itemId]) {
            const data = this.item.images[itemId];
            if (img) {
                img.src = data.medium || data.small || data.large || '';
                img.alt = data['image-alt-text'] || data.alt || '';
            }
 
            // Populate metadata fields
            const titleInput = template.querySelector('[name="image-title"]');
            const altInput = template.querySelector('[name="image-alt-text"]');
            const captionInput = template.querySelector('[name="image-caption"]');
 
            if (titleInput) titleInput.value = data['image-title'] || data.title || '';
            if (altInput) altInput.value = data['image-alt-text'] || data.alt || '';
            if (captionInput) captionInput.value = data['image-caption'] || data.caption || '';
        } else {
            console.warn(`No image data found for ID: ${itemId}`);
        }
 
        // Remove hint if present
        template.querySelector('details .upload-meta > .hint')?.remove();
    }
 
    /**
     * Populate timeline gallery - FIXED iteration
     */
    populateTimelineGallery(fieldWrapper, fieldName, fieldValue) {
        console.log('Populating Timeline Gallery', fieldValue);
 
        if (!fieldValue || !Array.isArray(fieldValue)) {
            console.warn('Timeline field value must be an array');
            return;
        }
 
        if (fieldValue.length === 0) {
            return;
        }
 
        const grid = fieldWrapper.querySelector('.item-grid');
        const uploadContainer = fieldWrapper.querySelector('.file-upload-container');
 
        // Clear existing items
        if (grid) {
            window.removeChildren(grid);
        }
 
        fieldWrapper.querySelector('.progress')?.remove();
 
        if (!grid) return;
 
        // FIX: Iterate directly over array, not Object.entries
        for (let itemData of fieldValue) {
            const template = window.getTemplate('timelineItem');
            if (!template) {
                console.warn('timelineItem template not found');
                continue;
            }
 
            const imageId = itemData.post_thumbnail;
            const postId = itemData.id;
 
            // Set template data attributes
            template.dataset.id = imageId;
            template.dataset.postId = postId;
 
            // Update selection controls
            let input = template.querySelector('input[name="select-item"]');
            let label = template.querySelector('label[for="select-item"]');
            if (input && label) {
                input.name = `select-item-${imageId}`;
                input.id = input.name;
                label.htmlFor = input.name;
            }
 
            // Remove unnecessary elements
            template.querySelector('video')?.remove();
            template.querySelector('.select-item span')?.remove();
 
            // Populate main image
            const img = template.querySelector('img');
            const imgData = this.item.images[imageId];
            if (img && imgData) {
                img.src = imgData.medium || imgData.small || imgData.large || '';
                img.title = imgData['image-title'] || '';
                img.alt = imgData['image-alt-text'] || '';
            }
 
            // Populate all fields within the template
            const fields = template.querySelectorAll('.field');
            fields.forEach(field => {
                if (field.classList.contains('group')) {
                    return;
                }
 
                const input = field.querySelector('input:not([type="file"]), textarea');
                if (!input) return;
 
                const label = field.querySelector('label');
                const fieldName = input.name.replace('upload_data::', '').replace(/^\[.*?\]/, '');
 
                // Get value from itemData or imgData
                let value = itemData[fieldName];
                if (value === undefined && imgData) {
                    value = imgData[fieldName];
                }
 
                // Populate the field using our standard method
                if (value !== undefined && value !== null) {
                    this.populateField(field, fieldName, value);
                }
 
                // Update field identifiers to include post ID
                const newName = `[${postId}]${fieldName}`;
                const newId = newName;
                input.name = newName;
                input.id = newId;
                if (label) label.htmlFor = newId;
            });
 
            grid.append(template);
        }
 
        // Hide upload container if items exist
        if (fieldValue.length > 0 && uploadContainer) {
            uploadContainer.hidden = true;
        }
    }
 
    populateTextField(fieldWrapper, fieldName, fieldValue) {
        const input = fieldWrapper.querySelector(`[name="${fieldName}"], input, textarea`);
        if (input && input.type !== 'file') {
            input.value = String(fieldValue || '');
 
            if (input.dataset.limit) {
                const counter = fieldWrapper.querySelector('.char-count .current');
                if (counter) {
                    counter.textContent = input.value.length;
                }
            }
        }
    }
 
    populateTextareaField(fieldWrapper, fieldName, fieldValue) {
        const textarea = fieldWrapper.querySelector(`textarea[name="${fieldName}"]`) ||
            fieldWrapper.querySelector('textarea:not([data-editor="true"])');
 
        if (textarea) {
            textarea.value = String(fieldValue || '');
            textarea.dispatchEvent(new Event('change', { bubbles: true }));
 
            if (textarea.dataset.limit) {
                const counter = fieldWrapper.querySelector('.char-count .current');
                if (counter) {
                    counter.textContent = textarea.value.length;
                    const limit = parseInt(textarea.dataset.limit, 10);
                    fieldWrapper.classList.toggle('reached', textarea.value.length >= limit);
                }
            }
        }
    }
 
    populateEditorField(fieldWrapper, fieldName, fieldValue) {
        const textarea = fieldWrapper.querySelector(`textarea[name="${fieldName}"][data-editor="true"]`);
        if (!textarea) return;
 
        textarea.value = String(fieldValue || '');
        const editorContainer = fieldWrapper.querySelector('.editor');
        const content = fieldValue || '<p><br></p>';
 
        if (editorContainer) {
            let quillInstance = editorContainer.__quill;
 
            if (!quillInstance && window.Quill) {
                for (let instance of (window.Quill.instances || [])) {
                    if (instance.container === editorContainer) {
                        quillInstance = instance;
                        break;
                    }
                }
            }
 
            if (quillInstance) {
                quillInstance.root.innerHTML = content;
                editorContainer.__quill = quillInstance;
            } else {
                editorContainer.innerHTML = content;
            }
        }
 
        textarea.dispatchEvent(new Event('change', { bubbles: true }));
    }
 
    getFieldType(fieldWrapper) {
        if (fieldWrapper.dataset.fieldType) return fieldWrapper.dataset.fieldType;
        if (fieldWrapper.dataset.type) return fieldWrapper.dataset.type;
 
        const typeClasses = [
            'upload', 'repeater', 'taxonomy', 'user', 'location',
            'set', 'checkbox', 'select', 'radio', 'true_false', 'date',
            'time', 'datetime', 'editor', 'number', 'text', 'textarea',
            'email', 'url', 'tel', 'phone'
        ];
 
        for (const type of typeClasses) {
            if (fieldWrapper.classList.contains(type)) {
                return type;
            }
        }
 
        const input = fieldWrapper.querySelector('input, select, textarea');
        if (input) {
            if (input.tagName === 'TEXTAREA') {
                return input.dataset.editor === 'true' ? 'editor' : 'textarea';
            }
            if (input.type) {
                return input.type === 'checkbox' && !fieldWrapper.classList.contains('true_false') ? 'set' : input.type;
            }
        }
 
        return 'text';
    }
 
    /**
     * Populate number fields
     */
    populateNumberField(fieldWrapper, fieldName, fieldValue) {
        const input = fieldWrapper.querySelector(`[name="${fieldName}"], input[type="number"]`);
        if (input) {
            input.value = Number(fieldValue) || 0;
        }
    }
 
    /**
     * Populate boolean/true_false fields
     */
    populateBooleanField(fieldWrapper, fieldName, fieldValue) {
        const input = fieldWrapper.querySelector(`[name="${fieldName}"], input[type="checkbox"]`);
        if (input) {
            input.checked = Boolean(fieldValue);
        }
    }
 
    /**
     * Populate select/radio fields
     */
    populateSelectField(fieldWrapper, fieldName, fieldValue) {
        const value = String(fieldValue || '');
 
        // Try select first
        const select = fieldWrapper.querySelector(`select[name="${fieldName}"]`);
        if (select) {
            select.value = value;
            return;
        }
 
        // Try radio buttons
        const radio = fieldWrapper.querySelector(`input[type="radio"][name="${fieldName}"][value="${value}"]`);
        if (radio) {
            radio.checked = true;
        }
    }
 
    /**
     * Populate set/checkbox fields (multiple selections)
     */
    populateSetField(fieldWrapper, fieldName, fieldValue) {
        // Parse value if it's a string
        let values = fieldValue;
        if (typeof fieldValue === 'string') {
            try {
                values = JSON.parse(fieldValue);
            } catch (e) {
                values = fieldValue.split(',').map(v => v.trim());
            }
        }
 
        if (!Array.isArray(values)) {
            values = [String(values)];
        }
 
        // Update checkboxes
        fieldWrapper.querySelectorAll(`input[type="checkbox"][name*="${fieldName}"]`).forEach(checkbox => {
            checkbox.checked = values.includes(checkbox.value);
        });
    }
 
    /**
     * Populate date/time fields
     */
    populateDateField(fieldWrapper, fieldName, fieldValue) {
        const input = fieldWrapper.querySelector(`[name="${fieldName}"], input`);
        if (input && fieldValue) {
            // Handle different date formats
            let dateValue = fieldValue;
            if (typeof fieldValue === 'object' && fieldValue.date) {
                dateValue = fieldValue.date;
            }
 
            // Convert to appropriate format for input type
            try {
                const date = new Date(dateValue);
                if (!isNaN(date.getTime())) {
                    switch (input.type) {
                        case 'date':
                            input.value = date.toISOString().split('T')[0];
                            break;
                        case 'time':
                            input.value = date.toTimeString().slice(0, 5);
                            break;
                        case 'datetime-local':
                            input.value = date.toISOString().slice(0, 16);
                            break;
                        default:
                            input.value = dateValue;
                    }
                }
            } catch (e) {
                input.value = dateValue;
            }
        }
    }
 
    /**
     * Populate location fields
     */
    populateLocationField(fieldWrapper, fieldName, fieldValue) {
        if (!fieldValue || typeof fieldValue !== 'object') {
            return;
        }
 
        // Location fields typically have sub-fields
        const subFields = ['address', 'lat', 'lng', 'street', 'city', 'province', 'postal_code', 'country'];
 
        subFields.forEach(subField => {
            if (fieldValue[subField] !== undefined) {
                const input = fieldWrapper.querySelector(`[name="${fieldName}_${subField}"], [name="${subField}"]`);
                if (input) {
                    input.value = String(fieldValue[subField] || '');
                }
            }
        });
    }
 
 
    /**
     * Populate user fields (similar to taxonomy)
     */
    populateUserField(fieldWrapper, fieldName, fieldValue) {
        // Similar logic to taxonomy fields
        this.populateTaxonomyField(fieldWrapper, fieldName, fieldValue);
    }
 
    /**
     * Populate repeater fields
     */
    populateRepeaterField(fieldWrapper, fieldName, fieldValue) {
        if (!fieldValue || !Array.isArray(fieldValue)) {
            return;
        }
 
        const container = fieldWrapper.querySelector('.repeater-items');
        const template = fieldWrapper.querySelector('template');
 
        if (!container || !template) {
            console.warn(`Repeater field ${fieldName}: missing container or template`);
            return;
        }
 
        // Clear existing rows
        window.removeChildren(container);
 
        // Create rows for each data item
        fieldValue.forEach((rowData, index) => {
            if (!rowData || typeof rowData !== 'object') {
                return;
            }
 
            const row = window.getTemplate(template.className);
            if (!row) {
                console.warn(`Repeater field ${fieldName}: template not found`);
                return;
            }
 
            // Set row ID and update row number
            row.id = `${fieldWrapper.closest('form').id}-${fieldName}-row-${index}`;
            row.dataset.index = index;
 
            const rowNumber = row.querySelector('.row-number');
            if (rowNumber) {
                rowNumber.textContent = `#${index + 1}`;
            }
 
            // Update field names and populate values
            row.querySelectorAll('input, select, textarea').forEach(field => {
                const originalName = field.name;
                const newName = `${fieldName}:${index}:${originalName}`;
                const newId = `${fieldName}-${index}-${originalName}-${field.value}`;
 
                // Update field identifiers
                field.name = newName;
                field.id = newId;
 
                // Update label
                const label = field.nextElementSibling;
                if (label && label.tagName === 'LABEL') {
                    label.htmlFor = newId;
                }
 
                // Populate field value
                if (rowData[originalName] !== undefined) {
                    this.populateRepeaterFieldValue(field, originalName, rowData[originalName]);
                }
            });
 
            container.appendChild(row);
        });
    }
 
    /**
     * Populate individual repeater field value
     */
    populateRepeaterFieldValue(field, fieldName, fieldValue) {
        switch (field.type) {
            case 'checkbox':
                field.checked = Boolean(fieldValue);
                break;
            case 'radio':
                field.checked = field.value === String(fieldValue);
                break;
            case 'select-one':
            case 'select-multiple':
                field.value = String(fieldValue || '');
                break;
            default:
                field.value = String(fieldValue || '');
        }
    }
}
 
// Make available globally
window.jvbPopulate = PopulateForm;