foundation.ts 2.4 KB

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