Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,9 @@ Use the `OneSignal` object from `react-native-onesignal`:
| SendUniqueOutcome(name) | `OneSignal.Session.addUniqueOutcome(name)` |
| SendOutcomeWithValue(name, value) | `OneSignal.Session.addOutcomeWithValue(name, value)` |
| TrackEvent(name, properties) | `OneSignal.User.trackEvent(name, properties)` |
| SetLanguage(language) | `OneSignal.User.setLanguage(language)` |
| GetPushSubscriptionId() | `await OneSignal.User.pushSubscription.getIdAsync()` |
| GetPushSubscriptionToken() | `await OneSignal.User.pushSubscription.getTokenAsync()` |
| IsPushOptedIn() | `await OneSignal.User.pushSubscription.getOptedInAsync()` |
| OptInPush() | `OneSignal.User.pushSubscription.optIn()` |
| OptOutPush() | `OneSignal.User.pushSubscription.optOut()` |
Expand Down Expand Up @@ -232,6 +234,7 @@ OneSignal.User.addEventListener('change', handler);
### Persistence

- `PreferencesService` wraps `AsyncStorage`
- Selected language is persisted for the User section dropdown only; the native SDK keeps its own language, so it is not re-applied on launch. Login and logout reset the picker to Device Default by clearing the cached value only. They don't call `setLanguage`, since `''` sends the device language and would overwrite the user's backend value.
- Triggers list (`triggersList`) is NOT persisted

### SDK State Restoration
Expand Down
128 changes: 128 additions & 0 deletions examples/demo/src/components/DropdownMenu.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import React from 'react';
import {
Modal,
Platform,
Pressable,
ScrollView,
StatusBar,
StyleSheet,
Text,
TouchableOpacity,
View,
useWindowDimensions,
} from 'react-native';

import { AppColors, AppTextStyles } from '../theme';

export interface DropdownOption {
label: string;
value: string;
}

export interface DropdownAnchor {
x: number;
y: number;
width: number;
height: number;
}

interface Props {
anchor: DropdownAnchor | null;
options: DropdownOption[];
selectedValue: string;
onSelect: (value: string) => void;
onClose: () => void;
testIDPrefix?: string;
}

const MENU_WIDTH = 240;
const MENU_MAX_HEIGHT = 320;
const SCREEN_MARGIN = 16;

export default function DropdownMenu({
anchor,
options,
selectedValue,
onSelect,
onClose,
testIDPrefix,
}: Props) {
const { width: screenWidth, height: screenHeight } = useWindowDimensions();

if (!anchor) {
return null;
}

// measureInWindow excludes the Android status bar, but the translucent
// modal draws under it.
const offsetY = Platform.OS === 'android' ? (StatusBar.currentHeight ?? 0) : 0;
const anchorTop = anchor.y + offsetY;
const anchorBottom = anchorTop + anchor.height;
// Open upward when the menu would run past the bottom of the screen.
const opensUp = anchorBottom + MENU_MAX_HEIGHT > screenHeight - SCREEN_MARGIN;
const position = {
right: Math.max(SCREEN_MARGIN, screenWidth - (anchor.x + anchor.width)),
...(opensUp ? { bottom: screenHeight - anchorTop } : { top: anchorBottom }),
};

const handleSelect = (value: string) => {
onSelect(value);
onClose();
};

return (
<Modal visible transparent animationType="fade" statusBarTranslucent onRequestClose={onClose}>
<Pressable style={StyleSheet.absoluteFill} onPress={onClose} />
<View style={[styles.menu, position]}>
<ScrollView style={styles.scroll}>
{options.map(({ label, value }) => {
const isSelected = value === selectedValue;
return (
<TouchableOpacity
key={value}
style={styles.item}
onPress={() => handleSelect(value)}
testID={testIDPrefix ? `${testIDPrefix}_${value || 'default'}` : undefined}
>
<Text style={[styles.itemLabel, isSelected && styles.itemLabelSelected]}>
{label}
</Text>
</TouchableOpacity>
);
})}
</ScrollView>
</View>
</Modal>
);
}

