checkboxGroupFoundation.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import warning from '../utils/warning';
  3. import { BasicCheckboxEvent } from './checkboxFoundation';
  4. export interface CheckboxGroupAdapter extends DefaultAdapter{
  5. updateGroupValue: (value: any[]) => void;
  6. notifyChange: (value: any[]) => void;
  7. }
  8. class CheckboxGroupFoundation extends BaseFoundation<CheckboxGroupAdapter> {
  9. static get checkboxGroupdefaultAdapter() {
  10. return {};
  11. }
  12. constructor(adapter: CheckboxGroupAdapter) {
  13. super({ ...CheckboxGroupFoundation.checkboxGroupdefaultAdapter, ...adapter });
  14. }
  15. init() {
  16. const { defaultValue, value } = this.getProps();
  17. if (typeof defaultValue !== 'undefined' && !Array.isArray(defaultValue)) {
  18. warning(true, 'Warning: [Semi CheckboxGroup] defaultValue should be an Array');
  19. }
  20. if (typeof value !== 'undefined' && !Array.isArray(value)) {
  21. warning(true, 'Warning: [Semi CheckboxGroup] value should be an Array');
  22. }
  23. }
  24. notifyChange(value: any[]) {
  25. this._adapter.notifyChange(value);
  26. }
  27. handleChange(evt: BasicCheckboxEvent) {
  28. const prevValue: any[] = this.getState('value');
  29. let newValue = [];
  30. if (!Array.isArray(prevValue)) {
  31. newValue = [prevValue];
  32. }
  33. if (evt.target.checked) {
  34. newValue = [...prevValue, evt.target.value];
  35. } else {
  36. newValue = prevValue.filter((itm, idx) => itm !== evt.target.value);
  37. }
  38. const isControlledMode = 'value' in this.getProps();
  39. if (isControlledMode) {
  40. // Controlled mode only needs to notify
  41. this.notifyChange(newValue);
  42. } else {
  43. // In uncontrolled mode, update the value in the state, and then notify
  44. this._adapter.updateGroupValue(newValue);
  45. this.notifyChange(newValue);
  46. }
  47. }
  48. getFormatName() {
  49. const propName = this.getProp('name');
  50. const defaultName = 'default';
  51. return propName || defaultName;
  52. }
  53. handlePropValueChange(newPropValue: any[]) {
  54. if (Array.isArray(newPropValue)) {
  55. this._adapter.updateGroupValue(newPropValue);
  56. } else {
  57. // to adjust reset in Form.CheckboxGroup
  58. if (typeof newPropValue === 'undefined') {
  59. this._adapter.updateGroupValue([]);
  60. }
  61. warning(true, 'Warning: [Semi CheckboxGroup] value should be an Array');
  62. }
  63. }
  64. // eslint-disable-next-line @typescript-eslint/no-empty-function
  65. destroy() {}
  66. }
  67. export default CheckboxGroupFoundation;