Skip to content

Commit

Permalink
fix(Snackbar/AppRootPortal): fix default shouldDisablePortalLogic in …
Browse files Browse the repository at this point in the history
…AppRootPortal (#6389)

В рефакторинге AppRootPortal в c7e4c41 мы инверсировали логику использования портала и там закралась ошибка в значении по умолчанию. До рефакторинга мы использовали портал если `mode !== 'full'`, 
https://github.com/VKCOM/VKUI/blob/7f1888d54ca8fb08a0a8d8d3697f0a19ccab6d19/packages/vkui/src/components/AppRoot/AppRootPortal.tsx#L35-L42

а теперь выключаем портал если `mode !== 'full'`.
https://github.com/VKCOM/VKUI/blob/959611e24e6168643ff409d8db08a585825d030f/packages/vkui/src/components/AppRoot/AppRootPortal.tsx#L38-L51

Эта ошибка повлекла за собой по крайней мере неверное позиционирование Snackbar, когда речь идёт о Snackbar + Tabbar у Epic в режиме миниапов (`mode="full"`). Snackbar рендерился используя портал, тем самым выпадая из селектора, задающего отступ.

Возможно, что нам тут даже не стоит полагаться на селектор вовсе и читать информацию о наличии tabbar из контекста, определяя размер экрана в котором tabbar рендерится внизу. В то же время Epic это больше о мобильных экранах.
Тем не менее ошибка в AppRootPortal есть.

Изменения
- Поправил условие для режима `full` по умолчанию. Покрыл тестами.
- обернул children в React.Fragment чтобы ts не ругался на типы AppRootPortal.
```
'AppRootPortal' cannot be used as a JSX component.
Its return type 'ReactNode' is not a valid JSX element. (tsserver 2786)
```
  • Loading branch information
mendrew authored Jan 29, 2024
1 parent 6b88aa6 commit 2fb0272
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 2 deletions.
77 changes: 77 additions & 0 deletions packages/vkui/src/components/AppRoot/AppRootPortal.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import * as React from 'react';
import { render, screen } from '@testing-library/react';
import { AppRoot, type AppRootProps } from './AppRoot';
import { AppRootPortal, type AppRootPortalProps } from './AppRootPortal';

function TestComponent({
appRootProps = {},
usePortal,
}: {
appRootProps?: AppRootProps;
usePortal?: AppRootPortalProps['usePortal'];
} = {}) {
const portalRootRef = React.useRef<HTMLDivElement | null>(null);

return (
<AppRoot portalRoot={portalRootRef} {...appRootProps}>
<AppRootPortal usePortal={usePortal}>
<div>content</div>
</AppRootPortal>
<div data-testid="portal-root" ref={portalRootRef} />
</AppRoot>
);
}

describe('AppRootPortal', () => {
it('does not use portal by default in full mode', () => {
render(<TestComponent appRootProps={{ mode: 'full' }} />);

expect(screen.getByTestId('portal-root').childElementCount).toBe(0);
});

it('uses portal in embedded mode', () => {
render(<TestComponent appRootProps={{ mode: 'embedded' }} />);

expect(screen.getByTestId('portal-root').childElementCount).toBe(1);
});

it('uses portal in partial mode', () => {
render(<TestComponent appRootProps={{ mode: 'partial' }} />);

expect(screen.getByTestId('portal-root').childElementCount).toBe(1);
});

it('does not use portal when portal is disabled in AppRoot', () => {
render(<TestComponent appRootProps={{ mode: 'partial', disablePortal: true }} />);

expect(screen.getByTestId('portal-root').childElementCount).toBe(0);
});

it('does not use portal when usePortal is false', () => {
render(<TestComponent appRootProps={{ mode: 'partial' }} usePortal={false} />);

expect(screen.getByTestId('portal-root').childElementCount).toBe(0);
});

it('uses portal in full mode when usePortal is true', () => {
render(<TestComponent appRootProps={{ mode: 'full' }} usePortal />);

expect(screen.getByTestId('portal-root').childElementCount).toBe(1);
});

it('uses portal passed via usePortal prop', () => {
const Wrapper = function Wrapper() {
const customPortalRef = React.useRef<HTMLDivElement | null>(null);
return (
<React.Fragment>
<TestComponent usePortal={customPortalRef} />
<div data-testid="custom-portal" ref={customPortalRef} />
</React.Fragment>
);
};
render(<Wrapper />);

expect(screen.getByTestId('portal-root').childElementCount).toBe(0);
expect(screen.getByTestId('custom-portal').childElementCount).toBe(1);
});
});
4 changes: 2 additions & 2 deletions packages/vkui/src/components/AppRoot/AppRootPortal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const AppRootPortal = ({ children, usePortal }: AppRootPortalProps) => {

const portalContainer = resolvePortalContainer(usePortal, portalRoot.current);
if (!portalContainer || shouldDisablePortal(usePortal, mode, Boolean(disablePortal))) {
return children;
return <React.Fragment>{children}</React.Fragment>;
}

return createPortal(
Expand All @@ -47,7 +47,7 @@ function shouldDisablePortal(
return disablePortal || usePortal !== true;
}
// fallback
return disablePortal || mode !== 'full';
return disablePortal || mode === 'full';
}

function resolvePortalContainer<PortalRootFromContext extends HTMLElement | null | undefined>(
Expand Down

0 comments on commit 2fb0272

Please sign in to comment.