text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```javascript /* @flow strict-local */ import invariant from 'invariant'; import React, { useContext } from 'react'; import type { Node } from 'react'; import { Text } from 'react-native'; import type { ____TextStyle_Internal } from 'react-native/Libraries/StyleSheet/StyleSheetTypes'; // eslint-disable-line id-match import { ThemeContext } from '../styles'; type Props = $ReadOnly<{| ...$Exact<React$ElementConfig<typeof Text>>, text?: string, inheritFontSize?: boolean, inheritColor?: boolean, |}>; /** * A thin wrapper for `Text` that ensures a consistent, themed style. * * Unlike `ZulipTextIntl`, it does not translate its contents. * * Pass either `text` or `children`, but not both. * * @prop text - Contents for Text. * @prop [style] - Can override our default style for this component. * @prop inheritFontSize, etc. - Use instead of `styles.fontSize`, etc., to * inherit value from an ancestor Text in the layout: * path_to_url#limited-style-inheritance * @prop ...all other Text props - Passed through verbatim to Text. * See upstream: path_to_url */ export default function ZulipText(props: Props): Node { const { text, children, style, inheritFontSize = false, inheritColor = false, ...restProps } = props; const themeData = useContext(ThemeContext); invariant( text != null || children != null, 'ZulipText: `text` or `children` should be non-nullish', ); invariant(text == null || children == null, 'ZulipText: `text` or `children` should be nullish'); // These attributes will be applied unless specifically overridden with // the `style` or `inherit*` props -- even if this `<ZulipText />` is // nested and would otherwise inherit the attributes from its ancestors. const aggressiveDefaultStyle: $Rest<____TextStyle_Internal, { ... }> = { fontSize: 15, color: themeData.color, // If adding an attribute `foo`, give callers a prop `inheritFoo`. }; if (inheritFontSize) { delete aggressiveDefaultStyle.fontSize; } if (inheritColor) { delete aggressiveDefaultStyle.color; } return ( <Text style={[aggressiveDefaultStyle, style]} {...restProps}> {text} {children} </Text> ); } ```
/content/code_sandbox/src/common/ZulipText.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
545
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import SectionSeparator from './SectionSeparator'; /* * Upstream `SectionList` is full of `any`s. This type is incomplete, * and just captures what we use. */ type Props = $ReadOnly<{| leadingItem: ?{ ... }, leadingSection: ?{ data: { length: number, ... }, ... }, |}>; /** Can be passed to RN's `SectionList` as `SectionSeparatorComponent`. */ export default function SectionSeparatorBetween(props: Props): Node { const { leadingItem, leadingSection } = props; if (leadingItem || !leadingSection || leadingSection.data.length === 0) { return null; } return <SectionSeparator />; } ```
/content/code_sandbox/src/common/SectionSeparatorBetween.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
169
```javascript /* @flow strict-local */ import * as React from 'react'; import ZulipText from './ZulipText'; import { openLinkWithUserPreference } from '../utils/openLink'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import { useGlobalSelector } from '../react-redux'; import { getGlobalSettings } from '../directSelectors'; import type { BoundedDiff } from '../generics'; type ZulipTextProps = $Exact<React$ElementConfig<typeof ZulipText>>; type Props = $ReadOnly<{| ...BoundedDiff< ZulipTextProps, {| // Could accept `style`, just be sure to merge with web-link style. style: ZulipTextProps['style'], onPress: ZulipTextProps['onPress'], |}, >, url: URL, |}>; const componentStyles = createStyleSheet({ link: { color: BRAND_COLOR, }, }); /** * A button styled like a web link. * * Accepts strings as children or a `text` prop, just like ZulipText. * * Also accepts `ZulipText`s and `ZulipTextIntl`s as children. To keep the * special formatting, you have to pass `inheritColor` to those. */ export default function WebLink(props: Props): React.Node { const { url, ...zulipTextProps } = props; const globalSettings = useGlobalSelector(getGlobalSettings); return ( <ZulipText style={componentStyles.link} onPress={() => { openLinkWithUserPreference(url, globalSettings); }} {...zulipTextProps} /> ); } ```
/content/code_sandbox/src/common/WebLink.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
364
```javascript /* @flow strict-local */ import React, { useMemo } from 'react'; import type { Node } from 'react'; import { LogBox, View } from 'react-native'; import type { LocalizableText } from '../types'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import Screen from './Screen'; import SelectableOptionRow from './SelectableOptionRow'; import ZulipTextIntl from './ZulipTextIntl'; import { createStyleSheet } from '../styles'; import { TranslationContext } from '../boot/TranslationProvider'; import { noTranslation } from '../i18n/i18n'; type Item<TKey> = $ReadOnly<{| key: TKey, title: LocalizableText, subtitle?: LocalizableText, disabled?: | {| +title: LocalizableText, +message?: LocalizableText, +learnMoreButton?: {| +url: URL, +text?: LocalizableText, |}, |} | false, selected: boolean, |}>; type Props<TItemKey> = $ReadOnly<{| navigation: AppNavigationProp<'selectable-options'>, route: RouteProp< 'selectable-options', {| title: LocalizableText, /** * An optional explanation, to be shown before the items. */ description?: LocalizableText, items: $ReadOnlyArray<Item<TItemKey>>, // This param is a function, so React Nav is right to point out that // it isn't serializable. But this is fine as long as we don't try to // persist navigation state for this screen or set up deep linking to // it, hence the LogBox suppression below. // // React Navigation doesn't offer a more sensible way to have us pass // the selection to the calling screen. We could store the selection // as a route param on the calling screen, or in Redux. But from this // screen's perspective, that's basically just setting a global // variable. Better to offer this explicit, side-effect-free way for // the data to flow where it should, when it should. onRequestSelectionChange: (itemKey: TItemKey, requestedValue: boolean) => void, search?: boolean, |}, >, |}>; // React Navigation would give us a console warning about non-serializable // route params. For more about the warning, see // path_to_url#your_sha256_hashgation-state // See comment on this param, above. LogBox.ignoreLogs([/selectable-options > params\.onRequestSelectionChange \(Function\)/]); /** * A screen for selecting items in a list, checkbox or radio-button style. * * The items and selection state are controlled by the route params. Callers * should declare a unique key for their own use of this route, as follows, * so that instances can't step on each other: * * navigation.push({ name: 'selectable-options', key: 'foo', params: { } }) * navigation.dispatch({ ...CommonActions.setParams({ }), source: 'foo' }) */ // If we need separate components dedicated to checkboxes and radio buttons, // we can split this. Currently it's up to the caller to enforce the // radio-button invariant (exactly one item selected) if they want to. export default function SelectableOptionsScreen<TItemKey: string | number>( props: Props<TItemKey>, ): Node { const { route } = props; const { title, description, items, onRequestSelectionChange, search } = route.params; const _ = React.useContext(TranslationContext); const [filter, setFilter] = React.useState(''); const filteredItems = filter.trim() === '' ? items : items.filter(item => { // TODO: Is this the best way to filter? Where `title` and // `subtitle` are present, behavior is matched to an old // implementation of the language picker. /* eslint-disable prefer-template */ const itemData = _(item.subtitle ?? noTranslation('')).toUpperCase() + ' ' + _(item.title ?? noTranslation('')).toUpperCase(); /* eslint-enable prefer-template */ const filterData = filter.toUpperCase(); return itemData.includes(filterData); }); const styles = useMemo( () => createStyleSheet({ descriptionWrapper: { padding: 16 }, }), [], ); return ( <Screen title={title} scrollEnabled search={search} searchBarOnChange={setFilter}> {description != null && ( <View style={styles.descriptionWrapper}> <ZulipTextIntl text={description} /> </View> )} {filteredItems.map(item => ( <SelectableOptionRow key={item.key} itemKey={item.key} title={item.title} subtitle={item.subtitle} disabled={item.disabled} selected={item.selected} onRequestSelectionChange={onRequestSelectionChange} /> ))} </Screen> ); } ```
/content/code_sandbox/src/common/SelectableOptionsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,091
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import type { EditingEvent } from 'react-native/Libraries/Components/TextInput/TextInput'; import { View } from 'react-native'; import InputWithClearButton from './InputWithClearButton'; import { createStyleSheet } from '../styles'; import type { LocalizableText } from '../types'; const styles = createStyleSheet({ wrapper: { flex: 1, flexDirection: 'row', alignItems: 'center', }, input: { flex: 1, borderWidth: 0, minHeight: 50, }, }); type Props = $ReadOnly<{| autoFocus?: boolean, onChangeText: (text: string) => void, onSubmitEditing: (e: EditingEvent) => mixed, placeholder?: LocalizableText, |}>; /** * A light abstraction over the standard TextInput component * that configures and styles it to be a used as a search input. * * @prop [autoFocus] - should the component be focused when mounted. * @prop onChangeText - Event called when search query is edited. */ export default function SearchInput(props: Props): Node { const { autoFocus = true, onChangeText, onSubmitEditing, placeholder = 'Search' } = props; return ( <View style={styles.wrapper}> <InputWithClearButton style={styles.input} autoCorrect={false} enablesReturnKeyAutomatically selectTextOnFocus underlineColorAndroid="transparent" autoCapitalize="none" placeholder={placeholder} returnKeyType="search" onChangeText={onChangeText} autoFocus={autoFocus} onSubmitEditing={onSubmitEditing} /> </View> ); } ```
/content/code_sandbox/src/common/SearchInput.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
370
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View, ActivityIndicator } from 'react-native'; import type { TextStyle, ViewStyle } from 'react-native/Libraries/StyleSheet/StyleSheet'; import ZulipTextIntl from './ZulipTextIntl'; import type { LocalizableReactText } from '../types'; import type { SubsetProperties } from '../generics'; import type { SpecificIconType } from './Icons'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import Touchable from './Touchable'; const styles = createStyleSheet({ frame: { height: 44, justifyContent: 'center', borderRadius: 22, overflow: 'hidden', }, primaryFrame: { backgroundColor: BRAND_COLOR, }, secondaryFrame: { borderWidth: 1.5, borderColor: BRAND_COLOR, }, disabledPrimaryFrame: { backgroundColor: 'hsla(0, 0%, 50%, 0.4)', }, disabledSecondaryFrame: { borderWidth: 1.5, borderColor: 'hsla(0, 0%, 50%, 0.4)', }, buttonContent: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', height: 44, }, icon: { marginRight: 8, }, primaryIcon: { color: 'white', }, secondaryIcon: { color: BRAND_COLOR, }, text: { fontSize: 16, }, primaryText: { color: 'white', }, secondaryText: { color: BRAND_COLOR, }, disabledText: { color: 'hsla(0, 0%, 50%, 0.8)', }, }); type Props = $ReadOnly<{| style?: SubsetProperties< ViewStyle, {| // The use of specific style properties for callers to micromanage the // layout of the button is pretty chaotic and fragile, introducing // implicit dependencies on details of the ZulipButton implementation. // TODO: Assimilate those usages into a more coherent set of options // provided by the ZulipButton interface explicitly. // // Until then, by listing here the properties we do use, we at least // make it possible when working on the ZulipButton implementation to // know the scope of different ways that callers can mess with the // styles. If you need one not listed here and it's in the same // spirit as others that are, feel free to add it. margin?: mixed, marginTop?: mixed, marginBottom?: mixed, marginHorizontal?: mixed, // (... e.g., go ahead and add more variations on margin.) padding?: mixed, paddingLeft?: mixed, paddingRight?: mixed, height?: mixed, width?: mixed, borderWidth?: mixed, borderRadius?: mixed, flex?: mixed, alignSelf?: mixed, backgroundColor?: mixed, |}, >, textStyle?: SubsetProperties<TextStyle, {| color?: mixed |}>, progress?: boolean, disabled?: boolean, Icon?: SpecificIconType, text: LocalizableReactText, secondary?: boolean, onPress: () => void | Promise<void>, isPressHandledWhenDisabled?: boolean, |}>; /** * A button component that is provides consistent look and feel * throughout the app. It can be disabled or show action-in-progress. * * If several buttons are on the same screen all or all but one should * have their `secondary` property set to `true`. * * @prop [style] - Style object applied to the outermost component. * @prop [textStyle] - Style applied to the button text. * @prop [progress] - Shows a progress indicator in place of the button text. * @prop [disabled] - If set the button is not pressable and visually looks disabled. * @prop [Icon] - Icon component to display in front of the button text * @prop text - The button text * @prop [secondary] - Less prominent styling, the button is not as important. * @prop onPress - Event called on button press. * @prop isPressHandledWhenDisabled - Whether `onPress` is used even when * `disabled` is true */ export default function ZulipButton(props: Props): Node { const { style, text, disabled = false, secondary = false, progress = false, onPress, Icon, isPressHandledWhenDisabled = false, } = props; const frameStyle = [ styles.frame, // Prettier bug on nested ternary /* prettier-ignore */ disabled ? secondary ? styles.disabledSecondaryFrame : styles.disabledPrimaryFrame : secondary ? styles.secondaryFrame : styles.primaryFrame, style, ]; const textStyle = [ styles.text, disabled ? styles.disabledText : secondary ? styles.secondaryText : styles.primaryText, props.textStyle, ]; const iconStyle = [styles.icon, secondary ? styles.secondaryIcon : styles.primaryIcon]; if (progress) { return ( <View style={frameStyle}> <ActivityIndicator color="white" /> </View> ); } return ( <View style={frameStyle}> <Touchable onPress={disabled && !isPressHandledWhenDisabled ? undefined : onPress}> <View style={styles.buttonContent}> {!!Icon && <Icon style={iconStyle} size={25} />} <ZulipTextIntl style={textStyle} text={text} /> </View> </Touchable> </View> ); } ```
/content/code_sandbox/src/common/ZulipButton.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,235
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { Image, View, PixelRatio } from 'react-native'; import { useSelector } from '../react-redux'; import { getAuthHeaders } from '../api/transport'; import { getAuth } from '../account/accountsSelectors'; import Touchable from './Touchable'; import { AvatarURL, FallbackAvatarURL } from '../utils/avatar'; import { IconUserBlank } from './Icons'; import { ThemeContext } from '../styles'; type Props = $ReadOnly<{| avatarUrl: AvatarURL | null, size: number, isMuted?: boolean, children?: Node, onPress?: () => void, |}>; /** * Renders an image of the user's avatar. * * @prop avatarUrl * @prop size - Sets width and height in logical pixels. * @prop [children] - If provided, will render inside the component body. * @prop [onPress] - Event fired on pressing the component. */ function UserAvatar(props: Props): Node { const { avatarUrl, children, size, isMuted = false, onPress } = props; const borderRadius = size / 8; const style = { height: size, width: size, borderRadius, }; const iconStyle = { height: size, width: size, textAlign: 'center', }; const { color } = useContext(ThemeContext); const auth = useSelector(state => getAuth(state)); let userImage; if (isMuted || !avatarUrl) { userImage = <IconUserBlank size={size} color={color} style={iconStyle} />; } else { userImage = ( <Image source={{ uri: avatarUrl.get(PixelRatio.getPixelSizeForLayoutSize(size)).toString(), ...(avatarUrl instanceof FallbackAvatarURL ? { headers: getAuthHeaders(auth) } : undefined), }} style={style} resizeMode="cover" /> ); } return ( <Touchable onPress={onPress}> <View accessibilityIgnoresInvertColors> {userImage} {children} </View> </Touchable> ); } export default UserAvatar; ```
/content/code_sandbox/src/common/UserAvatar.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
490
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { SpecificIconType } from './Icons'; import ZulipTextIntl from './ZulipTextIntl'; import ZulipSwitch from './ZulipSwitch'; import styles, { ThemeContext, createStyleSheet } from '../styles'; type Props = $ReadOnly<{| Icon?: SpecificIconType, label: string, value: boolean, onValueChange: (newValue: boolean) => void, |}>; const componentStyles = createStyleSheet({ container: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8, paddingHorizontal: 16, // For uniformity with other rows this might share a screen with, e.g., // NavRow and InputRowRadioButtons on the settings screen. See // height-related attributes on those rows. minHeight: 48, }, icon: { textAlign: 'center', marginRight: 8, }, }); /** * A row with a label and a switch component. */ export default function SwitchRow(props: Props): Node { const { label, value, onValueChange, Icon } = props; const themeContext = useContext(ThemeContext); return ( <View style={componentStyles.container}> {!!Icon && <Icon size={24} style={[componentStyles.icon, { color: themeContext.color }]} />} <ZulipTextIntl text={label} style={styles.flexed} /> <View style={styles.rightItem}> <ZulipSwitch value={value} onValueChange={onValueChange} /> </View> </View> ); } ```
/content/code_sandbox/src/common/SwitchRow.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
376
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import type { UserId } from '../types'; import { createStyleSheet } from '../styles'; import UserAvatar from './UserAvatar'; import PresenceStatusIndicator from './PresenceStatusIndicator'; import { tryGetUserForId } from '../users/userSelectors'; import { useSelector } from '../react-redux'; import { getMutedUsers } from '../directSelectors'; import * as logging from '../utils/logging'; const styles = createStyleSheet({ status: { bottom: 0, right: 0, position: 'absolute', }, }); type Props = $ReadOnly<{| userId: UserId, size: number, onPress?: () => void, |}>; /** * A user avatar with a PresenceStatusIndicator in the corner. * * @prop [userId] * @prop [size] * @prop [onPress] */ export default function UserAvatarWithPresence(props: Props): Node { const { userId, size, onPress } = props; const user = useSelector(state => tryGetUserForId(state, userId)); const isMuted = useSelector(getMutedUsers).has(userId); if (!user) { logging.warn("UserAvatarWithPresence: couldn't find user for ID", { userId }); return <UserAvatar avatarUrl={null} size={size} isMuted onPress={undefined} />; } return ( <UserAvatar avatarUrl={user.avatar_url} size={size} isMuted={isMuted} onPress={onPress}> <PresenceStatusIndicator style={styles.status} userId={user.user_id} hideIfOffline useOpaqueBackground /> </UserAvatar> ); } ```
/content/code_sandbox/src/common/UserAvatarWithPresence.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
370
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Platform, StatusBar, useColorScheme } from 'react-native'; // $FlowFixMe[untyped-import] import Color from 'color'; import type { ThemeName } from '../types'; import { useGlobalSelector } from '../react-redux'; import { foregroundColorFromBackground } from '../utils/color'; import { getGlobalSession, getGlobalSettings } from '../selectors'; import { getThemeToUse } from '../settings/settingsSelectors'; type BarStyle = React$ElementConfig<typeof StatusBar>['barStyle']; export const getStatusBarColor = (backgroundColor: string | void, theme: ThemeName): string => backgroundColor ?? (theme === 'dark' ? 'hsl(212, 28%, 18%)' : 'white'); export const getStatusBarStyle = (statusBarColor: string): BarStyle => foregroundColorFromBackground(statusBarColor) === 'white' /* force newline */ ? 'light-content' : 'dark-content'; type Props = $ReadOnly<{| backgroundColor?: string | void, hidden?: boolean, |}>; /** * Renders an RN `StatusBar` with appropriate props, and nothing else. * * Specifically, it controls the status bar's hidden/visible state and * its background color in platform-specific ways. Omitting `hidden` * will make the status bar visible, and omitting `backgroundColor` * will give a theme-appropriate default. * * `StatusBar` renders `null` every time. Therefore, don't look to * `ZulipStatusBar`'s position in the hierarchy of `View`s to affect * the layout in any way. * * That being said, hiding and un-hiding the status bar can change the * size of the top inset. E.g., on an iPhone without the "notch", the * top inset grows to accommodate a visible status bar, and shrinks to * give more room to the app's content when the status bar is hidden. */ export default function ZulipStatusBar(props: Props): Node { const { hidden = false } = props; const theme = useGlobalSelector(state => getGlobalSettings(state).theme); const osScheme = useColorScheme(); const themeToUse = getThemeToUse(theme, osScheme); const orientation = useGlobalSelector(state => getGlobalSession(state).orientation); const backgroundColor = props.backgroundColor; const statusBarColor = getStatusBarColor(backgroundColor, themeToUse); return ( orientation === 'PORTRAIT' && ( <StatusBar animated showHideTransition="slide" hidden={hidden && Platform.OS !== 'android'} backgroundColor={Color(statusBarColor).darken(0.1).hsl().string()} barStyle={getStatusBarStyle(statusBarColor)} /> ) ); } ```
/content/code_sandbox/src/common/ZulipStatusBar.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
607
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import type { Style } from '../types'; type Props = $ReadOnly<{| children: $ReadOnlyArray<Node>, spacing?: number, outerSpacing?: boolean, style?: ViewStyleProp, itemStyle?: Style, |}>; /** * A convenience component that uniformly styles and spaces its children. * * @prop children - Components to be styled. * @prop [spacing] - Set distance between components by setting * marginBottom on all but the last component. * @prop [outerSpacing] - Set a margin around the list. * @prop [style] - Style of the wrapper container. * @prop [itemStyle] - Style applied to each child. */ export default function ComponentList(props: Props): Node { const { children, itemStyle, spacing = 16, outerSpacing = true, style } = props; const outerStyle = outerSpacing ? { margin: spacing } : {}; const marginStyle = { marginBottom: spacing }; const childrenToRender = React.Children.toArray(children).filter(child => child); const childrenWithStyles = childrenToRender.map((child, i) => React.cloneElement(child, { style: [child.props.style, i + 1 < childrenToRender.length ? marginStyle : {}, itemStyle], }), ); return <View style={[style, outerStyle]}>{childrenWithStyles}</View>; } ```
/content/code_sandbox/src/common/ComponentList.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
337
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Platform, View } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import KeyboardAvoidingView from '../third/react-native/KeyboardAvoidingView'; type Props = $ReadOnly<{| behavior?: ?('height' | 'position' | 'padding'), children: Node, style?: ViewStyleProp, contentContainerStyle?: ViewStyleProp, /** * How much the top of `KeyboardAvoider`'s layout *parent* is * displaced downward from the top of the screen. * * If this isn't set correctly, the keyboard will hide some of * the bottom of the screen (an area whose height is what this * value should have been set to). * * I think `KeyboardAvoidingView`'s implementation mistakes `x` * and `y` from `View#onLayout` to be a `View`'s position * relative to the top left of the screen. In reality, I'm * pretty sure they represent a `View`'s position relative to * its parent: * path_to_url#issuecomment-773618381 * * But at least `KeyboardAvoidingView` exposes this prop, which * we can use to balance the equation if we need to. */ keyboardVerticalOffset?: number, /** * Whether to shorten the excursion by the height of the bottom inset. * * Use this when a child component uses SafeAreaView to pad the bottom * inset, and you want the open keyboard to cover that padding. * * (SafeAreaView has a bug where it applies a constant padding no matter * where it's positioned onscreen -- so in particular, if you ask for * bottom padding, you'll get bottom padding even when KeyboardAvoider * pushes the SafeAreaView up and out of the bottom inset.) */ compensateOverpadding?: boolean, |}>; /** * Renders RN's `KeyboardAvoidingView` on iOS, `View` on Android. * * This component's props that are named after * `KeyboardAvoidingView`'s special props get passed straight through * to that component. */ export default function KeyboardAvoider(props: Props): Node { const { behavior, children, style, contentContainerStyle, keyboardVerticalOffset = 0, // Same default value as KeyboardAvoidingView compensateOverpadding = false, } = props; const bottomInsetHeight = useSafeAreaInsets().bottom; if (Platform.OS === 'android') { return <View style={style}>{children}</View>; } return ( <KeyboardAvoidingView behavior={behavior} contentContainerStyle={contentContainerStyle} // See comment on this prop in the jsdoc. keyboardVerticalOffset={ keyboardVerticalOffset // A negative term here reduces the bottom inset we use for the // child, when the keyboard is open, so that the keyboard covers its // bottom padding. + (compensateOverpadding ? -bottomInsetHeight : 0) } style={style} > {children} </KeyboardAvoidingView> ); } ```
/content/code_sandbox/src/common/KeyboardAvoider.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
739
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; type Props = $ReadOnly<{| width?: number, height?: number, |}>; /** * An empty layout component used to simplify UI alignment. * Use when it is easier to use this instead of setting component * padding and margin. * * @prop [width] - Width of the component in pixels. * @prop [height] - Height of the component in pixels. */ export default function ViewPlaceholder(props: Props): Node { const { width, height } = props; const style = { width, height }; return <View style={style} />; } ```
/content/code_sandbox/src/common/ViewPlaceholder.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
152
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import subDays from 'date-fns/subDays'; import ZulipBanner from './ZulipBanner'; import { useSelector, useDispatch, useGlobalSelector } from '../react-redux'; import { getAccount, getSilenceServerPushSetupWarnings } from '../account/accountsSelectors'; import { dismissServerNotifsExpiringBanner } from '../account/accountActions'; import { kPushNotificationsEnabledEndDoc, pushNotificationsEnabledEndTimestampWarning, } from '../settings/NotifTroubleshootingScreen'; import { useDateRefreshedAtInterval } from '../reactUtils'; import { openLinkWithUserPreference } from '../utils/openLink'; import { getGlobalSettings } from '../directSelectors'; type Props = $ReadOnly<{||}>; /** * A "nag banner" saying the server will soon disable notifications, if so. * * Offers a dismiss button. If this notice is dismissed, it sleeps for a * week, then reappears if the warning still applies. */ export default function ServerNotifsExpiringBanner(props: Props): Node { const dispatch = useDispatch(); const globalSettings = useGlobalSelector(getGlobalSettings); const lastDismissedServerNotifsExpiringBanner = useSelector( state => getAccount(state).lastDismissedServerNotifsExpiringBanner, ); const perAccountState = useSelector(state => state); const dateNow = useDateRefreshedAtInterval(60_000); const expiryWarning = pushNotificationsEnabledEndTimestampWarning(perAccountState, dateNow); const silenceServerPushSetupWarnings = useSelector(getSilenceServerPushSetupWarnings); let visible = false; let text = ''; if (expiryWarning == null) { // don't show } else if (silenceServerPushSetupWarnings) { // don't show } else if ( lastDismissedServerNotifsExpiringBanner !== null && lastDismissedServerNotifsExpiringBanner >= subDays(dateNow, 8) ) { // don't show } else { visible = true; text = expiryWarning.reactText; } const buttons = []; buttons.push({ id: 'dismiss', label: 'Dismiss', onPress: () => { dispatch(dismissServerNotifsExpiringBanner()); }, }); buttons.push({ id: 'learn-more', label: 'Learn more', onPress: () => { openLinkWithUserPreference(kPushNotificationsEnabledEndDoc, globalSettings); }, }); return <ZulipBanner visible={visible} text={text} buttons={buttons} />; } ```
/content/code_sandbox/src/common/ServerNotifsExpiringBanner.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
570
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { ThemeContext, createStyleSheet } from '../styles'; const componentStyles = createStyleSheet({ lineSeparator: { height: 1, margin: 4, }, }); export default function LineSeparator(props: {||}): Node { const themeContext = useContext(ThemeContext); return ( <View style={[componentStyles.lineSeparator, { backgroundColor: themeContext.cardColor }]} /> ); } ```
/content/code_sandbox/src/common/LineSeparator.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
122
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import ZulipBanner from './ZulipBanner'; import { useSelector, useGlobalSelector, useDispatch } from '../react-redux'; import { getOwnUser } from '../selectors'; import { getIdentity, getServerVersion } from '../account/accountsSelectors'; import { getSession, getGlobalSettings } from '../directSelectors'; import { dismissCompatNotice } from '../session/sessionActions'; import { openLinkWithUserPreference } from '../utils/openLink'; import { ZulipVersion } from '../utils/zulipVersion'; import { roleIsAtLeast } from '../permissionSelectors'; import { Role } from '../api/permissionsTypes'; /** * The doc stating our oldest supported server version. */ // TODO: Instead, link to new Help Center doc once we have it: // path_to_url export const kServerSupportDocUrl: URL = new URL( 'path_to_url#compatibility-and-upgrading', ); /** * The oldest version we currently support. * * Should match the policy stated at kServerSupportDocUrl: all versions * below this should be older than 18 months. * * See also kMinAllowedServerVersion in apiErrors.js, for the version below * which we just refuse to connect. */ export const kMinSupportedVersion: ZulipVersion = new ZulipVersion('5.0'); /** * The next value we'll give to kMinSupportedVersion in the future. * * This should be the next major Zulip Server version after kMinSupportedVersion. */ export const kNextMinSupportedVersion: ZulipVersion = new ZulipVersion('6.0'); type Props = $ReadOnly<{||}>; /** * A "nag banner" saying the server version is unsupported, if so. */ export default function ServerCompatBanner(props: Props): Node { const dispatch = useDispatch(); const hasDismissedServerCompatNotice = useSelector( state => getSession(state).hasDismissedServerCompatNotice, ); const zulipVersion = useSelector(getServerVersion); const realm = useSelector(state => getIdentity(state).realm); const isAtLeastAdmin = useSelector(state => roleIsAtLeast(getOwnUser(state).role, Role.Admin)); const settings = useGlobalSelector(getGlobalSettings); let visible = false; let text = ''; if (zulipVersion.isAtLeast(kMinSupportedVersion)) { // don't show } else if (hasDismissedServerCompatNotice) { // don't show } else { visible = true; text = isAtLeastAdmin ? { text: '{realm} is running Zulip Server {serverVersion}, which is unsupported. Please upgrade your server as soon as possible.', values: { realm: realm.toString(), serverVersion: zulipVersion.raw() }, } : { text: '{realm} is running Zulip Server {serverVersion}, which is unsupported. Please contact your administrator about upgrading.', values: { realm: realm.toString(), serverVersion: zulipVersion.raw() }, }; } return ( <ZulipBanner visible={visible} text={text} buttons={[ { id: 'dismiss', label: 'Dismiss', onPress: () => { dispatch(dismissCompatNotice()); }, }, { id: 'learn-more', label: 'Learn more', onPress: () => { openLinkWithUserPreference(kServerSupportDocUrl, settings); }, }, ]} /> ); } ```
/content/code_sandbox/src/common/ServerCompatBanner.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
766
```javascript /* @flow strict-local */ import * as React from 'react'; import { View } from 'react-native'; import SwitchRow from './SwitchRow'; import TextRow from './TextRow'; import NavRow from './NavRow'; import type { LocalizableReactText } from '../types'; import { createStyleSheet } from '../styles'; import { QUARTER_COLOR } from '../styles/constants'; import ZulipTextIntl from './ZulipTextIntl'; type Props = $ReadOnly<{| /** * The current style works best if this ends in a colon. */ // The need to suggest a colon is probably a sign that we can improve the // layout in some subtle way. title?: LocalizableReactText, children: $ReadOnlyArray< React$Element<typeof SwitchRow> | React$Element<typeof NavRow> | React$Element<typeof TextRow>, >, |}>; export default function RowGroup(props: Props): React.Node { const { title, children } = props; const styles = React.useMemo( () => createStyleSheet({ container: { overflow: 'hidden', backgroundColor: QUARTER_COLOR, // TODO: Better color marginVertical: 4, }, headerContainer: { justifyContent: 'center', paddingHorizontal: 16, paddingVertical: 8, minHeight: 48, }, }), [], ); return ( <View style={styles.container}> {title != null && ( <View style={styles.headerContainer}> <ZulipTextIntl text={title} /> </View> )} {children} </View> ); } ```
/content/code_sandbox/src/common/RowGroup.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
355
```javascript /* @flow strict-local */ import { getStatusBarStyle } from '../ZulipStatusBar'; describe('getStatusBarStyle', () => { test('return bar style according to given color', () => { expect(getStatusBarStyle('#fff')).toEqual('dark-content'); expect(getStatusBarStyle('#000')).toEqual('light-content'); }); }); ```
/content/code_sandbox/src/common/__tests__/getStatusBarStyle-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
72
```javascript /* @flow strict-local */ import { getStatusBarColor } from '../ZulipStatusBar'; const themeDark = 'dark'; const themeLight = 'light'; describe('getStatusBarColor', () => { test('returns specific color when given, regardless of theme', () => { expect(getStatusBarColor('#fff', themeLight)).toEqual('#fff'); expect(getStatusBarColor('#fff', themeDark)).toEqual('#fff'); }); test('returns color according to theme for default case', () => { expect(getStatusBarColor(undefined, themeLight)).toEqual('white'); expect(getStatusBarColor(undefined, themeDark)).toEqual('hsl(212, 28%, 18%)'); }); }); ```
/content/code_sandbox/src/common/__tests__/getStatusBarColor-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
147
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { Message, Narrow } from '../types'; import { createStyleSheet } from '../styles'; import LoadingIndicator from '../common/LoadingIndicator'; import SearchEmptyState from '../common/SearchEmptyState'; import MessageList from '../webview/MessageList'; const styles = createStyleSheet({ results: { flex: 1, }, }); type Props = $ReadOnly<{| messages: $ReadOnlyArray<Message> | null, narrow: Narrow, isFetching: boolean, fetchNewer: () => Promise<void> | void, fetchOlder: () => Promise<void> | void, |}>; export default function SearchMessagesCard(props: Props): Node { const { narrow, isFetching, messages } = props; if (isFetching) { // Display loading indicator only if there are no messages to // display from a previous search. if (!messages || messages.length === 0) { return <LoadingIndicator size={40} />; } } if (!messages) { return null; } if (messages.length === 0) { return <SearchEmptyState text="No results" />; } return ( <View style={styles.results}> <MessageList initialScrollMessageId={ // This access is OK only because of the `.length === 0` check // above. messages[messages.length - 1].id } messages={messages} narrow={narrow} showMessagePlaceholders={false} // TODO: handle editing a message from the search results, // or make this prop optional startEditMessage={() => undefined} fetchOlder={props.fetchOlder} fetchNewer={props.fetchNewer} composeBoxRef={{ current: null }} // fake; no compose box on screen /> </View> ); } ```
/content/code_sandbox/src/search/SearchMessagesCard.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
426
```javascript /* @flow strict-local */ import type { Dispatch, StoreEnhancer } from 'redux'; import { REHYDRATE } from '../actionConstants'; import type { Action, GlobalState as State } from '../types'; import * as logging from '../utils/logging'; const processKey = key => { const int = parseInt(key, 10); if (Number.isNaN(int)) { throw new Error('redux-persist-migrate: migrations must be keyed with integer values'); } return int; }; /* eslint-disable no-use-before-define */ type PartialState = $ReadOnly<$Rest<State, { ... }>>; export default function createMigration( manifest: {| [string]: (PartialState) => PartialState |}, reducerKey: string, ): StoreEnhancer<State, Action, Dispatch<Action>> { const migratePayload = createMigrationFunction(manifest, reducerKey); const migrationDispatch = next => (action: Action) => { if (action.type === REHYDRATE) { return next({ ...action, payload: migratePayload(action.payload) }); } return next(action); }; return next => (reducer, initialState) => { const store = next(reducer, initialState); return { ...store, dispatch: migrationDispatch(store.dispatch), }; }; } /** Exported only for tests. */ export function createMigrationFunction( manifest: {| [string]: (PartialState) => PartialState |}, reducerKey: string, ): PartialState => PartialState { const versionSelector = state => state && state[reducerKey] && state[reducerKey].version; const versionSetter = (state, version) => { if (['undefined', 'object'].indexOf(typeof state[reducerKey]) === -1) { logging.error( 'redux-persist-migrate: state for versionSetter key must be an object or undefined', { version, reducerKey, 'actual-state': state[reducerKey] }, ); return state; } return { ...state, [reducerKey]: { ...state[reducerKey], version } }; }; const versionKeys = Object.keys(manifest) .map(processKey) .sort((a, b) => a - b); let currentVersion = versionKeys[versionKeys.length - 1]; if (!currentVersion && currentVersion !== 0) { currentVersion = -1; } const migrate = (state, version) => { let newState = state; versionKeys .filter(v => v > version || version === null) .forEach(v => { newState = manifest[v.toString()](newState); }); newState = versionSetter(newState, currentVersion); return newState; }; return function migratePayload(incomingState: PartialState): PartialState { const incomingVersion = parseInt(versionSelector(incomingState), 10); if (Number.isNaN(incomingVersion)) { // first launch after install, so incoming state is empty object // migration not required, just update version const payload = versionSetter(incomingState, currentVersion); return payload; } if (incomingVersion !== currentVersion) { const migratedState = migrate(incomingState, incomingVersion); return migratedState; } return incomingState; }; } ```
/content/code_sandbox/src/redux-persist-migrate/index.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
709
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import invariant from 'invariant'; import type { ComponentType } from 'react'; import type { EditingEvent } from 'react-native/Libraries/Components/TextInput/TextInput'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import type { Auth, Dispatch, Message } from '../types'; import Screen from '../common/Screen'; import SearchMessagesCard from './SearchMessagesCard'; import { SEARCH_NARROW } from '../utils/narrow'; import { LAST_MESSAGE_ANCHOR } from '../anchor'; import { connect } from '../react-redux'; import { getAuth } from '../account/accountsSelectors'; import { fetchMessages } from '../message/fetchActions'; import { getLoading } from '../directSelectors'; import config from '../config'; type OuterProps = $ReadOnly<{| // These should be passed from React Navigation navigation: AppNavigationProp<'search-messages'>, route: RouteProp<'search-messages', void>, |}>; type SelectorProps = $ReadOnly<{| auth: Auth, loading: boolean, |}>; type Props = $ReadOnly<{| ...OuterProps, dispatch: Dispatch, ...SelectorProps, // Warning: do not add new props without considering their effect on the // behavior of this component's non-React internal state. See comment below. |}>; type State = {| /** The latest search query we have results for. */ query: string, /** * The list of messages found as results for `query`. * * This is `null` if `query` is empty, representing an empty search box * and so effectively not a query to have results from at all. */ messages: $ReadOnlyArray<Message> | null, /** Whether there is currently an active valid network request. */ isFetching: boolean, /** Same as caughtUp.older in GlobalState, but for search screen. */ foundOldest: boolean, |}; class SearchMessagesScreenInner extends PureComponent<Props, State> { state = { query: '', messages: null, isFetching: false, foundOldest: true, }; /** * PRIVATE. Send search query to server, fetching message results. * * Stores the fetched messages in the Redux store. Does not read any * of the component's data except `props.dispatch`. */ fetchSearchMessages = async ( query: string, ): Promise<{ foundNewest: boolean, foundOldest: boolean, messages: $ReadOnlyArray<Message>, }> => { const fetchArgs = { narrow: SEARCH_NARROW(query), anchor: LAST_MESSAGE_ANCHOR, numBefore: config.messagesPerRequest, numAfter: 0, }; return this.props.dispatch(fetchMessages(fetchArgs)); }; // Non-React state. See comment following. // Invariant: lastIdSuccess <= lastIdReceived <= lastIdSent. lastIdSuccess: number = 1000; lastIdReceived: number = 1000; lastIdSent: number = 1000; isFetchingOlder: boolean = false; // This component is less pure than it should be. The correct behavior here is // probably that, when props change, all outstanding asynchronous requests // should be **synchronously** invalidated before the next render. // // As the only React prop this component has is `auth`, we ignore this for // now: any updates to `auth` would involve this screen being torn down and // reconstructed anyway. However, addition of any new props which need to // invalidate outstanding requests on change will require more work. handleQuerySubmit = async (e: EditingEvent) => { const query = e.nativeEvent.text; const id = ++this.lastIdSent; if (query === '') { // The empty query can be resolved without a network call. this.lastIdReceived = id; this.lastIdSuccess = id; this.setState({ query, messages: null, isFetching: false, foundOldest: true, }); return; } this.setState({ isFetching: true }); try { const { messages, foundOldest } = await this.fetchSearchMessages(query); // Update `state.messages` if this is our new latest result. if (id > this.lastIdSuccess) { this.lastIdSuccess = id; this.setState({ query, messages, foundOldest, }); } } finally { // Updating `isFetching` is the same for success or failure. if (id > this.lastIdReceived) { this.lastIdReceived = id; if (this.lastIdReceived === this.lastIdSent) { this.setState({ isFetching: false }); } // TODO: if the request failed, should we arrange to display // something to the user? } } }; // The real work to be done on a query is async. This wrapper exists // just to fire off `handleQuerySubmit` without waiting for it. // TODO do we even need this wrapper? handleQuerySubmitWrapper = (e: EditingEvent) => { this.handleQuerySubmit(e); }; fetchOlder = async () => { if ( this.props.loading || this.state.foundOldest || this.state.isFetching || this.isFetchingOlder ) { return; } invariant( this.state.messages !== null && this.state.messages.length > 0, 'must have at least 1 message already fetched', ); this.isFetchingOlder = true; try { const { query } = this.state; const anchor = this.state.messages[0].id; // FlowIssue: Flow insists on this `await await`. // Should be equivalent to `await`, so harmless. // See: path_to_url#issuecomment-960296275 const { messages: fetchedMessages, foundOldest } = await await this.props.dispatch( fetchMessages({ anchor, narrow: SEARCH_NARROW(this.state.query), numBefore: config.messagesPerRequest, numAfter: 0, }), ); this.setState(prevState => { if ( prevState.query === query // FlowIssue: ?. is needed because array can be empty // flowlint-next-line unnecessary-optional-chain:off && anchor === prevState.messages?.[0]?.id ) { // remove the anchor element, that gets fetched by default fetchedMessages.pop(); return { messages: [...fetchedMessages, ...prevState.messages], foundOldest }; } return {}; }); } finally { this.isFetchingOlder = false; } }; fetchNewer = () => { // Nothing to do. We fetched the messages with LAST_MESSAGE_ANCHOR // to begin with, so there's no further to scroll down. }; render() { const { messages, isFetching } = this.state; return ( <Screen search autoFocus searchBarOnSubmit={this.handleQuerySubmitWrapper} scrollEnabled={false} > <SearchMessagesCard messages={messages} isFetching={isFetching} narrow={SEARCH_NARROW(this.state.query)} fetchNewer={this.fetchNewer} fetchOlder={this.fetchOlder} /> </Screen> ); } } const SearchMessagesScreen: ComponentType<OuterProps> = connect(state => ({ auth: getAuth(state), loading: getLoading(state), }))(SearchMessagesScreenInner); export default SearchMessagesScreen; ```
/content/code_sandbox/src/search/SearchMessagesScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,673
```javascript /* @flow strict-local */ import type { CaughtUp, CaughtUpState, PerAccountState, Narrow } from '../types'; import { NULL_OBJECT } from '../nullObjects'; import { keyFromNarrow } from '../utils/narrow'; /** The value implicitly represented by a missing entry in CaughtUpState. */ export const DEFAULT_CAUGHTUP: CaughtUp = { older: false, newer: false, }; export const getCaughtUp = (state: PerAccountState): CaughtUpState => state.caughtUp || NULL_OBJECT; export const getCaughtUpForNarrowInner = (state: CaughtUpState, narrow: Narrow): CaughtUp => state[keyFromNarrow(narrow)] || DEFAULT_CAUGHTUP; export const getCaughtUpForNarrow = (state: PerAccountState, narrow: Narrow): CaughtUp => getCaughtUpForNarrowInner(getCaughtUp(state), narrow); ```
/content/code_sandbox/src/caughtup/caughtUpSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
189
```javascript import deepFreeze from 'deep-freeze'; import { getCaughtUpForNarrow } from '../caughtUpSelectors'; import { HOME_NARROW, HOME_NARROW_STR } from '../../utils/narrow'; describe('getCaughtUpForNarrow', () => { test('if a key with current narrow exists return it', () => { const state = deepFreeze({ caughtUp: { [HOME_NARROW_STR]: { older: false, newer: true }, }, }); const caughtUp = getCaughtUpForNarrow(state, HOME_NARROW); expect(caughtUp).toEqual({ older: false, newer: true }); }); test('when caught up key does not exist return default values of false', () => { const state = deepFreeze({ caughtUp: {}, }); const caughtUp = getCaughtUpForNarrow(state, HOME_NARROW); expect(caughtUp).toEqual({ older: false, newer: false }); }); }); ```
/content/code_sandbox/src/caughtup/__tests__/caughtUpSelectors-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
214
```javascript /* @flow strict-local */ import type { CaughtUpState, PerAccountApplicableAction } from '../types'; import { REGISTER_COMPLETE, MESSAGE_FETCH_START, MESSAGE_FETCH_ERROR, MESSAGE_FETCH_COMPLETE, EVENT_UPDATE_MESSAGE, EVENT_UPDATE_MESSAGE_FLAGS, RESET_ACCOUNT_DATA, } from '../actionConstants'; import { NULL_OBJECT } from '../nullObjects'; import { DEFAULT_CAUGHTUP } from './caughtUpSelectors'; import { isSearchNarrow, keyFromNarrow, streamNarrow, topicNarrow } from '../utils/narrow'; const initialState: CaughtUpState = NULL_OBJECT; /** Corresponds to the same-name function in the narrows reducer. */ function addMessages(state: CaughtUpState, narrow, messageIds): CaughtUpState { // NOTE: This behavior must stay parallel with how the narrows reducer // handles the same cases. // See narrowsReducer.js for discussion. const key = keyFromNarrow(narrow); // eslint-disable-next-line no-unused-vars const { [key]: ignored, ...rest } = state; return rest; } export default ( state: CaughtUpState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): CaughtUpState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; // Reset because `caughtUp` is server-data metadata, and we're resetting // the server data it's supposed to apply to: `state.narrows`. case REGISTER_COMPLETE: return initialState; case MESSAGE_FETCH_START: { // We don't want to accumulate old searches that we'll never // need again. if (isSearchNarrow(action.narrow)) { return state; } // Currently this whole case could be subsumed in `default`. But // we don't want to add this case with something else in mind, // later, and forget about the search-narrow check above. return state; } /** * The reverse of MESSAGE_FETCH_START, for cleanup. */ case MESSAGE_FETCH_ERROR: { return state; } case MESSAGE_FETCH_COMPLETE: { // We don't want to accumulate old searches that we'll never need again. if (isSearchNarrow(action.narrow)) { return state; } const key = keyFromNarrow(action.narrow); const { older: prevOlder, newer: prevNewer } = state[key] || DEFAULT_CAUGHTUP; return { ...state, [key]: { older: prevOlder || action.foundOldest, newer: prevNewer || action.foundNewest, }, }; } case EVENT_UPDATE_MESSAGE: { // Compare the corresponding narrowsReducer case. let result = state; const { event, move } = action; if (move) { const { orig_stream_id, new_stream_id, new_topic } = move; result = addMessages(result, topicNarrow(new_stream_id, new_topic), event.message_ids); if (new_stream_id !== orig_stream_id) { result = addMessages(result, streamNarrow(new_stream_id), event.message_ids); } } // We don't attempt to update search narrows. // The other way editing a message can affect what narrows it falls // into is by changing its flags. Those cause a separate event; see // the EVENT_UPDATE_MESSAGE_FLAGS case. return result; } case EVENT_UPDATE_MESSAGE_FLAGS: // TODO(#3408): Handle this to parallel narrowsReducer. return state; default: return state; } }; ```
/content/code_sandbox/src/caughtup/caughtUpReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
788
```javascript // @flow strict-local import type { UserId } from '../types'; type NotificationBase = {| realm_uri: string, user_id?: UserId, |}; /** * The data we need in JS/React code for acting on a notification. * * On iOS, these objects are constructed by our JS code from the data the * Zulip server sends in the APNs payload. See `fromAPNs` in * `src/notifications/extract.js`. * * On Android, these objects are sent to JS from our platform-native code, * constructed there by `MessageFcmMessage#dataForOpen` in `FcmMessage.kt`. * The correspondence of that code with this type isn't type-checked. */ // NOTE: Keep the Android-side code in sync with this type definition. export type Notification = | {| ...NotificationBase, recipient_type: 'stream', // TODO(server-5.0): Rely on stream ID (#3918). (We'll still want the // stream name, as a hint for display in case the stream is unknown; // see comment in getNarrowFromNotificationData.) stream_id?: number, stream_name: string, topic: string, |} // Group PM messages have `pm_users`, which is sorted, comma-separated IDs. | {| ...NotificationBase, recipient_type: 'private', pm_users: string |} // 1:1 PM messages lack `pm_users`. | {| ...NotificationBase, recipient_type: 'private', sender_email: string |}; ```
/content/code_sandbox/src/notification/types.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
336
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import * as eg from '../../__tests__/lib/exampleData'; import caughtUpReducer from '../caughtUpReducer'; import { MESSAGE_FETCH_ERROR } from '../../actionConstants'; import { HOME_NARROW, HOME_NARROW_STR, keyFromNarrow, SEARCH_NARROW, streamNarrow, topicNarrow, pm1to1NarrowFromUser, } from '../../utils/narrow'; import { objectFromEntries } from '../../jsBackport'; describe('caughtUpReducer', () => { describe('RESET_ACCOUNT_DATA', () => { const initialState = eg.baseReduxState.caughtUp; const action1 = { ...eg.action.message_fetch_complete, foundNewest: true, foundOldest: true }; const prevState = caughtUpReducer(initialState, action1); expect(prevState).not.toEqual(initialState); expect(caughtUpReducer(prevState, eg.action.reset_account_data)).toEqual(initialState); }); describe('REGISTER_COMPLETE', () => { const initialState = eg.baseReduxState.caughtUp; const prevState = caughtUpReducer(initialState, { ...eg.action.message_fetch_complete, foundNewest: true, foundOldest: true, }); expect(prevState).not.toEqual(initialState); expect(caughtUpReducer(prevState, eg.action.register_complete)).toEqual(initialState); }); describe('MESSAGE_FETCH_START', () => { test('when fetch starts caught up does not change', () => { const prevState = deepFreeze({ [HOME_NARROW_STR]: { older: true, newer: true } }); expect( caughtUpReducer( prevState, deepFreeze({ ...eg.action.message_fetch_start, narrow: HOME_NARROW }), ), ).toBe(prevState); }); test('if fetching for a search narrow, ignore', () => { const prevState = deepFreeze({ [HOME_NARROW_STR]: { older: false, newer: false } }); expect( caughtUpReducer( prevState, deepFreeze({ ...eg.action.message_fetch_start, narrow: SEARCH_NARROW('some query') }), ), ).toEqual(prevState); }); }); describe('MESSAGE_FETCH_ERROR', () => { test('reverses the effect of MESSAGE_FETCH_START as much as possible', () => { // As of the addition of this test, it's fully possible: // MESSAGE_FETCH_START applies the identity function to the // state (i.e., it doesn't do anything to it). Reversing that // effect is also done with the identity function. const narrow1 = pm1to1NarrowFromUser(eg.otherUser); const narrow2 = pm1to1NarrowFromUser(eg.thirdUser); // Include some other narrow to test that the reducer doesn't go mess // something up there. const initialState = deepFreeze({ [keyFromNarrow(narrow1)]: { older: true, newer: true } }); expect( [ deepFreeze({ ...eg.action.message_fetch_start, narrow: narrow2 }), deepFreeze({ type: MESSAGE_FETCH_ERROR, narrow: narrow2, error: new Error() }), ].reduce(caughtUpReducer, initialState), ).toEqual(initialState); }); }); describe('MESSAGE_FETCH_COMPLETE', () => { test('apply `foundNewest` and `foundOldest` when true', () => { const prevState = deepFreeze({}); expect( caughtUpReducer( prevState, deepFreeze({ ...eg.action.message_fetch_complete, foundNewest: true, foundOldest: true }), ), ).toEqual({ [HOME_NARROW_STR]: { older: true, newer: true } }); }); test('if fetched messages are from a search narrow, ignore them', () => { const prevState = deepFreeze({}); expect( caughtUpReducer( prevState, deepFreeze({ ...eg.action.message_fetch_complete, narrow: SEARCH_NARROW('some query'), foundOldest: true, foundNewest: true, }), ), ).toEqual(prevState); }); }); test('new false results do not reset previous true state', () => { const prevState = deepFreeze({ [HOME_NARROW_STR]: { older: true, newer: true } }); expect( caughtUpReducer( prevState, deepFreeze({ ...eg.action.message_fetch_complete, foundOldest: false, foundNewest: false }), ), ).toEqual({ [HOME_NARROW_STR]: { older: true, newer: true } }); }); describe('EVENT_UPDATE_MESSAGE', () => { const mkAction = args => { const { messages, ...restArgs } = args; const message = messages[0]; return eg.mkActionEventUpdateMessage({ message_id: message.id, message_ids: messages.map(m => m.id), stream_id: message.stream_id, orig_subject: message.subject, ...restArgs, }); }; const mkKey = (stream, topic) => topic !== undefined ? keyFromNarrow(topicNarrow(stream.stream_id, topic)) : keyFromNarrow(streamNarrow(stream.stream_id)); const topic1 = 'topic foo'; const topic2 = 'topic bar'; // const message1a = eg.streamMessage({ subject: topic1, id: 1 }); const message1b = eg.streamMessage({ subject: topic1, id: 2 }); // const message1c = eg.streamMessage({ subject: topic1, id: 3 }); // const message2a = eg.streamMessage({ subject: topic2, id: 4 }); test('new topic, same stream', () => { expect( caughtUpReducer( objectFromEntries([ [mkKey(eg.stream, topic1), { older: true, newer: true }], [mkKey(eg.stream, topic2), { older: true, newer: true }], [mkKey(eg.stream), { older: true, newer: true }], ]), mkAction({ messages: [message1b], subject: topic2 }), ), ).toEqual( objectFromEntries([ // old topic narrow remains caught up: [mkKey(eg.stream, topic1), { older: true, newer: true }], // new topic narrow gets cleared // stream narrow unchanged: [mkKey(eg.stream), { older: true, newer: true }], ]), ); }); test('same topic, new stream', () => { expect( caughtUpReducer( objectFromEntries([ [mkKey(eg.stream, topic1), { older: true, newer: true }], [mkKey(eg.stream), { older: true, newer: true }], [mkKey(eg.otherStream, topic1), { older: true, newer: true }], [mkKey(eg.otherStream), { older: true, newer: true }], ]), mkAction({ messages: [message1b], new_stream_id: eg.otherStream.stream_id }), ), ).toEqual( objectFromEntries([ // old topic and stream narrows remain caught up: [mkKey(eg.stream, topic1), { older: true, newer: true }], [mkKey(eg.stream), { older: true, newer: true }], // new topic and stream narrows both cleared ]), ); }); // Try to keep these tests corresponding closely to those for the // narrows reducer. (In the future these should really be a single // sub-reducer.) }); }); ```
/content/code_sandbox/src/caughtup/__tests__/caughtUpReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,662
```javascript /* @flow strict-local */ import PushNotificationIOS from '@react-native-community/push-notification-ios'; import type { Notification } from './types'; import { makeUserId } from '../api/idTypes'; import type { JSONableDict, JSONableInput, JSONableInputDict } from '../utils/jsonable'; import * as logging from '../utils/logging'; /** Confirm (or disprove) that a JSONableInput object is a dictionary. */ const asDict = (obj: JSONableInput | void): JSONableInputDict | void => { if (typeof obj !== 'object') { return undefined; } if (obj === null || obj instanceof Array) { return undefined; } return obj; }; /** Local error type. */ class ApnsMsgValidationError extends logging.ExtendableError { extras: logging.Extras; constructor(message, extras: logging.Extras) { super(message); this.extras = extras; } } /** Private. Exported only for tests. */ // // Extract Zulip notification data from a JSONable dictionary imported from an // APNs notification. // // @returns A `Notification` on success, `undefined` on suppressible failure. // @throws An ApnsMsgValidationError on unexpected failure. // export const fromAPNsImpl = (data: ?JSONableDict): Notification | void => { // // For the format this parses, see `ApnsPayload` in src/api/notificationTypes.js . // // Though in one case what it actually receives is more like this: // $Rest<ApnsPayload, {| aps: mixed |}> // That case is the "initial notification", a notification that launched // the app by being tapped, because the `PushNotificationIOS` library // parses the `ApnsPayload` and gives us (through `getData`) everything // but the `aps` property. /** Helper function: fail. */ const err = (style: string) => new ApnsMsgValidationError(`Received ${style} APNs notification`, { // an `undefined` value would make `extras` not JSONable, but we will // want to know if the value is undefined data: data === undefined ? '__undefined__' : data, }); if (data == null) { throw err('nullish'); } // Always present; see `ApnsPayload`. const zulip: JSONableInputDict | void = asDict(data.zulip); if (!zulip) { throw err('alien'); } // On Android, we also receive "remove" notification messages, tagged with an // `event` field with value 'remove'. As of 2.2-dev-775-g10e7e15088, however, // these are not yet sent to iOS devices, and we don't have a way to handle // them even if they were. // // The messages we currently do receive, and can handle, are analogous to // Android notification messages of event type 'message'. On the assumption // that some future version of the Zulip server will send explicit event types // in APNs messages, accept messages with that `event` value, but no other. const { event: eventType } = zulip; if (eventType !== 'message' && eventType !== undefined) { return undefined; } // // At this point we can begin trying to construct our `Notification`. // // For the format this code is parsing, see `ApnsPayload` in // src/api/notificationTypes.js . const { recipient_type } = zulip; if (recipient_type === undefined) { // Arguably not a real error, but we'd like to know when there are no longer // any of these servers left in the wild. throw err('archaic (pre-1.8.x)'); } if (typeof recipient_type !== 'string') { throw err('invalid'); } if (recipient_type !== 'stream' && recipient_type !== 'private') { throw err('invalid'); } const { realm_uri, user_id } = zulip; if (realm_uri === undefined) { throw err('archaic (pre-1.9.x)'); } if (typeof realm_uri !== 'string') { throw err('invalid'); } if (user_id !== undefined && typeof user_id !== 'number') { throw err('invalid'); } const identity = { realm_uri, ...(user_id === undefined ? Object.freeze({}) : { user_id: makeUserId(user_id) }), }; if (recipient_type === 'stream') { const { stream: stream_name, stream_id, topic } = zulip; if (typeof stream_name !== 'string' || typeof topic !== 'string') { throw err('invalid'); } if (stream_id !== undefined && typeof stream_id !== 'number') { throw err('invalid'); } return { ...identity, recipient_type: 'stream', ...((stream_id !== undefined ? { stream_id } : Object.freeze({})): { stream_id?: number }), stream_name, topic, }; } else { /* recipient_type === 'private' */ const { sender_email, pm_users } = zulip; if (pm_users !== undefined) { if (typeof pm_users !== 'string') { throw err('invalid'); } const ids = pm_users.split(',').map(s => parseInt(s, 10)); if (ids.some(id => Number.isNaN(id))) { throw err('invalid'); } return { ...identity, recipient_type: 'private', pm_users: ids.sort((a, b) => a - b).join(','), }; } if (typeof sender_email !== 'string') { throw err('invalid'); } return { ...identity, recipient_type: 'private', sender_email }; } /* unreachable */ }; /** * Extract Zulip notification data from a JSONable dictionary imported from an * APNs notification. Logs validation errors as warnings. * * @returns A `Notification` on success; `undefined` on failure. */ export const fromAPNs = (data: ?JSONableDict): Notification | void => { try { return fromAPNsImpl(data); } catch (errorIllTyped) { const err: mixed = errorIllTyped; // path_to_url if (err instanceof ApnsMsgValidationError) { logging.warn(err.message, err.extras); return undefined; } throw err; } }; // Despite the name `fromAPNs`, there is no parallel Android-side `fromFCM` // function here; the relevant task is performed in `FcmMessage.kt`. /** * Extract Zulip notification data from the blob our iOS libraries give us. * * On validation error (indicating a bug in either client or server), * logs a warning and returns void. * * On valid but unrecognized input (like a future, unknown type of * notification event), returns void. */ export const fromPushNotificationIOS = (notification: PushNotificationIOS): Notification | void => { // This is actually typed as ?Object (and so effectively `any`); but if // present, it must be a JSONable dictionary. It's giving us the // notification data, which was passed over APNs as JSON. const data: ?JSONableDict = notification.getData(); return fromAPNs(data); }; ```
/content/code_sandbox/src/notification/extract.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,623
```javascript /** * @flow strict-local */ import invariant from 'invariant'; import { Platform, PermissionsAndroid } from 'react-native'; import { androidSdkVersion } from '../reactNativeUtils'; /** * Show dialog requesting POST_NOTIFICATIONS permission if appropriate. * * See Android doc: * path_to_url * * If androidSdkVersion() < 33 (Android 13), skips the permission request * and returns null. The permission only exists on Android 13 and above. * * Returns true if already granted or granted now, * or false if denied or if "don't ask again" applies. * * If the user has chosen "Deny" more than once during the app's lifetime of * installation, the dialog won't appear ("don't ask again" is assumed): * path_to_url#handle-denial */ export const androidRequestNotificationsPermission = async (): Promise<boolean | null> => { invariant(Platform.OS === 'android', 'androidRequestNotificationsPermission called on iOS'); if (androidSdkVersion() < 33) { return null; } // See docs from Android for the underlying interaction with the user: // path_to_url // TODO(react-native-72): Use constant added in facebook/react-native@910a750fb: // PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS const permission = 'android.permission.POST_NOTIFICATIONS'; const granted = await PermissionsAndroid.check(permission); if (granted) { return true; } const result = await PermissionsAndroid.request(permission, { // RN uses this `rationale` argument to build a modal explaining why the // app needs the permission. Android and RN both have logic affecting // whether the modal is shown. For example, it may be shown if the // permission is being requested after previously being denied: // path_to_url#explain // The "OK" button dismisses the modal, after which Android's plain // Yes/No dialog will appear for the permission request. // TODO(i18n) title: 'Notifications', // TODO: Offer link to a help doc saying how to configure which // messages you get notifications for. message: 'Zulip can send push notifications about messages you might be interested in.', buttonPositive: 'OK', }); return result === PermissionsAndroid.RESULTS.GRANTED; }; ```
/content/code_sandbox/src/notification/androidPermission.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
507
```javascript /** * Opening a notification. * * @flow strict-local */ import { NativeModules, Platform } from 'react-native'; import PushNotificationIOS from '@react-native-community/push-notification-ios'; import type { Notification } from './types'; import type { Account, GlobalThunkAction, Identity, Narrow, Stream, UserId, UserOrBot, } from '../types'; import { topicNarrow, pm1to1NarrowFromUser, pmNarrowFromRecipients } from '../utils/narrow'; import * as logging from '../utils/logging'; import { fromPushNotificationIOS } from './extract'; import { isUrlOnRealm, tryParseUrl } from '../utils/url'; import { pmKeyRecipientsFromIds } from '../utils/recipient'; import { makeUserId } from '../api/idTypes'; import { getStreamsByName } from '../selectors'; import { getAccounts } from '../directSelectors'; import { getAllUsersByEmail, getOwnUserId } from '../users/userSelectors'; import { doNarrow } from '../message/messagesActions'; import { accountSwitch } from '../account/accountActions'; import { getIsActiveAccount, tryGetActiveAccountState } from '../account/accountsSelectors'; import { identityOfAccount } from '../account/accountMisc'; /** * Identify the account the notification is for, if possible. * * Returns an Identity of the account, or `null` if we haven't identified * the account. In the latter case, logs a warning. * * @param accounts The accounts state in Redux. */ export const getAccountFromNotificationData = ( data: Notification, accounts: $ReadOnlyArray<Account>, ): Identity | null => { const { realm_uri, user_id } = data; if (realm_uri == null) { // Old server, no realm info included. This field appeared in // Zulip 1.8, so we don't support these servers anyway. logging.warn('notification missing field: realm_uri'); return null; } const realmUrl = tryParseUrl(realm_uri); if (realmUrl === undefined) { logging.warn('notification realm_uri invalid as URL', { realm_uri }); return null; } const urlMatches = []; accounts.forEach(account => { if (isUrlOnRealm(account.realm, realmUrl)) { urlMatches.push(account); } }); if (urlMatches.length === 0) { // No match. Either we logged out of this account and didn't // successfully tell the server to stop sending notifications (possibly // just a race -- this notification was sent before the logout); or // there's some confusion where the realm_uri we have is different from // the one the server sends in notifications. const knownUrls = accounts.map(({ realm }) => realm.href); logging.warn('notification realm_uri not found in accounts', { realm_uri, parsed_url: realmUrl.toString(), known_urls: knownUrls, }); return null; } // TODO(server-2.1): Remove this, because user_id will always be present if (user_id === undefined) { if (urlMatches.length > 1) { logging.warn( 'notification realm_uri ambiguous; multiple matches found; user_id missing (old server)', { realm_uri, parsed_url: realmUrl.toString(), match_count: urlMatches.length, unique_identities_count: new Set(urlMatches.map(account => account.email)).size, }, ); return null; } else { return identityOfAccount(urlMatches[0]); } } // There may be multiple accounts in the notification's realm. Pick one // based on the notification's `user_id`. const userMatch = urlMatches.find(account => account.userId === user_id); if (userMatch == null) { // Maybe we didn't get a userId match because the correct account just // hasn't had its userId recorded on it yet. See jsdoc on the Account // type for when that is. const nullUserIdMatches = urlMatches.filter(account => account.userId === null); switch (nullUserIdMatches.length) { case 0: logging.warn( 'notifications: No accounts found with matching realm and matching-or-null user ID', ); return null; case 1: return identityOfAccount(nullUserIdMatches[0]); default: logging.warn( 'notifications: Multiple accounts found with matching realm and null user ID; could not choose', { nullUserIdMatchesCount: nullUserIdMatches.length }, ); return null; } } return identityOfAccount(userMatch); }; export const getNarrowFromNotificationData = ( data: Notification, allUsersByEmail: Map<string, UserOrBot>, streamsByName: Map<string, Stream>, ownUserId: UserId, ): Narrow | null => { if (!data.recipient_type) { // This condition is impossible if the value is rightly-typed; but in // the iOS case it comes more or less unfiltered from the Zulip server, // so we check here. // // TODO check further upstream instead, at a "crunchy shell". return null; } // TODO: If the notification is in an unknown stream, or a 1:1 PM from an // unknown user, give a better error. (This can happen for the stream // case if we were removed from the stream after the notification's // message was sent. It can also happen if the user or stream was just // created, and we haven't yet learned about it in the event queue; see // e068771d7, which fixed this issue for group PMs.) // // A nice version would navigate to ChatScreen for that unknown // conversation, which would show InvalidNarrow (with its sensible error // message) and whatever the notification did tell us about the // stream/user: in particular, the stream name. // // But because Narrow objects don't carry stream names, doing that will // require some alternate plumbing to pass the stream name through. For // now, we skip dealing with that; this should be an uncommon case, so // we settle for not crashing. // // Specifically, if the notification comes with a stream ID or user IDs, // we navigate to a ChatScreen and it shows InvalidNarrow, but we don't // report the stream name etc. If not, we ignore the notification. if (data.recipient_type === 'stream') { // TODO(server-5.0): Always use the stream ID (#3918). if (data.stream_id !== undefined) { // Ideally we'd also record the stream name here, for a better error // UX in case the stream is unknown. See long TODO comment above. return topicNarrow(data.stream_id, data.topic); } const stream = streamsByName.get(data.stream_name); return (stream && topicNarrow(stream.stream_id, data.topic)) ?? null; } if (data.pm_users === undefined) { const user = allUsersByEmail.get(data.sender_email); return (user && pm1to1NarrowFromUser(user)) ?? null; } const ids = data.pm_users.split(',').map(s => makeUserId(parseInt(s, 10))); return pmNarrowFromRecipients(pmKeyRecipientsFromIds(ids, ownUserId)); }; /** * Read the notification the app was started from, if any. * * This consumes the data; if called a second time, the result is always * null. * * (TODO: Well, it does on Android, anyway. #4763 is for doing so on iOS.) */ const readInitialNotification = async (): Promise<Notification | null> => { if (Platform.OS === 'android') { const { Notifications } = NativeModules; return Notifications.readInitialNotification(); } const notification: ?PushNotificationIOS = await PushNotificationIOS.getInitialNotification(); if (!notification) { return null; } return fromPushNotificationIOS(notification) || null; }; export const narrowToNotification = (data: ?Notification): GlobalThunkAction<void> => (dispatch, getState, { activeAccountDispatch }) => { if (!data) { return; } const globalState = getState(); const identity = getAccountFromNotificationData(data, getAccounts(globalState)); if (identity !== null && !getIsActiveAccount(getState(), identity)) { // Notification is for a non-active account. Switch there. dispatch(accountSwitch(identity)); // TODO actually narrow to conversation. return; } // If accountIndex is null, then `getAccountFromNotificationData` has // already logged a warning. We go on to treat it as if it's 0, i.e. the // active account, in the hopes that the user has one account they use // regularly and it's the same one this notification is for. const state = tryGetActiveAccountState(globalState); if (!state) { // There are no accounts at all. (Which also means accountIndex is null // and we've already logged a warning.) return; } const narrow = getNarrowFromNotificationData( data, getAllUsersByEmail(state), getStreamsByName(state), getOwnUserId(state), ); if (narrow) { activeAccountDispatch(doNarrow(narrow)); } }; /** * Act on the notification-opening the app was started from, if any. * * That is, if the app was started by the user opening a notification, act * on that; in particular, navigate to the conversation the notification was * from. * * This consumes the relevant data; if called multiple times after the user * only once opened a notification, it'll only do anything once. */ export const handleInitialNotification = (): GlobalThunkAction<Promise<void>> => async dispatch => { const data = await readInitialNotification(); dispatch(narrowToNotification(data)); }; ```
/content/code_sandbox/src/notification/notifOpen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,180
```javascript /** * Device tokens for notifications: getting them, reporting them, recording them. * * @flow strict-local */ import { NativeModules, Platform } from 'react-native'; import PushNotificationIOS from '@react-native-community/push-notification-ios'; import { GOT_PUSH_TOKEN, ACK_PUSH_TOKEN, REGISTER_PUSH_TOKEN_START, UNACK_PUSH_TOKEN, REGISTER_PUSH_TOKEN_END, } from '../actionConstants'; import type { Account, Identity, AccountIndependentAction, AllAccountsAction, ThunkAction, GlobalThunkAction, } from '../types'; import type { JSONable } from '../utils/jsonable'; import * as api from '../api'; import { getGlobalSession, getAccounts } from '../directSelectors'; import { identityOfAccount, authOfAccount, identityOfAuth } from '../account/accountMisc'; import { getAccount } from '../account/accountsSelectors'; import { androidRequestNotificationsPermission } from './androidPermission'; import * as logging from '../utils/logging'; /** * Get the FCM token. * * Returns null (and logs a warning or error) if getting the token failed. */ export const androidGetToken = (): GlobalThunkAction<Promise<mixed>> => async (dispatch, getState) => { try { return await NativeModules.Notifications.getToken(); } catch (e) { // `getToken` failed. That happens sometimes, apparently including // due to network errors: see #5061. In that case all will be well // if the user later launches the app while on a working network. // // But maybe this can happen in other, non-transient situations too. // Log it so we can hope to find out if that's happening. const ackedPushTokens = getAccounts(getState()).map(a => a.ackedPushToken); if (ackedPushTokens.some(t => t !== null) || ackedPushTokens.length === 0) { // It's probably a transient issue: we've previously gotten a // token (that we've even successfully sent to a server), or else // we have no accounts at all so we haven't had a chance to do so. logging.warn(`notif: getToken failed, but looks transient: ${e.message}`); } else { // Might not be transient! The user might be persistently unable // to get push notifications. logging.error(`notif: getToken failed, seems persistent: ${e.message}`); } return null; } }; /** * Try to cause a `remoteNotificationsRegistered` event. * * Our 'register' listener will fire on that event. */ export const getNotificationToken = () => { if (Platform.OS === 'ios') { // This leads to a call in RNCPushNotificationIOS to this, to // maybe prompt the user to grant authorization, with options for // what things to authorize (badge, sound, alert, etc.): // path_to_url // // If authorization is granted, the library calls this, to have the // application register for remote notifications: // path_to_url // // (Then, in case we're interested, the library calls // path_to_url // and sets the eventual result to be the resolution of the // Promise we get, so we can know if the user has enabled // alerts, the badge count, and sound.) // // The above-mentioned `registerForRemoteNotifications` function // ends up sending the app a device token; the app receives it in // our own code: `AppDelegate`'s // `didRegisterForRemoteNotificationsWithDeviceToken` method: // path_to_url // Following the library's setup instructions, we've asked that // method to hand control back to the library. // // It looks like the library then creates a notification, with the // magic-string name "RemoteNotificationsRegistered", using // path_to_url // It listens for this notification with // path_to_url // and, upon receipt, sends a React Native event to the JavaScript // part of the library. We can listen to this event, with // `PushNotificationIOS.addEventListener`, under the alias // 'register'. (We can also listen for registration failure under // the alias 'registrationError'.) // // In short, this kicks off a sequence: // authorization, with options -> // register for remote notifications -> // send event we already have a global listener for // // This satisfies the stern warnings in Apple's docs (at the above // links) to request authorization before registering with the push // notification service. PushNotificationIOS.requestPermissions(); } else { // On Android, we do this at application startup. } }; const gotPushToken = (pushToken: string | null): AccountIndependentAction => ({ type: GOT_PUSH_TOKEN, pushToken, }); const unackPushToken = (identity: Identity): AllAccountsAction => ({ type: UNACK_PUSH_TOKEN, identity, }); const registerPushTokenStart = (identity: Identity): AllAccountsAction => ({ type: REGISTER_PUSH_TOKEN_START, identity, }); const registerPushTokenEnd = (identity: Identity): AllAccountsAction => ({ type: REGISTER_PUSH_TOKEN_END, identity, }); const ackPushToken = (pushToken: string, identity: Identity): AllAccountsAction => ({ type: ACK_PUSH_TOKEN, identity, pushToken, }); /** Tell the given server about this device token, if it doesn't already know. */ const sendPushToken = ( account: Account | void, pushToken: string, ): GlobalThunkAction<Promise<void>> & ThunkAction<Promise<void>> => // Why both GlobalThunkAction and ThunkAction? Well, this function is // per-account... but whereas virtually all our other per-account code is // implicitly about the active account, this is about a specific account // it's explicitly passed. That makes it equally legitimate to call from // per-account or global code, and we do both. // TODO(#5006): Once we have per-account states for all accounts, make // this an ordinary per-account action. async dispatch => { if (!account || account.apiKey === '') { // We've logged out of the account and/or forgotten it. Shrug. return; } if (account.ackedPushToken === pushToken) { // The server already knows this device token. return; } const auth = authOfAccount(account); const identity = identityOfAccount(account); dispatch(registerPushTokenStart(identity)); try { await api.savePushToken(auth, Platform.OS, pushToken); dispatch(ackPushToken(pushToken, identity)); } finally { dispatch(registerPushTokenEnd(identity)); } }; /** * Tell this account's server about our device token, if needed. * * Also request permission to show notifications, if needed, and subject to * platform constraints on how often we can do that. */ export const initNotifications = (): ThunkAction<Promise<void>> => async ( dispatch, getState, { getGlobalSession }, // eslint-disable-line no-shadow ) => { if (Platform.OS === 'android') { // If this is denied, no need to skip the token-registration process. // The permission is all about putting up notifications in the UI: // banners, vibrations, and so on. If the user doesn't want us doing // that, Android will take care of it. Meanwhile, we can continue to // use FCM as a communications channel and have it already set up in // case the UI permission is granted later. androidRequestNotificationsPermission(); } const { pushToken } = getGlobalSession(); if (pushToken === null) { // Probably, we just don't have the token yet. When we learn it, // the listener will update this and all other logged-in servers. // Try to learn it. // // Or, if we *have* gotten something for the token and it was // `null`, we're probably on Android; see note on // `SessionState.pushToken`. It's harmless to call // `getNotificationToken` in that case; it does nothing on // Android. // // On iOS this is normal because getting the token may involve // showing the user a permissions modal, so we defer that until // this point. getNotificationToken(); return; } const account = getAccount(getState()); await dispatch(sendPushToken(account, pushToken)); }; /** Tell all logged-in accounts' servers about our device token, as needed. */ const sendAllPushToken = (): GlobalThunkAction<Promise<void>> => async (dispatch, getState) => { const { pushToken } = getGlobalSession(getState()); if (pushToken === null) { return; } const accounts = getAccounts(getState()); await Promise.all(accounts.map(account => dispatch(sendPushToken(account, pushToken)))); }; /** * Act on having learned a new device token. * * @param deviceToken This should be a `?string`, but there's no typechecking * at the registration site to allow us to ensure it. As we've been burned * by unexpected types here before, we do the validation explicitly. */ export const handleDeviceToken = (deviceToken: mixed): GlobalThunkAction<Promise<void>> => async dispatch => { // Null device tokens are known to occur (at least) on Android emulators // without Google Play services, and have been reported in other scenarios. // See path_to_url for relevant discussion. // // Otherwise, a device token should be some (platform-dependent and largely // unspecified) flavor of string. if (deviceToken !== null && typeof deviceToken !== 'string') { /* $FlowFixMe[incompatible-type]: `deviceToken` probably _is_ JSONable, but we can only hope. */ const token: JSONable = deviceToken; logging.error('Received invalid device token', { token }); // Take no further action. return; } dispatch(gotPushToken(deviceToken)); await dispatch(sendAllPushToken()); }; /** Ask this account's server to stop sending notifications to this device. */ // Doing this exclusively from the device is inherently unreliable; you // should be able to log in from elsewhere and cut the device off from your // account, including notifications, even when you don't have the device in // your possession. That's zulip/zulip#17939. export const tryStopNotifications = (account: Account): GlobalThunkAction<Promise<void>> & ThunkAction<Promise<void>> => // Why both GlobalThunkAction and ThunkAction? Well, this function is // per-account... but whereas virtually all our other per-account code is // implicitly about the active account, this is about a specific account // it's explicitly passed. That makes it equally legitimate to call from // per-account or global code, and we do both. // TODO(#5006): Once we have per-account states for all accounts, make // this an ordinary per-account action. async dispatch => { const auth = authOfAccount(account); const { ackedPushToken } = account; if (ackedPushToken !== null) { dispatch(unackPushToken(identityOfAuth(auth))); try { await api.forgetPushToken(auth, Platform.OS, ackedPushToken); } catch (e) { logging.warn(e); } } }; ```
/content/code_sandbox/src/notification/notifTokens.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,539
```javascript /* @flow strict-local */ import { DeviceEventEmitter, Platform, NativeModules, NativeEventEmitter } from 'react-native'; import type { PushNotificationEventName } from '@react-native-community/push-notification-ios'; import PushNotificationIOS from '@react-native-community/push-notification-ios'; import invariant from 'invariant'; import type { JSONableDict } from '../utils/jsonable'; import type { GlobalDispatch } from '../types'; import { androidGetToken, handleDeviceToken } from './notifTokens'; import type { Notification } from './types'; import * as logging from '../utils/logging'; import { fromAPNs } from './extract'; import { narrowToNotification } from './notifOpen'; // TODO: Could go in a separate file, with some thin wrapper perhaps. const iosNativeEventEmitter = Platform.OS === 'ios' ? new NativeEventEmitter<{| +response: [JSONableDict] |}>(NativeModules.ZLPNotificationsEvents) : null; /** * From ios/RNCPushNotificationIOS.m in @rnc/push-notification-ios at 1.2.2. */ type NotificationRegistrationFailedEvent = {| // NSError.localizedDescription, see // path_to_url message: string, // NSError.code, see // path_to_url code: number, // NSError.userInfo, see // path_to_url details: JSONableDict, |}; /** * Listens for notification-related events. * * An instance of this doesn't affect the subscriptions of any other * instance, or anything else. */ export default class NotificationListener { dispatch: GlobalDispatch; unsubs: Array<() => void> = []; constructor(dispatch: GlobalDispatch) { this.dispatch = dispatch; } /** Private. */ listenIOS( args: | {| +name: PushNotificationEventName, +handler: (...empty) => void | Promise<void> |} | {| +name: 'response', +handler: JSONableDict => void |}, ) { invariant( iosNativeEventEmitter != null, 'NotificationListener: expected `iosNativeEventEmitter` in listenIOS', ); if (args.name === 'response') { const { name, handler } = args; const sub = iosNativeEventEmitter.addListener(name, handler); this.unsubs.push(() => sub.remove()); return; } // TODO: Use iosNativeEventEmitter (as above) instead of // PushNotificationIOS (as below) for all iOS events // In the native code, the PushNotificationEventName we pass here // is mapped to something else (see implementation): // // 'notification' -> 'remoteNotificationReceived' // 'localNotification' -> 'localNotificationReceived' // 'register' -> 'remoteNotificationsRegistered' // 'registrationError' -> 'remoteNotificationRegistrationError' const { name, handler } = args; PushNotificationIOS.addEventListener(name, handler); this.unsubs.push(() => PushNotificationIOS.removeEventListener(name)); } /** Private. */ listenAndroid(name: string, handler: (...empty) => void | Promise<void>) { const subscription = DeviceEventEmitter.addListener(name, handler); this.unsubs.push(() => subscription.remove()); } /** Private. */ unlistenAll() { while (this.unsubs.length > 0) { this.unsubs.pop()(); } } /** Private. */ handleNotificationOpen: Notification => void = notification => { this.dispatch(narrowToNotification(notification)); }; /** Private. */ handleDeviceToken: mixed => Promise<void> = deviceToken => this.dispatch(handleDeviceToken(deviceToken)); /** Private. */ handleIOSRegistrationFailure: NotificationRegistrationFailedEvent => void = err => { logging.warn(`Failed to register iOS push token: ${err.code}`, { raw_error: err, }); }; /** Start listening. Don't call twice without intervening `stop`. */ async start() { if (Platform.OS === 'android') { // On Android, the object passed to the handler is constructed in // FcmMessage.kt, and will always be a Notification. this.listenAndroid('notificationOpened', this.handleNotificationOpen); this.listenAndroid('remoteNotificationsRegistered', this.handleDeviceToken); } else { this.listenIOS({ name: 'response', handler: payload => { const dataFromAPNs = fromAPNs(payload); if (!dataFromAPNs) { return; } this.handleNotificationOpen(dataFromAPNs); }, }); this.listenIOS({ name: 'register', handler: this.handleDeviceToken }); this.listenIOS({ name: 'registrationError', handler: this.handleIOSRegistrationFailure }); } if (Platform.OS === 'android') { // A bug was introduced in 3730be4c8 that delayed the setup of // our listener for 'remoteNotificationsRegistered' until a time // after the event was emitted from the native code. Until we // settle on a better, more consistent architecture, just grab // the token here and do the same thing our handler does (by // just calling the handler). const token = await this.dispatch(androidGetToken()); if (token !== null) { this.handleDeviceToken(token); } } else { // On iOS, we come back to this later: after the initial fetch, we // end up calling `getNotificationToken`, and that will cause us // to get the token if the user gives us notification permission. } } /** Stop listening. */ stop() { this.unlistenAll(); } } ```
/content/code_sandbox/src/notification/NotificationListener.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,219
```javascript /* @flow strict-local */ import * as typing_status from '@zulip/shared/lib/typing_status'; import type { Auth, PerAccountState, Narrow, UserId, ThunkAction } from '../types'; import * as api from '../api'; import { PRESENCE_RESPONSE } from '../actionConstants'; import { getAuth, getServerVersion } from '../selectors'; import { isPmNarrow, userIdsOfPmNarrow } from '../utils/narrow'; import { getUserForId } from './userSelectors'; export const reportPresence = (isActive: boolean): ThunkAction<Promise<void>> => async (dispatch, getState) => { const newUserInput = false; // TODO Why this value? Maybe it's the right one... but why? const auth = getAuth(getState()); const response = await api.reportPresence(auth, isActive, newUserInput); dispatch({ type: PRESENCE_RESPONSE, presence: response.presences, serverTimestamp: response.server_timestamp, }); }; // Callbacks for the typing_status module, all bound to this account. // NB the callbacks may be invoked later, on timers. They should continue // to refer to this account regardless of what the then-active account might be. const typingWorker = (state: PerAccountState) => { const auth: Auth = getAuth(state); // User ID arrays are only supported in server versions >= 2.0.0-rc1 // (zulip/zulip@2f634f8c0). For versions before this, email arrays // are used. // TODO(server-2.0): Simplify this away. const useEmailArrays = !getServerVersion(state).isAtLeast('2.0.0-rc1'); const getRecipients = user_ids_array => { if (useEmailArrays) { return JSON.stringify(user_ids_array.map(userId => getUserForId(state, userId).email)); } return JSON.stringify(user_ids_array); }; return { get_current_time: () => new Date().getTime(), notify_server_start: (user_ids_array: $ReadOnlyArray<UserId>) => { api.typing(auth, getRecipients(user_ids_array), 'start'); }, notify_server_stop: (user_ids_array: $ReadOnlyArray<UserId>) => { api.typing(auth, getRecipients(user_ids_array), 'stop'); }, }; }; export const sendTypingStart = (narrow: Narrow): ThunkAction<Promise<void>> => async (dispatch, getState) => { if (!isPmNarrow(narrow)) { return; } const recipientIds = userIdsOfPmNarrow(narrow); // TODO(#5005): The shared typing_status doesn't behave right on switching // accounts; it mingles state from the last call with data from this one. // E.g., `update` calls stop_last_notification with this worker, so the // new notify_server_stop, not with the old. Also if user IDs happen to // match when server changed, it won't notice change. // // To fix, state should live in an object we can keep around per-account, // instead of as module global. // // (This is pretty low-impact, because these are inherently ephemeral.) typing_status.update(typingWorker(getState()), recipientIds); }; // TODO call this on more than send: blur, navigate away, // delete all contents, etc. export const sendTypingStop = (narrow: Narrow): ThunkAction<Promise<void>> => async (dispatch, getState) => { if (!isPmNarrow(narrow)) { return; } // TODO(#5005): Same as in sendTypingStart, above. typing_status.update(typingWorker(getState()), null); }; ```
/content/code_sandbox/src/users/usersActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
840
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { SectionList } from 'react-native'; import { useSelector } from '../react-redux'; import type { UserOrBot } from '../types'; import { createStyleSheet } from '../styles'; import SectionHeader from '../common/SectionHeader'; import SearchEmptyState from '../common/SearchEmptyState'; import UserItem from './UserItem'; import { sortUserList, filterUserList, groupUsersByStatus } from './userHelpers'; import { getMutedUsers } from '../selectors'; import { getPresence } from '../presence/presenceModel'; import { ensureUnreachable } from '../generics'; const styles = createStyleSheet({ list: { flex: 1, }, }); type Props = $ReadOnly<{| filter: string, users: $ReadOnlyArray<UserOrBot>, selected?: $ReadOnlyArray<UserOrBot>, onPress: (user: UserOrBot) => void, |}>; export default function UserList(props: Props): Node { const { filter, users, onPress, selected = [] } = props; const mutedUsers = useSelector(getMutedUsers); const presences = useSelector(getPresence); const filteredUsers = filterUserList(users, filter).filter(user => !mutedUsers.has(user.user_id)); if (filteredUsers.length === 0) { return <SearchEmptyState text="No users found" />; } const sortedUsers = sortUserList(filteredUsers, presences); const groupedUsers = groupUsersByStatus(sortedUsers, presences); const sections = Object.keys(groupedUsers).map(key => ({ key, data: groupedUsers[key].map(u => u.user_id), })); return ( <SectionList style={styles.list} stickySectionHeadersEnabled keyboardShouldPersistTaps="always" initialNumToRender={20} sections={sections} keyExtractor={item => item} renderItem={({ item }) => ( <UserItem key={item} userId={item} onPress={onPress} isSelected={!!selected.find(user => user.user_id === item)} /> )} renderSectionHeader={({ section }) => section.data.length === 0 ? null : ( <SectionHeader text={(() => { // $FlowIgnore[incompatible-cast] something wrong with SectionList const key = (section.key: (typeof sections)[number]['key']); switch (key) { case 'active': return 'Active'; case 'idle': return 'Idle'; case 'offline': return 'Offline'; case 'unavailable': return 'Unavailable'; default: { ensureUnreachable(key); return key; } } })()} /> ) } /> ); } ```
/content/code_sandbox/src/users/UserList.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
608
```javascript /* @flow strict-local */ import type { User, UsersState, PerAccountApplicableAction } from '../types'; import { REGISTER_COMPLETE, EVENT_USER_ADD, EVENT_USER_REMOVE, EVENT, RESET_ACCOUNT_DATA, } from '../actionConstants'; import { EventTypes } from '../api/eventTypes'; import { NULL_ARRAY } from '../nullObjects'; const initialState: UsersState = NULL_ARRAY; export default ( state: UsersState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): UsersState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: return action.data.realm_users; case EVENT_USER_ADD: return [...state, action.person]; case EVENT_USER_REMOVE: return state; // TODO case EVENT: { const { event } = action; switch (event.type) { case EventTypes.realm_user: { switch (event.op) { case 'update': { return state.map(user => { const { person } = event; if (user.user_id !== person.user_id) { return user; } if (person.custom_profile_field) { return { ...user, profile_data: (() => { if (person.custom_profile_field.value !== null) { return { ...(user.profile_data: User['profile_data']), [person.custom_profile_field.id]: ({ value: person.custom_profile_field.value, rendered_value: person.custom_profile_field.rendered_value, // FlowIssue: This assertion is cumbersome. But // it fills a gap in Flow's coveragethat // apparently Flow doesn't announce by marking // anything with `any`. Remove when doing so // doesn't stop Flow from catching something // wrong on `value` or `rendered_value`. }: $Values<$NonMaybeType<User['profile_data']>>), }; } else { // eslint-disable-next-line no-unused-vars const { [person.custom_profile_field.id.toString()]: _, ...rest } = user.profile_data ?? {}; return rest; } })(), }; } else if (person.new_email !== undefined) { return { ...user, email: person.new_email }; } else { return { ...user, ...person }; } }); } default: return state; } } default: return state; } } default: return state; } }; ```
/content/code_sandbox/src/users/usersReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
538
```javascript // @flow strict-local import deepFreeze from 'deep-freeze'; import type { Notification } from '../types'; import type { UserOrBot } from '../../api/modelTypes'; import type { JSONableDict } from '../../utils/jsonable'; import { getNarrowFromNotificationData } from '../notifOpen'; import { topicNarrow, pm1to1NarrowFromUser, pmNarrowFromUsersUnsafe } from '../../utils/narrow'; import * as eg from '../../__tests__/lib/exampleData'; import { fromAPNsImpl as extractIosNotificationData } from '../extract'; import { objectEntries } from '../../flowPonyfill'; const realm_uri = eg.realm.toString(); const user_id = eg.selfUser.user_id; describe('getNarrowFromNotificationData', () => { const ownUserId = eg.selfUser.user_id; test('unknown notification data returns null', () => { // $FlowFixMe[incompatible-type]: actually validate APNs messages const notification: Notification = {}; const narrow = getNarrowFromNotificationData(notification, new Map(), new Map(), ownUserId); expect(narrow).toBe(null); }); test('recognizes stream notifications and returns topic narrow', () => { const stream = eg.makeStream({ name: 'some stream' }); const streamsByName = new Map([[stream.name, stream]]); const notification = { realm_uri, recipient_type: 'stream', stream_id: eg.stream.stream_id, // Name points to some other stream, but the ID prevails. stream_name: 'some stream', topic: 'some topic', }; const narrow = getNarrowFromNotificationData(notification, new Map(), streamsByName, ownUserId); expect(narrow).toEqual(topicNarrow(eg.stream.stream_id, 'some topic')); }); test('recognizes stream notification missing stream_id', () => { // TODO(server-5.0): this test's data will become ill-typed; delete it const stream = eg.makeStream({ name: 'some stream' }); const streamsByName = new Map([[stream.name, stream]]); const notification = { realm_uri, recipient_type: 'stream', stream_name: 'some stream', topic: 'some topic', }; const narrow = getNarrowFromNotificationData(notification, new Map(), streamsByName, ownUserId); expect(narrow).toEqual(topicNarrow(stream.stream_id, 'some topic')); }); test('on notification for a private message returns a PM narrow', () => { const users = [eg.selfUser, eg.otherUser]; const allUsersByEmail: Map<string, UserOrBot> = new Map(users.map(u => [u.email, u])); const notification = { realm_uri, recipient_type: 'private', sender_email: eg.otherUser.email, }; const narrow = getNarrowFromNotificationData( notification, allUsersByEmail, new Map(), ownUserId, ); expect(narrow).toEqual(pm1to1NarrowFromUser(eg.otherUser)); }); test('on notification for a group message returns a group narrow', () => { const users = [eg.selfUser, eg.makeUser(), eg.makeUser(), eg.makeUser()]; const allUsersByEmail: Map<string, UserOrBot> = new Map(users.map(u => [u.email, u])); const notification = { realm_uri, recipient_type: 'private', pm_users: users.map(u => u.user_id).join(','), }; const expectedNarrow = pmNarrowFromUsersUnsafe(users.slice(1)); const narrow = getNarrowFromNotificationData( notification, allUsersByEmail, new Map(), ownUserId, ); expect(narrow).toEqual(expectedNarrow); }); }); describe('extract iOS notification data', () => { const barebones = deepFreeze({ // TODO(server-5.0): this will become an error case 'stream, no ID': { recipient_type: 'stream', stream: 'announce', topic: 'New channel', realm_uri, }, stream: { recipient_type: 'stream', stream_id: 234, stream: 'announce', topic: 'New channel', realm_uri, }, '1:1 PM': { recipient_type: 'private', sender_email: 'nobody@example.com', realm_uri }, 'group PM': { recipient_type: 'private', pm_users: '54,321', realm_uri }, }); describe('success', () => { /** Helper function: test data immediately. */ const verify = (data: JSONableDict) => extractIosNotificationData({ zulip: data }); for (const [type, data] of objectEntries(barebones)) { test(`${type} notification`, () => { const expected = (() => { const { stream: stream_name = undefined, ...rest } = data; return stream_name !== undefined ? { ...rest, stream_name } : data; })(); // barebones 1.9.0-style message is accepted const msg = data; expect(verify(msg)).toEqual(expected); // new(-ish) optional user_id is accepted and copied // TODO: Rewrite so modern-style payloads are the baseline, e.g., // with a `modern` variable instead of `barebones`. Write // individual tests for supporting older-style payloads, and mark // those for future deletion, like with `TODO(1.9.0)`. const msg1 = { ...msg, user_id }; expect(verify(msg1)).toEqual({ ...expected, user_id }); // unused fields are not copied const msg2 = { ...msg, realm_id: 8675309 }; expect(verify(msg2)).toEqual(expected); // unknown fields are ignored and not copied const msg2a = { ...msg, unknown_data: ['unknown_data'] }; expect(verify(msg2a)).toEqual(expected); }); } }); /** Helper function: test raw data after another call. */ const makeRaw = (data: JSONableDict) => () => extractIosNotificationData(data); /** Helper function: test wrapped data after another call. */ const make = (data: JSONableDict) => () => extractIosNotificationData({ zulip: data }); describe('failure', () => { test('completely malformed or inappropriate messages', () => { expect(makeRaw({})).toThrow(); expect(makeRaw({ message_ids: [1] })).toThrow(); expect(makeRaw({ initechData: 'everything' })).toThrow(/alien/); }); test('very-old-style messages', () => { const sender_email = 'nobody@example.com'; // baseline expect(make({ realm_uri, recipient_type: 'private', sender_email })()).toBeTruthy(); // missing recipient_type expect(make({ realm_uri, sender_email })).toThrow(/archaic/); // missing realm_uri expect(make({ recipient_type: 'private', sender_email })).toThrow(/archaic/); }); test('broken or partial messages', () => { expect(make({ realm_uri, recipient_type: 'huddle' })).toThrow(/invalid/); expect(make({ realm_uri, recipient_type: 'stream' })).toThrow(/invalid/); expect(make({ realm_uri, recipient_type: 'stream', stream: 'stream name' })).toThrow( /invalid/, ); expect(make({ realm_uri, recipient_type: 'stream', subject: 'topic' })).toThrow(/invalid/); expect(make({ realm_uri, recipient_type: 'private', subject: 'topic' })).toThrow(/invalid/); }); test('values of incorrect type', () => { expect(make({ realm_uri, recipient_type: 'private', pm_users: [1, 2, 3] })).toThrow( /invalid/, ); expect(make({ realm_uri, recipient_type: 'stream', stream: [], topic: 'yes' })).toThrow( /invalid/, ); expect( make({ realm_uri, recipient_type: 'stream', stream: { name: 'somewhere' }, topic: 'no', }), ).toThrow(/invalid/); }); test('optional data is typechecked', () => { expect(make({ ...barebones.stream, realm_uri: null })).toThrow(/invalid/); expect(make({ ...barebones.stream, stream_id: '234' })).toThrow(/invalid/); expect(make({ ...barebones['group PM'], realm_uri: ['array', 'of', 'string'] })).toThrow( /invalid/, ); expect(make({ ...barebones.stream, user_id: 'abc' })).toThrow(/invalid/); }); test('hypothetical future: different event types', () => { expect(make({ event: 'remove' })()).toBeUndefined(); expect(make({ event: 'unknown type' })()).toBeUndefined(); }); }); }); ```
/content/code_sandbox/src/notification/__tests__/notification-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,934
```javascript /* @flow strict-local */ import invariant from 'invariant'; import React, { useCallback } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { UserId, UserOrBot } from '../types'; import ZulipText from '../common/ZulipText'; import Touchable from '../common/Touchable'; import UnreadCount from '../common/UnreadCount'; import UserAvatarWithPresence from '../common/UserAvatarWithPresence'; import { createStyleSheet, BRAND_COLOR } from '../styles'; import { useSelector } from '../react-redux'; import { getFullNameOrMutedUserReactText, tryGetUserForId } from './userSelectors'; import { getMutedUsers } from '../selectors'; import { getUserStatus } from '../user-statuses/userStatusesModel'; import { emojiTypeFromReactionType } from '../emoji/data'; import Emoji from '../emoji/Emoji'; import ZulipTextIntl from '../common/ZulipTextIntl'; import { getRealm } from '../directSelectors'; type Props = $ReadOnly<{| userId: UserId, isSelected?: boolean, showEmail?: boolean, unreadCount?: number, onPress?: UserOrBot => void, size?: 'large' | 'medium', |}>; /** * A user represented with avatar and name, for use in a list. */ export default function UserItem(props: Props): Node { const { userId, isSelected = false, onPress, unreadCount, showEmail = false, size = 'large', } = props; const enableGuestUserIndicator = useSelector(state => getRealm(state).enableGuestUserIndicator); const user = useSelector(state => tryGetUserForId(state, userId)); const mutedUsers = useSelector(getMutedUsers); const isMuted = mutedUsers.has(userId); const userStatusEmoji = useSelector( state => user && getUserStatus(state, user.user_id), )?.status_emoji; // eslint-disable-next-line no-underscore-dangle const _handlePress = useCallback(() => { invariant(user, 'Callback is used only if user is known'); invariant(onPress, 'Callback is used only if onPress provided'); onPress(user); }, [onPress, user]); const handlePress = onPress && user ? _handlePress : undefined; const displayName = getFullNameOrMutedUserReactText({ user, mutedUsers, enableGuestUserIndicator, }); let displayEmail = null; if (user != null && !isMuted && showEmail) { displayEmail = user.email; } const styles = React.useMemo( () => createStyleSheet({ wrapper: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8, paddingHorizontal: size === 'large' ? 16 : 8, // Minimum touch target height: // path_to_url#layout-and-typography minHeight: 48, }, selectedRow: { backgroundColor: BRAND_COLOR, }, text: { marginLeft: size === 'large' ? 16 : 8, }, textWrapper: { flexShrink: 1, }, selectedText: { color: 'white', }, textEmail: { fontSize: 10, color: 'hsl(0, 0%, 60%)', }, spacer: { flex: 1, minWidth: 4, }, }), [size], ); return ( <Touchable onPress={onPress && handlePress}> <View style={[styles.wrapper, isSelected && styles.selectedRow]}> <UserAvatarWithPresence // At size medium, keep just big enough for a 48px touch target. size={size === 'large' ? 48 : 32} userId={userId} onPress={handlePress} /> <View style={styles.textWrapper}> <ZulipTextIntl style={[styles.text, isSelected && styles.selectedText]} text={displayName} numberOfLines={1} ellipsizeMode="tail" /> {displayEmail != null && ( <ZulipText style={[styles.text, styles.textEmail, isSelected && styles.selectedText]} text={displayEmail} numberOfLines={1} ellipsizeMode="tail" /> )} </View> {userStatusEmoji && ( <View style={{ marginLeft: 4 }}> <Emoji code={userStatusEmoji.emoji_code} type={emojiTypeFromReactionType(userStatusEmoji.reaction_type)} // 15 is the fontSize in the user's name. size={size === 'large' ? 24 : 15} /> </View> )} <View style={styles.spacer} /> <UnreadCount count={unreadCount} inverse={isSelected} /> </View> </Touchable> ); } ```
/content/code_sandbox/src/users/UserItem.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,059
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import uniq from 'lodash.uniq'; import * as typeahead from '@zulip/shared/lib/typeahead'; import type { MutedUsersState, UserId, UserGroup, PresenceState, PresenceStatus, UserOrBot, } from '../types'; import { ensureUnreachable } from '../types'; import { getPresenceOnlyStatusForUser } from '../presence/presenceModel'; type UsersByStatus = {| active: UserOrBot[], idle: UserOrBot[], offline: UserOrBot[], unavailable: UserOrBot[], |}; export const groupUsersByStatus = ( users: $ReadOnlyArray<UserOrBot>, presences: PresenceState, ): UsersByStatus => { const groupedUsers = { active: [], idle: [], offline: [], unavailable: [] }; users.forEach(user => { const status = getPresenceOnlyStatusForUser(presences, user) ?? 'offline'; groupedUsers[status].push(user); }); return groupedUsers; }; const statusOrder = (status: PresenceStatus): number => { switch (status) { case 'active': return 1; case 'idle': return 2; case 'offline': return 3; default: ensureUnreachable(status); return 4; } }; export const sortUserList = ( users: $ReadOnlyArray<UserOrBot>, presences: PresenceState, ): $ReadOnlyArray<UserOrBot> => [...users].sort( (x1, x2) => statusOrder(getPresenceOnlyStatusForUser(presences, x1) ?? 'offline') - statusOrder(getPresenceOnlyStatusForUser(presences, x2) ?? 'offline') || x1.full_name.toLowerCase().localeCompare(x2.full_name.toLowerCase()), ); export const filterUserList = ( users: $ReadOnlyArray<UserOrBot>, filter: string, ): $ReadOnlyArray<UserOrBot> => users.filter( user => filter === '' || user.full_name.toLowerCase().includes(filter.toLowerCase()) || user.email.toLowerCase().includes(filter.toLowerCase()), ); export const filterUserStartWith = ( users: $ReadOnlyArray<UserOrBot>, filter: string, ownUserId: UserId, ): $ReadOnlyArray<UserOrBot> => { const loweredFilter = filter.toLowerCase(); const isAscii = /^[a-z]+$/.test(loweredFilter); return users.filter(user => { const full_name = isAscii ? typeahead.remove_diacritics(user.full_name) : user.full_name; return user.user_id !== ownUserId && full_name.toLowerCase().startsWith(loweredFilter); }); }; export const filterUserThatContains = ( users: $ReadOnlyArray<UserOrBot>, filter: string, ownUserId: UserId, ): $ReadOnlyArray<UserOrBot> => { const loweredFilter = filter.toLowerCase(); const isAscii = /^[a-z]+$/.test(loweredFilter); return users.filter(user => { const full_name = isAscii ? typeahead.remove_diacritics(user.full_name) : user.full_name; return user.user_id !== ownUserId && full_name.toLowerCase().includes(filter.toLowerCase()); }); }; export const filterUserMatchesEmail = ( users: $ReadOnlyArray<UserOrBot>, filter: string, ownUserId: UserId, ): $ReadOnlyArray<UserOrBot> => users.filter( user => user.user_id !== ownUserId && user.email.toLowerCase().includes(filter.toLowerCase()), ); /** * Get the list of users for a user-autocomplete query. * * Callers must ensure that `users` has just one unique object per user ID. */ export const getAutocompleteSuggestion = ( users: $ReadOnlyArray<UserOrBot>, filter: string, ownUserId: UserId, mutedUsers: MutedUsersState, ): $ReadOnlyArray<UserOrBot> => { if (users.length === 0) { return users; } const startWith = filterUserStartWith(users, filter, ownUserId); const contains = filterUserThatContains(users, filter, ownUserId); const matchesEmail = filterUserMatchesEmail(users, filter, ownUserId); // Dedupe users that match in multiple ways. const candidates: $ReadOnlyArray<UserOrBot> = // Lodash's "unique" is just as good as "unique by user ID" as long as // there aren't multiple unique objects per user ID. See doc: // path_to_url#uniq // So we ask the caller to satisfy that for `users`; then when we // deduplicate, here, we only pass objects that appear in `users`. uniq([...startWith, ...contains, ...matchesEmail]); return candidates.filter(user => !mutedUsers.has(user.user_id)); }; export const getAutocompleteUserGroupSuggestions = ( userGroups: $ReadOnlyArray<UserGroup>, filter: string = '', ): $ReadOnlyArray<UserGroup> => userGroups.filter( userGroup => userGroup.name.toLowerCase().includes(filter.toLowerCase()) || userGroup.description.toLowerCase().includes(filter.toLowerCase()), ); ```
/content/code_sandbox/src/users/userHelpers.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,104
```javascript /* @flow strict-local */ import { createSelector } from 'reselect'; import React from 'react'; import type { CustomProfileField, PerAccountState, UserOrBot, Selector, User, UserId, LocalizableText, LocalizableReactText, } from '../types'; import type { MutedUsersState, RealmState } from '../reduxTypes'; import { getUsers, getCrossRealmBots, getNonActiveUsers } from '../directSelectors'; import * as logging from '../utils/logging'; import { ensureUnreachable } from '../generics'; import { EmailAddressVisibility, Role } from '../api/permissionsTypes'; import ZulipText from '../common/ZulipText'; import { noTranslation } from '../i18n/i18n'; /** * All users in this Zulip org (aka realm). * * In particular this includes: * * cross-realm bots * * deactivated users (`is_active` false; see `User` and the linked docs) * * This is the right list to use in any UI context that might involve things * a user did in the past: messages they sent, reactions they added, etc. * Deactivating a user means they can't log in and see or send new messages, * and doesn't erase them from history. * * In contexts that are about offering *new* interactions -- like choosing a * user to send a PM to -- deactivated users should be left out. * * See: * * `getActiveUsersById` for leaving out deactivated users * * `User` for details on properties, and links to docs. */ const getAllUsers: Selector<$ReadOnlyArray<UserOrBot>> = createSelector( getUsers, getNonActiveUsers, getCrossRealmBots, (users = [], nonActiveUsers = [], crossRealmBots = []) => [ ...users, ...nonActiveUsers, ...crossRealmBots, ], ); /** See `getAllUsers` for discussion. */ export const getAllUsersById: Selector<Map<UserId, UserOrBot>> = createSelector( getAllUsers, allUsers => new Map(allUsers.map(user => [user.user_id, user])), ); /** * See `getAllUsers` for discussion. * * Prefer `getAllUsersById`; see #3764. * */ export const getAllUsersByEmail: Selector<Map<string, UserOrBot>> = createSelector( getAllUsers, allUsers => new Map(allUsers.map(user => [user.email, user])), ); /** * PRIVATE; exported only for tests. * * WARNING: despite the name, only (a) `is_active` users (b) excluding cross-realm bots. * * See `getAllUsersById`, and `getAllUsers` for discussion. */ export const getUsersById: Selector<Map<UserId, User>> = createSelector( getUsers, (users = []) => new Map(users.map(user => [user.user_id, user])), ); /** * WARNING: despite the name, only (a) `is_active` users (b) excluding cross-realm bots. * * See `getAllUsers`. */ export const getSortedUsers: Selector<$ReadOnlyArray<User>> = createSelector(getUsers, users => [...users].sort((x1, x2) => x1.full_name.toLowerCase().localeCompare(x2.full_name.toLowerCase())), ); /** * The user's own user ID in the active account. * * Throws if we have no data from the server. * * See also `getOwnUser`. */ export const getOwnUserId = (state: PerAccountState): UserId => { const { user_id } = state.realm; if (user_id === undefined) { throw new Error('No server data found'); } return user_id; }; /** * The person using the app, as represented by a `User` object. * * This is the server's information about the active, logged-in account, in * the same form as the information we get from the server about everyone * else in the organization. * * Throws if we have no such information. * * See also `getOwnUserId`. */ export const getOwnUser = (state: PerAccountState): User => { const ownUser = getUsersById(state).get(getOwnUserId(state)); if (ownUser === undefined) { throw new Error('Have ownUserId, but not found in user data'); } return ownUser; }; /** * The user with the given user ID, or null if no such user is known. * * This works for any user in this Zulip org/realm, including deactivated * users and cross-realm bots. See `getAllUsers` for details. * * See `getUserForId` for a version which only ever returns a real user, * throwing if none. That makes it a bit simpler to use in contexts where * we assume the relevant user must exist. */ export const tryGetUserForId = (state: PerAccountState, userId: UserId): UserOrBot | null => getAllUsersById(state).get(userId) ?? null; /** * The user with the given user ID. * * This works for any user in this Zulip org/realm, including deactivated * users and cross-realm bots. See `getAllUsers` for details. * * Throws if no such user exists in our data. This is therefore only * appropriate when we can know the given user must be one we know about, * which is uncommon. (For example, even if we're looking at a message the * user sent: we might be a guest with limited access to users, and the * other user might no longer be in the stream so not be in our data.) * * Generally use `tryGetUserForId` instead. */ export const getUserForId = (state: PerAccountState, userId: UserId): UserOrBot => { const user = tryGetUserForId(state, userId); if (!user) { throw new Error(`getUserForId: missing user: id ${userId}`); } return user; }; /** * DEPRECATED except as a cache private to this module. * * Excludes deactivated users. See `getAllUsers` for discussion. * * Instead of this selector, use: * * `getAllUsersById` for data on an arbitrary user * * `getUserIsActive` for the specific information of whether a user is * deactivated. */ const getActiveUsersById: Selector<Map<UserId, UserOrBot>> = createSelector( getUsers, getCrossRealmBots, (users = [], crossRealmBots = []) => new Map([...users, ...crossRealmBots].map(user => [user.user_id, user])), ); /** * The value of `is_active` for the given user. * * For a normal user, this is true unless the user or an admin has * deactivated their account. The name comes from Django; this property * isn't related to presence or to whether the user has recently used Zulip. * * (Conceptually this should be a property on the `User` object; the reason * it isn't is just that the Zulip API presents this information in a funny * other way.) */ // To understand this implementation, see the comment about `is_active` in // the `User` type definition. export const getUserIsActive = (state: PerAccountState, userId: UserId): boolean => !!getActiveUsersById(state).get(userId); /** A user's value for a custom profile field, put into meaningful form. */ export type CustomProfileFieldValue = | { +displayType: 'text', +text: string } | { +displayType: 'link', +text: string, +url: void | URL } | { +displayType: 'users', +userIds: $ReadOnlyArray<UserId> }; function interpretCustomProfileField( realmDefaultExternalAccounts: RealmState['defaultExternalAccounts'], realmField: CustomProfileField, profileData: UserOrBot['profile_data'], ): void | CustomProfileFieldValue { const userFieldData = profileData?.[realmField.id.toString()]; if (!userFieldData) { return undefined; } const { value } = userFieldData; const { type } = realmField; switch (type) { // In general this part of the API is not documented up to Zulip's // normal standards. Some discussion here: // path_to_url#narrow/stream/378-api-design/topic/custom.20profile.20fields/near/1387379 case 1: // CustomProfileFieldType.ShortText case 8: // CustomProfileFieldType.Pronouns case 2: // CustomProfileFieldType.LongText // The web client appears to treat LongText identically to ShortText. // Pronouns is explicitly meant to display the same as ShortText. return { displayType: 'text', text: value }; case 3: { // CustomProfileFieldType.Choice // TODO(server): This isn't really documented. But see chat thread: // path_to_url#narrow/stream/378-api-design/topic/custom.20profile.20fields/near/1383005 const choices = JSON.parse(realmField.field_data); return { displayType: 'text', text: choices[value].text }; } case 4: { // CustomProfileFieldType.Date // TODO(server): The value's format is undocumented, but empirically // it's a date in ISO format, like 2000-01-01. // That's readable as is, but: // TODO format this date using user's locale. return { displayType: 'text', text: value }; } case 5: // CustomProfileFieldType.Link // This isn't real clearly documented; but the `value` is just the URL. return { displayType: 'link', text: value, url: new URL(value) }; case 7: { // CustomProfileFieldType.ExternalAccount // TODO(server): This is undocumented. See chat thread: // path_to_url#narrow/stream/378-api-design/topic/external.20account.20custom.20profile.20fields/near/1387213 const realmData: { subtype: string, url_pattern?: string } = JSON.parse( realmField.field_data, ); const { subtype, url_pattern } = realmData; const pattern = url_pattern ?? realmDefaultExternalAccounts.get(subtype)?.url_pattern; const url = pattern == null ? undefined : new URL(pattern.replace('%(username)s', () => value)); if (!url) { logging.warn( `Missing url_pattern for custom profile field of type ExternalAccount, subtype '${subtype}'`, ); } return { displayType: 'link', text: value, url }; } case 6: { // CustomProfileFieldType.User // TODO(server): This is completely undocumented. The key to // reverse-engineering it was: // path_to_url#L247 const userIds: $ReadOnlyArray<UserId> = JSON.parse(value); return { displayType: 'users', userIds }; } default: ensureUnreachable(type); logging.warn(`Invalid custom profile field type: ${type}`); return undefined; } } /** * The given user's values for custom profile fields, interpreted to make usable. * * These are in the order a client is expected to present them in. Any * fields that are configured on the realm but that the user has no chosen * value for are omitted. * * This selector does no caching. Meant for use inside `React.useMemo`. */ export function getCustomProfileFieldsForUser( realm: RealmState, user: UserOrBot, ): Array<{| +fieldId: number, +name: string, +value: CustomProfileFieldValue |}> { const realmFields = realm.customProfileFields; const realmDefaultExternalAccounts = realm.defaultExternalAccounts; // TODO(server): The realm-wide field objects have an `order` property, // but the actual API appears to be that the fields should be shown in // the order they appear in the array (`custom_profile_fields` in the // API; our `realmFields` array here.) See chat thread: // path_to_url#narrow/stream/378-api-design/topic/custom.20profile.20fields/near/1382982 // // We go on to put at the start of the list any fields that are marked for // displaying in the "profile summary". (Possibly they should be at the // start of the list in the first place, but make sure just in case.) const sortedRealmFields = [ ...realmFields.filter(f => f.display_in_profile_summary), ...realmFields.filter(f => !f.display_in_profile_summary), ]; const fields = []; for (const realmField of sortedRealmFields) { const value = interpretCustomProfileField( realmDefaultExternalAccounts, realmField, user.profile_data, ); if (value) { fields.push({ name: realmField.name, fieldId: realmField.id, value }); } } return fields; } /** * The given user's real email address, if known, for displaying in the UI. * * Null if our user isn't able to see this user's real email address. */ export function getDisplayEmailForUser(realm: RealmState, user: UserOrBot): string | null { if (user.delivery_email !== undefined) { return user.delivery_email; } else if (realm.emailAddressVisibility === EmailAddressVisibility.Everyone) { // TODO(server-7.0): Not reached on FL 163+, where delivery_email is always present. return user.email; } else { return null; } } /** * Display text for a user's name, ignoring muting, as LocalizableText. * * Accepts `null` for the `user` argument; in that case, the name is * taken from `fallback` if present, and otherwise the text is * "(unknown user)". * * For the same text as LocalizableReactText, see getFullNameReactText. * * For a function that gives "Muted user" if the user is muted, see * getFullNameOrMutedUserText. */ export function getFullNameText(args: {| user: UserOrBot | null, enableGuestUserIndicator: boolean, fallback?: string, |}): LocalizableText { const { user, enableGuestUserIndicator, fallback } = args; if (user == null) { return fallback != null ? noTranslation(fallback) : '(unknown user)'; } if (user.role === Role.Guest && enableGuestUserIndicator) { return { text: '{userFullName} (guest)', values: { userFullName: user.full_name } }; } return noTranslation(user.full_name); } const italicTextStyle = { fontStyle: 'italic' }; /** * Display text for a user's name, ignoring muting, as LocalizableReactText. * * Just like getFullNameText, but gives LocalizableReactText. */ export function getFullNameReactText(args: {| +user: UserOrBot | null, +enableGuestUserIndicator: boolean, +fallback?: string, |}): LocalizableReactText { const { user, enableGuestUserIndicator, fallback } = args; if (user == null) { return fallback != null ? noTranslation(fallback) : '(unknown user)'; } if (user.role === Role.Guest && enableGuestUserIndicator) { return { text: '{userFullName} <i>(guest)</i>', values: { userFullName: user.full_name, i: chunks => ( <ZulipText inheritColor inheritFontSize style={italicTextStyle}> {chunks} </ZulipText> ), }, }; } return noTranslation(user.full_name); } /** * Display text for a user's name, as LocalizableText. * * Accepts `null` for the `user` argument; in that case, the name is * taken from `fallback` if present, and otherwise the text is * "(unknown user)". * * If the user is muted, gives "Muted user". * * For the same text as LocalizableReactText, see * getFullNameOrMutedUserReactText. * * For a function that ignores muting, see getFullNameOrMutedUserText. */ export function getFullNameOrMutedUserText(args: {| user: UserOrBot | null, mutedUsers: MutedUsersState, enableGuestUserIndicator: boolean, fallback?: string, |}): LocalizableText { const { user, mutedUsers, enableGuestUserIndicator, fallback } = args; if (user == null) { return fallback != null ? noTranslation(fallback) : '(unknown user)'; } if (mutedUsers.has(user.user_id)) { return 'Muted user'; } return getFullNameText({ user, enableGuestUserIndicator }); } /** * Display text for a user's name, as LocalizableReactText. * * Just like getFullNameOrMutedUserText, but gives LocalizableReactText. */ export function getFullNameOrMutedUserReactText(args: {| user: UserOrBot | null, mutedUsers: MutedUsersState, enableGuestUserIndicator: boolean, fallback?: string, |}): LocalizableReactText { const { user, mutedUsers, enableGuestUserIndicator, fallback } = args; if (user == null) { return fallback != null ? noTranslation(fallback) : '(unknown user)'; } if (mutedUsers.has(user.user_id)) { return 'Muted user'; } return getFullNameReactText({ user, enableGuestUserIndicator }); } ```
/content/code_sandbox/src/users/userSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,852
```javascript /* @flow strict-local */ import { getAllUsersByEmail, getAllUsersById, getUsersById, getUserForId, getUserIsActive, getCustomProfileFieldsForUser, getDisplayEmailForUser, } from '../userSelectors'; import * as eg from '../../__tests__/lib/exampleData'; import { CustomProfileFieldType } from '../../api/modelTypes'; import { randInt, randString } from '../../utils/misc'; import { EmailAddressVisibility } from '../../api/permissionsTypes'; describe('getAllUsersByEmail', () => { test('return users mapped by their email', () => { const users = [eg.makeUser(), eg.makeUser(), eg.makeUser()]; const state = eg.reduxState({ users }); expect(getAllUsersByEmail(state)).toEqual(new Map(users.map(u => [u.email, u]))); }); test('return users, bots, and inactive users mapped by their email', () => { const state = eg.reduxState({ users: [eg.selfUser], realm: { ...eg.baseReduxState.realm, crossRealmBots: [eg.crossRealmBot], nonActiveUsers: [eg.otherUser], }, }); expect(getAllUsersByEmail(state)).toEqual( new Map([ [eg.selfUser.email, eg.selfUser], [eg.crossRealmBot.email, eg.crossRealmBot], [eg.otherUser.email, eg.otherUser], ]), ); }); test('empty state does not cause an exception, returns an empty object', () => { expect(getAllUsersByEmail(eg.reduxState())).toEqual(new Map()); }); }); describe('getAllUsersById', () => { test('return users mapped by their id', () => { const users = [eg.makeUser(), eg.makeUser(), eg.makeUser()]; const state = eg.reduxState({ users }); expect(getAllUsersById(state)).toEqual(new Map(users.map(u => [u.user_id, u]))); }); test('return users, bots, and inactive users mapped by their id', () => { const state = eg.reduxState({ users: [eg.selfUser], realm: { ...eg.baseReduxState.realm, crossRealmBots: [eg.crossRealmBot], nonActiveUsers: [eg.otherUser], }, }); expect(getAllUsersById(state)).toEqual( new Map([ [eg.selfUser.user_id, eg.selfUser], [eg.crossRealmBot.user_id, eg.crossRealmBot], [eg.otherUser.user_id, eg.otherUser], ]), ); }); test('empty state does not cause an exception, returns an empty object', () => { expect(getAllUsersById(eg.reduxState())).toEqual(new Map()); }); }); describe('getUsersById', () => { test('return users mapped by their Id', () => { const users = [eg.makeUser(), eg.makeUser(), eg.makeUser()]; const state = eg.reduxState({ users }); expect(getUsersById(state)).toEqual(new Map(users.map(u => [u.user_id, u]))); }); }); describe('getUserForId', () => { const state = eg.reduxState({ users: [eg.selfUser], realm: { ...eg.baseReduxState.realm, crossRealmBots: [eg.crossRealmBot], nonActiveUsers: [eg.makeUser(), eg.makeUser()], }, }); test('returns the user if it has not been deactivated', () => { expect(getUserForId(state, state.users[0].user_id)).toEqual(state.users[0]); }); test('returns the user if it has been deactivated', () => { expect(getUserForId(state, state.realm.nonActiveUsers[0].user_id)).toEqual( state.realm.nonActiveUsers[0], ); }); test('returns the user if it is a cross realm bot', () => { expect(getUserForId(state, state.realm.crossRealmBots[0].user_id)).toEqual( state.realm.crossRealmBots[0], ); }); }); describe('getUserIsActive', () => { const state = eg.reduxState({ users: [eg.selfUser], realm: { ...eg.baseReduxState.realm, crossRealmBots: [eg.crossRealmBot], nonActiveUsers: [eg.makeUser(), eg.makeUser()], }, }); test('returns false for a user that has been deactivated', () => { expect(getUserIsActive(state, state.realm.nonActiveUsers[0].user_id)).toBeFalse(); }); test('returns true for a user that has not been deactivated', () => { expect(getUserIsActive(state, state.users[0].user_id)).toBeTrue(); }); test('returns true for a cross realm bot', () => { expect(getUserIsActive(state, state.realm.crossRealmBots[0].user_id)).toBeTrue(); }); }); describe('getCustomProfileFieldsForUser', () => { const mkRealm = (fields, defaultExternalAccounts) => eg.realmState({ customProfileFields: fields.map((f, i) => ({ order: i, hint: '', field_data: '', ...f })), ...(defaultExternalAccounts == null ? null : { defaultExternalAccounts }), }); const mkUser = fields => ({ ...eg.otherUser, profile_data: fields }); describe('by field type', () => { /* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "checkOne"] }] */ function checkOne(realmField, value, expectedValue, defaultExternalAccounts) { const fieldId = randInt(1000); const name = randString(); expect( getCustomProfileFieldsForUser( mkRealm([{ id: fieldId, name, ...realmField }], defaultExternalAccounts), mkUser({ [fieldId]: { value } }), ), ).toEqual([{ fieldId, name, value: expectedValue }]); } test('ShortText', () => { const text = 'hello'; checkOne({ type: CustomProfileFieldType.ShortText }, text, { displayType: 'text', text }); }); test('LongText', () => { const text = 'hello hello'; checkOne({ type: CustomProfileFieldType.LongText }, text, { displayType: 'text', text }); }); test('Choice', () => { const text = 'Foo text'; checkOne( { type: CustomProfileFieldType.Choice, field_data: JSON.stringify({ foo: { text } }) }, 'foo', { displayType: 'text', text }, ); }); test('Date', () => { const value = '2022-06-03'; checkOne({ type: CustomProfileFieldType.Date }, value, { displayType: 'text', text: value }); }); test('Link', () => { const url = 'path_to_url checkOne({ type: CustomProfileFieldType.Link }, url, { displayType: 'link', text: url, url: new URL(url), }); }); test('ExternalAccount, of a default subtype', () => { const subtype = 'github'; const username = 'exampleuser'; const url_pattern = 'path_to_url checkOne( { type: CustomProfileFieldType.ExternalAccount, field_data: JSON.stringify({ subtype }) }, username, { displayType: 'link', text: username, url: new URL(`path_to_url{username}`) }, new Map([[subtype, { url_pattern }]]), ); }); test('ExternalAccount, subtype custom', () => { const username = 'exampleuser'; const url_pattern = 'path_to_url checkOne( { type: CustomProfileFieldType.ExternalAccount, field_data: JSON.stringify({ subtype: 'custom', url_pattern }), }, username, { displayType: 'link', text: username, url: new URL(`path_to_url{username}`) }, ); }); test('User, empty list', () => { checkOne({ type: CustomProfileFieldType.User }, JSON.stringify([]), { displayType: 'users', userIds: [], }); }); test('User, single', () => { const userIds = [eg.thirdUser].map(u => u.user_id); checkOne({ type: CustomProfileFieldType.User }, JSON.stringify(userIds), { displayType: 'users', userIds, }); }); test('User, multiple', () => { const userIds = [eg.selfUser, eg.otherUser, eg.thirdUser].map(u => u.user_id); checkOne({ type: CustomProfileFieldType.User }, JSON.stringify(userIds), { displayType: 'users', userIds, }); }); }); test('use order from realm list, not IDs', () => { expect( getCustomProfileFieldsForUser( mkRealm([ { id: 2, name: 'name two', type: CustomProfileFieldType.ShortText }, { id: 1, name: 'name one', type: CustomProfileFieldType.ShortText }, ]), mkUser({ '1': { value: 'value one' }, '2': { value: 'value two' } }), ), ).toEqual([ { fieldId: 2, name: 'name two', value: { displayType: 'text', text: 'value two' } }, { fieldId: 1, name: 'name one', value: { displayType: 'text', text: 'value one' } }, ]); }); test('put highlighted fields first', () => { expect( getCustomProfileFieldsForUser( mkRealm([ { id: 1, name: 'name one', type: CustomProfileFieldType.ShortText }, { id: 2, name: 'name two', type: CustomProfileFieldType.ShortText, }, { id: 3, name: 'name three', type: CustomProfileFieldType.ShortText, display_in_profile_summary: true, }, ]), mkUser({ '1': { value: 'value one' }, '2': { value: 'value two' }, '3': { value: 'value three' }, }), ), ).toEqual([ { fieldId: 3, name: 'name three', value: { displayType: 'text', text: 'value three' } }, { fieldId: 1, name: 'name one', value: { displayType: 'text', text: 'value one' } }, { fieldId: 2, name: 'name two', value: { displayType: 'text', text: 'value two' } }, ]); }); test('omit unset fields', () => { expect( getCustomProfileFieldsForUser( mkRealm([ { id: 1, name: 'name one', type: CustomProfileFieldType.ShortText }, { id: 2, name: 'name two', type: CustomProfileFieldType.ShortText }, { id: 3, name: 'name three', type: CustomProfileFieldType.ShortText }, ]), mkUser({ '1': { value: 'value one' }, '3': { value: 'value three' } }), ), ).toMatchObject([{ fieldId: 1 }, { fieldId: 3 }]); }); }); describe('getDisplayEmailForUser', () => { const mkUser = fields => ({ ...eg.otherUser, ...fields }); test('visibility is admin, no delivery_email', () => { const realm = eg.realmState({ emailAddressVisibility: EmailAddressVisibility.Admins }); // eslint-disable-next-line no-unused-vars const { delivery_email, ...user } = eg.otherUser; expect(getDisplayEmailForUser(realm, user)).toBeNull(); }); test('email visibility is everyone, no delivery_email', () => { const realm = eg.realmState({ emailAddressVisibility: EmailAddressVisibility.Everyone }); // eslint-disable-next-line no-unused-vars const { delivery_email, ...user } = eg.otherUser; expect(getDisplayEmailForUser(realm, user)).toEqual(eg.otherUser.email); }); test('email visibility is everyone, delivery_email is null', () => { const realm = eg.realmState({ emailAddressVisibility: EmailAddressVisibility.Everyone }); const user = mkUser({ delivery_email: null }); expect(getDisplayEmailForUser(realm, user)).toBeNull(); }); test('email visibility is everyone, delivery_email is set', () => { const realm = eg.realmState({ emailAddressVisibility: EmailAddressVisibility.Everyone }); const user = mkUser({ delivery_email: 'delivery_email@example.org', email: 'other@example.org', }); expect(getDisplayEmailForUser(realm, user)).toEqual('delivery_email@example.org'); }); test('email visibility is admins, delivery_email is set', () => { const realm = eg.realmState({ emailAddressVisibility: EmailAddressVisibility.Admins }); const user = mkUser({ delivery_email: 'delivery_email@example.org', email: 'other@example.org', }); expect(getDisplayEmailForUser(realm, user)).toEqual('delivery_email@example.org'); }); }); ```
/content/code_sandbox/src/users/__tests__/userSelectors-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,871
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import * as eg from '../../__tests__/lib/exampleData'; import { UploadedAvatarURL } from '../../utils/avatar'; import { EVENT_USER_ADD, EVENT } from '../../actionConstants'; import { EventTypes, type RealmUserUpdateEvent } from '../../api/eventTypes'; import type { User } from '../../types'; import { Role } from '../../api/permissionsTypes'; import usersReducer from '../usersReducer'; import { randString } from '../../utils/misc'; describe('usersReducer', () => { describe('REGISTER_COMPLETE', () => { const user1 = eg.makeUser(); test('when `users` data is provided init state with it', () => { const prevState = deepFreeze([]); const action = eg.mkActionRegisterComplete({ realm_users: [user1], }); const actualState = usersReducer(prevState, action); expect(actualState).toEqual([user1]); }); }); describe('EVENT_USER_ADD', () => { const user1 = eg.makeUser(); test('flags from all messages are extracted and stored by id', () => { const prevState = deepFreeze([]); const action = deepFreeze({ id: 1, type: EVENT_USER_ADD, person: user1, }); const expectedState = [user1]; const actualState = usersReducer(prevState, action); expect(actualState).toEqual(expectedState); }); }); describe('EVENT > realm_user > update', () => { const theUser = eg.makeUser(); const prevState = deepFreeze([theUser]); /** * Check that an update event with supplied `person` works. * * May omit `user_id` to avoid repetition. * * Normally, the expected User value after the change is * * { ...theUser, ...person } * * But in at least one case (when updating custom profile fields), that * isn't even a valid User object because `person`'s properties aren't * a subset of User's. To handle that, callers can pass an * `expectedUser`. */ // Tell ESLint to recognize `check` as a helper function that runs // assertions. /* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "check"] }] */ const check = <P: RealmUserUpdateEvent['person']>( personMaybeWithoutId: $Rest<P, {| user_id?: mixed |}>, expectedUser?: User, ) => { const person: P = { user_id: theUser.user_id, ...personMaybeWithoutId }; const action = deepFreeze({ type: EVENT, event: { id: 1, type: EventTypes.realm_user, op: 'update', person }, }); expect(usersReducer(prevState, action)).toEqual([expectedUser ?? { ...theUser, ...person }]); }; /* * Should match REALM_USER OP: UPDATE in the doc. * * See path_to_url#realm_user-update. * * A few properties that we don't handle are commented out. */ test('When a user changes their full name.', () => { check({ full_name: randString() }); }); test('When a user changes their avatar.', () => { check({ avatar_url: UploadedAvatarURL.validateAndConstructInstance({ realm: new URL('path_to_url absoluteOrRelativeUrl: `/yo/avatar-${randString()}.png`, }), // avatar_source: user1.avatar_source === 'G' ? 'U' : 'G', // avatar_url_medium: randString(), // avatar_version: user1.avatar_version + 1, }); }); test('When a user changes their timezone setting.', () => { check({ timezone: randString() }); }); test('When the owner of a bot changes.', () => { check({ bot_owner_id: (theUser.bot_owner_id ?? 1) + 1 }); }); test('When the role of a user changes.', () => { const roleValues = Array.from(Role.members()); check({ role: roleValues[(roleValues.indexOf(theUser.role) + 1) % roleValues.length] }); }); test("When a user's billing-admin status changes", () => { check({ is_billing_admin: !theUser.is_billing_admin }); }); test('When the delivery email of a user changes.', () => { check({ delivery_email: randString() }); }); test('When the user updates one of their custom profile fields.', () => { const value = randString(); const rendered_value = randString(); check( { custom_profile_field: { id: 4, value, rendered_value } }, { ...theUser, profile_data: { '4': { value, rendered_value } } }, ); }); test('When the user clears one of their custom profile fields.', () => { check({ custom_profile_field: { id: 4, value: null } }, { ...theUser, profile_data: {} }); }); test('When the Zulip display email address of a user changes', () => { const new_email = randString(); check({ new_email }, { ...theUser, email: new_email }); }); }); describe('RESET_ACCOUNT_DATA', () => { const user1 = eg.makeUser(); test('resets state to initial state', () => { const prevState = deepFreeze([user1]); const expectedState = []; const actualState = usersReducer(prevState, eg.action.reset_account_data); expect(actualState).toEqual(expectedState); }); }); }); ```
/content/code_sandbox/src/users/__tests__/usersReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,239
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import Immutable from 'immutable'; import { sortUserList, filterUserList, getAutocompleteSuggestion, getAutocompleteUserGroupSuggestions, filterUserStartWith, filterUserThatContains, filterUserMatchesEmail, groupUsersByStatus, } from '../userHelpers'; import * as eg from '../../__tests__/lib/exampleData'; import { makePresenceState } from '../../presence/__tests__/presence-testlib'; describe('filterUserList', () => { test('empty input results in empty list', () => { const users = deepFreeze([]); const filteredUsers = filterUserList(users, 'some filter'); expect(filteredUsers).toEqual(users); }); test('searches in name, email and is case insensitive', () => { const user1 = eg.makeUser({ full_name: 'match', email: 'any@example.com' }); const user2 = eg.makeUser({ full_name: 'partial match', email: 'any@example.com' }); const user3 = eg.makeUser({ full_name: 'Case Insensitive MaTcH', email: 'any@example.com' }); const user4 = eg.makeUser({ full_name: 'Any Name', email: 'match@example.com' }); const user5 = eg.makeUser({ full_name: 'some name', email: 'another@example.com' }); const allUsers = deepFreeze([user1, user2, user3, user4, user5]); const shouldMatch = [user1, user2, user3, user4]; const filteredUsers = filterUserList(allUsers, 'match'); expect(filteredUsers).toEqual(shouldMatch); }); }); describe('getAutocompleteSuggestion', () => { test('empty input results in empty list', () => { const users = deepFreeze([]); const filteredUsers = getAutocompleteSuggestion( users, 'some filter', eg.selfUser.user_id, Immutable.Map(), ); expect(filteredUsers).toBe(users); }); test("filters out user's own entry", () => { const someGuyUser = eg.makeUser({ full_name: 'Some Guy' }); const meUser = eg.makeUser({ full_name: 'Me' }); const users = deepFreeze([someGuyUser, meUser]); const shouldMatch = [someGuyUser]; const filteredUsers = getAutocompleteSuggestion(users, '', meUser.user_id, Immutable.Map()); expect(filteredUsers).toEqual(shouldMatch); }); test('filters out muted user', () => { const mutedUser = eg.makeUser({ full_name: 'Muted User' }); const meUser = eg.makeUser({ full_name: 'Me' }); const users = deepFreeze([mutedUser, meUser]); const mutedUsers = Immutable.Map([[mutedUser.user_id, 0]]); const shouldMatch = []; const filteredUsers = getAutocompleteSuggestion(users, '', meUser.user_id, mutedUsers); expect(filteredUsers).toEqual(shouldMatch); }); test('searches in name, email and is case insensitive', () => { const user1 = eg.makeUser({ full_name: 'match', email: 'any1@example.com' }); const user2 = eg.makeUser({ full_name: 'match this', email: 'any2@example.com' }); const user3 = eg.makeUser({ full_name: 'MaTcH Case Insensitive', email: 'any3@example.com' }); const user4 = eg.makeUser({ full_name: 'some name', email: 'another@example.com' }); const user5 = eg.makeUser({ full_name: 'Example', email: 'match@example.com' }); const allUsers = deepFreeze([user1, user2, user3, user4, user5]); const shouldMatch = [user1, user2, user3, user5]; const filteredUsers = getAutocompleteSuggestion( allUsers, 'match', eg.selfUser.user_id, Immutable.Map(), ); expect(filteredUsers).toEqual(shouldMatch); }); test('result should be in priority of startsWith, contains in name, matches in email', () => { const user1 = eg.makeUser({ full_name: 'M Apple', email: 'any1@example.com' }); // does not match const user2 = eg.makeUser({ full_name: 'Normal boy', email: 'any2@example.com' }); // satisfy full_name contains condition const user3 = eg.makeUser({ full_name: 'example', email: 'example@example.com' }); // random entry const user4 = eg.makeUser({ full_name: 'Example', email: 'match@example.com' }); // satisfy email match condition const user5 = eg.makeUser({ full_name: 'match', email: 'any@example.com' }); // satisfy full_name starts with condition const user6 = eg.makeUser({ full_name: 'match', email: 'normal@example.com' }); // satisfy starts with and email condition const user7 = eg.makeUser({ full_name: 'Match App Normal', email: 'any3@example.com' }); // satisfy all conditions const user8 = user5; // duplicate const user9 = eg.makeUser({ full_name: 'Laptop', email: 'laptop@example.com' }); // random entry const user10 = eg.makeUser({ full_name: 'Mobile App', email: 'any@match.com' }); // satisfy email condition const user11 = eg.makeUser({ full_name: 'Normal', email: 'match2@example.com' }); // satisfy contains in name and matches in email condition const allUsers = deepFreeze([ user1, user2, user3, user4, user5, user6, user7, user8, user9, user10, user11, ]); const shouldMatch = [ user5, // name starts with 'ma' user6, // have priority as starts with 'ma' user7, // have priority as starts with 'ma' user2, // name contains in 'ma' user11, // have priority because of 'ma' contains in name user4, // email contains 'ma' user10, // email contains 'ma' ]; const filteredUsers = getAutocompleteSuggestion( allUsers, 'ma', eg.selfUser.user_id, Immutable.Map(), ); expect(filteredUsers).toEqual(shouldMatch); }); }); describe('getAutocompleteUserGroupSuggestions', () => { test('empty input results in empty list', () => { const userGroups = deepFreeze([]); const filteredUserGroups = getAutocompleteUserGroupSuggestions(userGroups, 'some filter'); expect(filteredUserGroups).toEqual(userGroups); }); test('searches in name and description, case-insensitive', () => { const userGroup1 = eg.makeUserGroup({ name: 'some user group', description: '' }); const userGroup2 = eg.makeUserGroup({ name: 'another one', description: '' }); const userGroup3 = eg.makeUserGroup({ name: 'last one', description: 'This is a Group' }); const userGroups = deepFreeze([userGroup1, userGroup2, userGroup3]); const shouldMatch = [userGroup1, userGroup3]; const filteredUsers = getAutocompleteUserGroupSuggestions(userGroups, 'group'); expect(filteredUsers).toEqual(shouldMatch); }); }); describe('sortUserList', () => { test('sorts list by name', () => { const user1 = eg.makeUser({ full_name: 'abc' }); const user2 = eg.makeUser({ full_name: 'xyz' }); const user3 = eg.makeUser({ full_name: 'jkl' }); const users = deepFreeze([user1, user2, user3]); const presences = makePresenceState([]); const shouldMatch = [user1, user3, user2]; const sortedUsers = sortUserList(users, presences); expect(sortedUsers).toEqual(shouldMatch); }); test('prioritizes status', () => { const user1 = eg.makeUser({ full_name: 'Mark' }); const user2 = eg.makeUser({ full_name: 'John' }); const user3 = eg.makeUser({ full_name: 'Bob' }); const user4 = eg.makeUser({ full_name: 'Rick' }); const users = deepFreeze([user1, user2, user3, user4]); const now = Date.now() / 1000; const presences = makePresenceState([ [user1, { aggregated: { client: 'website', status: 'offline', timestamp: now - 300 } }], [user2, { aggregated: { client: 'website', status: 'active', timestamp: now - 120 * 60 } }], [user3, { aggregated: { client: 'website', status: 'idle', timestamp: now - 20 * 60 } }], [user4, { aggregated: { client: 'website', status: 'active', timestamp: now } }], ]); const shouldMatch = [user4, user3, user2, user1]; const sortedUsers = sortUserList(users, presences); expect(sortedUsers).toEqual(shouldMatch); }); }); describe('filterUserStartWith', () => { test('returns users whose name starts with filter excluding self', () => { const user1 = eg.makeUser({ full_name: 'Apple' }); const user2 = eg.makeUser({ full_name: 'bob' }); const user3 = eg.makeUser({ full_name: 'app' }); const user4 = eg.makeUser({ full_name: 'Mobile app' }); const user5 = eg.makeUser({ full_name: 'Mac App' }); const selfUser = eg.makeUser({ full_name: 'app' }); const users = deepFreeze([user1, user2, user3, user4, user5, selfUser]); const expectedUsers = [user1, user3]; expect(filterUserStartWith(users, 'app', selfUser.user_id)).toEqual(expectedUsers); }); test('returns users whose name contains diacritics but otherwise starts with filter', () => { const withDiacritics = eg.makeUser({ full_name: 'Frd' }); const withoutDiacritics = eg.makeUser({ full_name: 'Frodo' }); const nonMatchingUser = eg.makeUser({ full_name: 'Zalix' }); const users = deepFreeze([withDiacritics, withoutDiacritics, nonMatchingUser]); const expectedUsers = [withDiacritics, withoutDiacritics]; expect(filterUserStartWith(users, 'Fro', eg.makeUser().user_id)).toEqual(expectedUsers); }); test('returns users whose name contains diacritics and filter uses diacritics', () => { const withDiacritics = eg.makeUser({ full_name: 'Frd' }); const withoutDiacritics = eg.makeUser({ full_name: 'Frodo' }); const wrongDiacritics = eg.makeUser({ full_name: 'Frd' }); const notIncludedDiactritic = eg.makeUser({ full_name: 'Fdo' }); const nonMatchingUser = eg.makeUser({ full_name: 'Zalix' }); const users = deepFreeze([ withDiacritics, withoutDiacritics, wrongDiacritics, notIncludedDiactritic, nonMatchingUser, ]); const expectedUsers = [withDiacritics]; expect(filterUserStartWith(users, 'Fr', eg.makeUser().user_id)).toEqual(expectedUsers); }); }); describe('groupUsersByStatus', () => { test('empty input results in empty map !!!', () => { const users = deepFreeze([]); const presence = makePresenceState([]); const groupedUsers = groupUsersByStatus(users, presence); expect(groupedUsers).toEqual({ active: [], idle: [], unavailable: [], offline: [] }); }); test('sort input by status, when no presence entry consider offline', () => { const user1 = eg.makeUser(); const user2 = eg.makeUser(); const user3 = eg.makeUser(); const user4 = eg.makeUser(); const users = deepFreeze([user1, user2, user3, user4]); const now = Date.now() / 1000; const presence = makePresenceState([ [user1, { aggregated: { client: 'website', status: 'active', timestamp: now } }], [user2, { aggregated: { client: 'website', status: 'idle', timestamp: now - 10 } }], [user3, { aggregated: { client: 'website', status: 'offline', timestamp: now - 150 } }], ]); const expectedResult = { active: [user1], idle: [user2], offline: [user3, user4], unavailable: [], }; const groupedUsers = groupUsersByStatus(users, presence); expect(groupedUsers).toEqual(expectedResult); }); }); describe('filterUserThatContains', () => { test('returns users whose full_name contains filter excluding self', () => { const user1 = eg.makeUser({ full_name: 'Apple' }); const user2 = eg.makeUser({ full_name: 'mam' }); const user3 = eg.makeUser({ full_name: 'app' }); const user4 = eg.makeUser({ full_name: 'Mobile app' }); const user5 = eg.makeUser({ full_name: 'Mac App' }); const user6 = eg.makeUser({ full_name: 'app' }); const selfUser = eg.makeUser({ full_name: 'app' }); const users = deepFreeze([user1, user2, user3, user4, user5, user6, selfUser]); const expectedUsers = [user2, user5]; expect(filterUserThatContains(users, 'ma', selfUser.user_id)).toEqual(expectedUsers); }); test('returns users whose full_name has diacritics but otherwise contains filter', () => { const withDiacritics = eg.makeUser({ full_name: 'Ardvrk' }); const withoutDiacritics = eg.makeUser({ full_name: 'Aardvark' }); const nonMatchingUser = eg.makeUser({ full_name: 'Turtle' }); const users = deepFreeze([withDiacritics, withoutDiacritics, nonMatchingUser]); const expectedUsers = [withDiacritics, withoutDiacritics]; expect(filterUserThatContains(users, 'vark', eg.makeUser().user_id)).toEqual(expectedUsers); }); test('returns users whose full_name has diacritics and filter uses diacritics', () => { const withDiacritics = eg.makeUser({ full_name: 'Ardvrk' }); const withoutDiacritics = eg.makeUser({ full_name: 'Aardvark' }); const wrongDiacritics = eg.makeUser({ full_name: 'Ardvrk' }); const notIncludedDiactritic = eg.makeUser({ full_name: 'Ardvk' }); const nonMatchingUser = eg.makeUser({ full_name: 'Turtle' }); const users = deepFreeze([ withDiacritics, withoutDiacritics, wrongDiacritics, notIncludedDiactritic, nonMatchingUser, ]); const expectedUsers = [withDiacritics]; expect(filterUserThatContains(users, 'vrk', eg.makeUser().user_id)).toEqual(expectedUsers); }); }); describe('filterUserMatchesEmail', () => { test('returns users whose email matches filter excluding self', () => { const user1 = eg.makeUser({ email: 'a@example.com' }); const user2 = eg.makeUser({ email: 'f@app.com' }); const user3 = eg.makeUser({ email: 'p@p.com' }); const user4 = eg.makeUser({ email: 'p3@p.com' }); const user5 = eg.makeUser({ email: 'p@p2.com' }); const user6 = eg.makeUser({ email: 'p@p.com' }); const selfUser = eg.makeUser({ email: 'own@example.com' }); const users = deepFreeze([user1, user2, user3, user4, user5, user6, selfUser]); const expectedUsers = [user1]; expect(filterUserMatchesEmail(users, 'example', selfUser.user_id)).toEqual(expectedUsers); }); }); ```
/content/code_sandbox/src/users/__tests__/userHelpers-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,674
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { useGlobalSelector, useSelector } from '../react-redux'; import Screen from '../common/Screen'; import NavRow from '../common/NavRow'; import ZulipText from '../common/ZulipText'; import { openLinkWithUserPreference } from '../utils/openLink'; import { getRealmUrl, getRealmName, getGlobalSettings } from '../selectors'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'legal'>, route: RouteProp<'legal', void>, |}>; /** (NB this is a per-account screen: it leads to this realm's policies.) */ export default function LegalScreen(props: Props): Node { const realm = useSelector(getRealmUrl); const realmName = useSelector(getRealmName); const globalSettings = useGlobalSelector(getGlobalSettings); const openZulipPolicies = useCallback(() => { openLinkWithUserPreference(new URL('path_to_url globalSettings); }, [globalSettings]); const openRealmPolicies = useCallback(() => { openLinkWithUserPreference(new URL('/policies/?nav=no', realm), globalSettings); }, [realm, globalSettings]); return ( <Screen title="Legal"> <NavRow title="Zulip terms" onPress={openZulipPolicies} type="external" /> <NavRow // These are really terms set by the server admin responsible for // hosting the org, and that server admin may or may not represent // the org itself, as this text might be read to imply. (E.g., // on Zulip Cloud they don't.) But: // - We don't want to complicate the wording. Not everyone knows // what a server is. // - These terms will often differ from Zulip's own terms (the ones // at the other link). // - These terms will apply to all users in the org, in all cases. // We should link to them. title={{ text: 'Terms for {realmName}', values: { realmName: ( <ZulipText inheritColor inheritFontSize style={{ fontWeight: 'bold' }} text={realmName} /> ), }, }} onPress={openRealmPolicies} type="external" /> </Screen> ); } ```
/content/code_sandbox/src/settings/LegalScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
553
```javascript /* @flow strict-local */ import type { ColorSchemeName } from 'react-native/Libraries/Utilities/NativeAppearance'; import type { ThemeSetting, ThemeName } from '../reduxTypes'; export const getThemeToUse = (theme: ThemeSetting, osScheme: ?ColorSchemeName): ThemeName => theme === 'default' ? 'light' : 'dark'; ```
/content/code_sandbox/src/settings/settingsSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
78
```javascript /* @flow strict-local */ import messagesByLanguage from '../i18n/messagesByLanguage'; export type Language = {| tag: $Keys<typeof messagesByLanguage>, name: string, selfname: string, |}; /** * The list of languages we offer in the language settings screen. * * The translation data files in `static/translations/` include all the * languages we have open on Transifex for people to translate. This means * all the languages that someone's expressed interest in translating Zulip * into, and there are usually some that aren't yet much translated at all. * * To avoid offering users a translation into their language when it won't * actually do anything, we maintain this separate list of languages that * are translated to an adequate level. * * The Zulip webapp offers a language in the UI when it's over 5% * translated. (Search for `percent_translated` in the server code.) * To see translation percentages, consult Transifex: * path_to_url * * For the values of `selfname`, consult Wikipedia: * path_to_url * path_to_url * or better yet, Wikipedia's own mobile UIs. Wikipedia is a very * conscientiously international and intercultural project with a lot of * effort going into it by speakers of many languages, which makes it a * useful gold standard for this. */ const languages: $ReadOnlyArray<Language> = [ // Keep these sorted by selfname, to help users find their language in the // UI. When in doubt how to sort (like between different scripts, or in // scripts you don't know), try to match the order found in other UIs, // like for choosing a language in your phone's system settings. // // When adding a language here, remember to add the language's name // (in English) to messages_en.json, too, so it can be translated. { tag: 'id', name: 'Indonesian', selfname: 'Bahasa Indonesia' }, { tag: 'ca', name: 'Catalan', selfname: 'Catal' }, { tag: 'cs', name: 'Czech', selfname: 'etina' }, { tag: 'cy', name: 'Welsh', selfname: 'Cymraeg' }, { tag: 'da', name: 'Danish', selfname: 'Dansk' }, { tag: 'de', name: 'German', selfname: 'Deutsch' }, { tag: 'en', name: 'English', selfname: 'English' }, { tag: 'en-GB', name: 'English (U.K.)', selfname: 'English (U.K.)' }, { tag: 'es', name: 'Spanish', selfname: 'Espaol' }, { tag: 'fr', name: 'French', selfname: 'Franais' }, { tag: 'gl', name: 'Galician', selfname: 'Galego' }, { tag: 'it', name: 'Italian', selfname: 'Italiano' }, { tag: 'lv', name: 'Latvian', selfname: 'Latvieu' }, { tag: 'lt', name: 'Lithuanian', selfname: 'Lietuvi' }, { tag: 'hu', name: 'Hungarian', selfname: 'Magyar' }, { tag: 'nl', name: 'Dutch', selfname: 'Nederlands' }, { tag: 'pl', name: 'Polish', selfname: 'Polski' }, // `pt-BR` omitted; it's over the threshold but fragmentary compared to // plain `pt`, which is meant to be the same thing. See discussion: // path_to_url#discussion_r673472275 // path_to_url#narrow/stream/58-translation/topic/language.20cleanup { tag: 'pt', name: 'Portuguese', selfname: 'Portugus' }, { tag: 'pt-PT', name: 'Portuguese (Portugal)', selfname: 'Portugus (Portugal)' }, { tag: 'ro', name: 'Romanian', selfname: 'Romn' }, { tag: 'fi', name: 'Finnish', selfname: 'Suomi' }, { tag: 'sv', name: 'Swedish', selfname: 'Svenska' }, { tag: 'tl', name: 'Tagalog', selfname: 'Tagalog' }, { tag: 'vi', name: 'Vietnamese', selfname: 'Ting Vit' }, { tag: 'tr', name: 'Turkish', selfname: 'Trke' }, { tag: 'be', name: 'Belarusian', selfname: '' }, { tag: 'bg', name: 'Bulgarian', selfname: '' }, { tag: 'mn', name: 'Mongolian', selfname: '' }, { tag: 'ru', name: 'Russian', selfname: '' }, { tag: 'sr', name: 'Serbian', selfname: '' }, { tag: 'uk', name: 'Ukrainian', selfname: '' }, { tag: 'ar', name: 'Arabic', selfname: '' }, { tag: 'bqi', name: 'Luri (Bakhtiari)', selfname: ' ()' }, { tag: 'fa', name: 'Persian', selfname: '' }, { tag: 'hi', name: 'Hindi', selfname: '' }, { tag: 'gu', name: 'Gujarati', selfname: '' }, { tag: 'ta', name: 'Tamil', selfname: '' }, { tag: 'ml', name: 'Malayalam', selfname: '' }, { tag: 'si', name: 'Sinhala', selfname: '' }, { tag: 'ko', name: 'Korean', selfname: '' }, { tag: 'zh-Hans', name: 'Chinese (China)', selfname: '' }, { tag: 'zh-TW', name: 'Chinese (Taiwan)', selfname: '' }, { tag: 'ja', name: 'Japanese', selfname: '' }, ]; export default languages; ```
/content/code_sandbox/src/settings/languages.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,403
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import invariant from 'invariant'; import type { AppNavigationMethods } from '../nav/AppNavigator'; import { useDispatch, useGlobalSelector, useSelector } from '../react-redux'; import { getAuth, getSettings } from '../selectors'; import SwitchRow from '../common/SwitchRow'; import * as api from '../api'; import NavRow from '../common/NavRow'; import TextRow from '../common/TextRow'; import { IconAlertTriangle } from '../common/Icons'; import { kWarningColor } from '../styles/constants'; import { getIdentity, getSilenceServerPushSetupWarnings, getZulipFeatureLevel, } from '../account/accountsSelectors'; import { getGlobalSession, getGlobalSettings, getRealm, getRealmName } from '../directSelectors'; import ZulipText from '../common/ZulipText'; import RowGroup from '../common/RowGroup'; import { openLinkWithUserPreference } from '../utils/openLink'; import { useNotificationReportsByIdentityKey, NotificationProblem, notifProblemShortReactText, chooseNotifProblemForShortText, pushNotificationsEnabledEndTimestampWarning, kPushNotificationsEnabledEndDoc, } from './NotifTroubleshootingScreen'; import { keyOfIdentity } from '../account/accountMisc'; import { ApiError } from '../api/apiErrors'; import { showErrorAlert } from '../utils/info'; import * as logging from '../utils/logging'; import { TranslationContext } from '../boot/TranslationProvider'; import { setSilenceServerPushSetupWarnings } from '../account/accountActions'; import { useDateRefreshedAtInterval } from '../reactUtils'; type Props = $ReadOnly<{| navigation: AppNavigationMethods, |}>; /** * A RowGroup with per-account settings for NotificationsScreen. */ export default function PerAccountNotificationSettingsGroup(props: Props): Node { const { navigation } = props; const dispatch = useDispatch(); const _ = React.useContext(TranslationContext); const dateNow = useDateRefreshedAtInterval(60_000); const auth = useSelector(getAuth); const identity = useSelector(getIdentity); const notificationReportsByIdentityKey = useNotificationReportsByIdentityKey(); const notificationReport = notificationReportsByIdentityKey.get(keyOfIdentity(identity)); invariant( notificationReport, 'NotificationsScreen: expected notificationReport for current account', ); const realmName = useSelector(getRealmName); const zulipFeatureLevel = useSelector(getZulipFeatureLevel); const pushNotificationsEnabled = useSelector(state => getRealm(state).pushNotificationsEnabled); const perAccountState = useSelector(state => state); const expiryWarning = pushNotificationsEnabledEndTimestampWarning(perAccountState, dateNow); const silenceServerPushSetupWarnings = useSelector(getSilenceServerPushSetupWarnings); const offlineNotification = useSelector(state => getSettings(state).offlineNotification); const onlineNotification = useSelector(state => getSettings(state).onlineNotification); const streamNotification = useSelector(state => getSettings(state).streamNotification); const globalSettings = useGlobalSelector(getGlobalSettings); const pushToken = useGlobalSelector(state => getGlobalSession(state).pushToken); const handleExpiryWarningPress = React.useCallback(() => { openLinkWithUserPreference(kPushNotificationsEnabledEndDoc, globalSettings); }, [globalSettings]); const handleSilenceWarningsChange = React.useCallback(() => { dispatch(setSilenceServerPushSetupWarnings(!silenceServerPushSetupWarnings)); }, [dispatch, silenceServerPushSetupWarnings]); // Helper variable so that we can refer to the button correctly in // other UI text. const troubleshootingPageTitle = 'Troubleshooting'; const handleTroubleshootingPress = useCallback(() => { navigation.push('notif-troubleshooting'); }, [navigation]); // TODO(#3999): It'd be good to show "working on it" UI feedback while a // request is pending, after the user touches a switch. const handleOfflineNotificationChange = useCallback(() => { api.toggleMobilePushSettings({ auth, opp: 'offline_notification_change', value: !offlineNotification, }); }, [offlineNotification, auth]); const handleOnlineNotificationChange = useCallback(() => { api.toggleMobilePushSettings({ auth, opp: 'online_notification_change', value: !onlineNotification, }); }, [onlineNotification, auth]); const handleStreamNotificationChange = useCallback(() => { api.toggleMobilePushSettings({ auth, opp: 'stream_notification_change', value: !streamNotification, }); }, [streamNotification, auth]); const [testNotificationRequestInProgress, setTestNotificationRequestInProgress] = React.useState(false); const handleTestNotificationPress = React.useCallback(async () => { invariant(pushToken != null, 'should be disabled if pushToken missing'); setTestNotificationRequestInProgress(true); try { await api.sendTestNotification(auth, { token: pushToken }); } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url if (!(error instanceof Error)) { logging.error('Unexpected non-error thrown from api.sendTestNotification'); return; } let msg = undefined; if (error instanceof ApiError) { // TODO recognize error.code and try to fix? give better feedback? msg = _('The server said:\n\n{errorMessage}', { errorMessage: error.message }); } else if (error.message.length > 0) { msg = error.message; } showErrorAlert(_('Failed to send test notification'), msg); } finally { setTestNotificationRequestInProgress(false); } }, [_, auth, pushToken]); let testNotificationDisabled = false; if (zulipFeatureLevel < 234) { testNotificationDisabled = { title: 'Feature not available', message: { text: 'This feature is only available for organizations on {zulipServerNameWithMinVersion}+.', values: { zulipServerNameWithMinVersion: 'Zulip Server 8.0' }, }, learnMoreButton: { url: new URL('path_to_url text: 'Upgrade instructions for server administrators', }, }; } else if (pushToken == null) { testNotificationDisabled = { title: 'Cannot send test notification', message: { text: 'Please tap {troubleshootingPageTitle} for more details.', values: { troubleshootingPageTitle: _(troubleshootingPageTitle) }, }, }; } else if (testNotificationRequestInProgress) { testNotificationDisabled = { title: 'Request in progress', message: 'Please wait. A request is already in progress.', }; } const children = []; if (expiryWarning != null) { children.push( <NavRow key="expiry" type="external" leftElement={{ type: 'icon', Component: IconAlertTriangle, color: kWarningColor }} title={expiryWarning.reactText} onPress={handleExpiryWarningPress} />, ); } if (pushNotificationsEnabled) { children.push( <SwitchRow key="offlineNotification" label="Notifications when offline" value={offlineNotification} onValueChange={handleOfflineNotificationChange} />, <SwitchRow key="onlineNotification" label="Notifications when online" value={onlineNotification} onValueChange={handleOnlineNotificationChange} />, <SwitchRow key="streamNotification" label="Stream notifications" value={streamNotification} onValueChange={handleStreamNotificationChange} />, <NavRow key="troubleshooting" {...(() => { const problem = chooseNotifProblemForShortText({ report: notificationReport }); return ( problem != null && { leftElement: { type: 'icon', Component: IconAlertTriangle, color: kWarningColor }, subtitle: notifProblemShortReactText(problem, realmName), } ); })()} title={troubleshootingPageTitle} onPress={handleTroubleshootingPress} />, <TextRow key="test" title="Send a test notification" onPress={handleTestNotificationPress} disabled={testNotificationDisabled} />, ); } else { children.push( <NavRow key="not-enabled" type="external" leftElement={{ type: 'icon', Component: IconAlertTriangle, color: kWarningColor }} title={notifProblemShortReactText(NotificationProblem.ServerHasNotEnabled, realmName)} onPress={() => { openLinkWithUserPreference( new URL( 'path_to_url#enabling-push-notifications-for-self-hosted-servers', ), globalSettings, ); }} />, ); } children.push( <SwitchRow key="silence-warnings" label="Silence warnings about disabled mobile notifications" value={silenceServerPushSetupWarnings} onValueChange={handleSilenceWarningsChange} />, ); return ( <RowGroup title={{ text: 'Notification settings for this account ({email} in {realmName}):', values: { email: ( <ZulipText inheritColor inheritFontSize style={{ fontWeight: 'bold' }} text={identity.email} /> ), realmName: ( <ZulipText inheritColor inheritFontSize style={{ fontWeight: 'bold' }} text={realmName} /> ), }, }} > {children} </RowGroup> ); } ```
/content/code_sandbox/src/settings/PerAccountNotificationSettingsGroup.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,086
```javascript /* @flow strict-local */ import invariant from 'invariant'; import * as React from 'react'; import { Platform, View, ScrollView, NativeModules } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import Clipboard from '@react-native-clipboard/clipboard'; import * as MailComposer from 'expo-mail-composer'; import { nativeApplicationVersion } from 'expo-application'; // $FlowFixMe[untyped-import] import uniq from 'lodash.uniq'; import subDays from 'date-fns/subDays'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import Screen from '../common/Screen'; import { createStyleSheet } from '../styles'; import { useDispatch, useGlobalSelector, useSelector } from '../react-redux'; import { getRealmName } from '../selectors'; import { getAccounts, getGlobalSession, getGlobalSettings, getRealm, getSession, getSettings, } from '../directSelectors'; import { getAccount, getServerVersion, getZulipFeatureLevel, tryGetActiveAccountState, } from '../account/accountsSelectors'; import { showErrorAlert, showToast } from '../utils/info'; import Input from '../common/Input'; import { identityOfAccount, keyOfIdentity } from '../account/accountMisc'; import AlertItem from '../common/AlertItem'; import ZulipText from '../common/ZulipText'; import type { Identity, LocalizableText, LocalizableReactText } from '../types'; import type { SubsetProperties } from '../generics'; import type { ZulipVersion } from '../utils/zulipVersion'; import { androidBrand, androidManufacturer, androidModel, useAppState } from '../reactNativeUtils'; import * as logging from '../utils/logging'; import { getHaveServerData } from '../haveServerDataSelectors'; import { TranslationContext } from '../boot/TranslationProvider'; import isAppOwnDomain from '../isAppOwnDomain'; import { openLinkWithUserPreference, openSystemNotificationSettings } from '../utils/openLink'; import { initNotifications } from '../notification/notifTokens'; import { ApiError } from '../api/apiErrors'; import NavRow from '../common/NavRow'; import RowGroup from '../common/RowGroup'; import TextRow from '../common/TextRow'; import type { PerAccountState } from '../reduxTypes'; import { useDateRefreshedAtInterval } from '../reactUtils'; import { roleIsAtLeast } from '../permissionSelectors'; import { Role } from '../api/permissionsTypes'; import { getOwnUser } from '../users/userSelectors'; import WebLink from '../common/WebLink'; const { Notifications, // android ZLPNotificationsStatus, // ios } = NativeModules; type Props = $ReadOnly<{| navigation: AppNavigationProp<'notif-troubleshooting'>, route: RouteProp<'notif-troubleshooting', void>, |}>; // Keep in sync with Android Notifications.googlePlayServicesAvailability. type GooglePlayServicesAvailability = {| +errorCode: number, +errorMessage: string | null, // observed to be null when there was no error +hasResolution: boolean, +isSuccess: boolean, |}; /** * Information about system settings, Google services availability, etc. * * A property will be null when we expect a value but don't have it yet. * It'll be undefined if we don't expect a value from the platform. (This * way, it's naturally removed from the JSON report we give the user.) */ type NativeState = {| +systemSettingsEnabled: boolean | null, +googlePlayServicesAvailability: GooglePlayServicesAvailability | null | void, // TODO: more, e.g.: // TODO(#5484): Android notification sound file missing // TODO(#438): Badge count disabled (once iOS supports it) |}; function useNativeState() { const [result, setResult] = React.useState<NativeState>({ systemSettingsEnabled: null, googlePlayServicesAvailability: Platform.OS === 'android' ? null : undefined, }); // Subject to races if calls to a given native method can resolve out of // order (unknown). const getAndSetResult = React.useCallback(() => { (async () => { const systemSettingsEnabled: boolean = await (Platform.OS === 'android' ? Notifications.areNotificationsEnabled() : ZLPNotificationsStatus.areNotificationsAuthorized()); setResult(r => ({ ...r, systemSettingsEnabled })); })(); if (Platform.OS === 'android') { (async () => { const googlePlayServicesAvailability: GooglePlayServicesAvailability = await Notifications.googlePlayServicesAvailability(); setResult(r => ({ ...r, googlePlayServicesAvailability })); })(); } }, []); // Greg points out that neither iOS or Android seems to have an API for // subscribing to changes, so one has to poll, and this seems like a fine // way to do so: // path_to_url#discussion_r1058055540 const appState = useAppState(); React.useEffect(() => { getAndSetResult(); }, [getAndSetResult, appState]); return result; } /** * Something that's very likely to prevent notifications from working. */ export enum NotificationProblem { TokenNotAcked = 0, TokenUnknown = 1, SystemSettingsDisabled = 2, GooglePlayServicesNotAvailable = 3, ServerHasNotEnabled = 4, // TODO: more, such as: // - Can't reach the server (ideally after #5615, to be less buggy) // - Android notification sound file missing (#5484) } const notifProblemsHighToLowShortTextPrecedence: $ReadOnlyArray<NotificationProblem> = [ NotificationProblem.SystemSettingsDisabled, NotificationProblem.GooglePlayServicesNotAvailable, NotificationProblem.ServerHasNotEnabled, NotificationProblem.TokenNotAcked, NotificationProblem.TokenUnknown, ]; invariant( new Set(notifProblemsHighToLowShortTextPrecedence).size === [...NotificationProblem.members()].length, 'notifProblemsHighToLowShortTextPrecedence missing or duplicate members', ); /** * Which of a NotificationReport's `problem`s to show short text for if any. * * Use this with notifProblemShortText and notifProblemShortReactText, * where there's room for just one problem's short text, like in the * NavRow leading to the notification settings screen. */ export const chooseNotifProblemForShortText = (args: {| // eslint-disable-next-line no-use-before-define report: { +problems: NotificationReport['problems'], ... }, ignoreServerHasNotEnabled?: boolean, |}): NotificationProblem | null => { const { report, ignoreServerHasNotEnabled = false } = args; const result = notifProblemsHighToLowShortTextPrecedence.find(p => { if (p === NotificationProblem.ServerHasNotEnabled && ignoreServerHasNotEnabled) { return false; } return report.problems.includes(p); }); return result ?? null; }; /** * A one-line summary of a NotificationProblem, as LocalizableText. * * For this as a LocalizableReactText, see notifProblemShortReactText. */ export const notifProblemShortText = ( problem: NotificationProblem, realmName: string, ): LocalizableText => { switch (problem) { case NotificationProblem.TokenNotAcked: case NotificationProblem.TokenUnknown: return 'Notifications for this account may not arrive.'; case NotificationProblem.SystemSettingsDisabled: return 'Notifications are disabled in system settings.'; case NotificationProblem.GooglePlayServicesNotAvailable: return 'Notifications require Google Play Services, which is unavailable.'; case NotificationProblem.ServerHasNotEnabled: return { text: 'Push notifications are not enabled for {realmName}.', values: { realmName }, }; } }; /** * A one-line summary of a NotificationProblem, as LocalizableReactText. * * For this as a LocalizableText, see notifProblemShortText. */ export const notifProblemShortReactText = ( problem: NotificationProblem, realmName: string, ): LocalizableReactText => { switch (problem) { case NotificationProblem.TokenNotAcked: case NotificationProblem.TokenUnknown: case NotificationProblem.SystemSettingsDisabled: case NotificationProblem.GooglePlayServicesNotAvailable: return notifProblemShortText(problem, realmName); case NotificationProblem.ServerHasNotEnabled: return { text: 'Push notifications are not enabled for {realmName}.', values: { realmName: ( <ZulipText inheritColor inheritFontSize style={{ fontWeight: 'bold' }} text={realmName} /> ), }, }; } }; /** * Data relevant to an account's push notifications, for support requests. * * Use jsonifyNotificationReport to get this into the form we want the user * to send the data in. One thing that does is strip away properties with * value `undefined`. */ export type NotificationReport = {| ...Identity, +isSelfHosted: boolean, +platform: SubsetProperties<typeof Platform, {| +OS: mixed, +Version: mixed, +isPad: boolean |}>, +nativeApplicationVersion: string | null, +manufacturer?: string, +brand?: string, +model?: string, +nativeState: NativeState, +problems: $ReadOnlyArray<NotificationProblem>, +isLoggedIn: boolean, +devicePushToken: string | null, +ackedPushToken: string | null, /** * See PerAccountSessionState.registerPushTokenRequestsInProgress. * * Pre-#5006, this will be undefined except for the active account if any. */ // TODO(#5006): When we maintain this for all accounts, include it for all. +registerPushTokenRequestsInProgress: number | void, /** * Server data from an event queue, if any. * * Pre-#5006, this will be undefined except for the active, logged-in * account, if it exists. For an active account that doesn't have server * data yet, will be null. */ // TODO(#5006): When we store server data for multiple accounts, include // this for all accounts that have server data. +serverData: {| +zulipVersion: ZulipVersion, +zulipFeatureLevel: number, +pushNotificationsEnabled: boolean, +pushNotificationsEnabledEndTimestamp: number | null, +endTimestampIsNear: boolean, +offlineNotification: boolean, +onlineNotification: boolean, +streamNotification: boolean, |} | null | void, |}; /** * Put a NotificationReport into the form we'd like to receive the data in. */ function jsonifyNotificationReport(report: NotificationReport): string { return JSON.stringify( { ...report, problems: report.problems.map(p => NotificationProblem.getName(p)) }, null, 2, ); } export const kPushNotificationsEnabledEndDoc: URL = new URL( 'path_to_url#upgrades-for-legacy-customers', ); export const pushNotificationsEnabledEndTimestampWarning = ( state: PerAccountState, dateNow: Date, ): {| text: LocalizableText, reactText: LocalizableReactText |} | null => { if (!getHaveServerData(state)) { return null; } const realmState = getRealm(state); const { pushNotificationsEnabledEndTimestamp: timestamp, pushNotificationsEnabled } = realmState; if (timestamp == null || !pushNotificationsEnabled) { return null; } const timestampMs = timestamp * 1000; const warningPeriodDays = roleIsAtLeast(getOwnUser(state).role, Role.Admin) ? 15 : 10; if (subDays(new Date(timestampMs), warningPeriodDays) > dateNow) { return null; } const realmName = realmState.name; const twentyFourHourTime = realmState.twentyFourHourTime; return { text: { text: twentyFourHourTime ? '{realmName} is scheduled to switch to a plan that does not include mobile notifications on {endTimestamp, date, short} at {endTimestamp, time, ::H:mm z}.' : '{realmName} is scheduled to switch to a plan that does not include mobile notifications on {endTimestamp, date, short} at {endTimestamp, time, ::h:mm z}.', values: { endTimestamp: timestampMs, realmName }, }, reactText: { text: twentyFourHourTime ? '{realmName} is scheduled to switch to a <z-link>plan</z-link> that does not include mobile notifications on {endTimestamp, date, short} at {endTimestamp, time, ::H:mm z}.' : '{realmName} is scheduled to switch to a <z-link>plan</z-link> that does not include mobile notifications on {endTimestamp, date, short} at {endTimestamp, time, ::h:mm z}.', values: { endTimestamp: timestampMs, realmName: ( <ZulipText inheritColor inheritFontSize style={{ fontWeight: 'bold' }} text={realmName} /> ), 'z-link': chunks => ( <WebLink inheritFontSize url={new URL('path_to_url#self-hosted')}> {chunks} </WebLink> ), }, }, }; }; /** * Generate and return a NotificationReport for all accounts we know about. */ export function useNotificationReportsByIdentityKey(): Map<string, NotificationReport> { const platform = React.useMemo( () => ({ OS: Platform.OS, Version: Platform.Version, isPad: Platform.isPad }), [], ); const nativeState = useNativeState(); const pushToken = useGlobalSelector(state => getGlobalSession(state).pushToken); const accounts = useGlobalSelector(getAccounts); const activeAccountState = useGlobalSelector(tryGetActiveAccountState); const dateNow = useDateRefreshedAtInterval(60_000); return React.useMemo( () => new Map( accounts.map(account => { const { ackedPushToken, apiKey } = account; const identity = identityOfAccount(account); const isLoggedIn = apiKey !== ''; let registerPushTokenRequestsInProgress = undefined; let serverData = undefined; if ( activeAccountState && keyOfIdentity(identityOfAccount(getAccount(activeAccountState))) === keyOfIdentity(identityOfAccount(account)) ) { registerPushTokenRequestsInProgress = getSession(activeAccountState).registerPushTokenRequestsInProgress; serverData = getHaveServerData(activeAccountState) ? { zulipVersion: getServerVersion(activeAccountState), zulipFeatureLevel: getZulipFeatureLevel(activeAccountState), pushNotificationsEnabled: getRealm(activeAccountState).pushNotificationsEnabled, pushNotificationsEnabledEndTimestamp: getRealm(activeAccountState).pushNotificationsEnabledEndTimestamp, endTimestampIsNear: pushNotificationsEnabledEndTimestampWarning(activeAccountState, dateNow) != null, offlineNotification: getSettings(activeAccountState).offlineNotification, onlineNotification: getSettings(activeAccountState).onlineNotification, streamNotification: getSettings(activeAccountState).streamNotification, } : null; } const problems = []; if (isLoggedIn) { if ( nativeState.googlePlayServicesAvailability && !nativeState.googlePlayServicesAvailability.isSuccess ) { problems.push(NotificationProblem.GooglePlayServicesNotAvailable); } if (nativeState.systemSettingsEnabled === false) { problems.push(NotificationProblem.SystemSettingsDisabled); } if (serverData && !serverData.pushNotificationsEnabled) { problems.push(NotificationProblem.ServerHasNotEnabled); } if (pushToken == null) { problems.push(NotificationProblem.TokenUnknown); } else if (pushToken !== ackedPushToken) { problems.push(NotificationProblem.TokenNotAcked); } } return [ keyOfIdentity(identityOfAccount(account)), { ...identity, isSelfHosted: !isAppOwnDomain(identity.realm), platform, nativeApplicationVersion, ...(Platform.OS === 'android' && { manufacturer: androidManufacturer(), brand: androidBrand(), model: androidModel(), }), nativeState, problems, isLoggedIn, devicePushToken: pushToken, ackedPushToken, registerPushTokenRequestsInProgress, serverData, }, ]; }), ), [nativeState, accounts, activeAccountState, pushToken, platform, dateNow], ); } /** * MailComposer.isAvailableAsync(), with polling on appState changes. */ function useMailComposerIsAvailable(): boolean | null { const [result, setResult] = React.useState(null); const getAndSetResult = React.useCallback(async () => { setResult(await MailComposer.isAvailableAsync()); }, []); const appState = useAppState(); React.useEffect(() => { getAndSetResult(); }, [getAndSetResult, appState]); return result; } /** * A per-account screen for troubleshooting notifications. * * Shows an alert (or alerts) when we know something is wrong, giving a * diagnosis and fix when we can, and otherwise asking the user to contact * support. * * Offers data (in JSON) that we can use in support requests and bug * reports. The user can tap a copy-to-clipboard button or open an email * composing session in their platform's native mail app. */ export default function NotifTroubleshootingScreen(props: Props): React.Node { const _ = React.useContext(TranslationContext); const dispatch = useDispatch(); const settings = useGlobalSelector(getGlobalSettings); const account = useSelector(getAccount); const identity = identityOfAccount(account); const realmName = useSelector(getRealmName); const notificationReportsByIdentityKey = useNotificationReportsByIdentityKey(); const report = notificationReportsByIdentityKey.get(keyOfIdentity(identityOfAccount(account))); invariant(report, 'NotifTroubleshootingScreen: expected report'); const styles = React.useMemo( () => createStyleSheet({ contentArea: { flex: 1, }, emailText: { fontWeight: 'bold', }, reportTextInput: { flex: 1, fontFamily: Platform.OS === 'ios' ? 'Courier' // This doesn't seem to work on Android : 'monospace', // This doesn't seem to work on iOS }, }), [], ); const handlePressRetryRegister = React.useCallback(async () => { try { await dispatch(initNotifications()); } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url if (!(error instanceof Error)) { logging.error('Unexpected non-error thrown'); } let msg = undefined; if (error instanceof ApiError) { msg = _('The server said:\n\n{errorMessage}', { errorMessage: error.message, }); } else if (error instanceof Error && error.message.length > 0) { msg = error.message; } showErrorAlert(_('Registration failed'), msg); } }, [_, dispatch]); const reportJson = React.useMemo(() => jsonifyNotificationReport(report), [report]); const handlePressCopy = React.useCallback(() => { Clipboard.setString(reportJson); showToast(_('Copied')); }, [reportJson, _]); const mailComposerIsAvailable = useMailComposerIsAvailable(); const handlePressTroubleshootingGuide = React.useCallback(() => { openLinkWithUserPreference( new URL('path_to_url#troubleshooting-mobile-notifications'), settings, ); }, [settings]); const handlePressEmailSupport = React.useCallback(async () => { const result = await MailComposer.composeAsync({ recipients: ['support@zulip.com'], subject: 'Zulip push notifications', body: `\ <h3>The problem:</h3> <p>(${_('Please describe the problem.')})</p> <h3>Other details:</h3> <p>(${_('If there are other details you would like to share, please write them here.')})</p> <hr> <p>This email was written from a template provided by the Zulip mobile app.</p> <details> <summary>Technical details:</summary> <pre>${reportJson}</pre> </details>\ `, isHtml: true, }); switch (result.status) { case MailComposer.MailComposerStatus.CANCELLED: break; case MailComposer.MailComposerStatus.SAVED: showToast(_('Draft saved')); break; case MailComposer.MailComposerStatus.SENT: showToast(_('Email sent')); logging.warn('NotifTroubleshootingScreen: MailComposer reports a sent email.'); break; case MailComposer.MailComposerStatus.UNDETERMINED: logging.warn('MailComposerStatus.UNDETERMINED'); break; } }, [reportJson, _]); // Generic "contact support" alert for any/all problems that the user // can't resolve themselves. If multiple problems map to this alert, we // deduplicate the alert. const genericAlert = ( <AlertItem bottomMargin text={{ text: 'Notifications for this account may not arrive. Please refer to the troubleshooting guide or contact {supportEmail} with the details below.', values: { supportEmail: ( <ZulipText inheritColor inheritFontSize style={styles.emailText} text="support@zulip.com" /> ), }, }} /> ); const alerts = []; report.problems.forEach(problem => { switch (problem) { case NotificationProblem.SystemSettingsDisabled: alerts.push( <AlertItem buttons={[ { id: 'fix', label: 'Open settings', onPress: openSystemNotificationSettings }, ]} bottomMargin text={notifProblemShortReactText(problem, realmName)} />, ); break; case NotificationProblem.GooglePlayServicesNotAvailable: // TODO: Could offer as a solution in case the user is actually fine // with Google Play Services and just has a problem with its setup: // - It looks like you can ask Android to run a native flow to // fix problems with Google Play Services: // path_to_url alerts.push( <AlertItem bottomMargin text={notifProblemShortReactText(problem, realmName)} />, ); break; case NotificationProblem.ServerHasNotEnabled: alerts.push( <AlertItem bottomMargin text={notifProblemShortReactText(problem, realmName)} buttons={[ { id: 'learn-more', label: 'Learn more', onPress: () => { openLinkWithUserPreference( new URL( 'path_to_url#enabling-push-notifications-for-self-hosted-servers', ), settings, ); }, }, ]} />, ); break; case NotificationProblem.TokenNotAcked: { invariant( report.registerPushTokenRequestsInProgress != null, 'report.registerPushTokenRequestsInProgress missing for active account?', ); const isInProgress = report.registerPushTokenRequestsInProgress > 0; alerts.push( <AlertItem bottomMargin text={{ text: isInProgress ? 'The Zulip server at {realm} has not yet registered your device token. A request is in progress.' : 'The Zulip server at {realm} has not yet registered your device token.', values: { realm: identity.realm.toString() }, }} buttons={ isInProgress ? undefined : [{ id: 'retry', label: 'Retry', onPress: handlePressRetryRegister }] } />, ); alerts.push(genericAlert); // Still point to support for good measure break; } case NotificationProblem.TokenUnknown: { // TODO: Could offer: // - Re-request the device token from the platform (#5329 may be // an obstacle), and show if a/the request hasn't completed alerts.push(genericAlert); break; } } }); return ( <Screen scrollEnabled={false} title="Troubleshooting"> <SafeAreaView mode="padding" edges={['right', 'left']} style={styles.contentArea}> <View style={{ paddingHorizontal: 16, paddingTop: 16 }}> { // TODO: Avoid comparing these complex UI-describing objects: // path_to_url#discussion_r1105122407 uniq(alerts) // Deduplicate genericAlert, which multiple problems might map to } </View> <RowGroup> {(() => { const children = []; children.push( <NavRow type="external" title="Troubleshooting guide" onPress={handlePressTroubleshootingGuide} />, ); if (mailComposerIsAvailable === true) { children.push( <TextRow title={{ text: 'Email {supportEmail}', values: { supportEmail: ( <ZulipText inheritColor inheritFontSize style={styles.emailText} text="support@zulip.com" /> ), }, }} onPress={handlePressEmailSupport} />, ); } children.push(<TextRow title="Copy to clipboard" onPress={handlePressCopy} />); return children; })()} </RowGroup> <View style={{ paddingHorizontal: 16, paddingTop: 8, paddingBottom: 16, flex: 1 }}> {Platform.OS === 'android' ? ( // ScrollView for Android-only symptoms like // facebook/react-native#23117 <ScrollView style={{ flex: 1 }}> <Input editable={false} multiline style={styles.reportTextInput} value={reportJson} /> </ScrollView> ) : ( <Input editable={false} multiline style={styles.reportTextInput} value={reportJson} /> )} </View> </SafeAreaView> </Screen> ); } ```
/content/code_sandbox/src/settings/NotifTroubleshootingScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
5,657
```javascript /* @flow strict-local */ import type { AccountIndependentAction, GlobalSettingsState } from '../types'; import { SET_GLOBAL_SETTINGS } from '../actionConstants'; export const setGlobalSettings = ( update: $Shape<$Exact<GlobalSettingsState>>, ): AccountIndependentAction => ({ type: SET_GLOBAL_SETTINGS, update, }); ```
/content/code_sandbox/src/settings/settingsActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
69
```javascript /* @flow strict-local */ import React, { useCallback, useContext } from 'react'; import type { Node } from 'react'; import { Alert } from 'react-native'; import invariant from 'invariant'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { useGlobalSelector, useSelector } from '../react-redux'; import Screen from '../common/Screen'; import NavRow from '../common/NavRow'; import { IconAlertTriangle } from '../common/Icons'; import type { LocalizableText } from '../types'; import { TranslationContext } from '../boot/TranslationProvider'; import { kWarningColor } from '../styles/constants'; import { getIdentities, getIdentity, getIsActiveAccount } from '../account/accountsSelectors'; import { openSystemNotificationSettings } from '../utils/openLink'; import { useNotificationReportsByIdentityKey, NotificationProblem, } from './NotifTroubleshootingScreen'; import { keyOfIdentity } from '../account/accountMisc'; import PerAccountNotificationSettingsGroup from './PerAccountNotificationSettingsGroup'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'notifications'>, route: RouteProp<'notifications', void>, |}>; function systemSettingsWarning(problem): LocalizableText | null { switch (problem) { case NotificationProblem.SystemSettingsDisabled: return 'Notifications are disabled.'; case NotificationProblem.GooglePlayServicesNotAvailable: case NotificationProblem.TokenNotAcked: case NotificationProblem.TokenUnknown: case NotificationProblem.ServerHasNotEnabled: // We can't ask the user to fix this in system notification settings. return null; } } /** * Notification settings with warnings when something seems wrong. * * Includes an area for per-account settings. */ export default function NotificationsScreen(props: Props): Node { const { navigation } = props; const _ = useContext(TranslationContext); const identity = useSelector(getIdentity); const notificationReportsByIdentityKey = useNotificationReportsByIdentityKey(); const notificationReport = notificationReportsByIdentityKey.get(keyOfIdentity(identity)); invariant( notificationReport, 'NotificationsScreen: expected notificationReport for current account', ); const otherAccounts = useGlobalSelector(state => getIdentities(state).filter(identity_ => !getIsActiveAccount(state, identity_)), ); const systemSettingsWarnings = notificationReport.problems .map(systemSettingsWarning) .filter(Boolean); const handleSystemSettingsPress = useCallback(() => { if (systemSettingsWarnings.length > 1) { Alert.alert( _('System settings for Zulip'), // List all warnings that apply. systemSettingsWarnings.map(w => _(w)).join('\n\n'), [ { text: _('Cancel'), style: 'cancel' }, { text: _('Open settings'), onPress: () => { openSystemNotificationSettings(); }, style: 'default', }, ], { cancelable: true }, ); return; } openSystemNotificationSettings(); }, [systemSettingsWarnings, _]); const handleOtherAccountsPress = useCallback(() => { navigation.push('account-pick'); }, [navigation]); return ( <Screen title="Notifications"> <NavRow leftElement={ systemSettingsWarnings.length > 0 ? { type: 'icon', Component: IconAlertTriangle, color: kWarningColor, } : undefined } title="System settings for Zulip" subtitle={(() => { switch (systemSettingsWarnings.length) { case 0: return undefined; case 1: return systemSettingsWarnings[0]; default: return 'Multiple issues. Tap to learn more.'; } })()} onPress={handleSystemSettingsPress} type="external" /> {!notificationReport.problems.includes(NotificationProblem.SystemSettingsDisabled) && ( <> <PerAccountNotificationSettingsGroup navigation={navigation} /> {otherAccounts.length > 0 && ( <NavRow {...(() => { const problemAccountsCount = otherAccounts.filter(a => { // eslint-disable-next-line no-underscore-dangle const notificationReport_ = notificationReportsByIdentityKey.get( keyOfIdentity(a), ); invariant(notificationReport_, 'AccountPickScreen: expected notificationReport_'); return notificationReport_.problems.length > 0; }).length; return problemAccountsCount > 0 ? { leftElement: { type: 'icon', Component: IconAlertTriangle, color: kWarningColor, }, subtitle: { text: `\ {problemAccountsCount, plural, one {Notifications for {problemAccountsCount} other logged-in account may not arrive.} other {Notifications for {problemAccountsCount} other logged-in accounts may not arrive.} }`, values: { problemAccountsCount }, }, } : undefined; })()} title="Other accounts" onPress={handleOtherAccountsPress} /> )} </> )} </Screen> ); } ```
/content/code_sandbox/src/settings/NotificationsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,076
```javascript /* @flow strict-local */ import type { GlobalSettingsState, PerAccountSettingsState } from '../reduxTypes'; import type { SettingsState, Action } from '../types'; import { RESET_ACCOUNT_DATA, SET_GLOBAL_SETTINGS, REGISTER_COMPLETE, EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, EVENT, } from '../actionConstants'; import { EventTypes } from '../api/eventTypes'; import { ensureUnreachable } from '../types'; const initialGlobalSettingsState: $Exact<GlobalSettingsState> = { language: 'en', theme: 'default', browser: 'default', experimentalFeaturesEnabled: false, markMessagesReadOnScroll: 'always', }; /** PRIVATE; exported only for tests. */ export const initialPerAccountSettingsState: $Exact<PerAccountSettingsState> = { offlineNotification: true, onlineNotification: true, streamNotification: false, displayEmojiReactionUsers: false, }; const initialState: SettingsState = { ...initialGlobalSettingsState, ...initialPerAccountSettingsState, }; // eslint-disable-next-line default-param-last export default (state: SettingsState = initialState, action: Action): SettingsState => { switch (action.type) { case RESET_ACCOUNT_DATA: return { ...state, ...initialPerAccountSettingsState }; case REGISTER_COMPLETE: { const { data } = action; if (data.user_settings) { return { ...state, offlineNotification: data.user_settings.enable_offline_push_notifications, onlineNotification: data.user_settings.enable_online_push_notifications, streamNotification: data.user_settings.enable_stream_push_notifications, // TODO(server-6.0): Remove fallback. displayEmojiReactionUsers: data.user_settings.display_emoji_reaction_users ?? false, }; } else { // Fall back to InitialDataUpdateDisplaySettings for servers that // don't support the user_settings_object client capability. return { ...state, /* $FlowIgnore[incompatible-cast]: If `user_settings` is absent, this will be present. */ offlineNotification: (action.data.enable_offline_push_notifications: boolean), // $FlowIgnore[incompatible-cast] onlineNotification: (action.data.enable_online_push_notifications: boolean), // $FlowIgnore[incompatible-cast] streamNotification: (action.data.enable_stream_push_notifications: boolean), }; } } case SET_GLOBAL_SETTINGS: return { ...state, ...action.update, }; case EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS: switch (action.notification_name) { case 'enable_offline_push_notifications': return { ...state, offlineNotification: action.setting }; case 'enable_online_push_notifications': return { ...state, onlineNotification: action.setting }; case 'enable_stream_push_notifications': return { ...state, streamNotification: action.setting }; default: ensureUnreachable(action.notification_name); return state; } case EVENT: { const { event } = action; switch (event.type) { case EventTypes.user_settings: if (event.op === 'update') { const { property, value } = event; switch (property) { case 'enable_offline_push_notifications': { // $FlowFixMe[incompatible-cast] - fix UserSettingsUpdateEvent return { ...state, offlineNotification: (value: boolean) }; } case 'enable_online_push_notifications': { // $FlowFixMe[incompatible-cast] - fix UserSettingsUpdateEvent return { ...state, onlineNotification: (value: boolean) }; } case 'enable_stream_push_notifications': { // $FlowFixMe[incompatible-cast] - fix UserSettingsUpdateEvent return { ...state, streamNotification: (value: boolean) }; } case 'display_emoji_reaction_users': { // $FlowFixMe[incompatible-cast] - fix UserSettingsUpdateEvent return { ...state, displayEmojiReactionUsers: (value: boolean) }; } default: return state; } } return state; default: return state; } } default: return state; } }; ```
/content/code_sandbox/src/settings/settingsReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
883
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import { nativeApplicationVersion } from 'expo-application'; import invariant from 'invariant'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { useSelector, useGlobalSelector, useDispatch } from '../react-redux'; import { getGlobalSettings } from '../selectors'; import NavRow from '../common/NavRow'; import InputRowRadioButtons from '../common/InputRowRadioButtons'; import SwitchRow from '../common/SwitchRow'; import Screen from '../common/Screen'; import { IconNotifications, IconLanguage, IconMoreHorizontal, IconSmartphone, IconServer, IconAlertTriangle, } from '../common/Icons'; import { setGlobalSettings } from '../actions'; import { shouldUseInAppBrowser } from '../utils/openLink'; import TextRow from '../common/TextRow'; import { getIdentity, getServerVersion } from '../account/accountsSelectors'; import { kMinSupportedVersion, kServerSupportDocUrl } from '../common/ServerCompatBanner'; import { kWarningColor } from '../styles/constants'; import { showErrorAlert } from '../utils/info'; import { TranslationContext } from '../boot/TranslationProvider'; import { useNotificationReportsByIdentityKey, chooseNotifProblemForShortText, notifProblemShortReactText, pushNotificationsEnabledEndTimestampWarning, } from './NotifTroubleshootingScreen'; import { noTranslation } from '../i18n/i18n'; import { keyOfIdentity } from '../account/accountMisc'; import languages from './languages'; import { getRealmName } from '../directSelectors'; import { useDateRefreshedAtInterval } from '../reactUtils'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'settings'>, route: RouteProp<'settings', void>, |}>; export default function SettingsScreen(props: Props): Node { const dateNow = useDateRefreshedAtInterval(60_000); const theme = useGlobalSelector(state => getGlobalSettings(state).theme); const browser = useGlobalSelector(state => getGlobalSettings(state).browser); const globalSettings = useGlobalSelector(getGlobalSettings); const markMessagesReadOnScroll = globalSettings.markMessagesReadOnScroll; const language = useGlobalSelector(state => getGlobalSettings(state).language); const perAccountState = useSelector(state => state); const expiryWarning = pushNotificationsEnabledEndTimestampWarning(perAccountState, dateNow); const zulipVersion = useSelector(getServerVersion); const identity = useSelector(getIdentity); const notificationReportsByIdentityKey = useNotificationReportsByIdentityKey(); const notificationReport = notificationReportsByIdentityKey.get(keyOfIdentity(identity)); invariant(notificationReport, 'SettingsScreen: expected notificationReport'); const realmName = useSelector(getRealmName); const dispatch = useDispatch(); const _ = React.useContext(TranslationContext); const { navigation } = props; const handleThemeChange = useCallback(() => { dispatch(setGlobalSettings({ theme: theme === 'default' ? 'night' : 'default' })); }, [theme, dispatch]); return ( <Screen title="Settings"> <SwitchRow label="Night mode" value={theme === 'night'} onValueChange={handleThemeChange} /> <SwitchRow label="Open links with in-app browser" value={shouldUseInAppBrowser(browser)} onValueChange={value => { dispatch(setGlobalSettings({ browser: value ? 'embedded' : 'external' })); }} /> <InputRowRadioButtons navigation={navigation} label="Mark messages as read on scroll" description="When scrolling through messages, should they automatically be marked as read?" valueKey={markMessagesReadOnScroll} items={[ { key: 'always', title: 'Always' }, { key: 'never', title: 'Never' }, { key: 'conversation-views-only', title: 'Only in conversation views', subtitle: 'Messages will be automatically marked as read only when viewing a single topic or direct message conversation.', }, ]} onValueChange={value => { dispatch(setGlobalSettings({ markMessagesReadOnScroll: value })); }} /> <NavRow leftElement={{ type: 'icon', Component: IconNotifications }} title="Notifications" {...(() => { const problem = chooseNotifProblemForShortText({ report: notificationReport }); if (expiryWarning == null && problem == null) { return; } let subtitle = undefined; if (problem != null) { subtitle = notifProblemShortReactText(problem, realmName); } else if (expiryWarning != null) { subtitle = expiryWarning.reactText; } invariant(subtitle != null, 'expected non-null `expiryWarning` or `problem`'); return { leftElement: { type: 'icon', Component: IconAlertTriangle, color: kWarningColor }, subtitle, }; })()} onPress={() => { navigation.push('notifications'); }} /> <InputRowRadioButtons icon={{ Component: IconLanguage }} navigation={navigation} label="Language" valueKey={language} items={languages.map(l => ({ key: l.tag, title: noTranslation(l.selfname), subtitle: l.tag === language ? noTranslation(l.selfname) : l.name, }))} onValueChange={value => { dispatch(setGlobalSettings({ language: value })); }} search /> <NavRow leftElement={{ type: 'icon', Component: IconMoreHorizontal }} title="Legal" onPress={() => { navigation.push('legal'); }} /> <TextRow icon={{ Component: IconSmartphone }} title="App version" subtitle={noTranslation(`v${nativeApplicationVersion ?? '?.?.?'}`)} /> <TextRow icon={{ Component: IconServer }} title="Server version" subtitle={noTranslation(zulipVersion.raw())} {...(!zulipVersion.isAtLeast(kMinSupportedVersion) && { icon: { Component: IconAlertTriangle, color: kWarningColor }, onPress: () => { showErrorAlert( 'Server not supported', _({ text: '{realm} is running Zulip Server {version}, which is unsupported. The minimum supported version is Zulip Server {minSupportedVersion}.', values: { realm: identity.realm.toString(), version: zulipVersion.raw(), minSupportedVersion: kMinSupportedVersion.raw(), }, }), { url: kServerSupportDocUrl, globalSettings }, ); }, })} /> </Screen> ); } ```
/content/code_sandbox/src/settings/SettingsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,456
```javascript /* @flow strict-local */ import invariant from 'invariant'; import { createSelector } from 'reselect'; import type { PerAccountState, PmMessage, PmConversationData, Selector } from '../types'; import { getPrivateMessages } from '../message/messageSelectors'; import { getAllUsersById, getOwnUserId } from '../users/userSelectors'; import { getUnreadByPms, getUnreadByHuddles } from '../unread/unreadSelectors'; import { pmUnreadsKeyFromMessage, pmKeyRecipientUsersFromMessage, pmKeyRecipientUsersFromIds, pmUnreadsKeyFromPmKeyIds, pmKeyRecipientsFromPmKeyUsers, } from '../utils/recipient'; import { getServerVersion } from '../account/accountsSelectors'; import * as model from './pmConversationsModel'; import { type PmConversationsState } from './pmConversationsModel'; function unreadCount(unreadsKey, unreadPms, unreadHuddles): number { // This business of looking in one place and then the other is kind // of messy. Fortunately it always works, because the key spaces // are disjoint: all `unreadHuddles` keys contain a comma, and all // `unreadPms` keys don't. /* $FlowFixMe[incompatible-type]: The keys of unreadPms are logically numbers... but because it's an object, they end up converted to strings, so this access with string keys works. We should probably use a Map for this and similar maps. */ return unreadPms[unreadsKey] || unreadHuddles[unreadsKey]; } // TODO(server-2.1): Delete this, and simplify logic around it. export const getRecentConversationsLegacy: Selector<$ReadOnlyArray<PmConversationData>> = createSelector( getOwnUserId, getPrivateMessages, getUnreadByPms, getUnreadByHuddles, getAllUsersById, ( ownUserId, messages: $ReadOnlyArray<PmMessage>, unreadPms: {| [number]: number |}, unreadHuddles: {| [string]: number |}, allUsersById, ): $ReadOnlyArray<PmConversationData> => { const items = messages .map(msg => { // Note this can be a different set of users from those in `keyRecipients`. const unreadsKey = pmUnreadsKeyFromMessage(msg, ownUserId); const keyRecipients = pmKeyRecipientUsersFromMessage(msg, allUsersById, ownUserId); return keyRecipients === null ? null : { unreadsKey, keyRecipients, msgId: msg.id }; }) .filter(Boolean); const latestByRecipients = new Map(); items.forEach(item => { const prev = latestByRecipients.get(item.unreadsKey); if (!prev || item.msgId > prev.msgId) { latestByRecipients.set(item.unreadsKey, item); } }); const sortedByMostRecent = Array.from(latestByRecipients.values()).sort( (a, b) => +b.msgId - +a.msgId, ); return sortedByMostRecent.map(conversation => ({ key: conversation.unreadsKey, keyRecipients: conversation.keyRecipients, msgId: conversation.msgId, unread: unreadCount(conversation.unreadsKey, unreadPms, unreadHuddles), })); }, ); export const getRecentConversationsModern: Selector<$ReadOnlyArray<PmConversationData>> = createSelector( state => state.pmConversations, getUnreadByPms, getUnreadByHuddles, getAllUsersById, getOwnUserId, // This is defined separately, just below. When this is defined inline, // if there's a type error in it, the message Flow gives is often pretty // terrible: just highlighting the whole thing and pointing at something // in the `reselect` libdef. Defining it separately seems to help. getRecentConversationsModernImpl, // eslint-disable-line no-use-before-define ); function getRecentConversationsModernImpl( { sorted, map }: PmConversationsState, unreadPms, unreadHuddles, allUsersById, ownUserId, ): $ReadOnlyArray<PmConversationData> { return sorted .toSeq() .map(recentsKey => { const keyRecipients = pmKeyRecipientUsersFromIds( model.usersOfKey(recentsKey), allUsersById, ownUserId, ); if (keyRecipients === null) { return null; } const unreadsKey = pmUnreadsKeyFromPmKeyIds( pmKeyRecipientsFromPmKeyUsers(keyRecipients), ownUserId, ); const msgId = map.get(recentsKey); invariant(msgId !== undefined, 'pm-conversations: key in sorted should be in map'); const unread = unreadCount(unreadsKey, unreadPms, unreadHuddles); return { key: unreadsKey, keyRecipients, msgId, unread }; }) .filter(Boolean) .toArray(); } const getServerIsOld: Selector<boolean> = createSelector( getServerVersion, version => !version.isAtLeast(model.MIN_RECENTPMS_SERVER_VERSION), ); /** * The most recent PM conversations, with unread count and latest message ID. */ export const getRecentConversations = ( state: PerAccountState, ): $ReadOnlyArray<PmConversationData> => getServerIsOld(state) ? getRecentConversationsLegacy(state) : getRecentConversationsModern(state); export const getUnreadConversations: Selector<$ReadOnlyArray<PmConversationData>> = createSelector( getRecentConversations, conversations => conversations.filter(c => c.unread > 0), ); ```
/content/code_sandbox/src/pm-conversations/pmConversationsSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,262
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import type { SettingsState } from '../../types'; import { SET_GLOBAL_SETTINGS, EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, EVENT, } from '../../actionConstants'; import type { InitialData } from '../../api/initialDataTypes'; import type { UserSettings } from '../../api/modelTypes'; import { EventTypes } from '../../api/eventTypes'; import settingsReducer, { initialPerAccountSettingsState } from '../settingsReducer'; import * as eg from '../../__tests__/lib/exampleData'; describe('settingsReducer', () => { const baseState = eg.baseReduxState.settings; describe('RESET_ACCOUNT_DATA', () => { test('resets per-account state without touching global state', () => { const prevState = [ // per-account eg.mkActionRegisterComplete({ user_settings: { /* $FlowIgnore[incompatible-cast] - testing modern servers, which send user_settings. */ ...(eg.action.register_complete.data.user_settings: $NonMaybeType< InitialData['user_settings'], >), enable_offline_push_notifications: false, enable_online_push_notifications: false, enable_stream_push_notifications: true, display_emoji_reaction_users: true, }, }), // global { type: SET_GLOBAL_SETTINGS, update: { theme: 'night' } }, { type: SET_GLOBAL_SETTINGS, update: { language: 'fr' } }, ].reduce(settingsReducer, eg.baseReduxState.settings); expect(settingsReducer(prevState, eg.action.reset_account_data)).toEqual({ ...prevState, ...initialPerAccountSettingsState, }); }); }); describe('REGISTER_COMPLETE', () => { test('changes value of all notification settings (legacy, without user_settings)', () => { const prevState = deepFreeze({ ...baseState, offlineNotification: false, onlineNotification: false, streamNotification: false, }); expect( settingsReducer( prevState, eg.mkActionRegisterComplete({ enable_offline_push_notifications: true, enable_online_push_notifications: true, enable_stream_push_notifications: true, user_settings: undefined, }), ), ).toMatchObject({ offlineNotification: true, onlineNotification: true, streamNotification: true, }); }); test('changes value of all per-account settings (modern, with user_settings)', () => { expect( settingsReducer( deepFreeze({ ...baseState, offlineNotification: false, onlineNotification: false, streamNotification: false, displayEmojiReactionUsers: false, }), eg.mkActionRegisterComplete({ user_settings: { /* $FlowIgnore[incompatible-cast] - testing modern servers, which send user_settings. */ ...(eg.action.register_complete.data.user_settings: $NonMaybeType< InitialData['user_settings'], >), enable_offline_push_notifications: true, enable_online_push_notifications: true, enable_stream_push_notifications: true, display_emoji_reaction_users: true, }, }), ), ).toEqual({ ...baseState, offlineNotification: true, onlineNotification: true, streamNotification: true, displayEmojiReactionUsers: true, }); }); }); describe('SET_GLOBAL_SETTINGS', () => { test('changes value of a key', () => { expect( settingsReducer( baseState, deepFreeze({ type: SET_GLOBAL_SETTINGS, update: { theme: 'night' } }), ), ).toEqual({ ...baseState, theme: 'night' }); }); }); describe('EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS', () => { test('changes offline notification setting', () => { const prevState = deepFreeze({ ...baseState, offlineNotification: false }); expect( settingsReducer( prevState, deepFreeze({ type: EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, id: 0, notification_name: 'enable_offline_push_notifications', setting: true, }), ), ).toEqual({ ...baseState, offlineNotification: true }); }); test('changes online notification setting', () => { const prevState = deepFreeze({ ...baseState, onlineNotification: false }); expect( settingsReducer( prevState, deepFreeze({ type: EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, id: 0, notification_name: 'enable_online_push_notifications', setting: true, }), ), ).toEqual({ ...baseState, onlineNotification: true }); }); test('changes stream notification setting', () => { const prevState = deepFreeze({ ...baseState, streamNotification: false }); expect( settingsReducer( prevState, deepFreeze({ type: EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, id: 0, notification_name: 'enable_stream_push_notifications', setting: true, }), ), ).toEqual({ ...baseState, streamNotification: true }); }); }); describe('EVENT', () => { describe('type `user_settings`, op `update`', () => { const eventCommon = { id: 0, type: EventTypes.user_settings, op: 'update' }; const mkCheck = <S: $Keys<SettingsState>, E: $Keys<UserSettings>>( statePropertyName: S, eventPropertyName: E, ): ((SettingsState[S], UserSettings[E]) => void) => (initialStateValue, eventValue) => { test(`${initialStateValue.toString()} ${eventValue?.toString() ?? '[nullish]'}`, () => { const initialState = { ...baseState }; /* $FlowFixMe[incompatible-type]: Trust that the caller passed the right kind of value for its chosen key. */ initialState[statePropertyName] = initialStateValue; const expectedState = { ...initialState }; /* $FlowFixMe[incompatible-type]: Trust that the caller passed the right kind of value for its chosen key. */ expectedState[statePropertyName] = eventValue; expect( settingsReducer(initialState, { type: EVENT, event: { ...eventCommon, property: eventPropertyName, value: eventValue }, }), ).toEqual(expectedState); }); }; describe('offlineNotification / enable_offline_push_notifications', () => { const check = mkCheck('offlineNotification', 'enable_offline_push_notifications'); check(true, true); check(true, false); check(false, true); check(false, false); }); describe('onlineNotification / enable_online_push_notifications', () => { const check = mkCheck('onlineNotification', 'enable_online_push_notifications'); check(true, true); check(true, false); check(false, true); check(false, false); }); describe('streamNotification / enable_stream_push_notifications', () => { const check = mkCheck('streamNotification', 'enable_stream_push_notifications'); check(true, true); check(true, false); check(false, true); check(false, false); }); describe('displayEmojiReactionUsers / display_emoji_reaction_users', () => { const check = mkCheck('displayEmojiReactionUsers', 'display_emoji_reaction_users'); check(true, true); check(true, false); check(false, true); check(false, false); }); }); }); }); ```
/content/code_sandbox/src/settings/__tests__/settingsReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,578
```javascript /* @flow strict-local */ import React, { useCallback, useMemo } from 'react'; import type { Node } from 'react'; import { FlatList } from 'react-native'; import { useDispatch, useSelector } from '../react-redux'; import type { PmConversationData, UserOrBot } from '../types'; import { type PmKeyUsers } from '../utils/recipient'; import { pm1to1NarrowFromUser, pmNarrowFromUsers } from '../utils/narrow'; import UserItem from '../users/UserItem'; import GroupPmConversationItem from './GroupPmConversationItem'; import { doNarrow } from '../actions'; import { getMutedUsers } from '../selectors'; type Props = $ReadOnly<{| conversations: $ReadOnlyArray<PmConversationData>, extraPaddingEnd?: number, |}>; /** * A list describing all PM conversations. * */ export default function PmConversationList(props: Props): Node { const dispatch = useDispatch(); const handleUserNarrow = useCallback( (user: UserOrBot) => { dispatch(doNarrow(pm1to1NarrowFromUser(user))); }, [dispatch], ); const handleGroupNarrow = useCallback( (users: PmKeyUsers) => { dispatch(doNarrow(pmNarrowFromUsers(users))); }, [dispatch], ); const { conversations, extraPaddingEnd = 0 } = props; const mutedUsers = useSelector(getMutedUsers); const styles = useMemo( () => ({ list: { flex: 1, flexDirection: 'column', paddingRight: extraPaddingEnd, }, }), [extraPaddingEnd], ); return ( <FlatList style={styles.list} initialNumToRender={20} data={conversations} renderItem={({ item }) => { const users = item.keyRecipients; if (users.length === 1) { const user_id = users[0].user_id; if (mutedUsers.has(user_id)) { return null; } else { return ( <UserItem userId={user_id} unreadCount={item.unread} onPress={handleUserNarrow} /> ); } } else { return ( <GroupPmConversationItem users={users} unreadCount={item.unread} onPress={handleGroupNarrow} /> ); } }} /> ); } ```
/content/code_sandbox/src/pm-conversations/PmConversationList.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
522
```javascript /* @flow strict-local */ import React, { useCallback, useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { useSelector } from '../react-redux'; import type { UserOrBot } from '../types'; import styles, { createStyleSheet } from '../styles'; import GroupAvatar from '../common/GroupAvatar'; import ZulipText from '../common/ZulipText'; import Touchable from '../common/Touchable'; import UnreadCount from '../common/UnreadCount'; import { getMutedUsers } from '../selectors'; import { TranslationContext } from '../boot/TranslationProvider'; import { getFullNameOrMutedUserReactText, getFullNameOrMutedUserText, } from '../users/userSelectors'; import ZulipTextIntl from '../common/ZulipTextIntl'; import { getRealm } from '../directSelectors'; const componentStyles = createStyleSheet({ text: { flex: 1, marginLeft: 16, marginRight: 8, }, }); type Props<U> = $ReadOnly<{| users: U, unreadCount: number, onPress: (users: U) => void, |}>; /** * A list item describing one group PM conversation. * */ export default function GroupPmConversationItem<U: $ReadOnlyArray<UserOrBot>>( props: Props<U>, ): Node { const { users, unreadCount, onPress } = props; const handlePress = useCallback(() => { onPress(users); }, [onPress, users]); const _ = useContext(TranslationContext); const mutedUsers = useSelector(getMutedUsers); const enableGuestUserIndicator = useSelector(state => getRealm(state).enableGuestUserIndicator); const names = users.map(user => _(getFullNameOrMutedUserText({ user, mutedUsers, enableGuestUserIndicator })), ); const namesReact = []; users.forEach((user, i) => { if (i !== 0) { namesReact.push( <ZulipText key={`${user.user_id}-comma`} inheritColor inheritFontSize text=", " />, ); } namesReact.push( <ZulipTextIntl key={`${user.user_id}`} inheritColor inheritFontSize text={getFullNameOrMutedUserReactText({ user, mutedUsers, enableGuestUserIndicator })} />, ); }); return ( <Touchable onPress={handlePress}> <View style={styles.listItem}> <GroupAvatar size={48} names={names} /> <ZulipText style={componentStyles.text} numberOfLines={2} ellipsizeMode="tail"> {namesReact} </ZulipText> <UnreadCount count={unreadCount} /> </View> </Touchable> ); } ```
/content/code_sandbox/src/pm-conversations/GroupPmConversationItem.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
599
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import type { RouteProp } from '../react-navigation'; import type { MainTabsNavigationProp } from '../main/MainTabsScreen'; import { ThemeContext, createStyleSheet } from '../styles'; import { useSelector } from '../react-redux'; import ZulipTextIntl from '../common/ZulipTextIntl'; import ZulipButton from '../common/ZulipButton'; import LoadingBanner from '../common/LoadingBanner'; import { IconPeople, IconPerson } from '../common/Icons'; import PmConversationList from './PmConversationList'; import { getRecentConversations } from '../selectors'; import { OfflineNoticePlaceholder } from '../boot/OfflineNoticeProvider'; const styles = createStyleSheet({ container: { flex: 1, }, button: { margin: 8, flex: 1, }, emptySlate: { flex: 1, textAlign: 'center', textAlignVertical: 'center', fontSize: 20, }, row: { flexDirection: 'row', }, }); type Props = $ReadOnly<{| navigation: MainTabsNavigationProp<'pm-conversations'>, route: RouteProp<'pm-conversations', void>, |}>; /** * The "PMs" page in the main tabs navigation. * */ export default function PmConversationsScreen(props: Props): Node { const { navigation } = props; const conversations = useSelector(getRecentConversations); const context = useContext(ThemeContext); return ( <SafeAreaView mode="padding" edges={['top']} style={[styles.container, { backgroundColor: context.backgroundColor }]} > <OfflineNoticePlaceholder /> <View style={styles.row}> <ZulipButton secondary Icon={IconPerson} style={styles.button} text="New DM" onPress={() => { setTimeout(() => navigation.push('new-1to1-pm')); }} /> <ZulipButton secondary Icon={IconPeople} style={styles.button} text="New group DM" onPress={() => { setTimeout(() => navigation.push('new-group-pm')); }} /> </View> <LoadingBanner /> {conversations.length === 0 ? ( <ZulipTextIntl style={styles.emptySlate} text="No recent conversations" /> ) : ( <PmConversationList conversations={conversations} /> )} </SafeAreaView> ); } ```
/content/code_sandbox/src/pm-conversations/PmConversationsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
573
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import { usersOfKey, keyOfExactUsers, reducer } from '../pmConversationsModel'; import * as eg from '../../__tests__/lib/exampleData'; import { makeUserId } from '../../api/idTypes'; import { randString } from '../../utils/misc'; describe('usersOfKey', () => { for (const [desc, ids] of [ ['self-1:1', []], ['other 1:1 PM', [123]], ['group PM', [123, 345, 567]], ]) { test(desc, () => { expect(usersOfKey(keyOfExactUsers(ids.map(makeUserId)))).toEqual(ids); }); } }); describe('reducer', () => { const initialState = reducer(undefined, ({ type: randString() }: $FlowFixMe)); const someKey = keyOfExactUsers([eg.makeUser().user_id]); const someState = { map: Immutable.Map([[someKey, 123]]), sorted: Immutable.List([someKey]) }; test('RESET_ACCOUNT_DATA', () => { expect(reducer(someState, eg.action.reset_account_data)).toEqual(initialState); }); describe('REGISTER_COMPLETE', () => { test('no data (old server)', () => { /* eslint-disable-next-line no-unused-vars */ const { recent_private_conversations, ...rest } = eg.action.register_complete.data; expect(reducer(someState, { ...eg.action.register_complete, data: rest })).toEqual( initialState, ); }); test('works in normal case', () => { // Includes self-1:1, other 1:1, and group PM thread. // Out of order. const recent_private_conversations = [ { user_ids: [], max_message_id: 234 }, { user_ids: [makeUserId(1)], max_message_id: 123 }, { user_ids: [2, 1].map(makeUserId), max_message_id: 345 }, // user_ids out of order ]; const expected = { // prettier-ignore map: Immutable.Map([['', 234], ['1', 123], ['1,2', 345]]), sorted: Immutable.List(['1,2', '', '1']), }; expect( reducer(someState, eg.mkActionRegisterComplete({ recent_private_conversations })), ).toEqual(expected); }); }); describe('MESSAGE_FETCH_COMPLETE', () => { const [user1, user2] = [eg.makeUser({ user_id: 1 }), eg.makeUser({ user_id: 2 })]; const msg = (id, otherUsers) => eg.pmMessageFromTo(eg.selfUser, otherUsers, { id }); const action = messages => ({ ...eg.action.message_fetch_complete, messages }); test('works', () => { let state = initialState; state = reducer( state, action([msg(45, [user1]), msg(123, [user1, user2]), eg.streamMessage(), msg(234, [user1])]), ); expect(state).toEqual({ // prettier-ignore map: Immutable.Map([['1', 234], ['1,2', 123]]), sorted: Immutable.List(['1', '1,2']), }); const newState = reducer(state, action([eg.streamMessage()])); expect(newState).toBe(state); state = reducer( state, action([ msg(345, [user2]), msg(159, [user2]), msg(456, [user1, user2]), msg(102, [user1, user2]), ]), ); expect(state).toEqual({ // prettier-ignore map: Immutable.Map([['1', 234], ['1,2', 456], ['2', 345]]), sorted: Immutable.List(['1,2', '2', '1']), }); }); }); describe('EVENT_NEW_MESSAGE', () => { const actionGeneral = eg.mkActionEventNewMessage; const [user1, user2] = [eg.makeUser({ user_id: 1 }), eg.makeUser({ user_id: 2 })]; const action = (id, otherUsers) => actionGeneral(eg.pmMessageFromTo(eg.selfUser, otherUsers, { id })); // We'll start from here to test various updates. const baseState = (() => { let state = initialState; state = reducer(state, action(234, [user1])); state = reducer(state, action(123, [user1, user2])); return state; })(); test('(check base state)', () => { // This is here mostly for checked documentation of what's in // baseState, to help in reading the other test cases. expect(baseState).toEqual({ // prettier-ignore map: Immutable.Map([['1', 234], ['1,2', 123]]), sorted: Immutable.List(['1', '1,2']), }); }); test('stream message -> do nothing', () => { const state = reducer(baseState, actionGeneral(eg.streamMessage())); expect(state).toBe(baseState); }); test('new conversation, newest message', () => { const state = reducer(baseState, action(345, [user2])); expect(state).toEqual({ // prettier-ignore map: Immutable.Map([['1', 234], ['1,2', 123], ['2', 345]]), sorted: Immutable.List(['2', '1', '1,2']), }); }); test('new conversation, not newest message', () => { const state = reducer(baseState, action(159, [user2])); expect(state).toEqual({ // prettier-ignore map: Immutable.Map([['1', 234], ['1,2', 123], ['2', 159]]), sorted: Immutable.List(['1', '2', '1,2']), }); }); test('existing conversation, newest message', () => { const state = reducer(baseState, action(345, [user1, user2])); expect(state).toEqual({ // prettier-ignore map: Immutable.Map([['1', 234], ['1,2', 345]]), sorted: Immutable.List(['1,2', '1']), }); }); test('existing newest conversation, newest message', () => { const state = reducer(baseState, action(345, [user1])); expect(state).toEqual({ // prettier-ignore map: Immutable.Map([['1', 345], ['1,2', 123]]), sorted: Immutable.List(['1', '1,2']), }); expect(state.sorted).toBe(baseState.sorted); }); test('existing conversation, not newest in conversation', () => { const state = reducer(baseState, action(102, [user1, user2])); expect(state).toBe(baseState); }); }); }); ```
/content/code_sandbox/src/pm-conversations/__tests__/pmConversationsModel-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,520
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import invariant from 'invariant'; import { EVENT_NEW_MESSAGE, MESSAGE_FETCH_COMPLETE, REGISTER_COMPLETE, RESET_ACCOUNT_DATA, } from '../actionConstants'; import { makeUserId } from '../api/idTypes'; import type { PerAccountApplicableAction, PmMessage, PmOutbox, UserId } from '../types'; import { recipientsOfPrivateMessage } from '../utils/recipient'; import { ZulipVersion } from '../utils/zulipVersion'; /** The minimum server version to expect this data to be available. */ // Actually 2.1-dev-384-g4c3c669b41 according to our notes in src/api/; // but this is cleaner, and 2.1 is out long enough that few people, if any, // will be running a 2.1-dev version anymore (and nobody should be.) // TODO(server-2.1): Delete this and all code conditioned on older than it. export const MIN_RECENTPMS_SERVER_VERSION: ZulipVersion = new ZulipVersion('2.1'); // // // Keys. // /** The key identifying a PM conversation in this data structure. */ // User IDs, excluding self, sorted numerically, joined with commas. export opaque type PmConversationKey = string; /** * PRIVATE. Exported only for tests. * * Sorts `ids` in-place. */ // Input must have the exact right (multi-)set of users. Needn't be sorted. export function keyOfExactUsers(ids: UserId[]): PmConversationKey { return ids.sort((a, b) => a - b).join(','); } // Input may contain self or not, and needn't be sorted. function keyOfUsers(ids: $ReadOnlyArray<UserId>, ownUserId: UserId): PmConversationKey { return keyOfExactUsers(ids.filter(id => id !== ownUserId)); } function keyOfPrivateMessage(msg: PmMessage | PmOutbox, ownUserId: UserId): PmConversationKey { return keyOfUsers( recipientsOfPrivateMessage(msg).map(r => r.id), ownUserId, ); } /** The users in the conversation, other than self. */ export function usersOfKey(key: PmConversationKey): UserId[] { return key ? key.split(',').map(s => makeUserId(Number.parseInt(s, 10))) : []; } // // // State and reducer. // /** * The list of recent PM conversations, plus data to efficiently maintain it. * * This gets initialized from the `recent_private_conversations` data * structure in the `/register` response (aka our initial fetch), and then * kept up to date as we learn about new or newly-fetched messages. */ // (Compare the webapp's implementation, in static/js/pm_conversations.js.) export type PmConversationsState = $ReadOnly<{| // The latest message ID in each conversation. map: Immutable.Map<PmConversationKey, number>, // The keys of the map, sorted by latest message descending. sorted: Immutable.List<PmConversationKey>, |}>; const initialState: PmConversationsState = { map: Immutable.Map(), sorted: Immutable.List() }; // Insert the key at the proper place in the sorted list. // // Optimized, taking O(1) time, for the case where that place is the start, // because that's the common case for a new message. May take O(n) time in // general. function insertSorted(sorted, map, key, msgId) { const i = sorted.findIndex(k => { const id = map.get(k); invariant(id !== undefined, 'pm-conversations: key in sorted should be in map'); return id < msgId; }); // Immutable.List is a deque, with O(1) shift/unshift as well as push/pop. if (i === 0) { return sorted.unshift(key); } if (i < 0) { // (This case isn't common and isn't here to optimize, though it happens // to be fast; it's just that `sorted.insert(-1, key)` wouldn't work.) return sorted.push(key); } return sorted.insert(i, key); } // Insert the message into the state. // // Can take linear time in general. That sounds inefficient... // but it's what the webapp does, so must not be catastrophic. // (In fact the webapp calls `Array#sort`, which takes at *least* // linear time, and may be (N log N).) // // Optimized for the EVENT_NEW_MESSAGE case; for REGISTER_COMPLETE and // FETCH_MESSAGES_COMPLETE, if we find we want to optimize them, the first // thing we'll want to do is probably to batch the work and skip this // function. // // For EVENT_NEW_MESSAGE, the point of the event is that we're learning // about the message in real time immediately after it was sent -- so the // overwhelmingly common case is that the message is newer than any existing // message we know about. (*) That's therefore the case we optimize for, // particularly in the helper `insertSorted`. // // (*) The alternative is possible, but requires some kind of race to occur; // e.g., we get a FETCH_MESSAGES_COMPLETE that includes the just-sent // message 1002, and only after that get the event about message 1001, sent // moments earlier. The event queue always delivers events in order, so // even the race is possible only because we fetch messages outside of the // event queue. function insert( state: PmConversationsState, key: PmConversationKey, msgId: number, ): PmConversationsState { /* eslint-disable padded-blocks */ let { map, sorted } = state; const prev = map.get(key); // prettier-ignore if (prev === undefined) { // The conversation is new. Add to both `map` and `sorted`. map = map.set(key, msgId); return { map, sorted: insertSorted(sorted, map, key, msgId) }; } else if (prev >= msgId) { // The conversation already has a newer message. Do nothing. return state; } else { // The conversation needs to be (a) updated in `map`... map = map.set(key, msgId); // ... and (b) possibly moved around in `sorted` to keep the list sorted. const i = sorted.indexOf(key); invariant(i >= 0, 'pm-conversations: key in map should be in sorted'); if (i === 0) { // The conversation was already the latest, so no reordering needed. // (This is likely a common case in practice -- happens every time // the user gets several PMs in a row in the same thread -- so good to // optimize.) } else { // It wasn't the latest. Just handle the general case. sorted = sorted.delete(i); // linear time, ouch sorted = insertSorted(sorted, map, key, msgId); } return { map, sorted }; } } // Insert the message into the state. // // See `insert` for discussion of the time complexity. function insertMessage(state, message, ownUserId) { if (message.type !== 'private') { return state; } return insert(state, keyOfPrivateMessage(message, ownUserId), message.id); } export function reducer( state: PmConversationsState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): PmConversationsState { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: { // TODO optimize; this is quadratic (but so is the webapp's version?!) let st = initialState; for (const r of action.data.recent_private_conversations ?? []) { const key = keyOfExactUsers([...r.user_ids]); st = insert(st, key, r.max_message_id); } return st; } case MESSAGE_FETCH_COMPLETE: { // TODO optimize; this is quadratic (but so is the webapp's version?!) let st = state; for (const m of action.messages) { st = insertMessage(st, m, action.ownUserId); } return st; } case EVENT_NEW_MESSAGE: { const { message, ownUserId } = action; return insertMessage(state, message, ownUserId); } default: return state; } } ```
/content/code_sandbox/src/pm-conversations/pmConversationsModel.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,849
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import { getRecentConversations } from '../pmConversationsSelectors'; import { keyOfExactUsers } from '../pmConversationsModel'; import { ALL_PRIVATE_NARROW_STR } from '../../utils/narrow'; import * as eg from '../../__tests__/lib/exampleData'; import { ZulipVersion } from '../../utils/zulipVersion'; const keyForUsers = users => users .map(u => u.user_id) .sort((a, b) => a - b) .map(String) .join(','); describe('getRecentConversationsModern', () => { const accounts = [{ ...eg.selfAccount, zulipVersion: new ZulipVersion('2.1') }]; const recentsKeyForUsers = users => keyOfExactUsers(users.map(u => u.user_id)); test('does its job', () => { const state = eg.reduxState({ accounts, realm: eg.realmState({ user_id: eg.selfUser.user_id }), users: [eg.selfUser, eg.otherUser, eg.thirdUser], unread: { ...eg.baseReduxState.unread, pms: [ { sender_id: eg.selfUser.user_id, unread_message_ids: [4] }, { sender_id: eg.otherUser.user_id, unread_message_ids: [1, 3] }, ], huddles: [ { user_ids_string: keyForUsers([eg.selfUser, eg.otherUser, eg.thirdUser]), unread_message_ids: [2], }, ], }, pmConversations: { // prettier-ignore map: Immutable.Map([ [[], 4], [[eg.otherUser], 3], [[eg.otherUser, eg.thirdUser], 2], ].map(([k, v]) => [recentsKeyForUsers(k), v])), sorted: Immutable.List( [[], [eg.otherUser], [eg.otherUser, eg.thirdUser]].map(recentsKeyForUsers), ), }, }); expect(getRecentConversations(state)).toEqual([ { key: eg.selfUser.user_id.toString(), keyRecipients: [eg.selfUser], msgId: 4, unread: 1 }, { key: eg.otherUser.user_id.toString(), keyRecipients: [eg.otherUser], msgId: 3, unread: 2 }, { key: keyForUsers([eg.selfUser, eg.otherUser, eg.thirdUser]), keyRecipients: [eg.otherUser, eg.thirdUser].sort((a, b) => a.user_id - b.user_id), msgId: 2, unread: 1, }, ]); }); }); describe('getRecentConversationsLegacy', () => { const accounts = [{ ...eg.selfAccount, zulipVersion: new ZulipVersion('2.0') }]; const userJohn = eg.makeUser(); const userMark = eg.makeUser(); test('when no messages, return no conversations', () => { const state = eg.reduxState({ accounts, realm: eg.realmState({ user_id: eg.selfUser.user_id }), users: [eg.selfUser], narrows: Immutable.Map([[ALL_PRIVATE_NARROW_STR, []]]), unread: { ...eg.baseReduxState.unread, pms: [], huddles: [], }, }); const actual = getRecentConversations(state); expect(actual).toEqual([]); }); test('returns unique list of recipients, includes conversations with self', () => { const state = eg.reduxState({ accounts, realm: eg.realmState({ user_id: eg.selfUser.user_id }), users: [eg.selfUser, userJohn, userMark], narrows: Immutable.Map([[ALL_PRIVATE_NARROW_STR, [0, 1, 2, 3, 4]]]), messages: eg.makeMessagesState([ eg.pmMessageFromTo(userJohn, [eg.selfUser], { id: 1 }), eg.pmMessageFromTo(userMark, [eg.selfUser], { id: 2 }), eg.pmMessageFromTo(userJohn, [eg.selfUser], { id: 3 }), eg.pmMessageFromTo(eg.selfUser, [], { id: 4 }), eg.pmMessageFromTo(userJohn, [eg.selfUser, userMark], { id: 0 }), ]), unread: { ...eg.baseReduxState.unread, pms: [ { sender_id: eg.selfUser.user_id, unread_message_ids: [4] }, { sender_id: userJohn.user_id, unread_message_ids: [1, 3] }, { sender_id: userMark.user_id, unread_message_ids: [2] }, ], huddles: [ { user_ids_string: keyForUsers([eg.selfUser, userJohn, userMark]), unread_message_ids: [0], }, ], }, }); const expectedResult = [ { key: eg.selfUser.user_id.toString(), keyRecipients: [eg.selfUser], msgId: 4, unread: 1 }, { key: userJohn.user_id.toString(), keyRecipients: [userJohn], msgId: 3, unread: 2 }, { key: userMark.user_id.toString(), keyRecipients: [userMark], msgId: 2, unread: 1 }, { key: keyForUsers([eg.selfUser, userJohn, userMark]), keyRecipients: [userJohn, userMark].sort((a, b) => a.user_id - b.user_id), msgId: 0, unread: 1, }, ]; const actual = getRecentConversations(state); expect(actual).toMatchObject(expectedResult); }); test('returns recipients sorted by last activity', () => { const state = eg.reduxState({ accounts, realm: eg.realmState({ user_id: eg.selfUser.user_id }), users: [eg.selfUser, userJohn, userMark], narrows: Immutable.Map([[ALL_PRIVATE_NARROW_STR, [1, 2, 3, 4, 5, 6]]]), messages: eg.makeMessagesState([ eg.pmMessageFromTo(userJohn, [eg.selfUser], { id: 2 }), eg.pmMessageFromTo(userMark, [eg.selfUser], { id: 1 }), eg.pmMessageFromTo(userJohn, [eg.selfUser], { id: 4 }), eg.pmMessageFromTo(userMark, [eg.selfUser], { id: 3 }), eg.pmMessageFromTo(userMark, [eg.selfUser, userJohn], { id: 5 }), eg.pmMessageFromTo(eg.selfUser, [], { id: 6 }), ]), unread: { ...eg.baseReduxState.unread, pms: [ { sender_id: eg.selfUser.user_id, unread_message_ids: [6] }, { sender_id: userJohn.user_id, unread_message_ids: [2, 4] }, { sender_id: userMark.user_id, unread_message_ids: [1, 3] }, ], huddles: [ { user_ids_string: keyForUsers([eg.selfUser, userJohn, userMark]), unread_message_ids: [5], }, ], }, }); const expectedResult = [ { key: eg.selfUser.user_id.toString(), keyRecipients: [eg.selfUser], msgId: 6, unread: 1 }, { key: keyForUsers([eg.selfUser, userJohn, userMark]), keyRecipients: [userJohn, userMark].sort((a, b) => a.user_id - b.user_id), msgId: 5, unread: 1, }, { key: userJohn.user_id.toString(), keyRecipients: [userJohn], msgId: 4, unread: 2 }, { key: userMark.user_id.toString(), keyRecipients: [userMark], msgId: 3, unread: 2 }, ]; const actual = getRecentConversations(state); expect(actual).toEqual(expectedResult); }); }); ```
/content/code_sandbox/src/pm-conversations/__tests__/pmConversationsSelectors-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,780
```javascript /* @flow strict-local */ import invariant from 'invariant'; import { EVENT, REGISTER_COMPLETE, LOGIN_SUCCESS, ACCOUNT_SWITCH, ACK_PUSH_TOKEN, UNACK_PUSH_TOKEN, LOGOUT, DISMISS_SERVER_PUSH_SETUP_NOTICE, ACCOUNT_REMOVE, SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS, DISMISS_SERVER_NOTIFS_EXPIRING_BANNER, } from '../actionConstants'; import { EventTypes } from '../api/eventTypes'; import type { AccountsState, Identity, Action, Account } from '../types'; import { NULL_ARRAY } from '../nullObjects'; import { ZulipVersion } from '../utils/zulipVersion'; import { identityOfAccount, keyOfIdentity } from './accountMisc'; const initialState = NULL_ARRAY; const findAccount = (state: AccountsState, identity: Identity): number => { const { realm, email } = identity; return state.findIndex( account => account.realm.toString() === realm.toString() && account.email === email, ); }; function updateActiveAccount(state, change) { const activeAccount: Account | void = state[0]; invariant(activeAccount, 'accounts reducer: expected active account'); return [change(activeAccount), ...state.slice(1)]; } // eslint-disable-next-line default-param-last export default (state: AccountsState = initialState, action: Action): AccountsState => { switch (action.type) { case REGISTER_COMPLETE: // TODO(#5009): Before implementing a multi-account schema (#5006), // this will be the wrong account if the active account changed // while the register was in progress. After #5006, this per-account // action should naturally act on its own per-account state. return updateActiveAccount(state, current => ({ ...current, userId: action.data.user_id, zulipFeatureLevel: action.data.zulip_feature_level, zulipVersion: action.data.zulip_version, lastDismissedServerPushSetupNotice: action.data.realm_push_notifications_enabled ? null : current.lastDismissedServerPushSetupNotice, lastDismissedServerNotifsExpiringBanner: action.data.realm_push_notifications_enabled_end_timestamp == null ? null : current.lastDismissedServerNotifsExpiringBanner, })); case ACCOUNT_SWITCH: { const index = state.findIndex( a => keyOfIdentity(identityOfAccount(a)) === keyOfIdentity(action.identity), ); const account: Account | void = state[index]; invariant(account, 'accounts reducer (ACCOUNT_SWITCH): destination account not found'); return index === 0 ? state // no change; skip computation : [account, ...state.filter(a => a !== account)]; // put account first } case LOGIN_SUCCESS: { const { realm, email, apiKey } = action; const accountIndex = findAccount(state, { realm, email }); if (accountIndex === -1) { return [ { realm, email, apiKey, userId: null, ackedPushToken: null, zulipVersion: null, zulipFeatureLevel: null, lastDismissedServerPushSetupNotice: null, lastDismissedServerNotifsExpiringBanner: null, silenceServerPushSetupWarnings: false, }, ...state, ]; } return [ { ...state[accountIndex], apiKey, ackedPushToken: null }, ...state.slice(0, accountIndex), ...state.slice(accountIndex + 1), ]; } case ACK_PUSH_TOKEN: { const { pushToken: ackedPushToken, identity } = action; const accountIndex = findAccount(state, identity); if (accountIndex === -1) { return state; } return [ ...state.slice(0, accountIndex), { ...state[accountIndex], ackedPushToken }, ...state.slice(accountIndex + 1), ]; } case UNACK_PUSH_TOKEN: { const { identity } = action; const accountIndex = findAccount(state, identity); if (accountIndex === -1) { return state; } return [ ...state.slice(0, accountIndex), { ...state[accountIndex], ackedPushToken: null }, ...state.slice(accountIndex + 1), ]; } case LOGOUT: { // TODO: This will be the wrong account if the active account changed // between pressing "logout" and confirming with the confirmation // dialog. Fix, perhaps by having the LOGOUT action include an // Identity in its payload. return updateActiveAccount(state, current => ({ ...current, apiKey: '', ackedPushToken: null, })); } case DISMISS_SERVER_PUSH_SETUP_NOTICE: { return updateActiveAccount(state, current => ({ ...current, lastDismissedServerPushSetupNotice: action.date, })); } case DISMISS_SERVER_NOTIFS_EXPIRING_BANNER: { return updateActiveAccount(state, current => ({ ...current, lastDismissedServerNotifsExpiringBanner: action.date, })); } case SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS: { return updateActiveAccount(state, current => ({ ...current, silenceServerPushSetupWarnings: action.value, })); } case ACCOUNT_REMOVE: { const shouldRemove = a => keyOfIdentity(identityOfAccount(a)) === keyOfIdentity(action.identity); invariant(state.some(shouldRemove), 'accounts reducer (ACCOUNT_REMOVE): account not found'); return state.filter(a => !shouldRemove(a)); } case EVENT: { const { event } = action; switch (event.type) { case EventTypes.restart: { const { zulip_feature_level, zulip_version } = event; if (zulip_feature_level === undefined || zulip_version === undefined) { return state; } // TODO: Detect if the feature level has changed, indicating an upgrade; // if so, trigger a full refetch of server data. See #4793. return updateActiveAccount(state, current => ({ ...current, zulipVersion: new ZulipVersion(zulip_version), zulipFeatureLevel: zulip_feature_level, })); } case EventTypes.realm: { if (event.op === 'update_dict') { return updateActiveAccount(state, current => ({ ...current, lastDismissedServerPushSetupNotice: event.data.push_notifications_enabled === true ? null : current.lastDismissedServerPushSetupNotice, lastDismissedServerNotifsExpiringBanner: event.data.push_notifications_enabled_end_timestamp === null ? null : current.lastDismissedServerNotifsExpiringBanner, })); } // (We've converted any `op: 'update'` events to // `op: 'update_dict'` events near the edge.) return state; } default: return state; } } default: return state; } }; ```
/content/code_sandbox/src/account/accountsReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,532
```javascript /* @flow strict-local */ import * as NavigationService from '../nav/NavigationService'; import type { PerAccountAction, AllAccountsAction, GlobalThunkAction, Identity } from '../types'; import { ACCOUNT_SWITCH, ACCOUNT_REMOVE, LOGIN_SUCCESS, DISMISS_SERVER_PUSH_SETUP_NOTICE, SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS, DISMISS_SERVER_NOTIFS_EXPIRING_BANNER, } from '../actionConstants'; import { registerAndStartPolling } from '../events/eventActions'; import { resetToMainTabs } from '../nav/navActions'; import { sendOutbox } from '../outbox/outboxActions'; import { initNotifications } from '../notification/notifTokens'; import { resetAccountData } from './logoutActions'; export const dismissServerPushSetupNotice = (): PerAccountAction => ({ type: DISMISS_SERVER_PUSH_SETUP_NOTICE, // We don't compute this in a reducer function. Those should be pure // functions of their params: // path_to_url#rules-of-reducers date: new Date(), }); export const dismissServerNotifsExpiringBanner = (): PerAccountAction => ({ type: DISMISS_SERVER_NOTIFS_EXPIRING_BANNER, // We don't compute this in a reducer function. Those should be pure // functions of their params: // path_to_url#rules-of-reducers date: new Date(), }); export const setSilenceServerPushSetupWarnings = (value: boolean): PerAccountAction => ({ type: SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS, value, }); const accountSwitchPlain = (identity: Identity): AllAccountsAction => ({ type: ACCOUNT_SWITCH, identity, }); export const accountSwitch = (identity: Identity): GlobalThunkAction<Promise<void>> => async (dispatch, getState, { activeAccountDispatch }) => { NavigationService.dispatch(resetToMainTabs()); // Clear out the space we use for the active account's server data, to // make way for a new active account. // TODO(#5006): When each account has its own space to hold server data, // we won't have to do this. activeAccountDispatch(resetAccountData()); dispatch(accountSwitchPlain(identity)); // Now dispatch some actions on the new, post-switch active account. // Because we just dispatched `accountSwitchPlain`, that new account // is now the active account, so `activeAccountDispatch` will act on it. await activeAccountDispatch(registerAndStartPolling()); // TODO(#3881): Lots of issues with outbox sending activeAccountDispatch(sendOutbox()); activeAccountDispatch(initNotifications()); }; export const removeAccount = (identity: Identity): AllAccountsAction => ({ type: ACCOUNT_REMOVE, identity, }); const loginSuccessPlain = (realm: URL, email: string, apiKey: string): AllAccountsAction => ({ type: LOGIN_SUCCESS, realm, email, apiKey, }); export const loginSuccess = (realm: URL, email: string, apiKey: string): GlobalThunkAction<Promise<void>> => async (dispatch, getState, { activeAccountDispatch }) => { NavigationService.dispatch(resetToMainTabs()); // In case there's already an active account, clear out the space we use // for the active account's server data, to make way for a new active // account. // TODO(#5006): When each account has its own space to hold server data, // we won't have to do this. activeAccountDispatch(resetAccountData()); dispatch(loginSuccessPlain(realm, email, apiKey)); // Now dispatch some actions on the new, post-login active account. // Because we just dispatched `loginSuccessPlain`, that new account is // now the active account, so `activeAccountDispatch` will act on it. await activeAccountDispatch(registerAndStartPolling()); // TODO(#3881): Lots of issues with outbox sending activeAccountDispatch(sendOutbox()); activeAccountDispatch(initNotifications()); }; ```
/content/code_sandbox/src/account/accountActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
862
```javascript /* @flow strict-local */ import * as NavigationService from '../nav/NavigationService'; import type { PerAccountAction, AllAccountsAction, ThunkAction } from '../types'; import { LOGOUT, RESET_ACCOUNT_DATA } from '../actionConstants'; import { resetToAccountPicker } from '../nav/navActions'; /** * Reset per-account server data and some client-side data (drafts/outbox). */ // In this file just to prevent import cycles. export const resetAccountData = (): PerAccountAction => ({ type: RESET_ACCOUNT_DATA, }); const logoutPlain = (): AllAccountsAction => ({ type: LOGOUT, }); /** * Forget this user's API key and erase their content. */ // In its own file just to prevent import cycles. export const logout = (): ThunkAction<Promise<void>> => async (dispatch, getState) => { NavigationService.dispatch(resetToAccountPicker()); dispatch(resetAccountData()); dispatch(logoutPlain()); }; ```
/content/code_sandbox/src/account/logoutActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
201
```javascript /* @flow strict-local */ import React, { useContext, useCallback } from 'react'; import type { Node } from 'react'; import invariant from 'invariant'; import { fetchServerSettings } from '../message/fetchActions'; import { TranslationContext } from '../boot/TranslationProvider'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { useGlobalSelector, useGlobalDispatch } from '../react-redux'; import { getAccountsByIdentity, getGlobalSettings } from '../selectors'; import Centerer from '../common/Centerer'; import ZulipButton from '../common/ZulipButton'; import Logo from '../common/Logo'; import Screen from '../common/Screen'; import ViewPlaceholder from '../common/ViewPlaceholder'; import AccountList from './AccountList'; import { accountSwitch, removeAccount } from '../actions'; import { showConfirmationDialog, showErrorAlert } from '../utils/info'; import { tryStopNotifications } from '../notification/notifTokens'; import type { Identity } from '../types'; import { getAccounts } from '../directSelectors'; import { useNotificationReportsByIdentityKey } from '../settings/NotifTroubleshootingScreen'; import { keyOfIdentity } from './accountMisc'; import type { NotificationReport } from '../settings/NotifTroubleshootingScreen'; /** The data needed for each item in the list-of-accounts UI. */ export type AccountStatus = {| ...Identity, isLoggedIn: boolean, // The issue-report data from NotifTroubleshootingScreen has a convenient // list of problems that are likely to prevent notifications from working. // We'll use it to warn on each account item that has problems. +notificationReport: { +problems: NotificationReport['problems'], ... }, +silenceServerPushSetupWarnings: boolean, |}; /** * The data needed for the list of accounts in this UI. * * This serves as a view-model for the use of this component. */ function useAccountStatuses(): $ReadOnlyArray<AccountStatus> { const accounts = useGlobalSelector(getAccounts); const notificationReportsByIdentityKey = useNotificationReportsByIdentityKey(); return accounts.map(({ realm, email, apiKey, silenceServerPushSetupWarnings }) => { const notificationReport = notificationReportsByIdentityKey.get( keyOfIdentity({ realm, email }), ); invariant(notificationReport, 'AccountPickScreen: expected notificationReport for identity'); return { realm, email, isLoggedIn: apiKey !== '', notificationReport, silenceServerPushSetupWarnings, }; }); } type Props = $ReadOnly<{| navigation: AppNavigationProp<'account-pick'>, route: RouteProp<'account-pick', void>, |}>; export default function AccountPickScreen(props: Props): Node { const { navigation } = props; const accountStatuses = useAccountStatuses(); // In case we need to grab the API for an account (being careful while // doing so, of course). const accountsByIdentity = useGlobalSelector(getAccountsByIdentity); const globalSettings = useGlobalSelector(getGlobalSettings); const dispatch = useGlobalDispatch(); const _ = useContext(TranslationContext); const handleAccountSelect = useCallback( async accountStatus => { const { realm, email, isLoggedIn } = accountStatus; if (isLoggedIn) { dispatch(accountSwitch({ realm, email })); } else { const result = await fetchServerSettings(realm); if (result.type === 'error') { showErrorAlert( _(result.title), _(result.message), result.learnMoreButton && { url: result.learnMoreButton.url, text: result.learnMoreButton.text != null ? _(result.learnMoreButton.text) : undefined, globalSettings, }, ); return; } const serverSettings = result.value; navigation.push('auth', { serverSettings }); } }, [globalSettings, dispatch, navigation, _], ); const handleAccountRemove = useCallback( accountStatus => { const { realm, email, isLoggedIn } = accountStatus; const account = accountsByIdentity({ realm, email }); invariant(account, 'AccountPickScreen: should have account'); showConfirmationDialog({ destructive: true, title: 'Remove account', message: { text: 'This will make the mobile app on this device forget {email} on {realmUrl}.', values: { realmUrl: realm.toString(), email }, }, onPressConfirm: () => { if (isLoggedIn) { // Don't delay the removeAccount action by awaiting this // request: it may take a long time or never succeed, and the // user expects the account to be removed from the list // immediately. dispatch(tryStopNotifications(account)); } dispatch(removeAccount({ realm, email })); }, _, }); }, [accountsByIdentity, _, dispatch], ); return ( <Screen title="Pick account" centerContent padding canGoBack={navigation.canGoBack()} shouldShowLoadingBanner={false} > <Centerer> {accountStatuses.length === 0 && <Logo />} <AccountList accountStatuses={accountStatuses} onAccountSelect={handleAccountSelect} onAccountRemove={handleAccountRemove} /> <ViewPlaceholder height={16} /> <ZulipButton text="Add new account" onPress={() => { navigation.push('realm-input', { initial: undefined }); }} /> </Centerer> </Screen> ); } ```
/content/code_sandbox/src/account/AccountPickScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,199
```javascript /* @flow strict-local */ import { createSelector } from 'reselect'; import invariant from 'invariant'; import type { Account, Auth, PerAccountState, GlobalState, Identity, Selector, GlobalSelector, } from '../types'; import { dubPerAccountState, assumeSecretlyGlobalState } from '../reduxTypes'; import { getAccounts } from '../directSelectors'; import { identityOfAccount, keyOfIdentity, identityOfAuth, authOfAccount } from './accountMisc'; import { ZulipVersion } from '../utils/zulipVersion'; /** The list of known accounts, reduced to `Identity`. */ export const getIdentities: GlobalSelector<$ReadOnlyArray<Identity>> = createSelector( getAccounts, accounts => accounts.map(identityOfAccount), ); /** * All known accounts, indexed by identity. */ export const getAccountsByIdentity: GlobalSelector<(Identity) => Account | void> = createSelector( getAccounts, accounts => { const map = new Map( accounts.map(account => [keyOfIdentity(identityOfAccount(account)), account]), ); return identity => map.get(keyOfIdentity(identity)); }, ); /** * The per-account state for the active account; undefined if no such account. * * I.e., for the account currently foregrounded in the UI. See glossary: * path_to_url * * In our legacy model where the global state is all about the active * account (pre-#5006), this is a lot like the identity function. Use this * function where even in a multi-account post-#5006 model, the input will * be the global state. * * In particular, always use this function (rather than simply casting) in * early startup, onboarding, account-switch, or other times where there may * be no active account. */ export const tryGetActiveAccountState = (state: GlobalState): PerAccountState | void => { const accounts = getAccounts(state); // TODO(#5006): This is the inverse of where getAccount uses the same // assumption that the two state types are really the same objects. return accounts && accounts.length > 0 ? dubPerAccountState(state) : undefined; }; /** * The `Account` object for this account. * * "This account" meaning the one this per-account state corresponds to. */ export const getAccount = (state: PerAccountState): Account => { // TODO(#5006): This is the key place we assume a PerAccountState is // secretly a GlobalState. We'll put the active `Account` somewhere // better and then fix that. // We're also assuming that the intended account is the active one. const globalState = assumeSecretlyGlobalState(state); const accounts = globalState.accounts; invariant(accounts.length > 0, 'getAccount: must have account'); return accounts[0]; }; /** * Whether the given identity matches the active account. * * Gives false if there is no active account. */ export const getIsActiveAccount = (state: GlobalState, identity: Identity): boolean => { const maybeActiveAccountState = tryGetActiveAccountState(state); if (!maybeActiveAccountState) { // There is no active account for `identity` to match. return false; } return ( keyOfIdentity(identityOfAccount(getAccount(maybeActiveAccountState))) === keyOfIdentity(identity) ); }; /** The realm URL for this account. */ export const getRealmUrl = (state: PerAccountState): URL => getAccount(state).realm; /** * The Zulip server version for this account. * * Prefer `getZulipFeatureLevel`, which is finer-grained, for most uses. * This function is useful for logging, for user-facing information, and for * old releases (pre-3.0) where the feature level is always 0. * * This function assumes we have server data for this account, and if not it * may throw. If you want to call it from a context where we may not have * server data, we can fix that; see implementation comment. * * If using this to condition behavior where we make a request to the * server, note that there's fundamentally a race; for details, see * `getZulipFeatureLevel`. */ export const getServerVersion = (state: PerAccountState): ZulipVersion => { const { zulipVersion } = getAccount(state); // This invariant will hold as long as we only call this function in a // context where we have server data. // // TODO(#5006): In a multi-account schema, we'll have PerAccountState for // accounts that aren't the active one, which might include some that lack // this data. Then we might start calling this function in the path for // talking to those servers, which currently would cause an exception. // // At that point probably just have a migration drop those Account // records -- they mean accounts the user hasn't talked to since // 1e17f6695, from 2020-05. // // Oh, and there's one other case where an Account record will lack this // data: immediately after login, before we complete the first initial // fetch. That's fixable, though: we already have the version from // server_settings when we enter the login flow, so we just need to // remember that value and stick it in the initial Account record. invariant(zulipVersion, 'zulipVersion must be non-null'); return zulipVersion; }; /** * The Zulip server feature level for this account. * * This function assumes we have server data for this account, and if not it * may throw. If you want to call it from a context where we may not have * server data, we can fix that; see implementation comment. * * If using this to condition behavior where we make a request to the * server, note that there's fundamentally a race: the server may have been * upgraded since we last heard from it. Generally we don't worry about * this because (a) usually our behavior for old servers is fine for new * servers (by design in the new server, because it's the same behavior old * clients will have), and then this can only be a problem on downgrade, * which is rare; (b) with the exception of initial fetch, almost all our * requests come while we already have a live event queue which would tell * us about an upgrade, so the race is quite narrow. */ export const getZulipFeatureLevel = (state: PerAccountState): number => { const { zulipFeatureLevel } = getAccount(state); // This invariant will hold as long as we only call this function in a // context where we have server data. // // TODO(#5006): Much like getServerVersion above. This property is just a // bit newer: b058fa266, from 2020-09. invariant(zulipFeatureLevel !== null, 'zulipFeatureLevel must be non-null in PerAccountState'); return zulipFeatureLevel; }; export const getSilenceServerPushSetupWarnings = (state: PerAccountState): boolean => getAccount(state).silenceServerPushSetupWarnings; /** * The auth object for this account, if logged in; else undefined. * * The account is "logged in" if we have an API key for it. * * This is for use in early startup, onboarding, account-switch, * authentication flows, or other times where the given account may not be * logged in. * * See: * * `getAuth` for use in the bulk of the app, operating on a logged-in * account. */ export const tryGetAuth: Selector<Auth | void> = createSelector(getAccount, account => { if (account.apiKey === '') { return undefined; } return authOfAccount(account); }); /** * True just if there is an active, logged-in account. * * See: * * `tryGetActiveAccountState` for the meaning of "active". * * `tryGetAuth` for the meaning of "logged in". */ export const getHasAuth = (globalState: GlobalState): boolean => { const state = tryGetActiveAccountState(globalState); return !!state && !!tryGetAuth(state); }; /** * The auth object for this account, if logged in; else throws. * * For use in all the normal-use screens and codepaths of the app, which * assume the specified account is logged in. * * See: * * `tryGetAuth` for the meaning of "logged in". * * `tryGetAuth` again, for use where the account might not be logged in. */ export const getAuth = (state: PerAccountState): Auth => { const auth = tryGetAuth(state); if (auth === undefined) { throw new Error('Active account not logged in'); } return auth; }; /** * The identity for this account, if logged in; throws if not logged in. * * See `getAuth` and `tryGetAuth` for discussion. */ // TODO why should this care if the account is logged in? export const getIdentity: Selector<Identity> = createSelector(getAuth, auth => identityOfAuth(auth), ); ```
/content/code_sandbox/src/account/accountsSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,046
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View, FlatList } from 'react-native'; import ViewPlaceholder from '../common/ViewPlaceholder'; import AccountItem from './AccountItem'; import type { AccountStatus } from './AccountPickScreen'; type Props = $ReadOnly<{| accountStatuses: $ReadOnlyArray<AccountStatus>, onAccountSelect: AccountStatus => Promise<void> | void, onAccountRemove: AccountStatus => Promise<void> | void, |}>; export default function AccountList(props: Props): Node { const { accountStatuses, onAccountSelect, onAccountRemove } = props; return ( <View> <FlatList data={accountStatuses} keyExtractor={item => `${item.email}${item.realm.toString()}`} ItemSeparatorComponent={() => <ViewPlaceholder height={8} />} renderItem={({ item, index }) => ( <AccountItem account={item} onSelect={onAccountSelect} onRemove={onAccountRemove} /> )} /> </View> ); } ```
/content/code_sandbox/src/account/AccountList.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
232
```javascript /* @flow strict-local */ import type { Account, Auth, Identity } from '../types'; const identitySlice = ({ realm, email }): Identity => ({ realm, email }); export const identityOfAuth: Auth => Identity = identitySlice; export const identityOfAccount: ($ReadOnly<{ ...Identity, ... }>) => Identity = identitySlice; /** A string corresponding uniquely to an identity, for use in `Map`s. */ export const keyOfIdentity = ({ realm, email }: Identity): string => `${realm.toString()}\0${email}`; export const authOfAccount = (account: Account): Auth => { const { realm, email, apiKey } = account; return { realm, email, apiKey }; }; ```
/content/code_sandbox/src/account/accountMisc.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
148
```javascript import deepFreeze from 'deep-freeze'; import { getAuth } from '../accountsSelectors'; describe('getAuth', () => { test('throws when no accounts', () => { const state = deepFreeze({ accounts: [], }); expect(() => { getAuth(state); }).toThrow(); }); test('throws when no API key', () => { const state = deepFreeze({ accounts: [ { apiKey: '', realm: 'path_to_url }, { apiKey: 'asdf', realm: 'path_to_url }, ], }); expect(() => { getAuth(state); }).toThrow(); }); test('returns the auth information from the first account, if valid', () => { const state = deepFreeze({ accounts: [ { apiKey: 'asdf', realm: 'path_to_url }, { apiKey: 'aoeu', realm: 'path_to_url }, ], }); expect(getAuth(state)).toEqual({ realm: 'path_to_url apiKey: 'asdf', }); }); }); ```
/content/code_sandbox/src/account/__tests__/accountsSelectors-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
230
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Alert, Pressable, View } from 'react-native'; // $FlowFixMe[untyped-import] import Color from 'color'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import ZulipText from '../common/ZulipText'; import Touchable from '../common/Touchable'; import ZulipTextIntl from '../common/ZulipTextIntl'; import { IconAlertTriangle, IconDone, IconTrash } from '../common/Icons'; import { useGlobalDispatch, useGlobalSelector } from '../react-redux'; import { getIsActiveAccount, tryGetActiveAccountState } from './accountsSelectors'; import type { AccountStatus } from './AccountPickScreen'; import { kWarningColor } from '../styles/constants'; import { TranslationContext } from '../boot/TranslationProvider'; import { accountSwitch } from './accountActions'; import { useNavigation } from '../react-navigation'; import { chooseNotifProblemForShortText, kPushNotificationsEnabledEndDoc, notifProblemShortText, pushNotificationsEnabledEndTimestampWarning, } from '../settings/NotifTroubleshootingScreen'; import { getGlobalSettings, getRealmName } from '../directSelectors'; import { getHaveServerData } from '../haveServerDataSelectors'; import { useDateRefreshedAtInterval } from '../reactUtils'; import { openLinkWithUserPreference } from '../utils/openLink'; import * as logging from '../utils/logging'; const styles = createStyleSheet({ wrapper: { justifyContent: 'space-between', }, accountItem: { padding: 16, flexDirection: 'row', alignItems: 'center', borderRadius: 4, }, selectedAccountItem: { borderColor: BRAND_COLOR, borderWidth: 1, }, details: { flex: 1, }, text: { fontWeight: 'bold', marginVertical: 2, }, icon: { marginLeft: 24, }, signedOutText: { fontStyle: 'italic', color: 'gray', marginVertical: 2, }, }); type Props = $ReadOnly<{| account: AccountStatus, onSelect: AccountStatus => Promise<void> | void, onRemove: AccountStatus => Promise<void> | void, |}>; export default function AccountItem(props: Props): Node { const { email, realm, isLoggedIn, notificationReport, silenceServerPushSetupWarnings } = props.account; const _ = React.useContext(TranslationContext); const navigation = useNavigation(); const dispatch = useGlobalDispatch(); const globalSettings = useGlobalSelector(getGlobalSettings); const isActiveAccount = useGlobalSelector(state => getIsActiveAccount(state, { email, realm })); // Don't show the "remove account" button (the "trash" icon) for the // active account when it's logged in. This prevents removing it when the // main app UI, relying on that account's data, may be on the nav stack. // See `getHaveServerData`. const showDoneIcon = isActiveAccount && isLoggedIn; const backgroundItemColor = isLoggedIn ? 'hsla(177, 70%, 47%, 0.1)' : 'hsla(0,0%,50%,0.1)'; const textColor = isLoggedIn ? BRAND_COLOR : 'gray'; const dateNow = useDateRefreshedAtInterval(60_000); const activeAccountState = useGlobalSelector(tryGetActiveAccountState); // The fallback text '(unknown organization name)' is never expected to // appear in the UI. As of writing, notifProblemShortText doesn't use its // realmName param except for a NotificationProblem which we only select // when we have server data for the relevant account. When we have that, // `realmName` will be the real realm name, not the fallback. // TODO(#5005) look for server data even when this item's account is not // the active one. let realmName = '(unknown organization name)'; let expiryWarning = null; if (isActiveAccount && activeAccountState != null && getHaveServerData(activeAccountState)) { realmName = getRealmName(activeAccountState); expiryWarning = silenceServerPushSetupWarnings ? null : pushNotificationsEnabledEndTimestampWarning(activeAccountState, dateNow); } const singleNotifProblem = chooseNotifProblemForShortText({ report: notificationReport, ignoreServerHasNotEnabled: silenceServerPushSetupWarnings, }); const handlePressNotificationWarning = React.useCallback(() => { if (expiryWarning == null && singleNotifProblem == null) { logging.warn('AccountItem: Notification warning pressed with nothing to show'); return; } if (singleNotifProblem != null) { Alert.alert( _('Notifications'), _(notifProblemShortText(singleNotifProblem, realmName)), [ { text: _('Cancel'), style: 'cancel' }, { text: _('Details'), onPress: () => { dispatch(accountSwitch({ realm, email })); navigation.push('notifications'); }, style: 'default', }, ], { cancelable: true }, ); return; } if (expiryWarning != null) { Alert.alert( _('Notifications'), _(expiryWarning.text), [ { text: _('Cancel'), style: 'cancel' }, { text: _('Details'), onPress: () => { openLinkWithUserPreference(kPushNotificationsEnabledEndDoc, globalSettings); }, style: 'default', }, ], { cancelable: true }, ); } }, [ email, singleNotifProblem, expiryWarning, realm, realmName, globalSettings, navigation, dispatch, _, ]); return ( <Touchable style={styles.wrapper} onPress={() => props.onSelect(props.account)}> <View style={[ styles.accountItem, showDoneIcon && styles.selectedAccountItem, { backgroundColor: backgroundItemColor }, ]} > <View style={styles.details}> <ZulipText style={[styles.text, { color: textColor }]} text={email} numberOfLines={1} /> <ZulipText style={[styles.text, { color: textColor }]} text={realm.toString()} numberOfLines={1} /> {!isLoggedIn && ( <ZulipTextIntl style={styles.signedOutText} text="Signed out" numberOfLines={1} /> )} </View> {(singleNotifProblem != null || expiryWarning != null) && ( <Pressable style={styles.icon} hitSlop={12} onPress={handlePressNotificationWarning}> {({ pressed }) => ( <IconAlertTriangle size={24} color={pressed ? Color(kWarningColor).fade(0.5).toString() : kWarningColor} /> )} </Pressable> )} {!showDoneIcon ? ( <Pressable style={styles.icon} hitSlop={12} onPress={() => props.onRemove(props.account)}> {({ pressed }) => ( <IconTrash size={24} color={pressed ? Color('crimson').fade(0.5).toString() : 'crimson'} /> )} </Pressable> ) : ( <IconDone style={styles.icon} size={24} color={BRAND_COLOR} /> )} </View> </Touchable> ); } ```
/content/code_sandbox/src/account/AccountItem.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,630
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import { ACCOUNT_SWITCH, LOGIN_SUCCESS, LOGOUT, ACCOUNT_REMOVE, EVENT, } from '../../actionConstants'; import { randString } from '../../utils/misc'; import accountsReducer from '../accountsReducer'; import { ZulipVersion } from '../../utils/zulipVersion'; import * as eg from '../../__tests__/lib/exampleData'; import { identityOfAccount } from '../accountMisc'; import { EventTypes } from '../../api/eventTypes'; import type { RealmUpdateDictEvent } from '../../api/eventTypes'; describe('accountsReducer', () => { describe('REGISTER_COMPLETE', () => { const account1 = eg.selfAccount; const account2 = eg.makeAccount(); const account3 = eg.makeAccount(); test('records zulipVersion on active account', () => { const newZulipVersion = new ZulipVersion('2.0.0'); expect( accountsReducer( deepFreeze([account1, account2, account3]), eg.mkActionRegisterComplete({ zulip_version: newZulipVersion }), ), ).toEqual([{ ...account1, zulipVersion: newZulipVersion }, account2, account3]); }); test('records userId on active account', () => { const newUserId = eg.makeUser().user_id; expect( accountsReducer( deepFreeze([account1, account2, account3]), eg.mkActionRegisterComplete({ user_id: newUserId }), ), ).toEqual([{ ...account1, userId: newUserId }, account2, account3]); }); test('records zulipFeatureLevel on active account', () => { const newZulipFeatureLevel = 6; expect( accountsReducer( deepFreeze([account1, account2, account3]), eg.mkActionRegisterComplete({ zulip_feature_level: newZulipFeatureLevel, }), ), ).toEqual([{ ...account1, zulipFeatureLevel: newZulipFeatureLevel }, account2, account3]); }); test('when realm_push_notifications_enabled: true, clears lastDismissedServerPushSetupNotice', () => { const account = { ...eg.selfAccount, lastDismissedServerPushSetupNotice: new Date() }; const actualState = accountsReducer( [account], eg.mkActionRegisterComplete({ realm_push_notifications_enabled: true }), ); expect(actualState).toEqual([{ ...account, lastDismissedServerPushSetupNotice: null }]); }); test('when realm_push_notifications_enabled: false, preserves lastDismissedServerPushSetupNotice', () => { const account = { ...eg.selfAccount, lastDismissedServerPushSetupNotice: new Date() }; const actualState = accountsReducer( [account], eg.mkActionRegisterComplete({ realm_push_notifications_enabled: false }), ); expect(actualState).toEqual([account]); }); test('when realm_push_notifications_enabled_end_timestamp is null, clears lastDismissedServerNotifsExpiringBanner', () => { const account = { ...eg.selfAccount, lastDismissedServerNotifsExpiringBanner: new Date() }; const actualState = accountsReducer( [account], eg.mkActionRegisterComplete({ realm_push_notifications_enabled_end_timestamp: null }), ); expect(actualState).toEqual([{ ...account, lastDismissedServerNotifsExpiringBanner: null }]); }); test('when realm_push_notifications_enabled_end_timestamp is not null, preserves lastDismissedServerNotifsExpiringBanner', () => { const account = { ...eg.selfAccount, lastDismissedServerNotifsExpiringBanner: new Date() }; const actualState = accountsReducer( [account], eg.mkActionRegisterComplete({ realm_push_notifications_enabled_end_timestamp: 1705616035 }), ); expect(actualState).toEqual([account]); }); // TODO(server-8.0) test('legacy: when realm_push_notifications_enabled_end_timestamp missing, preserves lastDismissedServerNotifsExpiringBanner: null', () => { const account = { ...eg.selfAccount, lastDismissedServerNotifsExpiringBanner: null }; const actualState = accountsReducer([account], eg.mkActionRegisterComplete({})); expect(actualState).toEqual([account]); }); }); describe('ACCOUNT_SWITCH', () => { const account1 = eg.makeAccount(); const account2 = eg.makeAccount(); const account3 = eg.makeAccount(); test('switching to first account does not change state', () => { const prevState = deepFreeze([account1, account2, account3]); const action = deepFreeze({ type: ACCOUNT_SWITCH, identity: identityOfAccount(account1), }); const newState = accountsReducer(prevState, action); expect(newState).toBe(prevState); }); test('switching to an account moves the account to be first in the list', () => { const prevState = deepFreeze([account1, account2, account3]); const action = deepFreeze({ type: ACCOUNT_SWITCH, identity: identityOfAccount(account2), }); const expectedState = [account2, account1, account3]; const newState = accountsReducer(prevState, action); expect(newState).toEqual(expectedState); }); }); describe('LOGIN_SUCCESS', () => { const account1 = eg.makeAccount({ realm: new URL('path_to_url ackedPushToken: randString(), }); const account2 = eg.makeAccount({ realm: new URL('path_to_url ackedPushToken: randString(), }); const prevState = deepFreeze([account1, account2]); test('on login, if account does not exist, add as first item, with null userId, zulipVersion, zulipFeatureLevel', () => { const newApiKey = randString(); const newEmail = 'newaccount@example.com'; const newRealm = new URL('path_to_url const action = deepFreeze({ type: LOGIN_SUCCESS, apiKey: newApiKey, email: newEmail, realm: newRealm, }); const expectedState = [ eg.makeAccount({ realm: newRealm, email: newEmail, apiKey: newApiKey, userId: null, zulipVersion: null, zulipFeatureLevel: null, }), account1, account2, ]; const newState = accountsReducer(prevState, action); expect(newState).toEqual(expectedState); }); test("on login, if account does exist, move to top, update with apiKey, set ackedPushToken to null, don't clobber anything else", () => { const newApiKey = randString(); const action = deepFreeze({ type: LOGIN_SUCCESS, apiKey: newApiKey, realm: account2.realm, email: account2.email, }); const expectedState = [{ ...account2, apiKey: newApiKey, ackedPushToken: null }, account1]; const newState = accountsReducer(prevState, action); expect(newState).toEqual(expectedState); }); }); describe('LOGOUT', () => { test('on logout, clear just apiKey and ackedPushToken from active account', () => { const account1 = eg.makeAccount({ ackedPushToken: '123' }); const account2 = eg.makeAccount(); const prevState = deepFreeze([account1, account2]); const action = deepFreeze({ type: LOGOUT }); const expectedState = [{ ...account1, apiKey: '', ackedPushToken: null }, account2]; const newState = accountsReducer(prevState, action); expect(newState).toEqual(expectedState); }); }); describe('ACCOUNT_REMOVE', () => { test('deletes selected account but keeps the rest', () => { const account1 = eg.makeAccount(); const account2 = eg.makeAccount(); expect( accountsReducer( deepFreeze([account1, account2]), deepFreeze({ type: ACCOUNT_REMOVE, identity: identityOfAccount(account1) }), ), ).toEqual([account2]); }); }); describe('EventTypes.restart', () => { test('when server version/feature level are present, update active account', () => { const prevState = eg.plusReduxState.accounts; const [prevActiveAccount, ...prevRestOfAccounts] = prevState; expect( accountsReducer(prevState, { type: EVENT, event: { id: 1, type: 'restart', server_generation: 2, immediate: true, zulip_version: '4.0-dev-3932-g3df2dbfd0d', zulip_feature_level: 58, }, }), ).toEqual([ { ...prevActiveAccount, zulipVersion: new ZulipVersion('4.0-dev-3932-g3df2dbfd0d'), zulipFeatureLevel: 58, }, ...prevRestOfAccounts, ]); }); test("when server version/feature level are not present, don't update active account", () => { const prevState = eg.plusReduxState.accounts; expect( accountsReducer(prevState, { type: EVENT, event: { id: 1, type: 'restart', server_generation: 2, immediate: true, }, }), ).toEqual(prevState); }); }); describe('EventTypes.realm, op update_dict', () => { const eventWith = (data: RealmUpdateDictEvent['data']) => ({ type: EVENT, event: { id: 0, type: EventTypes.realm, op: 'update_dict', property: 'default', data }, }); describe('lastDismissedServerPushSetupNotice', () => { const stateWithDismissedNotice = [ { ...eg.plusReduxState.accounts[0], lastDismissedServerPushSetupNotice: new Date() }, ]; const stateWithoutDismissedNotice = [ { ...eg.plusReduxState.accounts[0], lastDismissedServerPushSetupNotice: null }, ]; test('data.push_notifications_enabled is true, on state with dismissed notice', () => { const actualState = accountsReducer( stateWithDismissedNotice, eventWith({ push_notifications_enabled: true }), ); expect(actualState).toEqual(stateWithoutDismissedNotice); }); test('data.push_notifications_enabled is true, on state without dismissed notice', () => { const actualState = accountsReducer( stateWithoutDismissedNotice, eventWith({ push_notifications_enabled: true }), ); expect(actualState).toEqual(stateWithoutDismissedNotice); }); test('data.push_notifications_enabled is false, on state with dismissed notice', () => { const actualState = accountsReducer( stateWithDismissedNotice, eventWith({ push_notifications_enabled: false }), ); expect(actualState).toEqual(stateWithDismissedNotice); }); test('data.push_notifications_enabled is false, on state without dismissed notice', () => { const actualState = accountsReducer( stateWithoutDismissedNotice, eventWith({ push_notifications_enabled: false }), ); expect(actualState).toEqual(stateWithoutDismissedNotice); }); test('data.push_notifications_enabled is absent, on state with dismissed notice', () => { const actualState = accountsReducer(stateWithDismissedNotice, eventWith({})); expect(actualState).toEqual(stateWithDismissedNotice); }); test('data.push_notifications_enabled is absent, on state without dismissed notice', () => { const actualState = accountsReducer(stateWithoutDismissedNotice, eventWith({})); expect(actualState).toEqual(stateWithoutDismissedNotice); }); }); describe('lastDismissedServerNotifsExpiringBanner', () => { const stateWithDismissedBanner = [ { ...eg.plusReduxState.accounts[0], lastDismissedServerNotifsExpiringBanner: new Date() }, ]; const stateWithoutDismissedBanner = [ { ...eg.plusReduxState.accounts[0], lastDismissedServerNotifsExpiringBanner: null }, ]; const someTimestamp = 1705616035; test('data.push_notifications_enabled_end_timestamp is null, on state with dismissed banner', () => { const actualState = accountsReducer( stateWithDismissedBanner, eventWith({ push_notifications_enabled_end_timestamp: null }), ); expect(actualState).toEqual(stateWithoutDismissedBanner); }); test('data.push_notifications_enabled_end_timestamp is null, on state without dismissed banner', () => { const actualState = accountsReducer( stateWithoutDismissedBanner, eventWith({ push_notifications_enabled_end_timestamp: null }), ); expect(actualState).toEqual(stateWithoutDismissedBanner); }); test('data.push_notifications_enabled_end_timestamp is non-null, on state with dismissed banner', () => { const actualState = accountsReducer( stateWithDismissedBanner, eventWith({ push_notifications_enabled_end_timestamp: someTimestamp }), ); expect(actualState).toEqual(stateWithDismissedBanner); }); test('data.push_notifications_enabled_end_timestamp is non-null, on state without dismissed banner', () => { const actualState = accountsReducer( stateWithoutDismissedBanner, eventWith({ push_notifications_enabled_end_timestamp: someTimestamp }), ); expect(actualState).toEqual(stateWithoutDismissedBanner); }); test('data.push_notifications_enabled_end_timestamp is absent, on state with dismissed banner', () => { const actualState = accountsReducer(stateWithDismissedBanner, eventWith({})); expect(actualState).toEqual(stateWithDismissedBanner); }); test('data.push_notifications_enabled_end_timestamp is absent, on state without dismissed banner', () => { const actualState = accountsReducer(stateWithoutDismissedBanner, eventWith({})); expect(actualState).toEqual(stateWithoutDismissedBanner); }); }); }); }); ```
/content/code_sandbox/src/account/__tests__/accountsReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,004
```javascript // @flow strict-local import deepFreeze from 'deep-freeze'; import * as resolved_topic from '@zulip/shared/lib/resolved_topic'; import { HOME_NARROW } from '../../utils/narrow'; import * as eg from '../../__tests__/lib/exampleData'; import { constructMessageActionButtons, constructTopicActionButtons, constructStreamActionButtons, } from '../index'; import { makeUnreadState } from '../../unread/__tests__/unread-testlib'; import { makeMuteState } from '../../mute/__tests__/mute-testlib'; import { Role } from '../../api/permissionsTypes'; import { UserTopicVisibilityPolicy } from '../../api/modelTypes'; const buttonTitles = buttons => buttons.map(button => button.title); describe('constructStreamActionButtons', () => { const streamId = eg.stream.stream_id; const titles = backgroundData => buttonTitles(constructStreamActionButtons({ backgroundData, streamId })); // TODO: test constructStreamActionButtons for mute/unmute // TODO: test constructStreamActionButtons for copyLinkToStream test('show pinToTop', () => { const subscriptions = new Map([ [eg.stream.stream_id, eg.makeSubscription({ pin_to_top: false })], ]); expect(titles({ ...eg.plusBackgroundData, subscriptions })).toContain('Pin to top'); }); test('show unpinFromTop', () => { const subscriptions = new Map([ [eg.stream.stream_id, eg.makeSubscription({ pin_to_top: true })], ]); expect(titles({ ...eg.plusBackgroundData, subscriptions })).toContain('Unpin from top'); }); test('show enableNotifications', () => { const subscriptions = new Map([ [eg.stream.stream_id, eg.makeSubscription({ push_notifications: false })], ]); expect(titles({ ...eg.plusBackgroundData, subscriptions })).toContain('Enable notifications'); }); test('show disableNotifications', () => { const subscriptions = new Map([ [eg.stream.stream_id, eg.makeSubscription({ push_notifications: true })], ]); expect(titles({ ...eg.plusBackgroundData, subscriptions })).toContain('Disable notifications'); }); test('show subscribe', () => { expect(titles({ ...eg.plusBackgroundData, subscriptions: new Map() })).toContain('Subscribe'); }); test('show unsubscribe', () => { expect(titles({ ...eg.plusBackgroundData })).toContain('Unsubscribe'); }); // TODO: test constructStreamActionButtons for showStreamSettings }); describe('constructTopicActionButtons', () => { const streamMessage = eg.streamMessage(); const topic = streamMessage.subject; const streamId = eg.stream.stream_id; const titles = (backgroundData, topic_) => buttonTitles(constructTopicActionButtons({ backgroundData, streamId, topic: topic_ ?? topic })); test('show markTopicAsRead', () => { const unread = makeUnreadState(eg.plusReduxState, [streamMessage]); expect(titles({ ...eg.plusBackgroundData, unread })).toContain('Mark topic as read'); }); test('hide markTopicAsRead', () => { const unread = makeUnreadState(eg.plusReduxState, []); expect(titles({ ...eg.plusBackgroundData, unread })).not.toContain('Mark topic as read'); }); test('show unmuteTopic', () => { const mute = makeMuteState([[eg.stream, topic]]); expect(titles({ ...eg.plusBackgroundData, mute })).toContain('Unmute topic'); }); test('show muteTopic', () => { const mute = makeMuteState([]); expect(titles({ ...eg.plusBackgroundData, mute })).toContain('Mute topic'); }); test('show muteTopic on followed topic', () => { const mute = makeMuteState([[eg.stream, topic, UserTopicVisibilityPolicy.Followed]]); expect(titles({ ...eg.plusBackgroundData, mute })).toContain('Mute topic'); }); test('show followTopic on muted topic', () => { const mute = makeMuteState([[eg.stream, topic]]); expect(titles({ ...eg.plusBackgroundData, mute })).toContain('Follow topic'); }); test('show followTopic', () => { const mute = makeMuteState([]); expect(titles({ ...eg.plusBackgroundData, mute })).toContain('Follow topic'); }); test('show unfollowTopic', () => { const mute = makeMuteState([[eg.stream, topic, UserTopicVisibilityPolicy.Followed]]); expect(titles({ ...eg.plusBackgroundData, mute })).toContain('Unfollow topic'); }); test('show resolveTopic', () => { expect(titles({ ...eg.plusBackgroundData })).toContain('Resolve topic'); }); test('show unresolveTopic', () => { expect(titles({ ...eg.plusBackgroundData }, resolved_topic.resolve_name(topic))).toContain( 'Unresolve topic', ); }); test('show deleteTopic', () => { expect(titles({ ...eg.plusBackgroundData, ownUserRole: Role.Admin })).toContain('Delete topic'); }); test('hide deleteTopic', () => { expect(titles({ ...eg.plusBackgroundData, ownUserRole: Role.Member })).not.toContain( 'Delete topic', ); }); test('show unmuteStream', () => { const subscriptions = new Map([ [eg.stream.stream_id, eg.makeSubscription({ in_home_view: false })], ]); expect(titles({ ...eg.plusBackgroundData, subscriptions })).toContain('Unmute stream'); }); test('show muteStream', () => { const subscriptions = new Map([ [eg.stream.stream_id, eg.makeSubscription({ in_home_view: true })], ]); expect(titles({ ...eg.plusBackgroundData, subscriptions })).toContain('Mute stream'); }); // TODO: test constructTopicActionButtons for copyLinkToTopic // TODO: test constructTopicActionButtons for showStreamSettings }); // TODO: test constructPmConversationActionButtons describe('constructMessageActionButtons', () => { const narrow = deepFreeze(HOME_NARROW); const titles = (backgroundData, message, canStartQuoteAndReply = false) => buttonTitles( constructMessageActionButtons({ backgroundData, message, narrow, canStartQuoteAndReply, }), ); // TODO: test constructMessageActionButtons on Outbox // TODO: test constructMessageActionButtons for addReaction test('show showReactions', () => { const message = eg.streamMessage({ reactions: [eg.unicodeEmojiReaction] }); expect(titles(eg.plusBackgroundData, message)).toContain('See who reacted'); }); // TODO: test constructMessageActionButtons for hide showReactions // TODO: test constructMessageActionButtons for reply describe('canStartQuoteAndReply', () => { test.each([true, false])('%p', (value: boolean) => { expect( titles(eg.plusBackgroundData, eg.streamMessage(), value).includes('Quote and reply'), ).toBe(value); }); }); // TODO: test constructMessageActionButtons for copy and share // TODO: test constructMessageActionButtons for edit // TODO: test constructMessageActionButtons for delete test('show starMessage', () => { const message = eg.streamMessage(); const flags = { ...eg.plusBackgroundData.flags, starred: {} }; expect(titles({ ...eg.plusBackgroundData, flags }, message)).toContain('Star message'); }); test('show unstarMessage', () => { const message = eg.streamMessage(); const flags = { ...eg.plusBackgroundData.flags, starred: { [message.id]: true } }; expect(titles({ ...eg.plusBackgroundData, flags }, message)).toContain('Unstar message'); }); describe('viewReadReceipts', () => { test('show if read receipts enabled for org', () => { expect( titles({ ...eg.plusBackgroundData, enableReadReceipts: true }, eg.streamMessage()), ).toContain('View read receipts'); }); test('hide if read receipts not enabled for org', () => { expect( titles({ ...eg.plusBackgroundData, enableReadReceipts: false }, eg.streamMessage()), ).not.toContain('View read receipts'); }); }); }); ```
/content/code_sandbox/src/action-sheets/__tests__/action-sheet-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,793
```javascript /* @flow strict-local */ // eslint-disable-next-line id-match import type { ____Styles_Internal } from 'react-native/Libraries/StyleSheet/StyleSheetTypes'; import composeBoxStyles from './composeBoxStyles'; import { statics as miscStyles } from './miscStyles'; import { statics as navStyles } from './navStyles'; import utilityStyles from './utilityStyles'; export * from './constants'; export type { ThemeData } from './theme'; export { ThemeContext } from './theme'; /** * Use instead of StyleSheet.create. * * The upstream StyleSheet.create does precisely nothing in release mode. * In debug mode it does some runtime checks that are redundant with the * type-checker, and applies Object.freeze. The useful things it does are * entirely at the source-code level: * * It makes explicit that this is supposed to be a bunch of styles. * * It tells Flow up front that this is supposed to be a bunch of styles. * In most cases we'll go on to use the styles someplace with an * appropriate type and so Flow would give an error just fine without * using any function like this, but it can be handy if the style is * passed someplace with an unfortunate `any` type. * * Unfortunately the upstream StyleSheet.create also defeats all * type-checking on the styles it returns, marking them all as type `any`. * * This function does the useful things from StyleSheet.create, plus * unconditionally applies Object.freeze. And then it passes through the * styles' actual types unchanged. */ // The name ____Styles_Internal is kind of hilarious, yes. The type it // actually refers to is: an object where each property's type is a certain // object type, an exact object type with all properties optional. That // type has the also-hilarious name ____DangerouslyImpreciseStyle_Internal; // but it's just what you get by spreading together all the different style // types. Which makes it also the least upper bound, among plain object // types (i.e. not including union types), of all the different style types. export function createStyleSheet<+S: ____Styles_Internal>(obj: S): S { return Object.freeze(obj); } // By `Object.freeze`, we really mean `createStyleSheet`. But that's too // much for Flow in types-first mode, and it can't tell the exported // object's type on a quick skim. But apparently it has no problem if we // just do an `Object.freeze` directly. So, do that, and get // `createStyleSheet` to type-check the contents of `styles` separately, in // a trivial bit of code below. const styles = Object.freeze({ ...composeBoxStyles, ...miscStyles, ...navStyles, ...utilityStyles, }); // Check the contents of `styles` (see comment above). // eslint-disable-next-line no-unused-expressions () => createStyleSheet(styles); export default styles; ```
/content/code_sandbox/src/styles/index.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
633
```javascript /* @flow strict-local */ import { Platform } from 'react-native'; import type { MaterialTopTabBarOptions } from '@react-navigation/material-top-tabs'; import type { BottomTabBarOptions } from '@react-navigation/bottom-tabs'; import { BRAND_COLOR } from './constants'; export const bottomTabNavigatorConfig = (): {| tabBarOptions: BottomTabBarOptions |} => ({ tabBarOptions: { // TODO: Find a way to tell if we're on an Android tablet, // and use that -- we don't want to assume Android users // aren't on tablets, but `isPad` is iOS only and `Platform` // doesn't have something else for Android (yet): // path_to_url#ispad-ios showLabel: Platform.OS === 'ios' && Platform.isPad, showIcon: true, activeTintColor: BRAND_COLOR, inactiveTintColor: 'gray', labelStyle: { fontSize: 13, margin: 0, }, tabStyle: { flex: 1, }, style: { backgroundColor: 'transparent', // Fix a bug introduced in React Navigation v5 that is exposed // by setting `backgroundColor` to 'transparent', as we do. elevation: 0, }, }, }); export const materialTopTabNavigatorConfig = (): {| tabBarOptions: MaterialTopTabBarOptions |} => ({ tabBarOptions: { showLabel: true, showIcon: false, activeTintColor: BRAND_COLOR, inactiveTintColor: 'gray', labelStyle: { fontSize: 13, margin: 0, }, tabStyle: { flex: 1, }, pressColor: BRAND_COLOR, indicatorStyle: { backgroundColor: BRAND_COLOR, }, // TODO: `upperCaseLabel` vanished in react-navigation v5. We // used to use `false` for this, but it appears that the // effective default value is `true`, at least for material top // tab navigators: // path_to_url // // The coercion into uppercase only happens when the tab-bar // label (whether that comes directly from // `options.tabBarLabel`, or from `options.title`) is a string, // not a more complex React node. It also doesn't seem to happen // on bottom tab navigators, just material top ones; this // difference seems to align with Material Design choices (see // Greg's comment at // path_to_url#discussion_r556949209f). style: { backgroundColor: 'transparent', // Fix a bug introduced in React Navigation v5 that is exposed // by setting `backgroundColor` to 'transparent', as we do. elevation: 0, // Setting borderWidth and elevation to 0 works around an issue // affecting react-navigation's createMaterialTopTabNavigator. // path_to_url // path_to_url#issuecomment-689724208 // TODO: Brief testing suggests this workaround isn't needed; confirm. borderWidth: 0, elevation: 0, // eslint-disable-line no-dupe-keys }, }, }); ```
/content/code_sandbox/src/styles/tabs.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
685
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import Color from 'color'; export const CONTROL_SIZE = 44; export const NAVBAR_SIZE = 58; // The value `hsl(222, 99%, 69%)` is chosen to match `rgb(100, 146, 253.5)`, // which is the sRGB midpoint of the Zulip logo's gradient. // // Note this color is also used directly in several other places: // * in our WebView's CSS; // * under `android/` (search for "BRAND_COLOR"); // * in `ios/**/Brand.colorset/Contents.json`. export const BRAND_COLOR = 'hsl(222, 99%, 69%)'; export const BORDER_COLOR = BRAND_COLOR; export const HIGHLIGHT_COLOR: string = Color(BRAND_COLOR).fade(0.5).toString(); export const HALF_COLOR = 'hsla(0, 0%, 50%, 0.5)'; export const QUARTER_COLOR = 'hsla(0, 0%, 50%, 0.25)'; // Material warning color export const kWarningColor = 'hsl(40, 100%, 60%)'; ```
/content/code_sandbox/src/styles/constants.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
262
```javascript /* @flow strict-local */ export default { // Padding padding: { padding: 16, }, paddingVertical: { paddingVertical: 16, }, paddingHorizontal: { paddingHorizontal: 16, }, paddingTop: { paddingTop: 16, }, paddingBottom: { paddingBottom: 16, }, paddingLeft: { paddingLeft: 16, }, paddingRight: { paddingRight: 16, }, // Half padding halfPadding: { padding: 8, }, halfPaddingVertical: { paddingVertical: 8, }, halfPaddingHorizontal: { paddingHorizontal: 8, }, halfPaddingTop: { paddingTop: 8, }, halfPaddingBottom: { paddingBottom: 8, }, halfPaddingLeft: { paddingLeft: 8, }, halfPaddingRight: { paddingRight: 8, }, // Margin margin: { margin: 16, }, marginVertical: { marginVertical: 16, }, marginHorizontal: { marginHorizontal: 16, }, marginTop: { marginTop: 16, }, marginBottom: { marginBottom: 16, }, marginLeft: { marginLeft: 16, }, marginRight: { marginRight: 16, }, // Half margin halfMargin: { margin: 8, }, halfMarginVertical: { marginVertical: 8, }, halfMarginHorizontal: { marginHorizontal: 8, }, halfMarginTop: { marginTop: 8, }, halfMarginBottom: { marginBottom: 8, }, halfMarginLeft: { marginLeft: 8, }, halfMarginRight: { marginRight: 8, }, }; ```
/content/code_sandbox/src/styles/utilityStyles.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
400
```javascript /* @flow strict-local */ import { CONTROL_SIZE } from './constants'; export const statics = { largerText: { fontSize: 20, }, row: { flexDirection: 'row', alignItems: 'center', }, listItem: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8, paddingHorizontal: 16, }, flexed: { flex: 1, }, rightItem: { marginLeft: 'auto', }, center: { flex: 1, justifyContent: 'center', alignItems: 'center', }, field: { flex: 1, flexDirection: 'row', height: CONTROL_SIZE, marginTop: 5, marginBottom: 5, }, alignBottom: { flexDirection: 'column', justifyContent: 'flex-end', }, }; ```
/content/code_sandbox/src/styles/miscStyles.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
191
```javascript /* @flow strict-local */ import React from 'react'; import type { Context } from 'react'; import type { ThemeName } from '../reduxTypes'; export type ThemeData = {| themeName: ThemeName, color: string, backgroundColor: string, cardColor: string, dividerColor: string, |}; export const themeData: {| [name: ThemeName]: ThemeData |} = { dark: { themeName: 'dark', color: 'hsl(210, 11%, 85%)', backgroundColor: 'hsl(212, 28%, 18%)', cardColor: 'hsl(212, 31%, 21%)', // Dividers follow Material Design: opacity 12% black or 12% white. // See path_to_url dividerColor: 'hsla(0, 0%, 100%, 0.12)', }, light: { themeName: 'light', color: 'hsl(0, 0%, 20%)', backgroundColor: 'white', cardColor: 'hsl(0, 0%, 97%)', // Dividers follow Material Design: opacity 12% black or 12% white. // See path_to_url dividerColor: 'hsla(0, 0%, 0%, 0.12)', }, }; export const ThemeContext: Context<ThemeData> = React.createContext(themeData.light); ```
/content/code_sandbox/src/styles/theme.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
314
```javascript /* @flow strict-local */ export default { disabledComposeBox: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', backgroundColor: 'gray', paddingHorizontal: 16, paddingVertical: 8, }, disabledComposeButton: { padding: 12, }, disabledComposeText: { flex: 1, color: 'white', }, }; ```
/content/code_sandbox/src/styles/composeBoxStyles.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
91
```javascript /* @flow strict-local */ import { BRAND_COLOR } from './constants'; export const statics = { navWrapper: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', }, navSubtitle: { fontSize: 13, }, navTitle: { color: BRAND_COLOR, textAlign: 'left', fontSize: 20, }, }; ```
/content/code_sandbox/src/styles/navStyles.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
93
```javascript // @flow strict-local import * as React from 'react'; import { Platform } from 'react-native'; import { WebView } from 'react-native-webview'; import * as logging from '../utils/logging'; import { tryParseUrl } from '../utils/url'; import type { ElementConfigFull } from '../reactUtils'; /** * Return a suitable onShouldStartLoadWithRequest for a single-page WebView. * * When passed as the onShouldStartLoadWithRequest prop to a WebView, the * returned callback will ensure that the webview never navigates away from * `baseUrl`. * * This is a hardening measure for our message-list WebView. We already * intercept clicks/touches and open links in a separate browser, but this * ensures that if something slips through that it still doesn't break our * security assumptions. */ // See upstream docs for this WebView prop: // path_to_url#onshouldstartloadwithrequest function makeOnShouldStartLoadWithRequest( baseUrl: URL, ): React.ElementConfig<typeof WebView>['onShouldStartLoadWithRequest'] { let loaded_once = false; return event => { // eslint-disable-next-line no-use-before-define const ok = urlIsOk(event.url); if (!ok) { logging.warn('webview: rejected navigation event', { navigation_event: { ...event }, expected_url: baseUrl.toString(), }); } return ok; }; function urlIsOk(url: string): boolean { // On Android the onShouldStartLoadWithRequest prop is documented to be // skipped on first load; therefore, simply never return true. if (Platform.OS === 'android') { return false; } // Otherwise (for iOS), return `true` only if the URL looks like what // we're expecting, and only the first such time. const parsedUrl = tryParseUrl(url); if (!loaded_once && parsedUrl && parsedUrl.toString() === baseUrl.toString()) { loaded_once = true; return true; } return false; } } type Props = $ReadOnly<{| html: string, baseUrl: URL, ...$Rest< ElementConfigFull<typeof WebView>, {| source: mixed, originWhitelist: mixed, onShouldStartLoadWithRequest: mixed |}, >, |}>; /** * A WebView that shows the given HTML at the given base URL, only. * * The WebView will show the page described by the HTML string `html`. Any * attempts to navigate to a new page will be rejected. * * Relative URL references to other resources (scripts, images, etc.) will * be resolved relative to `baseUrl`. * * Assumes `baseUrl` has the scheme `file:`. No actual file need exist at * `baseUrl` itself, because the page is taken from the string `html`. */ export default (React.memo( React.forwardRef<Props, React.ElementRef<typeof WebView>>( /* eslint-disable-next-line prefer-arrow-callback */ function SinglePageWebView(props, ref) { const { html, baseUrl, ...moreProps } = props; // The `originWhitelist` and `onShouldStartLoadWithRequest` props are // meant to mitigate possible XSS bugs, by interrupting an attempted // exploit if it tries to navigate to a new URL by e.g. setting // `window.location`. // // Note that neither of them is a hard security barrier; they're checked // only against the URL of the document itself. They cannot be used to // validate the URL of other resources the WebView loads. // // Worse, the `originWhitelist` parameter is completely broken. See: // path_to_url return ( <WebView ref={ref} source={{ baseUrl: (baseUrl.toString(): string), html: (html: string) }} originWhitelist={['file://']} onShouldStartLoadWithRequest={makeOnShouldStartLoadWithRequest(baseUrl)} {...moreProps} /> ); }, ), ): React.AbstractComponent<Props, React.ElementRef<typeof WebView>>); ```
/content/code_sandbox/src/webview/SinglePageWebView.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
880
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import isEqual from 'lodash.isequal'; import type { Auth, FlagsState } from '../types'; import type { Props } from './MessageList'; import type { ScrollStrategy } from '../message/scrollStrategy'; import messageListElementHtml from './html/messageListElementHtml'; import messageTypingAsHtml from './html/messageTypingAsHtml'; import { getScrollStrategy } from '../message/scrollStrategy'; import { symmetricDiff } from '../collections'; export type WebViewInboundEventContent = {| type: 'content', scrollMessageId: number | null, auth: Auth, content: string, scrollStrategy: ScrollStrategy, |}; export type WebViewInboundEventFetching = {| type: 'fetching', showMessagePlaceholders: boolean, fetchingOlder: boolean, fetchingNewer: boolean, |}; export type WebViewInboundEventTyping = {| type: 'typing', content: string, |}; export type WebViewInboundEventReady = {| type: 'ready', |}; export type WebViewInboundEventSetDoNotMarkAsRead = {| type: 'set-do-not-mark-as-read', value: boolean, |}; export type WebViewInboundEventSetRead = {| type: 'set-read', value: boolean, messageIds: $ReadOnlyArray<number>, |}; export type WebViewInboundEvent = | WebViewInboundEventContent | WebViewInboundEventFetching | WebViewInboundEventTyping | WebViewInboundEventReady | WebViewInboundEventSetDoNotMarkAsRead | WebViewInboundEventSetRead; const updateContent = (prevProps: Props, nextProps: Props): WebViewInboundEventContent => { const scrollStrategy = getScrollStrategy(prevProps, nextProps); return { type: 'content', scrollMessageId: nextProps.initialScrollMessageId, auth: nextProps.backgroundData.auth, content: nextProps.messageListElementsForShownMessages .map(element => messageListElementHtml({ backgroundData: nextProps.backgroundData, element, _: nextProps._, }), ) .join(''), scrollStrategy, }; }; const updateFetching = (prevProps: Props, nextProps: Props): WebViewInboundEventFetching => ({ type: 'fetching', showMessagePlaceholders: nextProps.showMessagePlaceholders, fetchingOlder: nextProps.fetching.older && !nextProps.showMessagePlaceholders, fetchingNewer: nextProps.fetching.newer && !nextProps.showMessagePlaceholders, }); const updateTyping = (prevProps: Props, nextProps: Props): WebViewInboundEventTyping => ({ type: 'typing', content: nextProps.typingUsers.length > 0 ? messageTypingAsHtml(nextProps.backgroundData.auth.realm, nextProps.typingUsers) : '', }); const equalFlagsExcludingRead = (prevFlags: FlagsState, nextFlags: FlagsState): boolean => { if (prevFlags === nextFlags) { return true; } const allFlagNames = Array.from( new Set([...Object.keys(prevFlags || {}), ...Object.keys(nextFlags || {})]), ); return allFlagNames .filter(name => name !== 'read') .every(name => prevFlags[name] === nextFlags[name]); }; export default function generateInboundEvents( prevProps: Props, nextProps: Props, ): WebViewInboundEvent[] { const uevents = []; if ( !isEqual( prevProps.messageListElementsForShownMessages, nextProps.messageListElementsForShownMessages, ) || !equalFlagsExcludingRead(prevProps.backgroundData.flags, nextProps.backgroundData.flags) // TODO(#4655): Should also update here if backgroundData.mutedUsers // changes, e.g. because the user muted someone. ) { uevents.push(updateContent(prevProps, nextProps)); } if (prevProps.doNotMarkMessagesAsRead !== nextProps.doNotMarkMessagesAsRead) { uevents.push({ type: 'set-do-not-mark-as-read', value: nextProps.doNotMarkMessagesAsRead }); } if (prevProps.backgroundData.flags.read !== nextProps.backgroundData.flags.read) { // TODO: Don't consider messages outside the narrow we're viewing. // TODO: Only include messages that we already had and have just marked // as read/unread. We're currently including some messages only because // we've just learned about them from a fetch. const prevReadIds = Object.keys(prevProps.backgroundData.flags.read).map(id => +id); const nextReadIds = Object.keys(nextProps.backgroundData.flags.read).map(id => +id); prevReadIds.sort((a, b) => a - b); nextReadIds.sort((a, b) => a - b); const [newlyUnread, newlyRead] = symmetricDiff(prevReadIds, nextReadIds); if (newlyUnread.length > 0) { uevents.push({ type: 'set-read', value: false, messageIds: newlyUnread }); } if (newlyRead.length > 0) { uevents.push({ type: 'set-read', value: true, messageIds: newlyRead }); } } if ( !isEqual(prevProps.fetching, nextProps.fetching) || prevProps.showMessagePlaceholders !== nextProps.showMessagePlaceholders ) { uevents.push(updateFetching(prevProps, nextProps)); } if (!isEqual(prevProps.typingUsers, nextProps.typingUsers)) { uevents.push(updateTyping(prevProps, nextProps)); } return uevents; } ```
/content/code_sandbox/src/webview/generateInboundEvents.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,223
```javascript /* @flow strict-local */ import { Share, Alert } from 'react-native'; import Clipboard from '@react-native-clipboard/clipboard'; import invariant from 'invariant'; import * as resolved_topic from '@zulip/shared/lib/resolved_topic'; import type { Auth, Dispatch, FlagsState, GetText, Message, MuteState, Narrow, Outbox, Subscription, UserId, User, UserOrBot, EditMessage, Stream, LocalizableText, } from '../types'; import { UserTopicVisibilityPolicy } from '../api/modelTypes'; import type { UnreadState } from '../unread/unreadModelTypes'; import { apiNarrowOfNarrow, getNarrowForReply, isPmNarrow, isStreamOrTopicNarrow, isTopicNarrow, } from '../utils/narrow'; import { pmUiRecipientsFromKeyRecipients } from '../utils/recipient'; import type { PmKeyRecipients } from '../utils/recipient'; import { getTopicVisibilityPolicy } from '../mute/muteModel'; import * as api from '../api'; import { showConfirmationDialog, showErrorAlert, showToast } from '../utils/info'; import { doNarrow, deleteOutboxMessage, fetchSomeMessageIdForConversation } from '../actions'; import { deleteMessagesForTopic } from '../topics/topicActions'; import * as logging from '../utils/logging'; import { getUnreadCountForTopic } from '../unread/unreadModel'; import getIsNotificationEnabled from '../streams/getIsNotificationEnabled'; import { getStreamTopicUrl, getStreamUrl } from '../utils/internalLinks'; import { reactionTypeFromEmojiType } from '../emoji/data'; import { Role } from '../api/permissionsTypes'; import { roleIsAtLeast } from '../permissionSelectors'; import { kNotificationBotEmail } from '../api/constants'; import type { AppNavigationMethods } from '../nav/AppNavigator'; import { type ImperativeHandle as ComposeBoxImperativeHandle } from '../compose/ComposeBox'; import { getFullNameText } from '../users/userSelectors'; // TODO really this belongs in a libdef. export type ShowActionSheetWithOptions = ( { options: string[], cancelButtonIndex: number, ... }, (number) => void, ) => void; type StreamArgs = { auth: Auth, streamId: number, subscriptions: Map<number, Subscription>, streams: Map<number, Stream>, dispatch: Dispatch, navigation: AppNavigationMethods, _: GetText, ... }; type TopicArgs = { auth: Auth, streamId: number, topic: string, subscriptions: Map<number, Subscription>, streams: Map<number, Stream>, zulipFeatureLevel: number, dispatch: Dispatch, navigation: AppNavigationMethods, _: GetText, ... }; type PmArgs = { pmKeyRecipients: PmKeyRecipients, navigation: AppNavigationMethods, _: GetText, ... }; type MessageArgs = { auth: Auth, ownUser: User, narrow: Narrow, message: Message | Outbox, allUsersById: Map<UserId, UserOrBot>, streams: Map<number, Stream>, zulipFeatureLevel: number, dispatch: Dispatch, startEditMessage: (editMessage: EditMessage) => void, setDoNotMarkMessagesAsRead: boolean => void, composeBoxImperativeHandle: ComposeBoxImperativeHandle | null, navigation: AppNavigationMethods, _: GetText, ... }; type Button<-Args: { ... }> = {| +action: Args => void | Promise<void>, /** The label for the button. */ // This UI string should be represented in messages_en.json. +title: LocalizableText, /** The title of the alert-box that will be displayed if the * callback throws. */ // Required even when the callback can't throw (e.g., "Cancel"), // since we can't otherwise ensure that everything that _can_ throw // has one. // // This UI string should be represented in messages_en.json. +errorMessage: LocalizableText, |}; // // // The options for the action sheets. // const reply = { title: 'Reply', errorMessage: 'Failed to reply', action: ({ message, dispatch, ownUser }) => { dispatch(doNarrow(getNarrowForReply(message, ownUser.user_id), message.id)); }, }; const quoteAndReply = { title: 'Quote and reply', errorMessage: 'Quote-and-reply failed', action: async ({ message, composeBoxImperativeHandle }) => { if (!composeBoxImperativeHandle) { logging.error("quoteAndReply button pressed when it shouldn't have appeared in the UI"); return; } return composeBoxImperativeHandle.doQuoteAndReply(message); }, }; const copyToClipboard = { title: 'Copy to clipboard', errorMessage: 'Failed to copy message to clipboard', action: async ({ _, auth, message, zulipFeatureLevel }) => { const rawMessage = message.isOutbox === true ? message.markdownContent : await api.getRawMessageContent(auth, { message_id: message.id }, zulipFeatureLevel); Clipboard.setString(rawMessage); showToast(_('Message copied')); }, }; const editMessage = { title: 'Edit message', errorMessage: 'Failed to edit message', action: async ({ message, startEditMessage, auth, zulipFeatureLevel }) => { if (message.isOutbox === true) { logging.warn('Attempted "Edit message" for outbox message'); return; } const rawContent = await api.getRawMessageContent( auth, { message_id: message.id }, zulipFeatureLevel, ); startEditMessage({ id: message.id, content: rawContent, topic: message.subject, }); }, }; const deleteMessage = { title: 'Delete message', errorMessage: 'Failed to delete message', action: async ({ auth, message, dispatch }) => { if (message.isOutbox === true) { dispatch(deleteOutboxMessage(message.timestamp)); } else { await api.deleteMessage(auth, message.id); } }, }; const markTopicAsRead = { title: 'Mark topic as read', errorMessage: 'Failed to mark topic as read', action: async ({ auth, streamId, topic }) => { await api.markTopicAsRead(auth, streamId, topic); }, }; const markAsUnreadFromMessage = { title: 'Mark as unread from here', errorMessage: 'Failed to mark as unread', action: async ({ auth, zulipFeatureLevel, setDoNotMarkMessagesAsRead, narrow, message, _, allUsersById, streams, }) => { setDoNotMarkMessagesAsRead(true); // TODO(server-6.0): Simplify this away. (This is for api.updateMessageFlagsForNarrow.) invariant(zulipFeatureLevel >= 155, 'markAsUnreadFromMessage should be called only at FL 155'); const apiNarrow = apiNarrowOfNarrow(narrow, allUsersById, streams); // Ideally we might add another element to the API narrow like: // { negated: true, operator: 'is', operand: 'unread' }, // That way we'd skip acting on already-unread messages. // // Unfortunately that *also* skips any messages we lack a UserMessage // record for -- which means stream messages where we weren't subscribed // when the message was sent (and haven't subsequently created such a // record, e.g. by starring the message.) let response_count = 0; let updated_count = 0; const args = { anchor: message.id, include_anchor: true, num_before: 0, num_after: 5000, op: 'remove', flag: 'read', narrow: apiNarrow, }; while (true) { const result = await api.updateMessageFlagsForNarrow(auth, args); response_count++; updated_count += result.updated_count; if (result.found_newest) { if (response_count > 1) { // We previously showed a "working on it" toast, so say we're done. showToast(_('Marked {numMessages} messages as unread', { numMessages: updated_count })); } return; } if (result.last_processed_id === null) { // No messages were in the range of the request. // This should be impossible given that found_newest was false // (and that our num_after was positive.) logging.error('mark-unread: request failed to make progress', result); throw new Error(_('The server sent a malformed response.')); } args.anchor = result.last_processed_id; args.include_anchor = false; // The task is taking a while, so tell the user we're working on it. // No need to say how many messages, as the UnreadNotice banner should // follow along. // // TODO: Ideally we'd have a progress widget here that showed up based // on actual time elapsed -- so it could appear before the first // batch returns, if that takes a while -- and that then stuck // around continuously until the task ends. But we don't have an // off-the-shelf way to wire up such a thing, and marking a giant // number of messages unread isn't a common enough flow to be worth // substantial effort on UI polish. So for now, we use toasts, even // though they may feel a bit janky. showToast(_('Marking messages as unread')); } }, }; const unmuteTopicInMutedStream = { title: 'Unmute topic', errorMessage: 'Failed to unmute topic', action: async ({ auth, streamId, topic, streams, zulipFeatureLevel }) => { invariant(zulipFeatureLevel >= 170, 'Should only attempt to unmute in muted stream on FL 170+'); await api.updateUserTopic(auth, streamId, topic, UserTopicVisibilityPolicy.Unmuted); }, }; const unmuteTopic = { title: 'Unmute topic', errorMessage: 'Failed to unmute topic', action: async ({ auth, streamId, topic, streams, zulipFeatureLevel }) => { if (zulipFeatureLevel >= 170) { await api.updateUserTopic(auth, streamId, topic, UserTopicVisibilityPolicy.None); } else { // TODO(server-7.0): Cut this fallback to setTopicMute. const stream = streams.get(streamId); invariant(stream !== undefined, 'Stream with provided streamId must exist.'); // This still uses a stream name (#3918) because the API method does; see there. await api.setTopicMute(auth, stream.name, topic, false); } }, }; const muteTopic = { title: 'Mute topic', errorMessage: 'Failed to mute topic', action: async ({ auth, streamId, topic, streams, zulipFeatureLevel }) => { if (zulipFeatureLevel >= 170) { await api.updateUserTopic(auth, streamId, topic, UserTopicVisibilityPolicy.Muted); } else { // TODO(server-7.0): Cut this fallback to setTopicMute. const stream = streams.get(streamId); invariant(stream !== undefined, 'Stream with provided streamId must exist.'); // This still uses a stream name (#3918) because the API method does; see there. await api.setTopicMute(auth, stream.name, topic, true); } }, }; const followTopic = { title: 'Follow topic', errorMessage: 'Failed to follow topic', action: async ({ auth, streamId, topic, zulipFeatureLevel }) => { invariant(zulipFeatureLevel >= 219, 'Should only attempt to follow topic on FL 219+'); await api.updateUserTopic(auth, streamId, topic, UserTopicVisibilityPolicy.Followed); }, }; const unfollowTopic = { title: 'Unfollow topic', errorMessage: 'Failed to unfollow topic', action: async ({ auth, streamId, topic, zulipFeatureLevel }) => { invariant(zulipFeatureLevel >= 219, 'Should only attempt to unfollow topic on FL 219+'); await api.updateUserTopic(auth, streamId, topic, UserTopicVisibilityPolicy.None); }, }; const copyLinkToTopic = { title: 'Copy link to topic', errorMessage: 'Failed to copy topic link', action: async ({ auth, streamId, topic, streams, _ }) => { const topicUrl = getStreamTopicUrl(auth.realm, streamId, topic, streams); Clipboard.setString(topicUrl.toString()); showToast(_('Link copied')); }, }; const toggleResolveTopic = async ({ auth, streamId, topic, _, streams, zulipFeatureLevel }) => { // TODO: It'd be nice to use a message ID we know is in the conversation, // where possible, rather than do this extra fetch. Just need to thread // such a message ID through to here. (Like web, we'll still need this // for cases where we can show a topic without knowing of any message ID // definitely in it, e.g. in the list of topics for a stream.) const messageId = await fetchSomeMessageIdForConversation( auth, streamId, topic, streams, zulipFeatureLevel, ); if (messageId == null) { // The conversation is actually empty. This can be perfectly normal, // because by fetching information outside the events system we're // exposed to a race: e.g., someone else could have resolved the topic // already and we just hadn't heard yet. // // This exception will be caught at makeButtonCallback and the message // shown to the user. throw new Error( _('No messages in topic: {streamAndTopic}', { streamAndTopic: `#${streams.get(streamId)?.name ?? 'unknown'} > ${topic}`, }), ); } const newTopic = resolved_topic.is_resolved(topic) ? resolved_topic.unresolve_name(topic) : resolved_topic.resolve_name(topic); await api.updateMessage(auth, messageId, { propagate_mode: 'change_all', subject: newTopic, ...(zulipFeatureLevel >= 9 && { send_notification_to_old_thread: false, send_notification_to_new_thread: true, }), }); }; const resolveTopic = { title: 'Resolve topic', errorMessage: 'Failed to resolve topic', action: toggleResolveTopic, }; const unresolveTopic = { title: 'Unresolve topic', errorMessage: 'Failed to unresolve topic', action: toggleResolveTopic, }; const deleteTopic = { title: 'Delete topic', errorMessage: 'Failed to delete topic', action: async ({ streamId, topic, dispatch, _ }) => { const confirmed = await new Promise((resolve, reject) => { showConfirmationDialog({ destructive: true, title: 'Delete topic', message: { text: 'Deleting a topic will immediately remove it and its messages for everyone. Other users may find this confusing, especially if they had received an email or push notification related to the deleted messages.\n\nAre you sure you want to permanently delete {topic}?', values: { topic }, }, onPressConfirm: () => resolve(true), onPressCancel: () => resolve(false), _, }); }); if (confirmed) { await dispatch(deleteMessagesForTopic(streamId, topic)); } }, }; const unmuteStream = { title: 'Unmute stream', errorMessage: 'Failed to unmute stream', action: async ({ auth, streamId }) => { await api.setSubscriptionProperty(auth, streamId, 'is_muted', false); }, }; const muteStream = { title: 'Mute stream', errorMessage: 'Failed to mute stream', action: async ({ auth, streamId }) => { await api.setSubscriptionProperty(auth, streamId, 'is_muted', true); }, }; const copyLinkToStream = { title: 'Copy link to stream', errorMessage: 'Failed to copy stream link', action: async ({ auth, streamId, streams, _ }) => { const streamUrl = getStreamUrl(auth.realm, streamId, streams); Clipboard.setString(streamUrl.toString()); showToast(_('Link copied')); }, }; const showStreamSettings = { title: 'Stream settings', errorMessage: 'Failed to show stream settings', action: ({ streamId, navigation }) => { navigation.push('stream-settings', { streamId }); }, }; const subscribe = { title: 'Subscribe', errorMessage: 'Failed to subscribe', action: async ({ auth, streamId, streams }) => { const stream = streams.get(streamId); invariant(stream !== undefined, 'Stream with provided streamId not found.'); // This still uses a stream name (#3918) because the API method does; see there. await api.subscriptionAdd(auth, [{ name: stream.name }]); }, }; const unsubscribe = { title: 'Unsubscribe', errorMessage: 'Failed to unsubscribe', action: async ({ auth, streamId, subscriptions }) => { const sub = subscriptions.get(streamId); invariant(sub !== undefined, 'Subscription with provided streamId not found.'); // This still uses a stream name (#3918) because the API method does; see there. await api.subscriptionRemove(auth, [sub.name]); }, }; const pinToTop = { title: 'Pin to top', errorMessage: 'Failed to pin to top', action: async ({ auth, streamId }) => { await api.setSubscriptionProperty(auth, streamId, 'pin_to_top', true); }, }; const unpinFromTop = { title: 'Unpin from top', errorMessage: 'Failed to unpin from top', action: async ({ auth, streamId }) => { await api.setSubscriptionProperty(auth, streamId, 'pin_to_top', false); }, }; const enableNotifications = { title: 'Enable notifications', errorMessage: 'Failed to enable notifications', action: async ({ auth, streamId }) => { await api.setSubscriptionProperty(auth, streamId, 'push_notifications', true); }, }; const disableNotifications = { title: 'Disable notifications', errorMessage: 'Failed to disable notifications', action: async ({ auth, streamId }) => { await api.setSubscriptionProperty(auth, streamId, 'push_notifications', false); }, }; const seePmConversationDetails = { title: 'See details', errorMessage: 'Failed to show details', action: async ({ pmKeyRecipients, navigation }) => { navigation.push('pm-conversation-details', { recipients: pmKeyRecipients }); }, }; const starMessage = { title: 'Star message', errorMessage: 'Failed to star message', action: async ({ auth, message }) => { await api.toggleMessageStarred(auth, [message.id], true); }, }; const unstarMessage = { title: 'Unstar message', errorMessage: 'Failed to unstar message', action: async ({ auth, message }) => { await api.toggleMessageStarred(auth, [message.id], false); }, }; const shareMessage = { title: 'Share', errorMessage: 'Failed to share message', action: async ({ message }) => { await Share.share({ message: message.content.replace(/<(?:.|\n)*?>/gm, ''), }); }, }; const addReaction = { title: 'Add a reaction', errorMessage: 'Failed to add reaction', action: ({ auth, message, navigation, _ }) => { navigation.push('emoji-picker', { onPressEmoji: ({ code, name, type }) => { api .emojiReactionAdd(auth, message.id, reactionTypeFromEmojiType(type, name), code, name) .catch(err => { logging.error('Error adding reaction emoji', err); showToast(_('Failed to add reaction')); }); }, }); }, }; const showReactions = { title: 'See who reacted', errorMessage: 'Failed to show reactions', action: ({ message, navigation }) => { navigation.push('message-reactions', { messageId: message.id }); }, }; const viewReadReceipts = { title: 'View read receipts', errorMessage: 'Failed to show read receipts', action: ({ message, navigation, _ }) => { // Notification Bot messages about resolved/unresolved topics have // confusing read receipts. Because those messages are immediately // marked as read for all non-participants in the thread, it looks // like many people have immediately read the message. So, disable // showing read receipts for messages sent by Notification Bot. See // path_to_url . if (message.sender_email === kNotificationBotEmail) { // We might instead have handled this in the read-receipts screen by // showing this message there. But it's awkward code-wise to make that // screen sometimes skip the API call, api.getReadReceipts. And it's // nice to skip that API call because it lets the server add a // server-side check for this, if it wants, without fear of breaking // mobile releases that haven't adapted. showErrorAlert( _('Read receipts'), _('Read receipts are not available for Notification Bot messages.'), ); return; } navigation.push('read-receipts', { messageId: message.id }); }, }; const cancel: Button<{ ... }> = { title: 'Cancel', errorMessage: 'Failed to hide menu', action: () => {}, }; // // // Assembling the list of options for an action sheet. // // These are separate from their callers mainly for the sake of unit tests. // export const constructStreamActionButtons = (args: {| backgroundData: $ReadOnly<{ subscriptions: Map<number, Subscription>, userSettingStreamNotification: boolean, ... }>, streamId: number, |}): Button<StreamArgs>[] => { const { backgroundData, streamId } = args; const { subscriptions, userSettingStreamNotification } = backgroundData; const buttons = []; const sub = subscriptions.get(streamId); if (sub) { if (!sub.in_home_view) { buttons.push(unmuteStream); } else { buttons.push(muteStream); } buttons.push(copyLinkToStream); if (sub.pin_to_top) { buttons.push(unpinFromTop); } else { buttons.push(pinToTop); } const isNotificationEnabled = getIsNotificationEnabled(sub, userSettingStreamNotification); if (isNotificationEnabled) { buttons.push(disableNotifications); } else { buttons.push(enableNotifications); } buttons.push(unsubscribe); } else { buttons.push(subscribe); } buttons.push(showStreamSettings); buttons.push(cancel); return buttons; }; export const constructTopicActionButtons = (args: {| backgroundData: $ReadOnly<{ mute: MuteState, ownUserRole: Role, subscriptions: Map<number, Subscription>, unread: UnreadState, zulipFeatureLevel: number, ... }>, streamId: number, topic: string, |}): Button<TopicArgs>[] => { const { backgroundData, streamId, topic } = args; const { mute, ownUserRole, subscriptions, unread, zulipFeatureLevel } = backgroundData; const sub = subscriptions.get(streamId); const streamMuted = !!sub && !sub.in_home_view; // TODO(server-7.0): Simplify this condition away. const supportsUnmutingTopics = zulipFeatureLevel >= 170; // TODO(server-8.0): Simplify this condition away. const supportsFollowingTopics = zulipFeatureLevel >= 219; const buttons = []; const unreadCount = getUnreadCountForTopic(unread, streamId, topic); if (unreadCount > 0) { buttons.push(markTopicAsRead); } if (sub && !streamMuted) { // Stream subscribed and not muted. switch (getTopicVisibilityPolicy(mute, streamId, topic)) { case UserTopicVisibilityPolicy.Muted: buttons.push(unmuteTopic); if (supportsFollowingTopics) { buttons.push(followTopic); } break; case UserTopicVisibilityPolicy.None: case UserTopicVisibilityPolicy.Unmuted: buttons.push(muteTopic); if (supportsFollowingTopics) { buttons.push(followTopic); } break; case UserTopicVisibilityPolicy.Followed: buttons.push(muteTopic); if (supportsFollowingTopics) { buttons.push(unfollowTopic); } break; } } else if (sub && streamMuted) { // Muted stream. if (supportsUnmutingTopics) { switch (getTopicVisibilityPolicy(mute, streamId, topic)) { case UserTopicVisibilityPolicy.None: case UserTopicVisibilityPolicy.Muted: buttons.push(unmuteTopicInMutedStream); if (supportsFollowingTopics) { buttons.push(followTopic); } break; case UserTopicVisibilityPolicy.Unmuted: buttons.push(muteTopic); if (supportsFollowingTopics) { buttons.push(followTopic); } break; case UserTopicVisibilityPolicy.Followed: buttons.push(muteTopic); if (supportsFollowingTopics) { buttons.push(unfollowTopic); } break; } } } else { // Not subscribed to stream at all; no muting. } if (!resolved_topic.is_resolved(topic)) { buttons.push(resolveTopic); } else { buttons.push(unresolveTopic); } if (roleIsAtLeast(ownUserRole, Role.Admin)) { buttons.push(deleteTopic); } if (sub && streamMuted) { buttons.push(unmuteStream); } else if (sub && !streamMuted) { buttons.push(muteStream); } else { // Not subscribed to stream at all; no muting. } buttons.push(copyLinkToTopic); buttons.push(showStreamSettings); buttons.push(cancel); return buttons; }; export const constructPmConversationActionButtons = (args: {| backgroundData: $ReadOnly<{ ownUser: User, ... }>, pmKeyRecipients: PmKeyRecipients, |}): Button<PmArgs>[] => { const buttons = []; // TODO(#4655): If 1:1 PM, give a mute/unmute-user button, with a confirmation // dialog saying that it also affects the muted users' stream messages, // and linking to path_to_url buttons.push(seePmConversationDetails); buttons.push(cancel); return buttons; }; const messageNotDeleted = (message: Message | Outbox): boolean => message.content !== '<p>(deleted)</p>'; export const constructMessageActionButtons = (args: {| backgroundData: $ReadOnly<{ ownUser: User, flags: FlagsState, enableReadReceipts: boolean, allUsersById: Map<UserId, UserOrBot>, streams: Map<number, Stream>, subscriptions: Map<number, Subscription>, zulipFeatureLevel: number, ... }>, message: Message | Outbox, narrow: Narrow, canStartQuoteAndReply: boolean, |}): Button<MessageArgs>[] => { const { backgroundData, message, narrow, canStartQuoteAndReply } = args; const { ownUser, flags } = backgroundData; const buttons = []; if (message.isOutbox === true) { buttons.push(copyToClipboard); buttons.push(shareMessage); buttons.push(deleteMessage); buttons.push(cancel); return buttons; } if (messageNotDeleted(message)) { buttons.push(addReaction); } if (message.reactions.length > 0) { buttons.push(showReactions); } if (!isTopicNarrow(narrow) && !isPmNarrow(narrow)) { buttons.push(reply); } if (canStartQuoteAndReply) { buttons.push(quoteAndReply); } if (messageNotDeleted(message)) { buttons.push(copyToClipboard); buttons.push(shareMessage); } if ( // TODO(#2792): Don't show if message isn't editable. message.sender_id === ownUser.user_id // Our "edit message" UI only works in certain kinds of narrows. && (isStreamOrTopicNarrow(narrow) || isPmNarrow(narrow)) ) { buttons.push(editMessage); } if (message.sender_id === ownUser.user_id && messageNotDeleted(message)) { // TODO(#2793): Don't show if message isn't deletable. buttons.push(deleteMessage); } if ( // When do we offer "Mark as unread from here"? This logic parallels // `should_display_mark_as_unread` in web's static/js/popovers.js . // // We show it only if this particular message can be marked as unread // (even though in principle the feature could be useful just to mark // later messages as read.) That means it isn't already unread message.id in flags.read // and it isn't to a stream we're not subscribed to. && (message.type === 'private' || backgroundData.subscriptions.get(message.stream_id)) // Oh and if the server is too old for the feature, don't offer it. // TODO(server-6.0): Simplify this away. && backgroundData.zulipFeatureLevel >= 155 ) { buttons.push(markAsUnreadFromMessage); } if (message.id in flags.starred) { buttons.push(unstarMessage); } else { buttons.push(starMessage); } if (backgroundData.enableReadReceipts) { buttons.push(viewReadReceipts); } buttons.push(cancel); return buttons; }; // // // Actually showing an action sheet. // function makeButtonCallback<Args: { _: GetText, ... }>(buttonList: Button<Args>[], args: Args) { return buttonIndex => { (async () => { const pressedButton: Button<Args> = buttonList[buttonIndex]; try { await pressedButton.action(args); } catch (err) { // TODO: Log any unexpected errors. `RequestError` is expected, as // are any errors specifically thrown in the action's code. // (Those should probably get their own Error subclass so we can // distinguish them here.) Anything else is a bug. // // In fact, probably even `ApiError` (a subclass of // `RequestError`) should be logged. Those can be a bug -- e.g., // some subtle permission which we'd ideally take into account by // disabling the option in the UI -- though they can also just be // due to the inherent race condition of making a request while // some other client may have concurrently changed things. Alert.alert(args._(pressedButton.errorMessage), err.message); } })(); }; } function showActionSheet<Args: { _: GetText, ... }>(params: { showActionSheetWithOptions: ShowActionSheetWithOptions, options: Array<Button<Args>>, args: Args, ... }) { const { showActionSheetWithOptions, options, args, ...rest } = params; const titles = options.map(button => args._(button.title)); showActionSheetWithOptions( { ...rest, options: titles, cancelButtonIndex: titles.length - 1 }, makeButtonCallback(options, args), ); } export const showMessageActionSheet = (args: {| showActionSheetWithOptions: ShowActionSheetWithOptions, callbacks: {| dispatch: Dispatch, startEditMessage: (editMessage: EditMessage) => void, composeBoxImperativeHandle: ComposeBoxImperativeHandle | null, navigation: AppNavigationMethods, _: GetText, setDoNotMarkMessagesAsRead: boolean => void, |}, backgroundData: $ReadOnly<{ auth: Auth, ownUser: User, flags: FlagsState, enableReadReceipts: boolean, zulipFeatureLevel: number, allUsersById: Map<UserId, UserOrBot>, streams: Map<number, Stream>, subscriptions: Map<number, Subscription>, ... }>, message: Message | Outbox, narrow: Narrow, |}): void => { const { showActionSheetWithOptions, callbacks, backgroundData, message, narrow } = args; showActionSheet({ showActionSheetWithOptions, options: constructMessageActionButtons({ backgroundData, message, narrow, canStartQuoteAndReply: callbacks.composeBoxImperativeHandle !== null, }), args: { ...backgroundData, ...callbacks, message, narrow }, }); }; export const showTopicActionSheet = (args: {| showActionSheetWithOptions: ShowActionSheetWithOptions, callbacks: {| dispatch: Dispatch, navigation: AppNavigationMethods, _: GetText, |}, backgroundData: $ReadOnly<{ auth: Auth, mute: MuteState, streams: Map<number, Stream>, subscriptions: Map<number, Subscription>, unread: UnreadState, ownUser: User, ownUserRole: Role, zulipFeatureLevel: number, ... }>, streamId: number, topic: string, |}): void => { const { showActionSheetWithOptions, callbacks, backgroundData, topic, streamId } = args; const stream = backgroundData.streams.get(streamId); invariant(stream !== undefined, 'Stream with provided streamId not found.'); showActionSheet({ showActionSheetWithOptions, title: `#${stream.name} > ${topic}`, options: constructTopicActionButtons({ backgroundData, streamId, topic }), args: { ...backgroundData, ...callbacks, streamId, topic }, }); }; export const showStreamActionSheet = (args: {| showActionSheetWithOptions: ShowActionSheetWithOptions, callbacks: {| dispatch: Dispatch, navigation: AppNavigationMethods, _: GetText, |}, backgroundData: $ReadOnly<{ auth: Auth, streams: Map<number, Stream>, subscriptions: Map<number, Subscription>, userSettingStreamNotification: boolean, ... }>, streamId: number, |}): void => { const { showActionSheetWithOptions, callbacks, backgroundData, streamId } = args; const stream = backgroundData.streams.get(streamId); invariant(stream !== undefined, 'Stream with provided streamId not found.'); showActionSheet({ showActionSheetWithOptions, title: `#${stream.name}`, options: constructStreamActionButtons({ backgroundData, streamId }), args: { ...backgroundData, ...callbacks, streamId }, }); }; export const showPmConversationActionSheet = (args: {| showActionSheetWithOptions: ShowActionSheetWithOptions, callbacks: {| navigation: AppNavigationMethods, _: GetText, |}, backgroundData: $ReadOnly<{ ownUser: User, allUsersById: Map<UserId, UserOrBot>, enableGuestUserIndicator: boolean, ... }>, pmKeyRecipients: PmKeyRecipients, |}): void => { const { showActionSheetWithOptions, callbacks, backgroundData, pmKeyRecipients } = args; const { enableGuestUserIndicator } = backgroundData; showActionSheet({ showActionSheetWithOptions, // TODO(ios-14.5): Check for Intl.ListFormat support in all environments // TODO(i18n): Localize this list (will be easiest when we don't have // to polyfill Intl.ListFormat); see path_to_url#formatlist title: pmUiRecipientsFromKeyRecipients(pmKeyRecipients, backgroundData.ownUser.user_id) .map(userId => { const user = backgroundData.allUsersById.get(userId); invariant(user, 'allUsersById incomplete; could not show PM action sheet'); return callbacks._(getFullNameText({ user, enableGuestUserIndicator })); }) .sort() .join(', '), titleTextStyle: { // We hack with this Android-only option to keep extra-long lists of // recipients from sabotaging the UI. Better would be to control the // Text's `numberOfLines` prop, but the library doesn't offer that. // See screenshots at // path_to_url#issuecomment-997089710. // // On iOS, the native action sheet solves this problem for us, and // we're using that as of 2021-12. maxHeight: 160, }, options: constructPmConversationActionButtons({ backgroundData, pmKeyRecipients }), args: { ...backgroundData, ...callbacks, pmKeyRecipients }, }); }; ```
/content/code_sandbox/src/action-sheets/index.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
8,143
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import isEqual from 'lodash.isequal'; import invariant from 'invariant'; import type { MessageListElement, GetText } from '../types'; import { ensureUnreachable } from '../generics'; import type { BackgroundData } from './backgroundData'; import messageListElementHtml from './html/messageListElementHtml'; import { getUserStatusFromModel } from '../user-statuses/userStatusesCore'; import { isTopicFollowed } from '../mute/muteModel'; import { pmUiRecipientsFromMessage } from '../utils/recipient'; const NODE_ENV = process.env.NODE_ENV; export type Insert = $ReadOnly<{| type: 'insert', html: string, index: number, |}>; export type Delete = $ReadOnly<{| type: 'delete', index: number, |}>; export type Replace = $ReadOnly<{| type: 'replace', html: string, index: number, |}>; type Edit = Insert | Delete | Replace; export type EditSequence = $ReadOnlyArray<Edit>; /** * A compare function to sort a list of MessageListElements by `.key`. * * See the `MessageListElement.key` type definition. */ function compare(a: MessageListElement, b: MessageListElement) { const firstResult = Math.sign(a.key[0] - b.key[0]); if (firstResult !== 0) { return firstResult; } else { return Math.sign(a.key[1] - b.key[1]); } } function areElementsInOrder(elements: $ReadOnlyArray<MessageListElement>): boolean { return elements.every((elem, i, arr) => i === 0 || compare(arr[i - 1], arr[i]) === -1); } /** * Check for differences in data belonging to two MessageListElements * * Ignores all background data that doesn't belong to the two particular * elements and could plausibly affect all elements: language, narrow, * dark/light theme, current date, self-user's role (e.g., admin), etc. */ function doElementsDifferInterestingly( oldElement, newElement, oldBackgroundData, newBackgroundData, ): boolean { if (oldElement.type !== newElement.type) { return true; } switch (oldElement.type) { case 'time': // TODO(?): False positives on `.subsequentMessage.content` changes return !isEqual(oldElement, newElement); case 'header': { invariant(newElement.type === 'header', 'oldElement.type equals newElement.type'); // TODO(?): False positives on `.subsequentMessage.content` changes if (!isEqual(oldElement, newElement)) { return true; } const subsequentMessage = oldElement.subsequentMessage; if (subsequentMessage.type === 'stream') { if ( isTopicFollowed( subsequentMessage.stream_id, subsequentMessage.subject, oldBackgroundData.mute, ) !== isTopicFollowed( subsequentMessage.stream_id, subsequentMessage.subject, newBackgroundData.mute, ) ) { return true; } } else { invariant( oldBackgroundData.ownUser.user_id === newBackgroundData.ownUser.user_id, 'self-user ID not supposed to change', ); const ownUserId = oldBackgroundData.ownUser.user_id; const messageRecipients = pmUiRecipientsFromMessage(subsequentMessage, ownUserId); for (const recipient of messageRecipients) { const oldRecipientUser = oldBackgroundData.allUsersById.get(recipient.id); const newRecipientUser = newBackgroundData.allUsersById.get(recipient.id); if ( oldRecipientUser?.full_name !== newRecipientUser?.full_name || oldRecipientUser?.role !== newRecipientUser?.role ) { return true; } } } return false; } case 'message': { invariant(newElement.type === 'message', 'oldElement.type equals newElement.type'); const oldMessage = oldElement.message; const oldSender = oldBackgroundData.allUsersById.get(oldMessage.sender_id); const newMessage = newElement.message; const newSender = newBackgroundData.allUsersById.get(newMessage.sender_id); return ( !isEqual(oldElement, newElement) // TODO(?): Flags are metadata on a message, not "background data". // Attach them to the MessageListElement object itself, where we // construct it, then simplify this function. It's surprising to // see "background data" in this function's inputs. || Object.keys(oldBackgroundData.flags).some( flagName => // The WebView updates its "read" state through a different // event type, WebViewInboundEventMessagesRead. So, ignore that // flag here, but do notice any other flags changing. // TODO(?): Maybe actually handle 'read' here? See // path_to_url#discussion_r792992634 flagName !== 'read' && oldBackgroundData.flags[flagName][oldElement.message.id] !== newBackgroundData.flags[flagName][newElement.message.id], ) || oldSender?.full_name !== newSender?.full_name || oldSender?.role !== newSender?.role || oldBackgroundData.mutedUsers.get(oldElement.message.sender_id) !== newBackgroundData.mutedUsers.get(newElement.message.sender_id) || getUserStatusFromModel(oldBackgroundData.userStatuses, oldElement.message.sender_id) .status_emoji !== getUserStatusFromModel(newBackgroundData.userStatuses, newElement.message.sender_id) .status_emoji ); } default: { ensureUnreachable(oldElement.type); throw new Error(); } } } /** * PRIVATE - don't use until we have more test coverage (coming soon) */ export function getEditSequence( oldArgs: {| backgroundData: BackgroundData, elements: $ReadOnlyArray<MessageListElement>, _: GetText, |}, newArgs: {| backgroundData: BackgroundData, elements: $ReadOnlyArray<MessageListElement>, _: GetText, |}, ): EditSequence { const { elements: oldElements } = oldArgs; const { elements: newElements } = newArgs; if (NODE_ENV !== 'production') { invariant(areElementsInOrder(oldElements), 'getEditSequence: oldElements not in order'); invariant(areElementsInOrder(newElements), 'getEditSequence: newElements not in order'); } const hasLanguageChanged = oldArgs._ !== newArgs._; const hasGuestIndicatorSettingChanged = oldArgs.backgroundData.enableGuestUserIndicator !== newArgs.backgroundData.enableGuestUserIndicator; const result = []; let i = 0; let j = 0; while (i < oldElements.length && j < newElements.length) { const oldElement = oldElements[i]; const newElement = newElements[j]; const compareResult = compare(oldElement, newElement); if (compareResult < 0) { result.push({ type: 'delete', index: j }); i++; } else if (compareResult > 0) { result.push({ type: 'insert', index: j, html: messageListElementHtml({ backgroundData: newArgs.backgroundData, element: newElement, _: newArgs._, }), }); j++; } else { // Predict whether oldElement and newElement would render differently. // // We avoid the performance hit of actually computing both HTML // strings for comparison. Instead, we inspect the inputs of that // computation: context that affects how all elements in the list are // rendered, and oldElement and newElement themselves. // // False positives might be acceptable; false negatives are not. if ( hasLanguageChanged // Replace any translated text, like muted-user placeholders. || hasGuestIndicatorSettingChanged // Add/remove guest indicators || doElementsDifferInterestingly( oldElement, newElement, oldArgs.backgroundData, newArgs.backgroundData, ) ) { result.push({ type: 'replace', index: j, html: messageListElementHtml({ backgroundData: newArgs.backgroundData, element: newElement, _: newArgs._, }), }); } i++; j++; } } while (j < newElements.length) { result.push({ type: 'insert', index: j, html: messageListElementHtml({ backgroundData: newArgs.backgroundData, element: newElements[j], _: newArgs._, }), }); j++; } while (i < oldElements.length) { result.push({ type: 'delete', index: j }); i++; } return result; } ```
/content/code_sandbox/src/webview/generateInboundEventEditSequence.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,930
```javascript // @flow strict-local import type { AlertWordsState, Auth, FlagsState, GlobalSettingsState, ImageEmoji, MuteState, MutedUsersState, PerAccountState, Subscription, Stream, UserId, User, UserOrBot, } from '../types'; import type { UnreadState } from '../unread/unreadModelTypes'; import { getAuth, getAllImageEmojiById, getFlags, getAllUsersById, getMutedUsers, getOwnUser, getSettings, getSubscriptionsById, getStreamsById, getRealm, getZulipFeatureLevel, } from '../selectors'; import { getMute } from '../mute/muteModel'; import { getUnread } from '../unread/unreadModel'; import { getUserStatuses } from '../user-statuses/userStatusesModel'; import { type UserStatusesState } from '../user-statuses/userStatusesCore'; import { Role } from '../api/permissionsTypes'; import type { ServerEmojiData } from '../api/modelTypes'; /** * Data about the user, the realm, and all known messages. * * This data is all independent of the specific narrow or specific messages * we're displaying; data about those goes elsewhere. * * We pass this object down to a variety of lower layers and helper * functions, where it saves us from individually wiring through all the * overlapping subsets of this data they respectively need. */ export type BackgroundData = $ReadOnly<{| alertWords: AlertWordsState, allImageEmojiById: $ReadOnly<{| [id: string]: ImageEmoji |}>, auth: Auth, flags: FlagsState, mute: MuteState, allUsersById: Map<UserId, UserOrBot>, mutedUsers: MutedUsersState, ownUser: User, ownUserRole: Role, streams: Map<number, Stream>, subscriptions: Map<number, Subscription>, unread: UnreadState, twentyFourHourTime: boolean, userSettingStreamNotification: boolean, displayEmojiReactionUsers: boolean, userStatuses: UserStatusesState, zulipFeatureLevel: number, serverEmojiData: ServerEmojiData | null, enableReadReceipts: boolean, enableGuestUserIndicator: boolean, |}>; // TODO: Ideally this ought to be a caching selector that doesn't change // when the inputs don't. Doesn't matter in a practical way as used in // MessageList, because we memoize the expensive parts of rendering and in // generateInboundEvents we check for changes to individual relevant // properties of backgroundData, rather than backgroundData itself. But // it'd be better to set an example of the right general pattern. export const getBackgroundData = ( state: PerAccountState, globalSettings: GlobalSettingsState, ): BackgroundData => { const ownUser = getOwnUser(state); return { alertWords: state.alertWords, allImageEmojiById: getAllImageEmojiById(state), auth: getAuth(state), flags: getFlags(state), mute: getMute(state), allUsersById: getAllUsersById(state), mutedUsers: getMutedUsers(state), ownUser, ownUserRole: ownUser.role, streams: getStreamsById(state), subscriptions: getSubscriptionsById(state), unread: getUnread(state), twentyFourHourTime: getRealm(state).twentyFourHourTime, userSettingStreamNotification: getSettings(state).streamNotification, displayEmojiReactionUsers: getSettings(state).displayEmojiReactionUsers, userStatuses: getUserStatuses(state), zulipFeatureLevel: getZulipFeatureLevel(state), serverEmojiData: getRealm(state).serverEmojiData, enableReadReceipts: getRealm(state).enableReadReceipts, enableGuestUserIndicator: getRealm(state).enableGuestUserIndicator, }; }; ```
/content/code_sandbox/src/webview/backgroundData.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
851
```javascript /* @flow strict-local */ import { Alert } from 'react-native'; import Clipboard from '@react-native-clipboard/clipboard'; import * as api from '../api'; import config from '../config'; import type { UserId } from '../types'; import type { JSONableDict } from '../utils/jsonable'; import { showConfirmationDialog, showErrorAlert, showToast } from '../utils/info'; import { pmKeyRecipientsFromMessage } from '../utils/recipient'; import { isUrlAnImage, tryParseUrl } from '../utils/url'; import * as logging from '../utils/logging'; import { filterUnreadMessagesInRange } from '../utils/unread'; import { parseNarrow } from '../utils/narrow'; import { doNarrow, messageLinkPress } from '../actions'; import { showTopicActionSheet, showPmConversationActionSheet, showMessageActionSheet, } from '../action-sheets'; import { ensureUnreachable } from '../types'; import { base64Utf8Decode } from '../utils/encoding'; import type { Props } from './MessageList'; import type { AppNavigationMethods } from '../nav/AppNavigator'; type WebViewOutboundEventReady = {| type: 'ready', |}; // The user scrolled in the message list, or we pretended they did. We may // need to fetch more messages, or mark some messages as read. type WebViewOutboundEventScroll = {| type: 'scroll', // The height (in logical pixels?) of the entire message list document // this scroll event happened in. offsetHeight: number, // The height (in logical pixels?) of the visible portion of the message // list document. innerHeight: number, // The vertical offset (in logical pixels?) from the top of the message list // document to the top of the visible portion, following this scroll event. scrollY: number, // The earliest message ID of all those in view either before or after // this scroll event. startMessageId: number, // The latest message ID of all those in view either before or after // this scroll event. endMessageId: number, |}; type WebViewOutboundEventRequestUserProfile = {| type: 'request-user-profile', fromUserId: UserId, |}; type WebViewOutboundEventNarrow = {| type: 'narrow', // The result of `keyFromNarrow`, passed through `base64Utf8Encode`. // Pass it through `base64UtfDecode` before using. narrow: string, |}; type WebViewOutboundEventImage = {| type: 'image', src: string, messageId: number, |}; type WebViewOutboundEventReaction = {| type: 'reaction', messageId: number, name: string, code: string, reactionType: string, voted: boolean, |}; type WebViewOutboundEventUrl = {| type: 'url', href: string, messageId: number, |}; type WebViewOutboundEventLongPress = {| type: 'longPress', target: 'message' | 'header' | 'link', messageId: number, href: string | null, |}; type WebViewOutboundEventDebug = {| type: 'debug', |}; type WebViewOutboundEventWarn = {| type: 'warn', details: JSONableDict, |}; type WebViewOutboundEventError = {| type: 'error', details: {| message: string, source: string, line: number, column: number, userAgent: string, error: Error, |}, |}; type WebViewOutboundEventReactionDetails = {| type: 'reactionDetails', messageId: number, reactionName: string, |}; type WebViewOutboundEventMention = {| type: 'mention', userId: UserId, |}; type WebViewOutboundEventTimeDetails = {| type: 'time', originalText: string, |}; type WebViewOutboundEventVote = {| type: 'vote', messageId: number, key: string, vote: number, |}; export type WebViewOutboundEvent = | WebViewOutboundEventReady | WebViewOutboundEventScroll | WebViewOutboundEventRequestUserProfile | WebViewOutboundEventNarrow | WebViewOutboundEventImage | WebViewOutboundEventReaction | WebViewOutboundEventUrl | WebViewOutboundEventLongPress | WebViewOutboundEventReactionDetails | WebViewOutboundEventDebug | WebViewOutboundEventWarn | WebViewOutboundEventError | WebViewOutboundEventMention | WebViewOutboundEventTimeDetails | WebViewOutboundEventVote; const fetchMore = (props: Props, event: WebViewOutboundEventScroll) => { const { innerHeight, offsetHeight, scrollY } = event; if (scrollY < config.messageListThreshold) { props.fetchOlder(); } if (innerHeight + scrollY >= offsetHeight - config.messageListThreshold) { props.fetchNewer(); } }; const markRead = (props: Props, event: WebViewOutboundEventScroll) => { const { flags, auth } = props.backgroundData; if (props.doNotMarkMessagesAsRead) { return; } const unreadMessageIds = filterUnreadMessagesInRange( props.messages, flags, event.startMessageId, event.endMessageId, ); api.queueMarkAsRead(auth, unreadMessageIds); }; /** * Handle tapping an image or link for which we want to open the lightbox. */ const handleImage = ( props: Props, navigation: AppNavigationMethods, src: string, messageId: number, ) => { const { _ } = props; const parsedSrc = tryParseUrl(src, props.backgroundData.auth.realm); if (!parsedSrc) { showErrorAlert(_('Cannot open image'), _('Invalid image URL.')); return; } const message = props.messages.find(x => x.id === messageId); if (message && message.isOutbox !== true) { navigation.push('lightbox', { src: parsedSrc, message }); } }; const handleLongPress = (args: {| props: Props, target: 'message' | 'header' | 'link', messageId: number, href: string | null, navigation: AppNavigationMethods, |}) => { const { props, target, messageId, href, navigation } = args; const { _ } = props; if (href !== null) { const url = tryParseUrl(href, props.backgroundData.auth.realm); if (url == null) { showConfirmationDialog({ title: 'Copy invalid link', message: { text: 'This link appears to be invalid. Do you want to copy it anyway?\n\n{text}', values: { text: href }, }, onPressConfirm: () => { Clipboard.setString(href); showToast(_('Text copied')); }, _, }); return; } Clipboard.setString(url.toString()); showToast(_('Link copied')); return; } const message = props.messages.find(x => x.id === messageId); if (!message) { return; } const { dispatch, showActionSheetWithOptions, backgroundData, narrow, startEditMessage, setDoNotMarkMessagesAsRead, composeBoxRef, } = props; if (target === 'header') { if (message.type === 'stream') { showTopicActionSheet({ showActionSheetWithOptions, callbacks: { dispatch, navigation, _ }, backgroundData, streamId: message.stream_id, topic: message.subject, }); } else if (message.type === 'private') { showPmConversationActionSheet({ showActionSheetWithOptions, callbacks: { navigation, _ }, backgroundData, pmKeyRecipients: pmKeyRecipientsFromMessage(message, backgroundData.ownUser.user_id), }); } } else if (target === 'message') { showMessageActionSheet({ showActionSheetWithOptions, callbacks: { dispatch, startEditMessage, setDoNotMarkMessagesAsRead, // The immutable `.current` value, not the mutable ref object, so // that an action-sheet button press will act on values that were // current when the action sheet was opened: // path_to_url#discussion_r1027004559 composeBoxImperativeHandle: composeBoxRef.current, navigation, _, }, backgroundData, message, narrow, }); } }; export const handleWebViewOutboundEvent = ( props: Props, navigation: AppNavigationMethods, event: WebViewOutboundEvent, ) => { switch (event.type) { case 'ready': // handled by caller break; case 'scroll': fetchMore(props, event); markRead(props, event); break; case 'request-user-profile': { navigation.push('account-details', { userId: event.fromUserId }); break; } case 'narrow': props.dispatch(doNarrow(parseNarrow(base64Utf8Decode(event.narrow)))); break; case 'image': handleImage(props, navigation, event.src, event.messageId); break; case 'longPress': handleLongPress({ props, target: event.target, messageId: event.messageId, href: event.href, navigation, }); break; case 'url': if (isUrlAnImage(event.href)) { handleImage(props, navigation, event.href, event.messageId); } else { props.dispatch(messageLinkPress(event.href, props._)); } break; case 'reaction': { const { code, messageId, name, reactionType, voted } = event; const { auth } = props.backgroundData; if (voted) { api.emojiReactionRemove(auth, messageId, reactionType, code, name); } else { api.emojiReactionAdd(auth, messageId, reactionType, code, name); } } break; case 'reactionDetails': { const { messageId, reactionName } = event; navigation.push('message-reactions', { messageId, reactionName }); } break; case 'mention': { navigation.push('account-details', { userId: event.userId }); break; } case 'time': { const { _ } = props; const alertText = _('This time is in your timezone. Original text was {originalText}.', { originalText: event.originalText, }); Alert.alert('', alertText); break; } case 'vote': { api.sendSubmessage( props.backgroundData.auth, event.messageId, JSON.stringify({ type: 'vote', key: event.key, vote: event.vote, }), ); break; } case 'debug': console.debug(props, event); // eslint-disable-line break; case 'warn': logging.warn('WebView warning', event.details); break; case 'error': { const { error, ...rest } = event.details; logging.error(error, rest); break; } default: ensureUnreachable(event); logging.error(`WebView event of unknown type: ${event.type}`); break; } }; ```
/content/code_sandbox/src/webview/handleOutboundEvents.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,470
```javascript /* @flow strict-local */ import template from './template'; const messageLoadingHtml = template` <div class="loading"> <div class="loading-avatar"></div> <div class="loading-content"> <div class="loading-subheader"> <div class="block name"></div> <div class="block msg-timestamp show"></div> </div> <div class="block"></div> <div class="block"></div> </div> </div> `; const htmlScrollToBottom = template` <div id="scroll-bottom" class="scroll-bottom hidden"> <a href="" class="scroll-bottom"> <span class="text">Scroll to bottom</span> <svg class="scroll-bottom" width="1792" height="1792" viewBox="0 0 1792 1792" xmlns="path_to_url" aria-hidden> <path class="scroll-bottom" d="M1395 736q0 13-10 23l-466 466q-10 10-23 10t-23-10l-466-466q-10-10-10-23t10-23l50-50q10-10 23-10t23 10l393 393 393-393q10-10 23-10t23 10l50 50q10 10 10 23z"/> </svg> </a> </div> `; export default (content: string, showMessagePlaceholders: boolean): string => template` <div id="js-error-detailed"></div> <div id="js-error-plain">Oh no! Something went wrong. Try again?</div> <div id="js-error-plain-dummy">Oh no! Something went wrong. Try again?</div> <div id="spinner-older" class="hidden loading-spinner"></div> <div id="msglist-elements"> $!${content} </div> <div id="message-loading" class="${showMessagePlaceholders ? '' : 'hidden'}"> $!${messageLoadingHtml.repeat(10)} </div> <div id="spinner-newer" class="hidden loading-spinner"></div> <div id="typing"></div> $!${htmlScrollToBottom} `; ```
/content/code_sandbox/src/webview/html/htmlBody.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
473
```javascript /* @flow strict-local */ import type { GetText, MessageListElement } from '../../types'; import { ensureUnreachable } from '../../generics'; import type { BackgroundData } from '../backgroundData'; import message from './message'; import header from './header'; import time from './time'; export default ({ backgroundData, element, _, }: {| backgroundData: BackgroundData, element: MessageListElement, _: GetText, |}): string => { switch (element.type) { case 'time': return time(element); case 'header': return header(backgroundData, element, _); case 'message': return message(backgroundData, element, _); default: ensureUnreachable(element); throw new Error(`Unidentified element.type: '${element.type}'`); } }; ```
/content/code_sandbox/src/webview/html/messageListElementHtml.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
175
```javascript /* @flow strict-local */ import type { FlagsState } from '../../types'; /* eslint-disable */ /* * The bulk of this code is taken verbatim from the webapp: * path_to_url * in order to avoid multiple implementations of this rather tricky logic. * To permit that, we disable ESLint and Prettier. * * For an updated comparison, try a command like: * git diff --no-index ../zulip/static/js/alert_words.js src/webview/html/processAlertWords.js */ // escape_user_regex taken from jquery-ui/autocomplete.js, // licensed under MIT license. // prettier-ignore function escape_user_regex(value) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } /* Helper borrowed near-verbatim from webapp; see comment above. */ // prettier-ignore const process_message = function (words: $ReadOnlyArray<string>, message: {| alerted: boolean, content: string |}) { // Parsing for alert words is expensive, so we rely on the host // to tell us there any alert words to even look for. if (!message.alerted) { return; } words.forEach(function (word) { var clean = escape_user_regex(word); var before_punctuation = '\\s|^|>|[\\(\\".,\';\\[]'; var after_punctuation = '\\s|$|<|[\\)\\"\\?!:.,\';\\]!]'; var regex = new RegExp('(' + before_punctuation + ')' + '(' + clean + ')' + '(' + after_punctuation + ')', 'ig'); message.content = message.content.replace(regex, function (match, before, word, after, offset, content) { // Logic for ensuring that we don't muck up rendered HTML. var pre_match = content.substring(0, offset); // We want to find the position of the `<` and `>` only in the // match and the string before it. So, don't include the last // character of match in `check_string`. This covers the corner // case when there is an alert word just before `<` or `>`. var check_string = pre_match + match.substring(0, match.length - 1); var in_tag = check_string.lastIndexOf('<') > check_string.lastIndexOf('>'); // Matched word is inside a HTML tag so don't perform any highlighting. if (in_tag === true) { return before + word + after; } return before + "<span class='alert-word'>" + word + "</span>" + after; }); }); }; /** Mark any alert words in `content` with an appropriate span. */ export default ( content: string, id: number, alertWords: $ReadOnlyArray<string>, flags: FlagsState, ): string => { // This is kind of funny style, but lets us borrow the webapp's code near // verbatim, inside `process_message`. let message = { content, alerted: flags.has_alert_word[id] }; process_message(alertWords, message); return message.content; }; ```
/content/code_sandbox/src/webview/html/processAlertWords.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
675
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import escape from 'lodash.escape'; /** * As an ES6 template tag, escapes HTML in interpolated values, * except where marked. * * To mark a value as HTML to be included raw, use '$!$' instead of '$': * template`Hello ${&<world}` -> 'Hello &amp;&lt;world' * but * template`Hello $!${&<world}` -> 'Hello &<world' * * To include a literal '$!' before a value, write '$\!': * template`Hello $\!${&<world}` -> 'Hello $!&amp;&lt;world' */ export default ( strings: $ReadOnlyArray<string>, ...values: $ReadOnlyArray<string | number | boolean> ): string => { // $FlowIssue[prop-missing] #2616 github.com/facebook/flow/issues/2616 const raw: $ReadOnlyArray<string> = strings.raw; const result = []; values.forEach((value, i) => { if (raw[i].endsWith('$!')) { result.push(strings[i].substring(0, strings[i].length - 2)); result.push(value); } else { result.push(strings[i]); result.push(escape(value)); } }); result.push(strings[strings.length - 1]); return result.join(''); }; ```
/content/code_sandbox/src/webview/html/template.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
300
```javascript /* @flow strict-local */ import template from './template'; import type { TimeMessageListElement } from '../../types'; import { humanDate } from '../../utils/date'; /** * The HTML string for a message-list element of the "time" type. * * This is a private helper of messageListElementHtml. */ export default (element: TimeMessageListElement): string => template`\ <div class="msglist-element timerow" data-msg-id="${element.subsequentMessage.id}"> <div class="timerow-left"></div> ${humanDate(new Date(element.timestamp * 1000))} <div class="timerow-right"></div> </div>`; ```
/content/code_sandbox/src/webview/html/time.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
138
```javascript /* @flow strict-local */ import * as React from 'react'; import { useContext, useState } from 'react'; import { Platform, NativeModules } from 'react-native'; import { WebView } from 'react-native-webview'; // $FlowFixMe[untyped-import] import { useActionSheet } from '@expo/react-native-action-sheet'; import type { Dispatch, Fetching, GetText, Message, Narrow, Outbox, MessageListElement, UserOrBot, EditMessage, } from '../types'; import { ThemeContext } from '../styles'; import { useSelector, useDispatch, useGlobalSelector } from '../react-redux'; import { useNavigation } from '../react-navigation'; import { getCurrentTypingUsers, getFetchingForNarrow, getGlobalSettings } from '../selectors'; import { TranslationContext } from '../boot/TranslationProvider'; import type { ShowActionSheetWithOptions } from '../action-sheets'; import { getMessageListElementsMemoized } from '../message/messageSelectors'; import type { WebViewInboundEvent } from './generateInboundEvents'; import type { WebViewOutboundEvent } from './handleOutboundEvents'; import getHtml from './html/html'; import messageListElementHtml from './html/messageListElementHtml'; import generateInboundEvents from './generateInboundEvents'; import { handleWebViewOutboundEvent } from './handleOutboundEvents'; import { base64Utf8Encode } from '../utils/encoding'; import { caseNarrow, isConversationNarrow } from '../utils/narrow'; import { type BackgroundData, getBackgroundData } from './backgroundData'; import { ensureUnreachable } from '../generics'; import SinglePageWebView from './SinglePageWebView'; import { usePrevious } from '../reactUtils'; import { type ImperativeHandle as ComposeBoxImperativeHandle } from '../compose/ComposeBox'; /** * The actual React props for the MessageList component. */ type OuterProps = $ReadOnly<{| narrow: Narrow, messages: $ReadOnlyArray<Message | Outbox>, initialScrollMessageId: number | null, showMessagePlaceholders: boolean, startEditMessage: (editMessage: EditMessage) => void, fetchOlder: () => Promise<void> | void, fetchNewer: () => Promise<void> | void, // Careful: We expect this prop to be mutable, which is unusual. composeBoxRef: {| current: ComposeBoxImperativeHandle | null |}, |}>; /** * All the data for rendering the message list, and callbacks for its UI actions. * * This data gets used for rendering the initial HTML and for computing * inbound-events to update the page. Then the handlers for the message * list's numerous UI actions -- both for user interactions inside the page * as represented by outbound-events, and in action sheets -- use the data * and callbacks in order to do their jobs. * * This can be thought of -- hence the name -- as the React props for a * notional inner component, like we'd have if we obtained this data through * HOCs like `connect`. (Instead, we use Hooks, and don't have a separate * inner component.) */ export type Props = $ReadOnly<{| ...OuterProps, showActionSheetWithOptions: ShowActionSheetWithOptions, _: GetText, dispatch: Dispatch, // Data independent of the particular narrow or messages we're displaying. backgroundData: BackgroundData, // These props contain data specific to the particular narrow or // particular messages we're displaying. Data that's independent of those // should go in `BackgroundData`, above. fetching: Fetching, messageListElementsForShownMessages: $ReadOnlyArray<MessageListElement>, typingUsers: $ReadOnlyArray<UserOrBot>, // Local state, and setters. doNotMarkMessagesAsRead: boolean, setDoNotMarkMessagesAsRead: boolean => void, |}>; /** * Whether reading messages in this narrow can mark them as read. * * "Can", not "will": other conditions can mean we don't want to mark * messages as read even when in a narrow where this is true. */ const marksMessagesAsRead = (narrow: Narrow): boolean => // Generally we want these to agree with the web/desktop app, so that user // expectations transfer between the different apps. caseNarrow(narrow, { // These narrows show one conversation in full. Each message appears // in its full context, so it makes sense to say the user's read it // and doesn't need to be shown it as unread again. topic: () => true, pm: () => true, // These narrows show several conversations interleaved. They always // show entire conversations, so each message still appears in its // full context and it still makes sense to mark it as read. stream: () => true, home: () => true, allPrivate: () => true, // These narrows show selected messages out of context. The user will // typically still want to see them another way, in context, before // letting them disappear from their list of unread messages. search: () => false, starred: () => false, mentioned: () => false, }); function useMessageListProps(props: OuterProps): Props { const _ = useContext(TranslationContext); const showActionSheetWithOptions: ShowActionSheetWithOptions = useActionSheet().showActionSheetWithOptions; const dispatch = useDispatch(); const globalSettings = useGlobalSelector(getGlobalSettings); const [stateDoNotMarkMessagesAsRead, setDoNotMarkMessagesAsRead] = useState(null); const doNotMarkMessagesAsRead = stateDoNotMarkMessagesAsRead ?? (!marksMessagesAsRead(props.narrow) || (() => { switch (globalSettings.markMessagesReadOnScroll) { case 'always': return false; case 'never': return true; case 'conversation-views-only': return !isConversationNarrow(props.narrow); default: ensureUnreachable(globalSettings.markMessagesReadOnScroll); return false; } })()); return { ...props, showActionSheetWithOptions, _, dispatch, backgroundData: useSelector(state => getBackgroundData(state, globalSettings)), fetching: useSelector(state => getFetchingForNarrow(state, props.narrow)), messageListElementsForShownMessages: getMessageListElementsMemoized( props.messages, props.narrow, ), typingUsers: useSelector(state => getCurrentTypingUsers(state, props.narrow)), doNotMarkMessagesAsRead, setDoNotMarkMessagesAsRead, }; } /** * The URL of the platform-specific assets folder. * * This will be a `file:` URL. */ // It could be perfectly reasonable for this to be an `http:` or `https:` // URL instead, at least in development. We'd then just need to adjust // the `originWhitelist` we pass to `WebView`. // // - On iOS: We can't easily hardcode this because it includes UUIDs. So we // bring it over the React Native bridge from our native module // ZLPConstants. It's a file URL because the app bundle's `resourceURL` is: // path_to_url // // - On Android: Different apps' WebViews see different (virtual) root // directories as `file:///`, and in particular the WebView provides // the APK's `assets/` directory as `file:///android_asset/`. [1] // We can easily hardcode that, so we do. // // [1] Oddly, this essential feature doesn't seem to be documented! It's // widely described in how-tos across the web and StackOverflow answers. // It's assumed in some related docs which mention it in passing, and // treated matter-of-factly in some Chromium bug threads. Details at: // path_to_url#narrow/stream/243-mobile-team/topic/android.20filesystem/near/796440 const assetsUrl = Platform.OS === 'ios' ? new URL(NativeModules.ZLPConstants.resourceURL) : new URL('file:///android_asset/'); /** * The URL of the webview-assets folder. * * This is the folder populated at build time by `tools/build-webview`. */ const webviewAssetsUrl = new URL('webview/', assetsUrl); /** * Effective URL of the MessageList webview. * * It points to `index.html` in the webview-assets folder, which * doesn't exist. * * It doesn't need to exist because we provide all HTML at * creation (or refresh) time. This serves only as a placeholder, * so that relative URLs (e.g., to `base.css`, which does exist) * and cross-domain security restrictions have somewhere to * believe that this document originates from. */ const baseUrl = new URL('index.html', webviewAssetsUrl); export default function MessageList(outerProps: OuterProps): React.Node { // NOTE: This component has an unusual lifecycle for a React component! // // In the React element which this render function returns, the bulk of // the interesting content is in one string, an HTML document, which will // get passed to a WebView. // // That WebView is a leaf of the tree that React sees. But there's a lot // of structure inside that HTML string, and there's UI state (in // particular, the scroll position) in the resulting page in the browser. // So when the content that would go in that HTML changes, we don't want // to just replace the entire HTML document. We want to use the structure // to make localized updates to the page in the browser, much as React // does automatically for changes in its tree. // // This is important not only for performance (computing all the HTML for // a long list of messages is expensive), but for correct behavior: if we // did change the HTML string passed to the WebView, the user would find // themself suddenly scrolled back to the bottom. // // So: // * We compute the HTML document just once and then always re-use that // initial value. // * When the props change, we compute a set of events describing the // changes, and send them to our code inside the webview to execute. // // See also docs/architecture/react.md . const props = useMessageListProps(outerProps); const navigation = useNavigation(); const theme = React.useContext(ThemeContext); const webviewRef = React.useRef<React$ElementRef<typeof WebView> | null>(null); const sendInboundEventsIsReady = React.useRef<boolean>(false); const unsentInboundEvents = React.useRef<WebViewInboundEvent[]>([]); /** * Send the given inbound-events to the inside-webview code. * * See `handleMessageEvent` in the inside-webview code for where these are * received and processed. */ const sendInboundEvents = React.useCallback( (uevents: $ReadOnlyArray<WebViewInboundEvent>): void => { if (webviewRef.current !== null && uevents.length > 0) { /* $FlowFixMe[incompatible-type]: This `postMessage` is undocumented; tracking as #3572. */ const secretWebView: { postMessage: (string, string) => void, ... } = webviewRef.current; secretWebView.postMessage(base64Utf8Encode(JSON.stringify(uevents)), '*'); } }, [], ); const propsRef = React.useRef(props); React.useEffect(() => { const lastProps = propsRef.current; if (props === lastProps) { // Nothing to update. (This happens in particular on first render.) return; } propsRef.current = props; // Account for the new props by sending any needed inbound-events to the // inside-webview code. const uevents = generateInboundEvents(lastProps, props); if (sendInboundEventsIsReady.current) { sendInboundEvents(uevents); } else { unsentInboundEvents.current.push(...uevents); } }, [props, sendInboundEvents]); const handleMessage = React.useCallback( (event: { +nativeEvent: { +data: string, ... }, ... }) => { const eventData: WebViewOutboundEvent = JSON.parse(event.nativeEvent.data); if (eventData.type === 'ready') { sendInboundEventsIsReady.current = true; sendInboundEvents([{ type: 'ready' }, ...unsentInboundEvents.current]); unsentInboundEvents.current = []; } else { // Instead of closing over `props` itself, we indirect through // `propsRef`, which gets updated by the effect above. // // That's because unlike in a typical component, the UI this acts as // a UI callback for isn't based on the current props, but on the // data we've communicated through inbound-events. (See discussion // at top of component.) So that's the data we want to refer to // when interpreting the user's interaction; and `propsRef` is what // the effect above updates in sync with sending those events. // // (The distinction may not matter much here in practice. But a // nice bonus of this way is that we avoid re-renders of // SinglePageWebView, potentially a helpful optimization.) handleWebViewOutboundEvent(propsRef.current, navigation, eventData); } }, [sendInboundEvents, navigation], ); // We compute the page contents as an HTML string just once (*), on this // MessageList's first render. See discussion at top of function. // // Note this means that all changes to props must be handled by // inbound-events, or they simply won't be handled at all. // // (*) The logic below doesn't quite look that way -- what it says is that // we compute the HTML on first render, and again any time the theme // changes. Until we implement #5533, this comes to the same thing, // because the only way to change the theme is for the user to // navigate out to our settings UI. We write it this way so that it // won't break with #5533. // // On the other hand, this means that if the theme changes we'll get // the glitch described at top of function, scrolling the user to the // bottom. Better than mismatched themes, but not ideal. A nice bonus // followup on #5533 would be to add an inbound-event for changing the // theme, and then truly compute the HTML just once. const htmlRef = React.useRef(null); const prevTheme = usePrevious(theme); if (htmlRef.current == null || theme !== prevTheme) { const { backgroundData, messageListElementsForShownMessages, initialScrollMessageId, showMessagePlaceholders, doNotMarkMessagesAsRead, _, } = props; const contentHtml = messageListElementsForShownMessages .map(element => messageListElementHtml({ backgroundData, element, _ })) .join(''); const { auth } = backgroundData; htmlRef.current = getHtml( contentHtml, theme.themeName, { scrollMessageId: initialScrollMessageId, auth, showMessagePlaceholders, doNotMarkMessagesAsRead, }, backgroundData.serverEmojiData, ); } return ( <SinglePageWebView html={htmlRef.current} baseUrl={baseUrl} decelerationRate="normal" style={React.useMemo(() => ({ backgroundColor: 'transparent' }), [])} ref={webviewRef} onMessage={handleMessage} onError={React.useCallback(event => { console.error(event); // eslint-disable-line no-console }, [])} /> ); } ```
/content/code_sandbox/src/webview/MessageList.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,508
```javascript /* @flow strict-local */ import template from './template'; import type { Auth, ThemeName } from '../../types'; import css from '../css/css'; import htmlBody from './htmlBody'; import script from '../js/script'; import type { ServerEmojiData } from '../../api/modelTypes'; type InitOptionsType = {| scrollMessageId: number | null, auth: Auth, showMessagePlaceholders: boolean, doNotMarkMessagesAsRead: boolean, |}; /** * Workaround for a WebKit CSS transitions bug affecting both iOS and Android. * * The timestamp pills (and possibly other elements) have CSS transitions * defined for properties whose values are different from the default user-agent * specified values. * * When the relevant CSS rules were moved into a separate file in commit * 8fdb93b, this triggered the bug: the WebView started initially using its * default values, and only switching to the stylesheet-specified values once * they were loaded. Since this switch included the addition of transition rules, * the WebView applied the transition. This led to all the timestamp pills * starting (visually) in the flyout state. * * There are many possible fixes to this, including: * - reworking the transitions such that their start states are all equivalent * to `initial`; * - moving (at least) the CSS rules with transitions into inline stylesheets * within the generated HTML; and/or * - the following bizarre, but minimally intrusive, hack. * * * See: * - path_to_url * - path_to_url */ const webkitBugWorkaround: string = '<script> </script>'; export default ( content: string, theme: ThemeName, initOptions: InitOptionsType, serverEmojiData: ServerEmojiData | null, ): string => template` $!${script(initOptions.scrollMessageId, initOptions.auth, initOptions.doNotMarkMessagesAsRead)} $!${css(theme, serverEmojiData)} <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <body style="overflow-x: hidden;"> $!${htmlBody(content, initOptions.showMessagePlaceholders)} $!${webkitBugWorkaround} </body> `; ```
/content/code_sandbox/src/webview/html/html.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
477
```javascript /* @flow strict-local */ import { PixelRatio } from 'react-native'; import template from './template'; import type { UserOrBot } from '../../types'; const typingAvatar = (realm: URL, user: UserOrBot): string => template` <div class="avatar"> <img class="avatar-img" data-sender-id="${user.user_id}" src="${user.avatar_url .get( // 48 logical pixels; see `.avatar` and `.avatar img` in // src/webview/static/base.css. PixelRatio.getPixelSizeForLayoutSize(48), ) .toString()}"> </div> `; export default (realm: URL, users: $ReadOnlyArray<UserOrBot>): string => template` $!${users.map(user => typingAvatar(realm, user)).join('')} <div class="content"> <span></span> <span></span> <span></span> </div> `; ```
/content/code_sandbox/src/webview/html/messageTypingAsHtml.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
207
```javascript /* @flow strict-local */ import invariant from 'invariant'; import template from './template'; import { ensureUnreachable } from '../../types'; import type { GetText, HeaderMessageListElement } from '../../types'; import type { BackgroundData } from '../backgroundData'; import { streamNarrow, topicNarrow, pmNarrowFromRecipients, keyFromNarrow, } from '../../utils/narrow'; import { foregroundColorFromBackground } from '../../utils/color'; import { humanDate } from '../../utils/date'; import { pmUiRecipientsFromMessage, pmKeyRecipientsFromMessage, streamNameOfStreamMessage, } from '../../utils/recipient'; import { base64Utf8Encode } from '../../utils/encoding'; import { isTopicFollowed } from '../../mute/muteModel'; import { getFullNameOrMutedUserText } from '../../users/userSelectors'; const renderTopic = message => // TODO: pin down if '' happens, and what its proper semantics are. message.match_subject !== undefined && message.match_subject !== '' ? message.match_subject : template`${message.subject}`; /** * The HTML string for a message-list element of the "header" type. * * This is a private helper of messageListElementHtml. */ export default ( { mute, ownUser, subscriptions, allUsersById, mutedUsers, enableGuestUserIndicator, }: BackgroundData, element: HeaderMessageListElement, _: GetText, ): string => { const { subsequentMessage: message, style: headerStyle } = element; if (message.type === 'stream') { const streamName = streamNameOfStreamMessage(message); const topicNarrowStr = keyFromNarrow(topicNarrow(message.stream_id, message.subject)); const topicHtml = renderTopic(message); const isFollowed = isTopicFollowed(message.stream_id, message.subject, mute); if (headerStyle === 'topic+date') { return template`\ <div class="msglist-element header-wrapper header topic-header" data-narrow="${base64Utf8Encode(topicNarrowStr)}" data-msg-id="${message.id}" > <div class="topic-text" data-followed="${isFollowed}">$!${topicHtml}</div> <div class="topic-date">${humanDate(new Date(message.timestamp * 1000))}</div> </div>`; } else if (headerStyle === 'full') { const subscription = subscriptions.get(message.stream_id); const backgroundColor = subscription ? subscription.color : 'hsl(0, 0%, 80%)'; const textColor = foregroundColorFromBackground(backgroundColor); const streamNarrowStr = keyFromNarrow(streamNarrow(message.stream_id)); return template`\ <div class="msglist-element header-wrapper header stream-header topic-header" data-msg-id="${message.id}" data-narrow="${base64Utf8Encode(topicNarrowStr)}" > <div class="header stream-text" style="color: ${textColor}; background: ${backgroundColor}" data-narrow="${base64Utf8Encode(streamNarrowStr)}"> # ${streamName} </div> <div class="topic-text" data-followed="${isFollowed}">$!${topicHtml}</div> <div class="topic-date">${humanDate(new Date(message.timestamp * 1000))}</div> </div>`; } else { ensureUnreachable(headerStyle); throw new Error(); } } else if (message.type === 'private') { invariant( headerStyle === 'full', 'expected headerStyle to be "full" for PM; see getMessageListElements', ); const keyRecipients = pmKeyRecipientsFromMessage(message, ownUser.user_id); const narrowObj = pmNarrowFromRecipients(keyRecipients); const narrowStr = keyFromNarrow(narrowObj); const uiRecipients = pmUiRecipientsFromMessage(message, ownUser.user_id); return template`\ <div class="msglist-element header-wrapper private-header header" data-narrow="${base64Utf8Encode(narrowStr)}" data-msg-id="${message.id}" > ${uiRecipients .map(r => { const user = allUsersById.get(r.id) ?? null; // TODO use italics for "(guest)" return _( getFullNameOrMutedUserText({ user, mutedUsers, enableGuestUserIndicator, fallback: r.full_name, }), ); }) .sort() .join(', ')} </div>`; } else { ensureUnreachable(message.type); throw new Error(); } }; ```
/content/code_sandbox/src/webview/html/header.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,002
```javascript /* @flow strict-local */ import * as eg from '../../../__tests__/lib/exampleData'; import header from '../header'; import type { BackgroundData } from '../../backgroundData'; import { makeMuteState } from '../../../mute/__tests__/mute-testlib'; import { mock_ } from '../../../__tests__/lib/intl'; const backgroundData: BackgroundData = ({ mute: makeMuteState([]), ownEmail: eg.selfUser.email, subscriptions: [eg.stream], streams: new Map([[eg.stream.stream_id, eg.stream]]), }: $FlowFixMe); describe('header', () => { test('correctly encodes `<` in topic, in stream narrow', () => { const m = eg.streamMessage({ subject: '1 < 2' }); const h = header( backgroundData, { type: 'header', key: [m.id, 1], style: 'topic+date', subsequentMessage: m, }, mock_, ); expect(h).not.toContain('1 < 2'); expect(h).toContain('1 &lt; 2'); expect(h).not.toContain('1 &amp;lt; 2'); }); // TODO: test other cases, and other pieces of data (stream name, user names, etc.) }); ```
/content/code_sandbox/src/webview/html/__tests__/header-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
282
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import escape from 'lodash.escape'; import template from '../template'; describe('template', () => { const evil = '<alert />&amp;'; const escaped = escape(evil); test('interpolates', () => { expect(template``).toEqual(''); expect(template`a`).toEqual('a'); expect(template`a${'b'}c`).toEqual('abc'); }); test('escapes HTML', () => { expect(template`a${evil}c`).toEqual(`a${escaped}c`); }); test('optionally preserves HTML', () => { expect(template`a$!${evil}c`).toEqual(`a${evil}c`); }); test('has an escape for the option', () => { expect(template`a$\!${evil}c`).toEqual(`a$!${escaped}c`); }); }); ```
/content/code_sandbox/src/webview/html/__tests__/template-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
200
```javascript /* @flow strict-local */ import messageTypingAsHtml from '../messageTypingAsHtml'; import * as eg from '../../../__tests__/lib/exampleData'; describe('typing', () => { it('escapes &< (e.g., in `avatar_url` and `email`', () => { const name = '&<name'; const user = eg.makeUser({ full_name: name, email: `${name}@example.com` }); expect(messageTypingAsHtml(eg.realm, [user])).not.toContain('&<'); }); }); ```
/content/code_sandbox/src/webview/html/__tests__/render-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
118
```javascript /* @flow strict-local */ import { PixelRatio } from 'react-native'; import invariant from 'invariant'; import formatDistanceToNow from 'date-fns/formatDistanceToNow'; import * as poll_data from '@zulip/shared/lib/poll_data'; import template from './template'; import type { AggregatedReaction, FlagsState, GetText, Message, MessageLike, Outbox, MessageMessageListElement, Reaction, SubmessageData, UserId, WidgetData, UserStatus, } from '../../types'; import type { BackgroundData } from '../backgroundData'; import { shortTime } from '../../utils/date'; import aggregateReactions from '../../reactions/aggregateReactions'; import { displayCharacterForUnicodeEmojiCode } from '../../emoji/data'; import processAlertWords from './processAlertWords'; import * as logging from '../../utils/logging'; import { getUserStatusFromModel } from '../../user-statuses/userStatusesCore'; import { getFullNameOrMutedUserText, getFullNameText } from '../../users/userSelectors'; const messageTagsAsHtml = (isStarred: boolean, timeEdited: number | void): string => { const pieces = []; if (timeEdited !== undefined) { const editedTime = formatDistanceToNow(timeEdited * 1000); pieces.push(template`<span class="message-tag">edited ${editedTime} ago</span>`); } if (isStarred) { pieces.push('<span class="message-tag">starred</span>'); } return !pieces.length ? '' : template`<div class="message-tags">$!${pieces.join('')}</div>`; }; // Like get_display_full_names in the web app's people.js, but also gives // "You" so callers don't have to. const getDisplayFullNames = (userIds, backgroundData, _) => { const { allUsersById, mutedUsers, ownUser, enableGuestUserIndicator } = backgroundData; return userIds.map(id => { const user = allUsersById.get(id); if (!user) { logging.warn('render reaction: no user for ID', { id }); return '?'; } if (id === ownUser.user_id) { return _('You'); } // TODO use italics for "(guest)" return _(getFullNameOrMutedUserText({ user, mutedUsers, enableGuestUserIndicator })); }); }; const messageReactionAsHtml = ( backgroundData: BackgroundData, reaction: AggregatedReaction, shouldShowNames: boolean, _: GetText, ): string => { const { allImageEmojiById } = backgroundData; return template`<span onClick="" class="reaction${reaction.selfReacted ? ' self-voted' : ''}" data-name="${reaction.name}" data-code="${reaction.code}" data-type="${reaction.type}">$!${ allImageEmojiById[reaction.code] ? template`<img src="${allImageEmojiById[reaction.code].source_url}"/>` : displayCharacterForUnicodeEmojiCode(reaction.code, backgroundData.serverEmojiData) }&nbsp;${ // The web app puts this condition in get_vote_text in its reactions.js. shouldShowNames ? getDisplayFullNames(reaction.users, backgroundData, _).join(', ') : reaction.count }</span>`; }; const messageReactionListAsHtml = ( backgroundData: BackgroundData, reactions: $ReadOnlyArray<Reaction>, _: GetText, ): string => { const { ownUser, displayEmojiReactionUsers } = backgroundData; if (reactions.length === 0) { return ''; } // See the web app's get_vote_text in its reactions.js. const shouldShowNames = displayEmojiReactionUsers // The API lets clients choose the threshold. We use 3 like the web app. && reactions.length <= 3; const htmlList = aggregateReactions(reactions, ownUser.user_id).map(r => messageReactionAsHtml(backgroundData, r, shouldShowNames, _), ); return template`<div class="reaction-list">$!${htmlList.join('')}</div>`; }; const messageBody = (backgroundData: BackgroundData, message: Message | Outbox, _: GetText) => { const { alertWords, flags } = backgroundData; const { id, isOutbox, last_edit_timestamp, match_content, reactions } = (message: MessageLike); const content = match_content ?? message.content; return template`\ $!${processAlertWords(content, id, alertWords, flags)} $!${isOutbox === true ? '<div class="loading-spinner outbox-spinner"></div>' : ''} $!${messageTagsAsHtml(!!flags.starred[id], last_edit_timestamp)} $!${messageReactionListAsHtml(backgroundData, reactions, _)}`; }; /** * Render the body of a message that has submessages. * * Must not be called on a message without any submessages. */ const widgetBody = (message: Message, ownUserId: UserId) => { invariant( message.submessages !== undefined && message.submessages.length > 0, 'should have submessages', ); const widgetSubmessages: Array<{ sender_id: number, content: SubmessageData, ... }> = message.submessages .filter(submessage => submessage.msg_type === 'widget') .sort((m1, m2) => m1.id - m2.id) .map(submessage => ({ sender_id: submessage.sender_id, content: JSON.parse(submessage.content), })); const errorMessage = template`\ $!${message.content} <div class="special-message" ><p>Interactive message</p ><p>To use, open on web or desktop</p ></div>`; const pollWidget = widgetSubmessages.shift(); if (!pollWidget || !pollWidget.content) { return errorMessage; } /* $FlowFixMe[incompatible-type]: The first widget submessage should be a `WidgetData`; see jsdoc on `SubmessageData`. */ const pollWidgetContent: WidgetData = pollWidget.content; if (pollWidgetContent.widget_type !== 'poll') { return errorMessage; } if (pollWidgetContent.extra_data == null) { // We don't expect this to happen in general, but there are some malformed // messages lying around that will trigger this [1]. The code here is slightly // different the webapp code, but mostly because the current webapp // behaviour seems accidental: an error is printed to the console, and the // code that is written to handle the situation is never reached. Instead // of doing that, we've opted to catch this case here, and print out the // message (which matches the behaviour of the webapp, minus the console // error, although it gets to that behaviour in a different way). The bug // tracking fixing this on the webapp side is zulip/zulip#19145. // [1]: path_to_url#narrow/streams/public/near/582872 return template`$!${message.content}`; } const pollData = new poll_data.PollData({ message_sender_id: message.sender_id, current_user_id: ownUserId, is_my_poll: message.sender_id === ownUserId, question: pollWidgetContent.extra_data.question ?? '', options: pollWidgetContent.extra_data.options ?? [], // TODO: Implement this. comma_separated_names: () => '', report_error_function: (msg: string) => { logging.error(msg); }, }); for (const pollEvent of widgetSubmessages) { pollData.handle_event(pollEvent.sender_id, pollEvent.content); } const parsedPollData = pollData.get_widget_data(); return template`\ <div class="poll-widget"> <p class="poll-question">${parsedPollData.question}</p> <ul> $!${parsedPollData.options .map( option => template` <li> <button class="poll-vote" data-voted="${option.current_user_vote ? 'true' : 'false'}" data-key="${option.key}" >${option.count}</button> <span class="poll-option">${option.option}</span> </li>`, ) .join('')} </ul> </div>`; }; export const flagsStateToStringList = (flags: FlagsState, id: number): $ReadOnlyArray<string> => Object.keys(flags).filter(key => flags[key][id]); const senderEmojiStatus = ( emoji: UserStatus['status_emoji'], backgroundData: BackgroundData, ): string => emoji ? backgroundData.allImageEmojiById[emoji.emoji_code] ? template`\ <img class="status-emoji" src="${backgroundData.allImageEmojiById[emoji.emoji_code].source_url}" />` : template`\ <span class="status-emoji">$!${displayCharacterForUnicodeEmojiCode( emoji.emoji_code, backgroundData.serverEmojiData, )}</span>` : ''; /** * The HTML string for a message-list element of the "message" type. * * This is a private helper of messageListElementHtml. */ export default ( backgroundData: BackgroundData, element: MessageMessageListElement, _: GetText, ): string => { const { message, isBrief } = element; const { id, timestamp } = message; const flagStrings = flagsStateToStringList(backgroundData.flags, id); const isUserMuted = !!message.sender_id && backgroundData.mutedUsers.has(message.sender_id); const divOpenHtml = template`\ <div class="msglist-element message ${isBrief ? 'message-brief' : 'message-full'}" id="msg-${id}" data-msg-id="${id}" data-mute-state="${isUserMuted ? 'hidden' : 'shown'}" $!${flagStrings.map(flag => template`data-${flag}="true" `).join('')} >`; const messageTime = shortTime(new Date(timestamp * 1000), backgroundData.twentyFourHourTime); const timestampHtml = (showOnRender: boolean) => template`\ <div class="time-container"> <div class="msg-timestamp ${showOnRender ? 'show' : ''}"> ${messageTime} </div> </div>`; const bodyHtml = message.submessages && message.submessages.length > 0 ? widgetBody(message, backgroundData.ownUser.user_id) : messageBody(backgroundData, message, _); if (isBrief) { return template`\ $!${divOpenHtml} <div class="content"> $!${timestampHtml(false)} $!${bodyHtml} </div> </div>`; } const { sender_id } = message; const sender = backgroundData.allUsersById.get(sender_id) ?? null; const senderFullName = _( // TODO use italics for "(guest)" getFullNameText({ user: sender, enableGuestUserIndicator: backgroundData.enableGuestUserIndicator, fallback: message.sender_full_name, }), ); const avatarUrl = message.avatar_url .get( // 48 logical pixels; see `.avatar` and `.avatar img` in // src/webview/static/base.css. PixelRatio.getPixelSizeForLayoutSize(48), ) .toString(); const subheaderHtml = template`\ <div class="subheader"> <div class="name-and-status-emoji" data-sender-id="${sender_id}"> ${senderFullName}$!${senderEmojiStatus( getUserStatusFromModel(backgroundData.userStatuses, sender_id).status_emoji, backgroundData, )} </div> <div class="static-timestamp">${messageTime}</div> </div>`; const mutedMessageHtml = isUserMuted ? template`\ <div class="special-message muted-message-explanation"> ${_('This message was hidden because it is from a user you have muted. Long-press to view.')} </div>` : ''; return template`\ $!${divOpenHtml} <div class="avatar"> <img src="${avatarUrl}" alt="${senderFullName}" class="avatar-img" data-sender-id="${sender_id}"> </div> <div class="content"> $!${subheaderHtml} $!${bodyHtml} </div> $!${mutedMessageHtml} </div>`; }; ```
/content/code_sandbox/src/webview/html/message.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,718
```javascript /* @flow strict-local */ export default ` body { color: hsl(210, 11%, 85%); background: hsl(212, 28%, 18%); } .poll-vote { color: hsl(210, 11%, 85%); } .topic-header { background: hsl(212, 13%, 38%); } .msg-timestamp { background: hsl(212, 28%, 25%); } .highlight { background-color: hsla(51, 100%, 64%, 0.42); } .message_inline_image img.image-loading-placeholder { content: url("images/loader-white.svg"); } `; ```
/content/code_sandbox/src/webview/css/cssNight.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
140
```javascript import processAlertWords from '../processAlertWords'; const alertWords = ['alertone', 'alerttwo', 'alertthree', 'al*rt.*s', '.+', 'emoji']; describe('processAlertWords', () => { test('if msg id is not in has_alert_word flags, return original content', () => { const flags = { has_alert_word: {}, }; expect(processAlertWords('some emoji text', 2, alertWords, flags)).toEqual('some emoji text'); }); test('if msg id is present in has_alert_word flags, process message content', () => { const flags = { has_alert_word: { 2: true, }, }; expect(processAlertWords('<p>another alertone message</p>', 2, alertWords, flags)).toEqual( "<p>another <span class='alert-word'>alertone</span> message</p>", ); }); test('if msg contains multiple alert words, wrap all', () => { const flags = { has_alert_word: { 2: true, }, }; expect( processAlertWords( '<p>another alertthreemessage alertone and then alerttwo</p>', 2, alertWords, flags, ), ).toEqual( "<p>another alertthreemessage <span class='alert-word'>alertone</span> and then <span class='alert-word'>alerttwo</span></p>", ); }); test('miscellaneous tests', () => { const flags = { has_alert_word: { 2: true, }, }; expect(processAlertWords('<p>gotta al*rt.*s all</p>', 2, alertWords, flags)).toEqual( "<p>gotta <span class='alert-word'>al*rt.*s</span> all</p>", ); expect( processAlertWords('<p>path_to_url 2, alertWords, flags), ).toEqual('<p>path_to_url expect(processAlertWords('<p>still alertone? me</p>', 2, alertWords, flags)).toEqual( "<p>still <span class='alert-word'>alertone</span>? me</p>", ); expect( processAlertWords( '<p>now with link <a href="path_to_url" target="_blank" title="path_to_url">www.alerttwo.us/foo/bar</a></p>', 2, alertWords, flags, ), ).toEqual( '<p>now with link <a href="path_to_url" target="_blank" title="path_to_url">www.<span class=\'alert-word\'>alerttwo</span>.us/foo/bar</a></p>', ); expect( processAlertWords( '<p>I <img alt=":heart:" class="emoji" src="/static/generated/emoji/images/emoji/unicode/2764.png" title="heart"> emoji!</p>', 2, alertWords, flags, ), ).toEqual( '<p>I <img alt=":heart:" class="emoji" src="/static/generated/emoji/images/emoji/unicode/2764.png" title="heart"> <span class=\'alert-word\'>emoji</span>!</p>', ); }); }); ```
/content/code_sandbox/src/webview/html/__tests__/processAlertWords-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
719
```javascript /* @flow strict-local */ import { Platform } from 'react-native'; import type { ThemeName } from '../../types'; import cssPygments from './cssPygments'; import cssEmojis from './cssEmojis'; import cssNight from './cssNight'; import type { ServerEmojiData } from '../../api/modelTypes'; /** * Fix KaTeX frac-line elements disappearing. * * This is a hack, but it's probably better than not having fraction lines on * low-resolution phones. It's only known to be useful under Chrome and Android, * so we only include it there. * * See, among others: * path_to_url * path_to_url * path_to_url * path_to_url */ const katexFraclineHackStyle = `<style id="katex-frac-line-hack"> .katex .mfrac .frac-line { border-bottom-width: 1px !important; } </style>`; export default (theme: ThemeName, serverEmojiData: ServerEmojiData | null): string => ` <link rel='stylesheet' type='text/css' href='./base.css'> <link rel='stylesheet' type='text/css' href='./katex/katex.min.css'> <style> ${theme === 'dark' ? cssNight : ''} ${cssPygments(theme === 'dark')} ${cssEmojis(serverEmojiData)} </style> <style id="style-hide-js-error-plain"> #js-error-plain, #js-error-plain-dummy { display: none; } </style> ${Platform.OS === 'android' ? katexFraclineHackStyle : '<!-- Safari -->'} <style id="generated-styles"></style> `; ```
/content/code_sandbox/src/webview/css/css.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
350