1+ import Checkbox from "./field/checkbox" ;
2+ import NullField from "./field/nullField" ;
3+
4+ class FieldBuilder implements FieldBuilderInterface {
5+ private name : string = 'data-js-field-name' ;
6+ private condition : string = 'data-js-conditional-logic' ;
7+
8+ constructor ( private conditionBuilder : ConditionBuilderInterface ) {
9+ }
10+
11+ public build ( field : HTMLElement , type : string ) : FieldInterface {
12+ if ( ! this . validateRequiredAttributes ( field ) ) {
13+ console . error ( 'Field name and conditional is required' ) ;
14+ return this . buildNullField ( field , type ) ;
15+ }
16+
17+ switch ( type ) {
18+ case 'checkbox' :
19+ return this . buildCheckbox ( field ) ;
20+ }
21+
22+ return this . buildNullField ( field , type ) ;
23+ }
24+
25+ public buildNullField ( field : HTMLElement , type : string ) : FieldInterface {
26+ return new NullField (
27+ field ,
28+ type ,
29+ this . getFieldName ( field ) ,
30+ this . getFieldCondition ( field )
31+ ) ;
32+ }
33+
34+ public buildCheckbox ( field : HTMLElement ) : FieldInterface {
35+ const choices = field . querySelectorAll ( 'input[type="checkbox"]' ) ;
36+
37+
38+ return new Checkbox (
39+ field ,
40+ choices as NodeListOf < HTMLInputElement > ,
41+ this . getFieldName ( field ) ,
42+ this . getFieldCondition ( field )
43+ ) ;
44+ }
45+
46+ private getFieldName ( field : HTMLElement ) : string {
47+ return field . getAttribute ( 'data-js-field-name' ) as string ;
48+ }
49+
50+ private getFieldCondition ( field : HTMLElement ) : ConditionInterface [ ] {
51+ let condition = 0 ;
52+
53+ try {
54+ condition = JSON . parse ( field . getAttribute ( 'data-js-conditional-logic' ) as string ) ;
55+ } catch ( error ) {
56+ condition = 0 ;
57+ }
58+
59+ return this . conditionBuilder . build ( condition ) ;
60+ }
61+
62+ private validateRequiredAttributes ( field : HTMLElement ) : boolean {
63+ [ this . name , this . condition ] . forEach ( ( attribute ) => {
64+ if ( ! field . getAttribute ( attribute ) ) {
65+ console . error ( `Field is missing required attribute: ${ attribute } ` ) ;
66+ return false ;
67+ }
68+ } ) ;
69+
70+ return true ;
71+ }
72+ }
73+
74+ export default FieldBuilder ;
0 commit comments