Skip to content

Commit

Permalink
Merge pull request #4 from sima-land/#3
Browse files Browse the repository at this point in the history
Closes #3 GalleryModal: Добавлена возможность реагировать на события видео
  • Loading branch information
krutoo authored Jul 23, 2021
2 parents ab6f79f + 58471bc commit cbb8caa
Show file tree
Hide file tree
Showing 9 changed files with 111 additions and 32 deletions.
15 changes: 6 additions & 9 deletions src/common/helpers/clean-num-string.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import pipe from 'lodash/fp/pipe';
import toString from 'lodash/toString';

/**
* Очищает строку от любых символов, кроме цифр и удаляет лишние нули вначале.
* @param {string} str Строка.
* @return {string} Возвращает очищенную строку.
* @param value Строка.
* @return Возвращает очищенную строку.
*/
export const cleanNumString = pipe(
str => toString(str) && str.replace(/[^0-9]/g, ''),
str => str === '' ? '' : Number(str).toString()
);
export const cleanNumString = (value: unknown): string => {
const string = String(value).replace(/\D/g, '');
return string.length > 0 ? Number(string).toString() : '';
};
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ export default {
};

export const Primary = () => (
<GalleryModal media={data.media} onClose={action('GalleryModal:close')} />
<GalleryModal
media={data.media}
onClose={action('GalleryModal:close')}
onVideoEvent={e => action('GalleryModal:video-event')(e.type)}
/>
);

export const WithReview = () => (
Expand All @@ -28,6 +32,7 @@ export const WithReview = () => (
rating: 3.2,
author: 'Пелагеевская Вероника Сергеевна',
}}
onGoToReview={() => action('GalleryModal:go-to-review')}
onGoToReview={() => action('GalleryModal:go-to-review')()}
onVideoEvent={e => action('GalleryModal:video-event')(e.type)}
/>
);
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,72 @@ describe('GalleryModal', () => {
expect(wrapper).toMatchSnapshot();
});

it('should handle video events', () => {
const spy = jest.fn();

const wrapper = mount(
<GalleryModal
media={data.media.filter(item => item.type === 'video')}
onVideoEvent={spy}
/>
);

expect(spy).toBeCalledTimes(0);

// play
act(() => {
wrapper.find('video').simulate('play');
});
wrapper.update();

expect(spy).toBeCalledTimes(1);
expect(spy.mock.calls[0][0].type).toBe('play');

// pause
act(() => {
wrapper.find('video').simulate('pause');
});
wrapper.update();

expect(spy).toBeCalledTimes(2);
expect(spy.mock.calls[1][0].type).toBe('pause');

// ended
act(() => {
wrapper.find('video').simulate('ended');
});
wrapper.update();

expect(spy).toBeCalledTimes(3);
expect(spy.mock.calls[2][0].type).toBe('ended');
});

it('should handle video events without callback', () => {
const wrapper = mount(
<GalleryModal
media={data.media.filter(item => item.type === 'video')}
/>
);

// play
act(() => {
wrapper.find('video').simulate('play');
});
wrapper.update();

// pause
act(() => {
wrapper.find('video').simulate('pause');
});
wrapper.update();

// ended
act(() => {
wrapper.find('video').simulate('ended');
});
wrapper.update();
});

it('should renders with review footer', () => {
const spy = jest.fn();

Expand Down
29 changes: 20 additions & 9 deletions src/desktop/components/gallery-modal/components/gallery-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface GalleryModalProps extends Pick<ModalProps, 'withScrollDisable'
}
onGoToReview?: () => void
onClose?: () => void
onVideoEvent?: (event: React.SyntheticEvent<HTMLVideoElement>) => void
}

