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

Fixed a bug in the Swiper and Section components using hooks. #843

Merged
merged 8 commits into from
Oct 11, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ clean:
find . -name "*debug.log" -type f -delete;
lerna clean --yes;
rm -rf ./node_modules/;
rm -rf ./.cache-loader/;
node ./scripts/init-subtrees.js;
lerna bootstrap;

Expand Down
2 changes: 1 addition & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = (api) => {
api.cache(api.env('test'));
api.cache(true);

return {
extends: './themes/theme-gmd/babel.config.js',
Expand Down
2 changes: 1 addition & 1 deletion extensions/@shopgate-theme-config/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
"lodash": "^4.17.4"
},
"peerDependencies": {
"@shopgate/pwa-common": "6.7.1"
"@shopgate/pwa-common": "^6.7.1"
}
}
13 changes: 1 addition & 12 deletions libraries/common/components/Swiper/index.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'react-id-swiper/lib/styles/css/swiper.css';
import React, { useRef, useEffect } from 'react';
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import cls from 'classnames';
import IDSwiper from 'react-id-swiper';
Expand Down Expand Up @@ -128,17 +128,6 @@ const Swiper = (props) => {
allowSlideNext: !disabled,
};

useEffect(() => {
if (swiperInstance.current !== null && params.rebuildOnUpdate === false) {
if (loop) {
// Recreate the loop on prop updates to avoid duplicated slides from the last slide set.
swiperInstance.current.loopCreate();
}

swiperInstance.current.update();
}
}, [children]);