const styles = StyleSheet.create({
menu: {
position: 'absolute',
width: MENU_WIDTH,
maxHeight: MENU_MAX_HEIGHT,
backgroundColor: AppColors.osCardBackground,
borderRadius: 8,
elevation: 8,
shadowColor: '#000',
shadowOpacity: 0.2,
shadowRadius: 8,
shadowOffset: { width: 0, height: 4 },
},
scroll: {
borderRadius: 8,
paddingVertical: 8,
},
item: {
paddingVertical: 12,
paddingHorizontal: 16,
},
itemLabel: {
...AppTextStyles.bodyLarge,
color: '#212121',
},
itemLabelSelected: {
color: AppColors.osPrimary,
fontWeight: '500',
},
});
17 changes: 16 additions & 1 deletion examples/demo/src/components/sections/PushSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ToggleRow from '../ToggleRow';

interface Props {
pushSubscriptionId: string | undefined;
pushSubscriptionToken: string | undefined;
isPushEnabled: boolean;
hasNotificationPermission: boolean;
onSetPushEnabled: (value: boolean) => void;
Expand All @@ -17,12 +18,15 @@ interface Props {

export default function PushSection({
pushSubscriptionId,
pushSubscriptionToken,
isPushEnabled,
hasNotificationPermission,
onSetPushEnabled,
onPromptPush,
onInfoTap,
}: Props) {
const isSubscribed = isPushEnabled && hasNotificationPermission && !!pushSubscriptionToken;

return (
<SectionCard title="Push" onInfoTap={onInfoTap} sectionKey="push">
<View style={AppTheme.card}>
Expand All @@ -38,8 +42,15 @@ export default function PushSection({
</Text>
</View>
<View style={styles.divider} />
<View style={styles.idRow}>
<Text style={styles.idLabel}>Status</Text>
<Text style={styles.statusValue} testID="push_subscription_status">
{isSubscribed ? 'Subscribed' : 'Unsubscribed'}
</Text>
</View>
<View style={styles.divider} />
<ToggleRow
label="Enabled"
label="Opted In"
value={isPushEnabled}
onValueChange={onSetPushEnabled}
disabled={!hasNotificationPermission}
Expand Down Expand Up @@ -74,6 +85,10 @@ const styles = StyleSheet.create({
marginLeft: 8,
fontFamily: 'monospace',
},
statusValue: {
...AppTextStyles.bodySmall,
color: AppColors.osGrey700,
},
divider: {
height: 1,
backgroundColor: AppColors.osDivider,
Expand Down
104 changes: 101 additions & 3 deletions examples/demo/src/components/sections/UserSection.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,81 @@
import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import React, { useRef, useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';

import { AppColors, AppTextStyles, AppTheme, AppSpacing } from '../../theme';
import ActionButton from '../ActionButton';
import DropdownMenu, { type DropdownAnchor, type DropdownOption } from '../DropdownMenu';
import SingleInputModal from '../modals/SingleInputModal';
import SectionCard from '../SectionCard';

const LANGUAGE_OPTIONS: DropdownOption[] = [
{ label: 'Device Default', value: '' },
{ label: 'English', value: 'en' },
{ label: 'Arabic', value: 'ar' },
{ label: 'Azerbaijani', value: 'az' },
{ label: 'Bosnian', value: 'bs' },
{ label: 'Catalan', value: 'ca' },
{ label: 'Chinese (Simplified)', value: 'zh-Hans' },
{ label: 'Chinese (Traditional)', value: 'zh-Hant' },
{ label: 'Croatian', value: 'hr' },
{ label: 'Czech', value: 'cs' },
{ label: 'Danish', value: 'da' },
{ label: 'Dutch', value: 'nl' },
{ label: 'Estonian', value: 'et' },
{ label: 'Finnish', value: 'fi' },
{ label: 'French', value: 'fr' },
{ label: 'Georgian', value: 'ka' },
{ label: 'Bulgarian', value: 'bg' },
{ label: 'German', value: 'de' },
{ label: 'Greek', value: 'el' },
{ label: 'Hindi', value: 'hi' },
{ label: 'Hebrew', value: 'he' },
{ label: 'Hungarian', value: 'hu' },
{ label: 'Indonesian', value: 'id' },
{ label: 'Italian', value: 'it' },
{ label: 'Japanese', value: 'ja' },
{ label: 'Korean', value: 'ko' },
{ label: 'Latvian', value: 'lv' },
{ label: 'Lithuanian', value: 'lt' },
{ label: 'Malay', value: 'ms' },
{ label: 'Norwegian', value: 'nb' },
{ label: 'Persian', value: 'fa' },
{ label: 'Polish', value: 'pl' },
{ label: 'Portuguese', value: 'pt' },
{ label: 'Punjabi', value: 'pa' },
{ label: 'Romanian', value: 'ro' },
{ label: 'Russian', value: 'ru' },
{ label: 'Serbian', value: 'sr' },
{ label: 'Slovak', value: 'sk' },
{ label: 'Spanish', value: 'es' },
{ label: 'Swedish', value: 'sv' },
{ label: 'Thai', value: 'th' },
{ label: 'Turkish', value: 'tr' },
{ label: 'Ukrainian', value: 'uk' },
{ label: 'Vietnamese', value: 'vi' },
];

interface Props {
externalUserId: string | undefined;
language: string;
onLogin: (externalUserId: string) => Promise<void>;
onLogout: () => Promise<void>;
onSetLanguage: (language: string) => Promise<void>;
}

export default function UserSection({ externalUserId, onLogin, onLogout }: Props) {
export default function UserSection({
externalUserId,
language,
onLogin,
onLogout,
onSetLanguage,
}: Props) {
const [loginOpen, setLoginOpen] = useState(false);
const [languageAnchor, setLanguageAnchor] = useState<DropdownAnchor | null>(null);
const languageRowRef = useRef<View>(null);
const isLoggedIn = !!externalUserId;
const languageLabel =
LANGUAGE_OPTIONS.find((option) => option.value === language)?.label ?? language;

const handleLogin = async (userId: string) => {
await onLogin(userId);
Expand All @@ -24,6 +85,12 @@ export default function UserSection({ externalUserId, onLogin, onLogout }: Props
await onLogout();
};

const openLanguageMenu = () => {
languageRowRef.current?.measureInWindow((x, y, width, height) => {
setLanguageAnchor({ x, y, width, height });
});
};

return (
<SectionCard title="User" sectionKey="user">
<View style={[AppTheme.card, styles.card]}>
Expand All @@ -43,6 +110,21 @@ export default function UserSection({ externalUserId, onLogin, onLogout }: Props
{externalUserId ?? '—'}
</Text>
</View>
<View style={styles.divider} />
<TouchableOpacity
ref={languageRowRef}
style={styles.row}
onPress={openLanguageMenu}
testID="user_language_dropdown"
>
<Text style={styles.label}>Language</Text>
<View style={styles.dropdownValue}>
<Text style={styles.languageValue} testID="user_language_value">
{languageLabel}
</Text>
<Icon name="arrow-drop-down" size={22} color={AppColors.osGrey600} />
</View>
</TouchableOpacity>
</View>
<ActionButton
label={isLoggedIn ? 'SWITCH USER' : 'LOGIN USER'}
Expand All @@ -66,6 +148,14 @@ export default function UserSection({ externalUserId, onLogin, onLogout }: Props
onClose={() => setLoginOpen(false)}
testID="login_user_id_input"
/>
<DropdownMenu
anchor={languageAnchor}
options={LANGUAGE_OPTIONS}
selectedValue={language}
onSelect={onSetLanguage}
onClose={() => setLanguageAnchor(null)}
testIDPrefix="language_option"
/>
</SectionCard>
);
}
Expand All @@ -89,6 +179,14 @@ const styles = StyleSheet.create({
color: AppColors.osGrey700,
fontFamily: 'monospace',
},
dropdownValue: {
flexDirection: 'row',
alignItems: 'center',
},
languageValue: {
...AppTextStyles.bodySmall,
color: AppColors.osGrey700,
},
loggedInText: {
color: AppColors.osSuccess,
},
Expand Down
Loading
Loading