-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathForm Styler Feed.php
More file actions
1773 lines (1566 loc) · 82.3 KB
/
Form Styler Feed.php
File metadata and controls
1773 lines (1566 loc) · 82.3 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
<?php
/**
* BrightLeaf GF Form Styler (Feed Add-On)
*
* Goal
* - Provide a user-friendly, non-destructive way to style Gravity Forms without writing manual CSS.
* - Allow granular control over form appearance at the global, field-type, and individual field levels.
* - Ensure that styles are only applied when explicitly configured, preserving the theme's natural look by default.
*
* Features
* - Integrated UI: A custom styling panel built directly into the Gravity Forms Feed settings.
* - Global Tokens: Define base font sizes, colors, spacing, and borders that apply to the entire form.
* - Type Overrides: Set styles for all fields of a specific type (e.g., all text inputs or all buttons).
* - Field Overrides: Target specific fields by ID for high-specificity styling that wins over global/type settings.
* - Live CSS Preview: See the generated CSS in real-time within the admin UI before saving.
* - Base64 Storage: Style configurations are stored as base64-encoded JSON to avoid common character-filtering issues in database fields.
* - Conditional Emission: Only emits CSS for properties that have been explicitly set, reducing bloat and preventing style conflicts.
* - Admin Preview Support: Option to apply custom styles even within the Gravity Forms admin preview screens.
* - Debug Mode: Console logging for troubleshooting feed application and CSS injection.
*
* Requirements
* - A hidden field on the form you would like to style named `style_b64`.
*
* How To Use
* 1) Create a Styling Profile
* - Go to Forms -> [Your Form] -> Settings -> Form Styler.
* - Click "Add New" to create a new styling feed.
* - Give your profile a name (e.g., "Dark Theme" or "Contact Page Style").
*
* 2) Configure Styles
* - Open the "Styling" section in the feed settings.
* - Global Tokens: Use sections like Typography, Colors, and Spacing to set general form styles.
* - Type Overrides: Select a field type from the dropdown, then click "Type overrides" in the navigation to edit.
* - Field Overrides: Click a specific field in the field list on the left to apply styles only to that field.
*
* 3) Activate and Apply
* - Mark the feed as "Default" if you want it applied to all instances of this form.
* - Use the "Apply in admin preview" checkbox to see your styles while building the form.
* - To apply a specific (non-default) feed via URL for testing, append `?blfs_feed=[FEED_ID]` to your page URL.
*
* 4) Advanced Management
* - Export/Import: Copy the JSON payload to move styles between forms or sites.
* - Reset: Use the "Reset defaults" button to clear all configurations and start fresh.
*
* Developer Notes
* - CSS Injection: Styles are injected into the page head via `<style></style>` tags, scoped to the specific form and feed.
* - Scoping: CSS rules use dual selectors (`.blfs-scope-[ID]` and `#gform_wrapper_[ID]`) for maximum compatibility.
* - Payload: The authoritative data source is the base64-encoded JSON stored in the `style_b64` feed meta.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action(
'gform_loaded',
function () {
if ( ! class_exists( 'GFForms' ) || ! method_exists( 'GFForms', 'include_addon_framework' ) ) {
return;
}
GFForms::include_addon_framework();
if ( class_exists( 'GF_BrightLeaf_Form_Styler_AddOn' ) ) {
return;
}
/**
* Class GF_BrightLeaf_Form_Styler_AddOn
* Extends the GFFeedAddOn class to provide custom form-styling functionality for Gravity Forms.
*
* This add-on enables the addition of conditional styling configurations, feed management for form styling,
* and admin preview capabilities. It integrates seamlessly with Gravity Forms to allow the configuration
* and application of styles at both global and field-level granularity.
*/
class GF_BrightLeaf_Form_Styler_AddOn extends GFFeedAddOn {
// phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore,PHPCompatibility.FunctionDeclarations.NewClosure.ThisFoundOutsideClass
/**
* The version of the add-on.
*
* @var string
*/
protected $_version = '1.5.0';
/**
* The minimum required version of Gravity Forms.
*
* @var string
*/
protected $_min_gravityforms_version = '2.6';
/**
* The slug for the add-on.
*
* @var string
*/
protected $_slug = 'bl-gf-form-styler';
/**
* The path to the file containing the add-on.
*
* @var string
*/
protected $_path = __FILE__;
/**
* The full path to the file containing the add-on.
*
* @var string
*/
protected $_full_path = __FILE__;
/**
* The title of the add-on.
*
* @var string
*/
protected $_title = 'BrightLeaf Form Styler';
/**
* The short title of the add-on.
*
* @var string
*/
protected $_short_title = 'Form Styler';
// phpcs:enable PSR2.Classes.PropertyDeclaration.Underscore
/**
* The singleton instance of the class.
*
* @var self|null
*/
private static $instance = null;
/**
* Keep track of feeds already injected on this page load to prevent duplicate <style> blocks.
*
* @var array
*/
private static $injected_feeds = [];
/**
* Retrieves the singleton instance of the class.
*
* Ensures that only one instance of the class is created and reused across the application.
*
* @return self The singleton instance of the class.
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Initialize the add-on.
*
* Registers filters for form styling injection and preview management.
*/
public function init() {
parent::init();
add_filter( 'gform_get_form_filter', [ $this, 'inject_styling_into_form_html' ], 10, 2 );
add_filter( 'gform_form_tag', [ $this, 'filter_form_tag_add_scope_class' ], 10, 2 );
add_filter( 'gform_pre_render', [ $this, 'maybe_set_feed_override_from_request' ], 10, 1 );
add_filter( 'gform_admin_pre_render', [ $this, 'maybe_set_feed_override_from_request' ], 10, 1 );
}
/*
--------------------------------------------------------------------
Safe helpers
--------------------------------------------------------------------
*/
/**
* Get form ID from current context.
*
* Checks both GET params and current Gravity Forms context.
*
* @return int The form ID.
*/
protected function blfs_get_current_form_id_safe() {
$form_id = absint( rgget( 'id' ) );
if ( $form_id ) {
return $form_id;
}
$form = $this->get_current_form();
return absint( rgar( $form, 'id' ) );
}
/**
* Get feed ID from current request.
*
* @return int The feed ID from the 'fid' GET parameter.
*/
protected function blfs_get_current_feed_id_safe() {
return absint( rgget( 'fid' ) );
}
/**
* Safely retrieve a feed by ID.
*
* @param int $feed_id The feed ID.
*
* @return array|null The feed object array or null if not found.
*/
protected function blfs_get_feed_safe( $feed_id ) {
if ( ! $feed_id ) {
return null;
}
$feed = GFAPI::get_feed( $feed_id );
return is_array( $feed ) ? $feed : null;
}
/*
--------------------------------------------------------------------
Feed list columns
--------------------------------------------------------------------
*/
/**
* Define columns for the feed list table.
*
* @return array Associative array of column keys and labels.
*/
public function feed_list_columns() {
return [
'feedName' => 'Name',
'is_default' => 'Default',
'updated' => 'Updated',
];
}
/**
* Get value for the 'is_default' column in feed list.
*
* @param array $feed The feed object.
*
* @return string HTML/Emoji representation of default status.
*/
public function get_column_value_is_default( $feed ) {
$enabled = (bool) rgar( $feed, 'is_active' );
$default = rgar( rgar( $feed, 'meta' ), 'is_default' );
if ( ! $enabled ) {
return '<span style="opacity:.6;">—</span>';
}
return $default ? '✅' : '—';
}
/**
* Get value for the 'updated' column in feed list.
*
* @param array $feed The feed object.
*
* @return string Formatted date string or spacer.
*/
public function get_column_value_updated( $feed ) {
$ts = (int) rgar( rgar( $feed, 'meta' ), 'updated_ts' );
if ( ! $ts ) {
return '<span style="opacity:.6;">—</span>';
}
return esc_html( date_i18n( 'Y-m-d H:i', $ts ) );
}
/*
--------------------------------------------------------------------
Feed settings fields
--------------------------------------------------------------------
*/
/**
* Define feed settings fields.
*
* @return array Gravity Forms Add-on settings fields configuration.
*/
public function feed_settings_fields() {
return [
[
'title' => 'Feed Settings',
'fields' => [
[
'name' => 'feedName',
'label' => 'Profile name',
'type' => 'text',
'class' => 'medium',
'required' => true,
],
[
'name' => 'is_default',
'label' => 'Default profile for this form',
'type' => 'checkbox',
'choices' => [
[
'label' => 'Use this feed as the default styling profile',
'name' => 'is_default',
],
],
],
[
'name' => 'apply_admin_preview',
'label' => 'Apply in admin preview',
'type' => 'checkbox',
'choices' => [
[
'label' => 'Apply on admin preview screens (recommended)',
'name' => 'apply_admin_preview',
],
],
],
],
],
[
'title' => 'Styling',
'description' => 'Configure global tokens, type overrides, and field overrides. This UI saves a JSON payload (base64-encoded) in the feed meta.',
'fields' => [
[
'name' => 'style_b64',
'label' => '',
'type' => 'text',
'class' => 'large',
'style' => 'display:none;',
],
[
'name' => 'styler_ui',
'label' => '',
'type' => 'blfs_markup',
],
],
],
[
'title' => 'Advanced',
'fields' => [
[
'name' => 'debug_mode',
'label' => 'Debug logging',
'type' => 'checkbox',
'choices' => [
[
'label' => 'Enable console.log diagnostics (recommended during setup)',
'name' => 'debug_mode',
],
],
],
],
],
];
}
/*
--------------------------------------------------------------------
Custom settings field renderer — "type" => "blfs_markup"
--------------------------------------------------------------------
*/
/**
* Render the custom styling UI markup.
*/
public function settings_blfs_markup() {
$form_id = $this->blfs_get_current_form_id_safe();
if ( ! $form_id ) {
echo '<div style="color:#b32d2e;">Form Styler: Could not determine form ID.</div>';
return;
}
$feed_id = $this->blfs_get_current_feed_id_safe(); // 0 on "new feed"
$feed = $this->blfs_get_feed_safe( $feed_id );
$meta = is_array( $feed ) ? rgar( $feed, 'meta' ) : [];
$stored_b64 = rgar( $meta, 'style_b64' );
$json = '';
if ( ! empty( $stored_b64 ) && is_string( $stored_b64 ) ) {
$decoded = base64_decode( $stored_b64, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
if ( false !== $decoded ) {
$json = $decoded;
}
}
$factory_payload = $this->default_style_payload();
$factory_json = wp_json_encode( $factory_payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
if ( empty( $json ) ) {
$json = $factory_json;
}
$form = GFAPI::get_form( $form_id );
$fields = [];
$type_counts = [];
if ( is_array( $form ) && ! empty( $form['fields'] ) ) {
foreach ( $form['fields'] as $f ) {
$field_id = is_object( $f ) ? $f->id : rgar( $f, 'id' );
$field_type = is_object( $f ) ? $f->type : rgar( $f, 'type' );
$field_label = is_object( $f ) && method_exists( $f, 'get_field_label' )
? $f->get_field_label( false, '' )
: rgar( $f, 'label' );
$field_type = (string) $field_type;
if ( '' !== $field_type ) {
$type_counts[ $field_type ] = isset( $type_counts[ $field_type ] )
? ( $type_counts[ $field_type ] + 1 )
: 1;
}
$fields[] = [
'id' => $field_id,
'label' => $field_label ?: '(no label)',
'type' => $field_type ?: '',
];
}
}
$types = [];
foreach ( $type_counts as $t => $count ) {
$types[] = [
'type' => $t,
'count' => $count,
];
}
?>
<div id="blfs-root" style="max-width:1100px;">
<style>
#blfs-root { margin-top: 10px; }
.blfs-grid { display: grid; grid-template-columns: 270px 1fr; gap: 16px; align-items: start; }
.blfs-card { background: #fff; border: 1px solid #dcdcde; border-radius: 10px; padding: 14px; }
.blfs-card h3 { margin: 0 0 10px; font-size: 14px; }
.blfs-nav { display: flex; flex-direction: column; gap: 6px; }
.blfs-nav button { text-align: left; width: 100%; padding: 8px 10px; border-radius: 8px; border: 1px solid #dcdcde; background: #f6f7f7; cursor: pointer; }
.blfs-nav button[aria-current="true"] { background: #fff; border-color: #2271b1; box-shadow: 0 0 0 1px #2271b1 inset; }
.blfs-row { display: grid; grid-template-columns: 220px 1fr; gap: 10px; margin-bottom: 10px; align-items: center; }
.blfs-row label { font-weight: 600; }
.blfs-help { color: #646970; font-size: 12px; margin-top: 2px; }
.blfs-split { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.blfs-field-list { max-height: 260px; overflow: auto; border: 1px solid #dcdcde; border-radius: 8px; background: #fff; }
.blfs-field-item { padding: 8px 10px; border-bottom: 1px solid #f0f0f1; cursor: pointer; }
.blfs-field-item:hover { background: #f6f7f7; }
.blfs-field-item[aria-current="true"] { background: #e7f5ff; }
.blfs-inline { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.blfs-pill { font-size: 11px; padding: 2px 8px; border-radius: 999px; background: #f0f0f1; border: 1px solid #dcdcde; }
.blfs-preview-note { color: #1d2327; font-size: 12px; background: #f6f7f7; border: 1px solid #dcdcde; padding: 8px 10px; border-radius: 8px; }
.blfs-actions { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.blfs-actions button { padding: 7px 12px; border-radius: 8px; border: 1px solid #2271b1; background: #2271b1; color: #fff; cursor: pointer; }
.blfs-actions button.secondary { background: #fff; color: #2271b1; }
.blfs-actions button.danger { border-color: #d63638; background: #d63638; }
.blfs-textarea { width: 100%; min-height: 160px; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 12px; }
.blfs-css-preview { width: 100%; height: 200px; max-height: 500px; overflow-y: auto !important; resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 12px; background: #f6f7f7; border: 1px solid #dcdcde; border-radius: 8px; padding: 10px; }
.blfs-warn { color: #b32d2e; background: #fcf0f1; border: 1px solid #f5c6cb; border-radius: 8px; padding: 8px 10px; font-size: 12px; margin-top: 8px; }
@media (max-width: 980px) { .blfs-grid { grid-template-columns: 1fr; } }
</style>
<div class="blfs-preview-note">
<strong>How this works:</strong>
Global tokens become CSS variables on a feed-specific scope class. Type overrides apply to all fields of a given type.
Field overrides apply only to a specific field and win over type overrides.
</div>
<div class="blfs-grid" style="margin-top:12px;">
<div class="blfs-card">
<h3>Sections</h3>
<div class="blfs-nav" id="blfs-nav"></div>
<div style="margin-top:14px;">
<h3>Types</h3>
<select id="blfs-type-select" class="widefat"></select>
<div class="blfs-help">Pick a type, then open "Type overrides".</div>
</div>
<div style="margin-top:14px;">
<h3>Fields</h3>
<input type="text" id="blfs-field-search" class="widefat" placeholder="Search fields…" />
<div class="blfs-field-list" id="blfs-field-list" style="margin-top:8px;"></div>
</div>
</div>
<div class="blfs-card">
<div class="blfs-actions" style="justify-content:space-between;">
<div class="blfs-inline">
<span class="blfs-pill">Form ID: <?php echo esc_html( $form_id ); ?></span>
<span class="blfs-pill">Feed ID: <?php echo esc_html( $feed_id ?: 'new' ); ?></span>
</div>
<div class="blfs-inline">
<button type="button" class="secondary" id="blfs-export">Export JSON</button>
<button type="button" class="secondary" id="blfs-import">Import JSON</button>
<button type="button" class="danger" id="blfs-reset">Reset defaults</button>
</div>
</div>
<hr style="margin:14px 0;">
<div id="blfs-panel"></div>
<hr style="margin:14px 0;">
<h3 style="margin-bottom:8px;">Generated CSS (preview)</h3>
<textarea class="blfs-css-preview" id="blfs-css-preview"></textarea>
<div class="blfs-help">Preview only — CSS is injected at runtime via a <style> tag and is not stored in a GF settings field.</div>
<hr style="margin:14px 0;">
<h3 style="margin-bottom:8px;">JSON payload (advanced)</h3>
<textarea class="blfs-textarea" id="blfs-json-editor"></textarea>
<div class="blfs-help">This is the authoritative saved payload. The UI edits this value. Invalid JSON will be rejected on save.</div>
</div>
</div>
</div>
<script>
(function(){
const BLFS_FORM_ID = <?php echo $form_id; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped --already casted to int ?>;
const BLFS_FEED_ID = <?php echo $feed_id; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped --already casted to int ?>;
const BLFS_FIELDS = <?php echo wp_json_encode( $fields ); ?>;
const BLFS_TYPES = <?php echo wp_json_encode( $types ); ?>;
const BLFS_SAVED_JSON = <?php echo wp_json_encode( $json ); ?>;
const BLFS_FACTORY_JSON = <?php echo wp_json_encode( $factory_json ); ?>;
/* -------------------------------------------------------------- */
/* DOM refs */
/* -------------------------------------------------------------- */
// GF Add-On Framework generates names like: _gaddon_setting_style_b64
const hiddenField =
document.querySelector('input[name$="_style_b64"]') ||
document.querySelector('input[name*="style_b64"]') ||
document.querySelector('#gaddon-setting-row-style_b64 input');
// FIX: warn loudly if the hidden field is missing so the issue is obvious.
if ( ! hiddenField ) {
console.warn('[BLFS] ⚠ Could not find style_b64 hidden input — styles will NOT be saved! Check that the feed settings field name matches.');
}
const jsonEditor = document.getElementById('blfs-json-editor');
const cssPreview = document.getElementById('blfs-css-preview');
const typeSelect = document.getElementById('blfs-type-select');
/* -------------------------------------------------------------- */
/* Utilities */
/* -------------------------------------------------------------- */
function safeParse(str){ try { return JSON.parse(str); } catch(e){ return null; } }
function pretty(obj) { return JSON.stringify(obj, null, 2); }
function log(...args) { console.log('[BLFS]', ...args); }
function b64Decode(str){
try {
const binary = atob(str);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return new TextDecoder().decode(bytes);
} catch(e){ return null; }
}
function b64Encode(str){
try {
const bytes = new TextEncoder().encode(str);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
} catch(e){ return null; }
}
function setHidden(jsonStr){
if ( hiddenField ) hiddenField.value = b64Encode(jsonStr ) || '';
}
/* -------------------------------------------------------------- */
/* Initialise from stored value or default */
/* -------------------------------------------------------------- */
let initialJson = BLFS_SAVED_JSON;
if ( hiddenField && hiddenField.value ) {
const decoded = b64Decode(hiddenField.value);
if ( decoded ) initialJson = decoded;
}
jsonEditor.value = initialJson;
setHidden(initialJson);
let state = safeParse(jsonEditor.value) || safeParse(BLFS_SAVED_JSON) || {};
let activeSection = 'Global';
let activeFieldId = null;
let activeType = '';
/* -------------------------------------------------------------- */
/* Section definitions */
/* -------------------------------------------------------------- */
const SECTIONS = [
{ key: 'Global', label: 'Global tokens' },
{ key: 'Typography', label: 'Typography' },
{ key: 'Colors', label: 'Colors' },
{ key: 'Spacing', label: 'Spacing' },
{ key: 'Borders', label: 'Borders' },
{ key: 'Buttons', label: 'Buttons' },
{ key: 'States', label: 'States (focus/error)' },
{ key: 'TypeOverrides', label: 'Type overrides' },
{ key: 'FieldOverrides', label: 'Field overrides' },
];
/* -------------------------------------------------------------- */
/* State helpers */
/* -------------------------------------------------------------- */
function ensureDefaults(){
// Only scaffold the object structure — never inject hardcoded values.
// Empty strings mean "not set", so no CSS is emitted for that property.
state = state || {};
state.version = state.version || 1;
state.tokens = state.tokens || {};
state.tokens.typography = state.tokens.typography || { base_font_size:'', label_font_size:'', input_font_size:'' };
state.tokens.colors = state.tokens.colors || { text:'', label:'', choice_label:'', description:'', input_bg:'', input_border:'', focus:'', error:'', button_bg:'', button_text:'' };
state.tokens.spacing = state.tokens.spacing || { field_margin_bottom:'', input_padding:'', section_padding:'' };
state.tokens.borders = state.tokens.borders || { radius:'', border_width:'' };
state.tokens.buttons = state.tokens.buttons || { radius:'', padding:'' };
state.tokens.states = state.tokens.states || { focus_ring:'', error_border:'' };
if ( ! state.type_overrides || Array.isArray( state.type_overrides ) ) {
state.type_overrides = {};
}
if ( ! state.field_overrides || Array.isArray( state.field_overrides ) ) {
state.field_overrides = {};
}
}
function syncJson(){
ensureDefaults();
const text = pretty(state);
jsonEditor.value = text;
setHidden(text); // FIX: was using undefined `hiddenTextarea`
updateCssPreview();
}
function updateCssPreview(){
const obj = safeParse(jsonEditor.value);
if ( !obj ) {
cssPreview.value = 'Invalid JSON (preview not available).';
return;
}
const css = buildCssFromState(BLFS_FORM_ID, BLFS_FEED_ID || 0, obj);
cssPreview.value = css || '(no css generated)';
}
jsonEditor.addEventListener('input', () => {
const obj = safeParse(jsonEditor.value);
if ( obj ) {
state = obj;
setHidden(jsonEditor.value); // FIX: was missing b64 encoding in some paths
}
updateCssPreview();
});
/* -------------------------------------------------------------- */
/* Form submit guard */
/* -------------------------------------------------------------- */
document.addEventListener('submit', function(e){
const obj = safeParse(jsonEditor.value);
if ( !obj ) {
e.preventDefault();
alert('Form Styler: Invalid JSON. Please fix before saving.');
log('Invalid JSON prevented save.');
} else {
// FIX: was `if ( hiddenTextarea )` — hiddenTextarea was never defined.
// The hidden field is already kept in sync by setHidden(); re-sync here as a safety net.
setHidden(jsonEditor.value);
log('JSON validated, saving feed…');
}
}, true);
/* -------------------------------------------------------------- */
/* Escape helper */
/* -------------------------------------------------------------- */
function escapeHtml(s){
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
/* -------------------------------------------------------------- */
/* Nav render */
/* -------------------------------------------------------------- */
function renderNav(){
const nav = document.getElementById('blfs-nav');
nav.innerHTML = '';
SECTIONS.forEach(s => {
const btn = document.createElement('button');
btn.type = 'button';
btn.textContent = s.label;
btn.setAttribute('aria-current', s.key === activeSection ? 'true' : 'false');
btn.addEventListener('click', () => {
activeSection = s.key;
activeFieldId = null;
renderNav(); renderPanel(); renderFieldList();
log('Section changed:', activeSection);
});
nav.appendChild(btn);
});
}
/* -------------------------------------------------------------- */
/* Type select render */
/* -------------------------------------------------------------- */
function renderTypeSelect(){
typeSelect.innerHTML = '';
const opt0 = document.createElement('option');
opt0.value = '';
opt0.textContent = '— Select a type —';
typeSelect.appendChild(opt0);
BLFS_TYPES.forEach(t => {
const opt = document.createElement('option');
opt.value = t.type;
opt.textContent = `${t.type} (${t.count})`;
typeSelect.appendChild(opt);
});
typeSelect.value = activeType || '';
typeSelect.addEventListener('change', () => {
activeType = typeSelect.value;
if ( activeSection === 'TypeOverrides' ) renderPanel();
log('Active type:', activeType);
});
}
/* -------------------------------------------------------------- */
/* Field list render */
/* -------------------------------------------------------------- */
function renderFieldList(){
const box = document.getElementById('blfs-field-list');
const q = (document.getElementById('blfs-field-search').value || '').toLowerCase().trim();
let list = BLFS_FIELDS.slice();
if ( q ) {
list = list.filter(f =>
String(f.label||'').toLowerCase().includes(q) ||
String(f.type||'').toLowerCase().includes(q) ||
String(f.id).includes(q)
);
}
box.innerHTML = '';
list.forEach(f => {
const item = document.createElement('div');
item.className = 'blfs-field-item';
item.setAttribute('aria-current', String(f.id) === String(activeFieldId) ? 'true' : 'false');
item.innerHTML = `<div style="display:flex;justify-content:space-between;gap:10px;">
<div><strong>${escapeHtml(f.label||'(no label)')}</strong>
<div class="blfs-help">ID ${f.id} • ${escapeHtml(f.type||'')}</div></div>
<div class="blfs-pill">#field_${BLFS_FORM_ID}_${f.id}</div>
</div>`;
item.addEventListener('click', () => {
activeSection = 'FieldOverrides';
activeFieldId = String(f.id);
renderNav(); renderPanel(); renderFieldList();
log('Active field override:', activeFieldId);
});
box.appendChild(item);
});
}
document.getElementById('blfs-field-search').addEventListener('input', renderFieldList);
/* -------------------------------------------------------------- */
/* Generic input row builder */
/* -------------------------------------------------------------- */
function inputRow(label, value, onChange, opts={}){
const row = document.createElement('div');
row.className = 'blfs-row';
const lab = document.createElement('div');
lab.innerHTML = `<label>${escapeHtml(label)}</label>${opts.help ? `<div class="blfs-help">${escapeHtml(opts.help)}</div>` : ''}`;
const ctl = document.createElement('div');
const el = document.createElement('input');
el.type = 'text';
el.value = value || '';
el.className = 'regular-text';
el.placeholder = opts.placeholder || '';
el.addEventListener('input', () => onChange(el.value));
ctl.appendChild(el);
row.appendChild(lab);
row.appendChild(ctl);
return row;
}
/* -------------------------------------------------------------- */
/* Override editor (shared by type + field overrides) */
/* -------------------------------------------------------------- */
function renderOverrideEditor(targetObj, onClear){
const panel = document.createElement('div');
// Label section
const labelHead = document.createElement('div');
labelHead.style.cssText = 'font-weight:600; font-size:12px; text-transform:uppercase; letter-spacing:.04em; color:#646970; margin:0 0 8px;';
labelHead.textContent = 'Label';
panel.appendChild(labelHead);
panel.appendChild(inputRow('Label color', targetObj.label_color || '', v => { targetObj.label_color = v; syncJson(); }, { placeholder:'e.g. #1d2327' }));
panel.appendChild(inputRow('Label font size', targetObj.label_font_size || '', v => { targetObj.label_font_size = v; syncJson(); }, { help:'e.g. 14px — leave blank to inherit' }));
// Input section
const inputHead = document.createElement('div');
inputHead.style.cssText = 'font-weight:600; font-size:12px; text-transform:uppercase; letter-spacing:.04em; color:#646970; margin:14px 0 8px;';
inputHead.textContent = 'Input';
panel.appendChild(inputHead);
panel.appendChild(inputRow('Background', targetObj.input_bg || '', v => { targetObj.input_bg = v; syncJson(); }, { placeholder:'e.g. #ffffff' }));
panel.appendChild(inputRow('Text color', targetObj.input_text || '', v => { targetObj.input_text = v; syncJson(); }, { placeholder:'e.g. #1d2327' }));
panel.appendChild(inputRow('Border color', targetObj.input_border || '', v => { targetObj.input_border = v; syncJson(); }, { placeholder:'e.g. #dcdcde' }));
panel.appendChild(inputRow('Radius', targetObj.input_radius || '', v => { targetObj.input_radius = v; syncJson(); }, { help:'e.g. 10px — leave blank to inherit' }));
const actions = document.createElement('div');
actions.className = 'blfs-actions';
actions.style.marginTop = '14px';
const clearBtn = document.createElement('button');
clearBtn.type = 'button';
clearBtn.className = 'secondary';
clearBtn.textContent = 'Clear overrides';
clearBtn.addEventListener('click', () => {
onClear();
syncJson();
renderPanel();
log('Cleared overrides');
});
actions.appendChild(clearBtn);
panel.appendChild(actions);
return panel;
}
/* -------------------------------------------------------------- */
/* Panel render */
/* -------------------------------------------------------------- */
function renderPanel(){
ensureDefaults();
const panel = document.getElementById('blfs-panel');
panel.innerHTML = '';
const title = document.createElement('h3');
if ( activeSection === 'FieldOverrides' && activeFieldId ) {
title.textContent = `Field Overrides: #${activeFieldId}`;
} else if ( activeSection === 'TypeOverrides' ) {
title.textContent = `Type Overrides${activeType ? ': ' + activeType : ''}`;
} else {
title.textContent = (SECTIONS.find(s => s.key === activeSection)?.label || 'Settings');
}
panel.appendChild(title);
if ( activeSection === 'Global' ) {
const note = document.createElement('div');
note.className = 'blfs-help';
note.textContent = 'Use the sections on the left to edit token groups. These apply to the entire form unless overridden by type or field.';
panel.appendChild(note);
return;
}
if ( activeSection === 'Typography' ) {
panel.appendChild(inputRow('Base font size', state.tokens.typography.base_font_size, v => { state.tokens.typography.base_font_size = v; syncJson(); }, { help:'Example: 16px or 1rem' }));
panel.appendChild(inputRow('Label font size', state.tokens.typography.label_font_size, v => { state.tokens.typography.label_font_size = v; syncJson(); }));
panel.appendChild(inputRow('Input font size', state.tokens.typography.input_font_size, v => { state.tokens.typography.input_font_size = v; syncJson(); }));
return;
}
if ( activeSection === 'Colors' ) {
panel.appendChild(inputRow('Text', state.tokens.colors.text, v => { state.tokens.colors.text = v; syncJson(); }, { placeholder:'#1d2327' }));
panel.appendChild(inputRow('Label', state.tokens.colors.label, v => { state.tokens.colors.label = v; syncJson(); }, { placeholder:'#1d2327' }));
panel.appendChild(inputRow('Choice label', state.tokens.colors.choice_label, v => { state.tokens.colors.choice_label = v; syncJson(); }, { placeholder:'#1d2327', help:'Color for radio/checkbox option text (blank = inherit label color)' }));
panel.appendChild(inputRow('Description', state.tokens.colors.description, v => { state.tokens.colors.description = v; syncJson(); }, { placeholder:'#646970' }));
panel.appendChild(inputRow('Input background', state.tokens.colors.input_bg, v => { state.tokens.colors.input_bg = v; syncJson(); }, { placeholder:'#ffffff' }));
panel.appendChild(inputRow('Input border', state.tokens.colors.input_border, v => { state.tokens.colors.input_border = v; syncJson(); }, { placeholder:'#dcdcde' }));
panel.appendChild(inputRow('Focus', state.tokens.colors.focus, v => { state.tokens.colors.focus = v; syncJson(); }, { placeholder:'#2271b1' }));
panel.appendChild(inputRow('Error', state.tokens.colors.error, v => { state.tokens.colors.error = v; syncJson(); }, { placeholder:'#d63638' }));
panel.appendChild(inputRow('Button background',state.tokens.colors.button_bg, v => { state.tokens.colors.button_bg = v; syncJson(); }, { placeholder:'#2271b1' }));
panel.appendChild(inputRow('Button text', state.tokens.colors.button_text, v => { state.tokens.colors.button_text = v; syncJson(); }, { placeholder:'#ffffff' }));
return;
}
if ( activeSection === 'Spacing' ) {
panel.appendChild(inputRow('Field margin bottom', state.tokens.spacing.field_margin_bottom, v => { state.tokens.spacing.field_margin_bottom = v; syncJson(); }, { help:'Example: 16px' }));
panel.appendChild(inputRow('Input padding', state.tokens.spacing.input_padding, v => { state.tokens.spacing.input_padding = v; syncJson(); }, { help:'Example: 10px 12px' }));
panel.appendChild(inputRow('Section padding', state.tokens.spacing.section_padding, v => { state.tokens.spacing.section_padding = v; syncJson(); }, { help:'Example: 16px' }));
return;
}
if ( activeSection === 'Borders' ) {
panel.appendChild(inputRow('Border radius', state.tokens.borders.radius, v => { state.tokens.borders.radius = v; syncJson(); }, { help:'Example: 10px' }));
panel.appendChild(inputRow('Border width', state.tokens.borders.border_width, v => { state.tokens.borders.border_width = v; syncJson(); }, { help:'Example: 1px' }));
return;
}
if ( activeSection === 'Buttons' ) {
panel.appendChild(inputRow('Button radius', state.tokens.buttons.radius, v => { state.tokens.buttons.radius = v; syncJson(); }));
panel.appendChild(inputRow('Button padding', state.tokens.buttons.padding, v => { state.tokens.buttons.padding = v; syncJson(); }, { help:'Example: 10px 14px' }));
return;
}
if ( activeSection === 'States' ) {
panel.appendChild(inputRow('Focus ring', state.tokens.states.focus_ring, v => { state.tokens.states.focus_ring = v; syncJson(); }, { help:'Example: 0 0 0 3px rgba(34,113,177,.20)' }));
panel.appendChild(inputRow('Error border', state.tokens.states.error_border, v => { state.tokens.states.error_border = v; syncJson(); }, { placeholder:'#d63638' }));
return;
}
if ( activeSection === 'TypeOverrides' ) {
if ( !activeType ) {
const note = document.createElement('div');
note.className = 'blfs-help';
note.textContent = 'Select a field type on the left, then edit overrides here.';
panel.appendChild(note);
return;
}
state.type_overrides[activeType] = state.type_overrides[activeType] || {};
panel.appendChild(renderOverrideEditor(state.type_overrides[activeType], () => {
delete state.type_overrides[activeType];
}));
return;
}
if ( activeSection === 'FieldOverrides' ) {
if ( !activeFieldId ) {
const note = document.createElement('div');
note.className = 'blfs-help';
note.textContent = 'Click a field on the left to edit overrides.';
panel.appendChild(note);
return;
}
state.field_overrides[activeFieldId] = state.field_overrides[activeFieldId] || {};
panel.appendChild(renderOverrideEditor(state.field_overrides[activeFieldId], () => {
delete state.field_overrides[activeFieldId];
}));
}
}
/* -------------------------------------------------------------- */
/* Export / Import / Reset */
/* -------------------------------------------------------------- */
document.getElementById('blfs-export').addEventListener('click', () => {
syncJson();
navigator.clipboard.writeText(jsonEditor.value)
.then(() => { alert('Exported JSON copied to clipboard.'); log('Exported JSON.'); })
.catch(() => alert('Could not copy to clipboard. Please copy manually from the JSON textarea.'));
});
document.getElementById('blfs-import').addEventListener('click', () => {
const input = prompt('Paste JSON to import:');
if ( !input ) return;
const obj = safeParse(input);
if ( !obj ) { alert('Invalid JSON. Import canceled.' ); return; }
state = obj;
syncJson();
renderPanel();
log('Imported JSON.');
});
document.getElementById('blfs-reset').addEventListener('click', () => {
if ( !confirm('Reset to factory defaults? This will overwrite your current payload.' ) ) return;
state = safeParse(BLFS_FACTORY_JSON) || {};
jsonEditor.value = pretty(state);
setHidden(jsonEditor.value);
activeSection = 'Global';
activeFieldId = null;
activeType = '';
renderNav();
renderPanel();
renderTypeSelect();
renderFieldList();
updateCssPreview();
log('Reset to defaults.');
});
/* -------------------------------------------------------------- */
/* CSS builder — mirrors PHP generate_css_from_json() exactly */
/* -------------------------------------------------------------- */
function buildOverrideCss(scopes, expand, ov, selectorSub) {
if (!ov || typeof ov !== 'object') return '';
const labelSel = expand(selectorSub + ' .gfield_label');
const inputSel = expand(selectorSub + ' input:not([type="checkbox"]):not([type="radio"]), ' + selectorSub + ' textarea, ' + selectorSub + ' select');
const choiceLabelSel = expand(selectorSub + ' .gchoice label');
const labelColor = String(ov.label_color || '').trim();
const labelSize = String(ov.label_font_size || '').trim();
const inputBg = String(ov.input_bg || '').trim();
const inputText = String(ov.input_text || '').trim();
const inputBorder = String(ov.input_border || '').trim();
const inputRadius = String(ov.input_radius || '').trim();
let css = '';
if (labelColor || labelSize) {
css += `\n${labelSel} {`;
if (labelColor) css += ` color: ${labelColor} !important;`;
if (labelSize) css += ` font-size: ${labelSize} !important;`;
css += ' }\n';
}