foundation.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import { noop } from 'lodash';
  3. export interface TabsAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  4. collectPane: () => void;
  5. collectActiveKey: () => void;
  6. notifyTabClick: (activeKey: string, event: any) => void;
  7. notifyChange: (activeKey: string) => void;
  8. setNewActiveKey: (activeKey: string) => void;
  9. getDefaultActiveKeyFromChildren: () => string;
  10. notifyTabDelete: (tabKey: string) => void;
  11. }
  12. class TabsFoundation<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<TabsAdapter<P, S>, P, S> {
  13. constructor(adapter: TabsAdapter<P, S>) {
  14. super({ ...adapter });
  15. }
  16. init(): void {
  17. this._adapter.collectPane();
  18. }
  19. destroy = noop;
  20. _notifyChange(activeKey: string): void {
  21. const { activeKey: stateActiveKey } = this.getStates();
  22. if (stateActiveKey !== activeKey) {
  23. this._adapter.notifyChange(activeKey);
  24. }
  25. }
  26. handleTabClick(activeKey: string, event: any): void {
  27. const isControlledComponent = this._isInProps('activeKey');
  28. if (isControlledComponent) {
  29. this._notifyChange(activeKey);
  30. } else {
  31. this._notifyChange(activeKey);
  32. this.handleNewActiveKey(activeKey);
  33. }
  34. this._adapter.notifyTabClick(activeKey, event);
  35. }
  36. handleNewActiveKey(activeKey: string): void {
  37. const { activeKey: stateActiveKey } = this.getStates();
  38. if (stateActiveKey !== activeKey) {
  39. this._adapter.setNewActiveKey(activeKey);
  40. }
  41. }
  42. getDefaultActiveKey(): string {
  43. let activeKey;
  44. const props = this.getProps();
  45. if ('activeKey' in props) {
  46. activeKey = props.activeKey;
  47. } else if ('defaultActiveKey' in props) {
  48. activeKey = props.defaultActiveKey;
  49. } else {
  50. activeKey = this._adapter.getDefaultActiveKeyFromChildren();
  51. }
  52. return activeKey;
  53. }
  54. handleTabListChange(): void {
  55. this._adapter.collectPane();
  56. }
  57. handleTabPanesChange(): void {
  58. this._adapter.collectPane();
  59. this._adapter.collectActiveKey();
  60. }
  61. handleTabDelete(tabKey: string): void {
  62. this._adapter.notifyTabDelete(tabKey);
  63. }
  64. }
  65. export default TabsFoundation;