foundation.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import { Motion } from '../utils/type';
  3. export type ArgsType<T> = T extends (...args: infer A) => any ? A : never;
  4. export interface CollapseProps{
  5. activeKey?: string | string[];
  6. defaultActiveKey?: string | string[];
  7. accordion?: boolean;
  8. onChange?: (activeKey: CollapseProps['activeKey'], e: any) => void;
  9. expandIcon?: any;
  10. collapseIcon?: any;
  11. style?: any;
  12. className?: string;
  13. keepDOM?: boolean;
  14. motion?: Motion;
  15. expandIconPosition?: 'left' | 'right';
  16. }
  17. export interface CollapseState{
  18. activeSet: Set<string>;
  19. }
  20. export interface CollapseAdapter extends DefaultAdapter<CollapseProps, CollapseState>{
  21. handleChange: (...args: ArgsType<CollapseProps['onChange']>) => ReturnType<CollapseProps['onChange']>;
  22. // getStates: () => CollapseState;
  23. // getProps: () => CollapseProps;
  24. addActiveKey: (newSet: CollapseState['activeSet']) => void;
  25. }
  26. export default class CollapseFoundation extends BaseFoundation<CollapseAdapter> {
  27. constructor(adapter: CollapseAdapter) {
  28. super({
  29. ...adapter
  30. });
  31. }
  32. initActiveKey() {
  33. const {
  34. defaultActiveKey,
  35. activeKey,
  36. accordion
  37. } = this.getProps();
  38. let activeKeyList = activeKey ? activeKey : defaultActiveKey;
  39. if (accordion) {
  40. activeKeyList = Array.isArray(activeKeyList) ? activeKeyList[0] : activeKeyList;
  41. }
  42. if (activeKeyList && activeKeyList.length) {
  43. activeKeyList = Array.isArray(activeKeyList) ? activeKeyList : [activeKeyList];
  44. return activeKeyList;
  45. }
  46. return [];
  47. // this._adapter.initActiveSet(activeKeyList);
  48. }
  49. handleChange(newKey: string, e: any) {
  50. const {
  51. activeKey,
  52. accordion
  53. } = this.getProps();
  54. const {
  55. activeSet
  56. } = this.getStates();
  57. let newSet = new Set(activeSet) as CollapseState['activeSet'];
  58. if (newSet.has(newKey)) {
  59. newSet.delete(newKey);
  60. } else {
  61. if (accordion) {
  62. newSet = new Set([newKey]);
  63. } else {
  64. newSet.add(newKey);
  65. }
  66. }
  67. this._adapter.handleChange([...newSet.values()], e);
  68. if (typeof activeKey === 'undefined') {
  69. this._adapter.addActiveKey(newSet);
  70. }
  71. }
  72. }