JSPM

@applicaster/zapp-react-native-utils

5.1.0-alpha.47b06db8
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 6664
  • Score
    100M100P100Q135950F
  • License MIT

Applicaster Zapp React Native utilities package

Package Exports

  • @applicaster/zapp-react-native-utils/analyticsUtils
  • @applicaster/zapp-react-native-utils/analyticsUtils/dateFormatters
  • @applicaster/zapp-react-native-utils/analyticsUtils/manager
  • @applicaster/zapp-react-native-utils/appUtils/HooksManager
  • @applicaster/zapp-react-native-utils/appUtils/HooksManager/constants
  • @applicaster/zapp-react-native-utils/appUtils/RiverFocusManager
  • @applicaster/zapp-react-native-utils/appUtils/keyCodes
  • @applicaster/zapp-react-native-utils/appUtils/keyCodes/keys.android.js
  • @applicaster/zapp-react-native-utils/appUtils/playerManager
  • @applicaster/zapp-react-native-utils/arrayUtils
  • @applicaster/zapp-react-native-utils/cellUtils
  • @applicaster/zapp-react-native-utils/focusManager
  • @applicaster/zapp-react-native-utils/functionUtils
  • @applicaster/zapp-react-native-utils/navigationUtils
  • @applicaster/zapp-react-native-utils/navigationUtils/itemTypes
  • @applicaster/zapp-react-native-utils/objectUtils
  • @applicaster/zapp-react-native-utils/pluginUtils
  • @applicaster/zapp-react-native-utils/reactHooks
  • @applicaster/zapp-react-native-utils/reactUtils/createContext
  • @applicaster/zapp-react-native-utils/rectUtils
  • @applicaster/zapp-react-native-utils/styleKeysUtils
  • @applicaster/zapp-react-native-utils/stylesUtils

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@applicaster/zapp-react-native-utils) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@applicaster/zapp-react-native-utils

CircleCI npm version

logo

This package contains js utilities for the Quick Brick App

Contributing

  • Follow the steps in the main README to set up the Zapp-React-Native repo, and run the app.
  • add your folder or file
  • import it with
import { utility } from "@applicaster/zapp-react-native-utils/utility";

API

reactUtils

@applicaster/zapp-react-native-utils/reactUtils

attachLifeCycleMethods = (lifecycleMethods: { [name]: method }) => (Component) =>

adds lifecycle methods to any React component (stateless or class). The appropriate method will be used depending on the type of the component. If the component is stateless, it will wrap it in a class before it adds the method to the Component's prototype. Supports all React lifecycle methods except constructor and static getDerivedStateFromProps

import { attachLifeCycleMethods } from "@applicaster/zapp-react-native-utils/reactUtils";

const MyComponent = (props) => (
  <View>
    <Text>I'm component</Text>
  </View>
);

const lifeCycleDecorator = attachLifeCycleMethods({
  componentDidMount() {
    console.log("I'm mounted");
  },
  componentWillUpdate(nextProps, nextState) {
    console.log("component will change", nextProps, nextState);
  },
});

export const ComponentWithLifeCycleMethods = lifeCycleDecorator(MyComponent);

stringUtils

@applicaster/zapp-react-native/stringUtils

  • capitalize: (input: string) => string: sets the first letter of the input string as uppercase
  • toPascalCase: (input: string) => string: transforms a snake_case input string to PascalCase

@applicaster/zapp-react-native/objectUtils

All following functions are curried and can be either called by f(a, b) or f(a)(b). They work like all curried Ramda functions

  • filterObj: (predicate: any => boolean) => (object: any) => object: any uses the predicate function to filter an object values.
  • mapKeys: (mapper: string => string) => (object: any) => (object: any) maps over an object's keys and applies the mapper function to these keys. Curried function

stylesUtils

@applicaster/zapp-react-native/stylesUtils

  • fixColorHexCode: string => string: transforms a AARRGGBB hex code into a RRGGBBAA hex code - this is required because React Native uses RRGGBBAA colors, but Zapp Api provides AARRGGBB

pluginUtils

