foundation.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. export interface SwitchAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  3. setNativeControlChecked: (nativeControlChecked: boolean | undefined) => void;
  4. setNativeControlDisabled: (nativeControlDisabled: boolean | undefined) => void;
  5. notifyChange: (checked: boolean, e: any) => void;
  6. }
  7. export default class SwitchFoundation<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<SwitchAdapter<P, S>, P, S> {
  8. constructor(adapter: SwitchAdapter<P, S>) {
  9. super({ ...adapter });
  10. }
  11. init(): void {
  12. const { defaultChecked, checked, disabled } = this.getProps();
  13. this.setChecked(defaultChecked || checked);
  14. this.setDisabled(disabled);
  15. }
  16. setChecked(checked: boolean | undefined): void {
  17. this._adapter.setNativeControlChecked(checked);
  18. }
  19. setDisabled(disabled: boolean | undefined): void {
  20. this._adapter.setNativeControlDisabled(disabled);
  21. }
  22. handleChange(checked: boolean, e: any): void {
  23. const propChecked = this.getProps().checked;
  24. const isControledComponent = typeof propChecked !== 'undefined';
  25. if (isControledComponent) {
  26. this._adapter.notifyChange(checked, e);
  27. } else {
  28. this._adapter.setNativeControlChecked(checked);
  29. this._adapter.notifyChange(checked, e);
  30. }
  31. }
  32. // eslint-disable-next-line @typescript-eslint/no-empty-function
  33. destroy(): void {}
  34. }