Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ConfigProvider) Allow duplicated classes in the body created by ConfigProvider #5633

Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useContext } from 'react';
import { render } from '@testing-library/react';
import React, { useContext, useState } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { Appearance } from '../../helpers/appearance';
import { generateVKUITokensClassName } from '../../helpers/generateVKUITokensClassName';
import { Platform } from '../../lib/platform';
import { baselineComponent } from '../../testing/utils';
import { ConfigProvider } from './ConfigProvider';
Expand Down Expand Up @@ -130,4 +131,72 @@ describe('ConfigProvider', () => {
expect(config).toEqual(expect.objectContaining({ ...defaultConfig, [prop]: value }));
});
});

it('adds VKUITokenClassName to document.body on mount and removed on unmount', async () => {
const config = { appearance: Appearance.LIGHT, platform: Platform.VKCOM };
const ConfigUser = () => {
return null;
};
const { unmount } = render(
<ConfigProvider {...config}>
<ConfigUser />
</ConfigProvider>,
);

const vkuiBodySelector = generateVKUITokensClassName(config.platform, config.appearance);

expect(document.querySelector(`body.${vkuiBodySelector}`)).toBeTruthy();

unmount();

// removed on unmount
expect(document.querySelector(`body.${vkuiBodySelector}`)).toBeFalsy();
});

