UNPKG

@applicaster/zapp-react-native-ui-components

Version:

Applicaster Zapp React Native ui components for the Quick Brick App

103 lines (75 loc) 2.5 kB
import * as React from "react"; import { path } from "ramda"; import { isTV } from "@applicaster/zapp-react-native-utils/reactUtils"; import { useActions } from "@applicaster/zapp-react-native-utils/reactHooks/actions"; import { extractAsset } from "./utils"; type Return = { uri: string } | null; const getSourceContext = path(["source", "context"]); const getSourceUri = path(["source", "uri"]); const getState = path(["state"]); export const useImageSource = ({ uri, entry, otherProps }): Return => { const uriContext = getSourceContext(otherProps); const uriState = getState(otherProps); const action = useActions(uriContext); const initialEntryState = action?.initialEntryState?.(entry); const [entryStateLocal, setEntryStateLocal] = React.useState(initialEntryState); React.useEffect(() => { return action?.addListeners?.(({ entryState, entry: actionEntry }) => { if (entry.id === actionEntry.id) { setEntryStateLocal(entryState); } }); }, []); if (uriContext && uriState && action) { return extractAsset(!isTV(), entryStateLocal.asset, uriState); } if (uri) { return { uri }; } const uriFromSource = getSourceUri(otherProps); if (uriFromSource) { return { uri: uriFromSource }; } return null; }; const getSource = (uri, showDefault, placeholderImage, otherProps) => { const placeholderName = placeholderImage || ""; const defaultPath = { uri: placeholderName, }; if (showDefault) return defaultPath; if (uri) { return { uri }; } const uriFromSource = getSourceUri(otherProps); if (uriFromSource) { return { uri: uriFromSource }; } return defaultPath; }; export const useImageSourceWithDefault = ({ uri, entry, showDefault, placeholderImage, otherProps, }): Return => { const uriContext = getSourceContext(otherProps); const uriState = getState(otherProps); const action = useActions(uriContext); const initialEntryState = action?.initialEntryState?.(entry); const [entryStateLocal, setEntryStateLocal] = React.useState(initialEntryState); React.useEffect(() => { return action?.addListeners?.(({ entryState, entry: actionEntry }) => { if (entry.id === actionEntry.id) { setEntryStateLocal(entryState); } }); }, []); if (uriContext && uriState && action) { return extractAsset(!isTV(), entryStateLocal.asset, uriState); } return getSource(uri, showDefault, placeholderImage, otherProps); };