foundation.ts 2.4 KB

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