it('adds VKUITokenClassName to document.body on mount and not removes if child ConfigProvider is unmounted', async () => {
const config = { appearance: Appearance.LIGHT, platform: Platform.VKCOM };
const ConfigUser = () => {
return <div>User config</div>;
};

const ConfigUserWithOwnProvider = () => {
return (
<ConfigProvider {...config}>
<ConfigUser />
</ConfigProvider>
);
};

const TestComponent = () => {
const [isMounted, setIsMounted] = useState(true);

return (
<ConfigProvider {...config}>
<div>
<button onClick={() => setIsMounted(false)}>Unmount child context</button>
{isMounted && <ConfigUserWithOwnProvider />}
</div>
</ConfigProvider>
);
};

const { unmount } = render(<TestComponent />);

const vkuiBodySelector = generateVKUITokensClassName(config.platform, config.appearance);

// class name is applied to body
expect(document.querySelector(`body.${vkuiBodySelector}`)).toBeTruthy();

// unmount child ConfigProvider
fireEvent.click(screen.getByRole('button'));

// class from body is not removed on unmount of child context
expect(document.querySelector(`body.${vkuiBodySelector}`)).toBeTruthy();

// unmount parent context as well
unmount();

// when last context that is using this class is unmounted the class is removed from body
expect(document.querySelector(`body.${vkuiBodySelector}`)).toBeFalsy();
});
});
24 changes: 15 additions & 9 deletions packages/vkui/src/components/ConfigProvider/ConfigProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useObjectMemo } from '../../hooks/useObjectMemo';
import { useDOM } from '../../lib/dom';
import { TokensClassProvider } from '../../lib/tokensClassProvider';
import { useIsomorphicLayoutEffect } from '../../lib/useIsomorphicLayoutEffect';
import { addClassNameToElement, removeClassNameFromElement } from '../../lib/utils';
import { warnOnce } from '../../lib/warnOnce';
import {
ConfigProviderContext,
Expand Down Expand Up @@ -80,17 +81,22 @@ ${webviewTypeRule}

const { document } = useDOM();

useIsomorphicLayoutEffect(() => {
const VKUITokensClassName = generateVKUITokensClassName(platform, appearance);
// TODO [>=6]: переместить хук в AppRoot (см. https://github.com/VKCOM/VKUI/issues/4810).
useIsomorphicLayoutEffect(
function attachVKUITokensClassNameToBody() {
if (!document) {
return;
mendrew marked this conversation as resolved.
Show resolved Hide resolved
}

// eslint-disable-next-line no-restricted-properties
document!.body.classList.add(VKUITokensClassName);
const VKUITokensClassName = generateVKUITokensClassName(platform, appearance);

return () => {
// eslint-disable-next-line no-restricted-properties
document!.body.classList.remove(VKUITokensClassName);
};
}, [platform, appearance]);
addClassNameToElement(document.body, VKUITokensClassName);
return () => {
removeClassNameFromElement(document.body, VKUITokensClassName);
};
},
[platform, appearance],
);

const configContext = useObjectMemo({
webviewType,
Expand Down
49 changes: 49 additions & 0 deletions packages/vkui/src/lib/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { addClassNameToElement, removeClassNameFromElement } from './utils';

Check failure on line 1 in packages/vkui/src/lib/utils.test.ts

View workflow job for this annotation

GitHub Actions / Report CI results

removeClassNameFromElement > removes className from element

Error: expect(received).toEqual(expected) // deep equality Expected: "b-class a-class a-class" Received: "a-class b-class a-class" at Object.toEqual (/home/runner/work/VKUI/VKUI/packages/vkui/src/lib/utils.test.ts:32:39) at Promise.then.completed (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/utils.js:300:28) at new Promise (<anonymous>) at callAsyncCircusFn (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/utils.js:233:10) at _callCircusTest (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/run.js:315:40) at _runTest (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/run.js:251:3) at _runTestsForDescribeBlock (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/run.js:125:9) at _runTestsForDescribeBlock (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/run.js:120:9) at run (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/run.js:70:3) at runAndTransformResultsToJestFormat (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:122:21) at jestAdapter (/home/runner/work/VKUI/VKUI/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js:79:19) at runTestInternal (/home/runner/work/VKUI/VKUI/node_modules/jest-runner/build/runTest.js:367:16) at runTest (/home/runner/work/VKUI/VKUI/node_modules/jest-runner/build/runTest.js:444:34)

describe('addClassNameToElement', () => {
test('adds className to element', () => {
const div = document.createElement('div');
addClassNameToElement(div, 'a-class');

expect(div.getAttribute('class')).toEqual('a-class');

// allows to add duplicated class name
addClassNameToElement(div, 'a-class');
expect(div.getAttribute('class')).toEqual('a-class a-class');

addClassNameToElement(div, 'b-class');
expect(div.getAttribute('class')).toEqual('a-class a-class b-class');
});
});

describe('removeClassNameFromElement', () => {
test('removes className from element', () => {
const div = document.createElement('div');
div.setAttribute('class', 'a-class');

removeClassNameFromElement(div, 'a-class');
expect(div.getAttribute('class')).toEqual('');

// allows to remove duplicated class name
div.setAttribute('class', 'a-class b-class a-class');

// remove not existing class
removeClassNameFromElement(div, 'unknown-class');
expect(div.getAttribute('class')).toEqual('b-class a-class a-class');

removeClassNameFromElement(div, 'a-class');
expect(div.getAttribute('class')).toEqual('b-class a-class');

// allows to remove duplicated class name
div.setAttribute('class', 'a-class b-class a-class');

removeClassNameFromElement(div, 'b-class');
expect(div.getAttribute('class')).toEqual('a-class a-class');

removeClassNameFromElement(div, 'a-class');
expect(div.getAttribute('class')).toEqual('a-class');

removeClassNameFromElement(div, 'a-class');
expect(div.getAttribute('class')).toEqual('');
});
SevereCloud marked this conversation as resolved.
Show resolved Hide resolved
});
20 changes: 20 additions & 0 deletions packages/vkui/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,23 @@ export function getTitleFromChildren(children: React.ReactNode): string {

export const stopPropagation = <T extends React.SyntheticEvent>(event: T) =>
event.stopPropagation();

export function addClassNameToElement(element: HTMLElement, className: string) {
const elementClassName = element.getAttribute('class') || '';
const updatedClassName = `${elementClassName}${elementClassName ? ' ' : ''}${className}`;

element.setAttribute('class', updatedClassName);
}

export function removeClassNameFromElement(element: HTMLElement, classNameToRemove: string) {
const classNamesArray = (element.getAttribute('class') || '').split(/\s+/);
const elementIndexToRemove = classNamesArray.findIndex(
(className) => className === classNameToRemove,
);
if (elementIndexToRemove === -1) {
return;
}
classNamesArray.splice(elementIndexToRemove, 1);

element.setAttribute('class', classNamesArray.join(' '));
}
Loading