import React, { useReducer, useMemo, useContext } from "react"; import PropTypes from "prop-types"; import { obfuscate } from "../utils/obfuscateStrings"; const SensitiveInfoContext = React.createContext(); const initialState = { enabled: false }; const reducer = (state = initialState, action) => { switch (action.type) { case "onSensitiveInfoEnabled": { return { ...state, enabled: action.payload.enabled }; } default: { return state; } } }; const dispatchActions = dispatch => ({ onSensitiveInfoEnabled: enabled => dispatch({ type: "onSensitiveInfoEnabled", payload: { enabled } }) }); const useSensitiveInfo = () => { const { state, actions } = useContext(SensitiveInfoContext); const { enabled } = state; const { onSensitiveInfoEnabled } = actions; const mask = text => { if (!enabled) return text; return obfuscate(text, "#"); }; return { enabled, onSensitiveInfoEnabled, mask }; }; const SensitiveInfoProvider = ({ children }) => { const [state, dispatch] = useReducer(reducer, initialState); const actions = useMemo(() => dispatchActions(dispatch), [dispatch]); return ( {children} ); }; SensitiveInfoProvider.propTypes = { children: PropTypes.node.isRequired }; export { SensitiveInfoProvider, useSensitiveInfo }; export default SensitiveInfoProvider;