|
| 1 | +import * as React from "react"; |
| 2 | +import { FieldValue } from "simplr-forms/contracts"; |
| 3 | +import { DomFieldProps } from "../contracts/field"; |
| 4 | + |
| 5 | +import { BaseDomField, BaseDomFieldState } from "../abstractions/base-dom-field"; |
| 6 | +import { FieldOnChangeCallback } from "../contracts/field"; |
| 7 | +import { |
| 8 | + HTMLElementProps |
| 9 | +} from "../contracts/field"; |
| 10 | +import { |
| 11 | + FormProps |
| 12 | +} from "../contracts/form"; |
| 13 | + |
| 14 | +export type CheckBoxOnChangeCallback = FieldOnChangeCallback<HTMLInputElement>; |
| 15 | + |
| 16 | +/** |
| 17 | + * Override the differences between extended interfaces. |
| 18 | + */ |
| 19 | +export interface CheckBoxProps extends DomFieldProps, HTMLElementProps<HTMLInputElement> { |
| 20 | + name: string; |
| 21 | + onFocus?: React.FocusEventHandler<HTMLInputElement>; |
| 22 | + onBlur?: React.FocusEventHandler<HTMLInputElement>; |
| 23 | + onChange?: CheckBoxOnChangeCallback; |
| 24 | + |
| 25 | + defaultValue?: boolean; |
| 26 | + initialValue?: boolean; |
| 27 | + value?: boolean; |
| 28 | + ref?: React.Ref<CheckBox>; |
| 29 | +} |
| 30 | + |
| 31 | +export class CheckBox extends BaseDomField<CheckBoxProps, BaseDomFieldState, HTMLInputElement> { |
| 32 | + protected GetValueFromEvent(event: React.ChangeEvent<HTMLInputElement>): FieldValue { |
| 33 | + return event.currentTarget.checked; |
| 34 | + } |
| 35 | + |
| 36 | + protected OnChangeHandler: React.ChangeEventHandler<HTMLInputElement> = (event) => { |
| 37 | + this.OnValueChange(this.GetValueFromEvent(event)); |
| 38 | + |
| 39 | + const newValue = this.FormStore.GetField(this.FieldId).Value; |
| 40 | + |
| 41 | + if (this.props.onChange != null) { |
| 42 | + event.persist(); |
| 43 | + this.props.onChange(event, newValue, this.FieldId, this.FormId); |
| 44 | + } |
| 45 | + |
| 46 | + const formStoreState = this.FormStore.GetState(); |
| 47 | + const formProps = formStoreState.Form.Props as FormProps; |
| 48 | + if (formProps.onChange != null) { |
| 49 | + event.persist(); |
| 50 | + formProps.onChange(event, newValue, this.FieldId, this.FormId); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + protected get RawDefaultValue(): boolean { |
| 55 | + if (this.props.defaultValue != null) { |
| 56 | + return this.props.defaultValue; |
| 57 | + } |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + renderField(): JSX.Element | null { |
| 62 | + return <input |
| 63 | + ref={this.SetElementRef} |
| 64 | + type="checkbox" |
| 65 | + name={this.FieldId} |
| 66 | + checked={this.Value} |
| 67 | + onChange={this.OnChangeHandler} |
| 68 | + disabled={this.Disabled} |
| 69 | + onFocus={this.OnFocus} |
| 70 | + onBlur={this.OnBlur} |
| 71 | + {...this.GetHTMLProps(this.props) } |
| 72 | + />; |
| 73 | + } |
| 74 | +} |
0 commit comments