react-native#AccessibilityInfo TypeScript Examples

The following examples show how to use react-native#AccessibilityInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useReduceMotionPreference.ts    From mobile with Apache License 2.0 6 votes vote down vote up
export function useReduceMotionPreference() {
  const [prefersReducedMotion, setPreference] = useState(false);
  useEffect(() => {
    const handleChange = (isReduceMotionEnabled: AccessibilityEvent) => {
      setPreference(Boolean(isReduceMotionEnabled));
    };
    AccessibilityInfo.isReduceMotionEnabled()
      .then(handleChange)
      .catch(error => {
        console.warn('AccessibilityInfo.isReduceMotionEnabled promise failed', error);
      });
    AccessibilityInfo.addEventListener('reduceMotionChanged', handleChange);
    return () => {
      AccessibilityInfo.removeEventListener('reduceMotionChanged', handleChange);
    };
  }, []);
  return prefersReducedMotion;
}
Example #2
Source File: a11y-element.tsx    From protect-scotland with Apache License 2.0 6 votes vote down vote up
export function useA11yElement() {
  const {
    accessibility: {screenReaderEnabled}
  } = useApplication();
  const focusRef = useRef(null);
  const isFocused = useIsFocused();

  const focusA11yElement = useCallback(
    (timeout = 250) => {
      if (screenReaderEnabled && focusRef.current && isFocused) {
        const tag = findNodeHandle(focusRef.current);
        if (tag) {
          const id = setTimeout(
            () => AccessibilityInfo.setAccessibilityFocus(tag),
            timeout
          );
          return () => clearTimeout(id);
        }
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [screenReaderEnabled, focusRef.current, isFocused]
  );

  const a11yProps = useMemo(
    () => ({
      ref: focusRef
    }),
    []
  );

  return {a11yProps, focusRef, focusA11yElement};
}
Example #3
Source File: AccessibilityServiceProvider.tsx    From mobile with Apache License 2.0 6 votes vote down vote up
AccessibilityServiceProvider = ({children}: AccessibilityServiceProviderProps) => {
  const [screenReaderEnabled, setScreenReaderEnabled] = useState<
    AccessibilityServiceContextProps['isScreenReaderEnabled']
  >(false);

  useEffect(() => {
    const handleScreenReaderToggled = (screenReaderEnabled: any) => {
      setScreenReaderEnabled(screenReaderEnabled);
    };
    // for initial app start
    AccessibilityInfo.isScreenReaderEnabled()
      .then((enabled: any) => {
        setScreenReaderEnabled(enabled);
      })
      .catch(() => {
        setScreenReaderEnabled(false);
      });
    AccessibilityInfo.addEventListener('screenReaderChanged', handleScreenReaderToggled);
    return () => {
      AccessibilityInfo.removeEventListener('screenReaderChanged', handleScreenReaderToggled);
    };
  }, []);

  const props = useMemo(() => {
    return {isScreenReaderEnabled: screenReaderEnabled};
  }, [screenReaderEnabled]);

  return <AccessibilityServiceContext.Provider value={props}>{children}</AccessibilityServiceContext.Provider>;
}
Example #4
Source File: TutorialContent.tsx    From mobile with Apache License 2.0 5 votes vote down vote up
TutorialContent = ({item, isActive}: TutorialContentProps) => {
  const [i18n] = useI18n();
  const prefersReducedMotion = useReduceMotionPreference();
  const {width: viewportWidth, height: viewportHeight} = useWindowDimensions();

  const animationRef: React.Ref<LottieView> = useRef(null);
  useEffect(() => {
    // need to stop if user prefers reduced animations
    if (prefersReducedMotion) {
      animationRef.current?.play(animationData[item].pauseFrame, animationData[item].pauseFrame);
    } else if (isActive) {
      animationRef.current?.play();
    } else {
      animationRef.current?.reset();
    }
  }, [isActive, prefersReducedMotion, item]);

  const autoFocusRef = useRef<any>();
  useLayoutEffect(() => {
    const tag = findNodeHandle(autoFocusRef.current);
    if (isActive && tag) {
      AccessibilityInfo.setAccessibilityFocus(tag);
    }
  }, [isActive]);

  return (
    <ScrollView style={styles.flex} contentContainerStyle={styles.center}>
      <LottieView
        ref={animationRef}
        style={{width: viewportWidth, height: viewportHeight / 2}}
        source={animationData[item].source}
        imageAssetsFolder="animation/images"
        loop={!prefersReducedMotion}
      />
      <Box paddingHorizontal="xxl">
        <Text
          ref={autoFocusRef}
          textAlign="center"
          color="overlayBodyText"
          variant="bodySubTitle"
          marginBottom="m"
          accessibilityRole="header"
        >
          {i18n.translate(`Tutorial.${item}Title`)}
        </Text>
        <Text variant="bodyText" textAlign="center" color="overlayBodyText">
          {i18n.translate(`Tutorial.${item}`)}
        </Text>
      </Box>
    </ScrollView>
  );
}
Example #5
Source File: single-code-input.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
SingleCodeInput: React.FC<SingleCodeInputProps> = ({
  style,
  disabled = false,
  autoFocus = false,
  onChange,
  error,
  count,
  accessibilityHint,
  accessibilityLabel
}) => {
  const [value, setValue] = useState<string>('');
  const inputRef = createRef<TextInput>();
  const fontScale = PixelRatio.getFontScale();

  useEffect(() => {
    const isScreenReaderEnabled = (async function () {
      await AccessibilityInfo.isScreenReaderEnabled();
    })();
    if (autoFocus && !isScreenReaderEnabled) {
      inputRef.current?.focus();
    }
  }, [inputRef, autoFocus]);

  const onChangeTextHandler = (v: string) => {
    const validatedValue = v.replace(/[^a-zA-Z0-9]/g, '');
    setValue(validatedValue);

    if (!validatedValue) {
      return;
    }

    if (onChange) {
      onChange(validatedValue);
    }
  };

  const onFocusHandler = () => {
    if (error) {
      inputRef.current?.clear();
      inputRef.current?.focus();
      if (onChange) {
        onChange(value);
      }
    }
  };

  return (
    <View style={[styles.container, style]}>
      <TextInput
        ref={inputRef}
        selectTextOnFocus
        autoCapitalize="characters"
        style={[
          styles.input,
          {height: 60 * fontScale},
          error ? styles.errorBlock : styles.block
        ]}
        maxLength={count}
        keyboardType="default"
        returnKeyType="done"
        editable={!disabled}
        value={value}
        placeholder="——————"
        onFocus={onFocusHandler}
        onChangeText={onChangeTextHandler}
        accessibilityLabel={accessibilityLabel}
        accessibilityHint={accessibilityHint}
      />
    </View>
  );
}
Example #6
Source File: useAccessibilityAutoFocus.ts    From mobile with Apache License 2.0 5 votes vote down vote up
focusOnElement = (elementRef: any) => {
  const node = findNodeHandle(elementRef);
  if (!node) {
    return;
  }
  AccessibilityInfo.setAccessibilityFocus(node);
}
Example #7
Source File: context.tsx    From protect-scotland with Apache License 2.0 4 votes vote down vote up
AP = ({
  user,
  onboarded,
  completedExposureOnboarding,
  children
}: API) => {
  const [state, setState] = useState<State>({
    initializing: true,
    loading: false,
    user: (user && JSON.parse(user as string)) || null,
    onboarded,
    completedExposureOnboarding,
    accessibility: {
      reduceMotionEnabled: false,
      screenReaderEnabled: false
    }
  });

  const handleReduceMotionChange = (reduceMotionEnabled: boolean): void => {
    setState((s) => ({
      ...s,
      accessibility: {
        ...s.accessibility,
        reduceMotionEnabled: reduceMotionEnabled
      }
    }));
  };

  const handleScreenReaderChange = (screenReaderEnabled: boolean): void => {
    setState((s) => ({
      ...s,
      accessibility: {
        ...s.accessibility,
        screenReaderEnabled
      }
    }));
  };

  useEffect(() => {
    AccessibilityInfo.addEventListener(
      'reduceMotionChanged',
      handleReduceMotionChange
    );
    AccessibilityInfo.addEventListener(
      'screenReaderChanged',
      handleScreenReaderChange
    );

    AccessibilityInfo.isReduceMotionEnabled().then(handleReduceMotionChange);
    AccessibilityInfo.isScreenReaderEnabled().then(handleScreenReaderChange);

    return () => {
      AccessibilityInfo.removeEventListener(
        'reduceMotionChanged',
        handleReduceMotionChange
      );
      AccessibilityInfo.removeEventListener(
        'screenReaderChanged',
        handleScreenReaderChange
      );
    };
  }, []);

  const setContext = async (data: Partial<State>) => {
    setState((s) => ({
      ...s,
      ...data,
      ...(data.user ? {user: Object.assign({}, s.user, data.user)} : {})
    }));
    if (data.user) {
      await AsyncStorage.setItem(
        'scot.user',
        JSON.stringify(Object.assign({}, state.user, data.user))
      );
    }
    if (data.completedExposureOnboarding) {
      await AsyncStorage.setItem('scot.completedExposureOnboarding', 'y');
    }
  };

  const clearContext = async (): Promise<void> => {
    await SecureStore.deleteItemAsync('refreshToken');
    await SecureStore.deleteItemAsync('token');
    await SecureStore.deleteItemAsync('uploadToken');
    await SecureStore.deleteItemAsync('niexposuredate');
    await AsyncStorage.removeItem('scot.user');
    await AsyncStorage.removeItem('scot.showDebug');
    await AsyncStorage.removeItem('scot.onboarded');
    await AsyncStorage.removeItem('scot.completedExposureOnboarding');
    await AsyncStorage.removeItem('scot.statsData');
    await AsyncStorage.removeItem('scot.settings');
    await AsyncStorage.removeItem('analyticsConsent');

    setState((s) => ({
      ...s,
      onboarded: false,
      completedExposureOnboarding: false,
      user: undefined
    }));
  };

  const loadAppDataRef = useCallback(async () => {
    const {data} = await requestWithCache('scot.statsData', loadData);
    return setState((s) => ({...s, loading: false, data}));
  }, []);

  const value: ApplicationContextValue = {
    ...state,
    setContext,
    clearContext,
    loadAppData: loadAppDataRef
  };

  return (
    <ApplicationContext.Provider value={value}>
      {children}
    </ApplicationContext.Provider>
  );
}