Skip to content

Commit

Permalink
EuiValidatableControl convert to TS
Browse files Browse the repository at this point in the history
  • Loading branch information
Theo committed Apr 24, 2019
1 parent c49a998 commit 9f371a2
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 56 deletions.
3 changes: 0 additions & 3 deletions src/components/form/validatable_control/index.js

This file was deleted.

1 change: 1 addition & 0 deletions src/components/form/validatable_control/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { EuiValidatableControl } from './validatable_control';
51 changes: 0 additions & 51 deletions src/components/form/validatable_control/validatable_control.js

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ describe('EuiValidatableControl', () => {
</EuiValidatableControl>
);

expect(component)
.toMatchSnapshot();
expect(component).toMatchSnapshot();
});
});
73 changes: 73 additions & 0 deletions src/components/form/validatable_control/validatable_control.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import {
Children,
cloneElement,
Component,
ReactElement,
ReactNode,
} from 'react';
import { CommonProps } from '../../common';

export type HTMLConstraintValidityElement =
| HTMLButtonElement
| HTMLFieldSetElement
| HTMLInputElement
| HTMLObjectElement
| HTMLOutputElement
| HTMLSelectElement
| HTMLTextAreaElement
| Element & { setCustomValidity?: any };

export type EuiNodeWithRef = ReactNode & {
ref?: (node: ReactNode) => void;
};

export interface EuiValidatableControlProps {
isInvalid?: boolean;
children?: EuiNodeWithRef;
}

export class EuiValidatableControl extends Component<
CommonProps & EuiValidatableControlProps
> {
private control?: HTMLConstraintValidityElement;

updateValidity() {
if (
this.control == null ||
typeof this.control.setCustomValidity !== 'function'
) {
return; // jsdom doesn't polyfill this for the server-side
}

if (this.props.isInvalid) {
this.control.setCustomValidity('Invalid');
} else {
this.control.setCustomValidity('');
}
}

componentDidMount() {
this.updateValidity();
}

componentDidUpdate() {
this.updateValidity();
}

setRef = (node: HTMLConstraintValidityElement) => {
this.control = node;

// Call the original ref, if any
const { ref } = this.props.children as EuiNodeWithRef;
if (typeof ref === 'function') {
ref(node);
}
};

render() {
const child = Children.only(this.props.children);
return cloneElement(child as ReactElement<any>, {
ref: this.setRef,
});
}
}

0 comments on commit 9f371a2

Please sign in to comment.