UNPKG

@zohodesk/hooks

Version:

Unified Component Library - Hooks

83 lines (79 loc) 2.23 kB
import React, { useState, useEffect, useCallback, useMemo } from "react"; // import useNonInitialEffect from "../../custom-hooks/useNonInitialEffect"; import bindActions from "../utils/bindActions"; import useCommonReducer from "../utils/useCommonReducer"; import reducer, { init } from "./reducer"; import { switchNextItem, switchPrevItem, toggleThumbnailView, toggleZoomView, handleSelectItem } from "./actions"; export default function useMediaViewer(props, customReducer) { let { items, selectedItemId, onChangeHandler } = props; let { state, dispatch } = useCommonReducer(reducer, customReducer, Object.assign({}, init, { items, selectedItemId })); let { currentItem, currentItemIndex } = useMemo(() => { let currentItem = null; let currentItemIndex; state.items.forEach((item, index) => { if (item.id == state.selectedItemId) { currentItem = item; currentItemIndex = index; } }); // console.log("currentItem",currentItem) if (currentItem) { return { currentItem, currentItemIndex }; } else if (items.length > 0) { return { currentItem: items[0], currentItemIndex: 0 }; } else { return {}; } }, [state.items, state.selectedItemId]); useEffect(() => { onChangeHandler && onChangeHandler(state.selectedItemId, currentItem); }, [currentItem, state.selectedItemId]); useEffect(() => { handleSelectItem(selectedItemId); }, [selectedItemId]); let actions = bindActions({ switchNextItem, switchPrevItem, toggleThumbnailView, toggleZoomView, handleSelectItem }, dispatch); useEffect(() => { function onHandleKeyPress(e) { let keyCode = e.keyCode; if (keyCode === 27) { props.onClose && props.onClose(); } else if (keyCode === 37) { actions.switchPrevItem(); } else if (keyCode === 39) { actions.switchNextItem(); } } global.addEventListener('keydown', onHandleKeyPress); return () => { global.removeEventListener('keydown', onHandleKeyPress); }; }, []); return { ...state, currentItem, currentItemIndex, ...actions }; }