@applicaster/zapp-react-native/pluginUtils

  • findPluginByIdentifier: (identifier: string, plugins: {[string]: Plugin}) => Plugin: find a plugin for a given identifier,in the provided map of available plugins. Returns the entire plugin.
  • findPluginByType: (type: string, plugins: {[string]: Plugin}) => Plugin: find a plugin for a given type, in the provided map of available plugins. Returns the callable plugin module.
  • getNavigationPlugin: (type: string, plugins: {[string]: Plugin}, defaultComponents: ?{[string]: Plugin}: resolves the navigation plugin to use for a given type, from a provided map of available plugins. If provided, will fallback to one of the defaultComponent.

@applicaster/zapp-react-native/navigationUtils

  • getNavigationType: (category: "nav_bar" | "menu", navigations: [Navigations]) => string: retrieves the type of navigation for a given category (either nav_bar or menu), from the navigation data in the layout.json
  • getPathAttributes: (pathname: string) => [{ screenType: string, screenId: string }]: transforms a given route into a map of attributes for that specific route. /foo/bar/baz/qux becomes :
[
  { screenType: "foo", screenId: "bar" },
  { screenType: "baz", screenId: "qux" },
];
  • getItemType: (item: any, layoutVersion: 'v1' | 'v2' ) => string: gets the type of a given item in a feed.
  • getItemTargetId: (item: any) => string: gets the target screen id for a given item in a feed.

reactHooks

@applicaster/zapp-react-native/reactHooks

navigation hooks

@applicaster/zapp-react-native/reactHooks/navigation

useNavigation: (void) => NavigationContext - Hook returns navigation context (See navigation documentation at quick-brick-core)

const navigation = useNavigation();

useBackHandler: (callback: () => any) => void - Adds hardware back button listener to your component.

useBackHandler(() => {
  console.log("HArdware back button clicked");
});

layout hooks

@applicaster/zapp-react-native/reactHooks/layout

  • useDimensions: (context : 'screen'|'window' = 'window', {fullDimensions: bool = false, round: bool = false, excludeStatusBar: bool = false }) => { width: number, height: number, scale: number, fontScale, number } | { width: number, height: number } - Hook will be called on initial component mount, will measure the Dimensions and return the result. One every screen or window size change the hook will update it's dimensions.
const dimensions = useDimensions("window", { fullDimensions: true });
  • usePrevious: (value : any) => any - Hook will return previous value that was passed to it. Usefull if you want to replicated behavior of componentDidUpdate(prevState)

utility hooks

@applicaster/zapp-react-native/reactHooks/utils

const previousVideo = usePrevious(video);

useEffect(() => {
  if (previousVideo === video) {
    // do something
  }
});

flatList hooks

@applicaster/zapp-react-native/reactHooks/flatList

  • useSequentialRenderItem: (data : array) => {renderItem: (_renderItem, renderArgs) => Component, allLoaded: boolean} - Hook used for adding sequential loading functionality for mapper functions like map or flatList renderItem.

renderItem - wrapper for renderItem function, inflating it with extra function onLoadFinished that needs to be called when component is ready to be displayed. renderItem wraps the resolution of the _renderItem, in View with the display style set to "none" or "flex";

allLoaded - returns true when onLoadFinished was called for all items.

FlatList

const data = [{ id: 1 }];
const { allLoaded, renderItem } = useSequentialRenderItem(data);

const _renderItem = ({ item, index, onLoadFinished }) => {
  onLoadFinished();
  return <Component />;
};

return <FlatList data={data} renderItem={renderItem(_renderItem)} />;

Map

const data = [{ id: 1 }];
const { allLoaded, renderItem } = useSequentialRenderItem(data);

const _renderItem = ({ item, index, onLoadFinished }) => {
  onLoadFinished();
  return <Component />;
};

return data.map((item, index) => renderItem(_renderItem, { item, index }));

connection hooks

@applicaster/zapp-react-native/reactHooks/connection

  • useConnectionInfo: (justOnlineStatus : boolean) => boolean | connectionInfo(NetInfo RN Module ) - Hook will return NetInfo state or boolean for isConnected. Updated on every change in network connection type
const connectionType = useConnectionInfo();
// connectionType = { type: 'wifi', effectiveType: 'unknown' }
const connectionType = useConnectionInfo(true);
// connectionType = true

feed hooks

@applicaster/zapp-react-native/reactHooks

  • useFeedRefresh: ({ reloadData: function, component: { id: boolean | string, rules: {enable_data_refreshing: boolean, refreshing_interval: number} } }) => void - Hook will call reloadData function, in the specified intervals if enable_data_refreshing is set to true;
useFeedRefresh({ reloadData, component });
  • useFeedLoader: ({ feedUrl: string, pipesOptions?: { clearCache?: boolean, loadLocalFavourites?: boolean, silentRefresh?: boolean} }) => ({data: ?ApplicasterFeed, loading: boolean, url: string, error: Error,reloadData: (silentRefresh?: boolean) => void, loadNext: () => void}) - Hook will load data to the redux store and return a feed for the provided DSP URL. If the data for the provided url was already loaded, it will return that value
const { data, loading, url, reloadData, loadNext } = useFeedLoader({
  feedUrl: "applicaster://fetchData?type=url&url=applicaster.com",
});

reloadData(); // Reloads data using feedUrl provided to useFeedLoader
loadNext(); // Loads next data, using `next` key from the feed returned by feedUrl request

resolver hooks

  • useComponentResolver hook used to resolve a selected component from the list of plugins and apply decorators on it (optional).

Call signature

type Decorator = (React.Component<any>) => React.Component<any>;
type Props = {
  componentType: string,
  decorators?: Decorator | Array<Decorator>,
};
type Watchers = Array<any>;

useComponentResolver(
  ({ componentType, decorators }: Props),
  (watchers: Watchers)
);
  • componentType: plugin identifier of your component
  • decorators(optional): decorator/list of decorators used to decorate your component
  • watchers(optional): list of dependencies to be passed to useMemo hook that wraps componentResolver internally. Useful when component resolution is dependant on external variables. For example, one of the decorators uses external variable that is likely to change.

Example:

const viewWrapperDecorator = (Component) => (props) => (
  <View>{props.children}</View>
);

const Container = (props) => {
  const Component = useComponentResolver(
    {
      componentType: "horizontal_list_qb",
      decorators: viewWrapperDecorator,
    },
    [props.reCreateComponentOnThisPropChange]
  );

  return <Component />;
};

 

  • useCellResolver Creates cell component, based on passed configuration. Warning: resolution of this hook is memoized outside of RN lifecycle so once cell component is created it will won't be re-calculated, unless component.id changes.

Call signature:

type ZappComponent = {
  id: string;
  styles: {
    cell_plugin_configuration_id: string;
  };
};

useCellResolver({ component: ZappComponent });
  • component: Zapp component object

Example:

const component = {
  id: '123',
  styles: {
    cell_plugin_configuration_id: 'ahs733-fnk3f-fsnb21-fbsk235'
  }
}

const Cell = useCellResolver({component})
};

 