interface InnerStyles extends React.CSSProperties {
Expand All @@ -41,6 +42,7 @@ export const GalleryModal = ({
onMediaChange,
withScrollDisable,
scrollDisableOptions,
onVideoEvent,
}: GalleryModalProps) => {
const [currentIndex, setCurrent] = useState<number>(defaultMediaIndex);

Expand Down Expand Up @@ -101,7 +103,7 @@ export const GalleryModal = ({
{size !== null && (
<div className={cx('inner')} style={{ width: `${size}px` }}>
<div className={cx('square')}>
<Media {...media[currentIndex]} />
<Media {...media[currentIndex]} onVideoEvent={onVideoEvent} />

{media.length > 1 && (
<>
Expand Down Expand Up @@ -138,20 +140,29 @@ export const GalleryModal = ({
);
};

const Media = (props: MediaData) => (
const Media = ({ onVideoEvent, ...media }: MediaData & {
onVideoEvent?: (event: React.SyntheticEvent<HTMLVideoElement>) => void
}) => (
<div className={cx('media')}>
{props.type === 'image' && (
{media.type === 'image' && (
<ImageOverlay className={cx('media-image-wrap')}>
<img src={props.data.src} alt={props.data.alt || ''} />
<img src={media.data.src} alt={media.data.alt || ''} />
</ImageOverlay>
)}
{props.type === 'video' && (
<video autoPlay controls controlsList='nodownload'>
<source src={props.data.src} />
{media.type === 'video' && (
<video
autoPlay
controls
controlsList='nodownload'
onPlay={onVideoEvent}
onPause={onVideoEvent}
onEnded={onVideoEvent}
>
<source src={media.data.src} />
</video>
)}
{props.type === '360' && (
<AllRoundView photos={props.data.photos} />
{media.type === '360' && (
<AllRoundView photos={media.data.photos} />
)}
</div>
);
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
exports[`<ModifiersGroup /> should match snapshot 1`] = `
<div
className="modifiers-group height-limited"
data-testid="data-tetsid"
data-testid="modifiers-group"
>
<ForwardRef(ModifierButton)
className="guttered"
Expand Down
4 changes: 2 additions & 2 deletions src/desktop/components/modifiers/group/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export interface ModifiersGroupProps {
getItemImage?: ModifierPredicate<string>
isMarkdown?: ModifierPredicate<boolean>
onClickShowAll?: () => void
'data-tetsid'?: string
'data-testid'?: string
}

const cx = classnames.bind(classes);
Expand Down Expand Up @@ -190,7 +190,7 @@ export class ModifiersGroup extends Component<ModifiersGroupProps, State> {
isSelectedItem = defaultIsSelectedItem,
getItemImage = defaultGetItemImage,
isMarkdown = defaultGetIsMarkdown,
'data-tetsid': testId = 'data-tetsid',
'data-testid': testId = 'modifiers-group',
} = this.props;

const { needShowAll, hasHiddenNodes, lastVisibleChildIndex } = this.state;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ exports[`<ModifiersWidget /> should renders correctly with prop 1`] = `
>
<div
className="modifiers-group height-limited"
data-testid="data-tetsid"
data-testid="modifiers-group"
>
<ForwardRef(ModifierButton)
className="guttered"
Expand Down
16 changes: 8 additions & 8 deletions src/mobile/components/modifiers-list/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ const cx = classnames.bind(classes);

/**
* Компонент списка модификаторов.
* @param {Object} props Свойства компонента.
* @param {Array} props.items Массив данных модификаторов.
* @param {string} props.currencyGrapheme Графема валюты пользователя.
* @param {string} props.sizesTableUrl Url таблицы размеров.
* @param {Object} props.wrapperProps Свойства блока-обертки.
* @param {Object} props.itemsContainerProps Свойства блока-обертки списка модификаторов.
* @param {Function} props.onItemClick Обработчик клика на модификатор.
* @return {ReactElement} Компонент списка модификаторов.
* @param props Свойства компонента.
* @param props.items Массив данных модификаторов.
* @param props.currencyGrapheme Графема валюты пользователя.
* @param props.sizesTableUrl Url таблицы размеров.
* @param props.wrapperProps Свойства блока-обертки.
* @param props.itemsContainerProps Свойства блока-обертки списка модификаторов.
* @param props.onItemClick Обработчик клика на модификатор.
* @return Компонент списка модификаторов.
*/
export const ModifiersList = ({
items,
Expand Down

0 comments on commit cbb8caa

Please sign in to comment.