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 */ /* eslint-disable no-shadow */ import { useRef, useState, useCallback, useEffect, useMemo } from 'react'; import { TextInput } from 'react-native'; import type { SelectionChangeEvent } from 'react-native/Libraries/Components/TextInput/TextInput'; import { usePrevious } from './reactUtils'; type InputState = {| +value: string, +selection: {| +start: number, +end: number |} |}; /** * State management for an Input component that doesn't get passed `value` * or `selection`, i.e., an uncontrolled Input. * * For background on the concept, see * path_to_url * and our #2738 for the performance concerns that led us to use this in the * compose box. * * Returns: * - A ref to use for the TextInput * - The value and selection state * - Functions to set the value and selection * - Two callbacks that should be passed directly to the TextInput as props: * onChangeText, onSelectionChange. */ export default (initialState: {| +value?: InputState['value'], +selection?: InputState['selection'], |}): ([ {| current: React$ElementRef<typeof TextInput> | null |}, InputState, ((InputState => InputState['value']) | InputState['value']) => void, ((InputState => InputState['selection']) | InputState['selection']) => void, {| +onChangeText: string => void, +onSelectionChange: SelectionChangeEvent => void, |}, ]) => { const ref = useRef<React$ElementRef<typeof TextInput> | null>(null); const [state, setState] = useState<InputState>({ value: '', // default value selection: { start: 0, end: 0 }, // default value ...initialState, }); const setValueWasCalled = useRef<boolean>(false); const setValue = useCallback(updater => { setValueWasCalled.current = true; setState(state => ({ ...state, value: typeof updater === 'function' ? updater(state) : updater, })); }, []); const prevValue = usePrevious(state.value); useEffect(() => { if (prevValue !== state.value && setValueWasCalled.current) { // If the state change was requested from the JavaScript side, i.e., // not in response to a native-props change caused by the user's input // device, update the native props. ref.current?.setNativeProps({ text: state.value }); setValueWasCalled.current = false; } }); const setSelection = useCallback(() => { // TODO: Implement throw new Error('unimplemented!'); }, []); const inputCallbacks = useMemo( () => ({ onChangeText: (value: string) => { setState(state => ({ ...state, value })); }, onSelectionChange: (event: SelectionChangeEvent) => { const { selection } = event.nativeEvent; setState(state => ({ ...state, selection })); }, }), [], ); return [ref, state, setValue, setSelection, inputCallbacks]; }; ```
/content/code_sandbox/src/useUncontrolledInput.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
670
```javascript /* @flow strict-local */ const isDevelopment = process.env.NODE_ENV === 'development'; type Config = {| requestLongTimeoutMs: number, messagesPerRequest: number, messageListThreshold: number, enableReduxLogging: boolean, enableErrorConsoleLogging: boolean, appOwnDomains: $ReadOnlyArray<string>, |}; const config: Config = { // A completely unreasonable amount of time for a request, or // several retries of a request, to take. If this elapses, we're // better off giving up. requestLongTimeoutMs: 60 * 1000, messagesPerRequest: 100, messageListThreshold: 4000, enableReduxLogging: isDevelopment && !!global.btoa, enableErrorConsoleLogging: true, appOwnDomains: ['zulip.com', 'zulipchat.com', 'chat.zulip.org'], }; export default config; ```
/content/code_sandbox/src/config.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 React from 'react'; import type { Node } from 'react'; import { View, Image } from 'react-native'; import ZulipText from '../common/ZulipText'; import { createStyleSheet } from '../styles'; const styles = createStyleSheet({ description: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 8, }, icon: { width: 24, height: 24, marginRight: 8, }, name: { fontSize: 20, }, }); type Props = $ReadOnly<{| name: string, iconUrl: string, |}>; export default function RealmInfo(props: Props): Node { const { name, iconUrl } = props; return ( <View style={styles.description}> {iconUrl && <Image style={styles.icon} source={{ uri: iconUrl }} />} <ZulipText style={styles.name} text={name} /> </View> ); } ```
/content/code_sandbox/src/start/RealmInfo.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
225
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { ComponentType } from 'react'; import { View } from 'react-native'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import type { GlobalDispatch } from '../types'; import { createStyleSheet } from '../styles'; import { connectGlobal } from '../react-redux'; import * as api from '../api'; import ErrorMsg from '../common/ErrorMsg'; import Input from '../common/Input'; import PasswordInput from '../common/PasswordInput'; import Screen from '../common/Screen'; import WebLink from '../common/WebLink'; import ZulipButton from '../common/ZulipButton'; import ViewPlaceholder from '../common/ViewPlaceholder'; import ZulipText from '../common/ZulipText'; import { isValidEmailFormat } from '../utils/misc'; import { loginSuccess } from '../actions'; import ZulipTextIntl from '../common/ZulipTextIntl'; const styles = createStyleSheet({ linksTouchable: { marginTop: 10, alignItems: 'flex-end', }, forgotPasswordText: { textAlign: 'right', }, }); type OuterProps = $ReadOnly<{| // These should be passed from React Navigation navigation: AppNavigationProp<'password-auth'>, route: RouteProp<'password-auth', {| realm: URL, requireEmailFormat: boolean |}>, |}>; type SelectorProps = $ReadOnly<{||}>; type Props = $ReadOnly<{| ...OuterProps, dispatch: GlobalDispatch, ...SelectorProps, |}>; type State = {| email: string, password: string, error: string, progress: boolean, |}; class PasswordAuthScreenInner extends PureComponent<Props, State> { state = { progress: false, email: '', password: '', error: '', }; tryPasswordLogin = async () => { const { dispatch, route } = this.props; const { requireEmailFormat, realm } = route.params; const { email, password } = this.state; this.setState({ progress: true, error: undefined }); try { const fetchedKey = await api.fetchApiKey({ realm, apiKey: '', email }, email, password); this.setState({ progress: false }); dispatch(loginSuccess(realm, fetchedKey.email, fetchedKey.api_key)); } catch { // TODO: show message for *actual* error, from server; e.g. #4571 this.setState({ progress: false, error: requireEmailFormat ? 'Wrong email or password. Try again.' : 'Wrong username or password. Try again.', }); } }; validateForm = () => { const { requireEmailFormat } = this.props.route.params; const { email, password } = this.state; if (requireEmailFormat && !isValidEmailFormat(email)) { this.setState({ error: 'Enter a valid email address' }); } else if (!requireEmailFormat && email.length === 0) { this.setState({ error: 'Enter a username' }); } else if (!password) { this.setState({ error: 'Enter a password' }); } else { this.tryPasswordLogin(); } }; render() { const { requireEmailFormat, realm } = this.props.route.params; const { email, password, progress, error } = this.state; const isButtonDisabled = password.length === 0 || email.length === 0 || (requireEmailFormat && !isValidEmailFormat(email)); return ( <Screen title="Log in" centerContent padding keyboardShouldPersistTaps="always" shouldShowLoadingBanner={false} > <Input autoFocus={email.length === 0} autoCapitalize="none" autoCorrect={false} blurOnSubmit={false} keyboardType={requireEmailFormat ? 'email-address' : 'default'} placeholder={requireEmailFormat ? 'Email' : 'Username'} defaultValue={email} onChangeText={newEmail => this.setState({ email: newEmail })} /> <ViewPlaceholder height={8} /> <PasswordInput autoFocus={email.length !== 0} placeholder="Password" value={password} onChangeText={newPassword => this.setState({ password: newPassword })} blurOnSubmit={false} onSubmitEditing={this.validateForm} /> <ViewPlaceholder height={16} /> <ZulipButton disabled={isButtonDisabled} text="Log in" progress={progress} onPress={this.validateForm} /> <ErrorMsg error={error} /> <View style={styles.linksTouchable}> <ZulipText style={styles.forgotPasswordText}> <WebLink url={new URL('/accounts/password/reset/', realm)}> <ZulipTextIntl inheritColor text="Forgot password?" /> </WebLink> </ZulipText> </View> </Screen> ); } } const PasswordAuthScreen: ComponentType<OuterProps> = connectGlobal<{||}, _, _>()( PasswordAuthScreenInner, ); export default PasswordAuthScreen; ```
/content/code_sandbox/src/start/PasswordAuthScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,115
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { ComponentType } from 'react'; import { Linking, Platform } from 'react-native'; import type { AppleAuthenticationCredential } from 'expo-apple-authentication'; import * as AppleAuthentication from 'expo-apple-authentication'; import type { ServerSettings, AuthenticationMethods, ExternalAuthenticationMethod, } from '../api/settings/getServerSettings'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import isAppOwnDomain from '../isAppOwnDomain'; import type { GlobalDispatch } from '../types'; import { IconApple, IconPrivate, IconGoogle, IconGitHub, IconWindows, IconTerminal, } from '../common/Icons'; import type { SpecificIconType } from '../common/Icons'; import { connectGlobal } from '../react-redux'; import styles from '../styles'; import Centerer from '../common/Centerer'; import Screen from '../common/Screen'; import ZulipButton from '../common/ZulipButton'; import RealmInfo from './RealmInfo'; import { encodeParamsForUrl } from '../utils/url'; import * as webAuth from './webAuth'; import { loginSuccess } from '../actions'; import IosCompliantAppleAuthButton from './IosCompliantAppleAuthButton'; import { openLinkEmbedded } from '../utils/openLink'; /** * Describes a method for authenticating to the server. * * Different servers and orgs/realms accept different sets of auth methods, * described in the /server_settings response; see api.getServerSettings * and path_to_url . */ type AuthenticationMethodDetails = {| /** An identifier-style name used in the /server_settings API. */ name: string, /** A name to show in the UI. */ displayName: string, Icon: SpecificIconType, action: 'dev' | 'password' | {| url: string |}, |}; // Methods that don't show up in external_authentication_methods. const availableDirectMethods: $ReadOnlyArray<AuthenticationMethodDetails> = [ { name: 'dev', displayName: 'dev account', Icon: IconTerminal, action: 'dev', }, { name: 'password', displayName: 'password', Icon: IconPrivate, action: 'password', }, { name: 'ldap', displayName: 'password', Icon: IconPrivate, action: 'password', }, { // This one might move to external_authentication_methods in the future. name: 'remoteuser', displayName: 'SSO', Icon: IconPrivate, action: { url: 'accounts/login/sso/' }, }, ]; const externalMethodIcons = new Map([ ['google', IconGoogle], ['github', IconGitHub], ['azuread', IconWindows], ['apple', IconApple], ]); /** Exported for tests only. */ export const activeAuthentications = ( authenticationMethods: AuthenticationMethods, externalAuthenticationMethods: $ReadOnlyArray<ExternalAuthenticationMethod>, ): $ReadOnlyArray<AuthenticationMethodDetails> => { const result = []; // A server might intend some of these, such as 'dev' or 'password', but // omit them in external_authentication_methods. The only sign that // they're intended is their presence in authentication_methods even // though that's marked as deprecated in 2.1. Discussion: // path_to_url#narrow/stream/412-api-documentation/topic/audit.20for.20change.20entries.20vs.2E.20central.20changelog/near/1404115 availableDirectMethods.forEach(auth => { if (!authenticationMethods[auth.name]) { return; } if (auth.name === 'ldap' && authenticationMethods.password === true) { // For either of these, we show a button that looks and behaves // exactly the same. When both are enabled, dedupe them. return; } result.push(auth); }); externalAuthenticationMethods.forEach(method => { if (result.some(({ name }) => name === method.name)) { // Ignore duplicate. return; } // The server provides icons as image URLs; but we have our own built // in, which we don't have to load and can color to match the button. // TODO perhaps switch to server's, for the sake of SAML where ours is // generic and the server may have a more specific one. const Icon = externalMethodIcons.get(method.name) ?? IconPrivate; result.push({ name: method.name, displayName: method.display_name, Icon, action: { url: method.login_url }, }); }); return result; }; type OuterProps = $ReadOnly<{| // These should be passed from React Navigation navigation: AppNavigationProp<'auth'>, route: RouteProp< 'auth', {| // Keep constant through the life of an 'auth' route: don't // `navigation.navigate` or `navigation.setParams` or do anything else // that can change this. We use it to identify the server to the user, // and also to identify which server to send auth credentials to. So // we mustn't let it jump out from under the user. serverSettings: ServerSettings, |}, >, |}>; type SelectorProps = $ReadOnly<{||}>; type Props = $ReadOnly<{| ...OuterProps, dispatch: GlobalDispatch, ...SelectorProps, |}>; let otp = ''; /** * An event emitted by `Linking`. * * Determined by reading the implementation source code, and documentation: * path_to_url * * TODO move this to a libdef, and/or get an explicit type into upstream. */ type LinkingEvent = { url: string, ... }; class AuthScreenInner extends PureComponent<Props> { componentDidMount() { Linking.addEventListener('url', this.endWebAuth); Linking.getInitialURL().then((initialUrl: ?string) => { if (initialUrl !== null && initialUrl !== undefined) { this.endWebAuth({ url: initialUrl }); } }); const { serverSettings } = this.props.route.params; const authList = activeAuthentications( serverSettings.authentication_methods, serverSettings.external_authentication_methods, ); if (authList.length === 1) { this.handleAuth(authList[0]); } } componentWillUnmount() { Linking.removeEventListener('url', this.endWebAuth); } /** * Hand control to the browser for an external auth method. * * @param url The `login_url` string, a relative URL, from an * `external_authentication_method` object from `/server_settings`. */ beginWebAuth = async (url: string) => { const { serverSettings } = this.props.route.params; otp = await webAuth.generateOtp(); webAuth.openBrowser(new URL(url, serverSettings.realm_uri).toString(), otp); }; endWebAuth = (event: LinkingEvent) => { webAuth.closeBrowser(); const { dispatch } = this.props; const { serverSettings } = this.props.route.params; const auth = webAuth.authFromCallbackUrl(event.url, otp, serverSettings.realm_uri); if (auth) { dispatch(loginSuccess(auth.realm, auth.email, auth.apiKey)); } }; handleDevAuth = () => { const { serverSettings } = this.props.route.params; this.props.navigation.push('dev-auth', { realm: serverSettings.realm_uri, }); }; handlePassword = () => { const { serverSettings } = this.props.route.params; const realm = serverSettings.realm_uri; this.props.navigation.push('password-auth', { realm, requireEmailFormat: serverSettings.require_email_format_usernames, }); }; handleNativeAppleAuth = async () => { const { serverSettings } = this.props.route.params; const state = await webAuth.generateRandomToken(); const credential: AppleAuthenticationCredential = await AppleAuthentication.signInAsync({ state, requestedScopes: [ AppleAuthentication.AppleAuthenticationScope.FULL_NAME, AppleAuthentication.AppleAuthenticationScope.EMAIL, ], }); if (credential.state !== state) { throw new Error('`state` mismatch'); } otp = await webAuth.generateOtp(); const params = encodeParamsForUrl({ mobile_flow_otp: otp, native_flow: true, id_token: credential.identityToken, }); openLinkEmbedded(new URL(`/complete/apple/?${params}`, serverSettings.realm_uri)); // Currently, the rest is handled with the `zulip://` redirect, // same as in the web flow. // // TODO: Maybe have an endpoint we can just send a request to, // with `fetch`, and get the API key right away, without ever // having to open the browser. }; canUseNativeAppleFlow = async () => { const { serverSettings } = this.props.route.params; if (!(Platform.OS === 'ios' && (await AppleAuthentication.isAvailableAsync()))) { return false; } // The native flow for Apple auth assumes that the app and the server // are operated by the same organization, so that for a user to // entrust private information to either one is the same as entrusting // it to the other. Check that this realm is on such a server. // // (For other realms, we'll simply fall back to the web flow, which // handles things appropriately without relying on that assumption.) return isAppOwnDomain(serverSettings.realm_uri); }; handleAuth = async (method: AuthenticationMethodDetails) => { const { action } = method; if (action === 'dev') { this.handleDevAuth(); } else if (action === 'password') { this.handlePassword(); } else if (method.name === 'apple' && (await this.canUseNativeAppleFlow())) { this.handleNativeAppleAuth(); } else { this.beginWebAuth(action.url); } }; render() { const { serverSettings } = this.props.route.params; return ( <Screen title="Log in" centerContent padding shouldShowLoadingBanner={false}> <Centerer> <RealmInfo name={serverSettings.realm_name} iconUrl={new URL(serverSettings.realm_icon, serverSettings.realm_uri).toString()} /> {activeAuthentications( serverSettings.authentication_methods, serverSettings.external_authentication_methods, ).map(auth => auth.name === 'apple' && Platform.OS === 'ios' ? ( <IosCompliantAppleAuthButton key={auth.name} style={styles.halfMarginTop} onPress={() => this.handleAuth(auth)} /> ) : ( <ZulipButton key={auth.name} style={styles.halfMarginTop} secondary text={{ text: 'Sign in with {method}', values: { method: auth.displayName }, }} Icon={auth.Icon} onPress={() => this.handleAuth(auth)} /> ), )} </Centerer> </Screen> ); } } const AuthScreen: ComponentType<OuterProps> = connectGlobal<{||}, _, _>()(AuthScreenInner); export default AuthScreen; ```
/content/code_sandbox/src/start/AuthScreen.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 { NativeModules, Platform } from 'react-native'; import * as WebBrowser from 'expo-web-browser'; import type { Auth } from '../types'; import { openLinkEmbedded } from '../utils/openLink'; import { isUrlOnRealm, tryParseUrl } from '../utils/url'; import { base64ToHex, hexToAscii, xorHexStrings } from '../utils/encoding'; /* Logic for authenticating the user to Zulip through a browser. Specifically, this handles auth flows we don't know the specifics of here in the app's code. To handle that, we send the user to some URL in a browser, so they can go through whatever flow the server (or an auth provider it redirects them to in turn) wants to take them through. To close the loop when the authentication is complete, there's a particular protocol we carry out with the Zulip server, involving `zulip://` URLs and XOR-ing with a one-time pad named `mobile_flow_otp`. No docs on this protocol seem to exist. But see: * the implementations here and in the server * this 2019 chat message with a nice list of the steps: path_to_url#narrow/stream/16-desktop/topic/desktop.20app.20OAuth/near/803919 */ export const generateRandomToken = async (): Promise<string> => { if (Platform.OS === 'android') { return new Promise((resolve, reject) => { NativeModules.RNSecureRandom.randomBase64(32, (err, result) => { if (err) { reject(err); } resolve(base64ToHex(result)); }); }); } else { const rand = await NativeModules.UtilManager.randomBase64(32); return base64ToHex(rand); } }; // Generate a one time pad (OTP) which the server XORs the API key with // in its response to protect against credentials intercept export const generateOtp = async (): Promise<string> => generateRandomToken(); // TODO: Take URL object instead of string (but make a copy on which to // mutate `searchParams`) export const openBrowser = (url: string, otp: string) => { const urlCopy = new URL(url); urlCopy.searchParams.set('mobile_flow_otp', otp); openLinkEmbedded(urlCopy); }; export const closeBrowser = () => { if (Platform.OS === 'android') { NativeModules.CloseAllCustomTabsAndroid.closeAll(); } else { WebBrowser.dismissBrowser(); } }; /** * Decode an API key from the Zulip mobile-auth-via-web protocol. * * Corresponds to `otp_decrypt_api_key` on the server. */ const extractApiKey = (encoded: string, otp: string) => hexToAscii(xorHexStrings(encoded, otp)); export const authFromCallbackUrl = (callbackUrl: string, otp: string, realm: URL): Auth | null => { // callback format expected: zulip://login?realm={}&email={}&otp_encrypted_api_key={} const url = tryParseUrl(callbackUrl); if (!url) { return null; } const callbackRealmStr = url.searchParams.get('realm'); if (callbackRealmStr === null) { return null; } const callbackRealm = tryParseUrl(callbackRealmStr); if (!callbackRealm || !isUrlOnRealm(callbackRealm, realm)) { return null; } const email = url.searchParams.get('email'); const otpEncryptedApiKey = url.searchParams.get('otp_encrypted_api_key'); if ( url.host === 'login' && otp && email !== null && otpEncryptedApiKey !== null && otpEncryptedApiKey.length === otp.length ) { const apiKey = extractApiKey(otpEncryptedApiKey, otp); return { realm, email, apiKey }; } return null; }; ```
/content/code_sandbox/src/start/webAuth.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
857
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import { Keyboard, View, TextInput } from 'react-native'; import { useFocusEffect } from '@react-navigation/native'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import ZulipTextIntl from '../common/ZulipTextIntl'; import Screen from '../common/Screen'; import ZulipButton from '../common/ZulipButton'; import { tryParseUrl } from '../utils/url'; import { fetchServerSettings } from '../message/fetchActions'; import { ThemeContext } from '../styles/theme'; import { createStyleSheet, HALF_COLOR } from '../styles'; import { showErrorAlert } from '../utils/info'; import { TranslationContext } from '../boot/TranslationProvider'; import type { LocalizableText } from '../types'; import { getGlobalSettings } from '../directSelectors'; import { useGlobalSelector } from '../react-redux'; import { BRAND_COLOR } from '../styles/constants'; import ZulipText from '../common/ZulipText'; import WebLink from '../common/WebLink'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'realm-input'>, route: RouteProp<'realm-input', {| initial: boolean | void |}>, |}>; enum ValidationError { Empty = 0, InvalidUrl = 1, NoUseEmail = 2, UnsupportedSchemeZulip = 3, UnsupportedSchemeOther = 4, } function validationErrorMsg(validationError: ValidationError): LocalizableText { switch (validationError) { case ValidationError.Empty: return 'Please enter a URL.'; case ValidationError.InvalidUrl: return 'Please enter a valid URL.'; case ValidationError.NoUseEmail: return 'Please enter the server URL, not your email.'; case ValidationError.UnsupportedSchemeZulip: // TODO: What would be more helpful here? (First, maybe find out what // leads people to try a "zulip://" URL, if anyone actually does that) case ValidationError.UnsupportedSchemeOther: // eslint-disable-line no-fallthrough return 'The server URL must start with http:// or path_to_url } } type MaybeParsedInput = | {| +valid: true, value: URL |} | {| +valid: false, error: ValidationError |}; const tryParseInput = (realmInputValue: string): MaybeParsedInput => { const trimmedInputValue = realmInputValue.trim(); if (trimmedInputValue.length === 0) { return { valid: false, error: ValidationError.Empty }; } let url = tryParseUrl(trimmedInputValue); if (!/^https?:\/\//.test(trimmedInputValue)) { if (url && url.protocol === 'zulip:') { // Someone might get the idea to try one of the "zulip://" URLs that // are discussed sometimes. // TODO(?): Log to Sentry. How much does this happen, if at all? Maybe // log once when the input enters this error state, but don't spam // on every keystroke/render while it's in it. return { valid: false, error: ValidationError.UnsupportedSchemeZulip }; } else if (url && url.protocol !== 'http:' && url.protocol !== 'https:') { return { valid: false, error: ValidationError.UnsupportedSchemeOther }; } url = tryParseUrl(`path_to_url{trimmedInputValue}`); } if (!url) { return { valid: false, error: ValidationError.InvalidUrl }; } if (url.username !== '') { return { valid: false, error: ValidationError.NoUseEmail }; } return { valid: true, value: url }; }; type Suggestion = | ValidationError // Display relevant validation error message | string // Suggest this string as the server URL | null; // No suggestion function getSuggestion(realmInputValue, maybeParsedInput): Suggestion { if (!maybeParsedInput.valid) { switch (maybeParsedInput.error) { case ValidationError.NoUseEmail: case ValidationError.UnsupportedSchemeZulip: case ValidationError.UnsupportedSchemeOther: // Flag high-signal errors return maybeParsedInput.error; case ValidationError.Empty: case ValidationError.InvalidUrl: // Don't flag more noisy errors, which will often happen when the user // just hasn't finished typing a good URL. They'll still show up if // they apply at submit time; see the submit handler. } } const normalizedValue = realmInputValue.trim().replace(/^https?:\/\//, ''); if ( // This couldn't be a valid Zulip Cloud server subdomain. (Criteria // copied from check_subdomain_available in zerver/forms.py.) normalizedValue.length < 3 || !/^[a-z0-9-]*$/.test(normalizedValue) || normalizedValue[0] === '-' || normalizedValue[normalizedValue.length - 1] === '-' // TODO(?): Catch strings hard-coded as off-limits, like "your-org". // (See check_subdomain_available in zerver/forms.py.) ) { return null; } if ('chat'.startsWith(normalizedValue)) { return 'path_to_url } return `path_to_url{normalizedValue}.zulipchat.com/`; } export default function RealmInputScreen(props: Props): Node { const { navigation, route } = props; const globalSettings = useGlobalSelector(getGlobalSettings); const _ = React.useContext(TranslationContext); const themeContext = React.useContext(ThemeContext); const [progress, setProgress] = React.useState(false); const [realmInputValue, setRealmInputValue] = React.useState(''); const maybeParsedInput = tryParseInput(realmInputValue); const textInputRef = React.useRef<React$ElementRef<typeof TextInput> | null>(null); // When the route is focused in the navigation, focus the input. // Otherwise, if you go back to this screen from the auth screen, the // input won't be focused. useFocusEffect( useCallback(() => { if (textInputRef.current) { // Sometimes the effect of this `.focus()` is immediately undone // (the keyboard is closed) by a Keyboard.dismiss() from React // Navigation's internals. Seems like a complex bug, but the symptom // isn't terrible, it just means that on back-navigating to this // screen, sometimes the keyboard flicks open then closed, instead // of just opening. Shrug. See // path_to_url#narrow/stream/243-mobile-team/topic/realm-input/near/1346690 textInputRef.current.focus(); } }, []), ); const tryRealm = React.useCallback(async () => { if (!maybeParsedInput.valid) { showErrorAlert(_('Invalid input'), _(validationErrorMsg(maybeParsedInput.error))); return; } setProgress(true); const result = await fetchServerSettings(maybeParsedInput.value); setProgress(false); 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 }); Keyboard.dismiss(); }, [navigation, maybeParsedInput, globalSettings, _]); const suggestion = getSuggestion(realmInputValue, maybeParsedInput); const handlePressSuggestion = React.useCallback(suggestion_ => { setRealmInputValue(suggestion_); }, []); const styles = React.useMemo( () => createStyleSheet({ inputWrapper: { flexDirection: 'row', opacity: 0.8, marginTop: 16, marginBottom: 8, }, input: { flex: 1, padding: 0, fontSize: 20, color: themeContext.color, }, suggestionText: { fontSize: 12, fontStyle: 'italic' }, suggestionTextLink: { fontStyle: 'normal', color: BRAND_COLOR, // chosen to mimic WebLink }, button: { marginTop: 8 }, }), [themeContext], ); const suggestionContent = React.useMemo(() => { if (suggestion === null) { // Vertical spacer so the layout doesn't jump when a suggestion // appears or disappears. (The empty string might be neater, but it // doesn't give the right height probably lots of people wanted it to // be treated just like false/null/undefined in conditional rendering, // and React or RN gave in to that. I've tried the obvious ways to use // RN's PixelRatio.getFontScale() and never got the right height // either; dunno why.) return '\u200b'; // U+200B ZERO WIDTH SPACE } else if (typeof suggestion === 'string') { return ( <ZulipTextIntl inheritFontSize text={{ text: 'Suggestion: <z-link>{suggestedServerUrl}</z-link>', values: { suggestedServerUrl: suggestion, 'z-link': chunks => ( <ZulipText inheritFontSize style={styles.suggestionTextLink} onPress={() => handlePressSuggestion(suggestion)} > {chunks} </ZulipText> ), }, }} /> ); } else { return <ZulipTextIntl inheritFontSize text={validationErrorMsg(suggestion)} />; } }, [suggestion, handlePressSuggestion, styles]); return ( <Screen title="Welcome" canGoBack={!route.params.initial} padding centerContent keyboardShouldPersistTaps="always" shouldShowLoadingBanner={false} > <ZulipTextIntl text={{ text: 'Enter your Zulip server URL: <z-link>(Whats this?)</z-link>', values: { 'z-link': chunks => ( <WebLink url={new URL('path_to_url#find-the-zulip-log-in-url')}> {chunks} </WebLink> ), }, }} /> <View style={styles.inputWrapper}> <TextInput value={realmInputValue} placeholder="your-org.zulipchat.com" placeholderTextColor={HALF_COLOR} style={styles.input} autoFocus autoCorrect={false} autoCapitalize="none" returnKeyType="go" onChangeText={setRealmInputValue} blurOnSubmit={false} keyboardType="url" underlineColorAndroid="transparent" onSubmitEditing={tryRealm} enablesReturnKeyAutomatically disableFullscreenUI ref={textInputRef} /> </View> <ZulipText style={styles.suggestionText}>{suggestionContent}</ZulipText> <ZulipButton style={styles.button} text="Enter" progress={progress} onPress={tryRealm} isPressHandledWhenDisabled disabled={!maybeParsedInput.valid} /> </Screen> ); } ```
/content/code_sandbox/src/start/RealmInputScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,469
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { ComponentType } from 'react'; import { ActivityIndicator, View, FlatList } from 'react-native'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import type { DevUser, GlobalDispatch } from '../types'; import styles, { createStyleSheet } from '../styles'; import { connectGlobal } from '../react-redux'; import ErrorMsg from '../common/ErrorMsg'; import ZulipTextIntl from '../common/ZulipTextIntl'; import Screen from '../common/Screen'; import ZulipButton from '../common/ZulipButton'; import * as api from '../api'; import { loginSuccess } from '../actions'; const componentStyles = createStyleSheet({ accountItem: { height: 10 }, heading: { flex: 0 }, heading2: { fontSize: 20, }, container: { flex: 1, padding: 16, flexDirection: 'column', justifyContent: 'center', alignItems: 'stretch', }, }); type OuterProps = $ReadOnly<{| // These should be passed from React Navigation navigation: AppNavigationProp<'dev-auth'>, route: RouteProp<'dev-auth', {| realm: URL |}>, |}>; type SelectorProps = $ReadOnly<{||}>; type Props = $ReadOnly<{| ...OuterProps, dispatch: GlobalDispatch, ...SelectorProps, |}>; type State = {| progress: boolean, directAdmins: $ReadOnlyArray<DevUser>, directUsers: $ReadOnlyArray<DevUser>, error: string, |}; class DevAuthScreenInner extends PureComponent<Props, State> { state = { progress: false, directAdmins: [], directUsers: [], error: '', }; componentDidMount() { const realm = this.props.route.params.realm; this.setState({ progress: true, error: undefined }); (async () => { try { const response = await api.devListUsers({ realm, apiKey: '', email: '' }); this.setState({ directAdmins: response.direct_admins, directUsers: response.direct_users, progress: false, }); } catch (errorIllTyped) { const err: mixed = errorIllTyped; // path_to_url const message = err instanceof Error ? err.message : undefined; this.setState({ error: message }); } finally { this.setState({ progress: false }); } })(); } tryDevLogin = async (email: string) => { const realm = this.props.route.params.realm; this.setState({ progress: true, error: undefined }); try { const { api_key } = await api.devFetchApiKey({ realm, apiKey: '', email }, email); this.props.dispatch(loginSuccess(realm, email, api_key)); this.setState({ progress: false }); } catch (errorIllTyped) { const err: mixed = errorIllTyped; // path_to_url const message = err instanceof Error ? err.message : undefined; this.setState({ progress: false, error: message }); } }; render() { const { directAdmins, directUsers, error, progress } = this.state; return ( <Screen title="Pick a dev account" shouldShowLoadingBanner={false}> <View style={componentStyles.container}> {progress && <ActivityIndicator />} {!!error && <ErrorMsg error={error} />} <ZulipTextIntl style={[styles.field, componentStyles.heading2, componentStyles.heading]} text="Administrators" /> {directAdmins.map(admin => ( <ZulipButton key={admin.email} text={admin.email} onPress={() => this.tryDevLogin(admin.email)} /> ))} <ZulipTextIntl style={[styles.field, componentStyles.heading2, componentStyles.heading]} text="Normal users" /> <FlatList data={directUsers.map(user => user.email)} keyExtractor={(item, index) => item} ItemSeparatorComponent={() => <View style={componentStyles.accountItem} />} renderItem={({ item }) => ( <ZulipButton key={item} text={item} secondary onPress={() => this.tryDevLogin(item)} /> )} /> </View> </Screen> ); } } const DevAuthScreen: ComponentType<OuterProps> = connectGlobal<{||}, _, _>()(DevAuthScreenInner); export default DevAuthScreen; ```
/content/code_sandbox/src/start/DevAuthScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
986
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { Node } from 'react'; import { Image, Text, View, Platform } from 'react-native'; import { openLinkExternal } from '../utils/openLink'; import Touchable from '../common/Touchable'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import appStoreBadgePNG from '../../static/img/app-store-badge.png'; import googlePlayBadgePNG from '../../static/img/google-play-badge.png'; const styles = createStyleSheet({ appStoreBadge: { width: 180, height: 60, alignSelf: 'center', }, googlePlayBadge: { height: 80, width: 210, alignSelf: 'center', }, screen: { flex: 1, justifyContent: 'center', backgroundColor: BRAND_COLOR, }, text: { textAlign: 'center', color: 'white', fontSize: 20, margin: 8, }, badgeContainer: { marginTop: 30, flexDirection: 'row', justifyContent: 'center', }, }); function AppStoreBadge() { return <Image style={styles.appStoreBadge} source={appStoreBadgePNG} resizeMode="contain" />; } function GooglePlayBadge() { return <Image style={styles.googlePlayBadge} source={googlePlayBadgePNG} resizeMode="contain" />; } export default class CompatibilityScreen extends PureComponent<{||}> { storeURL: URL = Platform.OS === 'ios' ? new URL('path_to_url : new URL('path_to_url openStoreURL: () => void = () => { openLinkExternal(this.storeURL); }; render(): Node { return ( <View style={styles.screen}> <Text style={styles.text}>This app is too old!</Text> <Text style={styles.text}>Please update to the latest version.</Text> <View style={styles.badgeContainer}> <Touchable onPress={this.openStoreURL}> {Platform.OS === 'ios' ? <AppStoreBadge /> : <GooglePlayBadge />} </Touchable> </View> </View> ); } } ```
/content/code_sandbox/src/start/CompatibilityScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
470
```javascript /* @flow strict-local */ import { authFromCallbackUrl } from '../webAuth'; import * as eg from '../../__tests__/lib/exampleData'; describe('authFromCallbackUrl', () => { const otp = '13579bdf'; test('success', () => { const url = `zulip://login?realm=${eg.realm.toString()}&email=a@b&otp_encrypted_api_key=2636fdeb`; expect(authFromCallbackUrl(url, otp, eg.realm)).toEqual({ realm: eg.realm, email: 'a@b', apiKey: '5af4', }); }); test('wrong realm', () => { const url = 'zulip://login?realm=path_to_url expect(authFromCallbackUrl(url, otp, eg.realm)).toEqual(null); }); test('not login', () => { // Hypothetical link that isn't a login... but somehow with all the same // query params, for extra confusion for good measure. const url = `zulip://message?realm=${eg.realm.toString()}&email=a@b&otp_encrypted_api_key=2636fdeb`; expect(authFromCallbackUrl(url, otp, eg.realm)).toEqual(null); }); }); ```
/content/code_sandbox/src/start/__tests__/webAuth-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
272
```javascript /* @flow strict-local */ import { activeAuthentications } from '../AuthScreen'; describe('activeAuthentications: external_authentication_methods (server v2.1+ API)', () => { test('clobbers hardcoded info for same methods', () => { expect( activeAuthentications({ google: true }, [ { name: 'google', signup_url: '/accounts/register/social/google', display_icon: '/static/images/landing-page/logos/googl_e-icon.png', display_name: 'Google', login_url: '/accounts/login/social/google', }, ]), ).toMatchObject([ { name: 'google', displayName: 'Google', // NB different from hardcoded URL for same method action: { url: '/accounts/login/social/google' }, }, ]); }); test('supplements internal methods', () => { expect(activeAuthentications({ password: true, google: true }, [])).toMatchObject([ { name: 'password' }, ]); }); test('handles example SAML data', () => { expect( activeAuthentications({ saml: true }, [ { name: 'saml:okta', display_name: 'SAML', display_icon: null, login_url: '/accounts/login/social/saml/okta', signup_url: '/accounts/register/social/saml/okta', }, ]), ).toMatchObject([ { name: 'saml:okta', displayName: 'SAML', action: { url: '/accounts/login/social/saml/okta' }, }, ]); }); }); ```
/content/code_sandbox/src/start/__tests__/AuthScreen-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
352
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View, Image, TouchableWithoutFeedback } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import type { ThemeName } from '../../reduxTypes'; import { createStyleSheet } from '../../styles'; import ZulipTextIntl from '../../common/ZulipTextIntl'; import appleLogoBlackImg from '../../../static/img/apple-logo-black.png'; import appleLogoWhiteImg from '../../../static/img/apple-logo-white.png'; const styles = createStyleSheet({ buttonContent: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', height: 44, }, frame: { height: 44, justifyContent: 'center', borderRadius: 22, overflow: 'hidden', }, darkFrame: { backgroundColor: 'black', }, lightFrame: { backgroundColor: 'white', borderWidth: 1.5, borderColor: 'black', }, text: { fontSize: 16, }, darkText: { color: 'white', }, lightText: { color: 'black', }, }); type Props = $ReadOnly<{| style?: ViewStyleProp, onPress: () => void | Promise<void>, theme: ThemeName, |}>; /** * The custom "Sign in with Apple" button that follows the rules. * * Do not reuse this component; it is only meant to be rendered by the * IosCompliantAppleAuthButton, which controls whether the custom * button should be used. */ export default function Custom(props: Props): Node { const { style, onPress, theme } = props; const logoSource = theme === 'light' ? appleLogoBlackImg : appleLogoWhiteImg; const frameStyle = [ styles.frame, theme === 'light' ? styles.lightFrame : styles.darkFrame, style, ]; const textStyle = [styles.text, theme === 'light' ? styles.lightText : styles.darkText]; return ( <View style={frameStyle}> <TouchableWithoutFeedback onPress={onPress}> <View style={styles.buttonContent}> <Image source={logoSource} /> <ZulipTextIntl style={textStyle} text="Sign in with Apple" /> </View> </TouchableWithoutFeedback> </View> ); } ```
/content/code_sandbox/src/start/IosCompliantAppleAuthButton/Custom.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
525
```javascript /* @flow strict-local */ import React, { useState, useEffect } from 'react'; import type { Node } from 'react'; import { View, useColorScheme } from 'react-native'; import type { ViewStyle } from 'react-native/Libraries/StyleSheet/StyleSheet'; import * as AppleAuthentication from 'expo-apple-authentication'; import { useGlobalSelector } from '../../react-redux'; import type { SubsetProperties } from '../../generics'; import Custom from './Custom'; import { getGlobalSettings } from '../../selectors'; import { getThemeToUse } from '../../settings/settingsSelectors'; type Props = $ReadOnly<{| // See `ZulipButton`'s `style` prop, where a comment discusses this // idea. style?: SubsetProperties< ViewStyle, {| marginTop?: mixed, |}, >, onPress: () => void | Promise<void>, |}>; /** * A "Sign in with Apple" button (iOS only) that follows the rules. * * These official guidelines from Apple are at * path_to_url * * Not to be used on Android. There, we also offer "Sign in with * Apple", but without marking it with a different style from the * other buttons. */ export default function IosCompliantAppleAuthButton(props: Props): Node { const { style, onPress } = props; const theme = useGlobalSelector(state => getGlobalSettings(state).theme); const osScheme = useColorScheme(); const themeToUse = getThemeToUse(theme, osScheme); const [isNativeButtonAvailable, setIsNativeButtonAvailable] = useState<boolean | void>(undefined); useEffect(() => { async function getAndSetIsAvailable() { setIsNativeButtonAvailable(await AppleAuthentication.isAvailableAsync()); } // This nesting is odd, but we get an ESLint warning if we make the // `useEffect` callback itself an async function. See // path_to_url#discussion_r673557179 // and // path_to_url getAndSetIsAvailable(); }, []); if (isNativeButtonAvailable === undefined) { return <View style={[{ height: 44 }, style]} />; } else if (isNativeButtonAvailable) { return ( <AppleAuthentication.AppleAuthenticationButton buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN} buttonStyle={ themeToUse === 'light' ? AppleAuthentication.AppleAuthenticationButtonStyle.WHITE_OUTLINE : AppleAuthentication.AppleAuthenticationButtonStyle.BLACK } cornerRadius={22} style={[{ height: 44 }, style]} onPress={onPress} /> ); } else { return <Custom style={style} onPress={onPress} theme={themeToUse} />; } } ```
/content/code_sandbox/src/start/IosCompliantAppleAuthButton/index.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
602
```javascript /* @flow strict-local */ import React, { useState, useCallback } from 'react'; import type { Node } from 'react'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import type { UserOrBot } from '../types'; import { useSelector, useDispatch } from '../react-redux'; import Screen from '../common/Screen'; import { doNarrow, navigateBack } from '../actions'; import { pmNarrowFromRecipients } from '../utils/narrow'; import { pmKeyRecipientsFromUsers } from '../utils/recipient'; import UserPickerCard from './UserPickerCard'; import { getOwnUserId } from '../users/userSelectors'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'new-group-pm'>, route: RouteProp<'new-group-pm', void>, |}>; export default function NewGroupPmScreen(props: Props): Node { const { navigation } = props; const dispatch = useDispatch(); const ownUserId = useSelector(getOwnUserId); const [filter, setFilter] = useState<string>(''); const handlePickerComplete = useCallback( (selected: $ReadOnlyArray<UserOrBot>) => { navigation.dispatch(navigateBack()); dispatch(doNarrow(pmNarrowFromRecipients(pmKeyRecipientsFromUsers(selected, ownUserId)))); }, [dispatch, navigation, ownUserId], ); return ( <Screen search scrollEnabled={false} searchBarOnChange={setFilter}> <UserPickerCard filter={filter} onComplete={handlePickerComplete} showOwnUser={false} /> </Screen> ); } ```
/content/code_sandbox/src/user-picker/NewGroupPmScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
344
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { UserId, UserOrBot } from '../types'; import UserAvatarWithPresence from '../common/UserAvatarWithPresence'; import ComponentWithOverlay from '../common/ComponentWithOverlay'; import Touchable from '../common/Touchable'; import { createStyleSheet } from '../styles'; import { IconCancel } from '../common/Icons'; import { getFullNameReactText } from '../users/userSelectors'; import ZulipTextIntl from '../common/ZulipTextIntl'; import { useSelector } from '../react-redux'; import { getRealm } from '../directSelectors'; const styles = createStyleSheet({ wrapper: { flexDirection: 'column', marginLeft: 8, marginVertical: 8, }, text: { flex: 1, fontSize: 10, marginTop: 2, textAlign: 'center', }, textFrame: { width: 50, flexDirection: 'row', }, }); type Props = $ReadOnly<{| user: UserOrBot, onPress: UserId => void, |}>; /** * Pressable avatar for items in the user-picker card. */ export default function AvatarItem(props: Props): Node { const { user, onPress } = props; const enableGuestUserIndicator = useSelector(state => getRealm(state).enableGuestUserIndicator); const handlePress = React.useCallback(() => { onPress(user.user_id); }, [onPress, user.user_id]); return ( <View style={styles.wrapper}> <Touchable onPress={handlePress}> <ComponentWithOverlay overlaySize={20} overlayColor="white" overlayPosition="bottom-right" overlay={<IconCancel color="gray" size={20} />} > <UserAvatarWithPresence key={user.user_id} size={50} userId={user.user_id} /> </ComponentWithOverlay> </Touchable> <View style={styles.textFrame}> <ZulipTextIntl style={styles.text} text={getFullNameReactText({ user, enableGuestUserIndicator })} /> </View> </View> ); } ```
/content/code_sandbox/src/user-picker/AvatarItem.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
475
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { FlatList } from 'react-native'; import type { UserId, UserOrBot } from '../types'; import AvatarItem from './AvatarItem'; type Props = $ReadOnly<{| users: $ReadOnlyArray<UserOrBot>, listRef: React$Ref<typeof FlatList>, onPress: UserId => void, |}>; export default function AvatarList(props: Props): Node { const { listRef, users, onPress } = props; return ( <FlatList horizontal showsHorizontalScrollIndicator={false} initialNumToRender={20} data={users} ref={listRef} keyExtractor={user => String(user.user_id)} renderItem={({ item: user }) => <AvatarItem user={user} onPress={onPress} />} /> ); } ```
/content/code_sandbox/src/user-picker/AvatarList.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
189
```javascript /* @flow strict-local */ import React, { useCallback, useState } from 'react'; import type { Node } from 'react'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import Screen from '../common/Screen'; import UserList from '../users/UserList'; import type { UserOrBot } from '../types'; import { useSelector, useDispatch } from '../react-redux'; import { pm1to1NarrowFromUser } from '../utils/narrow'; import { getUsers } from '../selectors'; import { navigateBack, doNarrow } from '../actions'; import { useNavigation } from '../react-navigation'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'new-1to1-pm'>, route: RouteProp<'new-1to1-pm', void>, |}>; export default function New1to1PmScreen(props: Props): Node { const dispatch = useDispatch(); const users = useSelector(getUsers); const navigation = useNavigation(); const handleUserNarrow = useCallback( (user: UserOrBot) => { navigation.dispatch(navigateBack()); dispatch(doNarrow(pm1to1NarrowFromUser(user))); }, [dispatch, navigation], ); const [filter, setFilter] = useState<string>(''); return ( <Screen search scrollEnabled={false} searchBarOnChange={setFilter}> <UserList users={users} filter={filter} onPress={handleUserNarrow} /> </Screen> ); } ```
/content/code_sandbox/src/user-picker/New1to1PmScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
327
```javascript /* @flow strict-local */ import type { OutboxState, PerAccountApplicableAction, Outbox } from '../types'; import { REGISTER_COMPLETE, MESSAGE_SEND_START, EVENT_NEW_MESSAGE, DELETE_OUTBOX_MESSAGE, MESSAGE_SEND_COMPLETE, RESET_ACCOUNT_DATA, } from '../actionConstants'; import { NULL_ARRAY } from '../nullObjects'; import { filterArray } from '../utils/immutability'; const initialState = NULL_ARRAY; const messageSendStart = (state, action) => { const message = state.find(item => item.timestamp === action.outbox.timestamp); if (message) { return state; } return [...state, { ...action.outbox }]; }; export default ( state: OutboxState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): OutboxState => { switch (action.type) { // TODO(#3881): Figure out if we want this. case REGISTER_COMPLETE: return filterArray(state, (outbox: Outbox) => !outbox.isSent); case MESSAGE_SEND_START: return messageSendStart(state, action); case MESSAGE_SEND_COMPLETE: return state.map(<O: Outbox>(item: O): O => item.id !== action.local_message_id ? item : { ...(item: O), isSent: true }, ); case DELETE_OUTBOX_MESSAGE: case EVENT_NEW_MESSAGE: return filterArray(state, item => item && item.timestamp !== +action.local_message_id); case RESET_ACCOUNT_DATA: return initialState; default: return state; } }; ```
/content/code_sandbox/src/outbox/outboxReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
339
```javascript /* @flow strict-local */ import React, { useState, useRef, useEffect } from 'react'; import type { Node } from 'react'; import { View, FlatList } from 'react-native'; import { createSelector } from 'reselect'; import { usePrevious } from '../reactUtils'; import type { User, UserId, UserOrBot, Selector } from '../types'; import { createStyleSheet } from '../styles'; import { useSelector } from '../react-redux'; import FloatingActionButton from '../common/FloatingActionButton'; import LineSeparator from '../common/LineSeparator'; import { IconDone } from '../common/Icons'; import UserList from '../users/UserList'; import AvatarList from './AvatarList'; import AnimatedScaleComponent from '../animation/AnimatedScaleComponent'; import { getUsers } from '../selectors'; import { getOwnUserId } from '../users/userSelectors'; const styles = createStyleSheet({ wrapper: { flex: 1, }, button: { position: 'absolute', bottom: 10, right: 10, }, }); type Props = $ReadOnly<{| filter: string, onComplete: (selected: $ReadOnlyArray<UserOrBot>) => void, showOwnUser: boolean, |}>; const getUsersExceptSelf: Selector<$ReadOnlyArray<User>> = createSelector( getUsers, getOwnUserId, (users, ownUserId) => users.filter(user => user.user_id !== ownUserId), ); // The users we want to show in this particular UI. // We exclude (a) users with `is_active` false; (b) cross-realm bots; // (c) self when `showOwnUser` is false. function getUsersToShow(state, showOwnUser) { return showOwnUser ? getUsers(state) : getUsersExceptSelf(state); } export default function UserPickerCard(props: Props): Node { const { filter, showOwnUser } = props; const users = useSelector(state => getUsersToShow(state, showOwnUser)); const [selectedState, setSelectedState] = useState<$ReadOnlyArray<UserOrBot>>([]); const listRef = useRef<FlatList<UserOrBot> | null>(null); const prevSelectedState = usePrevious(selectedState); useEffect(() => { if (prevSelectedState && selectedState.length > prevSelectedState.length) { setTimeout(() => { listRef.current?.scrollToEnd(); }); } }, [selectedState, prevSelectedState, listRef]); return ( <View style={styles.wrapper}> <AnimatedScaleComponent visible={selectedState.length > 0}> <AvatarList listRef={listRef} users={selectedState} onPress={(userId: UserId) => { setSelectedState(state => state.filter(x => x.user_id !== userId)); }} /> </AnimatedScaleComponent> {selectedState.length > 0 && <LineSeparator />} <UserList filter={filter} users={users} selected={selectedState} onPress={(user: UserOrBot) => { setSelectedState(state => { if (state.find(x => x.user_id === user.user_id)) { return state.filter(x => x.user_id !== user.user_id); } else { return [...state, user]; } }); }} /> <AnimatedScaleComponent style={styles.button} visible={selectedState.length > 0}> <FloatingActionButton Icon={IconDone} size={50} disabled={selectedState.length === 0} onPress={() => { const { onComplete } = props; onComplete(selectedState); }} /> </AnimatedScaleComponent> </View> ); } ```
/content/code_sandbox/src/user-picker/UserPickerCard.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
768
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import outboxReducer from '../outboxReducer'; import { MESSAGE_SEND_START } from '../../actionConstants'; import * as eg from '../../__tests__/lib/exampleData'; describe('outboxReducer', () => { describe('RESET_ACCOUNT_DATA', () => { const initialState = eg.baseReduxState.outbox; const action1 = { type: MESSAGE_SEND_START, outbox: eg.streamOutbox({}) }; const prevState = outboxReducer(initialState, action1); expect(prevState).not.toEqual(initialState); expect(outboxReducer(prevState, eg.action.reset_account_data)).toEqual(initialState); }); describe('REGISTER_COMPLETE', () => { test('filters out isSent', () => { const message1 = eg.streamOutbox({ content: 'New one' }); const message2 = eg.streamOutbox({ content: 'Another one' }); const message3 = eg.streamOutbox({ content: 'Message already sent', isSent: true }); const prevState = deepFreeze([message1, message2, message3]); expect(outboxReducer(prevState, eg.action.register_complete)).toEqual([message1, message2]); }); }); describe('MESSAGE_SEND_START', () => { test('add a new message to the outbox', () => { const message = eg.streamOutbox({ content: 'New one' }); const prevState = deepFreeze([]); expect( outboxReducer(prevState, deepFreeze({ type: MESSAGE_SEND_START, outbox: message })), ).toEqual([message]); }); test('do not add a message with a duplicate timestamp to the outbox', () => { const message1 = eg.streamOutbox({ content: 'hello', timestamp: 123 }); const message2 = eg.streamOutbox({ content: 'hello twice', timestamp: 123 }); const prevState = deepFreeze([message1]); expect( outboxReducer(prevState, deepFreeze({ type: MESSAGE_SEND_START, outbox: message2 })), ).toBe(prevState); }); }); describe('EVENT_NEW_MESSAGE', () => { test('do not mutate state if a message is not removed', () => { const message = eg.streamMessage({ timestamp: 123 }); const prevState = deepFreeze([eg.streamOutbox({ timestamp: 546 })]); expect( outboxReducer( prevState, eg.mkActionEventNewMessage(message, { local_message_id: message.timestamp }), ), ).toBe(prevState); }); test('remove message if local_message_id matches', () => { const message1 = eg.streamOutbox({ timestamp: 546 }); const message2 = eg.streamOutbox({ timestamp: 150238512430 }); const message3 = eg.streamOutbox({ timestamp: 150238594540 }); const prevState = deepFreeze([message1, message2, message3]); expect( outboxReducer( prevState, eg.mkActionEventNewMessage(eg.streamMessage(), { local_message_id: 546 }), ), ).toEqual([message2, message3]); }); test("remove nothing if local_message_id doesn't match", () => { const message1 = eg.streamOutbox({ timestamp: 546 }); const message2 = eg.streamOutbox({ timestamp: 150238512430 }); const message3 = eg.streamOutbox({ timestamp: 150238594540 }); const prevState = deepFreeze([message1, message2, message3]); const actualState = outboxReducer( prevState, eg.mkActionEventNewMessage(eg.streamMessage(), { local_message_id: 15023859 }), ); expect(actualState).toBe(prevState); }); }); }); ```
/content/code_sandbox/src/outbox/__tests__/outboxReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
813
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import parseMarkdown from 'zulip-markdown-parser'; import invariant from 'invariant'; import { ApiError } from '../api/apiErrors'; import { showErrorAlert } from '../utils/info'; import * as logging from '../utils/logging'; import type { PerAccountState, Narrow, Outbox, PmOutbox, StreamOutbox, Stream, UserOrBot, UserId, PerAccountAction, ThunkAction, } from '../types'; import type { SubsetProperties } from '../generics'; import { MESSAGE_SEND_START, TOGGLE_OUTBOX_SENDING, DELETE_OUTBOX_MESSAGE, MESSAGE_SEND_COMPLETE, } from '../actionConstants'; import { getAuth, getStreamsById } from '../selectors'; import * as api from '../api'; import { getAllUsersById, getOwnUser } from '../users/userSelectors'; import { makeUserId } from '../api/idTypes'; import { caseNarrowPartial, isConversationNarrow } from '../utils/narrow'; import { BackoffMachine } from '../utils/async'; import { recipientsOfPrivateMessage, streamNameOfStreamMessage } from '../utils/recipient'; export const messageSendStart = (outbox: Outbox): PerAccountAction => ({ type: MESSAGE_SEND_START, outbox, }); export const toggleOutboxSending = (sending: boolean): PerAccountAction => ({ type: TOGGLE_OUTBOX_SENDING, sending, }); export const deleteOutboxMessage = (localMessageId: number): PerAccountAction => ({ type: DELETE_OUTBOX_MESSAGE, local_message_id: localMessageId, }); export const messageSendComplete = (localMessageId: number): PerAccountAction => ({ type: MESSAGE_SEND_COMPLETE, local_message_id: localMessageId, }); const trySendMessages = (dispatch, getState): boolean => { const state = getState(); const auth = getAuth(state); const outboxToSend = state.outbox.filter(outbox => !outbox.isSent); const oneWeekAgoTimestamp = Date.now() / 1000 - 60 * 60 * 24 * 7; try { outboxToSend.forEach(async item => { // If a message has spent over a week in the outbox, it's probably too // stale to try sending it. // // TODO: instead of just throwing these away, create an "unsendable" state // (including a reason for unsendability), and transition old messages to // that instead. if (item.timestamp < oneWeekAgoTimestamp) { dispatch(deleteOutboxMessage(item.id)); return; // i.e., continue } // prettier-ignore const to = item.type === 'private' // TODO(server-2.0): switch to numeric user IDs (#3764), not emails. ? recipientsOfPrivateMessage(item).map(r => r.email).join(',') // TODO(server-2.0): switch to numeric stream IDs (#3918), not names. // HACK: the server attempts to interpret this argument as JSON, then // CSV, then a literal. To avoid misparsing, always use JSON. : JSON.stringify([streamNameOfStreamMessage(item)]); try { await api.sendMessage(auth, { type: item.type, to, subject: item.subject, content: item.markdownContent, localId: item.timestamp, eventQueueId: state.session.eventQueueId ?? undefined, }); } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url if (error instanceof ApiError && error.message.length > 0) { showErrorAlert( // TODO(i18n) nontrivial to plumb through GetText; // skip for now in this legacy codebase 'Failed to send message', // E.g., "You do not have permission to send direct messages to this recipient." `The server at ${auth.realm.toString()} said:\n\n${error.message}`, ); dispatch(deleteOutboxMessage(item.id)); return; } } dispatch(messageSendComplete(item.timestamp)); }); return true; } catch (e) { logging.warn(e); return false; } }; /** Try sending any pending outbox messages for this account, with retries. */ export const sendOutbox = (): ThunkAction<Promise<void>> => async (dispatch, getState) => { const state = getState(); if (state.outbox.length === 0 || state.session.outboxSending) { return; } dispatch(toggleOutboxSending(true)); const backoffMachine = new BackoffMachine(); while (!trySendMessages(dispatch, getState)) { await backoffMachine.wait(); } dispatch(toggleOutboxSending(false)); }; // A valid display_recipient with all the thread's users, sorted by ID. const recipientsFromIds = (ids, allUsersById, ownUser) => { const result = ids.map(id => { const user = allUsersById.get(id); if (!user) { throw new Error('outbox: missing user when preparing to send PM'); } return { id, email: user.email, full_name: user.full_name }; }); if (!result.some(r => r.id === ownUser.user_id)) { result.push({ email: ownUser.email, id: ownUser.user_id, full_name: ownUser.full_name }); } result.sort((r1, r2) => r1.id - r2.id); return result; }; // prettier-ignore type DataFromNarrow = | SubsetProperties<PmOutbox, {| type: mixed, display_recipient: mixed, subject: mixed |}> | SubsetProperties<StreamOutbox, {| type: mixed, stream_id: mixed, display_recipient: mixed, subject: mixed |}>; const outboxPropertiesForNarrow = ( destinationNarrow: Narrow, streamsById: Map<number, Stream>, allUsersById: Map<UserId, UserOrBot>, ownUser: UserOrBot, ): DataFromNarrow => caseNarrowPartial(destinationNarrow, { pm: ids => ({ type: 'private', display_recipient: recipientsFromIds(ids, allUsersById, ownUser), subject: '', }), topic: (streamId, topic) => { const stream = streamsById.get(streamId); invariant(stream, 'narrow must be known stream'); return { type: 'stream', stream_id: stream.stream_id, display_recipient: stream.name, subject: topic, }; }, }); const getContentPreview = (content: string, state: PerAccountState): string => { try { return parseMarkdown( content, [ // TODO: Refactor so we don't make these fake user objects. { user_id: makeUserId(-1), full_name: 'all', email: '(Notify everyone)' }, { user_id: makeUserId(-2), full_name: 'everyone', email: '(Notify everyone)' }, ...state.users, ], state.streams, getAuth(state), state.realm.filters, state.realm.emoji, ); } catch { return content; } }; export const addToOutbox = (destinationNarrow: Narrow, content: string): ThunkAction<Promise<void>> => async (dispatch, getState) => { invariant(isConversationNarrow(destinationNarrow), 'destination narrow must be conversation'); const state = getState(); const ownUser = getOwnUser(state); const localTime = Math.round(new Date().getTime() / 1000); dispatch( messageSendStart({ isSent: false, ...outboxPropertiesForNarrow( destinationNarrow, getStreamsById(state), getAllUsersById(state), ownUser, ), markdownContent: content, content: getContentPreview(content, state), timestamp: localTime, id: localTime, sender_full_name: ownUser.full_name, sender_email: ownUser.email, sender_id: ownUser.user_id, avatar_url: ownUser.avatar_url, isOutbox: true, reactions: [], }), ); dispatch(sendOutbox()); }; ```
/content/code_sandbox/src/outbox/outboxActions.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 import type { ComponentType } from 'react'; import { typesEquivalent } from '../generics'; import type { OwnProps } from '../react-redux'; // A slight abbreviation to make some test cases more compact. type OwnPropsOf<P, -SP, -D> = OwnProps<ComponentType<P>, SP, D>; // prettier-ignore function test_OwnProps() { type Dispatch = { asdf: number, qwer: boolean, ... }; // Basic happy case. typesEquivalent< OwnPropsOf<{| +a: string, +b: number, +dispatch: Dispatch, |}, {| +b: number |}, Dispatch>, {| +a: string |}>(); (p: OwnPropsOf<{| +a: string, +b: number, +dispatch: Dispatch, |}, {| +b: number |}, Dispatch>): { ... } => p; // Component can have weaker expectations of a selector prop typesEquivalent< OwnPropsOf<{| +a: string, +b: number, +dispatch: Dispatch, |}, {| +b: 3 |}, Dispatch>, {| +a: string |}>(); // but not stronger // $FlowExpectedError[incompatible-type-arg] (p: OwnPropsOf<{| +a: string, +b: 3, +dispatch: Dispatch, |}, {| +b: number |}, Dispatch>): { ... } => p; // and must expect each selector prop in the first place. // $FlowExpectedError[prop-missing] (p: OwnPropsOf<{| +a: string, +dispatch: Dispatch, |}, {| +b: number |}, Dispatch>): { ... } => p; } // prettier-ignore // Test handling of the `dispatch` prop. function test_OwnProps_dispatch() { type Dispatch = { asdf: number, qwer: boolean, ... }; // Basic happy case. typesEquivalent< OwnPropsOf<{| +dispatch: Dispatch |}, {||}, Dispatch>, {||}>(); (p: OwnPropsOf<{| +dispatch: Dispatch |}, {||}, Dispatch>): { ... } => p; // Component can have weaker expectations typesEquivalent< OwnPropsOf<{| +dispatch: mixed |}, {||}, Dispatch>, {||}>(); // but not stronger // $FlowExpectedError[incompatible-type-arg] (p: OwnPropsOf<{| +dispatch: empty |}, {||}, Dispatch>): { ... } => p; // and must expect the prop at all. // $FlowExpectedError[prop-missing] (p: OwnPropsOf<{||}, {||}, Dispatch>): { ... } => p; } ```
/content/code_sandbox/src/__flow-tests__/react-redux-test.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 { usePrevious } from '../reactUtils'; function test_usePrevious() { declare var b: boolean; // With no initial value, returns T | void: { (usePrevious(b): boolean | void); // In particular, make sure the type knows the return value can be void. // (This is the case that would break with one natural-but-wrong way to // write the definition.) // $FlowExpectedError[incompatible-cast] (usePrevious(b): boolean); // $FlowExpectedError[incompatible-cast] (usePrevious(b): void); } // With initial value, returns union type: { (usePrevious(b, null): boolean | null); // $FlowExpectedError[incompatible-cast] (usePrevious(b, null): boolean); // $FlowExpectedError[incompatible-cast] (usePrevious(b, null): null); } // With initial value of type T, returns T: { (usePrevious(b, false): boolean); // $FlowExpectedError[incompatible-cast] (usePrevious(b, false): false); } } ```
/content/code_sandbox/src/__flow-tests__/reactUtils-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
252
```javascript /** * Type-tests for navigation. * * @flow strict-local */ import React, { type ComponentType } from 'react'; import { createStackNavigator, type StackNavigationProp } from '@react-navigation/stack'; import { type RouteProp, type RouteParamsOf } from '../react-navigation'; // Test that `RouteProp` gives route.params the right type. function testRouteParamTypes() { type ProfileProps = {| // skip navigation +route: RouteProp<'Profile', {| +userId: string |}>, |}; function Profile(props: ProfileProps) { const { params } = props.route; (params.userId: string); // $FlowExpectedError[incompatible-cast] (params.userId: empty); (('a': string): typeof params.userId); // $FlowExpectedError[incompatible-cast] (('a': mixed): typeof params.userId); // $FlowExpectedError[prop-missing] params.nonsense; } } // Test that `RouteProp` gives type-checking of the route name // at the navigator. function testNavigatorTypes() { // (The setup of this one is a bit cumbersome because we need to set up // the navigator.) type ProfileProps = {| +navigation: NavigationProp<'Profile'>, +route: RouteProp<'Profile', {| +userId: string |}>, |}; declare var Profile: ComponentType<ProfileProps>; declare var Profile12: ComponentType<{| +navigation: NavigationProp<'Profile1'>, +route: RouteProp<'Profile2', {| +userId: string |}>, |}>; type NavParamList = {| Profile: RouteParamsOf<typeof Profile>, Profile1: RouteParamsOf<typeof Profile12>, Profile2: RouteParamsOf<typeof Profile12>, |}; // prettier-ignore type NavigationProp<+RouteName: $Keys<NavParamList> = $Keys<NavParamList>> = StackNavigationProp<NavParamList, RouteName>; const Stack = createStackNavigator<NavParamList, NavParamList, NavigationProp<>>(); <Stack.Navigator> {/* Happy case is happy */} <Stack.Screen name="Profile" component={Profile} /> {/* FAIL - Should error but doesn't! on mismatch of name with route prop */} <Stack.Screen name="Profile1" component={Profile12} /> {/* FAIL - Should error but doesn't! on mismatch of name with navigation prop */} <Stack.Screen name="Profile2" component={Profile12} /> {/* $FlowExpectedError[prop-missing] - name that isn't even in the list */} <Stack.Screen name="Profile1234" component={Profile12} /> </Stack.Navigator>; } ```
/content/code_sandbox/src/__flow-tests__/nav-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
583
```javascript /* @flow strict-local */ import type { Action } from '../types'; // Assert that Action does not allow arbitrary objects. { const foo = { nonexistent_key: 'bar' }; // $FlowExpectedError[incompatible-type] const bar: Action = foo; } ```
/content/code_sandbox/src/__flow-tests__/types-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
58
```javascript /* @flow strict-local */ import type AnimatedValue from 'react-native/Libraries/Animated/nodes/AnimatedValue'; import type { DimensionValue } from 'react-native/Libraries/StyleSheet/StyleSheetTypes'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import type { IsSupertype } from '../generics'; import type { ViewStylePropWithout } from '../reactNativeUtils'; function test_ViewStylePropWithout() { type ViewStyleNoHeight = ViewStylePropWithout<{| height: DimensionValue, minHeight: DimensionValue, maxHeight: DimensionValue, |}>; // Is a subtype of ViewStyleProp (s: ViewStyleNoHeight): ViewStyleProp => s; // Accepts width-related attributes (s: {| minWidth: 10, width: AnimatedValue, maxWidth: '100%' |}): ViewStyleNoHeight => s; // Doesn't accept height-related attributes // $FlowExpectedError[incompatible-return] (s: {| minHeight: 10 |}): ViewStyleNoHeight => s; // $FlowExpectedError[incompatible-return] (s: {| height: AnimatedValue |}): ViewStyleNoHeight => s; // $FlowExpectedError[incompatible-return] (s: {| maxHeight: '100%' |}): ViewStyleNoHeight => s; } ```
/content/code_sandbox/src/__flow-tests__/reactNativeUtils-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
287
```javascript /* @flow strict-local */ import { EventTypes } from '../api/eventTypes'; import type { PerAccountApplicableAction, StreamsState, StreamUpdateEvent } from '../types'; import type { Stream, Subscription } from '../api/modelTypes'; import { ensureUnreachable } from '../types'; import { EVENT, REGISTER_COMPLETE, RESET_ACCOUNT_DATA } from '../actionConstants'; import { NULL_ARRAY } from '../nullObjects'; import { filterArray } from '../utils/immutability'; const initialState: StreamsState = NULL_ARRAY; export function updateStreamProperties<S: Stream | Subscription>( stream: S, event: StreamUpdateEvent, ): S { switch (event.property) { case ('name': 'name'): return { ...stream, [event.property]: event.value }; case ('description': 'description'): return { ...stream, [event.property]: event.value, rendered_description: event.rendered_description, }; case ('date_created': 'date_created'): return { ...stream, [event.property]: event.value }; case ('invite_only': 'invite_only'): return { ...stream, [event.property]: event.value, history_public_to_subscribers: event.history_public_to_subscribers, is_web_public: event.is_web_public, }; case ('rendered_description': 'rendered_description'): return { ...stream, [event.property]: event.value }; case ('is_web_public': 'is_web_public'): return { ...stream, [event.property]: event.value }; case ('stream_post_policy': 'stream_post_policy'): return { ...stream, [event.property]: event.value }; case ('message_retention_days': 'message_retention_days'): return { ...stream, [event.property]: event.value }; case ('history_public_to_subscribers': 'history_public_to_subscribers'): return { ...stream, [event.property]: event.value }; case ('first_message_id': 'first_message_id'): return { ...stream, [event.property]: event.value }; case ('is_announcement_only': 'is_announcement_only'): return { ...stream, [event.property]: event.value }; default: ensureUnreachable(event.property); return stream; } } export default ( state: StreamsState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): StreamsState => { switch (action.type) { case REGISTER_COMPLETE: return action.data.streams || initialState; case RESET_ACCOUNT_DATA: return initialState; case EVENT: { const { event } = action; switch (event.type) { case EventTypes.stream: switch (event.op) { case 'create': return state.concat( event.streams.filter(x => !state.find(y => x.stream_id === y.stream_id)), ); case 'delete': return filterArray( state, x => !event.streams.find(y => x && x.stream_id === y.stream_id), ); case 'update': return state.map(stream => { if (stream.stream_id !== event.stream_id) { return stream; } return updateStreamProperties(stream, event); }); case 'occupy': case 'vacate': return state; default: ensureUnreachable(event); return state; } default: return state; } } default: return state; } }; ```
/content/code_sandbox/src/streams/streamsReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
727
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; // $FlowFixMe[untyped-import] import { useActionSheet } from '@expo/react-native-action-sheet'; import styles, { BRAND_COLOR, createStyleSheet } from '../styles'; import { IconMention, IconFollow } from '../common/Icons'; import ZulipText from '../common/ZulipText'; import Touchable from '../common/Touchable'; import UnreadCount from '../common/UnreadCount'; import { showTopicActionSheet } from '../action-sheets'; import type { ShowActionSheetWithOptions } from '../action-sheets'; import { TranslationContext } from '../boot/TranslationProvider'; import { useDispatch, useSelector } from '../react-redux'; import { getAuth, getFlags, getSubscriptionsById, getStreamsById, getOwnUser, getZulipFeatureLevel, } from '../selectors'; import { getMute, isTopicFollowed } from '../mute/muteModel'; import { getUnread } from '../unread/unreadModel'; import { useNavigation } from '../react-navigation'; import { ThemeContext } from '../styles/theme'; const componentStyles = createStyleSheet({ selectedRow: { backgroundColor: BRAND_COLOR, }, mentionedLabel: { paddingRight: 4, color: 'gray', }, label: { flex: 1, }, selectedText: { color: 'white', }, muted: { opacity: 0.5, }, followedIcon: { paddingLeft: 4, width: 20, opacity: 0.2, }, }); type Props = $ReadOnly<{| streamId: number, name: string, isMuted?: boolean, isSelected?: boolean, isMentioned?: boolean, unreadCount?: number, onPress: (streamId: number, topic: string) => void, |}>; export default function TopicItem(props: Props): Node { const { streamId, name, isMuted = false, isSelected = false, isMentioned = false, unreadCount = 0, onPress, } = props; const showActionSheetWithOptions: ShowActionSheetWithOptions = useActionSheet().showActionSheetWithOptions; const _ = useContext(TranslationContext); const navigation = useNavigation(); const dispatch = useDispatch(); const backgroundData = useSelector(state => { const ownUser = getOwnUser(state); return { auth: getAuth(state), mute: getMute(state), streams: getStreamsById(state), subscriptions: getSubscriptionsById(state), unread: getUnread(state), ownUser, ownUserRole: ownUser.role, flags: getFlags(state), zulipFeatureLevel: getZulipFeatureLevel(state), }; }); const theme = useContext(ThemeContext); const iconColor = theme.themeName === 'dark' ? 'white' : 'black'; const isFollowed = useSelector(state => isTopicFollowed(streamId, name, getMute(state))); return ( <Touchable onPress={() => onPress(streamId, name)} onLongPress={() => { showTopicActionSheet({ showActionSheetWithOptions, callbacks: { dispatch, navigation, _ }, backgroundData, streamId, topic: name, }); }} > <View style={[ styles.listItem, isSelected && componentStyles.selectedRow, isMuted && componentStyles.muted, ]} > <ZulipText style={[componentStyles.label, isSelected && componentStyles.selectedText]} text={name} numberOfLines={1} ellipsizeMode="tail" /> {isMentioned && <IconMention size={14} style={componentStyles.mentionedLabel} />} <UnreadCount count={unreadCount} inverse={isSelected} /> {isFollowed ? ( <IconFollow style={componentStyles.followedIcon} size={14} color={iconColor} /> ) : ( // $FlowFixMe[incompatible-type]: complains about `color` but that's not present <View style={componentStyles.followedIcon} /> )} </View> </Touchable> ); } ```
/content/code_sandbox/src/streams/TopicItem.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
942
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import type { TextStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import { IconMute, IconStream, IconPrivate, IconWebPublic } from '../common/Icons'; type Props = $ReadOnly<{| color?: string, isPrivate: boolean, isMuted: boolean, isWebPublic: boolean | void, size: number, style?: TextStyleProp, |}>; export default function StreamIcon(props: Props): Node { const { color, style, isPrivate, isMuted, isWebPublic, size } = props; let Component = undefined; if (isMuted) { Component = IconMute; } else if (isPrivate) { Component = IconPrivate; } else if (isWebPublic ?? false) { Component = IconWebPublic; } else { Component = IconStream; } return <Component size={size} color={color} style={style} />; } ```
/content/code_sandbox/src/streams/StreamIcon.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
228
```javascript /* @flow strict-local */ import React, { useCallback, useContext } from 'react'; import type { Node } from 'react'; import { TranslationContext } from '../boot/TranslationProvider'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { useSelector } from '../react-redux'; import { getAuth } from '../selectors'; import { getStreamsByName } from '../subscriptions/subscriptionSelectors'; import Screen from '../common/Screen'; import EditStreamCard from './EditStreamCard'; import { showErrorAlert } from '../utils/info'; import { ApiError } from '../api/apiErrors'; import * as api from '../api'; import { privacyToStreamProps } from './streamsActions'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'create-stream'>, route: RouteProp<'create-stream', void>, |}>; export default function CreateStreamScreen(props: Props): Node { const _ = useContext(TranslationContext); const { navigation } = props; const auth = useSelector(getAuth); const streamsByName = useSelector(getStreamsByName); const handleComplete = useCallback( async ({ name, description, privacy }) => { // This will miss existing streams that the client can't know about; // for example, a private stream the user can't access. See comment // where we catch an `ApiError`, below. if (streamsByName.has(name)) { showErrorAlert(_('A stream with this name already exists.')); return false; } try { await api.createStream(auth, { name, description, ...privacyToStreamProps(privacy) }); return true; } catch (error) { // If the stream already exists but you can't access it (e.g., it's // private), then it won't be in the client's data structures, so // our client-side check above won't stop the request from being // made. In that case, we expect the server to always give an error, // because you can't subscribe to a stream that you can't access. // That error will have: // - error.message: `Unable to access stream (${streamName})`, or a // translation of that into the user's own language // - error.code: "BAD_REQUEST" (as of server feature level 126; // possibly the server should be more specific) if (error instanceof ApiError) { showErrorAlert(error.message); return false; } else { throw error; } } }, [auth, streamsByName, _], ); return ( <Screen title="Create new stream" padding> <EditStreamCard navigation={navigation} isNewStream initialValues={{ name: '', description: '', privacy: 'public' }} onComplete={handleComplete} /> </Screen> ); } ```
/content/code_sandbox/src/streams/CreateStreamScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
616
```javascript /* @flow strict-local */ import { type BoundedDiff, typesEquivalent } from '../generics'; import type { IsSupertype } from '../types'; /** General tip on writing tests for fancy generic types like these. */ // prettier-ignore function demo_need_value_flow() { // A basic principle of how Flow works is that it's focused on tracking // the, well, *flow* (the name is not a coincidence) of values from one // place in the program (a variable, a function parameter, an object // property, an expression, etc.) to another. // // Type-level expressions are secondary to this. Their implications often // only get worked through lazily, when some value-level flow makes it // necessary to do so. // // That means if you're testing some type-level operator like IsSupertype // or BoundedDiff, you'll typically need to create some value-level flows // to exercise it -- even for cases where the intent is that some choices // of type parameter result in an error of their own. // Here's a toy example of a generic type with an internal constraint: type IsString<S: string> = string; // IsString<T> should be an error for any T that isn't <: string. // And indeed it is, in a variety of contexts: // $FlowExpectedError[incompatible-type-arg] function f1<T>(x: T): IsString<T> { return 'b'; } // while compare: function f2<T: string>(x: T): IsString<'a'> { return 'b'; } function f3<T: string>(x: T): IsString<'a'> { return x; } // $FlowExpectedError[incompatible-type-arg] (x: string): IsString<number> => x; // $FlowExpectedError[incompatible-type-arg] (x: string): IsString<mixed> => x; // while compare: (x: string): IsString<string> => x; (x: string): IsString<'a'> => x; (x: string): IsString<empty> => x; // $FlowExpectedError[incompatible-type-arg] (x: IsString<mixed>): string => x; // while compare: (x: IsString<string>): string => x; // $FlowExpectedError[incompatible-type-arg] ('b': IsString<mixed>); // while compare: ('b': IsString<string>); // // // However. One thing those all have in common is that the offending // instantiation `IsString<>` appears as either the source or the // destination of some value-level flow. // For example, this return type had a returned value flowing into it: // $FlowExpectedError[incompatible-type-arg] (x: string): IsString<number> => x; // If we have the same bogus `IsString<>` type as a return type, but // avoid ever returning a value that has to flow to that return type, // then there's no error: (x: string): IsString<number> => { throw new Error(); }; // In the other direction, this parameter with a bogus type was the source // of a flow into the return value: // $FlowExpectedError[incompatible-type-arg] (x: IsString<mixed>): string => x; // We could flow it into somewhere else instead, and still get the error: // $FlowExpectedError[incompatible-type-arg] (x: IsString<mixed>): string => { (x: string); return 'b'; }; // But if it flows nowhere at all, there's no error: (x: IsString<mixed>): string => { x; return 'b'; }; (x: IsString<mixed>): string => 'b'; // Similarly if we just mention the bogus type in another way but with no // value-level flows to or from it, there's no error: declare var x: IsString<number>; // // // Happily this point isn't really a warning -- there's no need to worry // about getting anything wrong by forgetting it. As long as you set out // to write tests for the error case, if you forget this point then you'll // see that your tests are failing to fail. // // Rather, this is a tip for how to solve that problem if you run into it: // cause some value to flow to or from the bogus type, and then Flow // should notice that the type is bogus. } /** A subtler tip on writing tests for fancy generic types like these. */ function demo_short_circuits() { // As seen above, in order to test one of these types you need to exercise // it with some value-level flow to or from it. // // A further wrinkle is that if your value-level flow is necessarily OK // thanks to some general rule of the type system, some reasoning that // doesn't depend on the details of the bogus type (that you're trying to // test is indeed seen as bogus) then Flow may apply that rule and // short-circuit any closer inspection of the specific types on each side. // // In particular (and we'll demo each of these below): // * If the flow is from `empty`, it succeeds. (Even if the other end is // an internally-bogus type.) // * If the flow is to `mixed`, it succeeds. (Ditto.) // * If the flow is from some type to itself, it succeeds (even if that // type is internally bogus.) // // (The jargon for these facts is: `empty` is a "bottom" type; `mixed` is // a "top" type; and the subtype relation (the ability to flow from one // type to another) is "reflexive".) // // It seems bad that Flow can accept a program, with no errors, when it // contains a type somewhere that's bogus like `IsString<number>`. // Ideally Flow would reject those, because it's confusing. (One likely // reason it accepts them is for performance: each of these situations is // quick to check for, and then Flow gets to check off that flow as valid // and move on.) // // But from Flow's perspective this is a fundamentally sound thing to do, // because it can't enable something actually going wrong in the program // at runtime. That is, if some place in the program (some expression, // variable, object property, etc.) gets a bogus type, and if at runtime // that place actually gets reached so that there's some actual value that // supposedly has that bogus type, then (modulo some other issue in Flow) // it must be because of a type error somewhere in the program. // // In particular, if one of the rules above prevents an error we would // have otherwise gotten about a bogus type, and a value ever actually // reaches that bogus type at runtime, then there must be an error // somewhere else too: // * The `empty` type, as the name suggests, has no values. So if // something with a bogus type gets a value at runtime through a flow // from `empty`, then there must have been a type error along the way // to get the value into the `empty`-typed spot in the first place. // * A flow from a bogus type to `mixed` leads only from, not to, a bogus // type. // * If some point A with a bogus type T gets a value at runtime through // a flow from some other point B with the same bogus type T, then the // value must have already before then gotten into point B, with its // bogus type T. // // For the `empty` case in particular, here's a more theoretical way of // putting it that may be helpful. The type `empty` is the type // interpretation of logical falsity: if you have an expression of type // `empty`, then reaching that expression at runtime means asserting // falsehood. And "ex falso quodlibet": from falsehood, anything follows. // // // Here's the same toy example from before. type IsString<S: string> = string; // IsString<T> should be an error for any T that isn't <: string. // Here we flow something into a bogus IsString<T>, and get an error: // $FlowExpectedError[incompatible-type-arg] (x: string): IsString<number> => x; // But if the source of the flow is `empty`, there's no error: (x: empty): IsString<number> => x; // Similarly, a flow somewhere from a bogus IsString<T> is an error: // $FlowExpectedError[incompatible-type-arg] (x: IsString<number>): string => x; // but not if that somewhere is `mixed`: (x: IsString<number>): mixed => x; // Nor is flowing from the bogus type to itself an error: (x: IsString<number>): IsString<number> => x; // So if we want to test that `IsString<number>` is bogus as expected, // the solution is to flow from some type that isn't itself or `empty`: // $FlowExpectedError[incompatible-type-arg] (x: string): IsString<number> => x; // or to flow to some type that isn't itself or `mixed`: // $FlowExpectedError[incompatible-type-arg] (x: IsString<number>): string => x; // // // But what if the type already is no higher than `empty`? type IsString2<S: string> = empty; // If we flow from a type that isn't `empty`, the flow itself will be an // error. // Well, as one solution, we can flow *from* it instead: // $FlowExpectedError[incompatible-type-arg] (x: IsString2<number>): string => x; // Alternatively, we can still flow to it from some non-empty type: // $FlowExpectedError[incompatible-type-arg] // $FlowExpectedError[incompatible-return] (x: string): IsString2<number> => x; // It'll come with an additional suppression for the flow itself. // But that one will have an error code like `incompatible-return` or // `incompatible-cast`. The error in the type arguments passed to the // generic will have the distinctive error code `incompatible-type-arg`. // So the FlowExpectedError with that code checks for the error we're // trying to test for. // // // Happily, like the previous demo, this is not really a warning -- you // don't need to worry about it in advance, because if you run into it // you'll be alerted by your tests failing to find the expected errors. // // If you do, avoid flowing from `empty` or to `mixed` (or from the type // to itself.) Instead, find a less extreme type to use for the other end // of the flow. } /** This seems like a bug in Flow. Fortunately pretty avoidable. */ // TODO: make a bug report :-) (there doesn't seem to be an existing one) function demo_variance_short_circuit() { // In addition to the perfectly sound short circuits above, Flow has // another: // * If the flow is between two instances of the same generic type, // and that type has variance markings and the appropriate flows // between the respective type arguments succeed, then the overall flow // succeeds. (The example below may make this clearer.) // // This would be OK so long as when the lower type (the source of the // flow) in this situation is valid, that would imply the upper type (the // sink of the flow) is as well. If that were true, then: // * If the upper type is bogus, then the lower type is bogus too. So if // the upper type gets a value at runtime through this flow, then there // was already a value in the bogus lower type. // // Awkwardly, that does not seem to be true. // Define variations on our toy example above, now where the generic type // is covariant or contravariant. type IsStringCovar<+S: string> = string; type IsStringContra<-S: string> = string; // The `+` just means that IsStringCovar<S> <: IsStringCovar<T> whenever // S <: T. (When we make the definition, Flow checks this is actually // true: which it is, because `string <: string` in any event.) // // Conversely, the `-` just means that IsStringContra<S> <: IsStringContra<T> // whenever T <: S (note the swapping of sides). // // And now that we've declared those facts about these type aliases, and // Flow has checked them, Flow is prepared to use them freely. // Here's a flow between two equally-bogus IsStringCovar<> types. // That's fine in itself. (x: IsStringCovar<3>): IsStringCovar<number> => x; // But here's a flow from a valid IsStringCovar<> to an invalid one. // Flow still accepts it. (x: IsStringCovar<string>): IsStringCovar<number | string> => x; // And here's some perfectly runnable code, with a bogus IsStringCovar<> // on an expression that actually gets a value at runtime. { const f = (x: IsStringCovar<string>): IsStringCovar<number | string> => x; f('a'); // That expression has type IsStringCovar<number | string>. // Which is not a valid type, because IsStringCovar has a `string` bound // on its type parameter. // We can even have the value of bogus type get actually used: console.log(String(f('a'))); // There's no `any` there -- flowlib has on `class String`: // static (value:mixed):string; // so it takes a `mixed` and that's perfectly legit. // // The flows here, up to the argument to `String`, are // 'a' -> IsStringCovar<string> -> IsStringCovar<number | string> -> mixed // and the first is just fine; the second is accepted because variance; // and the third is accepted because of the `mixed` short circuit // described in `demo_short_circuits` above. // It's doubtful to exactly call that an unsoundness, because // IsStringCovar is such a toy example that the constraint in it doesn't // really matter. But it's a bit of a warning sign for sticking bounds // in generic definitions and counting on those to always be observed, // certainly when the constraints don't manifest in any more "real" way. // // Fortunately this issue is avoidable as long as when we choose to put // a variance annotation on a generic type's parameters, we check the // annotation's validity for ourselves. See below. } // Here's the same demo using a variation of the `IsSupertype` alias we // actually use in our code. type BadIsSupertype<+S, +T: S> = S; // (The real `IsSupertype` has `+S, -T: S`. That makes it harmless just // like `IsStringContra`, as below. See also test_IsSupertype_variance.) { const f = (x: BadIsSupertype<string, string>): BadIsSupertype<string, number | string> => x; const y: BadIsSupertype<string, number | string> = f('a'); console.log(String(f('a'))); // TODO try to construct a more-real demo, using BadIsSupertype } // On the other hand `IsStringContra` is harmless. We can make a flow // that Flow accepts *from* an invalid IsStringContra<> to a valid one: (x: IsStringContra<number | string>): IsStringContra<string> => x; // But if the source of the flow is a valid IsStringContra<>, then any // flow Flow would accept on account of the variance rule is one where the // sink is also valid. For example this is rejected: // $FlowExpectedError[incompatible-return] (x: IsStringContra<string>): IsStringContra<number | string> => x; // That's because for Flow to accept `IsStringContra<S> <: IsStringContra<T>` // on account of the variance of `IsStringContra`, we must have `T <: S` // (where the direction is swapped); that's what the `-S` in the definition // means. // // And on the other hand if `IsStringContra<S>` is valid, then `S <: string`. // // So if both of those are true, then `T <: S <: string`, so `T <: string` // and `IsStringContra<T>` is valid too. // In short, if the constraint `S: string` was satisfied and you // *increase* `S`, then it can stop being satisfied, so a generic type // definition with `+S: string` causes Flow to accept flows from a valid // type to an invalid one. But if you *decrease* `S`, then the constraint // remains satisfied; so a flow that gets accepted because of the variance // of a parameter `-S: string` can go from a valid type only to another // valid type. // Two possible views of what the Flow bug is here (and they're not // mutually exclusive; arguably it's two bugs) are: // // * It shouldn't short-circuit here (and maybe not in some of the other // cases above, in `demo_short_circuit`); it should detect when a // type-expression violates a generic type's stated bounds, even when // just evaluating a flow that the variance says is OK. // // * It shouldn't have accepted our definition of `IsStringCovar`, // because increasing `S` can cause the constraint `S: string` to stop // being satisfied. OTOH `IsStringContra` is fine, because decreasing // `S` always preserves the constraint. // // If it enforced either of those rules, there'd be no issue. So to avoid // this bug, it suffices for us to manually enforce either one of them. // // The first one applies anywhere we use the generic type, which is // potentially a lot of places and so is hard to systematically make a // practice of. But the second one only applies when *writing* a generic // type alias, and in particular one that makes fancy use of bounds. That // isn't something we write very often, so watching for this there is // fairly tractable. // // So to avoid this bug, what that comes down to is that it suffices to // not write a definition like `IsStringCovar`. This means: when adding // variance annotations +/- to the type parameters of a generic type // alias, we should watch the constraints and enforce that the stated // variance doesn't break them. } function test_IsSupertype() { // Test the basics, relative to a primitive type. // `number` is a supertype of `empty` and itself (1: IsSupertype<number, empty>); (1: IsSupertype<number, number>); // but not `mixed` or `string`. // $FlowExpectedError[incompatible-type-arg] (1: IsSupertype<number, mixed>); // $FlowExpectedError[incompatible-type-arg] (1: IsSupertype<number, string>); // Test the resulting type (as opposed to whether the type is instantiable // at all, which is the main point of `IsSupertype`.) (x: IsSupertype<number, number>): number => x; (x: number): IsSupertype<number, number> => x; (x: IsSupertype<number, 3>): number => x; (x: number): IsSupertype<number, 3> => x; // `empty` isn't a supertype of anything but itself. // $FlowExpectedError[incompatible-type-arg] (x: IsSupertype<empty, number>): number => x; // Test on unions. (1: IsSupertype<number | void, number>); // $FlowExpectedError[incompatible-type-arg] (1: IsSupertype<number, number | void>); } function test_IsSupertype_object_types() { // A value to cast. const a: {| a: number |} = { a: 1 }; // Check that the casts don't themselves cause errors, // so the errors we find below really do come from IsSupertype. (a: { a: number, ... }); (a: {| a: number |}); (a: {| +a: number |}); // And a quick demo that IsSupertype is reflexive, i.e. T <: T for each T. (a: IsSupertype<{ a: number, ... }, { a: number, ... }>); (a: IsSupertype<{| a: number |}, {| a: number |}>); (a: IsSupertype<{| +a: number |}, {| +a: number |}>); // Exact <: inexact, strictly. (a: IsSupertype<{ a: number, ... }, {| a: number |}>); // $FlowExpectedError[incompatible-exact] (a: IsSupertype<{| a: number |}, { a: number, ... }>); // Read-only properties are covariant. (a: IsSupertype<{| +a: number |}, {| +a: empty |}>); // $FlowExpectedError[incompatible-type-arg] (a: IsSupertype<{| +a: number |}, {| +a: mixed |}>); // Read-write properties are invariant. // $FlowExpectedError[incompatible-type-arg] (a: IsSupertype<{| a: number |}, {| a: empty |}>); // $FlowExpectedError[incompatible-type-arg] (a: IsSupertype<{| a: number |}, {| a: mixed |}>); // Same variance tests, this time with abstract types B <: A. function variance_again<A, B: A>() { // Now we have types B and A, which we know nothing about except that // B is a subtype of A. Quick demo of that setup: (x: B): A => x; // $FlowExpectedError[incompatible-return] (x: A): B => x; // Read-only properties are covariant, again. (x: IsSupertype<{| +a: A |}, {| +a: B |}>): { ... } => x; // $FlowExpectedError[incompatible-type-arg] (x: IsSupertype<{| +a: B |}, {| +a: A |}>): { ... } => x; // Read-write properties are invariant, again. // $FlowExpectedError[incompatible-type-arg] (x: IsSupertype<{| a: A |}, {| a: B |}>): { ... } => x; // $FlowExpectedError[incompatible-type-arg] (x: IsSupertype<{| a: B |}, {| a: A |}>): { ... } => x; } // Read-write <: read-only, strictly. (a: IsSupertype<{| +a: number |}, {| a: number |}>); // $FlowExpectedError[incompatible-variance] (a: IsSupertype<{| a: number |}, {| +a: number |}>); // Another value to cast. const ab: {| a: number, b: number |} = { a: 1, b: 2 }; (ab: { a: number, b: number, ... }); (ab: {| a: number, b: number |}); // Extra properties; exact and inexact doing their jobs. (a: IsSupertype<{ a: number, ... }, { a: number, b: number, ... }>); (a: IsSupertype<{ a: number, ... }, {| a: number, b: number |}>); // $FlowExpectedError[prop-missing] (ab: IsSupertype<{ a: number, b: number, ... }, { a: number, ... }>); // $FlowExpectedError[prop-missing] // $FlowExpectedError[incompatible-exact] (ab: IsSupertype<{| a: number, b: number |}, { a: number, ... }>); // $FlowExpectedError[prop-missing] // $FlowExpectedError[incompatible-exact] (a: IsSupertype<{| a: number |}, { a: number, b: number, ... }>); // $FlowExpectedError[prop-missing] (a: IsSupertype<{| a: number |}, {| a: number, b: number |}>); } function test_IsSupertype_variance() { // Test that IsSupertype doesn't exercise the Flow loophole demonstrated // with BadIsSupertype above. { // $FlowExpectedError[incompatible-return] const f = (x: IsSupertype<string, string>): IsSupertype<string, number | string> => x; const y: IsSupertype<string, number | string> = f('a'); } // More succinctly: // $FlowExpectedError[incompatible-return] (x: IsSupertype<string, string>): IsSupertype<string, number | string> => x; // On the other hand, IsSupertype has all the variance it can legitimately // have. It's covariant in its first parameter: (x: IsSupertype<string, string>): IsSupertype<number | string, string> => x; // as well as *contravariant* in its second parameter: (x: IsSupertype<string, string>): IsSupertype<string, 'a'> => x; } function test_typesEquivalent() { // $ReadOnly means the same thing as putting a `+` variance sigil // on each property, so these are two ways of spelling the same thing. typesEquivalent<$ReadOnly<{| x: number |}>, {| +x: number |}>(); // $FlowExpectedError[incompatible-call] - These are different types :-) typesEquivalent<number, number | void>(); // prettier-ignore // Demonstrate the use of `$Diff`. typesEquivalent<$Diff<{| x: number, y: number |}, {| y: mixed |}>, {| x: number |}>(); } // prettier-ignore function test_typesEquivalent_$Diff_surprise() { // These two types are "equivalent" in that a value of either type can be // used where the other type is expected. typesEquivalent<{| x?: mixed |}, {| x: mixed |}>(); // But they are *not* always interchangeable when passed to a type-level // operation (what Flow docs call a "type destructor"), like `$Diff`. type S = {| x: number |}; typesEquivalent<$Diff<S, {| x?: mixed |}>, // $FlowExpectedError[prop-missing] $Diff<S, {| x: mixed |}>>(); // Instead, subtracting `x?: mixed` just makes the property optional: typesEquivalent<$Diff<S, {| x?: mixed |}>, {| x?: number |}>(); // while subtracting `x: mixed` actually removes it: typesEquivalent<$Diff<S, {| x: mixed |}>, {||}>(); { // Aside: The fact that these are equivalent in the first place is // arguably an unsoundness bug in Flow: it means we can end up treating // a value `{}` as being of type `{| x: mixed |}`, even though the // latter on its face should always require a property `x`. // And indeed we can't give such a value that type directly: // $FlowExpectedError[incompatible-exact] const a1: {| x: mixed |} = {}; // $FlowExpectedError[incompatible-exact] // $FlowExpectedError[prop-missing] const a2: {| x: mixed |} = ({}: {||}); // $FlowExpectedError[prop-missing] const a3: {| x: mixed |} = Object.freeze({}); // But we can if we launder it through `{| x?: mixed |}`: const b1: {| x?: mixed |} = Object.freeze({}); const b2: {| x: mixed |} = b1; // This is mostly OK in practice because if we actually try to read the // `x` property on one of these values, we get `undefined` -- which is a // perfectly good value of type `mixed`, so we had to be prepared to // handle it in any case. { // BTW the `Object.freeze` is just to avoid an unrelated Flow quirk // related to "unsealed" object types: // path_to_url#issuecomment-695064325 // We can get the same result by including any other properties at all // in the type, which makes the example a bit longer but probably more // realistic anyway. // Here's the error again on trying to apply that type directly: // $FlowExpectedError[prop-missing] const c1: {| x: mixed, y: mixed |} = { y: 3 }; // $FlowExpectedError[prop-missing] const c2: {| x: mixed, y: mixed |} = ({ y: 3 }: {| y: mixed |}); // And here we are again laundering it through an optional `x`: const d1: {| x?: mixed, y: mixed |} = { y: 3 }; const d2: {| x: mixed, y: mixed |} = d1; } } } // prettier-ignore function test_BoundedDiff() { // Here we use functions, to avoid having to ever actually make a value of // the various types. // Basic happy use. typesEquivalent<BoundedDiff<{| +a: string, +b: number |}, {| +b: number |}>, {| +a: string |}>(); // Basic happy use, checking only that the type is valid at all (and is // some object type). This gives a baseline for some test cases below, // where we expect an error from BoundedDiff itself. (x: BoundedDiff<{| +a: string, +b: number |}, {| +b: number |}>): { ... } => x; // No extraneous properties allowed. // $FlowExpectedError[prop-missing] (x: BoundedDiff<{| +a: string, +b: number |}, {| +c: number |}>): { ... } => x; // For a given property, must be subtracting with (non-strict) subtype. (x: BoundedDiff<{| +a: string, +b: number |}, {| +b: 3 |}>): { ... } => x; (x: BoundedDiff<{| +a: string, +b: 3 |}, {| +b: 3 |}>): { ... } => x; // $FlowExpectedError[incompatible-type-arg] (x: BoundedDiff<{| +a: string, +b: 3 |}, {| +b: number |}>): { ... } => x; // Property is removed even if subtracting with a proper subtype. typesEquivalent<BoundedDiff<{| +a: string, +b: number |}, {| +b: 3 |}>, {| +a: string |}>(); typesEquivalent<BoundedDiff<{| +a: string, +b: mixed |}, {| +b: empty |}>, {| +a: string |}>(); } ```
/content/code_sandbox/src/__flow-tests__/generics-tests.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
7,289
```javascript /* @flow strict-local */ import React, { useCallback, useMemo } from 'react'; import type { Node } from 'react'; import { View, SectionList } from 'react-native'; import { useNavigation } from '../react-navigation'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import type { Subscription } from '../types'; import { createStyleSheet } from '../styles'; import { useDispatch, useSelector } from '../react-redux'; import LoadingBanner from '../common/LoadingBanner'; import SectionSeparatorBetween from '../common/SectionSeparatorBetween'; import SearchEmptyState from '../common/SearchEmptyState'; import { streamNarrow } from '../utils/narrow'; import { getUnreadByStream } from '../selectors'; import { getSubscriptions } from '../directSelectors'; import { doNarrow } from '../actions'; import { caseInsensitiveCompareFunc } from '../utils/misc'; import StreamItem from './StreamItem'; import ModalNavBar from '../nav/ModalNavBar'; import NavRow from '../common/NavRow'; const styles = createStyleSheet({ container: { flex: 1, flexDirection: 'column', }, list: { flex: 1, flexDirection: 'column', }, }); type Props = $ReadOnly<{| navigation: AppNavigationProp<'subscribed'>, route: RouteProp<'subscribed', void>, |}>; type FooterProps = $ReadOnly<{||}>; function AllStreamsButton(props: FooterProps): Node { const navigation = useNavigation(); const handlePressAllScreens = useCallback(() => { navigation.push('all-streams'); }, [navigation]); return <NavRow title="All streams" titleBoldUppercase onPress={handlePressAllScreens} />; } export default function SubscriptionsScreen(props: Props): Node { const dispatch = useDispatch(); const subscriptions = useSelector(getSubscriptions); const unreadByStream = useSelector(getUnreadByStream); const sections = useMemo(() => { const sortedSubscriptions = subscriptions .slice() .sort((a, b) => caseInsensitiveCompareFunc(a.name, b.name)); return [ { key: 'Pinned', data: sortedSubscriptions.filter(x => x.pin_to_top) }, { key: 'Unpinned', data: sortedSubscriptions.filter(x => !x.pin_to_top) }, ]; }, [subscriptions]); const handleNarrow = useCallback( stream => dispatch(doNarrow(streamNarrow(stream.stream_id))), [dispatch], ); return ( <View style={styles.container}> {/* Consumes the top inset. */} <ModalNavBar canGoBack={false} title="Streams" /> <LoadingBanner /> {subscriptions.length === 0 ? ( <SearchEmptyState text="No streams found" /> ) : ( <SectionList style={styles.list} sections={sections} extraData={unreadByStream} initialNumToRender={20} keyExtractor={item => item.stream_id} renderItem={({ item }: { item: Subscription, ... }) => ( <StreamItem streamId={item.stream_id} name={item.name} iconSize={16} isPrivate={item.invite_only} isWebPublic={item.is_web_public} description="" color={item.color} unreadCount={unreadByStream[item.stream_id]} isMuted={item.in_home_view === false} // if 'undefined' is not muted offersSubscribeButton={false} // isSubscribed is ignored when offersSubscribeButton false onPress={handleNarrow} /> )} SectionSeparatorComponent={SectionSeparatorBetween} ListFooterComponent={AllStreamsButton} /> )} </View> ); } ```
/content/code_sandbox/src/streams/SubscriptionsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
802
```javascript /* @flow strict-local */ import type { Subscription } from '../types'; /** * Whether push notifications are enabled for this stream. * * The `userSettingsStreamNotification` parameter should correspond to * `state.settings.streamNotification`. */ export default ( subscription: Subscription | void, userSettingStreamNotification: boolean, ): boolean => subscription?.push_notifications ?? userSettingStreamNotification; ```
/content/code_sandbox/src/streams/getIsNotificationEnabled.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
80
```javascript /* @flow strict-local */ import React, { useState, useCallback } from 'react'; import type { Node } from 'react'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import type { UserOrBot } from '../types'; import { useSelector } from '../react-redux'; import Screen from '../common/Screen'; import { navigateBack } from '../actions'; import * as api from '../api'; import { getAuth, getStreamForId } from '../selectors'; import UserPickerCard from '../user-picker/UserPickerCard'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'invite-users'>, route: RouteProp<'invite-users', {| streamId: number |}>, |}>; export default function InviteUsersScreen(props: Props): Node { const { navigation } = props; const auth = useSelector(getAuth); const stream = useSelector(state => getStreamForId(state, props.route.params.streamId)); const [filter, setFilter] = useState<string>(''); const handleInviteUsers = useCallback( (selected: $ReadOnlyArray<UserOrBot>) => { const recipients = selected.map(user => user.email); // This still uses a stream name (#3918) because the API method does; see there. api.subscriptionAdd(auth, [{ name: stream.name }], recipients); navigation.dispatch(navigateBack()); }, [auth, navigation, stream.name], ); return ( <Screen search scrollEnabled={false} searchBarOnChange={setFilter}> <UserPickerCard filter={filter} onComplete={handleInviteUsers} showOwnUser={false} /> </Screen> ); } ```
/content/code_sandbox/src/streams/InviteUsersScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
356
```javascript /* @flow strict-local */ import type { Stream, ThunkAction } from '../types'; import * as api from '../api'; import { getAuth, getZulipFeatureLevel } from '../selectors'; import { ensureUnreachable } from '../generics'; import type { SubsetProperties } from '../generics'; export type Privacy = 'web-public' | 'public' | 'invite-only-public-history' | 'invite-only'; type StreamPrivacyProps = SubsetProperties< Stream, // If making any optional, read discussion first: // path_to_url#narrow/stream/378-api-design/topic/PATCH.20.2Fstreams.2F.7Bstream_id.7D/near/1383984 { +is_web_public: mixed, +invite_only: mixed, +history_public_to_subscribers: mixed, ... }, >; export const streamPropsToPrivacy = (streamProps: StreamPrivacyProps): Privacy => { if (streamProps.is_web_public === true) { return 'web-public'; } else if (streamProps.invite_only === false) { return 'public'; } else if (streamProps.history_public_to_subscribers === true) { return 'invite-only-public-history'; } else { return 'invite-only'; } }; export const privacyToStreamProps = (privacy: Privacy): $Exact<StreamPrivacyProps> => { switch (privacy) { case 'web-public': return { is_web_public: true, invite_only: false, history_public_to_subscribers: true }; case 'public': return { is_web_public: false, invite_only: false, history_public_to_subscribers: true }; case 'invite-only-public-history': return { is_web_public: false, invite_only: true, history_public_to_subscribers: true }; case 'invite-only': return { is_web_public: false, invite_only: true, history_public_to_subscribers: false }; default: ensureUnreachable(privacy); // (Unreachable as long as the cases are exhaustive.) throw new Error(); } }; export const updateExistingStream = ( id: number, changedValues: {| +name?: string, +description?: string, +privacy?: Privacy |}, ): ThunkAction<Promise<void>> => async (dispatch, getState) => { const state = getState(); const maybeEncode = (value: string): string => // Adapt to a server API change that was accidentally incompatible: // path_to_url#issuecomment-852254404 // path_to_url#issuecomment-946362729 // TODO(#4659): Ideally this belongs inside `api.updateStream`. // TODO(server-4.0): Simplify this (if it hasn't already moved.) getZulipFeatureLevel(state) >= 64 ? value : JSON.stringify(value); const auth = getAuth(state); const updates = {}; if (changedValues.name !== undefined) { updates.new_name = maybeEncode(changedValues.name); } if (changedValues.description !== undefined) { updates.description = maybeEncode(changedValues.description); } if (changedValues.privacy !== undefined) { const streamProps = privacyToStreamProps(changedValues.privacy); // Only send is_web_public if the server will recognize it. // TODO(server-5.0): Remove conditional. if (getZulipFeatureLevel(state) >= 98) { updates.is_web_public = streamProps.is_web_public; } updates.is_private = streamProps.invite_only; updates.history_public_to_subscribers = streamProps.history_public_to_subscribers; } if (Object.keys(updates).length === 0) { return; } await api.updateStream(auth, id, updates); }; ```
/content/code_sandbox/src/streams/streamsActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
813
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { Stream, Subscription } from '../types'; import styles, { createStyleSheet } from '../styles'; import ZulipText from '../common/ZulipText'; import StreamIcon from './StreamIcon'; import { NULL_SUBSCRIPTION } from '../nullObjects'; const componentStyles = createStyleSheet({ streamRow: { flexDirection: 'row', alignItems: 'center', }, streamText: { fontSize: 20, }, descriptionText: { opacity: 0.8, marginTop: 16, }, streamIcon: { marginRight: 8, }, }); type Props = $ReadOnly<{| stream: Stream, subscription?: Subscription, |}>; export default function StreamCard(props: Props): Node { const { stream, subscription } = props; return ( <View style={styles.padding}> <View style={componentStyles.streamRow}> <StreamIcon style={componentStyles.streamIcon} size={22} color={subscription?.color || NULL_SUBSCRIPTION.color} isMuted={subscription ? !subscription.in_home_view : false} isPrivate={stream.invite_only} isWebPublic={stream.is_web_public} /> <ZulipText style={componentStyles.streamText} text={stream.name} numberOfLines={1} ellipsizeMode="tail" /> </View> {stream.description.length > 0 && ( <ZulipText style={componentStyles.descriptionText} text={stream.description} /> )} </View> ); } ```
/content/code_sandbox/src/streams/StreamCard.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
366
```javascript /* @flow strict-local */ import React, { useCallback, useRef, useContext } from 'react'; import type { Node } from 'react'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { useSelector, useDispatch } from '../react-redux'; import { updateExistingStream } from '../actions'; import { getStreamForId } from '../selectors'; import Screen from '../common/Screen'; import EditStreamCard from './EditStreamCard'; import { streamPropsToPrivacy } from './streamsActions'; import { ApiError } from '../api/apiErrors'; import { showErrorAlert } from '../utils/info'; import { TranslationContext } from '../boot/TranslationProvider'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'edit-stream'>, route: RouteProp<'edit-stream', {| streamId: number |}>, |}>; export default function EditStreamScreen(props: Props): Node { const { navigation } = props; const dispatch = useDispatch(); const stream = useSelector(state => getStreamForId(state, props.route.params.streamId)); const _ = useContext(TranslationContext); // What we pass for EditStreamCard's `initialValues` should be constant. const initialValues = useRef({ name: stream.name, description: stream.description, privacy: streamPropsToPrivacy(stream), }).current; const handleComplete = useCallback( async changedValues => { try { await dispatch(updateExistingStream(stream.stream_id, changedValues)); return true; } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url if (error instanceof ApiError) { showErrorAlert( _('Cannot apply requested settings'), // E.g., "Must be an organization or stream administrator", with // code UNAUTHORIZED_PRINCIPAL, when trying to change an // existing stream's privacy setting when unauthorized. The // server could be more specific with this error. error.message, ); return false; } else { throw error; } } }, [stream, dispatch, _], ); return ( <Screen title="Edit stream" padding> <EditStreamCard navigation={navigation} isNewStream={false} initialValues={initialValues} onComplete={handleComplete} /> </Screen> ); } ```
/content/code_sandbox/src/streams/EditStreamScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
507
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { useSelector } from '../react-redux'; import { delay } from '../utils/async'; import SwitchRow from '../common/SwitchRow'; import Screen from '../common/Screen'; import ZulipButton from '../common/ZulipButton'; import { getSettings } from '../directSelectors'; import { getAuth, getOwnUser, getStreamForId } from '../selectors'; import StreamCard from './StreamCard'; import { IconPin, IconMute, IconNotifications, IconEdit, IconPlusSquare } from '../common/Icons'; import styles from '../styles'; import { getSubscriptionsById } from '../subscriptions/subscriptionSelectors'; import * as api from '../api'; import getIsNotificationEnabled from './getIsNotificationEnabled'; import { roleIsAtLeast } from '../permissionSelectors'; import { Role } from '../api/permissionsTypes'; type Props = $ReadOnly<{| navigation: AppNavigationProp<'stream-settings'>, route: RouteProp<'stream-settings', {| streamId: number |}>, |}>; export default function StreamSettingsScreen(props: Props): Node { const { navigation } = props; const auth = useSelector(getAuth); const isAtLeastAdmin = useSelector(state => roleIsAtLeast(getOwnUser(state).role, Role.Admin)); const stream = useSelector(state => getStreamForId(state, props.route.params.streamId)); const subscription = useSelector(state => getSubscriptionsById(state).get(props.route.params.streamId), ); const userSettingStreamNotification = useSelector(state => getSettings(state).streamNotification); const handleTogglePinStream = useCallback( (newValue: boolean) => { api.setSubscriptionProperty(auth, stream.stream_id, 'pin_to_top', newValue); }, [auth, stream], ); const handleToggleMuteStream = useCallback( (newValue: boolean) => { api.setSubscriptionProperty(auth, stream.stream_id, 'is_muted', newValue); }, [auth, stream], ); const handlePressEdit = useCallback(() => { navigation.push('edit-stream', { streamId: stream.stream_id }); }, [navigation, stream.stream_id]); const handlePressEditSubscribers = useCallback(() => { navigation.push('invite-users', { streamId: stream.stream_id }); }, [navigation, stream.stream_id]); const handlePressSubscribe = useCallback(() => { // This still uses a stream name (#3918) because the API method does; see there. api.subscriptionAdd(auth, [{ name: stream.name }]); }, [auth, stream]); const handlePressUnsubscribe = useCallback(() => { // This still uses a stream name (#3918) because the API method does; see there. api.subscriptionRemove(auth, [stream.name]); }, [auth, stream]); const handleToggleStreamPushNotification = useCallback(() => { const currentValue = getIsNotificationEnabled(subscription, userSettingStreamNotification); api.setSubscriptionProperty(auth, stream.stream_id, 'push_notifications', !currentValue); }, [auth, stream, subscription, userSettingStreamNotification]); return ( <Screen title="Stream"> <StreamCard stream={stream} subscription={subscription} /> {subscription && ( <> <SwitchRow Icon={IconPin} label="Pinned" value={subscription.pin_to_top} onValueChange={handleTogglePinStream} /> <SwitchRow Icon={IconMute} label="Muted" value={subscription.in_home_view === false} onValueChange={handleToggleMuteStream} /> <SwitchRow Icon={IconNotifications} label="Notifications" value={getIsNotificationEnabled(subscription, userSettingStreamNotification)} onValueChange={handleToggleStreamPushNotification} /> </> )} <View style={styles.padding}> {isAtLeastAdmin && ( // TODO: Group all the stream's attributes together (name, // description, policies, etc.), with an associated "Edit" // button that gives a UI for changing those attributes. For the // grouping, try react-native-paper's `Card`, with a // ZulipTextButton in its `Card.Actions`. See // path_to_url // Or their `Surface`: // path_to_url <ZulipButton style={styles.marginTop} Icon={IconEdit} text="Edit stream" secondary onPress={() => delay(handlePressEdit)} /> )} <ZulipButton style={styles.marginTop} Icon={IconPlusSquare} text="Add subscribers" secondary onPress={() => delay(handlePressEditSubscribers)} /> {subscription ? ( <ZulipButton style={styles.marginTop} text="Unsubscribe" secondary onPress={() => delay(handlePressUnsubscribe)} /> ) : ( <ZulipButton style={styles.marginTop} text="Subscribe" secondary onPress={() => delay(handlePressSubscribe)} /> )} </View> </Screen> ); } ```
/content/code_sandbox/src/streams/StreamSettingsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,150
```javascript /* @flow strict-local */ import React, { useContext, useMemo } from 'react'; import type { Node } from 'react'; import { View, Pressable } from 'react-native'; // $FlowFixMe[untyped-import] import { useActionSheet } from '@expo/react-native-action-sheet'; import { showErrorAlert } from '../utils/info'; import { showStreamActionSheet } from '../action-sheets'; import type { ShowActionSheetWithOptions } from '../action-sheets'; import { TranslationContext } from '../boot/TranslationProvider'; import { useDispatch, useSelector, useGlobalSelector } from '../react-redux'; import { getAuth, getRealmUrl, getFlags, getSubscriptionsById, getStreamsById, getOwnUser, getSettings, getGlobalSettings, } from '../selectors'; import { ThemeContext, BRAND_COLOR, HIGHLIGHT_COLOR, HALF_COLOR } from '../styles'; import ZulipText from '../common/ZulipText'; import Touchable from '../common/Touchable'; import UnreadCount from '../common/UnreadCount'; import { foregroundColorFromBackground } from '../utils/color'; import { IconPlus, IconDone, IconCaretUp, IconCaretDown } from '../common/Icons'; import StreamIcon from './StreamIcon'; import { useNavigation } from '../react-navigation'; type Props = $ReadOnly<{| name: string, streamId: number, description?: string, handleExpandCollapse?: (id: number) => void, isCollapsed?: boolean, isMuted: boolean, isPrivate: boolean, isSubscribed?: boolean, isWebPublic: boolean | void, color?: string, backgroundColor?: string, unreadCount?: number, iconSize: number, offersSubscribeButton?: boolean, extraPaddingEnd?: number, // These stream names are here for a mix of good reasons and (#3918) bad ones. // To audit all uses, change `name` to write-only (`-name:`), and run Flow. onPress: ({ stream_id: number, name: string, ... }) => void, onSubscribeButtonPressed?: ({ stream_id: number, name: string, ... }, newValue: boolean) => void, |}>; /** * A single-line list item to show a stream or stream subscription. * * Many of the props must correspond to certain properties of a Stream or * Subscription. * * @prop name - the stream's name * @prop description - the stream's description * @prop isMuted - false for a Stream; !sub.in_home_view for Subscription * @prop isPrivate - .invite_only for a Stream or a Subscription * @prop isSubscribed - whether the user is subscribed to the stream; * ignored (and can be any value) unless offersSubscribeButton is true * @prop color - if provided, MUST be .color on a Subscription * @prop backgroundColor - if provided, MUST be .color on a Subscription * * @prop unreadCount - number of unread messages * @prop iconSize * @prop offersSubscribeButton - whether to offer a subscribe/unsubscribe button * @prop onPress - press handler for the item * @prop onSubscribeButtonPressed */ export default function StreamItem(props: Props): Node { const { streamId, name, description, color, backgroundColor, handleExpandCollapse, isCollapsed, isPrivate, isMuted, isWebPublic, isSubscribed = false, iconSize, offersSubscribeButton = false, unreadCount, extraPaddingEnd = 0, onPress, onSubscribeButtonPressed, } = props; const realmUrl = useSelector(getRealmUrl); const globalSettings = useGlobalSelector(getGlobalSettings); const showActionSheetWithOptions: ShowActionSheetWithOptions = useActionSheet().showActionSheetWithOptions; const _ = useContext(TranslationContext); const navigation = useNavigation(); const dispatch = useDispatch(); const backgroundData = useSelector(state => ({ auth: getAuth(state), ownUser: getOwnUser(state), streams: getStreamsById(state), subscriptions: getSubscriptionsById(state), flags: getFlags(state), userSettingStreamNotification: getSettings(state).streamNotification, })); const { backgroundColor: themeBackgroundColor, color: themeColor } = useContext(ThemeContext); const iconColor = color !== undefined ? color : foregroundColorFromBackground( backgroundColor !== undefined ? backgroundColor : themeBackgroundColor, ); const textColor = backgroundColor !== undefined ? (foregroundColorFromBackground(backgroundColor): string) : themeColor; const styles = useMemo( () => ({ wrapper: { flexDirection: 'row', alignItems: 'center', paddingVertical: handleExpandCollapse ? 0 : 8, paddingLeft: handleExpandCollapse ? 0 : 16, paddingRight: extraPaddingEnd + 16, backgroundColor, opacity: isMuted ? 0.5 : 1, }, collapsePressable: { display: 'flex', alignItems: 'center', justifyContent: 'center', paddingTop: 8, paddingBottom: 8, paddingLeft: 8, paddingRight: 0, }, collapseIcon: { marginRight: 8, }, text: { flex: 1, paddingLeft: 8, paddingRight: 8, }, name: { color: textColor, }, description: { opacity: 0.75, fontSize: 12, }, }), [backgroundColor, extraPaddingEnd, handleExpandCollapse, isMuted, textColor], ); const collapseButton = handleExpandCollapse && ( <Pressable style={styles.collapsePressable} onPress={() => handleExpandCollapse(streamId)}> {isCollapsed === false ? ( <IconCaretUp style={styles.collapseIcon} size={20} color={iconColor} /> ) : ( <IconCaretDown style={styles.collapseIcon} size={20} color={iconColor} /> )} </Pressable> ); let subscribeButton = null; if (offersSubscribeButton) { const disabled = !isSubscribed && isPrivate; subscribeButton = ( <Pressable onPress={() => { if (onSubscribeButtonPressed) { if (disabled) { showErrorAlert( _('Cannot subscribe to stream'), _('Stream #{name} is private.', { name }), { url: new URL('/help/stream-permissions', realmUrl), globalSettings }, ); return; } onSubscribeButtonPressed({ stream_id: streamId, name }, !isSubscribed); } }} hitSlop={12} style={{ opacity: disabled ? 0.1 : 1 }} > {({ pressed }) => isSubscribed ? ( <IconDone size={24} color={pressed ? HIGHLIGHT_COLOR : BRAND_COLOR} /> ) : ( <IconPlus size={24} color={pressed ? HALF_COLOR : iconColor} /> ) } </Pressable> ); } return ( <Touchable onPress={() => onPress({ stream_id: streamId, name })} onLongPress={() => { showStreamActionSheet({ showActionSheetWithOptions, callbacks: { dispatch, navigation, _ }, backgroundData, streamId, }); }} > <View style={styles.wrapper}> {collapseButton} <StreamIcon size={iconSize} color={iconColor} isMuted={isMuted} isPrivate={isPrivate} isWebPublic={isWebPublic} /> <View style={styles.text}> <ZulipText numberOfLines={1} style={styles.name} text={name} ellipsizeMode="tail" /> {description !== undefined && description !== '' && ( <ZulipText numberOfLines={1} style={styles.description} text={description} ellipsizeMode="tail" /> )} </View> <UnreadCount color={iconColor} count={unreadCount} /> {subscribeButton} </View> </Touchable> ); } ```
/content/code_sandbox/src/streams/StreamItem.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,772
```javascript /* @flow strict-local */ import React, { useState, useCallback, useMemo, useEffect, useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { Privacy } from './streamsActions'; import { ensureUnreachable } from '../types'; import { useSelector } from '../react-redux'; import { getRealm, getRealmUrl } from '../selectors'; import { Role, type CreatePublicOrPrivateStreamPolicyT, CreateWebPublicStreamPolicy, } from '../api/permissionsTypes'; import { getCanCreatePublicStreams, getCanCreatePrivateStreams, getCanCreateWebPublicStreams, roleIsAtLeast, } from '../permissionSelectors'; import type { AppNavigationMethods } from '../nav/AppNavigator'; import Input from '../common/Input'; import InputRowRadioButtons from '../common/InputRowRadioButtons'; import ZulipTextIntl from '../common/ZulipTextIntl'; import ZulipButton from '../common/ZulipButton'; import styles from '../styles'; import { TranslationContext } from '../boot/TranslationProvider'; import type { LocalizableText } from '../types'; import { showConfirmationDialog } from '../utils/info'; import { getOwnUser } from '../users/userSelectors'; type PropsBase = $ReadOnly<{| navigation: AppNavigationMethods, initialValues: {| name: string, description: string, privacy: Privacy, |}, |}>; type PropsEditStream = $ReadOnly<{| ...PropsBase, isNewStream: false, onComplete: (changedValues: {| // Properties optional because some values might not have changed. +name?: string, +description?: string, +privacy?: Privacy, |}) => boolean | Promise<boolean>, |}>; type PropsCreateStream = $ReadOnly<{| ...PropsBase, isNewStream: true, onComplete: ({| name: string, description: string, privacy: Privacy |}) => | boolean | Promise<boolean>, |}>; type Props = $ReadOnly<PropsEditStream | PropsCreateStream>; function explainCreateWebPublicStreamPolicy( policy: CreateWebPublicStreamPolicy, realmName: string, ): LocalizableText { return { text: (() => { switch (policy) { case CreateWebPublicStreamPolicy.Nobody: return '{realmName} does not allow anybody to make web-public streams.'; case CreateWebPublicStreamPolicy.OwnerOnly: return '{realmName} only allows organization owners to make web-public streams.'; case CreateWebPublicStreamPolicy.AdminOrAbove: return '{realmName} only allows organization administrators or owners to make web-public streams.'; case CreateWebPublicStreamPolicy.ModeratorOrAbove: return '{realmName} only allows organization moderators, administrators, or owners to make web-public streams.'; } })(), values: { realmName }, }; } function explainCreatePublicStreamPolicy( policy: CreatePublicOrPrivateStreamPolicyT, realmName: string, ): LocalizableText { return { text: (() => { switch (policy) { // FlowIssue: sad that we end up having to write numeric literals here :-/ // But the most important thing to get from the type-checker here is // that the ensureUnreachable works -- that ensures that when we add a // new possible value, we'll add a case for it here. Couldn't find a // cleaner way to write this that still accomplished that. Discussion: // path_to_url#discussion_r875147220 case 2: // CreatePublicOrPrivateStreamPolicy.AdminOrAbove return '{realmName} only allows organization administrators or owners to make public streams.'; case 4: // CreatePublicOrPrivateStreamPolicy.ModeratorOrAbove return '{realmName} only allows organization moderators, administrators, or owners to make public streams.'; case 3: // CreatePublicOrPrivateStreamPolicy.FullMemberOrAbove return '{realmName} only allows full organization members, moderators, administrators, or owners to make public streams.'; case 1: // CreatePublicOrPrivateStreamPolicy.MemberOrAbove return '{realmName} only allows organization members, moderators, administrators, or owners to make public streams.'; default: { ensureUnreachable(policy); // (Unreachable as long as the cases are exhaustive.) return ''; } } })(), values: { realmName }, }; } function explainCreatePrivateStreamPolicy( policy: CreatePublicOrPrivateStreamPolicyT, realmName: string, ): LocalizableText { return { text: (() => { switch (policy) { // FlowIssue: sad that we end up having to write numeric literals here :-/ // But the most important thing to get from the type-checker here is // that the ensureUnreachable works -- that ensures that when we add a // new possible value, we'll add a case for it here. Couldn't find a // cleaner way to write this that still accomplished that. Discussion: // path_to_url#discussion_r875147220 case 2: // CreatePublicOrPrivateStreamPolicy.AdminOrAbove return '{realmName} only allows organization administrators or owners to make private streams.'; case 4: // CreatePublicOrPrivateStreamPolicy.ModeratorOrAbove return '{realmName} only allows organization moderators, administrators, or owners to make private streams.'; case 3: // CreatePublicOrPrivateStreamPolicy.FullMemberOrAbove return '{realmName} only allows full organization members, moderators, administrators, or owners to make private streams.'; case 1: // CreatePublicOrPrivateStreamPolicy.MemberOrAbove return '{realmName} only allows organization members, moderators, administrators, or owners to make private streams.'; default: { ensureUnreachable(policy); // (Unreachable as long as the cases are exhaustive.) return ''; } } })(), values: { realmName }, }; } /** * Most user-facing strings come from stream_privacy_policy_values in * static/js/stream_data.js. The ones in `disabledIfNotInitialValue` are the * exception; I made them up. */ function useStreamPrivacyOptions(initialValue: Privacy, isNewStream: boolean) { const { createPublicStreamPolicy, createPrivateStreamPolicy, webPublicStreamsEnabled, enableSpectatorAccess, createWebPublicStreamPolicy, name: realmName, } = useSelector(getRealm); const canCreatePublicStreams = useSelector(getCanCreatePublicStreams); const canCreatePrivateStreams = useSelector(getCanCreatePrivateStreams); const canCreateWebPublicStreams = useSelector(getCanCreateWebPublicStreams); const ownUserRole = useSelector(getOwnUser).role; const realmUrl = useSelector(getRealmUrl); const shouldDisableIfNotInitialValue = useCallback( <T: mixed>(canCreate: boolean, explainPolicy: (T, string) => LocalizableText, policy: T) => { if (!isNewStream && !roleIsAtLeast(ownUserRole, Role.Admin)) { return { title: 'Insufficient permission', message: 'Only organization administrators and owners can edit streams.', }; } return ( !canCreate && { title: 'Insufficient permission', message: explainPolicy(policy, realmName), learnMoreButton: roleIsAtLeast(ownUserRole, Role.Admin) ? { url: new URL('/help/configure-who-can-create-streams', realmUrl), text: 'Configure permissions', } : undefined, } ); }, [isNewStream, ownUserRole, realmName, realmUrl], ); return useMemo( () => [ !(webPublicStreamsEnabled && enableSpectatorAccess) ? undefined : { key: 'web-public', title: 'Web-public', subtitle: 'Organization members can join (guests must be invited by a subscriber); anyone on the Internet can view complete message history without creating an account', disabledIfNotInitialValue: shouldDisableIfNotInitialValue( canCreateWebPublicStreams, explainCreateWebPublicStreamPolicy, createWebPublicStreamPolicy, ), }, { key: 'public', title: 'Public', subtitle: 'Organization members can join (guests must be invited by a subscriber); organization members can view complete message history without joining', disabledIfNotInitialValue: shouldDisableIfNotInitialValue( canCreatePublicStreams, explainCreatePublicStreamPolicy, createPublicStreamPolicy, ), }, { key: 'invite-only-public-history', title: 'Private, shared history', subtitle: 'Must be invited by a subscriber; new subscribers can view complete message history; hidden from non-administrator users', disabledIfNotInitialValue: shouldDisableIfNotInitialValue( canCreatePrivateStreams, explainCreatePrivateStreamPolicy, createPrivateStreamPolicy, ), }, { key: 'invite-only', title: 'Private, protected history', subtitle: 'Must be invited by a subscriber; new subscribers can only see messages sent after they join; hidden from non-administrator users', disabledIfNotInitialValue: shouldDisableIfNotInitialValue( canCreatePrivateStreams, explainCreatePrivateStreamPolicy, createPrivateStreamPolicy, ), }, ] .filter(Boolean) .map(x => { const { disabledIfNotInitialValue = false, ...rest } = x; return { ...rest, // E.g., if editing an existing stream that's already // web-public, let the user keep it that way, even if they // wouldn't have permission to switch to web-public from // something else. In particular, as the user is filling out the // form, let them accidentally choose a different setting, then // switch back to the first setting without making them submit // the accidental setting or restart the app. disabled: x.key !== initialValue && disabledIfNotInitialValue, }; }), [ initialValue, shouldDisableIfNotInitialValue, canCreatePublicStreams, createPublicStreamPolicy, canCreatePrivateStreams, createPrivateStreamPolicy, webPublicStreamsEnabled, canCreateWebPublicStreams, createWebPublicStreamPolicy, enableSpectatorAccess, ], ); } export default function EditStreamCard(props: Props): Node { const { navigation, initialValues, isNewStream } = props; const _ = useContext(TranslationContext); const [name, setName] = useState<string>(props.initialValues.name); const [description, setDescription] = useState<string>(props.initialValues.description); const [privacy, setPrivacy] = useState<Privacy>(props.initialValues.privacy); // When adding more, update areInputsTouched. const [awaitingUserInput, setAwaitingUserInput] = useState<boolean>(true); const areInputsTouched = name !== initialValues.name || description !== initialValues.description || privacy !== initialValues.privacy; useEffect( () => navigation.addListener('beforeRemove', e => { if (!(awaitingUserInput && areInputsTouched)) { return; } e.preventDefault(); showConfirmationDialog({ destructive: true, title: 'Discard changes', message: 'You have unsaved changes. Leave without saving?', onPressConfirm: () => navigation.dispatch(e.data.action), _, }); }), [_, areInputsTouched, navigation, awaitingUserInput], ); const handlePerformAction = useCallback(async () => { setAwaitingUserInput(false); let result = false; try { if (props.isNewStream) { result = await props.onComplete({ name, description, privacy }); } else { result = await props.onComplete({ name: initialValues.name !== name ? name : undefined, description: initialValues.description !== description ? description : undefined, privacy: initialValues.privacy !== privacy ? privacy : undefined, }); } } finally { if (result) { navigation.goBack(); } else { setAwaitingUserInput(true); } } }, [props, navigation, initialValues, name, description, privacy]); const privacyOptions = useStreamPrivacyOptions(props.initialValues.privacy, isNewStream); return ( <View> <ZulipTextIntl text="Name" /> <Input style={styles.marginBottom} placeholder="Name" autoFocus defaultValue={initialValues.name} onChangeText={setName} /> <ZulipTextIntl text="Description" /> <Input style={styles.marginBottom} placeholder="Description" defaultValue={initialValues.description} onChangeText={setDescription} /> <InputRowRadioButtons navigation={navigation} label="Privacy" description="Who can access the stream?" items={privacyOptions} valueKey={privacy} onValueChange={setPrivacy} /> <ZulipButton style={styles.marginTop} text={isNewStream ? 'Create' : 'Save'} disabled={name.length === 0} onPress={handlePerformAction} /> </View> ); } ```
/content/code_sandbox/src/streams/EditStreamCard.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,853
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import * as eg from '../../__tests__/lib/exampleData'; import { EventTypes, type StreamEvent } from '../../api/eventTypes'; import { EVENT } from '../../actionConstants'; import streamsReducer from '../streamsReducer'; const mkAction = <E: $Diff<StreamEvent, {| id: mixed, type: mixed |}>>(event: E) => deepFreeze({ type: EVENT, event: { id: 0, type: EventTypes.stream, ...event } }); describe('streamsReducer', () => { describe('RESET_ACCOUNT_DATA', () => { test('resets state to initial state', () => { expect( streamsReducer([eg.makeStream({ name: 'some_stream' })], eg.action.reset_account_data), ).toEqual([]); }); }); describe('REGISTER_COMPLETE', () => { test('stores initial streams data', () => { const streams = [eg.makeStream(), eg.makeStream()]; const prevState = eg.baseReduxState.streams; const action = eg.mkActionRegisterComplete({ streams }); expect(streamsReducer(prevState, action)).toEqual(streams); }); }); describe('EVENT -> stream -> create', () => { test('add new stream', () => { const stream1 = eg.makeStream({ name: 'some stream', stream_id: 1 }); const stream2 = eg.makeStream({ name: 'some other stream', stream_id: 2 }); const action = mkAction({ op: 'create', streams: [stream1, stream2] }); expect(streamsReducer([], action)).toEqual([stream1, stream2]); }); test('if stream already exist, do not add it', () => { const stream1 = eg.makeStream({ description: 'description', stream_id: 1, name: 'some stream', }); const stream2 = eg.makeStream({ name: 'some other stream', stream_id: 2 }); const action = mkAction({ op: 'create', streams: [stream1, stream2] }); expect(streamsReducer([stream1], action)).toEqual([stream1, stream2]); }); }); describe('EVENT -> stream -> delete', () => { test('removes stream from state', () => { const stream1 = eg.makeStream({ description: 'description', stream_id: 1, name: 'some stream', }); const stream2 = eg.makeStream({ description: 'description', stream_id: 2, name: 'other stream', }); const stream3 = eg.makeStream({ description: 'description', stream_id: 3, name: 'third stream', }); const action = mkAction({ op: 'delete', streams: [stream1, stream2] }); const newState = streamsReducer([stream1, stream2, stream3], action); expect(newState).toEqual([stream3]); }); test('removes streams that exist, do nothing if not', () => { const stream1 = eg.makeStream({ name: 'some stream', stream_id: 1 }); const stream2 = eg.makeStream({ name: 'some other stream', stream_id: 2 }); const action = mkAction({ op: 'delete', streams: [stream1, stream2] }); expect(streamsReducer([stream1], action)).toEqual([]); }); }); describe('EVENT -> stream -> update', () => { test('Change the name property', () => { const stream123 = eg.makeStream({ stream_id: 123, name: 'competition' }); const stream67 = eg.makeStream({ stream_id: 67, name: 'design' }); const stream53 = eg.makeStream({ stream_id: 53, name: 'mobile' }); const action = mkAction({ op: 'update', stream_id: 123, name: 'competition', property: 'name', value: 'real competition', }); expect(streamsReducer([stream123, stream67, stream53], action)).toEqual([ { ...stream123, name: 'real competition' }, stream67, stream53, ]); }); test('Change the description property', () => { const stream123 = eg.makeStream({ stream_id: 123, name: 'competition', description: 'slack', }); const stream67 = eg.makeStream({ stream_id: 67, name: 'design', description: 'basic design', }); const stream53 = eg.makeStream({ stream_id: 53, name: 'mobile', description: 'android' }); const action = mkAction({ op: 'update', stream_id: 53, name: 'mobile', property: 'description', value: 'iOS + android', rendered_description: '<p>iOS + android</p>', }); expect(streamsReducer([stream123, stream67, stream53], action)).toEqual([ stream123, stream67, { ...stream53, description: 'iOS + android', rendered_description: '<p>iOS + android</p>' }, ]); }); test('Change the invite_only property', () => { const stream1 = eg.makeStream({ stream_id: 1, name: 'web public stream', invite_only: false, is_web_public: true, history_public_to_subscribers: true, }); const stream2 = eg.makeStream({ stream_id: 2, name: 'invite only stream', invite_only: true, is_web_public: false, history_public_to_subscribers: true, }); const action = mkAction({ op: 'update', stream_id: stream1.stream_id, name: stream1.name, property: 'invite_only', value: true, is_web_public: false, history_public_to_subscribers: false, }); expect(streamsReducer([stream1, stream2], action)).toEqual([ { ...stream1, invite_only: true, is_web_public: false, history_public_to_subscribers: false, }, stream2, ]); }); }); }); ```
/content/code_sandbox/src/streams/__tests__/streamsReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,349
```javascript /* @flow strict-local */ import { Platform, Share } from 'react-native'; import { downloadImage, downloadFileToCache } from './download'; import type { Auth } from '../types'; import ShareFileAndroid from '../nativeModules/ShareFileAndroid'; import { showToast } from '../utils/info'; import * as api from '../api'; import { openLinkEmbedded } from '../utils/openLink'; import * as logging from '../utils/logging'; /** * Share natively if possible, else open browser for the user to share there. */ // TODO(i18n): Wire up toasts for translation. export default async (url: URL, auth: Auth) => { const tempUrl = await api.tryGetFileTemporaryUrl(url, auth); if (tempUrl === null) { // Open the file in a browser and invite the user to use the browser's // "share" feature. That's probably not what they expected when they hit // "share" and when the browser opens, it's probably not always clear // what that has to do with the share they wanted to do. // // So we're giving them some kind of indication of "yes, we heard you, // you want to share the file -- this is the path we're offering for // doing that". // // TODO(?): Could find a better way to convey this. showToast('Please share the image from your browser'); openLinkEmbedded(url); return; } const fileName = url.pathname.split('/').pop(); if (Platform.OS === 'android') { try { const res: $FlowFixMe = await downloadFileToCache(tempUrl.toString(), fileName); await ShareFileAndroid.shareFile(res.path()); } catch (error) { showToast('Share failed'); logging.error(error); } } else { try { const uri = await downloadImage(tempUrl.toString(), fileName, auth); await Share.share({ url: uri, message: (url.toString(): string) }); } catch (error) { showToast('Share failed'); logging.error(error); } } }; ```
/content/code_sandbox/src/lightbox/shareImage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
451
```javascript /* @flow strict-local */ import React, { useState, useCallback } from 'react'; import type { Node } from 'react'; import { View, LayoutAnimation } from 'react-native'; // $FlowFixMe[untyped-import] import PhotoView from 'react-native-photo-view'; // $FlowFixMe[untyped-import] import { useActionSheet } from '@expo/react-native-action-sheet'; import type { Message } from '../types'; import { useSelector } from '../react-redux'; import type { ShowActionSheetWithOptions } from '../action-sheets'; import { getAuth } from '../selectors'; import { isUrlOnRealm } from '../utils/url'; import LightboxHeader from './LightboxHeader'; import LightboxFooter from './LightboxFooter'; import { constructActionSheetButtons, executeActionSheetAction } from './LightboxActionSheet'; import { createStyleSheet } from '../styles'; import { navigateBack } from '../actions'; import { streamNameOfStreamMessage } from '../utils/recipient'; import ZulipStatusBar from '../common/ZulipStatusBar'; import { useNavigation } from '../react-navigation'; import { getAuthHeaders } from '../api/transport'; type Props = $ReadOnly<{| src: URL, message: Message, |}>; export default function Lightbox(props: Props): Node { const navigation = useNavigation(); const [headerFooterVisible, setHeaderFooterVisible] = useState<boolean>(true); const showActionSheetWithOptions: ShowActionSheetWithOptions = useActionSheet().showActionSheetWithOptions; const auth = useSelector(getAuth); // Pulled out here just because this function is used twice. const handleImagePress = useCallback(() => { LayoutAnimation.configureNext({ ...LayoutAnimation.Presets.easeInEaseOut, duration: 100, // from 300 }); setHeaderFooterVisible(m => !m); }, [setHeaderFooterVisible]); const { src, message } = props; const footerMessage = message.type === 'stream' ? `Shared in #${streamNameOfStreamMessage(message)}` : 'Shared with you'; const styles = React.useMemo( () => createStyleSheet({ img: { height: 300, flex: 1, width: '100%', }, header: { backgroundColor: 'black', opacity: 0.8, position: 'absolute', width: '100%', ...(headerFooterVisible ? { top: 0 } : { bottom: '100%' }), }, footer: { backgroundColor: 'black', opacity: 0.8, position: 'absolute', width: '100%', ...(headerFooterVisible ? { bottom: 0 } : { top: '100%' }), }, container: { flex: 1, justifyContent: 'space-between', alignItems: 'center', }, }), [headerFooterVisible], ); return ( <> <ZulipStatusBar hidden={!headerFooterVisible} backgroundColor="black" /> <View style={styles.container}> <PhotoView source={ // Important: Don't include auth headers unless `src` is on the realm. isUrlOnRealm(src, auth.realm) ? { uri: src.toString(), headers: getAuthHeaders(auth) } : { uri: src.toString() } } style={styles.img} // Doesn't seem to do anything on iOS: // path_to_url // path_to_url // TODO: Figure out how to make it work. resizeMode="contain" // Android already doesn't show any scrollbars; these two // iOS-only props let us hide them on iOS. showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} onTap={handleImagePress} onViewTap={handleImagePress} /> <View style={styles.header}> <LightboxHeader onPressBack={() => { navigation.dispatch(navigateBack()); }} message={message} /> </View> <View style={styles.footer}> <LightboxFooter displayMessage={footerMessage} onOptionsPress={() => { const options = constructActionSheetButtons(); const cancelButtonIndex = options.length - 1; showActionSheetWithOptions( { options, cancelButtonIndex, }, buttonIndex => { executeActionSheetAction({ title: options[buttonIndex], src, auth, }); }, ); }} /> </View> </View> </> ); } ```
/content/code_sandbox/src/lightbox/Lightbox.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
975
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Text, View, Pressable } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import { SafeAreaView } from 'react-native-safe-area-context'; import { Icon } from '../common/Icons'; import { createStyleSheet } from '../styles'; const styles = createStyleSheet({ wrapper: { flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 16, paddingVertical: 8, flex: 1, }, text: { color: 'white', fontSize: 14, alignSelf: 'center', }, iconTouchTarget: { alignSelf: 'center', marginVertical: 4, }, }); type Props = $ReadOnly<{| style?: ViewStyleProp, displayMessage: string, onOptionsPress: () => void, |}>; export default function LightboxFooter(props: Props): Node { const { displayMessage, onOptionsPress, style } = props; return ( <SafeAreaView mode="padding" edges={['right', 'bottom', 'left']}> <View style={[styles.wrapper, style]}> <Text style={styles.text}>{displayMessage}</Text> <Pressable style={styles.iconTouchTarget} onPress={onOptionsPress} hitSlop={12}> {({ pressed }) => ( <Icon size={24} color={pressed ? 'gray' : 'white'} name="more-vertical" /> )} </Pressable> </View> </SafeAreaView> ); } ```
/content/code_sandbox/src/lightbox/LightboxFooter.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
353
```javascript /* @flow strict-local */ import { Platform, PermissionsAndroid } from 'react-native'; import type { Rationale } from 'react-native/Libraries/PermissionsAndroid/PermissionsAndroid'; import { CameraRoll } from '@react-native-camera-roll/camera-roll'; import RNFetchBlob from 'rn-fetch-blob'; import type { Auth } from '../api/transportTypes'; import { getMimeTypeFromFileExtension } from '../utils/url'; import { androidSdkVersion } from '../reactNativeUtils'; /** * Request permission WRITE_EXTERNAL_STORAGE if needed or throw if can't get it. * * We don't need to request this permission on Android 10 (SDK version 29) * or above. See android/app/src/main/AndroidManifest.xml for why. * * The error thrown will have a `message` suitable for showing to the user * as a toast. */ export const androidEnsureStoragePermission = async (rationale: Rationale): Promise<void> => { if (androidSdkVersion() > 28) { return; } // See docs from Android for the underlying interaction with the user: // path_to_url // and from RN for the specific API that wraps it: // path_to_url const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE; const granted = await PermissionsAndroid.check(permission); if (granted) { return; } const result = await PermissionsAndroid.request(permission, rationale); const { DENIED, NEVER_ASK_AGAIN /* , GRANTED */ } = PermissionsAndroid.RESULTS; if (result === DENIED || result === NEVER_ASK_AGAIN) { throw new Error('Storage permission required'); } // result === GRANTED }; /** * Download a remote image to the device. * * @param url A URL to the image. Should be a valid temporary URL generated * using `getFileTemporaryUrl`. * @param fileName Name of the file to be downloaded. Should include the * extension. * @param auth Authentication info for the current user. */ export const downloadImage = async (url: string, fileName: string, auth: Auth): Promise<mixed> => { if (Platform.OS === 'ios') { return CameraRoll.save(url); } // Platform.OS === 'android' const mime = getMimeTypeFromFileExtension(fileName.split('.').pop()); await androidEnsureStoragePermission({ // TODO: Set these user-facing strings up for translation. title: 'Storage permission needed', message: 'To download images, allow Zulip to store files on your device.', }); return RNFetchBlob.config({ addAndroidDownloads: { path: `${RNFetchBlob.fs.dirs.DownloadDir}/${fileName}`, useDownloadManager: true, mime, // Android DownloadManager fails if the url is missing a file extension title: fileName, notification: true, }, }).fetch('GET', url); }; /** * Download a remote file to the app's cache directory. * * @param tempUrl A URL to the file. Should be a valid temporary URL generated * using `getFileTemporaryUrl`. * @param fileName Name of the file to be downloaded. Should include the * extension. */ export const downloadFileToCache = async (tempUrl: string, fileName: string): Promise<mixed> => RNFetchBlob.config({ path: `${RNFetchBlob.fs.dirs.CacheDir}/${fileName}`, }).fetch('GET', tempUrl); ```
/content/code_sandbox/src/lightbox/download.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
733
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { Message } from '../types'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { createStyleSheet } from '../styles'; import Lightbox from './Lightbox'; const styles = createStyleSheet({ screen: { flex: 1, flexDirection: 'column', alignItems: 'stretch', backgroundColor: 'black', }, }); type Props = $ReadOnly<{| navigation: AppNavigationProp<'lightbox'>, route: RouteProp<'lightbox', {| src: URL, message: Message |}>, |}>; export default function LightboxScreen(props: Props): Node { const { src, message } = props.route.params; return ( <View style={styles.screen}> <Lightbox src={src} message={message} /> </View> ); } ```
/content/code_sandbox/src/lightbox/LightboxScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
212
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View, Pressable } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { shortTime, humanDate } from '../utils/date'; import { createStyleSheet } from '../styles'; import UserAvatarWithPresence from '../common/UserAvatarWithPresence'; import { Icon } from '../common/Icons'; import { OfflineNoticePlaceholder } from '../boot/OfflineNoticeProvider'; import { useSelector } from '../react-redux'; import { getFullNameReactText, tryGetUserForId } from '../users/userSelectors'; import { getRealm } from '../directSelectors'; import type { Message } from '../api/modelTypes'; import ZulipText from '../common/ZulipText'; import ZulipTextIntl from '../common/ZulipTextIntl'; const styles = createStyleSheet({ text: { flex: 1, justifyContent: 'space-between', paddingLeft: 16, }, name: { color: 'white', fontSize: 14, fontWeight: 'bold', }, subheader: { color: 'white', fontSize: 12, }, rightIconTouchTarget: { alignSelf: 'center', marginVertical: 4, }, contentArea: { flex: 1, flexDirection: 'row', paddingHorizontal: 16, paddingVertical: 8, }, }); type Props = $ReadOnly<{| message: Message, onPressBack: () => void, |}>; /** * Shows sender's name and date of photo being displayed. */ export default function LightboxHeader(props: Props): Node { const { onPressBack, message } = props; const { timestamp, sender_id: senderId } = message; const displayDate = humanDate(new Date(timestamp * 1000)); const time = shortTime(new Date(timestamp * 1000)); const subheader = `${displayDate} at ${time}`; const sender = useSelector(state => tryGetUserForId(state, senderId)); const enableGuestUserIndicator = useSelector(state => getRealm(state).enableGuestUserIndicator); return ( <SafeAreaView mode="padding" edges={['top']}> <OfflineNoticePlaceholder /> <SafeAreaView mode="padding" edges={['right', 'left']} style={styles.contentArea}> <UserAvatarWithPresence size={36} userId={senderId} /> <View style={styles.text}> <ZulipTextIntl style={styles.name} numberOfLines={1} text={getFullNameReactText({ user: sender, enableGuestUserIndicator, fallback: message.sender_full_name, })} /> <ZulipText style={styles.subheader} numberOfLines={1}> {subheader} </ZulipText> </View> <Pressable style={styles.rightIconTouchTarget} onPress={onPressBack} hitSlop={12}> {({ pressed }) => <Icon size={24} color={pressed ? 'gray' : 'white'} name="x" />} </Pressable> </SafeAreaView> </SafeAreaView> ); } ```
/content/code_sandbox/src/lightbox/LightboxHeader.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
685
```javascript /* @flow strict-local */ import { Share } from 'react-native'; import { BRAND_COLOR } from '../styles'; export default (url: string) => { const shareOptions = { message: url, title: 'Shared using Zulip!', }; Share.share(shareOptions, { tintColor: BRAND_COLOR }).catch(err => {}); }; ```
/content/code_sandbox/src/lightbox/share.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
76
```javascript /* @flow strict-local */ import type { Auth } from '../types'; import { downloadImage } from './download'; import share from './share'; import shareImage from './shareImage'; import { showToast } from '../utils/info'; import * as api from '../api'; import { openLinkEmbedded } from '../utils/openLink'; type DownloadImageType = {| src: URL, auth: Auth, |}; type ShareLinkType = {| src: URL, auth: Auth, |}; type ExecuteActionSheetActionType = {| title: string, src: URL, auth: Auth, |}; type ButtonProps = {| auth: Auth, src: URL, |}; type ButtonType = {| title: string, onPress: (props: ButtonProps) => void | Promise<void>, |}; /** * Download directly if possible, else open browser for the user to download there. */ const tryToDownloadImage = async ({ src, auth }: DownloadImageType) => { const tempUrl = await api.tryGetFileTemporaryUrl(src, auth); if (tempUrl === null) { openLinkEmbedded(src); return; } const fileName = src.pathname.split('/').pop(); try { await downloadImage(tempUrl.toString(), fileName, auth); showToast('Download complete'); } catch (error) { showToast(error.message); } }; const shareLink = ({ src, auth }: ShareLinkType) => { share(src.toString()); }; const shareImageDirectly = ({ src, auth }: DownloadImageType) => { shareImage(src, auth); }; const actionSheetButtons: $ReadOnlyArray<ButtonType> = [ { title: 'Download image', onPress: tryToDownloadImage }, { title: 'Share image', onPress: shareImageDirectly }, { title: 'Share link to image', onPress: shareLink }, { title: 'Cancel', onPress: () => {} }, ]; // TODO(i18n): Wire the titles up for translation. export const constructActionSheetButtons = (): string[] => actionSheetButtons.map(button => button.title); // TODO: Wire toasts, etc., up for translation. export const executeActionSheetAction = ({ title, ...props }: ExecuteActionSheetActionType) => { const button = actionSheetButtons.find(x => x.title === title); if (button) { button.onPress(props); } }; ```
/content/code_sandbox/src/lightbox/LightboxActionSheet.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
513
```javascript /* @flow strict-local */ import { createSelector } from 'reselect'; import type { Narrow, Selector, UserOrBot } from '../types'; import { getTyping } from '../directSelectors'; import { userIdsOfPmNarrow, isPmNarrow } from '../utils/narrow'; import { pmTypingKeyFromPmKeyIds } from '../utils/recipient'; import { NULL_ARRAY } from '../nullObjects'; import { getAllUsersById } from '../users/userSelectors'; export const getCurrentTypingUsers: Selector<$ReadOnlyArray<UserOrBot>, Narrow> = createSelector( (state, narrow) => narrow, state => getTyping(state), state => getAllUsersById(state), (narrow, typing, allUsersById): $ReadOnlyArray<UserOrBot> => { if (!isPmNarrow(narrow)) { return NULL_ARRAY; } const typingKey = pmTypingKeyFromPmKeyIds(userIdsOfPmNarrow(narrow)); const currentTyping = typing[typingKey]; if (!currentTyping || !currentTyping.userIds) { return NULL_ARRAY; } return currentTyping.userIds.map(userId => allUsersById.get(userId)).filter(Boolean); }, ); ```
/content/code_sandbox/src/typing/typingSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
267
```javascript /* @flow strict-local */ import type { PerAccountApplicableAction, TypingState } from '../types'; import { EVENT_TYPING_START, EVENT_TYPING_STOP, CLEAR_TYPING, RESET_ACCOUNT_DATA, REGISTER_COMPLETE, } from '../actionConstants'; import { pmTypingKeyFromRecipients } from '../utils/recipient'; import { NULL_OBJECT } from '../nullObjects'; const initialState: TypingState = NULL_OBJECT; const eventTypingStart = (state, action) => { if (action.sender.user_id === action.ownUserId) { // don't change state when self is typing return state; } const normalizedRecipients: string = pmTypingKeyFromRecipients( action.recipients.map(r => r.user_id), action.ownUserId, ); const previousTypingUsers = state[normalizedRecipients] || { userIds: [] }; const isUserAlreadyTyping = previousTypingUsers.userIds.indexOf(action.sender.user_id); if (isUserAlreadyTyping > -1) { return { ...state, [normalizedRecipients]: { userIds: [...previousTypingUsers.userIds], time: action.time, }, }; } return { ...state, [normalizedRecipients]: { userIds: [...previousTypingUsers.userIds, action.sender.user_id], time: action.time, }, }; }; const eventTypingStop = (state, action) => { const normalizedRecipients: string = pmTypingKeyFromRecipients( action.recipients.map(r => r.user_id), action.ownUserId, ); const previousTypingUsers = state[normalizedRecipients]; if (!previousTypingUsers) { return state; } const newTypingUsers = state[normalizedRecipients].userIds.filter( userId => userId !== action.sender.user_id, ); if (newTypingUsers.length > 0) { return { ...state, [normalizedRecipients]: { time: action.time, userIds: newTypingUsers, }, }; } // if key is empty now, remove the key const newState = { ...state }; delete newState[normalizedRecipients]; return newState; }; const clearTyping = (state, action) => { const newState = { ...state }; action.outdatedNotifications.map(recipients => delete newState[recipients]); return newState; }; export default ( state: TypingState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): TypingState => { switch (action.type) { case EVENT_TYPING_START: return eventTypingStart(state, action); case EVENT_TYPING_STOP: return eventTypingStop(state, action); case CLEAR_TYPING: return clearTyping(state, action); case RESET_ACCOUNT_DATA: return initialState; // Reset to clear stale data; payload has no initial data for this model case REGISTER_COMPLETE: return initialState; default: return state; } }; ```
/content/code_sandbox/src/typing/typingReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
673
```javascript /* @flow strict-local */ import type { PerAccountAction, ThunkAction } from '../types'; import { sleep } from '../utils/async'; import { getTyping } from '../directSelectors'; /** * The value to use for `server_typing_started_expiry_period_milliseconds`. * * The corresponding old server setting was `TYPING_STARTED_EXPIRY_PERIOD`. * * The specified behavior is that we should be taking this value from server * data. See docs: * path_to_url * * But in this legacy codebase, the most expedient thing is to hardcode it * to a large value. We'll get proper user-facing behavior as long as this * value exceeds by at least a network round-trip the effective value of * `server_typing_started_wait_period_milliseconds` in the behavior of other * clients. Discussion: * path_to_url#narrow/stream/243-mobile-team/topic/typing.20notifications.20constants/near/1665193 */ const typingStartedExpiryPeriodMs = 45000; /** * The period at which to poll for expired typing notifications. * * Really no polling should be needed here -- a timer would be better. * But that's how this code has always worked, and for this legacy codebase * that'll do. */ const typingPollPeriodMs = 3000; export const clearTyping = (outdatedNotifications: $ReadOnlyArray<string>): PerAccountAction => ({ type: 'CLEAR_TYPING', outdatedNotifications, }); const typingStatusExpiryLoop = () => async (dispatch, getState) => { // loop to auto dismiss typing notifications after typingNotificationTimeout while (true) { await sleep(typingPollPeriodMs); const currentTime = new Date().getTime(); const typing = getTyping(getState()); if (Object.keys(typing).length === 0) { break; // break if no typing notifications } const outdatedNotifications = []; Object.keys(typing).forEach(recipients => { if (currentTime - typing[recipients].time >= typingStartedExpiryPeriodMs) { outdatedNotifications.push(recipients); } }); dispatch(clearTyping(outdatedNotifications)); } }; /** Start the typing-status expiry loop, if there isn't one already. */ export const ensureTypingStatusExpiryLoop = (): ThunkAction<Promise<void>> => async (dispatch, getState) => { const state = getState(); if (Object.keys(state.typing).length === 0) { dispatch(typingStatusExpiryLoop()); } }; ```
/content/code_sandbox/src/typing/typingActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
552
```javascript /* @flow strict-local */ import { getCurrentTypingUsers } from '../typingSelectors'; import { HOME_NARROW, pm1to1NarrowFromUser, pmNarrowFromUsersUnsafe } from '../../utils/narrow'; import { NULL_ARRAY } from '../../nullObjects'; import * as eg from '../../__tests__/lib/exampleData'; import { pmKeyRecipientsFor1to1, pmKeyRecipientsFromUsers, pmTypingKeyFromPmKeyIds, } from '../../utils/recipient'; describe('getCurrentTypingUsers', () => { test('return NULL_ARRAY when current narrow is not private or group', () => { const state = eg.reduxState({}); const typingUsers = getCurrentTypingUsers(state, HOME_NARROW); expect(typingUsers).toBe(NULL_ARRAY); }); test('when in private narrow and the same user is typing return details', () => { const expectedUser = eg.makeUser(); const state = eg.reduxState({ typing: { [expectedUser.user_id.toString()]: { userIds: [expectedUser.user_id] }, }, users: [expectedUser], }); const typingUsers = getCurrentTypingUsers(state, pm1to1NarrowFromUser(expectedUser)); expect(typingUsers).toEqual([expectedUser]); }); test('when two people are typing, return details for all of them', () => { const user1 = eg.makeUser(); const user2 = eg.makeUser(); const users = [user1, user2].sort((a, b) => a.user_id - b.user_id); const normalizedRecipients = pmTypingKeyFromPmKeyIds( pmKeyRecipientsFromUsers(users, eg.selfUser.user_id), ); const state = eg.reduxState({ typing: { [normalizedRecipients]: { userIds: users.map(u => u.user_id) }, }, users: [user1, user2], }); const typingUsers = getCurrentTypingUsers(state, pmNarrowFromUsersUnsafe(users)); expect(typingUsers).toEqual(users); }); test('when in private narrow but different user is typing return NULL_ARRAY', () => { const user1 = eg.makeUser(); const user2 = eg.makeUser(); const normalizedRecipients = pmTypingKeyFromPmKeyIds(pmKeyRecipientsFor1to1(user1.user_id)); const state = eg.reduxState({ typing: { [normalizedRecipients]: { userIds: [user1.user_id] }, }, users: [user1, user2], }); const typingUsers = getCurrentTypingUsers(state, pm1to1NarrowFromUser(user2)); expect(typingUsers).toEqual(NULL_ARRAY); }); test('when in group narrow and someone is typing in that narrow return details', () => { const expectedUser = eg.makeUser(); const anotherUser = eg.makeUser(); const users = [expectedUser, anotherUser].sort((a, b) => a.user_id - b.user_id); const normalizedRecipients = pmTypingKeyFromPmKeyIds( pmKeyRecipientsFromUsers(users, eg.selfUser.user_id), ); const state = eg.reduxState({ typing: { [normalizedRecipients]: { userIds: [expectedUser.user_id] }, }, users: [expectedUser, anotherUser], }); const typingUsers = getCurrentTypingUsers(state, pmNarrowFromUsersUnsafe(users)); expect(typingUsers).toEqual([expectedUser]); }); test('when in a private narrow with a deactivated user, return valid data', () => { const deactivatedUser = eg.makeUser(); const state = eg.reduxState({ typing: {}, realm: eg.realmState({ nonActiveUsers: [deactivatedUser] }), }); const getTypingUsers = () => getCurrentTypingUsers(state, pm1to1NarrowFromUser(deactivatedUser)); expect(getTypingUsers).not.toThrow(); expect(getTypingUsers()).toEqual([]); }); test('when in a private narrow with a cross-realm bot, return valid data', () => { const crossRealmBot = eg.makeCrossRealmBot(); const state = eg.reduxState({ typing: {}, realm: eg.realmState({ crossRealmBots: [crossRealmBot] }), }); const getTypingUsers = () => getCurrentTypingUsers(state, pm1to1NarrowFromUser(crossRealmBot)); expect(getTypingUsers).not.toThrow(); expect(getTypingUsers()).toEqual([]); }); }); ```
/content/code_sandbox/src/typing/__tests__/typingSelectors-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
999
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import type { PerAccountAction, User } from '../../types'; import { EVENT_TYPING_START, EVENT_TYPING_STOP } from '../../actionConstants'; import typingReducer from '../typingReducer'; import { NULL_OBJECT } from '../../nullObjects'; import * as eg from '../../__tests__/lib/exampleData'; import { makeUserId } from '../../api/idTypes'; describe('typingReducer', () => { const user1 = { ...eg.otherUser, user_id: makeUserId(1) }; const user2 = { ...eg.thirdUser, user_id: makeUserId(2) }; const egTypingAction = (args: {| op: 'start' | 'stop', sender: User, recipients: $ReadOnlyArray<User>, time: number, |}): PerAccountAction => { const { op, sender, recipients, time } = args; const base = { id: 123, ownUserId: eg.selfUser.user_id, sender: { user_id: sender.user_id, email: sender.email }, recipients: recipients.map(r => ({ user_id: r.user_id, email: r.email })), time, }; return op === 'start' ? { ...base, op: 'start', type: EVENT_TYPING_START } : { ...base, op: 'stop', type: EVENT_TYPING_STOP }; }; describe('RESET_ACCOUNT_DATA', () => { const initialState = eg.baseReduxState.typing; const action1 = egTypingAction({ op: 'start', sender: user1, recipients: [user1, user2], time: 123456789, }); const prevState = typingReducer(initialState, action1); expect(prevState).not.toEqual(initialState); expect(typingReducer(prevState, eg.action.reset_account_data)).toEqual(initialState); }); describe('REGISTER_COMPLETE', () => { test('resets state to initial state', () => { const initialState = eg.baseReduxState.typing; const action1 = egTypingAction({ op: 'start', sender: user1, recipients: [user1, eg.selfUser], time: 123456889, }); const prevState = typingReducer(initialState, action1); expect(prevState).not.toEqual(initialState); const action2 = eg.action.register_complete; expect(typingReducer(prevState, action2)).toEqual(eg.baseReduxState.typing); }); }); describe('EVENT_TYPING_START', () => { test('adds sender as currently typing user', () => { const prevState = NULL_OBJECT; expect( typingReducer( prevState, egTypingAction({ op: 'start', sender: user1, recipients: [user1, eg.selfUser], time: 123456789, }), ), ).toEqual({ '1': { time: 123456789, userIds: [user1.user_id] } }); }); test('if user is already typing, no change in userIds but update time', () => { const prevState = deepFreeze({ '1': { time: 123456789, userIds: [user1.user_id] } }); expect( typingReducer( prevState, egTypingAction({ op: 'start', sender: user1, recipients: [user1, eg.selfUser], time: 123456889, }), ), ).toEqual({ '1': { time: 123456889, userIds: [user1.user_id] } }); }); test('if other people are typing in other narrows, add, do not affect them', () => { const prevState = deepFreeze({ '1': { time: 123489, userIds: [user1.user_id] } }); expect( typingReducer( prevState, egTypingAction({ op: 'start', sender: user2, recipients: [user1, user2, eg.selfUser], time: 123456789, }), ), ).toEqual({ '1': { time: 123489, userIds: [user1.user_id] }, '1,2': { time: 123456789, userIds: [user2.user_id] }, }); }); test('if another user is typing already, append new one', () => { const prevState = deepFreeze({ '1,2': { time: 123489, userIds: [user1.user_id] } }); expect( typingReducer( prevState, egTypingAction({ op: 'start', sender: user2, recipients: [user1, user2, eg.selfUser], time: 123456789, }), ), ).toEqual({ '1,2': { time: 123456789, userIds: [user1.user_id, user2.user_id] } }); }); }); describe('EVENT_TYPING_STOP', () => { test('if after removing, key is an empty list, key is removed', () => { const prevState = deepFreeze({ '1': { time: 123489, userIds: [user1.user_id] }, '3': { time: 123489, userIds: [eg.selfUser.user_id] }, }); expect( typingReducer( prevState, egTypingAction({ op: 'stop', sender: user1, recipients: [user1, eg.selfUser], time: 123456789, }), ), ).toEqual({ '3': { time: 123489, userIds: [eg.selfUser.user_id] } }); }); test('if two people are typing, just one is removed', () => { const prevState = deepFreeze({ '1': { time: 123489, userIds: [user1.user_id, eg.selfUser.user_id] }, }); expect( typingReducer( prevState, egTypingAction({ op: 'stop', sender: user1, recipients: [user1, eg.selfUser], time: 123456789, }), ), ).toEqual({ '1': { time: 123456789, userIds: [eg.selfUser.user_id] } }); }); test('if typing state does not exist, no change is made', () => { const prevState = NULL_OBJECT; expect( typingReducer( prevState, egTypingAction({ op: 'stop', sender: user1, recipients: [user1, eg.selfUser], time: 123456789, }), ), ).toEqual({}); }); }); }); ```
/content/code_sandbox/src/typing/__tests__/typingReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,466
```javascript /* @flow strict-local */ import type { InputSelection } from '../types'; export default ( textWhole: string, selection: InputSelection, ): {| lastWordPrefix: string, filter: string |} => { const { start, end } = selection; let text = textWhole; if (start === end && start !== text.length) { // new letter is typed in middle text = text.substring(0, start); } const lastIndex: number = Math.max( text.lastIndexOf(':'), text.lastIndexOf('#'), ['\n', ' ', '#', ':'].includes(text[text.lastIndexOf('@') - 1]) || text.lastIndexOf('@') === 0 // to make sure `@` is not the part of email ? text.lastIndexOf('@') : -1, ); const lastWordPrefix: string = lastIndex !== -1 ? text[lastIndex] : ''; const filter: string = text.length > lastIndex + 1 && !['\n', ' '].includes(text[lastIndex + 1]) ? text.substring(lastIndex + 1, text.length) : ''; return { lastWordPrefix, filter }; }; ```
/content/code_sandbox/src/autocomplete/getAutocompleteFilter.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
249
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import { FlatList } from 'react-native'; import type { Narrow } from '../types'; import Popup from '../common/Popup'; import EmojiRow from '../emoji/EmojiRow'; import { getFilteredEmojis } from '../emoji/data'; import { useSelector } from '../react-redux'; import { getActiveImageEmoji } from '../selectors'; import { getRealm } from '../directSelectors'; type Props = $ReadOnly<{| filter: string, onAutocomplete: (name: string) => void, destinationNarrow?: Narrow, |}>; const MAX_CHOICES = 30; export default function EmojiAutocomplete(props: Props): Node { const { filter, onAutocomplete } = props; const activeImageEmoji = useSelector(getActiveImageEmoji); const serverEmojiData = useSelector(state => getRealm(state).serverEmojiData); const filteredEmojis = getFilteredEmojis(filter, activeImageEmoji, serverEmojiData); const handlePress = useCallback( ({ type, code, name }) => { onAutocomplete(name); }, [onAutocomplete], ); if (filteredEmojis.length === 0) { return null; } return ( <Popup> <FlatList keyboardShouldPersistTaps="always" initialNumToRender={12} data={filteredEmojis.slice(0, MAX_CHOICES)} keyExtractor={item => item.emoji_name} renderItem={({ item }) => ( <EmojiRow type={item.emoji_type} code={item.emoji_code} name={item.emoji_name} onPress={handlePress} /> )} /> </Popup> ); } ```
/content/code_sandbox/src/autocomplete/EmojiAutocomplete.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
379
```javascript /* @flow strict-local */ import React, { useEffect } from 'react'; import type { Node } from 'react'; import { FlatList } from 'react-native'; import type { Narrow } from '../types'; import { createStyleSheet } from '../styles'; import { useDispatch, useSelector } from '../react-redux'; import { getTopicsForNarrow } from '../selectors'; import Popup from '../common/Popup'; import ZulipText from '../common/ZulipText'; import Touchable from '../common/Touchable'; import AnimatedScaleComponent from '../animation/AnimatedScaleComponent'; import { fetchTopicsForStream } from '../topics/topicActions'; const styles = createStyleSheet({ topic: { padding: 10, }, }); type Props = $ReadOnly<{| /** If null, this component won't do anything. */ narrow: Narrow | null, isFocused: boolean, text: string, onAutocomplete: (name: string) => void, |}>; export default function TopicAutocomplete(props: Props): Node { const { narrow, isFocused, text, onAutocomplete } = props; const dispatch = useDispatch(); const topics = useSelector(state => (narrow ? getTopicsForNarrow(state, narrow) : [])); useEffect(() => { // The following should be sufficient to ensure we're up-to-date // with the complete list of topics at all times that we need to // be: // // - When we first expect to see the list, fetch all topics for // the stream. // // - Afterwards, update the list when a new message arrives, if it // introduces a new topic. // // The latter is already taken care of (see handling of // EVENT_NEW_MESSAGE in topicsReducer). So, do the former here. if (narrow) { dispatch(fetchTopicsForStream(narrow)); } }, [dispatch, narrow]); if (!isFocused || !narrow) { return null; } const topicsToSuggest = topics.filter( x => x && x !== text && x.toLowerCase().indexOf(text.toLowerCase()) > -1, ); return ( <AnimatedScaleComponent visible={topicsToSuggest.length > 0}> <Popup> <FlatList nestedScrollEnabled keyboardShouldPersistTaps="always" initialNumToRender={10} data={topicsToSuggest} keyExtractor={item => item} renderItem={({ item }) => ( <Touchable onPress={() => onAutocomplete(item)}> <ZulipText style={styles.topic} text={item} /> </Touchable> )} /> </Popup> </AnimatedScaleComponent> ); } ```
/content/code_sandbox/src/autocomplete/TopicAutocomplete.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
582
```javascript /* @flow strict-local */ import type { InputSelection } from '../types'; export default (textWhole: string, autocompleteText: string, selection: InputSelection): string => { const { start, end } = selection; let remainder = ''; let text = textWhole; if (start === end && start !== text.length) { // new letter is typed remainder = text.substring(start, text.length); text = text.substring(0, start); } const lastIndex: number = Math.max( text.lastIndexOf(':'), text.lastIndexOf('#'), text.lastIndexOf('@'), ); const prefix = text[lastIndex] === ':' ? ':' : `${text[lastIndex]}`; const suffix = text[lastIndex] === ':' ? ':' : ''; return `${text.substring(0, lastIndex)}${prefix}${autocompleteText}${suffix} ${remainder}`; }; ```
/content/code_sandbox/src/autocomplete/getAutocompletedText.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
183
```javascript /* @flow strict-local */ import React, { useCallback, useContext } from 'react'; import type { Node } from 'react'; import { SectionList } from 'react-native'; import type { UserOrBot, UserGroup, Narrow } from '../types'; import { useSelector } from '../react-redux'; import { getMutedUsers, getSortedUsers, getUserGroups } from '../selectors'; import { getAutocompleteSuggestion, getAutocompleteUserGroupSuggestions, } from '../users/userHelpers'; import Popup from '../common/Popup'; import UserItem from '../users/UserItem'; import UserGroupItem from '../user-groups/UserGroupItem'; import { getOwnUserId } from '../users/userSelectors'; import WildcardMentionItem, { getWildcardMentionsForQuery, WildcardMentionType, } from './WildcardMentionItem'; import { TranslationContext } from '../boot/TranslationProvider'; import { getZulipFeatureLevel } from '../account/accountsSelectors'; import { streamChannelRenameFeatureLevel } from '../boot/streamChannelRenamesMap'; type Props = $ReadOnly<{| filter: string, destinationNarrow: Narrow, onAutocomplete: (name: string) => void, |}>; export default function PeopleAutocomplete(props: Props): Node { const { filter, destinationNarrow, onAutocomplete } = props; const _ = useContext(TranslationContext); const zulipFeatureLevel = useSelector(getZulipFeatureLevel); const mutedUsers = useSelector(getMutedUsers); const ownUserId = useSelector(getOwnUserId); const users = useSelector(getSortedUsers); const userGroups = useSelector(getUserGroups); const handleUserGroupItemAutocomplete = useCallback( (name: string): void => { onAutocomplete(`*${name}*`); }, [onAutocomplete], ); const handleWildcardMentionAutocomplete = useCallback( (type, serverCanonicalString) => { onAutocomplete(`**${serverCanonicalString}**`); }, [onAutocomplete], ); const handleUserItemAutocomplete = useCallback( (user: UserOrBot): void => { // If another user with the same full name is found, we send the // user ID as well, to ensure the mentioned user is uniquely identified. if (users.find(x => x.full_name === user.full_name && x.user_id !== user.user_id)) { // See the `get_mention_syntax` function in // `static/js/people.js` in the webapp. onAutocomplete(`**${user.full_name}|${user.user_id}**`); return; } onAutocomplete(`**${user.full_name}**`); }, [users, onAutocomplete], ); const filteredUserGroups = getAutocompleteUserGroupSuggestions(userGroups, filter); const wildcardMentionsForQuery = getWildcardMentionsForQuery( filter, destinationNarrow, // TODO(server-8.0) zulipFeatureLevel >= 224, zulipFeatureLevel >= streamChannelRenameFeatureLevel, _, ); const filteredUsers = getAutocompleteSuggestion(users, filter, ownUserId, mutedUsers); if (filteredUserGroups.length + filteredUsers.length === 0) { return null; } type Section<T> = {| +data: $ReadOnlyArray<T>, +renderItem: ({ item: T, ... }) => React$MixedElement, |}; const sections = [ ({ data: filteredUserGroups, renderItem: ({ item }) => ( <UserGroupItem key={item.name} name={item.name} description={item.description} onPress={handleUserGroupItemAutocomplete} /> ), }: Section<UserGroup>), ({ data: wildcardMentionsForQuery, renderItem: ({ item }) => ( <WildcardMentionItem key={WildcardMentionType.getName(item)} type={item} destinationNarrow={destinationNarrow} onPress={handleWildcardMentionAutocomplete} /> ), }: Section<WildcardMentionType>), ({ data: filteredUsers, renderItem: ({ item }) => ( <UserItem key={item.user_id} userId={item.user_id} showEmail onPress={handleUserItemAutocomplete} size="medium" /> ), }: Section<UserOrBot>), ]; return ( <Popup> { // $FlowFixMe[incompatible-variance] /* $FlowFixMe[prop-missing] SectionList type is confused; should take $ReadOnly objects. */ <SectionList keyboardShouldPersistTaps="always" initialNumToRender={10} sections={sections} /> } </Popup> ); } ```
/content/code_sandbox/src/autocomplete/PeopleAutocomplete.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,034
```javascript /* @flow strict-local */ import React, { useCallback, useContext, useMemo } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import * as typeahead from '@zulip/shared/lib/typeahead'; import type { GetText, Narrow } from '../types'; import { IconWildcardMention } from '../common/Icons'; import ZulipText from '../common/ZulipText'; import Touchable from '../common/Touchable'; import { createStyleSheet, ThemeContext } from '../styles'; import { caseNarrowDefault, isStreamOrTopicNarrow } from '../utils/narrow'; import { TranslationContext } from '../boot/TranslationProvider'; import { useSelector } from '../react-redux'; import { getZulipFeatureLevel } from '../account/accountsSelectors'; import { streamChannelRenameFeatureLevel } from '../boot/streamChannelRenamesMap'; /** * A type of wildcard mention recognized by the server. * * For the string the server knows this by, see serverCanonicalStringOf. * * See user doc on wildcard mentions: * path_to_url#wildcard-mentions */ export enum WildcardMentionType { // These values are arbitrary. For the string the server knows these by, // see serverCanonicalStringOf. All = 0, Everyone = 1, Stream = 2, Topic = 3, } /** * The canonical English string, like "everyone" or "all". * * See also serverCanonicalStringOf for the string the server knows this by. * (It might differ in a future where servers localize these.) */ // All of these should appear in messages_en.json so we can make the // wildcard mentions discoverable in the people autocomplete in the client's // own language. See getWildcardMentionsForQuery. const englishCanonicalStringOf = ( type: WildcardMentionType, useChannelTerminology: boolean, ): string => { switch (type) { case WildcardMentionType.All: return 'all'; case WildcardMentionType.Everyone: return 'everyone'; case WildcardMentionType.Stream: // TODO(server-9.0) remove "stream" terminology return useChannelTerminology ? 'channel' : 'stream'; case WildcardMentionType.Topic: return 'topic'; } }; /** * The string recognized by the server, like "everyone" or "all". * * Currently the same as englishCanonicalStringOf, but that should change if * servers start localizing these. */ const serverCanonicalStringOf = englishCanonicalStringOf; const descriptionOf = ( type: WildcardMentionType, destinationNarrow: Narrow, _: GetText, ): string => { switch (type) { case WildcardMentionType.All: case WildcardMentionType.Everyone: return caseNarrowDefault( destinationNarrow, { topic: () => _('Notify stream'), pm: () => _('Notify recipients') }, // A "destination narrow" should really be a conversation narrow // (i.e., stream or topic), but including this default case is easy, // and better than an error/crash in case we've missed that somehow. () => _('Notify everyone'), ); case WildcardMentionType.Stream: return _('Notify stream'); case WildcardMentionType.Topic: return _('Notify topic'); } }; export const getWildcardMentionsForQuery = ( query: string, destinationNarrow: Narrow, topicMentionSupported: boolean, useChannelTerminology: boolean, _: GetText, ): $ReadOnlyArray<WildcardMentionType> => { const queryMatchesWildcard = (type: WildcardMentionType): boolean => typeahead.query_matches_string( query, serverCanonicalStringOf(type, useChannelTerminology), ' ', ) || typeahead.query_matches_string( query, _(englishCanonicalStringOf(type, useChannelTerminology)), ' ', ); const results = []; // These three WildcardMentionType values are synonyms, so only show one. // // The help center mentions @-all, sometimes also @-everyone, and // apparently never @-stream: // path_to_url // path_to_url // So the right order of preference seems to be [all, everyone, stream]. if (queryMatchesWildcard(WildcardMentionType.All)) { results.push(WildcardMentionType.All); } else if (queryMatchesWildcard(WildcardMentionType.Everyone)) { results.push(WildcardMentionType.Everyone); } else if ( isStreamOrTopicNarrow(destinationNarrow) && queryMatchesWildcard(WildcardMentionType.Stream) ) { results.push(WildcardMentionType.Stream); } // Then show @-topic if it applies. if ( topicMentionSupported && isStreamOrTopicNarrow(destinationNarrow) && queryMatchesWildcard(WildcardMentionType.Topic) ) { results.push(WildcardMentionType.Topic); } return results; }; type Props = $ReadOnly<{| type: WildcardMentionType, destinationNarrow: Narrow, onPress: (type: WildcardMentionType, serverCanonicalString: string) => void, |}>; export default function WildcardMentionItem(props: Props): Node { const { type, destinationNarrow, onPress } = props; const _ = useContext(TranslationContext); const zulipFeatureLevel = useSelector(getZulipFeatureLevel); const useChannelTerminology = zulipFeatureLevel >= streamChannelRenameFeatureLevel; const handlePress = useCallback(() => { onPress(type, serverCanonicalStringOf(type, useChannelTerminology)); }, [onPress, type, useChannelTerminology]); const themeContext = useContext(ThemeContext); const styles = useMemo( () => createStyleSheet({ wrapper: { flexDirection: 'row', alignItems: 'center', padding: 8, // Minimum touch target height: // path_to_url#layout-and-typography minHeight: 48, }, textWrapper: { flex: 1, marginLeft: 8, }, text: {}, descriptionText: { fontSize: 10, color: 'hsl(0, 0%, 60%)', }, }), [], ); return ( <Touchable onPress={handlePress}> <View style={styles.wrapper}> <IconWildcardMention // Match the size of the avatar in UserItem, which also appears in // the people autocomplete. We're counting on this icon being a // square. size={32} color={themeContext.color} /> <View style={styles.textWrapper}> <ZulipText style={styles.text} text={serverCanonicalStringOf(type, useChannelTerminology)} numberOfLines={1} ellipsizeMode="tail" /> <ZulipText style={styles.descriptionText} text={descriptionOf(type, destinationNarrow, _)} numberOfLines={1} ellipsizeMode="tail" /> </View> </View> </Touchable> ); } ```
/content/code_sandbox/src/autocomplete/WildcardMentionItem.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,594
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import type { InputSelection, Narrow } from '../types'; import getAutocompletedText from './getAutocompletedText'; import getAutocompleteFilter from './getAutocompleteFilter'; import EmojiAutocomplete from './EmojiAutocomplete'; import StreamAutocomplete from './StreamAutocomplete'; import PeopleAutocomplete from './PeopleAutocomplete'; import AnimatedScaleComponent from '../animation/AnimatedScaleComponent'; const prefixToComponent = { ':': EmojiAutocomplete, '#': StreamAutocomplete, '@': PeopleAutocomplete, }; type Props = $ReadOnly<{| isFocused: boolean, text: string, selection: InputSelection, destinationNarrow: Narrow, /** * The callback that is called when the user taps on any of the suggested items. * * @param input The text entered by the user, modified to include the autocompletion. * @param completion The suggestion selected by the user. Includes markdown formatting, but not the prefix. Eg. **FullName**, **StreamName**. * @param lastWordPrefix The type of the autocompletion - valid values are keys of 'prefixToComponent'. */ onAutocomplete: (input: string, completion: string, lastWordPrefix: string) => void, |}>; export default function AutocompleteView(props: Props): Node { const { isFocused, text, onAutocomplete, selection, destinationNarrow } = props; const handleAutocomplete = useCallback( (autocomplete: string) => { const { lastWordPrefix } = getAutocompleteFilter(text, selection); const newText = getAutocompletedText(text, autocomplete, selection); onAutocomplete(newText, autocomplete, lastWordPrefix); }, [onAutocomplete, selection, text], ); const { lastWordPrefix, filter } = getAutocompleteFilter(text, selection); const AutocompleteComponent = prefixToComponent[lastWordPrefix]; const shouldShow = isFocused && !!AutocompleteComponent && filter.length > 0; return ( <AnimatedScaleComponent visible={shouldShow}> {shouldShow && ( <AutocompleteComponent filter={filter} onAutocomplete={handleAutocomplete} destinationNarrow={destinationNarrow} /> )} </AnimatedScaleComponent> ); } ```
/content/code_sandbox/src/autocomplete/AutocompleteView.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
510
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import { FlatList } from 'react-native'; import type { Narrow } from '../types'; import { useSelector } from '../react-redux'; import Popup from '../common/Popup'; import { getSubscriptions } from '../directSelectors'; import StreamItem from '../streams/StreamItem'; type Props = $ReadOnly<{| filter: string, onAutocomplete: (name: string) => void, destinationNarrow?: Narrow, |}>; export default function StreamAutocomplete(props: Props): Node { const { filter, onAutocomplete } = props; const subscriptions = useSelector(getSubscriptions); const handleStreamItemAutocomplete = useCallback( stream => onAutocomplete(`**${stream.name}**`), [onAutocomplete], ); const isPrefixMatch = x => x.name.toLowerCase().startsWith(filter.toLowerCase()); const matchingSubscriptions = subscriptions // Include it if there's a match anywhere in the name .filter(x => x.name.toLowerCase().includes(filter.toLowerCase())) // but show prefix matches at the top of the list. .sort((a, b) => +isPrefixMatch(b) - +isPrefixMatch(a)); if (matchingSubscriptions.length === 0) { return null; } return ( <Popup> <FlatList nestedScrollEnabled keyboardShouldPersistTaps="always" initialNumToRender={matchingSubscriptions.length} data={matchingSubscriptions} keyExtractor={item => item.stream_id.toString()} renderItem={({ item }) => ( <StreamItem streamId={item.stream_id} name={item.name} isMuted={!item.in_home_view} isPrivate={item.invite_only} isWebPublic={item.is_web_public} iconSize={12} color={item.color} onPress={handleStreamItemAutocomplete} /> )} /> </Popup> ); } ```
/content/code_sandbox/src/autocomplete/StreamAutocomplete.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
431
```javascript /* @flow strict-local */ import getAutocompletedText from '../getAutocompletedText'; describe('getAutocompletedText', () => { let selection = { start: 3, end: 3 }; test('can autocomplete users', () => { expect(getAutocompletedText('@ab', '**abcd**', selection)).toEqual('@**abcd** '); }); test('can autocomplete user groups', () => { expect(getAutocompletedText('@ab', '*abcd*', selection)).toEqual('@*abcd* '); }); test('can autocomplete streams', () => { expect(getAutocompletedText('#ab', '**abcd**', selection)).toEqual('#**abcd** '); }); test('can autocomplete emojis', () => { expect(getAutocompletedText(':ab', 'abcd', selection)).toEqual(':abcd: '); }); test('can autocomplete more complicated text', () => { selection = { start: 12, end: 12 }; expect(getAutocompletedText('@**word** @w', '**word word**', selection)).toEqual( '@**word** @**word word** ', ); selection = { start: 2, end: 2 }; expect(getAutocompletedText(':+', '+1', selection)).toEqual(':+1: '); }); test('get autocompleted text for middle text autocomplete', () => { selection = { start: 3, end: 3 }; expect(getAutocompletedText(':abSome text', 'abcd', selection)).toEqual(':abcd: Some text'); }); }); ```
/content/code_sandbox/src/autocomplete/__tests__/getAutocompletedText-test.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 getAutocompleteFilter from '../getAutocompleteFilter'; describe('getAutocompleteFilter', () => { let selection = { start: 0, end: 0 }; test('get empty object for empty text', () => { expect(getAutocompleteFilter('', selection)).toEqual({ filter: '', lastWordPrefix: '' }); }); test('get @users filters', () => { selection = { start: 1, end: 1 }; expect(getAutocompleteFilter('@', selection)).toEqual({ filter: '', lastWordPrefix: '@' }); selection = { start: 3, end: 3 }; expect(getAutocompleteFilter('@ab', selection)).toEqual({ filter: 'ab', lastWordPrefix: '@' }); selection = { start: 6, end: 6 }; expect(getAutocompleteFilter('@ab cd', selection)).toEqual({ filter: 'ab cd', lastWordPrefix: '@', }); selection = { start: 5, end: 5 }; expect(getAutocompleteFilter('abc @ ', selection)).toEqual({ filter: '', lastWordPrefix: '@', }); }); test('get respective lastWordPrefix even when keyword is entered in new line', () => { selection = { start: 1, end: 1 }; expect(getAutocompleteFilter('\n@', selection)).toEqual({ filter: '', lastWordPrefix: '' }); expect(getAutocompleteFilter('\n#', selection)).toEqual({ filter: '', lastWordPrefix: '' }); expect(getAutocompleteFilter('\n:', selection)).toEqual({ filter: '', lastWordPrefix: '' }); selection = { start: 2, end: 2 }; expect(getAutocompleteFilter('\n@', selection)).toEqual({ filter: '', lastWordPrefix: '@' }); expect(getAutocompleteFilter('\n#', selection)).toEqual({ filter: '', lastWordPrefix: '#' }); expect(getAutocompleteFilter('\n:', selection)).toEqual({ filter: '', lastWordPrefix: ':' }); }); test('get #streams filters', () => { selection = { start: 1, end: 1 }; expect(getAutocompleteFilter('#', selection)).toEqual({ filter: '', lastWordPrefix: '#' }); selection = { start: 3, end: 3 }; expect(getAutocompleteFilter('#ab', selection)).toEqual({ filter: 'ab', lastWordPrefix: '#' }); selection = { start: 6, end: 6 }; expect(getAutocompleteFilter('#ab cd', selection)).toEqual({ filter: 'ab cd', lastWordPrefix: '#', }); selection = { start: 5, end: 5 }; expect(getAutocompleteFilter('abc # ', selection)).toEqual({ filter: '', lastWordPrefix: '#', }); }); test('get :emoji filters', () => { selection = { start: 1, end: 1 }; expect(getAutocompleteFilter(':', selection)).toEqual({ filter: '', lastWordPrefix: ':' }); selection = { start: 3, end: 3 }; expect(getAutocompleteFilter(':ab', selection)).toEqual({ filter: 'ab', lastWordPrefix: ':' }); selection = { start: 6, end: 6 }; expect(getAutocompleteFilter(':ab cd', selection)).toEqual({ filter: 'ab cd', lastWordPrefix: ':', }); selection = { start: 5, end: 5 }; expect(getAutocompleteFilter('abc : ', selection)).toEqual({ filter: '', lastWordPrefix: ':', }); }); test('get filter for more complicated text', () => { selection = { start: 9, end: 9 }; expect(getAutocompleteFilter(':smile@ab', selection)).toEqual({ filter: 'smile@ab', lastWordPrefix: ':', }); selection = { start: 2, end: 2 }; expect(getAutocompleteFilter(':s@ab', selection)).toEqual({ filter: 's', lastWordPrefix: ':' }); selection = { start: 12, end: 12 }; expect(getAutocompleteFilter(':smile@ab cd', selection)).toEqual({ filter: 'smile@ab cd', lastWordPrefix: ':', }); selection = { start: 3, end: 3 }; expect(getAutocompleteFilter('@ab :cd #a b', selection)).toEqual({ filter: 'ab', lastWordPrefix: '@', }); selection = { start: 7, end: 7 }; expect(getAutocompleteFilter('@ab :cd #a b', selection)).toEqual({ filter: 'cd', lastWordPrefix: ':', }); selection = { start: 12, end: 12 }; expect(getAutocompleteFilter('@ab :cd #a b', selection)).toEqual({ filter: 'a b', lastWordPrefix: '#', }); selection = { start: 8, end: 8 }; expect(getAutocompleteFilter(':#@smile', selection)).toEqual({ filter: 'smile', lastWordPrefix: '@', }); selection = { start: 1, end: 1 }; expect(getAutocompleteFilter(':#@smile', selection)).toEqual({ filter: '', lastWordPrefix: ':', }); selection = { start: 11, end: 11 }; expect(getAutocompleteFilter('@r@::@q@m p', selection)).toEqual({ filter: '@q@m p', lastWordPrefix: ':', }); selection = { start: 1, end: 1 }; expect(getAutocompleteFilter('@r@::@q@m p', selection)).toEqual({ filter: '', lastWordPrefix: '@', }); selection = { start: 16, end: 16 }; expect(getAutocompleteFilter('some @ab:cd #a b', selection)).toEqual({ filter: 'a b', lastWordPrefix: '#', }); }); }); ```
/content/code_sandbox/src/autocomplete/__tests__/getAutocompleteFilter-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,311
```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 { createStyleSheet } from '../styles'; const styles = createStyleSheet({ wrapper: { justifyContent: 'center', alignItems: 'center', }, overlay: { position: 'absolute', overflow: 'hidden', }, 'top-right': { right: 0, top: 0, }, 'top-left': { left: 0, top: 0, }, 'bottom-right': { right: 0, bottom: 0, }, 'bottom-left': { bottom: 0, left: 0, }, }); type Props = $ReadOnly<{| children: Node, overlay: Node, showOverlay?: boolean, overlaySize: number, overlayColor: string, overlayPosition: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left', style?: ViewStyleProp, customOverlayStyle?: ViewStyleProp, |}>; /** * Place an overlay, with a colored-disk background, on another component. * * @prop children - Main component to be rendered. * @prop overlay - Component to be overlayed over the main one. * @prop [showOverlay] - Should the overlay be shown. * @prop overlaySize - The size of the overlay in pixels. * @prop overlayColor - Background color for overlay. * @prop overlayPosition - What corner to align the overlay to. * @prop [style] - Applied to a wrapper View. * @prop [customOverlayStyle] - Apply custom style to overlay. */ export default function ComponentWithOverlay(props: Props): Node { const { children, style, overlay, showOverlay = true, overlayPosition, overlaySize, overlayColor, customOverlayStyle, } = props; const wrapperStyle = [styles.wrapper, style]; const overlayStyle = [ styles.wrapper, styles.overlay, styles[overlayPosition], { minWidth: overlaySize, height: overlaySize, borderRadius: overlaySize, backgroundColor: overlayColor, }, customOverlayStyle, ]; return ( <View style={wrapperStyle}> {children} {showOverlay && overlaySize > 0 && <View style={overlayStyle}>{overlay}</View>} </View> ); } ```
/content/code_sandbox/src/common/ComponentWithOverlay.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
546
```javascript /* @flow strict-local */ import React, { useState, useCallback } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import Input from './Input'; import type { Props as InputProps } from './Input'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import ZulipTextIntl from './ZulipTextIntl'; import Touchable from './Touchable'; const styles = createStyleSheet({ showPasswordButton: { position: 'absolute', right: 0, top: 0, bottom: 0, justifyContent: 'center', }, showPasswordButtonText: { margin: 8, color: BRAND_COLOR, }, }); // Prettier wants a ", >" here, which is silly. // prettier-ignore type Props = $ReadOnly<$Diff<InputProps, // "mixed" here is a way of spelling "no matter *what* type // `InputProps` allows for these, don't allow them here." {| secureTextEntry: mixed, autoCorrect: mixed, autoCapitalize: mixed, _: mixed |}>>; /** * A password input component using Input internally. * Provides a 'show'/'hide' button to show the password. * * All props are passed through to `Input`. See `Input` for descriptions. */ export default function PasswordInput(props: Props): Node { const [isHidden, setIsHidden] = useState<boolean>(true); const handleShow = useCallback(() => { setIsHidden(prevIsHidden => !prevIsHidden); }, []); return ( <View> <Input {...props} secureTextEntry={isHidden} autoCorrect={false} autoCapitalize="none" /> <Touchable style={styles.showPasswordButton} onPress={handleShow}> <ZulipTextIntl style={styles.showPasswordButtonText} text={isHidden ? 'show' : 'hide'} /> </Touchable> </View> ); } ```
/content/code_sandbox/src/common/PasswordInput.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
423
```javascript /* @flow strict-local */ import * as React from 'react'; import { View } from 'react-native'; // $FlowFixMe[untyped-import] import Color from 'color'; import type { LocalizableReactText } from '../types'; import { kWarningColor } from '../styles/constants'; import { createStyleSheet } from '../styles'; import ZulipTextIntl from './ZulipTextIntl'; import ZulipTextButton from './ZulipTextButton'; type Button = {| +id: string, +label: LocalizableReactText, +onPress: () => Promise<void> | void, |}; type Props = $ReadOnly<{| text: LocalizableReactText, buttons?: $ReadOnlyArray<Button>, /** * Give a top margin of the correct in-between space for a set of buttons */ topMargin?: true, /** * Give a bottom margin of the correct in-between space for a set of * buttons */ bottomMargin?: true, |}>; // TODO before reuse: jsdoc export default function AlertItem(props: Props): React.Node { const { text, buttons, topMargin, bottomMargin } = props; const styles = React.useMemo( () => createStyleSheet({ surface: { padding: 8, backgroundColor: Color(kWarningColor).fade(0.9).toString(), borderColor: kWarningColor, borderWidth: 1, borderRadius: 8, marginTop: topMargin ? 8 : undefined, marginBottom: bottomMargin ? 8 : undefined, }, text: { color: kWarningColor, }, buttonsRow: { flexDirection: 'row', }, }), [bottomMargin, topMargin], ); return ( <View style={styles.surface}> <ZulipTextIntl style={styles.text} text={text} /> {buttons && ( <View style={styles.buttonsRow}> {buttons.map(({ id, label, onPress }, index) => ( <ZulipTextButton key={id} leftMargin={index !== 0 || undefined} label={label} onPress={onPress} /> ))} </View> )} </View> ); } ```
/content/code_sandbox/src/common/AlertItem.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
489
```javascript // @flow strict-local import React, { type Node } from 'react'; import { Text, View } from 'react-native'; // eslint-disable-next-line import/extensions import codePointMap from '../../static/assets/fonts/zulip-icons.map.js'; type Props = $ReadOnly<{| ...$Exact<React$ElementConfig<typeof Text>>, name: $Keys<typeof codePointMap>, size: number, color?: string, |}>; /** The icons font. */ const fontFamily = 'zulip-icons'; /** * An icon from Zulip's custom icons. * * This component provides the same icons that are written in the web app * with CSS class `zulip-icon`. * * Specifically, where the web app writes * `<i class="zulip-icon zulip-icon-SOMETHING" ></i>`, * one can get the same icon here by writing * `<ZulipIcon name='SOMETHING' />`. * * These icons come from the Zulip shared package, `@zulip/shared` on NPM; * they're `static/shared/icons/*.svg` in the zulip.git tree. For more * background, see `tools/build-icon-font`. * * This component accepts all `Text` style props, which it passes to an * internal `Text` component. But it does not inherit text styles from its * parent. If you want some style that's also present on the parent, pass * it explicitly. */ export default function ZulipIcon(props: Props): Node { const { name, size, color, style: styleOuter, ...restProps } = props; const codePoint = codePointMap[name]; const glyph = codePoint == null ? ' ICON MISSING ' : String.fromCodePoint(codePoint); const style = [styleOuter, { fontFamily, fontSize: size, color }]; return ( <View> {/* The wrapper View ensures we don't inherit text styles: path_to_url#nested-text In particular, inheriting `fontWeight: 'bold'` or `fontStyle: 'italic'` would result in not finding a glyph for the icon in the font. */} <Text selectable={false} style={style} {...restProps}> {glyph} </Text> </View> ); } ```
/content/code_sandbox/src/common/ZulipIcon.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
502
```javascript /* @flow strict-local */ import React from 'react'; import type { ComponentType } from 'react'; import { Text } from 'react-native'; import type { IconProps as IconPropsBusted } from 'react-native-vector-icons'; import Feather from 'react-native-vector-icons/Feather'; import type { FeatherGlyphs } from 'react-native-vector-icons/Feather'; import IoniconsIcon from 'react-native-vector-icons/Ionicons'; import MaterialIcon from 'react-native-vector-icons/MaterialIcons'; import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import ZulipIcon from './ZulipIcon'; /** * The props actually accepted by icon components in r-n-vector-icons. * * This corresponds to the documented interface: * path_to_url#properties * * Upstream has a .js.flow file which is meant to describe this. But the * type definition there is wrong in a couple of ways: * * it leaves most of the properties of `Text` unspecified, and just * defines an inexact object type so that it's much looser than reality; * * of the handful of properties it does mention, it defines one more * narrowly than the actual `Text`, as `allowFontScaling?: boolean` when * it should be `allowFontScaling?: ?boolean`. */ type IconProps<Glyphs: string> = {| ...$Exact<React$ElementConfig<typeof Text>>, name: Glyphs, /** * The size, as a font size. * * Upstream accepts a missing size. But really a default size doesn't * make sense, so we make it required. */ size: number, color?: string, |}; const fixIconType = <Glyphs: string>( iconSet: ComponentType<IconPropsBusted<Glyphs>>, ): ComponentType<IconProps<Glyphs>> => (iconSet: $FlowFixMe); // See comment above about wrong types. /** Names acceptable for `Icon`. */ export type IconNames = FeatherGlyphs; /** A component-type for the icon set we mainly use. */ export const Icon: ComponentType<IconProps<IconNames>> = fixIconType<IconNames>(Feather); /** A (type for a) component-type like `Icon` but with `name` already specified. */ export type SpecificIconType = ComponentType<$Diff<IconProps<empty>, {| name: mixed |}>>; const makeIcon = <Glyphs: string>( iconSet: ComponentType<IconPropsBusted<Glyphs>>, name: Glyphs, ): SpecificIconType => function RNVIIcon(props) { const FixedIcon = fixIconType<Glyphs>(iconSet); return <FixedIcon name={name} {...props} />; }; export const IconInbox: SpecificIconType = makeIcon(Feather, 'inbox'); export const IconMention: SpecificIconType = makeIcon(Feather, 'at-sign'); export const IconSearch: SpecificIconType = makeIcon(Feather, 'search'); // SelectableOptionRow depends on this being square. export const IconDone: SpecificIconType = makeIcon(Feather, 'check'); export const IconCancel: SpecificIconType = makeIcon(Feather, 'slash'); export const IconTrash: SpecificIconType = makeIcon(Feather, 'trash-2'); export const IconSend: SpecificIconType = makeIcon(MaterialIcon, 'send'); export const IconMute: SpecificIconType = makeIcon(MaterialIcon, 'volume-off'); export const IconStream: SpecificIconType = makeIcon(Feather, 'hash'); export const IconPin: SpecificIconType = makeIcon(SimpleLineIcons, 'pin'); export const IconPrivate: SpecificIconType = makeIcon(Feather, 'lock'); export const IconPrivateChat: SpecificIconType = makeIcon(Feather, 'mail'); export const IconApple: SpecificIconType = makeIcon(IoniconsIcon, 'logo-apple'); export const IconGoogle: SpecificIconType = makeIcon(IoniconsIcon, 'logo-google'); export const IconGitHub: SpecificIconType = makeIcon(Feather, 'github'); export const IconWindows: SpecificIconType = makeIcon(IoniconsIcon, 'logo-windows'); export const IconNotifications: SpecificIconType = makeIcon(Feather, 'bell'); export const IconLanguage: SpecificIconType = makeIcon(Feather, 'globe'); export const IconSettings: SpecificIconType = makeIcon(Feather, 'settings'); export const IconCaretUp: SpecificIconType = makeIcon(MaterialIcon, 'expand-less'); export const IconCaretDown: SpecificIconType = makeIcon(MaterialIcon, 'expand-more'); // InputRowRadioButtons depends on this being square. export const IconRight: SpecificIconType = makeIcon(Feather, 'chevron-right'); export const IconPlusCircle: SpecificIconType = makeIcon(Feather, 'plus-circle'); export const IconLeft: SpecificIconType = makeIcon(Feather, 'chevron-left'); // UserGroupItem depends on this being square. export const IconPeople: SpecificIconType = makeIcon(Feather, 'users'); export const IconPerson: SpecificIconType = makeIcon(Feather, 'user'); export const IconImage: SpecificIconType = makeIcon(Feather, 'image'); export const IconCamera: SpecificIconType = makeIcon(Feather, 'camera'); export const IconTerminal: SpecificIconType = makeIcon(Feather, 'terminal'); export const IconMoreHorizontal: SpecificIconType = makeIcon(Feather, 'more-horizontal'); export const IconSmartphone: SpecificIconType = makeIcon(Feather, 'smartphone'); export const IconServer: SpecificIconType = makeIcon(Feather, 'server'); export const IconEdit: SpecificIconType = makeIcon(Feather, 'edit'); export const IconPlusSquare: SpecificIconType = makeIcon(Feather, 'plus-square'); export const IconVideo: SpecificIconType = makeIcon(Feather, 'video'); export const IconUserBlank: SpecificIconType = makeIcon(FontAwesome, 'user'); export const IconAttach: SpecificIconType = makeIcon(Feather, 'paperclip'); export const IconAttachment: SpecificIconType = makeIcon(IoniconsIcon, 'document-attach-outline'); export const IconGroup: SpecificIconType = makeIcon(FontAwesome, 'group'); export const IconPlus: SpecificIconType = makeIcon(Feather, 'plus'); export const IconAlertTriangle: SpecificIconType = makeIcon(Feather, 'alert-triangle'); // WildcardMentionItem depends on this being square. export const IconWildcardMention: SpecificIconType = makeIcon(FontAwesome, 'bullhorn'); /* eslint-disable react/function-component-definition */ export const IconWebPublic: SpecificIconType = props => <ZulipIcon name="globe" {...props} />; export const IconFollow: SpecificIconType = props => <ZulipIcon name="follow" {...props} />; ```
/content/code_sandbox/src/common/Icons.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,508
```javascript /* @flow strict-local */ import React, { useState, useCallback, useContext } from 'react'; import type { Node } from 'react'; import { TextInput, Platform } from 'react-native'; import type { LocalizableText } from '../types'; import { createStyleSheet, ThemeContext, HALF_COLOR, BORDER_COLOR } from '../styles'; import { TranslationContext } from '../boot/TranslationProvider'; export type Props = $ReadOnly<{| ...React$ElementConfig<typeof TextInput>, placeholder?: LocalizableText, onChangeText?: (text: string) => void, textInputRef?: React$Ref<typeof TextInput>, |}>; const componentStyles = createStyleSheet({ input: { ...Platform.select({ ios: { borderWidth: 1, borderColor: BORDER_COLOR, borderRadius: 2, padding: 8, }, }), }, }); /** * A light abstraction over the standard TextInput component * that allows us to seamlessly provide internationalization * capabilities and also style the component depending on * the platform the app is running on. * * @prop [style] - Can override our default style for inputs. * @prop placeholder - Translated before passing to TextInput as * a prop of the same name. * @prop [textInputRef] - Passed to TextInput in `ref`. See upstream docs * on refs: path_to_url * @prop ...all other TextInput props - Passed through verbatim to TextInput. * See upstream: path_to_url */ export default function Input(props: Props): Node { const { style, placeholder, textInputRef, ...restProps } = props; const [isFocused, setIsFocused] = useState<boolean>(false); const handleFocus = useCallback(() => { setIsFocused(true); }, []); const handleBlur = useCallback(() => { setIsFocused(false); }, []); const themeContext = useContext(ThemeContext); const _ = useContext(TranslationContext); return ( <TextInput style={[componentStyles.input, { color: themeContext.color }, style]} placeholder={placeholder != null ? _(placeholder) : undefined} placeholderTextColor={HALF_COLOR} underlineColorAndroid={isFocused ? BORDER_COLOR : HALF_COLOR} onFocus={handleFocus} onBlur={handleBlur} ref={textInputRef} {...restProps} /> ); } ```
/content/code_sandbox/src/common/Input.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
497
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Image, View } from 'react-native'; import SpinningProgress from './SpinningProgress'; import { createStyleSheet } from '../styles'; import messageLoadingImg from '../../static/img/message-loading.png'; const styles = createStyleSheet({ wrapper: { flex: 1, padding: 4, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, logo: { alignSelf: 'center', overflow: 'hidden', position: 'absolute', }, }); type Props = $ReadOnly<{| color?: 'default' | 'black' | 'white', showLogo?: boolean, size?: number, |}>; /** * Renders a loading indicator - a faint circle and a bold * quarter of a circle spinning around it. Optionally, * a Zulip logo in the center. * * @prop [color] - The color of the circle. * @prop [showLogo] - Show or not a Zulip logo in the center. * @prop [size] - Diameter of the indicator in pixels. */ export default function LoadingIndicator(props: Props): Node { const { color = 'default', showLogo = false, size = 40 } = props; return ( <View style={styles.wrapper}> <View> <SpinningProgress color={color} size={size} /> {showLogo && ( <Image style={[ styles.logo, { width: (size / 3) * 2, height: (size / 3) * 2, marginTop: size / 6 }, ]} source={messageLoadingImg} resizeMode="contain" /> )} </View> </View> ); } ```
/content/code_sandbox/src/common/LoadingIndicator.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
390
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import ZulipTextIntl from './ZulipTextIntl'; import { createStyleSheet } from '../styles'; const styles = createStyleSheet({ field: { flexDirection: 'row', marginTop: 5, marginBottom: 5, justifyContent: 'center', }, error: { color: 'red', fontSize: 16, }, }); type Props = $ReadOnly<{| error: string, |}>; /** * Displays a styled error message. * If no message provided, component is not rendered. * * @prop error - The error message string. */ export default function ErrorMsg(props: Props): Node { const { error } = props; if (!error) { return null; } return ( <View style={styles.field}> <ZulipTextIntl style={styles.error} text={error} /> </View> ); } ```
/content/code_sandbox/src/common/ErrorMsg.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
221
```javascript /* @flow strict-local */ import { useState, useCallback, useRef } from 'react'; import { useConditionalEffect, useDebugAssertConstant, useHasStayedTrueForMs } from '../reactUtils'; import { tryFetch } from '../message/fetchActions'; type SuccessResult<TData> = {| +type: 'success', +data: TData |}; type FailResult = {| +type: 'error', +error: mixed |}; type Result<TData> = SuccessResult<TData> | FailResult; /** * Fetch and refresh data outside the event system, to show in the UI. * * Some data, like read receipts, isn't provided via the event system and * must be fetched with an API call. Use this Hook to maintain an * automatically refreshed shapshot of the data in a React component. * * The returned `latestResult` and `latestSuccessResult` will be unique per * request and will be === when the latest result was successful. * * Of course, any API call can fail or take longer than expected. Callers * should use this Hook's output to inform the user when this is the case. * For example: * * const { latestResult, latestSuccessResult } = useFetchedDataWithRefresh(); * const latestResultIsError = latestResult?.type === 'error'; * const isFirstLoadLate = useHasStayedTrueForMs(latestSuccessResult === null, 10_000); * const haveStaleData = * useHasNotChangedForMs(latestSuccessResult, 40_000) && latestSuccessResult !== null; * * Still, this Hook handles its own retry logic and will do its best to * fetch and show the data for as long as the calling React component is * mounted. * * @param {callApiMethod} - E.g., a function that returns the Promise from * api.getReadReceipts(), to fetch read receipts. * @param {refreshIntervalMs} - How long to wait after the latest response * (success or failure) before requesting again. */ export default function useFetchedDataWithRefresh<TData>( callApiMethod: () => Promise<TData>, refreshIntervalMs: number, ): {| +latestResult: null | Result<TData>, +latestSuccessResult: null | SuccessResult<TData>, |} { useDebugAssertConstant(refreshIntervalMs); const [isFetching, setIsFetching] = useState(false); const [latestResult, setLatestResult] = useState(null); const [latestSuccessResult, setLatestSuccessResult] = useState(null); const fetch = useCallback(async () => { setIsFetching(true); try { const data: TData = await tryFetch(callApiMethod); const result = { type: 'success', data }; setLatestResult(result); setLatestSuccessResult(result); } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url const result = { type: 'error', error }; setLatestResult(result); } finally { setIsFetching(false); } }, [callApiMethod]); const startFetchIfNotFetching = useCallback(() => { if (isFetching) { return; } fetch(); }, [isFetching, fetch]); const isFirstCall = useRef(true); const shouldRefresh = useHasStayedTrueForMs(!isFetching, refreshIntervalMs) || isFirstCall.current; isFirstCall.current = false; useConditionalEffect(startFetchIfNotFetching, shouldRefresh); return { latestResult, latestSuccessResult, }; } ```
/content/code_sandbox/src/common/useFetchedDataWithRefresh.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
774
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View, useColorScheme } from 'react-native'; import { ThemeContext, createStyleSheet } from '../styles'; import { useGlobalSelector } from '../react-redux'; import { getGlobalSettings } from '../directSelectors'; import { getThemeToUse } from '../settings/settingsSelectors'; const styles = createStyleSheet({ popup: { maxHeight: 250, marginHorizontal: 16, marginVertical: 8, borderRadius: 5, overflow: 'hidden', // Keep the overlay inside the rounded corners. // Elevation of 8 agrees with menus and bottom sheets, which seem like // the best matches in this table: // path_to_url#default-elevations elevation: 8, // TODO(material): Is this the right shadow for that elevation? shadowOpacity: 0.5, shadowRadius: 16, }, // In a dark theme, we signal elevation by overlaying the background with // white at low opacity, following the Material spec: // path_to_url#properties // (In a light theme, the shadow does that job.) overlay: { backgroundColor: 'hsla(0, 0%, 100%, 0.12)', // elevation 8 -> alpha 0.12 }, }); type Props = $ReadOnly<{| children: Node, |}>; /** * An elevated surface, good for autocomplete popups. * * If using this for something else, consider parametrizing its height, or * other constants in its styles. */ export default function Popup(props: Props): Node { const themeContext = useContext(ThemeContext); const theme = useGlobalSelector(state => getGlobalSettings(state).theme); const osScheme = useColorScheme(); const themeToUse = getThemeToUse(theme, osScheme); // TODO(color/theme): find a cleaner way to express this const isDarkTheme = themeToUse !== 'light'; return ( <View style={[{ backgroundColor: themeContext.backgroundColor }, styles.popup]}> <View style={isDarkTheme && styles.overlay}>{props.children}</View> </View> ); } ```
/content/code_sandbox/src/common/Popup.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
486
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; // $FlowFixMe[untyped-import] import Color from 'color'; import Touchable from './Touchable'; import { createStyleSheet } from '../styles'; import { colorHashFromString } from '../utils/color'; import { IconGroup } from './Icons'; const styles = createStyleSheet({ frame: { justifyContent: 'center', alignItems: 'center', }, }); type Props = $ReadOnly<{| names: $ReadOnlyArray<string>, size: number, children?: Node, onPress?: () => void, |}>; /** * Renders a text avatar based on a single or multiple user's * initials and a color calculated as a hash from their name. * We are currently using it only for group chats. * * @prop names - The name of one or more users, used to extract their initials. * @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. */ export default function GroupAvatar(props: Props): Node { const { children, names, size, onPress } = props; const frameSize = { height: size, width: size, borderRadius: size / 8, backgroundColor: Color(colorHashFromString(names.join(', '))) .lighten(0.6) .hex(), }; const iconColor = Color(colorHashFromString(names.join(', '))).string(); return ( <Touchable onPress={onPress}> <View style={[styles.frame, frameSize]}> <IconGroup size={size * 0.75} color={iconColor} /> {children} </View> </Touchable> ); } ```
/content/code_sandbox/src/common/GroupAvatar.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
391
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import ComponentWithOverlay from './ComponentWithOverlay'; import UnreadCount from './UnreadCount'; import { BRAND_COLOR, createStyleSheet } from '../styles'; const styles = createStyleSheet({ button: { flex: 1, }, overlayStyle: { right: -10, top: 10, }, }); type Props = $ReadOnly<{| children: Node, unreadCount: number, |}>; export default function CountOverlay(props: Props): Node { const { children, unreadCount } = props; return ( <View> <ComponentWithOverlay style={styles.button} // It looks like what we want to match is 25 * 0.75, which is 18.75, // path_to_url#L69 overlaySize={18.75} overlayColor={BRAND_COLOR} overlayPosition="top-right" showOverlay={unreadCount > 0} customOverlayStyle={styles.overlayStyle} overlay={<UnreadCount count={unreadCount} />} > {children} </ComponentWithOverlay> </View> ); } ```
/content/code_sandbox/src/common/CountOverlay.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
271
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { createStyleSheet } from '../styles'; const styles = createStyleSheet({ separator: { height: 1, margin: 10, backgroundColor: 'hsla(0, 0%, 50%, 0.75)', }, }); export default function SectionSeparator(props: {||}): Node { return <View style={styles.separator} />; } ```
/content/code_sandbox/src/common/SectionSeparator.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
108
```javascript /* @flow strict-local */ import React, { useContext, useMemo } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { EmojiType, LocalizableReactText } from '../types'; import ZulipTextIntl from './ZulipTextIntl'; import Touchable from './Touchable'; import { Icon, IconRight } from './Icons'; import type { SpecificIconType } from './Icons'; import globalStyles, { ThemeContext, createStyleSheet } from '../styles'; import Emoji from '../emoji/Emoji'; import { ensureUnreachable } from '../generics'; type Props = $ReadOnly<{| /** An icon or emoji displayed at the left of the row. */ leftElement?: | {| +type: 'icon', +Component: SpecificIconType, +color?: string, |} | {| +type: 'emoji', +emojiCode: string, +emojiType: EmojiType, |}, title: LocalizableReactText, subtitle?: LocalizableReactText, // TODO: Should we make this unconfigurable? Should we have two reusable // components, with and without this? titleBoldUppercase?: true, type?: 'nested' | 'external', /** * Press handler for the whole row. * * The behavior should correspond to `type`: * 'nested': navigate to a "nested" screen. * 'external': open a URL with the user's `BrowserPreference` */ onPress: () => void | Promise<void>, |}>; /** * When tapped, this row navigates to a "nested" screen or opens a URL. * * 'nested' type: shows a right-facing arrow. * 'external' type: shows an "external link" icon. * * If you need a selectable option row instead, use `SelectableOptionRow`. */ export default function NavRow(props: Props): Node { const { title, subtitle, titleBoldUppercase, type = 'nested', onPress, leftElement } = props; const themeContext = useContext(ThemeContext); const styles = useMemo( () => createStyleSheet({ container: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8, paddingHorizontal: 16, // Minimum touch target height (and width): // path_to_url#layout-and-typography minHeight: 48, }, leftElement: { marginRight: 8, }, iconFromProps: { textAlign: 'center', }, textWrapper: { flex: 1, }, title: { ...(titleBoldUppercase ? { textTransform: 'uppercase', fontWeight: '500' } : undefined), }, subtitle: { fontWeight: '300', fontSize: 13, }, iconRight: { textAlign: 'center', marginLeft: 8, color: themeContext.color, }, }), [themeContext, titleBoldUppercase], ); return ( <Touchable onPress={onPress}> <View style={styles.container}> {leftElement && ( <View style={styles.leftElement}> {(() => { switch (leftElement.type) { case 'icon': return ( <leftElement.Component size={24} style={styles.iconFromProps} color={leftElement.color ?? themeContext.color} /> ); case 'emoji': return ( <Emoji size={24} code={leftElement.emojiCode} type={leftElement.emojiType} /> ); default: ensureUnreachable(leftElement.type); } })()} </View> )} <View style={styles.textWrapper}> <ZulipTextIntl style={styles.title} text={title} /> {subtitle !== undefined && <ZulipTextIntl style={styles.subtitle} text={subtitle} />} </View> <View style={globalStyles.rightItem}> {type === 'nested' ? ( <IconRight size={24} style={styles.iconRight} /> ) : ( <Icon name="external-link" size={24} style={styles.iconRight} /> )} </View> </View> </Touchable> ); } ```
/content/code_sandbox/src/common/NavRow.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
933
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { useSelector } from '../react-redux'; import { getLoading } from '../selectors'; import ZulipTextIntl from './ZulipTextIntl'; import LoadingIndicator from './LoadingIndicator'; import { ThemeContext, createStyleSheet } from '../styles'; const key = 'LoadingBanner'; const styles = createStyleSheet({ block: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: 'hsl(6, 98%, 57%)', }, none: { display: 'none' }, }); type Props = $ReadOnly<{| spinnerColor?: 'black' | 'white' | 'default', textColor?: string, backgroundColor?: string, |}>; /** * Display a notice that the app is connecting to the server, when appropriate. */ export default function LoadingBanner(props: Props): Node { const loading = useSelector(getLoading); const themeContext = useContext(ThemeContext); if (!loading) { return <View key={key} style={styles.none} />; } const { spinnerColor = 'default', textColor = themeContext.color, backgroundColor = themeContext.backgroundColor, } = props; const style = { width: '100%', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor, }; return ( <View key={key} style={style}> <View> <LoadingIndicator size={14} color={spinnerColor} /> </View> <ZulipTextIntl style={{ fontSize: 14, margin: 2, color: textColor, }} text="Connecting..." /> </View> ); } ```
/content/code_sandbox/src/common/LoadingBanner.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
398
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { ScrollView, View } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import type { EditingEvent } from 'react-native/Libraries/Components/TextInput/TextInput'; import { createStyleSheet, ThemeContext } from '../styles'; import type { LocalizableText, LocalizableReactText } from '../types'; import KeyboardAvoider from './KeyboardAvoider'; import LoadingBanner from './LoadingBanner'; import ModalNavBar from '../nav/ModalNavBar'; import ModalSearchNavBar from '../nav/ModalSearchNavBar'; type Props = $ReadOnly<{| centerContent?: boolean, children: Node, keyboardShouldPersistTaps?: 'never' | 'always' | 'handled', padding?: boolean, scrollEnabled?: boolean, search?: boolean, autoFocus?: boolean, searchBarOnChange?: (text: string) => void, searchBarOnSubmit?: (e: EditingEvent) => void, shouldShowLoadingBanner?: boolean, searchPlaceholder?: LocalizableText, canGoBack?: boolean, title?: LocalizableReactText, |}>; /** * Wrapper component for each screen of the app, for consistent look-and-feel. * * Provides a nav bar, colors the status bar, can center the contents, etc. * The `children` are ultimately wrapped in a `ScrollView` from upstream. * * @prop [centerContent] - Should the contents be centered. * @prop children - Components to render inside the screen. * @prop [keyboardShouldPersistTaps] - Passed through to ScrollView. * @prop [padding] - Should padding be added to the contents of the screen. * @prop [scrollEnabled] - Whether to use a ScrollView or a normal View. * * @prop [search] - If 'true' show a search box in place of the title. * @prop [autoFocus] - If search bar enabled, should it be focused initially. * @prop [searchBarOnChange] - Event called on search query change. * @prop [searchBarOnSubmit] - Event called on search query submit. * @prop [searchPlaceholder] - text shown as search placeholder. * * @prop [canGoBack] - If true (the default), show UI for "navigate back". * @prop [title] - Text shown as the title of the screen. * Required unless `search` is true. */ export default function Screen(props: Props): Node { const { backgroundColor } = useContext(ThemeContext); const { autoFocus = false, canGoBack = true, centerContent = false, children, keyboardShouldPersistTaps = 'handled', padding = false, scrollEnabled = true, search = false, searchPlaceholder, searchBarOnChange = (text: string) => {}, title = '', shouldShowLoadingBanner = true, searchBarOnSubmit = (e: EditingEvent) => {}, } = props; const styles = React.useMemo( () => createStyleSheet({ screen: { flex: 1, flexDirection: 'column', backgroundColor, }, wrapper: { flex: 1, justifyContent: 'center', alignItems: 'stretch', }, childrenWrapper: { flex: 1, }, centerContent: { flexGrow: 1, justifyContent: 'center', // TODO: decide whether to add `alignItems: 'center'`: // path_to_url#discussion_r665486501 }, padding: { padding: 16, }, }), [backgroundColor], ); return ( <SafeAreaView mode="padding" edges={['bottom']} style={styles.screen}> {search ? ( <ModalSearchNavBar autoFocus={autoFocus} canGoBack={canGoBack} searchBarOnChange={searchBarOnChange} searchBarOnSubmit={searchBarOnSubmit} placeholder={searchPlaceholder} /> ) : ( <ModalNavBar canGoBack={canGoBack} title={title} /> )} {shouldShowLoadingBanner && <LoadingBanner />} <KeyboardAvoider behavior="padding" style={styles.wrapper}> {scrollEnabled ? ( <ScrollView contentContainerStyle={[ centerContent && styles.centerContent, padding && styles.padding, ]} style={styles.childrenWrapper} keyboardShouldPersistTaps={keyboardShouldPersistTaps} > {children} </ScrollView> ) : ( <View style={[ styles.childrenWrapper, centerContent && styles.centerContent, padding && styles.padding, ]} > {children} </View> )} </KeyboardAvoider> </SafeAreaView> ); } ```
/content/code_sandbox/src/common/Screen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,021
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Switch } from 'react-native'; // $FlowFixMe[untyped-import] import Color from 'color'; import { BRAND_COLOR } from '../styles'; type Props = $ReadOnly<{| disabled?: boolean, value: boolean, onValueChange: (arg: boolean) => void, |}>; /** * An on/off component, provides consistent styling of the * built-in Switch component. * * @prop [disabled] - If set the component is not switchable and visually looks disabled. * @prop value - value of the switch. * @prop onValueChange - Event called on switch. */ export default function ZulipSwitch(props: Props): Node { const { disabled = false, onValueChange, value } = props; return ( <Switch value={value} trackColor={{ false: 'hsl(0, 0%, 86%)', true: Color(BRAND_COLOR).fade(0.3).toString(), }} thumbColor={ /* eslint-disable operator-linebreak */ value ? // Material design would actually have this be a secondary // color, not a primary color. See "Thumb attributes" at // this doc: // path_to_url#anatomy-and-key-properties BRAND_COLOR : // Material design would have this be `colorSurface` // (see above-linked doc), which defaults to `#FFFFFF`, // at least in light mode; see // path_to_url '#FFFFFF' } onValueChange={onValueChange} disabled={disabled} /> ); } ```
/content/code_sandbox/src/common/ZulipSwitch.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
367
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { createStyleSheet, HALF_COLOR } from '../styles'; import type { LocalizableReactText } from '../types'; import ZulipTextIntl from './ZulipTextIntl'; import ZulipTextButton from './ZulipTextButton'; // `textRow` and `buttonsRow` are named for the more common case where // there's not enough room for the text and the button(s) to share a single // row. // // But we do support having the text and button(s) share a row if there's // room, i.e., if the entities' combined widths are less than or equal to // one row width. The spec gives an example of this in an illustration where // the text just takes one line and there's only one action button. // // TODO(?): The vertical centering logic for when the text and buttons share // a row isn't pixel-perfect; it depends on explicit padding/margin values // instead of declaring "center" somewhere. This is an intentional // compromise to reduce complexity while still supporting the two-row // layout. If we find an elegant solution, we should use it. const styles = createStyleSheet({ wrapper: { flexDirection: 'row', flexWrap: 'wrap', backgroundColor: HALF_COLOR, paddingLeft: 16, paddingRight: 8, paddingBottom: 8, paddingTop: 10, }, textRow: { flexGrow: 1, flexDirection: 'row', marginBottom: 12, }, text: { marginTop: 6, lineHeight: 20, }, buttonsRow: { flexGrow: 1, flexDirection: 'row', justifyContent: 'flex-end', }, }); type Button = $ReadOnly<{| id: string, label: LocalizableReactText, onPress: () => void, |}>; type Props = $ReadOnly<{| visible: boolean, text: LocalizableReactText, buttons: $ReadOnlyArray<Button>, |}>; /** * A banner that follows Material Design specifications as much as possible. * * See path_to_url */ // Please consult the Material Design doc before making layout changes, and // try to make them in a direction that brings us closer to the guidelines. export default function ZulipBanner(props: Props): Node { const { visible, text, buttons } = props; if (!visible) { return null; } return ( <SafeAreaView mode="padding" edges={['right', 'left']} style={styles.wrapper}> <View style={styles.textRow}> <ZulipTextIntl style={styles.text} text={text} /> </View> <View style={styles.buttonsRow}> {buttons.map(({ id, label, onPress }, index) => ( <ZulipTextButton key={id} leftMargin={index !== 0 || undefined} label={label} onPress={onPress} /> ))} </View> </SafeAreaView> ); } ```
/content/code_sandbox/src/common/ZulipBanner.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
692
```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 { SpecificIconType } from './Icons'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import Touchable from './Touchable'; const styles = createStyleSheet({ wrapper: { justifyContent: 'center', alignItems: 'center', backgroundColor: BRAND_COLOR, // This looks like it could clip the left/right of an icon if it's wider // than it is tall? (This can happen: see // path_to_url#discussion_r631342348.) // See note on the Icon prop in the jsdoc. overflow: 'hidden', }, }); type Props = $ReadOnly<{| style?: ViewStyleProp, disabled: boolean, size: number, Icon: SpecificIconType, onPress: () => void, accessibilityLabel?: string, |}>; /** * A button component implementing a popular 'action button' * UI pattern. The button is circular, has an icon, and usually * overlayed over the main UI in a prominent place. * * @prop [style] - Style applied to the wrapper component. * @prop disabled - If 'true' component can't be pressed and * becomes visibly inactive. * @prop size - Diameter of the component in pixels. * @prop Icon - Icon component to render. Should be a square (?) - see note * where we set overflow: 'hidden' * @prop onPress - Event called on component press. */ export default function FloatingActionButton(props: Props): Node { const { style, size, disabled, onPress, Icon, accessibilityLabel } = props; const iconSize = Math.trunc(size / 2); const customWrapperStyle = { width: size, height: size, borderRadius: size, opacity: disabled ? 0.25 : 1, }; const iconStyle = { margin: Math.trunc(size / 4), }; return ( <Touchable style={style} onPress={disabled ? undefined : onPress} accessibilityLabel={accessibilityLabel} > <View style={[styles.wrapper, customWrapperStyle]}> <Icon style={iconStyle} size={iconSize} color="white" /> </View> </Touchable> ); } ```
/content/code_sandbox/src/common/FloatingActionButton.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
524
```javascript /* @flow strict-local */ import React from 'react'; import type { Node, ElementConfig } from 'react'; import { TouchableHighlight, TouchableNativeFeedback, Platform, View } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import { HIGHLIGHT_COLOR } from '../styles'; type Props = $ReadOnly<{| accessibilityLabel?: string, style?: ViewStyleProp, hitSlop?: ElementConfig<typeof View>['hitSlop'], children: Node, onPress?: () => void | Promise<void>, onLongPress?: () => void, |}>; /** * Make a child component respond properly to touches, on both platforms. * * Most of the work is done by components from upstream; details linked * below. Our `Touchable` serves mainly as an adapter to give them a * uniform interface. * * Useful facts about layout and behavior: * * * The result of `render` looks like this: * (touchable area,) * (with `style` ) -> (child) * * * The touchable area is a wrapper `View`, which is both the touch target * and the area that will show feedback. Its layout is controlled by the * given `style` prop. * * * In the `TouchableHighlight` case (used on iOS), the child component * is a clone of the one passed as `children`, but with `style.opacity` * adjusted when highlighted. (In the `TouchableNativeFeedback` case, * the child component is `children` verbatim.) * * For a few additional details, see upstream docs: * path_to_url * path_to_url * For much more detail, see `Touchable.js` in RN upstream, and its copious * jsdoc (which isn't rendered on the web, unfortunately.) * * @prop [style] - Style for the touch target / feedback area. * @prop [children] - A single component (not zero, or more than one.) * @prop [onPress] - Passed through; see upstream docs. * @prop [onLongPress] - Passed through; see upstream docs. * @prop [accessibilityLabel] - Passed through; see upstream docs. * @prop [hitSlop] - Passed through; see upstream docs. */ // TODO(?): Use Pressable API: path_to_url export default function Touchable(props: Props): Node { const { accessibilityLabel, style, onPress, onLongPress, hitSlop } = props; const child: Node = React.Children.only(props.children); if (!onPress && !onLongPress) { return ( <View accessible={!!accessibilityLabel} accessibilityLabel={accessibilityLabel} style={style} hitSlop={hitSlop} > {child} </View> ); } if (Platform.OS === 'ios') { // TouchableHighlight makes its own wrapper View to be the touch // target, passing the `style` prop through. return ( <TouchableHighlight accessibilityLabel={accessibilityLabel} underlayColor={HIGHLIGHT_COLOR} style={style} onPress={onPress} onLongPress={onLongPress} hitSlop={hitSlop} > {child} </TouchableHighlight> ); } // TouchableNativeFeedback doesn't create any wrapper component -- it // returns a clone of the child it's given, with added props to make it // a touch target. We make our own wrapper View, in order to provide // the same interface as we do with TouchableHighlight. return ( <TouchableNativeFeedback accessibilityLabel={accessibilityLabel} background={TouchableNativeFeedback.Ripple(HIGHLIGHT_COLOR, false)} onPress={onPress} onLongPress={onLongPress} hitSlop={hitSlop} > <View style={style}>{child}</View> </TouchableNativeFeedback> ); } ```
/content/code_sandbox/src/common/Touchable.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
871
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import LoadingIndicator from './LoadingIndicator'; import ZulipStatusBar from './ZulipStatusBar'; const componentStyles = createStyleSheet({ center: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: BRAND_COLOR, }, }); type Props = $ReadOnly<{||}>; /** * Meant to be used to cover the whole screen. */ export default function FullScreenLoading(props: Props): Node { return ( <> <ZulipStatusBar backgroundColor={BRAND_COLOR} /> { // No need for `OfflineNoticePlaceholder` here: the content, a // loading indicator centered on the whole screen, isn't near the // top of the screen, so it doesn't need protection from being // hidden under the offline notice. } <View style={componentStyles.center}> <LoadingIndicator color="black" size={80} showLogo /> </View> </> ); } ```
/content/code_sandbox/src/common/FullScreenLoading.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
247
```javascript /* @flow strict-local */ import React, { useRef, useState, useCallback } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import Input from './Input'; import type { Props as InputProps } from './Input'; import styles, { createStyleSheet, BRAND_COLOR } from '../styles'; import { Icon } from './Icons'; const componentStyles = createStyleSheet({ clearButtonIcon: { color: BRAND_COLOR, paddingRight: 16, }, }); type Props = $ReadOnly<$Diff<InputProps, {| textInputRef: mixed, value: mixed, _: mixed |}>>; /** * A component wrapping Input and providing an 'X' button * to clear the entered text. * * All props are passed through to `Input`. See `Input` for descriptions. */ export default function InputWithClearButton(props: Props): Node { const { onChangeText } = props; const [text, setText] = useState<string>(''); // We should replace the fixme with // `React$ElementRef<typeof TextInput>` when we can. Currently, that // would make `.current` be `any(implicit)`, which we don't want; // this is probably down to bugs in Flow's special support for React. const textInputRef = useRef<$FlowFixMe>(); const handleChangeText = useCallback( (_text: string) => { setText(_text); if (onChangeText) { onChangeText(_text); } }, [onChangeText], ); const handleClear = useCallback(() => { handleChangeText(''); if (textInputRef.current) { // `.current` is not type-checked; see definition. textInputRef.current.clear(); } }, [handleChangeText]); return ( <View style={styles.row}> <Input {...props} textInputRef={textInputRef} onChangeText={handleChangeText} value={text} /> {text.length > 0 && ( <Icon name="x" size={24} onPress={handleClear} style={componentStyles.clearButtonIcon} /> )} </View> ); } ```
/content/code_sandbox/src/common/InputWithClearButton.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
453
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import styles, { createStyleSheet } from '../styles'; const componentStyles = createStyleSheet({ centerer: { flex: 1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', }, inner: { width: '100%', maxWidth: 480, }, }); type Props = $ReadOnly<{| style?: ViewStyleProp, children: Node, padding: boolean, |}>; /** * A layout component that centers wrapped components * horizontally and vertically. * * @prop [style] - Apply styles to wrapper component. * @prop children - Components to be centered. * @prop [padding] - Specifies if the components should be padded. */ // TODO: Remove this component. Callers should be more transparent about // what they want, especially if that includes setting things unrelated to // centering, like `maxWidth: 480`. export default class Centerer extends PureComponent<Props> { static defaultProps: {| padding: boolean |} = { padding: false, }; render(): Node { const { children, padding, style } = this.props; return ( <View style={[componentStyles.centerer, padding && styles.padding, style]}> <View style={componentStyles.inner}>{children}</View> </View> ); } } ```
/content/code_sandbox/src/common/Centerer.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 React from 'react'; import type { Node } from 'react'; import { Image } from 'react-native'; import AnimatedRotateComponent from '../animation/AnimatedRotateComponent'; import spinningProgressImg from '../../static/img/spinning-progress.png'; import spinningProgressBlackImg from '../../static/img/spinning-progress-black.png'; import spinningProgressWhiteImg from '../../static/img/spinning-progress-white.png'; type Props = $ReadOnly<{| color: 'default' | 'black' | 'white', size: number, |}>; /** * Renders a progress indicator - light circle and a darker * quarter of a circle overlapping it, spinning. * * This is a temporary replacement of the ART-based SpinningProgress. * * @prop color - The color of the circle. * @prop size - Diameter of the circle in pixels. */ export default function SpinningProgress(props: Props): Node { const { color, size } = props; const style = { width: size, height: size }; const source = (() => { switch (color) { case 'white': return spinningProgressWhiteImg; case 'black': return spinningProgressBlackImg; default: return spinningProgressImg; } })(); return ( <AnimatedRotateComponent> <Image style={style} source={source} resizeMode="contain" /> </AnimatedRotateComponent> ); } ```
/content/code_sandbox/src/common/SpinningProgress.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
298
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Text, View } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import { foregroundColorFromBackground } from '../utils/color'; const styles = createStyleSheet({ frame: { paddingTop: 2, paddingRight: 4, paddingBottom: 2, paddingLeft: 4, backgroundColor: BRAND_COLOR, justifyContent: 'center', alignItems: 'center', }, text: { color: 'white', fontSize: 12, }, frameInverse: { backgroundColor: 'white', }, textInverse: { color: BRAND_COLOR, }, frameMuted: { opacity: 0.5, }, }); type Props = $ReadOnly<{| style?: ViewStyleProp, color?: string, count?: number, inverse?: boolean, |}>; /** * Unified way to display unread counts. * * @prop [style] - Style object for additional customization. * @prop [color] - Background color. * @prop [count] - Numerical value for the unread count. * @prop [inverse] - Indicate if styling should be inverted (dark on light). */ export default function UnreadCount(props: Props): Node { const { style, isMuted = false, borderRadius = 2, color = BRAND_COLOR, count = 0, inverse = false, limited = false, } = props; if (!count) { return null; } const frameStyle = [ styles.frame, inverse && styles.frameInverse, isMuted && styles.frameMuted, { borderRadius }, { backgroundColor: color }, style, ]; const textColor = foregroundColorFromBackground(color); const textStyle = [styles.text, inverse && styles.textInverse, { color: textColor }]; const countString = limited && count >= 100 ? '99+' : count.toString(); return ( <View style={frameStyle}> <Text style={textStyle} numberOfLines={1}> {countString} </Text> </View> ); } ```
/content/code_sandbox/src/common/UnreadCount.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 from 'react'; import type { Node } from 'react'; import { FormattedMessage } from 'react-intl'; import type { BoundedDiff } from '../generics'; import ZulipText from './ZulipText'; import type { LocalizableReactText } from '../types'; type Props = $ReadOnly<{| ...BoundedDiff<$Exact<React$ElementConfig<typeof ZulipText>>, {| +children: ?Node |}>, text: LocalizableReactText, |}>; /** * A wrapper for `ZulipText` that translates the text with react-intl * * Use `ZulipText` instead if you don't want the text translated. * * Unlike `ZulipText`, only accepts a `LocalizableReactText`, as the `text` * prop, and doesn't support `children`. */ export default function ZulipTextIntl(props: Props): Node { const { text, ...restProps } = props; const message = typeof text === 'object' ? text.text : text; const values = typeof text === 'object' ? text.values : undefined; return ( <ZulipText {...restProps}> <FormattedMessage id={message} // If you see this in dev, it means there's a user-facing string // that hasn't been added to // static/translations/messages_en.json. Please add it! :) defaultMessage={ process.env.NODE_ENV === 'development' ? `UNTRANSLATED${message}UNTRANSLATED` : message } values={values} /> </ZulipText> ); } ```
/content/code_sandbox/src/common/ZulipTextIntl.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
357
```javascript /* @flow strict-local */ import React, { useMemo } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { LocalizableReactText } from '../types'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import ZulipTextIntl from './ZulipTextIntl'; import Touchable from './Touchable'; // When adding a variant, take care that it's legitimate, it addresses a // common use case consistently, and its styles are defined coherently. We // don't want this component to grow brittle with lots of little flags to // micromanage its styles. type Variant = 'standard'; const styleSheetForVariant = (variant: Variant) => createStyleSheet({ // See path_to_url#specs. touchable: { height: 36, paddingHorizontal: 8, minWidth: 64, }, // Chosen because of the value for this distance at // path_to_url#specs. A banner is one context // where we've wanted to use text buttons. leftMargin: { marginLeft: 8, }, rightMargin: { marginRight: 8, }, // `Touchable` only accepts one child, so make sure it fills the // `Touchable`'s full area and centers everything in it. childOfTouchable: { flex: 1, alignItems: 'center', justifyContent: 'center', }, text: { // From the spec: // > Text labels need to be distinct from other elements. If the text // > label isnt fully capitalized, it should use a different color, // > style, or layout from other text. textTransform: 'uppercase', color: BRAND_COLOR, textAlign: 'center', textAlignVertical: 'center', }, }); type Props = $ReadOnly<{| /** See note on the `Variant` type. */ variant?: Variant, /** * Give a left margin of the correct in-between space for a set of buttons */ leftMargin?: true, /** * Give a right margin of the correct in-between space for a set of * buttons */ rightMargin?: true, /** * The text label: path_to_url#text-button * * Should be short. */ label: LocalizableReactText, onPress: () => void | Promise<void>, |}>; /** * A button modeled on Material Design's "text button" concept. * * See path_to_url#text-button : * * > Text buttons are typically used for less-pronounced actions, including * > those located * > * > - In dialogs * > - In cards * > * > In cards, text buttons help maintain an emphasis on card content. */ // TODO: Consider making this a thin wrapper around something like // react-native-paper's `Button` // (path_to_url encoding // things like project-specific styles and making any sensible adjustments // to the interface. export default function ZulipTextButton(props: Props): Node { const { variant = 'standard', leftMargin, rightMargin, label, onPress } = props; const variantStyles = useMemo(() => styleSheetForVariant(variant), [variant]); return ( <Touchable style={[ variantStyles.touchable, leftMargin && variantStyles.leftMargin, rightMargin && variantStyles.rightMargin, ]} onPress={onPress} > <View style={variantStyles.childOfTouchable}> <ZulipTextIntl style={variantStyles.text} text={label} /> </View> </Touchable> ); } ```
/content/code_sandbox/src/common/ZulipTextButton.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
789
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import { createStyleSheet, ThemeContext } from '../styles'; import { useSelector } from '../react-redux'; import { getPresenceStatusForUserId } from '../presence/presenceModel'; import { ensureUnreachable } from '../types'; import type { UserId } from '../types'; const styles = createStyleSheet({ common: { width: 12, height: 12, borderRadius: 6, }, maybeOpaqueBackgroundWrapper: { alignItems: 'center', justifyContent: 'center', }, opaqueBackground: { width: 15, height: 15, borderRadius: 7.5, }, active: { backgroundColor: 'hsl(106, 74%, 44%)', }, idleWrapper: { borderWidth: 2, borderColor: 'hsl(39, 100%, 50%)', }, idleHalfCircle: { backgroundColor: 'hsl(39, 100%, 50%)', width: 8, height: 4, marginTop: 4, borderTopLeftRadius: 0, borderTopRightRadius: 0, borderBottomLeftRadius: 4, borderBottomRightRadius: 4, }, offline: { backgroundColor: 'gray', }, unavailableWrapper: { borderColor: 'gray', borderWidth: 1.5, }, unavailableLine: { backgroundColor: 'gray', marginVertical: 3.5, marginHorizontal: 1.5, height: 2, }, }); function MaybeOpaqueBackgroundWrapper( props: $ReadOnly<{| useOpaqueBackground: boolean, style?: ViewStyleProp, children: Node, |}>, ) { const { useOpaqueBackground, style, children } = props; const { backgroundColor } = useContext(ThemeContext); return ( <View style={[ styles.maybeOpaqueBackgroundWrapper, useOpaqueBackground ? styles.opaqueBackground : undefined, useOpaqueBackground ? { backgroundColor } : undefined, style, ]} > {children} </View> ); } function PresenceStatusIndicatorActive() { return <View style={[styles.active, styles.common]} />; } function PresenceStatusIndicatorIdle() { return ( <View style={[styles.idleWrapper, styles.common]}> <View style={styles.idleHalfCircle} /> </View> ); } function PresenceStatusIndicatorOffline() { return <View style={[styles.offline, styles.common]} />; } // TODO(server-6.0): Remove; this status was made obsolete in FL 148. function PresenceStatusIndicatorUnavailable() { return ( <View style={[styles.unavailableWrapper, styles.common]}> <View style={styles.unavailableLine} /> </View> ); } type Props = $ReadOnly<{| style?: ViewStyleProp, userId: UserId, hideIfOffline: boolean, useOpaqueBackground: boolean, |}>; /** * A colored dot indicating user online status. * * green if 'online' * * orange if 'idle' * * gray if 'offline' * * @prop [style] - Style object for additional customization. * @prop email - email of the user whose status we are showing. * @prop hideIfOffline - Do not render for 'offline' state. */ export default function PresenceStatusIndicator(props: Props): Node { const { userId, style, hideIfOffline, useOpaqueBackground } = props; const status = useSelector(state => getPresenceStatusForUserId(state, userId)); if (status === null || (hideIfOffline && status === 'offline')) { return null; } switch (status) { case 'active': return ( <MaybeOpaqueBackgroundWrapper style={style} useOpaqueBackground={useOpaqueBackground}> <PresenceStatusIndicatorActive /> </MaybeOpaqueBackgroundWrapper> ); case 'idle': return ( <MaybeOpaqueBackgroundWrapper style={style} useOpaqueBackground={useOpaqueBackground}> <PresenceStatusIndicatorIdle /> </MaybeOpaqueBackgroundWrapper> ); case 'offline': return ( <MaybeOpaqueBackgroundWrapper style={style} useOpaqueBackground={useOpaqueBackground}> <PresenceStatusIndicatorOffline /> </MaybeOpaqueBackgroundWrapper> ); case 'unavailable': return ( <MaybeOpaqueBackgroundWrapper style={style} useOpaqueBackground={useOpaqueBackground}> <PresenceStatusIndicatorUnavailable /> </MaybeOpaqueBackgroundWrapper> ); default: ensureUnreachable(status); return null; } } ```
/content/code_sandbox/src/common/PresenceStatusIndicator.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,025
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import subWeeks from 'date-fns/subWeeks'; import ZulipBanner from './ZulipBanner'; import { useSelector, useDispatch } from '../react-redux'; import { getAccount, getSilenceServerPushSetupWarnings } from '../account/accountsSelectors'; import { getRealm } from '../directSelectors'; import { getRealmName } from '../selectors'; import { dismissServerPushSetupNotice } from '../account/accountActions'; import { NotificationProblem, notifProblemShortReactText, } from '../settings/NotifTroubleshootingScreen'; import type { AppNavigationMethods } from '../nav/AppNavigator'; import { useDateRefreshedAtInterval } from '../reactUtils'; type Props = $ReadOnly<{| navigation: AppNavigationMethods, |}>; /** * A "nag banner" saying the server hasn't enabled push notifications, if so * * Offers a dismiss button. If this notice is dismissed, it sleeps for two * weeks, then reappears if the server hasn't gotten set up for push * notifications in that time. ("This notice" means the currently applicable * notice. If the server does get setup for push notifications, then gets * un-setup, a new notice will apply.) */ export default function ServerNotifsDisabledBanner(props: Props): Node { const { navigation } = props; const dispatch = useDispatch(); const lastDismissedServerPushSetupNotice = useSelector( state => getAccount(state).lastDismissedServerPushSetupNotice, ); const pushNotificationsEnabled = useSelector(state => getRealm(state).pushNotificationsEnabled); const silenceServerPushSetupWarnings = useSelector(getSilenceServerPushSetupWarnings); const realmName = useSelector(getRealmName); const dateNow = useDateRefreshedAtInterval(60_000); let visible = false; let text = ''; if (pushNotificationsEnabled) { // don't show } else if (silenceServerPushSetupWarnings) { // don't show } else if ( lastDismissedServerPushSetupNotice !== null && lastDismissedServerPushSetupNotice >= subWeeks(dateNow, 2) ) { // don't show } else { visible = true; text = notifProblemShortReactText(NotificationProblem.ServerHasNotEnabled, realmName); } const buttons = []; buttons.push({ id: 'dismiss', label: 'Dismiss', onPress: () => { dispatch(dismissServerPushSetupNotice()); }, }); buttons.push({ id: 'learn-more', label: 'Learn more', onPress: () => { dispatch(dismissServerPushSetupNotice()); navigation.push('notifications'); }, }); return <ZulipBanner visible={visible} text={text} buttons={buttons} />; } ```
/content/code_sandbox/src/common/ServerNotifsDisabledBanner.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
618
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { useSelector } from '../react-redux'; import UserAvatar from './UserAvatar'; import { getOwnUser } from '../users/userSelectors'; type Props = $ReadOnly<{| size: number, |}>; /** * Renders an image of the current user's avatar * * @prop size - Sets width and height in logical pixels. */ export default function OwnAvatar(props: Props): Node { const { size } = props; const user = useSelector(getOwnUser); return <UserAvatar avatarUrl={user.avatar_url} size={size} />; } ```
/content/code_sandbox/src/common/OwnAvatar.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
139
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import Color from 'color'; import * as React from 'react'; import { View } from 'react-native'; import invariant from 'invariant'; import { useGlobalSelector } from '../react-redux'; import { getGlobalSettings } from '../directSelectors'; import type { LocalizableText, LocalizableReactText } from '../types'; import { showErrorAlert } from '../utils/info'; import { TranslationContext } from '../boot/TranslationProvider'; import ZulipTextIntl from './ZulipTextIntl'; import Touchable from './Touchable'; import type { SpecificIconType } from './Icons'; import { ThemeContext, createStyleSheet } from '../styles'; type Props = $ReadOnly<{| icon?: {| +Component: SpecificIconType, +color?: string, |}, title: LocalizableReactText, subtitle?: LocalizableReactText, onPress?: () => void | Promise<void>, disabled?: | {| +title: LocalizableText, +message?: LocalizableText, +learnMoreButton?: {| +url: URL, +text?: LocalizableText, |}, |} | false, |}>; /** * A row with a title, and optional icon, subtitle, and press handler. * * See also NavRow, SwitchRow, etc. */ export default function TextRow(props: Props): React.Node { const { title, subtitle, onPress, icon, disabled } = props; const globalSettings = useGlobalSelector(getGlobalSettings); const _ = React.useContext(TranslationContext); const themeContext = React.useContext(ThemeContext); const fadeColorIfDisabled = React.useCallback( (color: string) => typeof disabled === 'object' ? (Color(color).fade(0.5).toString(): string) : color, [disabled], ); const styles = React.useMemo( () => createStyleSheet({ container: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8, paddingHorizontal: 16, // Minimum touch target height (and width): // path_to_url#layout-and-typography minHeight: 48, }, icon: { textAlign: 'center', marginRight: 8, color: fadeColorIfDisabled(icon?.color ?? themeContext.color), }, textWrapper: { flex: 1, }, title: { color: fadeColorIfDisabled(themeContext.color), }, subtitle: { fontWeight: '300', fontSize: 13, color: fadeColorIfDisabled(themeContext.color), }, }), [themeContext, icon, fadeColorIfDisabled], ); const content = ( <View style={styles.container}> {!!icon && <icon.Component size={24} style={styles.icon} />} <View style={styles.textWrapper}> <ZulipTextIntl style={styles.title} text={title} /> {subtitle !== undefined && <ZulipTextIntl style={styles.subtitle} text={subtitle} />} </View> </View> ); const hasTouchResponse = onPress != null || typeof disabled === 'object'; const effectiveOnPress = React.useCallback(() => { invariant( hasTouchResponse, 'effectiveOnPress should only be called when hasTouchResponse is true', ); if (disabled) { const { title, message, learnMoreButton } = disabled; // eslint-disable-line no-shadow showErrorAlert( _(title), message != null ? _(message) : undefined, learnMoreButton && { url: learnMoreButton.url, text: learnMoreButton.text != null ? _(learnMoreButton.text) : undefined, globalSettings, }, ); return; } invariant(onPress != null, 'onPress should be true because hasTouchResponse is true'); onPress(); }, [_, disabled, globalSettings, onPress, hasTouchResponse]); return hasTouchResponse ? <Touchable onPress={effectiveOnPress}>{content}</Touchable> : content; } ```
/content/code_sandbox/src/common/TextRow.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
886
```javascript /* @flow strict-local */ import React, { useCallback, useRef, useMemo, useEffect, useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import invariant from 'invariant'; import { CommonActions } from '@react-navigation/native'; import type { LocalizableText } from '../types'; import type { GlobalParamList } from '../nav/globalTypes'; import { randString } from '../utils/misc'; import { createStyleSheet } from '../styles'; import Touchable from './Touchable'; import ZulipTextIntl from './ZulipTextIntl'; import { IconRight } from './Icons'; import type { AppNavigationMethods } from '../nav/AppNavigator'; import { ThemeContext } from '../styles/theme'; import type { SpecificIconType } from './Icons'; type Item<TKey> = $ReadOnly<{| key: TKey, title: LocalizableText, subtitle?: LocalizableText, disabled?: | {| +title: LocalizableText, +message?: LocalizableText, +learnMoreButton?: {| +url: URL, +text?: LocalizableText, |}, |} | false, |}>; type Props<TItemKey> = $ReadOnly<{| icon?: {| +Component: SpecificIconType, +color?: string, |}, /** * Component must be under the stack nav with the selectable-options screen. * * Pass this down from props or `useNavigation`. */ navigation: AppNavigationMethods, /** What the setting is about, e.g., "Theme". */ label: LocalizableText, /** What the setting is about, in a short sentence or two. */ description?: LocalizableText, /** The current value of the input. */ valueKey: TItemKey, /** * The available options to choose from, with unique `key`s, one of which * must be `valueKey`. */ items: $ReadOnlyArray<Item<TItemKey>>, onValueChange: (newValue: TItemKey) => void, /** * Whether to offer a search bar at the top for filtering. * * The query is checked against items' `title` and `subtitle`. */ search?: boolean, |}>; /** * An input row for the user to make a choice, radio-button style. * * Shows the current value (the selected item), represented as the item's * `.title`. When tapped, opens the selectable-options screen, where the * user can change the selection or read more about each selection. */ // This has the navigate-to-nested-screen semantics of // <NavRow type="nested" />, represented by IconRight. NavRow would // probably be the wrong abstraction, though, because it isn't an input // component; it doesn't have a value to display. export default function InputRowRadioButtons<TItemKey: string | number>( props: Props<TItemKey>, ): Node { const { navigation, label, description, valueKey, items, onValueChange, search, icon } = props; const screenKey: string = useRef(`selectable-options-${randString()}`).current; const selectedItem = items.find(c => c.key === valueKey); invariant(selectedItem != null, 'InputRowRadioButtons: exactly one choice must be selected'); const screenParams = useMemo( () => ({ title: label, description, items: items.map(({ key, title, subtitle, disabled }) => ({ key, title, subtitle, disabled, selected: key === valueKey, })), onRequestSelectionChange: (itemKey, requestedValue) => { if (!requestedValue || itemKey === valueKey) { // Can't unselect a radio button. return; } navigation.goBack(); onValueChange(itemKey); }, search, }), [navigation, label, description, items, valueKey, onValueChange, search], ); const handleRowPressed = useCallback(() => { // Normally we'd use `.push`, to avoid `.navigate`'s funky // rewind-history behavior. But `.push` doesn't accept a custom key, so // we use `.navigate`. This is fine because the funky rewind-history // behavior can't happen here; see // path_to_url#discussion_r868799934 navigation.navigate({ name: 'selectable-options', key: screenKey, params: (screenParams: GlobalParamList['selectable-options']), }); }, [navigation, screenKey, screenParams]); // Live-update the selectable-options screen. useEffect(() => { navigation.dispatch(state => /* eslint-disable operator-linebreak */ state.routes.find(route => route.key === screenKey) ? { ...CommonActions.setParams(screenParams), source: screenKey } : // A screen with key `screenKey` isn't currently mounted on the // navigator. Don't refer to such a screen; that would be an // error. CommonActions.reset(state), ); }, [navigation, screenParams, screenKey]); // The desired height for IconRight, which we'll pass for its `size` prop. // It'll also be its width. const kRightArrowIconSize = 24; const themeData = useContext(ThemeContext); const styles = useMemo( () => createStyleSheet({ wrapper: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8, paddingHorizontal: 16, // Minimum touch target height (and width): // path_to_url#layout-and-typography minHeight: 48, }, iconFromProps: { textAlign: 'center', marginRight: 8, color: icon?.color ?? themeData.color, }, textWrapper: { flex: 1, flexDirection: 'column', }, valueTitle: { fontWeight: '300', fontSize: 13, }, iconRightWrapper: { height: kRightArrowIconSize, // IconRight is a square, so width equals height and this is the // right amount of width to reserve. width: kRightArrowIconSize, }, }), [themeData, icon], ); return ( <Touchable onPress={handleRowPressed}> <View style={styles.wrapper}> {!!icon && <icon.Component size={24} style={styles.iconFromProps} />} <View style={styles.textWrapper}> <ZulipTextIntl text={label} /> <ZulipTextIntl text={selectedItem.title} style={styles.valueTitle} /> </View> <View style={styles.iconRightWrapper}> <IconRight size={kRightArrowIconSize} color={themeData.color} /> </View> </View> </Touchable> ); } ```
/content/code_sandbox/src/common/InputRowRadioButtons.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,486
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { ThemeContext, createStyleSheet } from '../styles'; import ZulipTextIntl from './ZulipTextIntl'; import type { LocalizableReactText } from '../types'; const styles = createStyleSheet({ header: { padding: 10, backgroundColor: 'hsla(0, 0%, 50%, 0.75)', }, }); type Props = $ReadOnly<{| text: LocalizableReactText, |}>; export default function SectionHeader(props: Props): Node { const { text } = props; const themeData = useContext(ThemeContext); return ( <View style={[styles.header, { backgroundColor: themeData.backgroundColor }]}> <ZulipTextIntl text={text} /> </View> ); } ```
/content/code_sandbox/src/common/SectionHeader.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
197
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import ZulipTextIntl from './ZulipTextIntl'; import { createStyleSheet } from '../styles'; const styles = createStyleSheet({ container: { flex: 1, padding: 16, marginTop: 8, justifyContent: 'center', }, text: { fontSize: 18, textAlign: 'center', }, }); type Props = $ReadOnly<{| text: string, |}>; export default function SearchEmptyState(props: Props): Node { const { text } = props; return ( <View style={styles.container}> <ZulipTextIntl style={styles.text} text={text} /> </View> ); } ```
/content/code_sandbox/src/common/SearchEmptyState.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
179
```javascript /* @flow strict-local */ import React, { useContext, useMemo } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { useGlobalSelector } from '../react-redux'; import type { LocalizableText } from '../types'; import ZulipTextIntl from './ZulipTextIntl'; import Touchable from './Touchable'; import { BRAND_COLOR, createStyleSheet, HALF_COLOR, ThemeContext } from '../styles'; import { IconDone } from './Icons'; import { showErrorAlert } from '../utils/info'; import { TranslationContext } from '../boot/TranslationProvider'; import { getGlobalSettings } from '../directSelectors'; type Props<TItemKey: string | number> = $ReadOnly<{| // A key to uniquely identify the item. The function passed as // `onRequestSelectionChange` gets passed this. We would have just // called this `key` except that would collide with React's builtin // `key` attribute (which callers should also pass if they're in a // position that requires it). itemKey: TItemKey, title: LocalizableText, subtitle?: LocalizableText, disabled?: | {| +title: LocalizableText, +message?: LocalizableText, +learnMoreButton?: {| +url: URL, +text?: LocalizableText, |}, |} | false, selected: boolean, // We might have called this `onPress`, but // - pressing just happens to be how this component wants the user // to manually select/deselect // - callers don't have a license to do whatever they want here; see // note in jsdoc onRequestSelectionChange: (itemKey: TItemKey, requestedValue: boolean) => void, |}>; // The desired height of the checkmark icon, which we'll pass for its `size` // prop. It'll also be its width, since it's a square. const kCheckmarkSize = 24; /** * A labeled row for an item among related items; shows a checkmark * when selected. * * NOTE: This isn't an all-purpose action button. The component has * two essential states: selected and deselected. These must clearly * represent two states in the app; e.g., for each supported language, * it is either active or not. The event handler shouldn't do random * things that aren't related to that state, like navigating to a * different screen. */ export default function SelectableOptionRow<TItemKey: string | number>( props: Props<TItemKey>, ): Node { const { itemKey, title, subtitle, selected, onRequestSelectionChange, disabled = false } = props; const globalSettings = useGlobalSelector(getGlobalSettings); const _ = useContext(TranslationContext); const themeData = useContext(ThemeContext); const styles = useMemo( () => createStyleSheet({ textWrapper: { flex: 1, flexDirection: 'column', }, // Reserve a space for the checkmark so the layout (e.g., word // wrapping of the subtitle) doesn't change when `selected` changes. checkmarkWrapper: { height: kCheckmarkSize, // The checkmark icon is a square, so width equals height and this // is the right amount of width to reserve. width: kCheckmarkSize, }, title: { color: disabled ? HALF_COLOR : themeData.color, }, subtitle: { color: disabled ? HALF_COLOR : themeData.color, fontWeight: '300', fontSize: 13, }, wrapper: { flexDirection: 'row', alignItems: 'center', paddingTop: 12, paddingBottom: 12, paddingLeft: 16, paddingRight: 16, }, }), [disabled, themeData.color], ); return ( <Touchable onPress={() => { if (disabled) { const { title, message, learnMoreButton } = disabled; // eslint-disable-line no-shadow showErrorAlert( _(title), message != null ? _(message) : undefined, learnMoreButton && { url: learnMoreButton.url, text: learnMoreButton.text != null ? _(learnMoreButton.text) : undefined, globalSettings, }, ); return; } onRequestSelectionChange(itemKey, !selected); }} > <View style={styles.wrapper}> <View style={styles.textWrapper}> <ZulipTextIntl text={title} style={styles.title} /> {subtitle !== undefined && <ZulipTextIntl text={subtitle} style={styles.subtitle} />} </View> <View style={styles.checkmarkWrapper}> {selected && <IconDone size={kCheckmarkSize} color={BRAND_COLOR} />} </View> </View> </Touchable> ); } ```
/content/code_sandbox/src/common/SelectableOptionRow.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,071
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Image } from 'react-native'; import logoImg from '../../static/img/logo.png'; import { createStyleSheet } from '../styles'; const styles = createStyleSheet({ logo: { width: 40, height: 40, margin: 20, alignSelf: 'center', }, }); export default function Logo(): Node { return <Image style={styles.logo} source={logoImg} resizeMode="contain" />; } ```
/content/code_sandbox/src/common/Logo.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
114