appUtils - orientationHelper

@applicaster/zapp-react-native/appUtils/orientationHelper

const ORIENTATIONS = {
  portrait: 1,
  landscapeRight: 2,
  landscapeLeft: 4,
  landscapeSensor: 6,
  allButUpsideDown: 7,
  portraitUpsideDown: 8,
  all: 15,
};

allowedOrientationsForScreen: (ORIENTATIONS) => void - Sets allowed orientations for the current screen releaseOrientationsForScreen: () => void - releases orientations set for current screen and sets it to the previous state addOrientationChangeListener: (callback: ({toOrientation: ORIENTATIONS, fromOrientation: ORIENTATIONS)) => listenerInstance - Adds orientation change listener that will call the callback on every allowed orientation change (set with allowedOrientationsForScreen). removeOrientationChangeListener: (listenerInstance) => void - Removes passed listener

Example of how to use orientation handler inside React useEffect hook:

useEffect(() => {
  allowedOrientationsForScreen(ORIENTATIONS.allButUpsideDown);
  const listener = addOrientationChangeListener(
    ({ toOrientation, fromOrientation }) => {
      // Do something
    }
  );

  return () => {
    releaseOrientationsForScreen();
    removeOrientationChangeListener(listener);
  };
}, []);

testUtils

@applicaster/zapp-react-native-utils/testUtils

  • testIDEquals: (testId: any) => boolean | { width: number, height: number } - Function to be used in tandem with enzyme findWhere
wrapper.findWhere(testIDEquals("text"));