return (
<div className={cls(container, className)} aria-hidden={ariaHidden}>
<IDSwiper {...params} {...additionalParams}>
Expand Down
1 change: 1 addition & 0 deletions libraries/common/components/Swiper/styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const innerContainer = css({
height: 'auto',
},
' .swiper-pagination': {
transform: 'translate3d(-50%,0,0) !important',
' .swiper-pagination-bullet': {
background: '#808080',
opacity: '.5',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,11 @@ exports[`<Section /> should render hidden when no children rendered 1`] = `
title="my.headline"
titleParams={Object {}}
>
<section
aria-labelledby="my-headline"
className="css-gyrv08"
>
<h1
hidden={true}
id="my-headline"
>
<Translate
params={Object {}}
string="my.headline"
>
my.headline
</Translate>
</h1>
</section>
<section />
</Section>
`;

exports[`<Section /> should render visible 1`] = `
exports[`<Section /> should render with a label 1`] = `
<Section
className={null}
title="my.headline"
Expand All @@ -37,9 +22,8 @@ exports[`<Section /> should render visible 1`] = `
>
<section
aria-labelledby="my-headline"
className=""
>
<h1
<h2
hidden={true}
id="my-headline"
>
Expand All @@ -53,7 +37,7 @@ exports[`<Section /> should render visible 1`] = `
>
my.headline
</Translate>
</h1>
</h2>
<div
id="child-component"
/>
Expand Down
41 changes: 13 additions & 28 deletions libraries/engage/a11y/components/Section/__tests__/index.spec.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,6 @@
/* eslint-disable require-jsdoc, extra-rules/potential-point-free,
class-methods-use-this, extra-rules/no-single-line-objects */
import React from 'react';
import { mount } from 'enzyme';
import Section from '../index';
import { hidden } from '../style';

const mutationConstructorSpy = jest.fn();
const mutationObserveSpy = jest.fn();
const mutationDisconnectSpy = jest.fn();

global.MutationObserver = class {
constructor(callback) { mutationConstructorSpy(callback); }

observe(element, initObject) { mutationObserveSpy(element, initObject); }

disconnect() { mutationDisconnectSpy(); }
};

const mockTranslate = jest.fn();

Expand All @@ -36,23 +21,26 @@ describe('<Section />', () => {
jest.clearAllMocks();
});

it('should render visible', () => {
it('should render with a label', () => {
const wrapper = mount((
<Section title={title} titleParams={titleParams}>
<div id="child-component" />
</Section>
));

expect(wrapper).toMatchSnapshot();
expect(wrapper.find('section').hasClass(hidden.toString())).toBe(false);
expect(mockTranslate).toHaveBeenCalledWith({ string: title, params: titleParams });
expect(wrapper.find('h2').exists()).toBe(true);
expect(mockTranslate).toHaveBeenCalledWith({
string: title,
params: titleParams,
});
});

it('should render hidden when no children rendered', () => {
const wrapper = mount(<Section title={title} />);
expect(wrapper).toMatchSnapshot();
expect(wrapper.find('section').hasClass(hidden.toString())).toBe(true);
expect(mockTranslate).toHaveBeenCalledWith({ string: title, params: {} });
expect(wrapper.find('h2').exists()).toBe(false);
expect(mockTranslate).toHaveBeenCalledTimes(0);
});

describe('MutationObserver', () => {
Expand All @@ -63,13 +51,13 @@ describe('<Section />', () => {
});

it('should create an observer instance', () => {
expect(mutationConstructorSpy).toHaveBeenCalledTimes(1);
expect(mutationConstructorSpy).toHaveBeenCalledWith(expect.any(Function));
expect(global.mutationConstructorSpy).toHaveBeenCalledTimes(1);
expect(global.mutationConstructorSpy).toHaveBeenCalledWith(expect.any(Function));
});

it('should observe with the correct initialization', () => {
expect(mutationObserveSpy).toHaveBeenCalledTimes(1);
expect(mutationObserveSpy).toHaveBeenCalledWith(
expect(global.mutationObserveSpy).toHaveBeenCalledTimes(1);
expect(global.mutationObserveSpy).toHaveBeenCalledWith(
wrapper.find('section').instance(),
{
childList: true,
Expand All @@ -79,10 +67,7 @@ describe('<Section />', () => {

it('should call disconnect on unmount', () => {
wrapper.unmount();
expect(mutationDisconnectSpy).toHaveBeenCalledTimes(1);
expect(global.mutationDisconnectSpy).toHaveBeenCalledTimes(1);
});
});
});

/* eslint-enable require-jsdoc, extra-rules/potential-point-free,
class-methods-use-this, extra-rules/no-single-line-objects */
38 changes: 21 additions & 17 deletions libraries/engage/a11y/components/Section/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import React, {
useRef, useState, useMemo, useLayoutEffect,
} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import kebabCase from 'lodash/kebabCase';
import { I18n } from '@shopgate/engage/components';
import { hidden } from './style';

/**
* Checks the section ref has suitable child nodes.
Expand All @@ -31,22 +29,24 @@ const hasChildNodes = (ref, headlineId) => {
* The Section component is supposed to be used to structure the content to improve a11y. It
* renders a headline on top which is only visible for screen readers and describes the section.
* Internally a MutationObserver maintains the visibility based on the presence of rendered content.
* @param {string} title The section title - can be a translation placeholder.
* @param {Object} [titleParams={}] Additional parameters for the title translation placeholder.
* @param {Object} [className=null] A class name for the section.
* @param {NodeList} [children=null] Component children.
* @param {Object} props The component props.
* @param {string} props.title The section title - can be a placeholder.
* @param {Object} [props.titleParams={}] Additional parameters for the title placeholder.
* @param {Object} [props.className=null] A class name for the section.
* @param {NodeList} [props.children=null] Component children.
* @returns {JSX}
*/
const Section = ({
title, titleParams, children, className, ...rest
}) => {
function Section(props) {
const {
title, titleParams, children, className, ...rest
} = props;
const contentRef = useRef(null);
const [hasContent, setHasContent] = useState(false);
const id = useMemo(() => kebabCase(title), [title]);

const observer = useMemo(() => new MutationObserver(() => {
setHasContent(hasChildNodes(contentRef, id));
}));
}), [contentRef, id]);

useLayoutEffect(() => {
setHasContent(hasChildNodes(contentRef, id));
Expand All @@ -57,19 +57,23 @@ const Section = ({
};
}, [contentRef, id, observer]);

const classes = classNames(className, {
[hidden]: !hasContent,
});
if (!hasContent) {
return (
<section {...rest} ref={contentRef}>
{children}
</section>
);
}

return (
<section {...rest} ref={contentRef} className={classes} aria-labelledby={id}>
<h1 id={id} hidden>
<section {...rest} ref={contentRef} aria-labelledby={id}>
<h2 id={id} hidden>
<I18n.Text string={title} params={titleParams} />
</h1>
</h2>
{children}
</section>
);
};
}

Section.propTypes = {
title: PropTypes.string.isRequired,
Expand Down
5 changes: 0 additions & 5 deletions libraries/engage/a11y/components/Section/style.js

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ import React from 'react';
import { mount } from 'enzyme';
import configureStore from 'redux-mock-store';
import mockRenderOptions from '@shopgate/pwa-common/helpers/mocks/mockRenderOptions';
import PlaceholderParagraph from '@shopgate/pwa-ui-shared/PlaceholderParagraph';
import ProductDescription from './index';
import { PlaceholderParagraph } from '@shopgate/engage/components';
import Description from '../index';

jest.mock('./connector', () => obj => obj);
jest.mock('../connector', () => obj => obj);

describe('<ProductDescription />', () => {
describe('<Description />', () => {
const mockStore = configureStore();
const html = '<h1>foo</h1>';

it('should not render if no data is available', () => {
const store = mockStore({});
const wrapper = mount(<ProductDescription store={store} html={null} />, mockRenderOptions);
const wrapper = mount(<Description store={store} html={null} />, mockRenderOptions);
const foundContent = wrapper.findWhere(n =>
typeof n.prop('dangerouslySetInnerHTML') !== 'undefined');

Expand All @@ -25,7 +25,7 @@ describe('<ProductDescription />', () => {

it('should render description if data is available', () => {
const store = mockStore({});
const wrapper = mount(<ProductDescription store={store} html={html} />, mockRenderOptions);
const wrapper = mount(<Description store={store} html={html} />, mockRenderOptions);
const foundContent = wrapper.findWhere(n =>
typeof n.prop('dangerouslySetInnerHTML') !== 'undefined');

Expand Down
Loading