text
stringlengths 9
39.2M
| dir
stringlengths 25
226
| lang
stringclasses 163
values | created_date
timestamp[s] | updated_date
timestamp[s] | repo_name
stringclasses 751
values | repo_full_name
stringclasses 752
values | star
int64 1.01k
183k
| len_tokens
int64 1
18.5M
|
|---|---|---|---|---|---|---|---|---|
```javascript
/* @flow strict-local */
import { NativeModules, Platform, Linking } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import OpenNotification from 'react-native-open-notification';
import type { BrowserPreference, GlobalSettingsState } from '../types';
const { ZLPConstants } = NativeModules;
/** Open a URL in the in-app browser. */
export function openLinkEmbedded(url: URL): void {
if (Platform.OS === 'ios') {
WebBrowser.openBrowserAsync(url.toString());
} else {
NativeModules.CustomTabsAndroid.openURL(url.toString());
}
}
/** Open a URL in the user's default browser app. */
export function openLinkExternal(url: URL): void {
Linking.openURL(url.toString());
}
export function shouldUseInAppBrowser(browser: BrowserPreference): boolean {
if (browser === 'default') {
return Platform.OS === 'android';
} else {
return browser === 'embedded';
}
}
/** Open a URL using whichever browser the user has configured in the Zulip settings. */
export function openLinkWithUserPreference(url: URL, settings: GlobalSettingsState): void {
if (shouldUseInAppBrowser(settings.browser)) {
openLinkEmbedded(url);
} else {
openLinkExternal(url);
}
}
export function openSystemNotificationSettings() {
if (Platform.OS === 'ios') {
Linking.openURL(
// Link directly to notification settings when iOS supports it
// (15.4+). Otherwise, link to the regular settings, and the user
// should get to notification settings with one tap from there.
ZLPConstants['UIApplication.openNotificationSettingsURLString'] // New name, iOS 16.0+
// TODO(ios-16.0): Remove use of old name
?? ZLPConstants.UIApplicationOpenNotificationSettingsURLString // Old name, iOS 15.4+
// TODO(ios-15.4): Remove fallback.
?? ZLPConstants['UIApplication.openSettingsURLString'],
);
} else {
// On iOS, react-native-open-notification doesn't support opening all
// the way to *notification* settings. It does support that on
// Android, so we use it here. The library is oddly named for one that
// opens notification settings; perhaps one day we'll replace it with
// our own code. But Greg points out that the implementation is small
// and reasonable:
// path_to_url#discussion_r1058039648
OpenNotification.open();
}
}
```
|
/content/code_sandbox/src/utils/openLink.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 541
|
```javascript
/* @flow strict-local */
import { ExtendableError } from './logging';
export class TimeoutError extends ExtendableError {}
/**
* Time-out a Promise after `timeLimitMs` has passed.
*
* Returns a new Promise that rejects with a TimeoutError if the
* passed `promise` doesn't settle (resolve/reject) within the time
* limit specified by `timeLimitMs`; otherwise, it settles the way
* `promise` does.
*/
export async function promiseTimeout<T>(promise: Promise<T>, timeLimitMs: number): Promise<T> {
return Promise.race([
promise,
new Promise((_, reject) => setTimeout(() => reject(new TimeoutError()), timeLimitMs)),
]);
}
/** Like setTimeout(..., 0), but returns a Promise of the result. */
export function delay<T>(callback: () => T): Promise<T> {
return new Promise(resolve => resolve()).then(callback);
}
export const sleep = (ms: number = 0): Promise<void> =>
new Promise(resolve => setTimeout(resolve, ms));
/**
* Makes a machine that can sleep for increasing durations, for network backoff.
*
* Call the constructor before a loop starts, and call .wait() in each iteration
* of the loop. Do not re-use the instance after exiting the loop.
*/
export class BackoffMachine {
_firstDuration: number;
_durationCeiling: number;
_base: number;
_startTime: number | void;
_waitsCompleted: number;
constructor() {
this._firstDuration = 100;
this._durationCeiling = 10 * 1000;
this._base = 2;
this._startTime = undefined;
this._waitsCompleted = 0;
}
/**
* How many waits have completed so far.
*
* Use this to implement "give up" logic by breaking out of the loop after a
* threshold number of waits.
*/
waitsCompleted(): number {
return this._waitsCompleted;
}
/**
* Promise to resolve after the appropriate duration.
*
* The popular exponential backoff strategy is to increase the duration
* exponentially with the number of sleeps completed, with a base of 2, until a
* ceiling is reached. E.g., if firstDuration is 100 and durationCeiling is 10 *
* 1000 = 10000, the sequence is
*
* 100, 200, 400, 800, 1600, 3200, 6400, 10000, 10000, 10000, ...
*
* Instead of using this strategy directly, we also apply "jitter". We use
* capped exponential backoff for the *upper bound* on a random duration, where
* the lower bound is always zero. Mitigating "bursts" is the goal of any
* "jitter" strategy, and the larger the range of randomness, the smoother the
* bursts. Keeping the lower bound at zero maximizes the range while preserving
* a capped exponential shape on the expected value. Greg discusses this in more
* detail in #3841.
*/
async wait(): Promise<void> {
if (this._startTime === undefined) {
this._startTime = Date.now();
}
const duration =
Math.random() // "Jitter"
* Math.min(
// Upper bound of random duration should not exceed durationCeiling
this._durationCeiling,
this._firstDuration * this._base ** this._waitsCompleted,
);
await sleep(duration);
this._waitsCompleted++;
}
}
```
|
/content/code_sandbox/src/utils/async.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 782
|
```javascript
/* @flow strict-local */
import { objectFromEntries } from '../jsBackport';
export const caseInsensitiveCompareFunc = (a: string, b: string): number =>
a.toLowerCase().localeCompare(b.toLowerCase());
export function deeperMerge<K, V>(
obj1: $ReadOnly<{| [K]: V |}>,
obj2: $ReadOnly<{| [K]: V |}>,
): {| [K]: V |} {
const mergedKeys = Array.from(new Set([...Object.keys(obj1), ...Object.keys(obj2)]));
return objectFromEntries(
mergedKeys.map(key =>
// Prettier bug on nested ternary
/* prettier-ignore */
[key,
obj1[key] === undefined
? obj2[key]
: obj2[key] === undefined
? obj1[key]
: { ...obj1[key], ...obj2[key] }],
),
);
}
export const isValidEmailFormat = (email: string = ''): boolean => /\S+@\S+\.\S+/.test(email);
/** Return an integer start <= N < end, roughly uniformly at random. */
export const randInt = (end: number, start: number = 0): number =>
Math.floor(Math.random() * (end - start) + start);
/** Return a string that's almost surely different every time. */
export const randString = (): string => randInt(2 ** 54).toString(36);
```
|
/content/code_sandbox/src/utils/misc.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 307
|
```javascript
// @flow strict-local
import { objectFromEntries } from '../jsBackport';
/**
* Return an object where each property value equals the key.
*
* This is a handy idiom for making objects that function like enums.
* For an example, see:
* path_to_url#toc-keymirror
*
* The main reason to use this helper rather than just write out the result
* directly is that it lets Flow infer a more specific type. For example:
*
* const Status1 = keyMirror({ on: null, off: null });
* Status1.on; // type is 'on'
*
* const Status2 = { on: 'on', off: 'off' };
* Status2.on; // type is string, which is less helpful
*/
export function keyMirror<O: { ... }>(o: O): $ObjMapi<O, <K>(K) => K> {
return objectFromEntries(Object.keys(o).map(k => [k, k]));
}
```
|
/content/code_sandbox/src/utils/keyMirror.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 { nativeApplicationVersion } from 'expo-application';
import { Platform } from 'react-native';
import { androidRelease } from '../reactNativeUtils';
const systemName =
// prettier-ignore
Platform.OS === 'ios'
// Probably "iOS" on all iOS devices we support (was "iPhone OS" long ago):
// path_to_url#L68
// path_to_url
? Platform.constants.systemName
: 'Android';
const systemVersion =
// prettier-ignore
Platform.OS === 'ios'
// E.g. "16.4" for iOS 16.4:
// path_to_url#L67
// path_to_url
? `${Platform.constants.osVersion}`
// (E.g. '13' for Android 13 Tiramisu)
: androidRelease();
export default `ZulipMobile/${
nativeApplicationVersion ?? '?.?.?'
} (${systemName} ${systemVersion})`;
```
|
/content/code_sandbox/src/utils/userAgent.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 216
|
```javascript
/* @flow strict-local */
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-use-before-define */
// $FlowFixMe[untyped-import]
import md5 from 'blueimp-md5';
import * as logging from './logging';
import { ensureUnreachable } from '../generics';
import { type UserId } from '../api/idTypes';
import { isUrlAbsolute, isUrlPathAbsolute } from './url';
/**
* Pixel dimensions of different size choices we have (they're all
* square) when requesting an uploaded avatar.
*/
// DEFAULT_AVATAR_SIZE in zerver/lib/upload.py.
export const DEFAULT_UPLOAD_SIZE_PX = 100;
// MEDIUM_AVATAR_SIZE in zerver/lib/upload.py.
export const MEDIUM_UPLOAD_SIZE_PX = 500;
/**
* A way to get a standard avatar URL, or a sized one if available
*
* This class is abstract. Only instantiate its subclasses.
*/
export class AvatarURL {
/**
* From info on a user or bot, make the right subclass instance.
*/
static fromUserOrBotData(args: {|
rawAvatarUrl: string | void | null,
userId: UserId,
email: string,
realm: URL,
|}): AvatarURL {
const { rawAvatarUrl, userId, email, realm } = args;
if (rawAvatarUrl === undefined) {
// New in Zulip 3.0, feature level 18, the field may be missing on
// user objects in the register response, at the server's discretion,
// if we announce the `user_avatar_url_field_optional` client
// capability, which we do. See `user_avatar_url_field_optional` at:
// path_to_url
//
// TODO(server-3.0): Simplify this comment.
return FallbackAvatarURL.validateAndConstructInstance({ realm, userId });
} else if (rawAvatarUrl === null) {
// If we announce `client_gravatar`, which we do, `rawAvatarUrl`
// might be null. In that case, we take responsibility for
// computing a hash for the user's email and using it to form a
// URL for an avatar served by Gravatar.
return GravatarURL.validateAndConstructInstance({ email });
} else if (typeof rawAvatarUrl === 'string') {
// If we don't announce `client_gravatar` (which we do), or if
// the server doesn't have EMAIL_ADDRESS_VISIBILITY_EVERYONE
// set, then `rawAvatarUrl` will be the absolute Gravatar URL
// string.
//
// (In the latter case, we won't have real email addresses with
// which to generate the correct hash; see
// path_to_url Implemented at
// `do_events_register` in zerver/lib/events.py on the server.)
if (
rawAvatarUrl.startsWith(
// Best not to use an expensive `new URL` call, when the
// following is equivalent (assuming `rawAvatarUrl` is also
// valid through its /pathname, ?query=params, and
// #fragment). The trailing slash ensures that we've
// examined the full origin in `rawAvatarUrl`.
`${GravatarURL.ORIGIN}/`,
)
) {
return GravatarURL.validateAndConstructInstance({ email, urlFromServer: rawAvatarUrl });
}
// Otherwise, it's a realm-uploaded avatar, either absolute or
// relative, depending on how uploads are stored.
return UploadedAvatarURL.validateAndConstructInstance({
realm,
absoluteOrRelativeUrl: rawAvatarUrl,
});
} else {
ensureUnreachable(rawAvatarUrl);
const msg = 'Unexpected value for `rawAvatarUrl` in `AvatarURL.fromUserOrBotData`';
logging.error(msg, { value: rawAvatarUrl });
throw new Error(msg);
}
}
get(sizePhysicalPx: number): URL {
throw new Error('unimplemented');
}
}
/**
* A Gravatar URL with a hash we compute from an email address.
*
* See path_to_url which covers
* the size options.
*/
export class GravatarURL extends AvatarURL {
/**
* Serialize to a special string; reversible with `deserialize`.
*/
static serialize(instance: GravatarURL): string {
return instance._standardUrl instanceof URL
? instance._standardUrl.toString()
: instance._standardUrl;
}
/**
* Use a special string from `serialize` to make a new instance.
*/
static deserialize(serialized: string): GravatarURL {
return new GravatarURL(serialized);
}
/**
* Construct from raw server data, or throw an error.
*
* Pass the Gravatar URL string from the server, if we've got it, to
* avoid doing an expensive `new URL` call.
*/
// We should avoid doing unnecessary `new URL` calls here. They are
// very expensive, and their use in these pseudo-constructors (which
// process data at the edge, just as it's received from the server)
// used to slow down `api.registerForEvents` quite a lot.
//
// In the past, we've been more conservative about validating a URL
// string that comes to us from the server at this point: we'd parse
// it with the URL constructor, grab the Gravatar hash from the
// result, and construct another URL with that hash and exactly the
// things we wanted it to have (like `d=identicon`).
//
// With some loss of validation, we've removed those two `new URL`
// calls in the path where the server provides a Gravatar URL
// string. Still, we should be able to trust that the server gives
// us properly formatted URLs; if it didn't, it seems like the kind
// of bug that would be fixed quickly.
static validateAndConstructInstance(args: {|
email: string,
urlFromServer?: string,
|}): GravatarURL {
const { email, urlFromServer } = args;
if (urlFromServer !== undefined) {
// This may not be *quite* the URL we would have generated
// ourselves. In the wild, I've seen one with a `version=1`, for
// example. But we trust the server to give us one that works,
// anyway -- and perhaps any extra things we get will be a good
// bonus.
return new GravatarURL(urlFromServer);
} else {
return new GravatarURL(
// Thankfully, this string concatenation is quite safe: we
// know enough about our inputs here to compose a properly
// formatted URL with them, without using `new URL`.
`${GravatarURL.ORIGIN}/avatar/${md5(email.toLowerCase())}?d=identicon`,
);
}
}
static ORIGIN: string = 'path_to_url
/**
* Standard URL from which to generate others. PRIVATE.
*
* May be a string if the instance was constructed at rehydrate
* time, when URL validation is unnecessary.
*/
_standardUrl: string | URL;
/**
* PRIVATE: Make an instance from already-validated data.
*
* Not part of the public interface; use the static methods instead.
*
* It's private because we need a path to constructing an instance
* without constructing URL objects, which takes more time than is
* acceptable when we can avoid it, e.g., during rehydration.
* Constructing URL objects is a necessary part of validating data
* from the server, but we only need to validate the data once, when
* it's first received.
*/
constructor(standardUrl: string | URL) {
super();
this._standardUrl = standardUrl;
}
/**
* Get a URL object for the given size.
*
* `sizePhysicalPx` must be an integer. (Gravatar doesn't advertise
* the ability to specify noninteger values for the size.)
*/
get(sizePhysicalPx: number): URL {
// `this._standardUrl` may have begun its life as a string, to
// avoid computing a URL object during rehydration
if (typeof this._standardUrl === 'string') {
this._standardUrl = new URL(this._standardUrl);
}
/* $FlowFixMe[incompatible-call]: Make a new URL to mutate
path_to_url#discussion_r512351202
*/
const result: URL = new URL(this._standardUrl);
result.searchParams.set('s', sizePhysicalPx.toString());
return result;
}
}
/**
* The /avatar/{user_id} redirect.
*
* See the point on `user_avatar_url_field_optional` at
* path_to_url
*
* Note that this endpoint needs authentication; we should send the
* auth headers (see src/api/transport) with the request.
*
* This endpoint isn't known to support size customization if the
* image at the redirect is a Gravatar image, but does support
* default/medium sizing if it's an uploaded image (see note on
* `UploadedAvatarURL`).
*/
export class FallbackAvatarURL extends AvatarURL {
/**
* Serialize to a special string; reversible with `deserialize`.
*/
static serialize(instance: FallbackAvatarURL): string {
return instance._standardUrl instanceof URL
? instance._standardUrl.toString()
: instance._standardUrl;
}
/**
* Use a special string from `serialize` to make a new instance.
*/
static deserialize(serialized: string): FallbackAvatarURL {
return new FallbackAvatarURL(serialized);
}
/**
* Construct from raw server data (the user ID), or throw an error.
*
* The `realm` must be already validated, e.g., by coming from the
* Redux state.
*/
// We should avoid doing unnecessary `new URL` calls here. They are
// very expensive, and their use in these pseudo-constructors (which
// process data at the edge, just as it's received from the server)
// used to slow down `api.registerForEvents` quite a lot.
static validateAndConstructInstance(args: {| realm: URL, userId: UserId |}): FallbackAvatarURL {
const { realm, userId } = args;
// Thankfully, this string concatenation is quite safe: we know
// enough about our inputs here to compose a properly formatted
// URL with them, without using `new URL`. (In particular,
// `realm.origin` doesn't have a trailing slash.)
return new FallbackAvatarURL(`${realm.origin}/avatar/${userId.toString()}`);
}
/**
* Standard URL from which to generate others. PRIVATE.
*
* May start out as a string, and will be converted to a URL object
* in the first `.get()` call.
*/
_standardUrl: string | URL;
/**
* PRIVATE: Make an instance from already-validated data.
*
* Not part of the public interface; use the static methods instead.
*/
constructor(standardUrl: string | URL) {
super();
this._standardUrl = standardUrl;
}
/**
* Get a URL object for the given size.
*
* Not known to support size customization if the image at the
* redirect is a Gravatar image, but does support default/medium
* sizing if it's an uploaded image (see note on
* `UploadedAvatarURL`).
*/
get(sizePhysicalPx: number): URL {
// `this._standardUrl` may have begun its life as a string, to
// avoid expensively calling the URL constructor
if (typeof this._standardUrl === 'string') {
this._standardUrl = new URL(this._standardUrl);
}
let result: URL = this._standardUrl;
if (sizePhysicalPx > DEFAULT_UPLOAD_SIZE_PX) {
/* $FlowFixMe[incompatible-call]: Make a new URL to mutate,
instead of mutating this._standardUrl
path_to_url#discussion_r512351202
*/
result = new URL(this._standardUrl);
result.pathname += '/medium';
}
return result;
}
}
/**
* An avatar that was uploaded to the Zulip server.
*
* There are two size options; if `sizePhysicalPx` is greater than
* DEFAULT_UPLOAD_SIZE_PX, medium is chosen:
* * default: DEFAULT_UPLOAD_SIZE_PX square
* * medium: MEDIUM_UPLOAD_SIZE_PX square
*
* Don't send auth headers with requests to this type of avatar URL.
* The s3 backend doesn't want them; it gives a 400 with an
* "Unsupported Authorization Type" message.
*/
export class UploadedAvatarURL extends AvatarURL {
/**
* Serialize to a special string; reversible with `deserialize`.
*/
static serialize(instance: UploadedAvatarURL): string {
return instance._standardUrl instanceof URL
? instance._standardUrl.toString()
: instance._standardUrl;
}
/**
* Use a special string from `serialize` to make a new instance.
*/
static deserialize(serialized: string): UploadedAvatarURL {
return new UploadedAvatarURL(serialized);
}
/**
* Construct from raw server data, or throw an error.
*
* Expects a relative, path-absolute URL plus the realm for a local
* upload; otherwise, an absolute URL of the avatar on the S3 backend.
*/
static validateAndConstructInstance(args: {|
realm: URL,
absoluteOrRelativeUrl: string,
|}): UploadedAvatarURL {
const { realm, absoluteOrRelativeUrl } = args;
// Ideally, we'd say `new URL(absoluteOrRelativeUrl, realm)`.
// The URL constructor is too expensive; but we can do an exact
// equivalent, given our assumptions on the kinds of URL strings
// the server will send.
let absoluteUrl = undefined;
if (isUrlAbsolute(absoluteOrRelativeUrl)) {
// An absolute URL string. Ignore the base URL.
absoluteUrl = absoluteOrRelativeUrl;
} else if (isUrlPathAbsolute(absoluteOrRelativeUrl)) {
// A path-absolute URL string, like `/avatar/`. We rely on our
// assumption that the realm URL equals its origin, modulo the latter
// having no trailing slash.
absoluteUrl = `${realm.origin}${absoluteOrRelativeUrl}`;
} else {
const msg = 'Unexpected form of avatar URL from server';
logging.error(msg, { avatarUrl: absoluteOrRelativeUrl });
throw new Error(msg);
}
return new UploadedAvatarURL(absoluteUrl);
}
/**
* Standard URL from which to generate others. PRIVATE.
*
* May start out as a string, and will be converted to a URL object
* in the first `.get()` call.
*/
_standardUrl: string | URL;
/**
* PRIVATE: Make an instance from already-validated data.
*
* Not part of the public interface; use the static methods instead.
*/
constructor(standardUrl: string | URL) {
super();
this._standardUrl = standardUrl;
}
/**
* Get a URL object for the given size.
*
* `sizePhysicalPx` should be an integer.
*/
get(sizePhysicalPx: number): URL {
// `this._standardUrl` may have begun its life as a string, to
// avoid expensively calling the URL constructor
if (typeof this._standardUrl === 'string') {
this._standardUrl = new URL(this._standardUrl);
}
let result: URL = this._standardUrl;
if (sizePhysicalPx > DEFAULT_UPLOAD_SIZE_PX) {
/* $FlowFixMe[incompatible-call]: Make a new URL to mutate,
instead of mutating this._standardUrl
path_to_url#discussion_r512351202
*/
result = new URL(this._standardUrl);
result.pathname = result.pathname.replace(
// `.png` is optional: s3 uploads don't use it, local ones do.
// See TODO in zulip/zulip@c03615b98.
/(?:\.png)?$/,
'-medium.png',
);
}
return result;
}
}
```
|
/content/code_sandbox/src/utils/avatar.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 3,549
|
```javascript
/* @flow strict-local */
/* eslint-disable no-underscore-dangle */
type VersionElements = {|
major: number | void,
minor: number | void,
patch: number | void,
flag: 'dev' | ['rc', number] | void,
numCommits: number | void,
commitId: string | void,
|};
/**
* Parsed form of a Zulip server version.
*
* Used on a Zulip version received from the server with /server_settings
* * to compare it to a threshold version where a feature was added on the
* server: use .isAtLeast
* * to report it to Sentry: use .raw for its raw form, and .elements
* for the data needed to make other tags to help with event
* aggregation.
*
* The ZulipVersion instance itself cannot be persisted in CompressedAsyncStorage or
* sent to Sentry because it isn't serializable. Instead, persist the raw
* version string.
*/
export class ZulipVersion {
_raw: string;
_comparisonArray: $ReadOnlyArray<number>;
_elements: VersionElements;
constructor(raw: string) {
this._raw = raw;
const elements = ZulipVersion._getElements(raw);
this._comparisonArray = ZulipVersion._getComparisonArray(elements);
this._elements = elements;
}
/**
* The raw version string that was passed to the constructor.
*/
raw(): string {
return this._raw;
}
toJSON(): string {
return this.raw();
}
/**
* Data to be sent to Sentry to help with event aggregation.
*/
elements(): VersionElements {
return this._elements;
}
/**
* True if this version is later than or equal to a given threshold.
*/
isAtLeast(otherZulipVersion: string | ZulipVersion): boolean {
const otherZulipVersionInstance =
otherZulipVersion instanceof ZulipVersion
? otherZulipVersion
: new ZulipVersion(otherZulipVersion);
const otherComparisonArray = otherZulipVersionInstance._comparisonArray;
const minLength = Math.min(this._comparisonArray.length, otherComparisonArray.length);
for (let i = 0; i < minLength; i++) {
if (this._comparisonArray[i] !== otherComparisonArray[i]) {
// We found a difference; the greater number wins.
return this._comparisonArray[i] > otherComparisonArray[i];
}
}
// It's a tie so far, and one of the arrays has ended. The array with
// further elements wins.
return this._comparisonArray.length >= otherComparisonArray.length;
}
/**
* This version, classified by release and by major release.
*/
classify(): {| raw: string, fine: string, coarse: string |} {
const OMITTED = 'x';
const UNKNOWN = '?';
const elements = this.elements();
const major = elements.major ?? UNKNOWN;
const minor = elements.minor ?? UNKNOWN;
const patch = elements.patch ?? UNKNOWN;
let coarse = undefined;
let fine = undefined;
// Effective with 3.0, we changed our numbering conventions; 3.x and
// 4.x are each the same level of granularity as 2.1.x or 2.0.x.
if (this.isAtLeast('3.0')) {
coarse = [major, OMITTED].join('.');
fine = [major, minor].join('.');
} else {
coarse = [major, minor, OMITTED].join('.');
fine = [major, minor, patch].join('.');
}
return { coarse, fine, raw: this.raw() };
}
/**
* Parse the raw string into a VersionElements.
*/
static _getElements(raw: string): VersionElements {
const result: VersionElements = {
major: undefined,
minor: undefined,
patch: undefined,
flag: undefined,
numCommits: undefined,
commitId: undefined,
};
let rest = raw;
const numbersMatch = /^(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(rest);
if (numbersMatch === null) {
return result;
}
result.major = parseInt(numbersMatch[1], 10);
result.minor = numbersMatch[2] !== undefined ? parseInt(numbersMatch[2], 10) : undefined;
result.patch = numbersMatch[3] !== undefined ? parseInt(numbersMatch[3], 10) : undefined;
rest = rest.slice(numbersMatch[0].length);
const flagMatch = /^-(?:(dev)|(?:(rc)(\d+)))/.exec(rest);
if (flagMatch !== null) {
if (flagMatch[1] === 'dev') {
result.flag = 'dev';
} else if (flagMatch[2] === 'rc') {
result.flag = ['rc', parseInt(flagMatch[3], 10)];
}
rest = rest.slice(flagMatch[0].length);
}
// Look for a suffix from git-describe.
const commitsMatch = /^-(\d+)-g([a-fA-F0-9]{4,40})/.exec(rest);
if (commitsMatch !== null) {
result.numCommits = parseInt(commitsMatch[1], 10);
result.commitId = commitsMatch[2];
}
return result;
}
/**
* Compute a $ReadOnlyArray<number> to be used in .isAtLeast comparisons.
*/
static _getComparisonArray(elements: VersionElements): $ReadOnlyArray<number> {
const { major, minor, patch, flag, numCommits } = elements;
const result: number[] = [];
// Push major, minor, and patch first, then trim trailing zeroes.
if (major !== undefined) {
result.push(major);
}
if (minor !== undefined) {
result.push(minor);
}
if (patch !== undefined) {
result.push(patch);
}
while (result[result.length - 1] === 0) {
result.pop();
}
// -dev < -rc1 < -rc2 < (final release)
if (flag === undefined) {
result.push(-1);
} else if (Array.isArray(flag) && flag[0] === 'rc') {
result.push(-2);
result.push(flag[1]);
} else if (flag === 'dev') {
result.push(-3);
}
// Break ties with numCommits.
if (numCommits !== undefined) {
result.push(numCommits);
}
return result;
}
}
```
|
/content/code_sandbox/src/utils/zulipVersion.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,453
|
```javascript
/* @flow strict-local */
import { Alert } from 'react-native';
import Toast from 'react-native-simple-toast';
import type { GlobalSettingsState, GetText, LocalizableText } from '../types';
import { openLinkWithUserPreference } from './openLink';
export const showToast = (message: string) => {
Toast.show(message);
};
type LearnMoreButton = {|
url: URL,
text?: string,
// Needed by openLinkWithUserPreference
globalSettings: GlobalSettingsState,
|};
const makeLearnMoreButton = learnMoreButton => {
const { url, text, globalSettings } = learnMoreButton;
return {
// TODO: Translate default text
text: text ?? 'Learn more',
onPress: () => {
openLinkWithUserPreference(url, globalSettings);
},
};
};
export const showErrorAlert = (
title: string,
message?: string,
learnMoreButton?: LearnMoreButton,
): void => {
const buttons = [];
if (learnMoreButton) {
buttons.push(makeLearnMoreButton(learnMoreButton));
}
buttons.push({
// TODO: translate
text: 'OK',
onPress: () => {},
});
Alert.alert(title, message, buttons, { cancelable: true });
};
export const showConfirmationDialog = (args: {|
+destructive?: true,
/**
* As in the web app, very brief, sentence case, no question mark
*
* E.g., "Delete topic".
*/
+title: LocalizableText,
+message: LocalizableText,
+learnMoreButton?: LearnMoreButton,
+onPressConfirm: () => void,
+onPressCancel?: () => void,
+_: GetText,
|}) => {
const { destructive, title, message, learnMoreButton, onPressConfirm, onPressCancel, _ } = args;
const buttons = [];
if (learnMoreButton) {
buttons.push(makeLearnMoreButton(learnMoreButton));
}
buttons.push(
{ text: _('Cancel'), style: 'cancel', onPress: onPressCancel },
{ text: _('Confirm'), style: destructive ? 'destructive' : 'default', onPress: onPressConfirm },
);
Alert.alert(_(title), _(message), buttons, { cancelable: true });
};
```
|
/content/code_sandbox/src/utils/info.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 498
|
```javascript
/* @flow strict-local */
import {
captureException,
captureMessage,
configureScope,
withScope as withScopeImpl,
} from '@sentry/react-native';
import type { ZulipVersion } from './zulipVersion';
import type { JSONable } from './jsonable';
import { objectEntries } from '../flowPonyfill';
import config from '../config';
/** Type of "extras" intended for Sentry. */
export type Extras = {| +[key: string]: JSONable |};
// TODO import from @sentry/react-native libdef
type Scope = $FlowFixMe;
type SeverityType = $FlowFixMe;
/**
* `Error`, but subclass instances have the name of the subclass at `.name`
*
* All of our custom error classes should extend this. For ones that don't,
* instances will have "Error" for their `.name`, instead of "TimeoutError",
* "NetworkError", etc. That's worse than useless because we could
* misidentify an error while debugging, based on the understandable but
* wrong assumption that our custom errors' names already correspond to the
* subclasses' names out of the box.
*/
// TODO: Add linting to make sure all our custom errors extend this
export class ExtendableError extends Error {
// Gotcha: Minification has been making this differ from what we see in
// our source code. Don't use in equality checks or user-facing text:
// path_to_url#javascript_compressors_and_minifiers
// However, we're trying Metro's `minifierConfig` to see if we can have it
// not minify classnames that end in Error.
//
// This will work even down a chain of subclasses, i.e.,
// MyVerySpecificError extends MySpecificError extends ExtendableError. If
// you call `new MyVerySpecificError()`, then `MyVerySpecificError`'s
// constructor will be the value of `this.constructor` here, so the
// instance gets the correct name.
name: typeof Error.name = this.constructor.name;
}
/** Wrapper for `Sentry.withScope`, allowing callbacks to return values. */
function withScope<R>(callback: Scope => R): R {
let ret: R;
withScopeImpl(scope => {
ret = callback(scope);
});
// Flow can't know that `ret` has actually been initialized
return ((ret: $FlowFixMe): R);
}
type ServerVersionTags = {|
rawServerVersion: string | void,
coarseServerVersion: string | void,
fineServerVersion: string | void,
|};
/**
* Get server-version tags at various levels of granularity.
*
* If the passed server version is falsy, all the tags will be
* `undefined`.
*/
const getServerVersionTags = (zulipVersion: ?ZulipVersion): ServerVersionTags => {
// Why might we not have the server version? If there's no active
// account. N.B: an account may be the active account but not
// logged in; see
// path_to_url#active-account.
if (!zulipVersion) {
return {
rawServerVersion: undefined,
coarseServerVersion: undefined,
fineServerVersion: undefined,
};
}
const { raw, fine, coarse } = zulipVersion.classify();
return { rawServerVersion: raw, coarseServerVersion: coarse, fineServerVersion: fine };
};
export function setTagsFromServerVersion(zulipVersion: ?ZulipVersion) {
configureScope(scope => {
// Set server version tags on Sentry's global scope, so
// all events will have them. See
// path_to_url
// for more about Sentry tags.
//
// If `zulipVersion` is falsy, all values in the object
// passed to `setTags` will be undefined. This means the
// tags will be removed from the scope, though this is
// unofficial as a way to remove tags:
// path_to_url#issue-534072956
scope.setTags(getServerVersionTags(zulipVersion));
});
}
/**
* Log an event (a string or Error) at some arbitrary severity.
*
* Returns a Sentry event_id, although this is not expected to be useful.
*/
const logToSentry = (event: string | Error, level: SeverityType, extras: Extras): string =>
withScope(scope => {
scope.setLevel(level);
scope.setExtras(extras);
if (event instanceof Error) {
return captureException(event, scope);
} else {
return captureMessage(event, scope);
}
});
type LogParams = {|
consoleMethod: mixed => void,
severity: SeverityType,
|};
type LogFunction = (event: string | Error, extras?: Extras) => void;
const makeLogFunction = ({ consoleMethod, severity }: LogParams): LogFunction => {
const toConsole = consoleMethod.bind(console);
return (event: string | Error, extras: Extras = {}) => {
logToSentry(event, severity, extras);
if (config.enableErrorConsoleLogging) {
toConsole(event);
const data = objectEntries(extras)
.map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)
.join('\n');
if (data) {
toConsole(data);
}
}
};
};
/* eslint-disable no-console */
// Notes on the behavior of `console.error`, `console.warn`, `console.log`:
//
// * When debugging JS: all display in the Chrome dev console, and not in
// the Android system log.
// * `error` and `warn` produce a nice expando-hidden stack trace, in
// addition to formatting their arguments.
// * `log` just formats the arguments.
// * An `Error` argument formats with its embedded stack trace. (As just
// text, with no spiffy expando.)
//
// * In a debug build, whether debugging JS or not:
// * `error` pops up the RN error red-screen.
// * `warn` could pop up an RN yellow-box, but we've set
// `console.disableYellowBox` so it doesn't.
//
// * On Android, on both debug and release builds, except when debugging JS:
// * All of `error`, `warn`, `log` go to the system log (for `adb logcat`).
// * An `Error` argument formats with (the name + message and) just the
// single source location where it was created, no stack trace.
/**
* Log an error at "error" severity.
*
* The error will be logged to Sentry and/or the console as appropriate.
*
* In a debug build, this pops up the RN error red-screen. This is
* appropriate when the condition should never happen and definitely
* represents a bug. For conditions that can happen without a bug (e.g. a
* failure to reach the server), consider `logging.warn`.
*
* See also:
* * `logging.warn` and `logging.info` for logging at lower severity
*
* @param event A string describing the nature of the event to be logged, or an
* exception whose `.message` is such a string. Related events should have
* identical such strings, when feasible.
* @param extras Diagnostic data which may differ between separate occurrences
* of the event.
*/
export const error: (event: string | Error, extras?: Extras) => void = makeLogFunction({
consoleMethod: console.error,
severity: 'error',
});
/**
* Log an event at "warning" severity.
*
* The event will be logged to Sentry and/or the console as appropriate.
*
* In the JS debugging console, this produces a yellow-highlighted warning,
* but no popup interruption. This makes it appropriate for conditions
* which have an inevitable background rate. For conditions which
* definitely represent a bug in the app, consider `logging.error` instead.
*
* See also:
* * `logging.error` for logging at higher severity
* * `logging.info` for logging at lower severity
*
* @param event A string describing the nature of the event to be logged, or an
* exception whose `.message` is such a string. Related events should have
* identical such strings, when feasible.
* @param extras Diagnostic data which may differ between separate occurrences
* of the event.
*/
export const warn: (event: string | Error, extras?: Extras) => void = makeLogFunction({
consoleMethod: console.warn,
severity: 'warning',
});
/**
* Log an event at "info" severity.
*
* The event will be logged to the console as appropriate.
*
* This will *not* log any information to Sentry. Consider also calling
* `Sentry.addBreadcrumb`.
*
* See also:
* * `logging.warn` and `logging.error` for logging at higher severity
*/
export const info = (event: string | Error | { ... }) => {
if (config.enableErrorConsoleLogging) {
console.log(event);
}
};
```
|
/content/code_sandbox/src/utils/logging.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,968
|
```javascript
/* @flow strict-local */
import base64 from 'base-64';
export const xorHexStrings = (hex1: string, hex2: string): string => {
if (hex1.length !== hex2.length) {
throw new Error('Both inputs must have the same length.');
}
return hex1
.split('')
.map((char, i) => (parseInt(hex1[i], 16) ^ parseInt(hex2[i], 16)).toString(16))
.join('')
.toUpperCase();
};
export const hexToAscii = (hex: string): string => {
let ascii = '';
for (let i = 0; i < hex.length; i += 2) {
ascii += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
return ascii;
};
export const asciiToHex = (ascii: string): string =>
ascii
.split('')
.map(char => `0${char.charCodeAt(0).toString(16)}`.slice(-2))
.join('')
.toUpperCase();
export const base64ToHex = (bytes: string): string => asciiToHex(base64.decode(bytes));
export const hexToBase64 = (hex: string): string => base64.encode(hexToAscii(hex));
/**
* Encode a string as the base64 representation of its UTF-8 bytes.
*
* This lets us pass an arbitrary string through a channel (like the
* `postMessage` on RN's WebViews on Android) that tries to do something
* like percent-decode it, or (like an HTML attribute) that forbids certain
* characters.
*
* See also `base64Utf8Decode` for the inverse.
*/
export const base64Utf8Encode = (text: string): string =>
// References on reliably encoding strings to Base64:
// path_to_url#Unicode_strings
// path_to_url
//
// In short:
// * base64 encoders want bytes, not really Unicode strings, so they
// insist their input consist of the characters U+0000 to U+00FF;
// * `encodeURIComponent` together with `unescape` is a way of getting
// that, effectively producing the UTF-8 encoding of the input.
//
// We use `base64.encode` because `btoa` is unavailable in the JS
// environment provided by RN on iOS.
base64.encode(unescape(encodeURIComponent(text)));
/**
* The inverse of `base64Utf8Encode`, above.
*/
export const base64Utf8Decode = (str: string): string =>
decodeURIComponent(escape(base64.decode(str)));
```
|
/content/code_sandbox/src/utils/encoding.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 563
|
```javascript
/* @flow strict-local */
// $FlowFixMe[untyped-import]
import isEqual from 'lodash.isequal';
import { mapOrNull } from '../collections';
import * as logging from './logging';
import type {
PmRecipientUser,
Message,
StreamMessage,
PmMessage,
Outbox,
StreamOutbox,
PmOutbox,
UserId,
UserOrBot,
} from '../types';
/**
* The stream name a stream message was sent to.
*
* BUG(#5208): This is as of whenever we learned about the message;
* it doesn't get updated if the stream is renamed.
*/
export const streamNameOfStreamMessage = (message: StreamMessage | StreamOutbox): string =>
message.display_recipient;
/**
* The recipients of a PM, in the form found on PmMessage.
*
* BUG(#5208): This is as of whenever we learned about the message;
* it doesn't get updated if one of these users changes their
* name, email, avatar, or other details.
*/
export const recipientsOfPrivateMessage = (
message: PmMessage | PmOutbox,
): $ReadOnlyArray<PmRecipientUser> => message.display_recipient;
/**
* A list of users identifying a PM conversation, as per pmKeyRecipientsFromMessage.
*
* This is an "opaque type alias" for an array of plain old data.
* See Flow docs: path_to_url
*
* That means:
* * For code outside this module, it's some unknown subtype of the given
* array type.
* * Secretly, it actually is just that array type, and code inside this
* module can see that.
* * (In general, the public type bound and the secret underlying type can
* be different, but in this case we've made them the same.)
*
* As a result:
* * The only way to produce a value of this type is with code inside this
* module. (For code outside the module, the secret underlying type
* could have any number of requirements it can't see; it could even be
* `empty`, which has no values.)
* * But code outside this module can still freely *consume* the data in a
* value of this type, just like any other value of the given array type.
*
* Or to say the same things from a different angle:
* * For code inside this module, this is just like a normal type alias,
* to the secret/private underlying type.
* * For code outside this module trying to produce a value of this type,
* it's a brick wall -- it's effectively like the `empty` type.
* * For code outside this module trying to consume a value of this type,
* it's just like a normal type alias to the public type bound; which in
* this case we've chosen to make the same as the private underlying type.
*
* See also `pmNarrowFromRecipients`, which requires a value of this type.
*/
export opaque type PmKeyRecipients: $ReadOnlyArray<UserId> = $ReadOnlyArray<UserId>;
/**
* A list of users identifying a PM conversation, as per pmKeyRecipientsFromMessage.
*
* This is just like `PmKeyRecipients` but with a different selection of
* details about the users. See there for discussion.
*
* See also `pmNarrowFromUsers`, which requires a value of this type.
*/
export opaque type PmKeyUsers: $ReadOnlyArray<UserOrBot> = $ReadOnlyArray<UserOrBot>;
/** Convert from user objects to user IDs for identifying a PM conversation. */
export const pmKeyRecipientsFromPmKeyUsers = (recipients: PmKeyUsers): PmKeyRecipients =>
recipients.map(r => r.user_id);
/**
* The list of users identifying a 1:1 PM conversation, possibly with self.
*
* `userId` should be the self user for the self-1:1 conversation, or the
* other user in a non-self 1:1 conversation.
*/
// (The fact that this function doesn't call for `ownUserId` as an argument
// basically exposes our choice of internal representation for both self-1:1
// and other 1:1 conversations. So be it. If we ever feel a need to change
// that, we can always refactor this function and its callers then.)
export const pmKeyRecipientsFor1to1 = (userId: UserId): PmKeyRecipients => [userId];
/**
* Declare, **unchecked**, that a list of users identifies a PM conversation.
*
* This function bypasses our filtering logic for finding the right set of
* users to identify the conversation according to our convention. The
* caller is responsible for ensuring that the invariant nevertheless holds.
*/
export const makePmKeyRecipients_UNSAFE = (recipients: $ReadOnlyArray<UserId>): PmKeyRecipients =>
recipients;
// Filter a list of PM recipients in the quirky way that we do, and sort.
//
// Specifically: all users, except the self-user, except if it's the
// self-1:1 thread then include the self-user after all. Then sort by ID.
//
// This is a module-private helper. See callers for what this set of
// conditions *means* -- two different things, in fact, that have the same
// behavior by coincidence.
const filterRecipients = (
recipients: $ReadOnlyArray<PmRecipientUser>,
ownUserId: UserId,
): $ReadOnlyArray<PmRecipientUser> =>
recipients.length === 1
? recipients
: recipients.filter(r => r.id !== ownUserId).sort((a, b) => a.id - b.id);
// Like filterRecipients, but on user IDs directly.
const filterRecipientsAsUserIds = (
recipients: $ReadOnlyArray<UserId>,
ownUserId: UserId,
): $ReadOnlyArray<UserId> =>
recipients.length === 1
? recipients
: recipients.filter(r => r !== ownUserId).sort((a, b) => a - b);
/**
* The same list of users as pmKeyRecipientsFromMessage, in quirkier form.
*/
// Note that sorting by user ID is the same as the server does for group PMs
// (see comment on Message#display_recipient). Then for 1:1 PMs the
// server's behavior is quirkier... but we keep only one user for those
// anyway, so it doesn't matter.
export const normalizeRecipientsAsUserIdsSansMe = (
recipients: $ReadOnlyArray<UserId>,
ownUserId: UserId,
): string => filterRecipientsAsUserIds(recipients, ownUserId).join(',');
/**
* The set of users to show in the UI to identify a PM conversation.
*
* See also:
* * `pmKeyRecipientsFromMessage`, which should be used when a consistent,
* unique key is needed for identifying different PM conversations in our
* data structures.
* * `pmUiRecipientsFromKeyRecipients`, which takes a `PmKeyRecipients`
* as input instead of a message.
*
* BUG(#5208): This is as of whenever we learned about the message;
* it doesn't get updated if one of these users changes their
* name, email, avatar, or other details.
*/
export const pmUiRecipientsFromMessage = (
message: PmMessage | PmOutbox,
ownUserId: UserId,
): $ReadOnlyArray<PmRecipientUser> =>
filterRecipients(recipientsOfPrivateMessage(message), ownUserId);
/**
* The set of users to show in the UI to identify a PM conversation.
*
* This produces the same set of users as `pmUiRecipientsFromMessage`,
* just from a different form of input. See there for more discussion.
*/
export const pmUiRecipientsFromKeyRecipients = (
recipients: PmKeyRecipients,
ownUserId: UserId,
): $ReadOnlyArray<UserId> =>
// As it happens, the representation we use in PmKeyRecipients is the same
// as we want in the UI:
// * for the self-1:1 conversation, just the self user;
// * for other 1:1 conversations, the other user;
// * for group PM conversations, all the other users.
recipients;
/**
* The list of users to identify a PM conversation by in our data structures.
*
* This produces the same list of users as `pmKeyRecipientsFromMessage`,
* just from a different form of input. See there for more discussion.
*/
export const pmKeyRecipientsFromIds = (
userIds: $ReadOnlyArray<UserId>,
ownUserId: UserId,
): PmKeyRecipients => filterRecipientsAsUserIds(userIds, ownUserId);
/**
* The list of users to identify a PM conversation by in our data structures.
*
* This list is sorted by user ID.
*
* Typically we go on to take either the emails or user IDs in the result,
* stringify them, and join with `,` to produce a string key. IDs are
* preferred; see #3764.
*
* See also:
* * `pmUiRecipientsFromMessage`, which gives a set of users to show in the
* UI.
*
* * The `Narrow` type and its constructors in `narrow.js`, which we use to
* make keys to identify narrows in general, including stream and topic
* narrows.
*
* * The other `pmKeyRecipients` functions in this module, which do the
* same computation but with different forms of input and output.
*
* * `normalizeRecipientsAsUserIdsSansMe` and `pmUnreadsKeyFromMessage`,
* which do the same job as this function with slight variations, and
* which we variously use in different places in the app.
*
* It would be great to unify on a single version, as the variation is a
* possible source of bugs.
*/
// The list would actually be sorted even without explicit sorting, because:
// * For group PMs, the server provides them in that order; see comment
// on Message#display_recipient.
// * For 1:1 PMs, we only keep one user in the list.
// But we also sort them ourselves, so as not to rely on that fact about
// the server; it's easy enough to do.
export const pmKeyRecipientsFromMessage = (
message: PmMessage | PmOutbox,
ownUserId: UserId,
): PmKeyRecipients =>
pmKeyRecipientsFromIds(
recipientsOfPrivateMessage(message).map(r => r.id),
ownUserId,
);
/**
* The list of users to identify a PM conversation by in our data structures.
*
* This produces the same list of users as `pmKeyRecipientsFromMessage`, just
* from a different form of input.
*
* The input may either include or exclude self, without affecting the
* result.
*
* Returns null when a user couldn't be found in the given `allUsersById`.
*/
export const pmKeyRecipientUsersFromIds = (
userIds: $ReadOnlyArray<UserId>,
allUsersById: Map<UserId, UserOrBot>,
ownUserId: UserId,
): PmKeyUsers | null => {
const resultIds = userIds.filter(id => id !== ownUserId);
if (resultIds.length === 0) {
resultIds.push(ownUserId);
}
const users = mapOrNull(resultIds, id => allUsersById.get(id));
if (!users) {
logging.warn('pmKeyRecipientUsersFromIds: missing data on user');
return null;
}
return users.sort((a, b) => a.user_id - b.user_id);
};
/**
* Just like pmKeyRecipientsFromMessage, but in a slightly different format.
*/
export const pmKeyRecipientUsersFromMessage = (
message: PmMessage | PmOutbox,
allUsersById: Map<UserId, UserOrBot>,
ownUserId: UserId,
): PmKeyUsers | null => {
const userIds = recipientsOfPrivateMessage(message).map(r => r.id);
return pmKeyRecipientUsersFromIds(userIds, allUsersById, ownUserId);
};
/**
* Just like pmKeyRecipientsFromMessage, but from a different form of input.
*/
export const pmKeyRecipientsFromUsers = (
users: $ReadOnlyArray<UserOrBot>,
ownUserId: UserId,
): PmKeyRecipients =>
pmKeyRecipientsFromIds(
users.map(u => u.user_id),
ownUserId,
);
/**
* The key this PM is filed under in the "unread messages" data structure.
*
* Note this diverges slightly from pmKeyRecipientsFromMessage in its
* behavior -- it encodes a different set of users.
*
* See also:
* * `pmKeyRecipientsFromMessage`, which we use for other data structures.
* * `pmUnreadsKeyFromPmKeyIds`, for getting one of these keys given what
* we use for other data structures.
* * `pmUnreadsKeyFromOtherUsers`, for getting one of these keys from still
* another form of input.
* * `UnreadState`, the type of `state.unread`, which is the data structure
* these keys appear in.
*
* @param ownUserId - Required if the message could be a 1:1 PM; optional if
* it is definitely a group PM.
*/
// Specifically, this includes all user IDs for group PMs and self-PMs,
// and just the other user ID for non-self 1:1s; and in each case the list
// is sorted numerically and encoded in ASCII-decimal, comma-separated.
// See the `unread_msgs` data structure in `src/api/initialDataTypes.js`.
export const pmUnreadsKeyFromMessage = (message: PmMessage, ownUserId?: UserId): string => {
const recipients = recipientsOfPrivateMessage(message);
// This includes all users in the thread; see `Message#display_recipient`.
const userIds = recipients.map(r => r.id);
if (userIds.length === 1) {
// Self-PM.
return userIds[0].toString();
} else if (userIds.length === 2) {
// Non-self 1:1 PM. Unlike display_recipient, leave out the self user.
if (ownUserId === undefined) {
throw new Error('getRecipientsIds: got 1:1 PM, but ownUserId omitted');
}
return userIds.filter(userId => userId !== ownUserId)[0].toString();
} else {
// Group PM.
return userIds.sort((a, b) => a - b).join(',');
}
};
/**
* The key for a PM thread in "unreads" data, given the key we use elsewhere.
*
* This produces the same key string that `pmUnreadsKeyFromMessage` would
* give, given the list of users that `pmKeyRecipientsFromMessage` would
* give and which we use in most of our other data structures.
*
* Careful: This is a *string key*. Don't === against numeric `.sender_id`s
* in UnreadPmsState. You won't find the object you're looking for, and Flow
* won't complain.
*
* See also `pmUnreadsKeyFromOtherUsers` for getting one of these keys from
* still another form of input.
*/
// See comment on pmUnreadsKeyFromMessage for details on this form.
export const pmUnreadsKeyFromPmKeyIds = (userIds: PmKeyRecipients, ownUserId: UserId): string => {
if (userIds.length === 1) {
// A 1:1 PM. Both forms include just one user: the other user if any,
// and self for a self-1:1.
return userIds[0].toString();
} else {
// A group PM. Our main "key" form includes just the other users;
// this form includes all users.
return [...userIds, ownUserId].sort((a, b) => a - b).join(',');
}
};
/**
* The key for a PM thread in "unreads" data, given the set of non-self users.
*
* This produces the same key string that `pmUnreadsKeyFromMessage` would
* give, given the list of all users in the thread other than the self user.
*
* See also `pmUnreadsKeyFromPmKeyIds` for getting one of these keys from
* still another form of input.
*/
// See comment on pmUnreadsKeyFromMessage for details on this form.
export const pmUnreadsKeyFromOtherUsers = (
userIds: $ReadOnlyArray<UserId>,
ownUserId: UserId,
): string => {
if (userIds.length === 0) {
// Self-PM.
return ownUserId.toString();
} else if (userIds.length === 1) {
// Non-self 1:1 PM.
return userIds[0].toString();
} else {
// Group PM.
return [ownUserId, ...userIds].sort((a, b) => a - b).join(',');
}
};
/**
* The key for a PM thread in typing-status data, given the IDs we use generally.
*
* This produces the key string we use in `state.typing`, given the list of
* users that `pmKeyRecipientsFromMessage` would provide and that we use in
* most of our other data structures indexed on narrows.
*
* See also `pmTypingKeyFromRecipients`.
*/
// That key string is: just the usual "PM key" list of users, stringified
// and comma-separated.
export const pmTypingKeyFromPmKeyIds = (userIds: PmKeyRecipients): string => userIds.join(',');
/**
* The key for a PM thread in typing-status data, given a recipients list.
*
* This produces the key string we use in `state.typing`, given the list of
* users that a typing-status event provides in `recipients`.
*
* See also `pmTypingKeyFromPmKeyIds`.
*/
// This implementation works because:
// * For all but self-PMs, we want the list of non-self users, which
// `filterRecipientsAsUserIds` will give regardless of whether self was
// in the input. (So it doesn't matter what convention the server uses
// for these events.)
// * Self-PMs don't have typing-status events in the first place.
export const pmTypingKeyFromRecipients = (
recipients: $ReadOnlyArray<UserId>,
ownUserId: UserId,
): string => pmTypingKeyFromPmKeyIds(filterRecipientsAsUserIds(recipients, ownUserId));
export const isSameRecipient = (
message1: Message | Outbox,
message2: Message | Outbox,
): boolean => {
switch (message1.type) {
case 'private':
if (message2.type !== 'private') {
return false;
}
// We rely on the recipients being listed in a consistent order
// between different messages in the same PM conversation. The server
// is indeed consistent to that degree; see comments on the Message
// type. But:
//
// TODO: This can wrongly return false if the recipients come in a
// different order. In particular this happens if there's a real
// Message, then an Outbox message, to the same 1:1 PM thread (other
// than self-1:1.) The effect is that if you send a 1:1, then go
// visit an interleaved narrow where it appears, you may see an
// extraneous recipient header.
//
// We could fix that by sorting, but this is in a hot loop where
// we're already doing too much computation. Instead, we should
// store an unambiguous ===-comparable key on each message to
// identify its conversation, and sort when computing that. Until
// then, we just tolerate this glitch in that edge case.
return isEqual(
recipientsOfPrivateMessage(message1).map(r => r.id),
recipientsOfPrivateMessage(message2).map(r => r.id),
);
case 'stream':
if (message2.type !== 'stream') {
return false;
}
return (
message1.stream_id === message2.stream_id
&& message1.subject.toLowerCase() === message2.subject.toLowerCase()
);
default:
// Invariant
return false;
}
};
```
|
/content/code_sandbox/src/utils/recipient.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 4,484
|
```javascript
/* @flow strict-local */
import format from 'date-fns/format';
import isToday from 'date-fns/isToday';
import isYesterday from 'date-fns/isYesterday';
import isSameYear from 'date-fns/isSameYear';
import addMinutes from 'date-fns/addMinutes';
// $FlowFixMe[untyped-import]
import tz from 'timezone/loaded';
export { default as isSameDay } from 'date-fns/isSameDay';
/**
* If in tests, adjust the date to roughly pretend the timezone is UTC.
*
* When not in tests, this function just returns its argument.
*
* When in tests, it returns an adjusted `Date` which, in the timezone we're
* actually using, will hopefully give the same answers on methods like
* `getHours` as the original `Date` would give in the UTC timezone, and so
* libraries like `date-fns/format` will produce the same results as they
* would on the original `Date` in the UTC timezone.
*
* Normalizing those results to UTC, in turn, helps us get consistent
* results for snapshot tests.
*
* In general what this function aims to do is impossible. In particular,
* in places with daylight savings time (aka summer time), the local time
* skips an hour each spring; so for example there is no time at all that
* was 2021-03-14 02:30 (or any other time from 02:00 to before 03:00) in
* America/New_York, and so if the current timezone is America/New_York and
* the given `Date` is 2021-03-14 02:30Z (i.e., 2021-03-13 21:30 in
* America/New_York) then there is no valid result this function could
* return.
*
* So while this function makes a reasonable effort, there's a window around
* any time when the offset changes for the current timezone (in particular,
* around the start and end of DST / summer time) in which the result may
* not be right.
*
* That's OK because the function only does anything in tests (for actual
* users, we want to use the ambient timezone anyway), plus in tests we do
* our best to make the timezone in use be UTC in the first place. See note
* in `jest/globalSetup.js` where we do that.
*/
// For more background on how this works, see discussion:
// path_to_url#narrow/stream/243-mobile-team/topic/Snapshot.20tests/near/1167545
function maybePretendUtc(date: Date): Date {
/* eslint-disable operator-linebreak */
/* eslint-disable-next-line no-underscore-dangle */
return global.__TEST__
? // Negate the UTC offset, using an offset we get from `date` itself, so
// it'll be correct for DST-type changes through the year.
// Empirically, the sign seems to be correct:
// path_to_url#discussion_r648702356
addMinutes(date, date.getTimezoneOffset())
: date;
}
export const shortTime = (date: Date, twentyFourHourTime: boolean = false): string =>
format(maybePretendUtc(date), twentyFourHourTime ? 'H:mm' : 'h:mm a');
export const shortDate = (date: Date): string => format(date, 'MMM d');
export const longDate = (date: Date): string => format(date, 'MMM d, yyyy');
export const daysInDate = (date: Date): number => Math.trunc(date / 1000 / 60 / 60 / 24);
export const humanDate = (date: Date): string => {
if (isToday(date)) {
return 'Today';
}
if (isYesterday(date)) {
return 'Yesterday';
}
return isSameYear(new Date(date), new Date()) ? shortDate(date) : longDate(date);
};
export const nowInTimeZone = (timezone: string): string => tz(tz(new Date()), '%I:%M %p', timezone);
```
|
/content/code_sandbox/src/utils/date.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 882
|
```javascript
/* @flow strict-local */
import { makeUserId } from '../api/idTypes';
import type { ApiNarrow, Message, Outbox, Stream, UserId, UserOrBot } from '../types';
import {
normalizeRecipientsAsUserIdsSansMe,
pmKeyRecipientsFromMessage,
recipientsOfPrivateMessage,
type PmKeyRecipients,
type PmKeyUsers,
pmKeyRecipientsFromPmKeyUsers,
pmKeyRecipientsFor1to1,
makePmKeyRecipients_UNSAFE,
} from './recipient';
import type { UserMessageFlag } from '../api/modelTypes';
import { ensureUnreachable } from '../generics';
/* eslint-disable no-use-before-define */
/**
* A narrow.
*
* A narrow is the navigational property that defines what to show in the
* message list UI: it's a subset of messages which might be a conversation,
* a whole stream, a search, or a few other varieties.
*
* Much of the data we fetch is to support the message list UI, and so we
* keep much of it in data structures indexed by narrow.
*
* See also:
* * `keyFromNarrow`, for converting into a string key good for indexing
* into a data structure;
* * `caseNarrow` and its relatives, for pattern-matching or destructuring;
* * `ApiNarrow` for the form we put a narrow in when talking to the
* server, and `apiNarrowOfNarrow` for converting to it.
*/
export opaque type Narrow =
| {| type: 'stream', streamId: number |}
| {| type: 'topic', streamId: number, topic: string |}
| {| type: 'pm', userIds: PmKeyRecipients |}
| {| type: 'search', query: string |}
| {| type: 'all' | 'starred' | 'mentioned' | 'all-pm' |};
export const HOME_NARROW: Narrow = Object.freeze({ type: 'all' });
export const HOME_NARROW_STR: string = keyFromNarrow(HOME_NARROW);
/**
* A PM narrow, either 1:1 or group.
*
* The list of users represented in `emails` must agree with what
* `pmKeyRecipientsFromMessage` would return. Effectively this means:
* * it actually comes from `pmKeyRecipientsFromMessage`, or one of its
* relatives in `src/utils/recipient.js`;
* * or it's a singleton list, which those would always be a no-op on.
*
* We enforce this by keeping this constructor private to this module, and
* only calling it from higher-level constructors whose input types enforce
* one of these conditions or the other. (Well, and one more which is only
* to be used in test code.)
*
* In the past, before this was checked and before it was done consistently,
* we had quite a lot of bugs due to different parts of our code
* accidentally disagreeing on whether to include the self-user, or on how
* to sort the list (by user ID vs. email), or neglecting to sort it at all.
*/
const pmNarrowInternal = (userIds: PmKeyRecipients): Narrow =>
Object.freeze({ type: 'pm', userIds });
/**
* A PM narrow, either 1:1 or group.
*
* The argument's type guarantees that it comes from
* `pmKeyRecipientsFromMessage` or one of its related functions. This
* ensures that we've properly either removed the self user, or not.
*
* See also `pmNarrowFromUsers`, which does the same thing with a slightly
* different form of input.
*/
export const pmNarrowFromRecipients = (recipients: PmKeyRecipients): Narrow =>
pmNarrowInternal(recipients);
/**
* A PM narrow, either 1:1 or group.
*
* This is just like `pmNarrowFromRecipients`, but taking a slightly
* different form of input. Use whichever one is more convenient.
*
* See also `pm1to1NarrowFromUser`, which is more convenient when you have a
* single specific user.
*/
export const pmNarrowFromUsers = (recipients: PmKeyUsers): Narrow =>
pmNarrowInternal(pmKeyRecipientsFromPmKeyUsers(recipients));
/**
* FOR TESTS ONLY. Like pmNarrowFromUsers, but without validation.
*
* This exists purely for convenience in tests. Unlike the other Narrow
* constructors, its type does not require the argument to have come from a
* function that applies our "maybe filter out self" convention. The caller
* is still required to do so, but nothing checks this.
*
* Outside of tests, always use pmNarrowFromUsers instead. Use
* pmKeyRecipientsFromUsers, along with an ownUserId value, to produce the
* needed input.
*
* This does take care of sorting the input as needed.
*/
// It'd be fine for test data to go through the usual filtering logic; the
// annoying thing is just that that requires an ownUserId value.
export const pmNarrowFromUsersUnsafe = (recipients: $ReadOnlyArray<UserOrBot>): Narrow => {
const userIds = recipients.map(u => u.user_id).sort((a, b) => a - b);
// This call is unsafe, but that's why this function is too.
return pmNarrowInternal(makePmKeyRecipients_UNSAFE(userIds));
};
/**
* A 1:1 PM narrow, possibly with self.
*
* This has the same effect as calling pmNarrowFromUsers, but for code that
* statically has just one other user it's a bit more convenient because it
* doesn't require going through our `recipient` helpers.
*/
export const pm1to1NarrowFromUser = (user: UserOrBot): Narrow =>
pmNarrowInternal(pmKeyRecipientsFor1to1(user.user_id));
export const specialNarrow = (operand: 'starred' | 'mentioned' | 'dm'): Narrow => {
switch (operand) {
case 'starred':
return Object.freeze({ type: 'starred' });
case 'mentioned':
return Object.freeze({ type: 'mentioned' });
case 'dm':
return Object.freeze({ type: 'all-pm' });
default:
ensureUnreachable(operand);
throw new Error();
}
};
export const STARRED_NARROW: Narrow = specialNarrow('starred');
export const STARRED_NARROW_STR: string = keyFromNarrow(STARRED_NARROW);
export const MENTIONED_NARROW: Narrow = specialNarrow('mentioned');
export const MENTIONED_NARROW_STR: string = keyFromNarrow(MENTIONED_NARROW);
export const ALL_PRIVATE_NARROW: Narrow = specialNarrow('dm');
export const ALL_PRIVATE_NARROW_STR: string = keyFromNarrow(ALL_PRIVATE_NARROW);
export const streamNarrow = (streamId: number): Narrow =>
Object.freeze({ type: 'stream', streamId });
export const topicNarrow = (streamId: number, topic: string): Narrow =>
Object.freeze({ type: 'topic', streamId, topic });
export const SEARCH_NARROW = (query: string): Narrow => Object.freeze({ type: 'search', query });
type NarrowCases<T> = {|
home: () => T,
pm: (ids: PmKeyRecipients) => T,
starred: () => T,
mentioned: () => T,
allPrivate: () => T,
stream: (streamId: number) => T,
topic: (streamId: number, topic: string) => T,
search: (query: string) => T,
|};
/* prettier-ignore */
export function caseNarrow<T>(narrow: Narrow, cases: NarrowCases<T>): T {
const err = (): empty => {
throw new Error(`bad narrow: ${JSON.stringify(narrow)}`);
};
switch (narrow.type) {
case 'stream': return cases.stream(narrow.streamId);
case 'topic': return cases.topic(narrow.streamId, narrow.topic);
case 'pm': return cases.pm(narrow.userIds);
case 'search': return cases.search(narrow.query);
case 'all': return cases.home();
case 'starred': return cases.starred();
case 'mentioned': return cases.mentioned();
case 'all-pm': return cases.allPrivate();
default: return err();
}
}
export function caseNarrowPartial<T>(narrow: Narrow, cases: $Shape<NarrowCases<T>>): T {
const err = (type: string) => (): empty => {
throw new Error(`unexpected ${type} narrow: ${keyFromNarrow(narrow)}`);
};
return caseNarrow(
narrow,
Object.assign(
({
home: err('home'),
pm: err('PM'),
starred: err('starred'),
mentioned: err('mentions'),
allPrivate: err('all-private'),
stream: err('stream'),
topic: err('topic'),
search: err('search'),
}: NarrowCases<T>),
cases,
),
);
}
export function caseNarrowDefault<T>(
narrow: Narrow,
cases: $Shape<NarrowCases<T>>,
defaultCase: () => T,
): T {
return caseNarrow(
narrow,
Object.assign(
({
home: defaultCase,
pm: defaultCase,
starred: defaultCase,
mentioned: defaultCase,
allPrivate: defaultCase,
stream: defaultCase,
topic: defaultCase,
search: defaultCase,
}: NarrowCases<T>),
cases,
),
);
}
/**
* The key we use for this narrow in our Redux data structures.
*
* See in particular `NarrowsState`, `CaughtUpState`, `FetchingState`,
* and `DraftsState`.
*
* The key may contain arbitrary Unicode codepoints. If passing through a
* channel (like an HTML attribute) that only allows certain codepoints, use
* something like `base64Utf8Encode` to encode into the permitted subset.
*/
// The arbitrary Unicode codepoints come from topics. (These aren't
// *completely* arbitrary, but close enough that there's little to gain
// from relying on constraints on them.)
export function keyFromNarrow(narrow: Narrow): string {
// The ":s" (for "string") in several of these was to keep them disjoint,
// out of an abundance of caution, from later keys that use numeric IDs.
//
// Similarly, ":d" ("dual") marked those with both numeric IDs and strings.
return caseNarrow(narrow, {
// NB if you're changing any of these: be sure to do a migration.
// Take a close look at migration 19 and any later related migrations.
// An earlier version had `stream:s:`. Another had `stream:d:`.
stream: streamId => `stream:${streamId}`,
// An earlier version had `topic:s:`. Another had `topic:d:`.
topic: (streamId, topic) => `topic:${streamId}:${topic}`,
// An earlier version had `pm:s:`. Another had `pm:d:`.
pm: ids => `pm:${ids.join(',')}`,
home: () => 'all',
starred: () => 'starred',
mentioned: () => 'mentioned',
allPrivate: () => 'all-pm',
search: query => `search:${query}`,
});
}
/**
* Parse a narrow previously encoded with keyFromNarrow.
*/
export const parseNarrow = (narrowStr: string): Narrow => {
const makeError = () => new Error('parseNarrow: bad narrow');
const tag = /^.*?(?::|$)/.exec(narrowStr)?.[0] ?? '';
const rest = narrowStr.substr(tag.length);
// invariant: tag + rest === narrowStr
switch (tag) {
case 'stream:': {
if (!/^\d+$/.test(rest)) {
throw makeError();
}
return streamNarrow(Number.parseInt(rest, 10));
}
case 'topic:': {
// The `/s` regexp flag means the `.` pattern matches absolutely
// anything. By default it rejects certain "newline" characters,
// which in principle could appear in topics.
const match = /^(\d+):(.*)/s.exec(rest);
if (!match) {
throw makeError();
}
return topicNarrow(Number.parseInt(match[1], 10), match[2]);
}
case 'pm:': {
const ids = rest.split(',').map(s => makeUserId(Number.parseInt(s, 10)));
// Here we're relying on the key having been encoded from a
// correct list of users.
return pmNarrowInternal(makePmKeyRecipients_UNSAFE(ids));
}
case 'search:': {
return SEARCH_NARROW(rest);
}
default:
if (rest !== '') {
throw makeError();
}
switch (tag) {
case 'all':
return HOME_NARROW;
case 'starred':
return STARRED_NARROW;
case 'mentioned':
return MENTIONED_NARROW;
case 'all-pm':
return ALL_PRIVATE_NARROW;
default:
throw makeError();
}
}
};
export const isHomeNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { home: () => true }, () => false);
export const is1to1PmNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { pm: ids => ids.length === 1 }, () => false);
export const isGroupPmNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { pm: ids => ids.length > 1 }, () => false);
/**
* The "PM key recipients" IDs for a PM narrow; else error.
*
* This is the same list of users that can appear in a `PmKeyRecipients` or
* `PmKeyUsers`, but contains only their user IDs.
*/
export const userIdsOfPmNarrow = (narrow: Narrow): PmKeyRecipients =>
caseNarrowPartial(narrow, { pm: ids => ids });
/**
* The stream ID for a stream or topic narrow; else error.
*
* Most callers of this should probably be getting passed a stream ID
* instead of a Narrow in the first place; or if they do handle other kinds
* of narrows, should be using `caseNarrow`.
*/
export const streamIdOfNarrow = (narrow: Narrow): number =>
caseNarrowPartial(narrow, { stream: id => id, topic: id => id });
/**
* The topic for a topic narrow; else error.
*
* Most callers of this should probably be getting passed a topic (and a
* stream ID) instead of a Narrow in the first place; or if they do handle
* other kinds of narrows, should be using `caseNarrow`.
*/
export const topicOfNarrow = (narrow: Narrow): string =>
caseNarrowPartial(narrow, { topic: (id, topic) => topic });
export const isPmNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { pm: () => true }, () => false);
export const isSpecialNarrow = (narrow?: Narrow): boolean =>
!!narrow
&& caseNarrowDefault(
narrow,
{ starred: () => true, mentioned: () => true, allPrivate: () => true },
() => false,
);
export const isAllPrivateNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { allPrivate: () => true }, () => false);
export const isStreamNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { stream: () => true }, () => false);
export const isTopicNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { topic: () => true }, () => false);
export const isStreamOrTopicNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { stream: () => true, topic: () => true }, () => false);
export const isSearchNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { search: () => true }, () => false);
export const isMentionedNarrow = (narrow?: Narrow): boolean =>
!!narrow && caseNarrowDefault(narrow, { mentioned: () => true }, () => false);
/**
* Whether the narrow represents a single whole conversation.
*
* A conversation is the smallest unit that discussions are threaded into:
* either a specific topic in a stream, or a PM thread (either 1:1 or group).
*
* When sending a message, its destination is identified by a conversation.
*/
export const isConversationNarrow = (narrow: Narrow): boolean =>
caseNarrowDefault(narrow, { topic: () => true, pm: () => true }, () => false);
/**
* Convert the narrow into the form used in the Zulip API at get-messages.
*/
export const apiNarrowOfNarrow = (
narrow: Narrow,
allUsersById: Map<UserId, UserOrBot>,
streamsById: Map<number, Stream>,
): ApiNarrow => {
const get = <K, V>(description, map: Map<K, V>, key: K): V => {
const result = map.get(key);
if (result === undefined) {
throw new Error(`apiNarrowOfNarrow: missing ${description}`);
}
return result;
};
return caseNarrow(narrow, {
stream: streamId => [
// TODO(server-2.1): just send stream ID instead
{ operator: 'stream', operand: get('stream', streamsById, streamId).name },
],
topic: (streamId, topic) => [
// TODO(server-2.1): just send stream ID instead
{ operator: 'stream', operand: get('stream', streamsById, streamId).name },
{ operator: 'topic', operand: topic },
],
pm: ids => {
const emails = ids.map(id => get('user', allUsersById, id).email);
// TODO(server-7.0): send `dm` rather than `pm-with`
// TODO(server-2.1): just send IDs instead
return [{ operator: 'pm-with', operand: emails.join(',') }];
},
search: query => [{ operator: 'search', operand: query }],
home: () => [],
starred: () => [{ operator: 'is', operand: 'starred' }],
mentioned: () => [{ operator: 'is', operand: 'mentioned' }],
// TODO(server-7.0): send `is:dm` rather than `is:private`
allPrivate: () => [{ operator: 'is', operand: 'private' }],
});
};
/**
* True just if the given message is part of the given narrow.
*
* This function does not support search narrows, and for them always
* returns false.
*
* The message's flags must be in `flags`; `message.flags` is ignored. This
* makes it the caller's responsibility to deal with the ambiguity in our
* Message type of whether the message's flags live in a `flags` property or
* somewhere else.
*
* See also getNarrowsForMessage, which should list exactly the narrows this
* would return true for.
*/
export const isMessageInNarrow = (
message: Message | Outbox,
flags: $ReadOnlyArray<UserMessageFlag>,
narrow: Narrow,
ownUserId: UserId,
): boolean =>
caseNarrow(narrow, {
home: () => true,
stream: streamId => message.type === 'stream' && streamId === message.stream_id,
topic: (streamId, topic) =>
message.type === 'stream' && streamId === message.stream_id && topic === message.subject,
pm: ids => {
if (message.type !== 'private') {
return false;
}
const recipients = recipientsOfPrivateMessage(message).map(r => r.id);
const narrowAsRecipients = ids;
return (
normalizeRecipientsAsUserIdsSansMe(recipients, ownUserId)
=== normalizeRecipientsAsUserIdsSansMe(narrowAsRecipients, ownUserId)
);
},
starred: () => flags.includes('starred'),
mentioned: () => flags.includes('mentioned') || flags.includes('wildcard_mentioned'),
allPrivate: () => message.type === 'private',
search: () => false,
// Adding a case here? Be sure to add to getNarrowsForMessage, too.
});
/**
* Whether we show the compose box on this narrow's message list.
*
* This is really a UI choice that belongs to a specific part of the UI.
* It's here for now because several files refer to it.
*/
// TODO make this appropriately part of the UI code.
export const showComposeBoxOnNarrow = (narrow: Narrow): boolean =>
caseNarrow(narrow, {
pm: () => true,
stream: () => true,
topic: () => true,
home: () => false,
starred: () => false,
mentioned: () => false,
allPrivate: () => false,
search: () => false,
});
/**
* Answers the question, "What narrows does this message appear in?"
*
* This function does not support search narrows, and it always
* excludes them.
*
* The message's flags must be in `flags`; `message.flags` is ignored. This
* makes it the caller's responsibility to deal with the ambiguity in our
* Message type of whether the message's flags live in a `flags` property or
* somewhere else.
*
* See also isMessageInNarrow, which should return true for exactly the
* narrows this lists and no others.
*/
export const getNarrowsForMessage = (
message: Message | Outbox,
ownUserId: UserId,
flags: $ReadOnlyArray<UserMessageFlag>,
): $ReadOnlyArray<Narrow> => {
const result = [];
// All messages are in the home narrow.
result.push(HOME_NARROW);
if (message.type === 'private') {
result.push(ALL_PRIVATE_NARROW);
result.push(pmNarrowFromRecipients(pmKeyRecipientsFromMessage(message, ownUserId)));
} else {
result.push(topicNarrow(message.stream_id, message.subject));
result.push(streamNarrow(message.stream_id));
}
if (flags.includes('mentioned') || flags.includes('wildcard_mentioned')) {
result.push(MENTIONED_NARROW);
}
if (flags.includes('starred')) {
result.push(STARRED_NARROW);
}
// SEARCH_NARROW we always leave out
return result;
};
/**
* Answers the question, "Where should my reply to a message go?"
*
* For stream messages, chooses a topic narrow over a stream narrow.
*/
// TODO: probably make this a private local helper of its one caller,
// now that it's free of fiddly details from the Narrow data structure
export const getNarrowForReply = (message: Message | Outbox, ownUserId: UserId): Narrow => {
if (message.type === 'private') {
return pmNarrowFromRecipients(pmKeyRecipientsFromMessage(message, ownUserId));
} else {
return topicNarrow(message.stream_id, message.subject);
}
};
```
|
/content/code_sandbox/src/utils/narrow.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 5,188
|
```javascript
/* @flow strict-local */
import { StatusBar, Platform } from 'react-native';
// Network activity indicators should be visible if *any* network activity is occurring
let activityCounter = 0;
export const networkActivityStart = (isSilent: boolean) => {
if (isSilent) {
return;
}
activityCounter++;
if (Platform.OS === 'ios') {
StatusBar.setNetworkActivityIndicatorVisible(true);
}
};
export const networkActivityStop = (isSilent: boolean) => {
if (isSilent) {
return;
}
activityCounter--;
if (activityCounter === 0 && Platform.OS === 'ios') {
StatusBar.setNetworkActivityIndicatorVisible(false);
}
};
```
|
/content/code_sandbox/src/utils/networkActivity.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 153
|
```javascript
/* @flow strict-local */
import type { FlagsState, Message, Outbox } from '../types';
export const filterUnreadMessageIds = (
messageIds: $ReadOnlyArray<number>,
flags: FlagsState,
): number[] => messageIds.filter((msgId: number) => !flags || !flags.read || !flags.read[msgId]);
export const filterUnreadMessagesInRange = (
messages: $ReadOnlyArray<Message | Outbox>,
flags: FlagsState,
fromId: number,
toId: number,
): number[] => {
const messagesInRange = messages
.filter(msg => !msg.isOutbox)
.filter(msg => msg.id >= fromId && msg.id <= toId);
return filterUnreadMessageIds(
messagesInRange.map(x => x.id),
flags,
);
};
```
|
/content/code_sandbox/src/utils/unread.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 174
|
```javascript
/* @flow strict-local */
import { addBreadcrumb } from '@sentry/react-native';
import * as internal_url from '@zulip/shared/lib/internal_url';
import { makeUserId } from '../api/idTypes';
import type { Narrow, Stream, UserId, Message, Outbox, PmMessage, PmOutbox } from '../types';
import { topicNarrow, streamNarrow, specialNarrow, pmNarrowFromRecipients } from './narrow';
import { pmKeyRecipientsFromIds, recipientsOfPrivateMessage } from './recipient';
import { isUrlOnRealm } from './url';
/**
* For narrow URL path_to_url#narrow/foo/bar, split the part of
* the hash after #narrow/ to give ['foo', 'bar'].
*
* The passed `url` must appear to be a link to a Zulip narrow on the given
* `realm`. In particular, `isNarrowLink(url, realm)` must be true.
*
* If `url` ends with a slash, the returned array won't have '' as its last
* element; that element is removed.
*/
// TODO: Parse into an array of objects with { negated, operator, operand },
// like the web app's parse_narrow in static/js/hash_util.js.
// TODO(#3757): Use @zulip/shared for that parsing.
const getHashSegmentsFromNarrowLink = (url: URL, realm: URL) => {
const result = url.hash
.split('/')
// Remove the first item, "#narrow".
.slice(1);
if (result[result.length - 1] === '') {
// url ends with /
result.splice(-1, 1);
}
return result;
};
/**
* Test for a link to a Zulip narrow on the given realm.
*
* True just if the given URL appears to be a link to a Zulip narrow on the
* given realm.
*/
export const isNarrowLink = (url: URL, realm: URL): boolean =>
isUrlOnRealm(url, realm)
&& url.pathname === '/'
&& url.search === ''
&& /^#narrow\//i.test(url.hash);
/** Decode a dot-encoded string. */
// The Zulip webapp uses this encoding in narrow-links:
// path_to_url#L18-L25
export const decodeHashComponent = (string: string): string => {
try {
return decodeURIComponent(string.replace(/\./g, '%'));
} catch (err) {
// `decodeURIComponent` throws strikingly uninformative errors
addBreadcrumb({
level: 'info',
type: 'decoding',
message: 'decodeHashComponent error',
data: { input: string },
});
throw err;
}
};
/**
* Parse the operand of a `stream` operator, returning a stream ID.
*
* The ID might point to a stream that's hidden from our user (perhaps
* doesn't exist). If so, most likely the user doesn't have permission to
* see the stream's existence -- like with a guest user for any stream
* they're not in, or any non-admin with a private stream they're not in.
* Could be that whoever wrote the link just made something up.
*
* Returns null if the operand has an unexpected shape, or has the old shape
* (stream name but no ID) and we don't know of a stream by the given name.
*/
// Why does this parser need stream data? Because the operand formats
// ("new" and "old") collide, and in choosing which format to apply, we
// want to know if one or the other would give a real stream we know
// about. Also, we can't get a stream ID from an "old"-format operand
// without a mapping from stream names to IDs.
const parseStreamOperand = (operand, streamsById, streamsByName): null | number => {
// "New" (2018) format: ${stream_id}-${stream_name} .
const match = /^([\d]+)(?:-.*)?$/.exec(operand);
const newFormatStreamId = match ? parseInt(match[1], 10) : null;
if (newFormatStreamId != null && streamsById.has(newFormatStreamId)) {
return newFormatStreamId;
}
// Old format: just stream name. This case is relevant indefinitely,
// so that links in old conversations continue to work.
const streamName = decodeHashComponent(operand);
const stream = streamsByName.get(streamName);
if (stream) {
return stream.stream_id;
}
if (newFormatStreamId != null) {
// Neither format found a Stream, so it's hidden or doesn't exist. But
// at least we have a stream ID; give that to the caller. (See jsdoc.)
return newFormatStreamId;
}
// Unexpected shape, or the old shape and we don't know of a stream with
// the given name.
return null;
};
/** Parse the operand of a `topic` or `subject` operator. */
const parseTopicOperand = operand => decodeHashComponent(operand);
/** Parse the operand of a `pm-with` operator. */
const parsePmOperand = operand => {
const idStrs = operand.split('-')[0].split(',');
return idStrs.map(s => makeUserId(parseInt(s, 10)));
};
/**
* Gives a Narrow object for the given narrow link, or `null`.
*
* Returns null if any of the operator/operand pairs are invalid.
*
* Since narrow links can combine operators in ways our Narrow type can't
* represent, this can also return null for valid narrow links.
*
* This can also return null for some valid narrow links that our Narrow
* type *could* accurately represent. We should try to understand these
* better, but some kinds will be rare, even unheard-of:
* #narrow/topic/mobile.20releases/stream/1-announce (stream/topic reversed)
* #narrow/stream/1-announce/stream/1-announce (duplicated operator)
*
* The passed `url` must appear to be a link to a Zulip narrow on the given
* `realm`. In particular, `isNarrowLink(url, realm)` must be true.
*/
export const getNarrowFromNarrowLink = (
url: URL,
realm: URL,
streamsById: Map<number, Stream>,
streamsByName: Map<string, Stream>,
ownUserId: UserId,
): Narrow | null => {
// isNarrowLink() is true, by jsdoc, so this call is OK.
const hashSegments = getHashSegmentsFromNarrowLink(url, realm);
if (
// 'dm' is new in server-7.0; means the same as 'pm-with'
(hashSegments.length === 2 && (hashSegments[0] === 'pm-with' || hashSegments[0] === 'dm'))
|| (hashSegments.length === 4
&& (hashSegments[0] === 'pm-with' || hashSegments[0] === 'dm')
&& (hashSegments[2] === 'near' || hashSegments[2] === 'with'))
) {
// TODO: This case is pretty useless in practice, due to basically a
// bug in the webapp: the URL that appears in the location bar for a
// group PM conversation excludes self, so it's unusable for anyone
// else. In particular this will foil you if, say, you try to give
// someone else in the conversation a link to a particular message.
const ids = parsePmOperand(hashSegments[1]);
return pmNarrowFromRecipients(pmKeyRecipientsFromIds(ids, ownUserId));
}
if (
// 'channel' is new in server-9.0; means the same as 'stream'
(hashSegments.length === 4
&& (hashSegments[0] === 'stream' || hashSegments[0] === 'channel')
&& (hashSegments[2] === 'subject' || hashSegments[2] === 'topic'))
|| (hashSegments.length === 6
&& (hashSegments[0] === 'stream' || hashSegments[0] === 'channel')
&& (hashSegments[2] === 'subject' || hashSegments[2] === 'topic')
&& (hashSegments[4] === 'near' || hashSegments[4] === 'with'))
) {
const streamId = parseStreamOperand(hashSegments[1], streamsById, streamsByName);
return streamId != null ? topicNarrow(streamId, parseTopicOperand(hashSegments[3])) : null;
}
if (
hashSegments.length === 2
// 'channel' is new in server-9.0; means the same as 'stream'
&& (hashSegments[0] === 'stream' || hashSegments[0] === 'channel')
) {
const streamId = parseStreamOperand(hashSegments[1], streamsById, streamsByName);
return streamId != null ? streamNarrow(streamId) : null;
}
if (
hashSegments.length === 2
&& hashSegments[0] === 'is'
&& (hashSegments[1] === 'starred'
|| hashSegments[1] === 'mentioned'
|| hashSegments[1] === 'dm' // new in server-7.0; means the same as 'private'
|| hashSegments[1] === 'private')
) {
switch (hashSegments[1]) {
case 'starred':
return specialNarrow('starred');
case 'mentioned':
return specialNarrow('mentioned');
case 'dm':
case 'private':
return specialNarrow('dm');
}
}
return null; // TODO(?) Give HOME_NARROW
};
/**
* From a URL and realm with `isNarrowLink(url, realm) === true`, give
* message_id if the URL has /near/{message_id}, otherwise give null.
*/
export const getNearOperandFromLink = (url: URL, realm: URL): number | null => {
// isNarrowLink() is true, by jsdoc, so this call is OK.
const hashSegments = getHashSegmentsFromNarrowLink(url, realm);
// This and nearOperandIndex can simplify when we rename/repurpose
// getHashSegmentsFromNarrowLink so it gives an array of
// { negated, operator, operand } objects; see TODO there.
const nearOperatorIndex = hashSegments.findIndex(
(str, i) =>
// This is a segment where we expect an operator to be specified.
i % 2 === 0
// The operator is 'near' or 'with' and its meaning is not negated
// (`str` does not start with "-").
//
// Quoting Greg from #5866:
// > Currently the app doesn't interpret the "anchor" meaning of
// > `/near/` links at all (that's #3604) we already effectively
// > give `/near/` links exactly the meaning that the upcoming
// > `/with/` links will have. So to handle the new links, we just
// > need to parse them and then handle them the way we already handle
// > `/near/` links.
// Which makes sense for this legacy codebase.
&& (str === 'near' || str === 'with'),
);
if (nearOperatorIndex < 0) {
return null;
}
// We expect an operand to directly follow its operator.
const nearOperandIndex = nearOperatorIndex + 1;
const nearOperandStr = hashSegments[nearOperandIndex];
// Must look like a message ID
if (!/^[0-9]+$/.test(nearOperandStr)) {
return null;
}
return parseInt(nearOperandStr, 10);
};
export const getStreamTopicUrl = (
realm: URL,
streamId: number,
topic: string,
streamsById: Map<number, Stream>,
): URL => {
const maybe_get_stream_name = id => streamsById.get(id)?.name;
const encodedStreamId = internal_url.encode_stream_id(streamId, maybe_get_stream_name);
const encodedTopic = internal_url.encodeHashComponent(topic);
const path = `#narrow/stream/${encodedStreamId}/topic/${encodedTopic}`;
return new URL(path, realm);
};
export const getStreamUrl = (
realm: URL,
streamId: number,
streamsById: Map<number, Stream>,
): URL => {
const maybe_get_stream_name = id => streamsById.get(streamId)?.name;
const path = `#narrow/stream/${internal_url.encode_stream_id(streamId, maybe_get_stream_name)}`;
return new URL(path, realm);
};
/**
* A /pm-with/ link for a whole PM conversation a message belongs to.
*/
// Based on pm_perma_link in static/js/people.js in the zulip/zulip repo.
// TODO(shared): Share that code.
export const getPmConversationLinkForMessage = (
realm: URL,
message: PmMessage | PmOutbox,
zulipFeatureLevel: number,
): URL => {
const recipientIds = recipientsOfPrivateMessage(message)
.map(r => r.id)
.sort((a, b) => a - b);
const suffix = recipientIds.length >= 3 ? 'group' : zulipFeatureLevel >= 177 ? 'dm' : 'pm';
const slug = `${recipientIds.join(',')}-${suffix}`;
// TODO(server-7.0): Remove FL 177 condition (here and on `suffix`)
const operator = zulipFeatureLevel >= 177 ? 'dm' : 'pm-with';
return new URL(`#narrow/${operator}/${slug}`, realm);
};
/**
* A /near/ link to a given message, as a URL object.
*/
export const getMessageUrl = (
realm: URL,
message: Message | Outbox,
streamsById: Map<number, Stream>,
zulipFeatureLevel: number,
): URL => {
let result = undefined;
// Build the part that points to the message's conversation
if (message.type === 'stream') {
result = getStreamTopicUrl(realm, message.stream_id, message.subject, streamsById);
} else {
result = getPmConversationLinkForMessage(realm, message, zulipFeatureLevel);
}
// then add the part that points to the message.
result.hash += `/near/${message.id}`;
return result;
};
```
|
/content/code_sandbox/src/utils/internalLinks.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 3,160
|
```javascript
// @flow strict-local
/**
* A wrapper around Map, akin to Python's `defaultdict`.
*/
// This could be a subclass of Map instead. That would also mean it gets
// all the handy methods of Map.
//
// The slightly tricky bit is that that would mean it could enter our Redux
// state where the type says simply `Map`. So `replaceRevive` would need to
// handle it, and some picky tests might need adjustment too.
//
// We haven't done that yet mainly because we haven't yet had much of a use
// case for using this outside of small local contexts where we don't need
// the other methods of Map.
export default class DefaultMap<K, V> {
map: Map<K, V> = new Map();
default: () => V;
constructor(default_: () => V) {
this.default = default_;
}
/** Return the value at the given key, creating it if necessary. */
getOrCreate(key: K): V {
let value = this.map.get(key);
if (value === undefined) {
value = this.default();
this.map.set(key, value);
}
return value;
}
}
```
|
/content/code_sandbox/src/utils/DefaultMap.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 255
|
```javascript
// @flow strict-local
import DefaultMap from '../DefaultMap';
describe('DefaultMap', () => {
test('smoke', () => {
const m = new DefaultMap(() => []);
expect([...m.map.entries()].sort()).toEqual([]);
// Create a value.
m.getOrCreate('a').push(1);
expect([...m.map.entries()].sort()).toEqual([['a', [1]]]);
// Different key gets a fresh value.
m.getOrCreate('b').push(2);
// prettier-ignore
expect([...m.map.entries()].sort()).toEqual([['a', [1]], ['b', [2]]]);
// Existing key gets the existing value.
m.getOrCreate('a').push(3);
// prettier-ignore
expect([...m.map.entries()].sort()).toEqual([['a', [1, 3]], ['b', [2]]]);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/DefaultMap-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 194
|
```javascript
/* @flow strict-local */
import { foregroundColorFromBackground, colorHashFromString } from '../color';
describe('foregroundColorFromBackground', () => {
test('returns "black" for light backgrounds', () => {
expect(foregroundColorFromBackground('#ffffff')).toEqual('black');
expect(foregroundColorFromBackground('lightgray')).toEqual('black');
expect(foregroundColorFromBackground('#b0b0b0')).toEqual('black');
});
test('returns "white" for dark backgrounds', () => {
expect(foregroundColorFromBackground('#000000')).toEqual('white');
expect(foregroundColorFromBackground('#333333')).toEqual('white');
expect(foregroundColorFromBackground('#0000f0')).toEqual('white');
});
});
describe('colorHashFromString', () => {
test('returns a 6 digit hex number to use as a color ', () => {
expect(colorHashFromString('')).toHaveLength(7);
expect(colorHashFromString('')).toHaveLength(7);
expect(colorHashFromString('John Doe')).toHaveLength(7);
expect(colorHashFromString('abcdefghijklmnopqrstuvwxyz'.repeat(50))).toHaveLength(7);
});
test('produces the same output for the same input', () => {
const hash1 = colorHashFromString('John Doe');
const hash2 = colorHashFromString('John Doe');
expect(hash1).toEqual(hash2);
});
test('produces different output for similar inputs', () => {
const hash1 = colorHashFromString('John Doe, Juan Prez');
const hash2 = colorHashFromString('John Doe, Jean Dupont');
expect(hash1).not.toEqual(hash2);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/color-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 351
|
```javascript
/* @flow strict-local */
import { objectEntries } from '../flowPonyfill';
/**
* An object `encodeParamsForUrl` can flatten.
*
* In principle the values should be strings; but we include some other
* primitive types for which `toString` is just as good as `JSON.stringify`.
*/
export type UrlParamValue = string | boolean | number;
export type UrlParams = $ReadOnly<{| [string]: UrlParamValue | void |}>;
/**
* Encode parameters as if for the URL query-part submitting an HTML form.
*
* Following the pattern of JSON.stringify, drop (rather than encoding in any
* fashion) parameters whose provided value is `undefined`.
*/
export const encodeParamsForUrl = (params: UrlParams): string =>
objectEntries(params)
/* Filter out entries with `undefined` values, with type-level recognition.
(Flow's core definitions treat `.filter(Boolean)` as a special case. See
path_to_url for more information.) */
.map(([key, value]): ?[string, UrlParamValue] => (value === undefined ? null : [key, value]))
.filter(Boolean)
/* Encode. */
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value.toString())}`)
.join('&');
/**
* Test for an absolute URL, assuming a valid URL.
*
* Specifically, we assume the input is a "valid URL string" as defined by
* the URL Standard:
* path_to_url#url-writing
* and return true just if it's an "absolute-URL-with-fragment string".
*
* If the input is not a valid URL string, the result is unspecified.
*/
export const isUrlAbsolute = (url: string): boolean =>
// True just if the string starts with a "URL-scheme string", then `:`.
// Every "absolute-URL string" must do so.
// Every "relative-URL string" must not do so: either it starts with a
// "path-relative-scheme-less-URL string", or it starts with `/`.
url.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:/) !== null;
/**
* Test for a relative URL string, assuming a valid URL.
*
* Specifically, we assume the input is a "valid URL string" as defined by
* the URL Standard:
* path_to_url#url-writing
* and return true just if it's a "relative-URL-with-fragment string".
*
* If the input is not a valid URL string, the result is unspecified.
*/
export const isUrlRelative = (url: string): boolean => !isUrlAbsolute(url);
/**
* Test for a path-absolute URL string, assuming a valid URL.
*
* Specifically, we assume the input is a "valid URL string" as defined by
* the URL Standard:
* path_to_url#url-writing
* and return true just if it's a "path-absolute-URL string".
*
* This is the kind like "/foo/bar" that keeps the part of the base URL
* before the path, and replaces the rest.
*
* Specifically this is a kind of relative URL string: so when this returns
* true (for a valid URL), `isUrlRelative` will always also return true and
* `isUrlAbsolute` will return false.
*/
export const isUrlPathAbsolute = (url: string): boolean =>
// A "path-absolute URL string" must start with `/` and not `//`.
// On the other hand:
// * a "path-relative scheme-less-URL string" must not start with `/`;
// * the other forms of "relative-URL string" all must start with `//`.
!!url.match(/^\/($|[^\/])/); // eslint-disable-line no-useless-escape
// ESLint says one of these slashes could be written unescaped.
// But that seems like a recipe for confusion, so we escape them both.
/** Just like `new URL`, but on error return undefined instead of throwing. */
export const tryParseUrl = (url: string, base?: string | URL): URL | void => {
try {
return new URL(url, base);
} catch {
return undefined;
}
};
/**
* Test if the given URL is within the given realm.
*/
// This is used in and out of the WebView, so it must work with the native
// URL implementation and also the polyfill we use in React Native land.
export const isUrlOnRealm = (url: URL, realm: URL): boolean => url.origin === realm.origin;
export const getFileExtension = (filename: string): string => filename.split('.').pop();
export const isUrlAnImage = (url: string): boolean =>
['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(getFileExtension(url).toLowerCase());
const mimes = {
jpeg: 'image/jpeg',
jpg: 'image/jpeg',
png: 'image/png',
gif: 'image/gif',
tif: 'image/tiff',
tiff: 'image/tiff',
mov: 'video/quicktime',
};
export const getMimeTypeFromFileExtension = (extension: string): string =>
mimes[extension.toLowerCase()] || 'application/octet-stream';
```
|
/content/code_sandbox/src/utils/url.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,117
|
```javascript
/* @flow strict-local */
import { sleep, BackoffMachine } from '../async';
import { assertUsingFakeTimers } from '../../__tests__/lib/fakeTimers';
describe('BackoffMachine', () => {
beforeAll(() => {
assertUsingFakeTimers();
});
afterEach(() => {
expect(jest.getTimerCount()).toBe(0);
jest.clearAllTimers();
});
const measureWait = async (promise: Promise<void>) => {
const start = Date.now();
jest.runOnlyPendingTimers();
await promise;
return Date.now() - start;
};
test('timeouts are random from zero to 100ms, 200ms, 400ms, 800ms...', async () => {
// This is a randomized test. NUM_TRIALS is chosen so that the failure
// probability < 1e-9. There are 2 * 11 assertions, and each one has a
// failure probability < 1e-12; see below.
const NUM_TRIALS = 100;
const expectedMaxDurations = [100, 200, 400, 800, 1600, 3200, 6400, 10000, 10000, 10000, 10000];
const trialResults: Array<$ReadOnlyArray<number>> = [];
for (let i = 0; i < NUM_TRIALS; i++) {
const resultsForThisTrial = [];
const backoffMachine = new BackoffMachine();
for (let j = 0; j < expectedMaxDurations.length; j++) {
const duration = await measureWait(backoffMachine.wait());
resultsForThisTrial.push(duration);
}
trialResults.push(resultsForThisTrial);
}
expectedMaxDurations.forEach((expectedMax, i) => {
const maxFromAllTrials = Math.max(...trialResults.map(r => r[i]));
const minFromAllTrials = Math.min(...trialResults.map(r => r[i]));
// Each of these assertions has a failure probability of:
// 0.75 ** NUM_TRIALS = 0.75 ** 100 < 1e-12
expect(minFromAllTrials).toBeLessThan(expectedMax * 0.25);
expect(maxFromAllTrials).toBeGreaterThan(expectedMax * 0.75);
});
});
});
const sleepMeasure = async (expectedMs: number) => {
const start = Date.now();
await sleep(expectedMs);
const actualMs = Date.now() - start;
return actualMs;
};
describe('sleep (ideal)', () => {
beforeAll(() => {
assertUsingFakeTimers();
});
afterEach(() => {
// clear any unset timers
expect(jest.getTimerCount()).toBe(0);
jest.clearAllTimers();
});
test('waits for exactly the right number of milliseconds', async () => {
const expectedMs = 1000;
const sleepPromise: Promise<number> = sleepMeasure(expectedMs);
jest.runOnlyPendingTimers();
// If `sleepPromise` hasn't resolved already, it never will; this await will
// hang. In this case, Jest will eventually time out and report failure.
// path_to_url#jestsettimeouttimeout
const actualMs = await sleepPromise;
expect(actualMs).toEqual(expectedMs);
});
});
describe('sleep (real)', () => {
beforeAll(() => {
jest.useRealTimers();
});
test('waits for approximately the right number of milliseconds', async () => {
const expectedMs = 1000;
const actualMs = await sleepMeasure(expectedMs);
// `sleep` should sleep for the specified number of milliseconds (and not,
// for example, that many seconds or microseconds).
expect(actualMs).toBeGreaterThanOrEqual(expectedMs - 1); // []
expect(actualMs).toBeLessThan(10 * expectedMs); // []
// [] The fudge term of -1 in this test is a workaround for a Node.js
// issue, path_to_url This has caused
// actual test flakes; see our issue #4010 for examples.
//
// [] In theory, we can't be sure of this test; the time between the
// specified timeout expiring and a timeslice actually becoming
// available may be arbitrarily long.
//
// In practice, 10x really is enough of a padding factor that it's never
// been an issue, even with real-world timers on shared CI hardware with
// unpredictable loads.
});
});
```
|
/content/code_sandbox/src/utils/__tests__/async-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 992
|
```javascript
// @flow strict-local
import { randString } from '../misc';
import { ZulipVersion } from '../zulipVersion';
import * as eg from '../../__tests__/lib/exampleData';
describe('ZulipVersion.prototype.isAtLeast(otherZulipVersion)', () => {
// if i > j, versions[i][k] > versions[j][l] for all k, l
// if i = j, versions[i][k] = versions[j][l] for all k, l
// if i < j, versions[i][k] < versions[j][l] for all k, l
// (where i, j, k, l are valid indexes)
const versions: $ReadOnlyArray<$ReadOnlyArray<ZulipVersion>> = [
['0.0.0', '', '-dev', '-devasdfjkl;', '-123-g01ab', 'asdfjkl;-dev'],
['0.0.1-dev'],
['0.0.1-rc1'],
['0.0.1-rc1-112-g35959d43c4'],
['0.0.1-rc2'],
['0.0.1-rc3'],
['0.0.1'],
['0.0.2'],
['0.1.0'],
['1.0.0'],
['2.1.0-rc1'],
['2.1.0-rc1-112-g35959d43c4', '2.1.0-rc1-112-g35959d43c4'],
['2.1.0-rc1-113-g3412341234'],
['2.1.0'],
['2.1.0-113-gabcdabcdab'],
['2.1.0-114-gabcdabcdab'],
['2.1.1-50-gd452ad31e0'],
['2.2-dev', '2.2.0-dev'],
[
// nonsense means ignore the rest
'2.2asdf',
'2.2.0',
'2.2.0.0',
'2.2.0.1',
'2.2.0asdfjkl;asdfjkl;as',
'2.2.0asdfjkl;-dev',
'2.2.0asdfjkl;-rc1',
],
].map(equalRawVersions => equalRawVersions.map(r => new ZulipVersion(r)));
for (let i = 0; i < versions.length; i++) {
for (let j = 0; j < versions.length; j++) {
for (let k = 0; k < versions[i].length; k++) {
for (let l = 0; l < versions[j].length; l++) {
const expected = i >= j;
const actual = versions[i][k].isAtLeast(versions[j][l]);
const name =
i >= j
? `${versions[i][k].raw()} is at least ${versions[j][l].raw()}`
: `${versions[j][l].raw()} is at least ${versions[i][k].raw()}`;
test(name, () => {
// Compare versions[i][k] to versions[j][l] for all valid i, j, k, l
expect(actual).toBe(expected);
});
}
}
}
}
});
describe('ZulipVersion.prototype.raw()', () => {
const raw = randString();
test('Returns the same string the instance was constructed with', () => {
expect(new ZulipVersion(raw).raw()).toBe(raw);
});
});
describe('ZulipVersion.prototype.toJSON()', () => {
const rawUnstructured = randString();
const rawStructured = eg.recentZulipVersion.raw();
test('Returns the same string the instance was constructed with', () => {
expect(new ZulipVersion(rawUnstructured).toJSON()).toBe(rawUnstructured);
expect(new ZulipVersion(rawStructured).toJSON()).toBe(rawStructured);
});
});
describe('ZulipVersion.prototype.elements()', () => {
const raw1 = '0.1.0';
test(`new ZulipVersion(${raw1}).elements()`, () => {
expect(new ZulipVersion(raw1).elements()).toStrictEqual({
major: 0,
minor: 1,
patch: 0,
flag: undefined,
numCommits: undefined,
commitId: undefined,
});
});
const raw2 = '2.1.0-rc1-112-g35959d43c4';
test(`new ZulipVersion(${raw2}).elements()`, () => {
expect(new ZulipVersion(raw2).elements()).toStrictEqual({
major: 2,
minor: 1,
patch: 0,
flag: ['rc', 1],
numCommits: 112,
commitId: '35959d43c4',
});
});
});
describe('ZulipVersion.prototype.classify()', () => {
for (const [coarse, fine, raw] of [
['1.9.x', '1.9.1', '1.9.1-23-gabcabcabc'],
['2.1.x', '2.1.3', '2.1.3'],
['3.x', '3.1', '3.1'],
['4.x', '4.0', '4.0'],
]) {
test(raw, () => {
expect(new ZulipVersion(raw).classify()).toStrictEqual({ raw, coarse, fine });
});
}
});
```
|
/content/code_sandbox/src/utils/__tests__/zulipVersion-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,228
|
```javascript
/* @flow strict-local */
import { promiseTimeout, TimeoutError } from '../async';
import { fakeSleep } from '../../__tests__/lib/fakeTimers';
const ONE_MINUTE_MS: number = 1000 * 60;
describe('promiseTimeout', () => {
afterEach(() => {
// clear any unset timers
expect(jest.getTimerCount()).toBe(0);
jest.clearAllTimers();
});
test('If `promise` resolves with `x` before time is up, resolves with `x`', async () => {
const x = Math.random();
const quickPromise = fakeSleep(1).then(() => x);
await expect(promiseTimeout(quickPromise, ONE_MINUTE_MS)).resolves.toBe(x);
jest.runAllTimers();
});
test('If `promise` rejects before time is up, rejects with that reason', async () => {
const x = Math.random();
const quickPromise = (async () => {
await fakeSleep(1);
throw new Error(x.toString());
})();
await expect(promiseTimeout(quickPromise, ONE_MINUTE_MS)).rejects.toThrow(x.toString());
jest.runAllTimers();
});
test('If time is up, throws a TimeoutError', async () => {
const endlessPromise = new Promise((resolve, reject) => {});
const endlessPromiseWithTimeout = promiseTimeout(endlessPromise, ONE_MINUTE_MS);
jest.runAllTimers();
await expect(endlessPromiseWithTimeout).rejects.toThrow(TimeoutError);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/promiseTimeout-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 332
|
```javascript
import deepFreeze from 'deep-freeze';
import { removeItemsFromArray, filterArray, replaceItemInArray } from '../immutability';
describe('removeItemsFromArray', () => {
test('return a new array with items removed, do not mutate input', () => {
const inputArray = deepFreeze([1, 2, 3, 4, 5]);
const itemsToRemove = [4, 5, 6];
const expectedResult = [1, 2, 3];
const result = removeItemsFromArray(inputArray, itemsToRemove);
expect(result).toEqual(expectedResult);
});
test('when no items are removed, return the original array', () => {
const inputArray = deepFreeze([1, 2, 3]);
const itemsToRemove = [4, 5, 6];
const result = removeItemsFromArray(inputArray, itemsToRemove);
expect(result).toBe(inputArray);
});
});
describe('filterArray', () => {
test('filters an array according to given predicate', () => {
const input = [1, 2, 3, 4, 5];
const predicate = x => x % 2 === 0;
const expectedResult = [2, 4];
const result = filterArray(input, predicate);
expect(result).toEqual(expectedResult);
});
test('do not return a new array if no items are filtered', () => {
const input = [2, 4, 6];
const predicate = x => x % 2 === 0;
const result = filterArray(input, predicate);
expect(result).toBe(input);
});
});
describe('replaceItemInArray', () => {
test('replace item by producing a new array', () => {
const input = [1, 2, 3];
const predicate = x => x === 2;
const replaceFunc = x => 'two';
const expectedResult = [1, 'two', 3];
const result = replaceItemInArray(input, predicate, replaceFunc);
expect(result).not.toBe(input);
expect(result).toEqual(expectedResult);
});
test('replace several items if more than one match', () => {
const input = [1, 2, 3, 4, 5];
const predicate = x => x % 2 === 1;
const replaceFunc = x => 'odd';
const expectedResult = ['odd', 2, 'odd', 4, 'odd'];
const result = replaceItemInArray(input, predicate, replaceFunc);
expect(result).not.toBe(input);
expect(result).toEqual(expectedResult);
});
test('if item is not found append it', () => {
const input = [1, 2, 3];
const predicate = x => x === 4;
const replaceFunc = x => 'four';
const expectedResult = [1, 2, 3, 'four'];
const result = replaceItemInArray(input, predicate, replaceFunc);
expect(result).not.toBe(input);
expect(result).toEqual(expectedResult);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/immutability-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 666
|
```javascript
/* @flow strict-local */
import {
normalizeRecipientsAsUserIdsSansMe,
isSameRecipient,
pmKeyRecipientUsersFromIds,
} from '../recipient';
import * as eg from '../../__tests__/lib/exampleData';
import { makeUserId } from '../../api/idTypes';
import { randString } from '../misc';
describe('normalizeRecipientsAsUserIdsSansMe', () => {
test('if only self user ID provided return unmodified', () => {
const recipients = [1].map(makeUserId);
const ownUserId = makeUserId(1);
const expectedResult = '1';
const normalized = normalizeRecipientsAsUserIdsSansMe(recipients, ownUserId);
expect(normalized).toEqual(expectedResult);
});
test('when more than one user IDs normalize but filter out self user ID', () => {
const recipients = [22, 1, 5, 3, 4].map(makeUserId);
const expectedResult = '3,4,5,22';
const ownUserId = makeUserId(1);
const normalized = normalizeRecipientsAsUserIdsSansMe(recipients, ownUserId);
expect(normalized).toEqual(expectedResult);
});
});
describe('pmKeyRecipientUsersFromIds', () => {
const allUsersById = new Map([eg.selfUser, eg.otherUser, eg.thirdUser].map(u => [u.user_id, u]));
const [self, other, third] = [eg.selfUser, eg.otherUser, eg.thirdUser];
// prettier-ignore
for (const [description, users, expectedSet] of [
['self-1:1, self included', [self], [self]],
['self-1:1, self omitted', [ ], [self]],
['other 1:1, self included', [self, other], [other]],
['other 1:1, self included', [ other], [other]],
['group PM, self included', [self, other, third], [other, third]],
['group PM, self included', [ other, third], [other, third]],
]) {
test(`correct on ${description}`, () => {
expect(
pmKeyRecipientUsersFromIds(users.map(u => u.user_id), allUsersById, eg.selfUser.user_id),
).toEqual(expectedSet.sort((a, b) => a.user_id - b.user_id));
});
}
});
describe('isSameRecipient', () => {
test('recipient types are compared first, if they differ then recipients differ', () => {
expect(isSameRecipient(eg.pmMessage(), eg.streamMessage())).toBe(false);
});
// Skipped because we don't currently support this. See comment on implementation.
test.skip('recipients are same for private type if display_recipient match in any order', () => {
const msg1 = eg.pmMessageFromTo(eg.selfUser, [eg.otherUser, eg.thirdUser]);
const msg2 = eg.pmMessageFromTo(eg.selfUser, [eg.thirdUser, eg.otherUser]);
expect(isSameRecipient(msg1, msg2)).toBe(true);
});
test('recipients are same for stream type if display_recipient and subject match', () => {
const topic = randString();
const msg1 = eg.streamMessage({ stream: eg.stream, subject: topic, content: randString() });
const msg2 = eg.streamMessage({ stream: eg.stream, subject: topic, content: randString() });
expect(isSameRecipient(msg1, msg2)).toBe(true);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/recipient-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 773
|
```javascript
import { filterUnreadMessageIds, filterUnreadMessagesInRange } from '../unread';
describe('filterUnreadMessageIds', () => {
test('empty message list has no unread messages', () => {
const messages = [];
const flags = {};
const expectedUnread = [];
const actualUnread = filterUnreadMessageIds(messages, flags);
expect(actualUnread).toEqual(expectedUnread);
});
test('messages with no flags or empty flag array are not read', () => {
const messages = [1, 2, 3];
const flags = {
read: {
3: true,
},
};
const expectedUnread = [1, 2];
const actualUnread = filterUnreadMessageIds(messages, flags);
expect(actualUnread).toEqual(expectedUnread);
});
test('messages are not read if not in flags object, regardless of message property', () => {
const messages = [1];
const flags = {};
const expectedUnread = [1];
const actualUnread = filterUnreadMessageIds(messages, flags);
expect(actualUnread).toEqual(expectedUnread);
});
});
describe('filterUnreadMessagesInRange', () => {
test('if from or to ids are -1 result is empty', () => {
const messages = [{ id: 1 }];
const flags = {};
const expectedUnread = [];
const actualUnread = filterUnreadMessagesInRange(messages, flags, -1, -1);
expect(actualUnread).toEqual(expectedUnread);
});
test('empty message list has no unread messages', () => {
const messages = [];
const flags = {};
const expectedUnread = [];
const actualUnread = filterUnreadMessagesInRange(messages, flags, 1, 5);
expect(actualUnread).toEqual(expectedUnread);
});
test('messages with no flags or empty flag array are not read', () => {
const messages = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }];
const flags = {
read: {
3: true,
},
};
const expectedUnread = [2, 4, 5];
const actualUnread = filterUnreadMessagesInRange(messages, flags, 2, 5);
expect(actualUnread).toEqual(expectedUnread);
});
test('if start is after end no messages are returned', () => {
const messages = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }];
const flags = {};
const expectedUnread = [];
const actualUnread = filterUnreadMessagesInRange(messages, flags, 5, 1);
expect(actualUnread).toEqual(expectedUnread);
});
test('messages in outbox are filtered out', () => {
const messages = [{ id: 1 }, { id: 2 }, { id: 34567, isOutbox: true }];
const flags = {};
const expectedUnread = [1, 2];
const actualUnread = filterUnreadMessagesInRange(messages, flags, 1, Number.MAX_SAFE_INTEGER);
expect(actualUnread).toEqual(expectedUnread);
});
test('messages are not read if not in flags object, regardless of message property', () => {
const messages = [{ id: 1 }];
const flags = {};
const expectedUnread = [1];
const actualUnread = filterUnreadMessagesInRange(messages, flags, 1, 5);
expect(actualUnread).toEqual(expectedUnread);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/unread-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 804
|
```javascript
/* @flow strict-local */
import {
HOME_NARROW,
isHomeNarrow,
pm1to1NarrowFromUser,
is1to1PmNarrow,
pmNarrowFromUsersUnsafe,
isSpecialNarrow,
ALL_PRIVATE_NARROW,
streamNarrow,
isStreamNarrow,
topicNarrow,
isTopicNarrow,
SEARCH_NARROW,
isSearchNarrow,
isPmNarrow,
isMessageInNarrow,
isStreamOrTopicNarrow,
getNarrowsForMessage,
getNarrowForReply,
parseNarrow,
STARRED_NARROW,
MENTIONED_NARROW,
keyFromNarrow,
topicOfNarrow,
caseNarrowPartial,
streamIdOfNarrow,
} from '../narrow';
import type { Narrow, Message } from '../../types';
import * as eg from '../../__tests__/lib/exampleData';
describe('HOME_NARROW', () => {
test('is a home narrow', () => {
expect(isHomeNarrow(HOME_NARROW)).toBe(true);
});
});
describe('pm1to1NarrowFromUser', () => {
test('produces a 1:1 narrow', () => {
const narrow = pm1to1NarrowFromUser(eg.otherUser);
expect(is1to1PmNarrow(narrow)).toBeTrue();
expect(caseNarrowPartial(narrow, { pm: ids => ids })).toEqual([eg.otherUser.user_id]);
});
test('if operator is "pm-with" and only one email, then it is a private narrow', () => {
expect(is1to1PmNarrow(HOME_NARROW)).toBe(false);
expect(is1to1PmNarrow(pm1to1NarrowFromUser(eg.otherUser))).toBe(true);
});
});
describe('isPmNarrow', () => {
test('a private or group narrow is any "pm-with" narrow', () => {
expect(isPmNarrow(undefined)).toBe(false);
expect(isPmNarrow(HOME_NARROW)).toBe(false);
expect(isPmNarrow(pm1to1NarrowFromUser(eg.otherUser))).toBe(true);
expect(isPmNarrow(pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]))).toBe(true);
});
});
describe('isStreamOrTopicNarrow', () => {
test('check for stream or topic narrow', () => {
expect(isStreamOrTopicNarrow(undefined)).toBe(false);
expect(isStreamOrTopicNarrow(streamNarrow(eg.stream.stream_id))).toBe(true);
expect(isStreamOrTopicNarrow(topicNarrow(eg.stream.stream_id, 'some topic'))).toBe(true);
expect(isStreamOrTopicNarrow(HOME_NARROW)).toBe(false);
expect(isStreamOrTopicNarrow(pm1to1NarrowFromUser(eg.otherUser))).toBe(false);
expect(isStreamOrTopicNarrow(pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]))).toBe(
false,
);
expect(isStreamOrTopicNarrow(STARRED_NARROW)).toBe(false);
});
});
describe('specialNarrow', () => {
test('only narrowing with the "is" operator is special narrow', () => {
expect(isSpecialNarrow(undefined)).toBe(false);
expect(isSpecialNarrow(HOME_NARROW)).toBe(false);
expect(isSpecialNarrow(streamNarrow(eg.stream.stream_id))).toBe(false);
expect(isSpecialNarrow(STARRED_NARROW)).toBe(true);
});
});
describe('streamNarrow', () => {
test('narrows to messages from a specific stream', () => {
const narrow = streamNarrow(eg.stream.stream_id);
expect(isStreamNarrow(narrow)).toBeTrue();
expect(streamIdOfNarrow(narrow)).toEqual(eg.stream.stream_id);
});
test('only narrow with operator of "stream" is a stream narrow', () => {
expect(isStreamNarrow(undefined)).toBe(false);
expect(isStreamNarrow(HOME_NARROW)).toBe(false);
expect(isStreamNarrow(streamNarrow(eg.stream.stream_id))).toBe(true);
});
});
describe('topicNarrow', () => {
test('narrows to a specific topic within a specified stream', () => {
const narrow = topicNarrow(eg.stream.stream_id, 'some topic');
expect(isTopicNarrow(narrow)).toBeTrue();
expect(streamIdOfNarrow(narrow)).toEqual(eg.stream.stream_id);
expect(topicOfNarrow(narrow)).toEqual('some topic');
});
test('only narrow with two items, one for stream, one for topic is a topic narrow', () => {
expect(isTopicNarrow(undefined)).toBe(false);
expect(isTopicNarrow(HOME_NARROW)).toBe(false);
expect(isTopicNarrow(topicNarrow(eg.stream.stream_id, 'some topic'))).toBe(true);
});
});
describe('SEARCH_NARROW', () => {
test('narrow with "search" operand is a search narrow', () => {
expect(isSearchNarrow(undefined)).toBe(false);
expect(isSearchNarrow(HOME_NARROW)).toBe(false);
expect(isSearchNarrow(SEARCH_NARROW('some query'))).toBe(true);
});
});
describe('isMessageInNarrow', () => {
const otherStream = eg.makeStream();
// prettier-ignore
for (const [narrowDescription, narrow, cases] of [
['all-messages ("home") narrow', HOME_NARROW, [
['a message', true, eg.streamMessage()],
]],
['whole-stream narrow', streamNarrow(eg.stream.stream_id), [
['matching stream message', true, eg.streamMessage()],
['other-stream message', false, eg.streamMessage({ stream: otherStream })],
['PM', false, eg.pmMessage()],
]],
['stream conversation', topicNarrow(eg.stream.stream_id, 'cabbages'), [
['matching message', true, eg.streamMessage({ subject: 'cabbages' })],
['message in same stream but other topic', false, eg.streamMessage({ subject: 'kings' })],
['other-stream message', false, eg.streamMessage({ stream: otherStream })],
['PM', false, eg.pmMessage()],
]],
['1:1 PM conversation, non-self', pm1to1NarrowFromUser(eg.otherUser), [
['matching PM, inbound', true, eg.pmMessageFromTo(eg.otherUser, [eg.selfUser])],
['matching PM, outbound', true, eg.pmMessageFromTo(eg.selfUser, [eg.otherUser])],
['self-1:1 message', false, eg.pmMessageFromTo(eg.selfUser, [])],
['group-PM including this user, inbound', false, eg.pmMessageFromTo(eg.otherUser, [eg.selfUser, eg.thirdUser])],
['group-PM including this user, outbound', false, eg.pmMessageFromTo(eg.selfUser, [eg.otherUser, eg.thirdUser])],
['stream message', false, eg.streamMessage()],
]],
['self-1:1 conversation', pm1to1NarrowFromUser(eg.selfUser), [
['self-1:1 message', true, eg.pmMessageFromTo(eg.selfUser, [])],
['other 1:1 message, inbound', false, eg.pmMessageFromTo(eg.otherUser, [eg.selfUser])],
['other 1:1 message, outbound', false, eg.pmMessageFromTo(eg.selfUser, [eg.otherUser])],
['group-PM, inbound', false, eg.pmMessageFromTo(eg.otherUser, [eg.selfUser, eg.thirdUser])],
['group-PM, outbound', false, eg.pmMessageFromTo(eg.selfUser, [eg.otherUser, eg.thirdUser])],
['stream message', false, eg.streamMessage()],
]],
['group-PM conversation', pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]), [
['matching group-PM, inbound', true, eg.pmMessageFromTo(eg.otherUser, [eg.selfUser, eg.thirdUser])],
['matching group-PM, outbound', true, eg.pmMessageFromTo(eg.selfUser, [eg.otherUser, eg.thirdUser])],
['1:1 within group, inbound', false, eg.pmMessageFromTo(eg.otherUser, [eg.selfUser])],
['1:1 within group, outbound', false, eg.pmMessageFromTo(eg.selfUser, [eg.otherUser])],
['self-1:1 message', false, eg.pmMessageFromTo(eg.selfUser, [])],
['stream message', false, eg.streamMessage()],
]],
['group-PM conversation, including self', pmNarrowFromUsersUnsafe([eg.selfUser, eg.otherUser, eg.thirdUser]), [
['matching group-PM, inbound', true, eg.pmMessageFromTo(eg.otherUser, [eg.selfUser, eg.thirdUser])],
['matching group-PM, outbound', true, eg.pmMessageFromTo(eg.selfUser, [eg.otherUser, eg.thirdUser])],
['1:1 within group, inbound', false, eg.pmMessageFromTo(eg.otherUser, [eg.selfUser])],
['1:1 within group, outbound', false, eg.pmMessageFromTo(eg.selfUser, [eg.otherUser])],
['self-1:1 message', false, eg.pmMessageFromTo(eg.selfUser, [])],
['stream message', false, eg.streamMessage()],
]],
['all-PMs narrow', ALL_PRIVATE_NARROW, [
['a PM', true, eg.pmMessage()],
['stream message', false, eg.streamMessage()],
]],
['is:mentioned', MENTIONED_NARROW, [
['w/ mentioned flag', true, eg.streamMessage({ flags: ['mentioned'] })],
['w/ wildcard_mentioned flag', true, eg.streamMessage({ flags: ['wildcard_mentioned'] })],
['w/o flags', false, eg.streamMessage()],
]],
['is:starred', STARRED_NARROW, [
['w/ starred flag', true, eg.streamMessage({ flags: ['starred'] })],
['w/o flags', false, eg.streamMessage()],
]],
]) {
describe(narrowDescription, () => {
for (const [messageDescription, expected, message] of cases) {
test(`${expected ? 'contains' : 'excludes'} ${messageDescription}`, () => {
expect(
isMessageInNarrow(message, message.flags ?? [], narrow, eg.selfUser.user_id),
).toBe(expected);
});
}
});
}
});
describe('getNarrowsForMessage', () => {
/**
* Helper function that tests one Message.
*
* In addition to the expected output the case declares, also expect
* MENTIONED_NARROW or STARRED_NARROW if those flags are present.
*/
// Tell ESLint to recognize `checkCase` as a helper function that
// runs assertions.
/* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "checkCase"] }] */
const checkCase = (c: {| label: string, message: Message, expectedNarrows: Narrow[] |}) => {
test(`${c.label}; no flags`, () => {
expect(getNarrowsForMessage(c.message, eg.selfUser.user_id, [])).toIncludeSameMembers(
c.expectedNarrows,
);
});
test(`${c.label}; starred`, () => {
expect(
getNarrowsForMessage(c.message, eg.selfUser.user_id, ['starred']),
).toIncludeSameMembers([...c.expectedNarrows, STARRED_NARROW]);
});
test(`${c.label}; mentioned`, () => {
expect(
getNarrowsForMessage(c.message, eg.selfUser.user_id, ['mentioned']),
).toIncludeSameMembers([...c.expectedNarrows, MENTIONED_NARROW]);
});
test(`${c.label}; wildcard_mentioned`, () => {
expect(
getNarrowsForMessage(c.message, eg.selfUser.user_id, ['mentioned']),
).toIncludeSameMembers([...c.expectedNarrows, MENTIONED_NARROW]);
});
test(`${c.label}; starred, mentioned, and wildcard_mentioned`, () => {
expect(
getNarrowsForMessage(c.message, eg.selfUser.user_id, [
'starred',
'mentioned',
'wildcard_mentioned',
]),
).toIncludeSameMembers([...c.expectedNarrows, STARRED_NARROW, MENTIONED_NARROW]);
});
};
const cases = [
{
label: "Message in a stream with topic 'myTopic'",
message: {
...eg.streamMessage({ stream: eg.stream }),
subject: 'myTopic',
},
expectedNarrows: [
HOME_NARROW,
streamNarrow(eg.stream.stream_id),
topicNarrow(eg.stream.stream_id, 'myTopic'),
],
},
{
// If we find that `subject` is sometimes the empty string and
// that needs to be treated as a special case, this case should
// be edited.
//
// It's not currently clear that we'd ever get a stream message
// with the empty string for `subject` from the server.
//
// We don't store outbox messages with the empty string for
// `subject`; if the topic input is left blank, we put down
// `apiConstants.kNoTopicTopic` for `subject`.
label: 'Message in a stream with empty-string topic',
message: {
...eg.streamMessage({ stream: eg.stream }),
subject: '',
},
expectedNarrows: [
HOME_NARROW,
streamNarrow(eg.stream.stream_id),
topicNarrow(eg.stream.stream_id, ''),
],
},
{
label: 'PM message with one person',
message: eg.pmMessage(),
expectedNarrows: [HOME_NARROW, ALL_PRIVATE_NARROW, pm1to1NarrowFromUser(eg.otherUser)],
},
{
label: 'Group PM message',
message: eg.pmMessageFromTo(eg.otherUser, [eg.selfUser, eg.thirdUser]),
expectedNarrows: [
HOME_NARROW,
ALL_PRIVATE_NARROW,
pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]),
],
},
];
cases.forEach(c => {
checkCase(c);
});
});
describe('getNarrowForReply', () => {
test('for self-PM, returns self-1:1 narrow', () => {
expect(getNarrowForReply(eg.pmMessageFromTo(eg.selfUser, []), eg.selfUser.user_id)).toEqual(
pm1to1NarrowFromUser(eg.selfUser),
);
});
test('for 1:1 PM, returns a 1:1 PM narrow', () => {
const message = eg.pmMessage();
const expectedNarrow = pm1to1NarrowFromUser(eg.otherUser);
const actualNarrow = getNarrowForReply(message, eg.selfUser.user_id);
expect(actualNarrow).toEqual(expectedNarrow);
});
test('for group PM, returns a group PM narrow', () => {
const message = eg.pmMessageFromTo(eg.otherUser, [eg.selfUser, eg.thirdUser]);
const expectedNarrow = pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]);
const actualNarrow = getNarrowForReply(message, eg.selfUser.user_id);
expect(actualNarrow).toEqual(expectedNarrow);
});
test('for stream message with nonempty topic, returns a topic narrow', () => {
const message = eg.streamMessage();
const expectedNarrow = topicNarrow(eg.stream.stream_id, message.subject);
const actualNarrow = getNarrowForReply(message, eg.selfUser.user_id);
expect(actualNarrow).toEqual(expectedNarrow);
});
});
describe('keyFromNarrow+parseNarrow', () => {
const baseNarrows = [
['whole stream', streamNarrow(eg.stream.stream_id)],
['stream conversation', topicNarrow(eg.stream.stream_id, 'a topic')],
['1:1 PM conversation, non-self', pm1to1NarrowFromUser(eg.otherUser)],
['self-1:1 conversation', pm1to1NarrowFromUser(eg.selfUser)],
['group-PM conversation', pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser])],
['all-messages ("home")', HOME_NARROW],
['is:starred', STARRED_NARROW],
['is:mentioned', MENTIONED_NARROW],
['all-PMs', ALL_PRIVATE_NARROW],
['search narrow', SEARCH_NARROW('a query')],
];
// The only character not allowed in Zulip stream names is '\x00'.
// (See `check_stream_name` in zulip.git:zerver/lib/streams.py.)
// Try approximately everything else.
const diverseCharacters = eg.diverseCharacters.replace(/\x00/g, '');
const htmlEntities = 'h & t & &lquo;ml"';
const diverseCharactersStream = eg.makeStream({ name: diverseCharacters });
const htmlEntitiesStream = eg.makeStream({ name: htmlEntities });
const awkwardNarrows = [
['whole stream about awkward characters', streamNarrow(diverseCharactersStream.stream_id)],
['whole stream about HTML entities', streamNarrow(htmlEntitiesStream.stream_id)],
[
'stream conversation about awkward characters',
topicNarrow(diverseCharactersStream.stream_id, `regarding ${diverseCharacters}`),
],
[
'stream conversation about HTML entities',
topicNarrow(htmlEntitiesStream.stream_id, `regarding ${htmlEntities}`),
],
['search narrow for awkward characters', SEARCH_NARROW(diverseCharacters)],
['search narrow for HTML entities', SEARCH_NARROW(htmlEntities)],
];
describe('round-trips', () => {
for (const [description, narrow] of [...baseNarrows, ...awkwardNarrows]) {
test(description, () => {
expect(parseNarrow(keyFromNarrow(narrow))).toEqual(narrow);
});
}
});
});
```
|
/content/code_sandbox/src/utils/__tests__/narrow-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 4,054
|
```javascript
import { shortTime, shortDate, longDate, daysInDate, humanDate } from '../date';
describe('Timezones (for test environment only)', () => {
test('Timezone has been set to UTC, unless on Windows', () => {
expect(
new Date().getTimezoneOffset() === 0
// 'win32' is the only possible value that would indicate Windows:
// path_to_url#narrow/stream/243-mobile-team/topic/Snapshot.20tests/near/1167560
|| process.platform === 'win32',
).toBe(true);
});
});
describe('shortTime', () => {
test('returns only hour and minutes', () => {
const date = new Date(Date.UTC(2000, 0, 1, 20, 10));
expect(shortTime(date)).toBe('8:10 PM');
});
test('returns as 24hrs time format, when true passed as second parameter', () => {
const date = new Date(Date.UTC(2000, 0, 1, 20, 10));
expect(shortTime(date, true)).toBe('20:10');
});
});
describe('shortDate', () => {
test('returns month and day, no year', () => {
const date = new Date(2000, 0, 1, 20, 10);
expect(shortDate(date)).toBe('Jan 1');
});
});
describe('longDate', () => {
test('returns month, day and year', () => {
const date = new Date(2000, 0, 1, 20, 10);
expect(longDate(date)).toBe('Jan 1, 2000');
});
});
describe('daysInDate', () => {
test('determines the days in a Date', () => {
expect(daysInDate(Date.UTC(1970, 0, 1, 2, 0))).toBe(0);
expect(daysInDate(Date.UTC(2000, 0, 1))).toBe(10957);
});
test('consecutive days differ one day', () => {
const date1 = new Date(2000, 0, 1);
const date2 = new Date(2000, 0, 2);
const diff = daysInDate(date2) - daysInDate(date1);
expect(diff).toBe(1);
});
});
describe('humanDate', () => {
test('if date is today, return "Today"', () => {
expect(humanDate(new Date())).toBe('Today');
});
test('if date is yesterday, return "Yesterday"', () => {
const date = new Date();
date.setDate(date.getDate() - 1);
expect(humanDate(date)).toBe('Yesterday');
});
test('if date is any other day than today and yesterday, return formatted date', () => {
expect(humanDate(new Date(2000, 0, 1))).toBe('Jan 1, 2000');
});
});
```
|
/content/code_sandbox/src/utils/__tests__/date-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 653
|
```javascript
/* @flow strict-local */
// $FlowFixMe[untyped-import]
import md5 from 'blueimp-md5';
import {
AvatarURL,
GravatarURL,
FallbackAvatarURL,
UploadedAvatarURL,
DEFAULT_UPLOAD_SIZE_PX,
MEDIUM_UPLOAD_SIZE_PX,
} from '../avatar';
import * as eg from '../../__tests__/lib/exampleData';
describe('AvatarURL', () => {
describe('fromUserOrBotData', () => {
const user = eg.makeUser();
const { email, user_id: userId } = user;
const realm = eg.realm;
test('gives a `FallbackAvatarURL` if `rawAvatarURL` is undefined', () => {
const rawAvatarUrl = undefined;
expect(AvatarURL.fromUserOrBotData({ rawAvatarUrl, userId, email, realm })).toBeInstanceOf(
FallbackAvatarURL,
);
});
test('gives a `GravatarURL` if `rawAvatarURL` is null', () => {
const rawAvatarUrl = null;
expect(AvatarURL.fromUserOrBotData({ rawAvatarUrl, userId, email, realm })).toBeInstanceOf(
GravatarURL,
);
});
test('gives a `GravatarURL` if `rawAvatarURL` is a URL string on Gravatar origin', () => {
const rawAvatarUrl =
'path_to_url
expect(AvatarURL.fromUserOrBotData({ rawAvatarUrl, userId, email, realm })).toBeInstanceOf(
GravatarURL,
);
});
test('gives an `UploadedAvatarURL` if `rawAvatarURL` is a non-Gravatar absolute URL string', () => {
const rawAvatarUrl =
'path_to_url
expect(AvatarURL.fromUserOrBotData({ rawAvatarUrl, userId, email, realm })).toBeInstanceOf(
UploadedAvatarURL,
);
});
test('gives an `UploadedAvatarURL` if `rawAvatarURL` is a relative URL string', () => {
const rawAvatarUrl =
'/user_avatars/2/08fb6d007eb10a56efee1d64760fbeb6111c4352.png?x=x&version=2';
expect(AvatarURL.fromUserOrBotData({ rawAvatarUrl, userId, email, realm })).toBeInstanceOf(
UploadedAvatarURL,
);
});
});
});
const SIZES_TO_TEST = [24, 32, 48, 80, 200, DEFAULT_UPLOAD_SIZE_PX, MEDIUM_UPLOAD_SIZE_PX];
const SIZES_OVER_DEFAULT = SIZES_TO_TEST.filter(s => s > DEFAULT_UPLOAD_SIZE_PX);
const SIZES_AT_MOST_DEFAULT = SIZES_TO_TEST.filter(s => s <= DEFAULT_UPLOAD_SIZE_PX);
describe('GravatarURL', () => {
test('serializes/deserializes correctly', () => {
const instance = GravatarURL.validateAndConstructInstance({ email: eg.selfUser.email });
const roundTripped = GravatarURL.deserialize(GravatarURL.serialize(instance));
SIZES_TO_TEST.forEach(size => {
expect(instance.get(size).toString()).toEqual(roundTripped.get(size).toString());
});
});
test('lowercases email address before hashing', () => {
const email = 'uNuSuAlCaPs@example.com';
const instance = GravatarURL.validateAndConstructInstance({ email });
SIZES_TO_TEST.forEach(size => {
expect(instance.get(size).toString()).toContain(md5('unusualcaps@example.com'));
});
});
test('uses URL from server, if provided', () => {
const email = 'user13313@chat.zulip.org';
const urlFromServer =
'path_to_url
const instance = GravatarURL.validateAndConstructInstance({
email,
urlFromServer,
});
SIZES_TO_TEST.forEach(size => {
const clonedUrlOfSize = new URL(instance.get(size).toString());
const clonedUrlFromServer = new URL(urlFromServer);
clonedUrlFromServer.searchParams.delete('s');
clonedUrlOfSize.searchParams.delete('s');
// `urlFromServer` should equal the result for this size, modulo
// the actual size param.
expect(clonedUrlOfSize.toString()).toEqual(clonedUrlFromServer.toString());
});
});
test('produces corresponding URLs for all sizes', () => {
const instance = GravatarURL.validateAndConstructInstance({ email: eg.selfUser.email });
SIZES_TO_TEST.forEach(size => {
expect(instance.get(size).toString()).toContain(`s=${size.toString()}`);
});
});
});
describe('UploadedAvatarURL', () => {
test('serializes/deserializes correctly', () => {
const instance = UploadedAvatarURL.validateAndConstructInstance({
realm: eg.realm,
absoluteOrRelativeUrl:
'path_to_url
});
const roundTripped = UploadedAvatarURL.deserialize(UploadedAvatarURL.serialize(instance));
SIZES_TO_TEST.forEach(size => {
expect(instance.get(size).toString()).toEqual(roundTripped.get(size).toString());
});
});
test('if a relative URL, gives a URL on the given realm', () => {
const instance = UploadedAvatarURL.validateAndConstructInstance({
realm: new URL('path_to_url
absoluteOrRelativeUrl:
'/user_avatars/2/e35cdbc4771c5e4b94e705bf6ff7cca7fa1efcae.png?x=x&version=2',
});
SIZES_TO_TEST.forEach(size => {
const result = instance.get(size).toString();
expect(
result
=== 'path_to_url
|| result
=== 'path_to_url
).toBeTrue();
});
});
test('s3 uploads: appends -medum.png for sizes over default', () => {
const instance = UploadedAvatarURL.validateAndConstructInstance({
realm: new URL('path_to_url
absoluteOrRelativeUrl:
'path_to_url
});
SIZES_OVER_DEFAULT.forEach(size => {
expect(instance.get(size).toString()).toEqual(
'path_to_url
);
});
SIZES_AT_MOST_DEFAULT.forEach(size => {
expect(instance.get(size).toString()).toEqual(
'path_to_url
);
});
});
test('local uploads: converts *.png to *-medium.png for sizes over default', () => {
const realm = new URL('path_to_url
const instance = UploadedAvatarURL.validateAndConstructInstance({
realm,
absoluteOrRelativeUrl:
'/user_avatars/2/e35cdbc4771c5e4b94e705bf6ff7cca7fa1efcae.png?x=x&version=2',
});
SIZES_OVER_DEFAULT.forEach(size => {
expect(instance.get(size).toString()).toEqual(
'path_to_url
);
});
SIZES_AT_MOST_DEFAULT.forEach(size => {
expect(instance.get(size).toString()).toEqual(
'path_to_url
);
});
});
});
describe('FallbackAvatarURL', () => {
test('serializes/deserializes correctly', () => {
const instance = FallbackAvatarURL.validateAndConstructInstance({
realm: eg.realm,
userId: eg.selfUser.user_id,
});
const roundTripped = FallbackAvatarURL.deserialize(FallbackAvatarURL.serialize(instance));
SIZES_TO_TEST.forEach(size => {
expect(instance.get(size).toString()).toEqual(roundTripped.get(size).toString());
});
});
test('gives the `/avatar/{user_id}` URL, on the provided realm', () => {
const userId = eg.selfUser.user_id;
const instance = FallbackAvatarURL.validateAndConstructInstance({
realm: new URL('path_to_url
userId,
});
SIZES_OVER_DEFAULT.forEach(size => {
expect(instance.get(size).toString()).toEqual(
`path_to_url{userId.toString()}/medium`,
);
});
SIZES_AT_MOST_DEFAULT.forEach(size => {
expect(instance.get(size).toString()).toEqual(
`path_to_url{userId.toString()}`,
);
});
});
});
```
|
/content/code_sandbox/src/utils/__tests__/avatar-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,741
|
```javascript
/* @flow strict-local */
import {
base64ToHex,
hexToBase64,
hexToAscii,
asciiToHex,
xorHexStrings,
base64Utf8Encode,
} from '../encoding';
describe('base64ToHex', () => {
test('correctly converts a base64 string to a hex string', () => {
const hex = your_sha256_hash;
const base64 = 'qDSKk6g0k4rzE0gSTSOSEjGS0jq0XGMJLqNTvf4jedw=';
expect(base64ToHex(base64)).toBe(hex);
});
});
describe('hexToBase64', () => {
test('correctly converts a hex string to a base64 string', () => {
const hex = your_sha256_hash;
const base64 = 'qDSKk6g0k4rzE0gSTSOSEjGS0jq0XGMJLqNTvf4jedw=';
expect(hexToBase64(hex)).toBe(base64);
});
});
describe('xorHexStrings', () => {
test('correctly XORs two hex strings of the same length', () => {
const hex1 = your_sha256_hash;
const hex2 = your_sha256_hash;
const encoded = xorHexStrings(hex1, hex2);
expect(xorHexStrings(encoded, hex1)).toBe(hex2);
expect(xorHexStrings(encoded, hex2)).toBe(hex1);
});
test('throws an error if inputs differ in length', () => {
const hex1 = your_sha256_hash;
const hex2 = 'FEA3914A39410903458238420142388DABEE932FE021CD23C024D324EEEEEEE';
expect(() => xorHexStrings(hex1, hex2)).toThrow();
});
});
describe('hexToAscii', () => {
test('correctly converts a hex string to an ASCII encoded string', () => {
const ascii = 'Thus spoke Zarathustra.';
const hex = '546875732073706F6B65205A617261746875737472612E';
expect(hexToAscii(hex)).toBe(ascii);
});
});
describe('asciiToHex', () => {
test('correctly converts an ASCII encoded string to a hex string', () => {
const ascii = 'Thus spoke Zarathustra.';
const hex = '546875732073706F6B65205A617261746875737472612E';
expect(asciiToHex(ascii)).toBe(hex);
});
});
describe('base64Utf8Encode', () => {
test('can handle an empty string', () => {
const text = '';
const expected = '';
const result = base64Utf8Encode(text);
expect(result).toBe(expected);
});
test('supports Unicode characters outside the BMP', () => {
const text = '';
const expected = '8J+Yh/CfmIg=';
const result = base64Utf8Encode(text);
expect(result).toBe(expected);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/encoding-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 664
|
```javascript
/* @flow strict-local */
import invariant from 'invariant';
// Tell ESLint to recognize `expectStream` as a helper function that
// runs assertions.
/* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "check", "expectStream"] }] */
import type { Stream } from '../../types';
import {
streamNarrow,
topicNarrow,
pmNarrowFromUsersUnsafe,
STARRED_NARROW,
isPmNarrow,
isStreamNarrow,
isTopicNarrow,
isSpecialNarrow,
ALL_PRIVATE_NARROW,
MENTIONED_NARROW,
} from '../narrow';
import {
isNarrowLink,
getNarrowFromNarrowLink,
getNearOperandFromLink,
decodeHashComponent,
} from '../internalLinks';
import * as eg from '../../__tests__/lib/exampleData';
import { isUrlRelative } from '../url';
import { getStreamsById, getStreamsByName } from '../../subscriptions/subscriptionSelectors';
import { getOwnUserId } from '../../users/userSelectors';
import type { Narrow } from '../narrow';
const realm = new URL('path_to_url
const urlOnRealm = relativeUrl => {
invariant(
isUrlRelative(relativeUrl),
'For absolute URLs, just use the one-argument `new URL()`.',
);
return new URL(relativeUrl, realm);
};
describe('isNarrowLink', () => {
const cases: $ReadOnlyArray<[boolean, string, URL] | [boolean, string, URL, URL]> = [
[true, 'legacy: stream name, no ID', urlOnRealm('#narrow/stream/jest')],
[true, 'legacy: stream name, no ID, topic', urlOnRealm('#narrow/stream/jest/topic/topic1')],
[true, 'with numeric channel ID', urlOnRealm('#narrow/channel/123-jest')],
[true, 'with numeric channel ID (old operator)', urlOnRealm('#narrow/stream/123-jest')],
[
true,
'with numeric channel ID and topic',
urlOnRealm('#narrow/channel/123-jest/topic/topic1'),
],
[
true,
'with numeric channel ID (old operator) and topic',
urlOnRealm('#narrow/stream/123-jest/topic/topic1'),
],
[true, 'with numeric pm user IDs (new operator)', urlOnRealm('#narrow/dm/123-mark')],
[true, 'with numeric pm user IDs (old operator)', urlOnRealm('#narrow/pm-with/123-mark')],
[false, 'wrong fragment', urlOnRealm('#nope')],
[false, 'wrong path', urlOnRealm('/user_uploads/#narrow/channel/jest')],
[false, 'wrong domain', new URL('path_to_url#narrow/channel/jest')],
[false, '#narrowly', urlOnRealm('#narrowly/channel/jest')],
[false, 'double slash', new URL(`${realm.origin}//#narrow/channel/jest`)],
[false, 'triple slash', new URL(`${realm.origin}///#narrow/channel/jest`)],
[
true,
'with port',
new URL('#narrow/channel/jest', 'path_to_url
new URL('path_to_url
],
// This one fails because our polyfilled URL implementation has IDNA stripped out.
// [
// true,
// 'same domain, punycoded host',
// new URL('path_to_url#narrow/channel/jest'),
// new URL('path_to_url/'),
// ], // FAILS
[
true,
'punycodable host',
new URL('#narrow/channel/jest', 'path_to_url/'),
new URL('path_to_url/'),
],
// This one fails because our polyfilled URL implementation has IDNA stripped out.
// [
// true,
// 'same domain, IDNA-mappable',
// new URL('https://m./#narrow/channel/jest'),
// new URL('path_to_url
// ], // FAILS
[
true,
'ipv4 address',
new URL('#narrow/channel/jest', 'path_to_url
new URL('path_to_url
],
// This one fails because our polyfilled URL implementation has IDNA stripped out.
// [
// true,
// 'same IPv4 address, IDNA-mappable',
// new URL('http:///#narrow/channel/jest'),
// new URL('path_to_url
// ], // FAILS
// TODO: Add tests for IPv6.
// These examples may seem weird, but a previous version accepted most of them.
[
false,
'wrong domain, realm-like path, narrow-like fragment',
// This one, except possibly the fragment, is a 100% realistic link
// for innocent normal use. The buggy old version narrowly avoided
// accepting it... but would accept all the variations below.
new URL(`path_to_url{urlOnRealm('#narrow/channel/jest').toString()}`),
],
[
false,
'odd scheme, wrong domain, realm-like path, narrow-like fragment',
new URL(`ftp://web.archive.org/web/*/${urlOnRealm('#narrow/channel/jest').toString()}`),
],
[
false,
'same domain, realm-like path, narrow-like fragment',
urlOnRealm(`web/*/${urlOnRealm('#narrow/channel/jest').toString()}`),
],
];
/* $FlowFixMe[invalid-tuple-index]:
realm_ is URL | void, but complains of out-of-bounds access */
for (const [expected, description, url, realm_] of cases) {
test(`${expected ? 'accept' : 'reject'} ${description}: ${url.toString()}`, () => {
expect(isNarrowLink(url, realm_ ?? realm)).toBe(expected);
});
}
});
// TODO: Combine / dedupe with "getNarrowFromNarrowLink (part 2)" tests, below
describe('getNarrowFromNarrowLink (part 1)', () => {
const mkCheck = (narrowExpectation: (Narrow => boolean) | null) => hash => {
const streams = [
eg.makeStream({ stream_id: 1, name: 'jest' }),
eg.makeStream({ stream_id: 2, name: 'stream' }),
eg.makeStream({ stream_id: 3, name: 'topic' }),
eg.makeStream({ stream_id: 4, name: 'mobile' }),
];
const baseState = eg.reduxStatePlus({ streams });
const narrow = getNarrowFromNarrowLink(
new URL(hash, realm),
realm,
getStreamsById(baseState),
getStreamsByName(baseState),
getOwnUserId(baseState),
);
if (typeof narrowExpectation === 'function') {
test(`${hash} - ${narrowExpectation.name} should be true`, () => {
expect(narrow && narrowExpectation(narrow)).toBeTrue();
});
} else {
test(`${hash} - should return null`, () => {
expect(narrow).toBeNull();
});
}
};
describe('"/#narrow/channel/<>" is a channel link', () => {
const check = mkCheck(isStreamNarrow);
['/#narrow/channel/1-jest', '/#narrow/channel/2-stream/', '/#narrow/channel/3-topic/'].forEach(
hash => check(hash),
);
});
describe('"/#narrow/stream/<>" is a stream link', () => {
const check = mkCheck(isStreamNarrow);
['/#narrow/stream/jest', '/#narrow/stream/stream/', '/#narrow/stream/topic/'].forEach(hash =>
check(hash),
);
// TODO: Test with modern-style stream links that use stream IDs
});
describe('"/#narrow/channel/<>/topic/<>" is a topic link', () => {
const check = mkCheck(isTopicNarrow);
[
'/#narrow/channel/1-jest/topic/test',
'/#narrow/channel/4-mobile/subject/topic/near/378333',
'/#narrow/channel/4-mobile/subject/topic/with/378333',
'/#narrow/channel/4-mobile/topic/topic/',
'/#narrow/channel/3-stream/topic/topic/near/1',
'/#narrow/channel/3-stream/topic/topic/with/1',
].forEach(hash => check(hash));
});
describe('"/#narrow/stream/<>/topic/<>" is a topic link', () => {
const check = mkCheck(isTopicNarrow);
[
'/#narrow/stream/jest/topic/test',
'/#narrow/stream/mobile/subject/topic/near/378333',
'/#narrow/stream/mobile/subject/topic/with/378333',
'/#narrow/stream/mobile/topic/topic/',
'/#narrow/stream/stream/topic/topic/near/1',
'/#narrow/stream/stream/topic/topic/with/1',
'/#narrow/stream/stream/subject/topic/near/1',
'/#narrow/stream/stream/subject/topic/with/1',
'/#narrow/stream/stream/subject/topic',
].forEach(hash => check(hash));
});
describe('"/#narrow/dm/<>" is a PM link', () => {
const check = mkCheck(isPmNarrow);
[
'/#narrow/dm/1,2-group',
'/#narrow/dm/1,2-group/near/1',
'/#narrow/dm/1,2-group/with/1',
'/#narrow/dm/a.40b.2Ecom.2Ec.2Ed.2Ecom/near/3',
'/#narrow/dm/a.40b.2Ecom.2Ec.2Ed.2Ecom/with/3',
].forEach(hash => check(hash));
});
describe('"/#narrow/pm-with/<>" is a PM link', () => {
const check = mkCheck(isPmNarrow);
[
'/#narrow/pm-with/1,2-group',
'/#narrow/pm-with/1,2-group/near/1',
'/#narrow/pm-with/1,2-group/with/1',
'/#narrow/pm-with/a.40b.2Ecom.2Ec.2Ed.2Ecom/near/3',
'/#narrow/pm-with/a.40b.2Ecom.2Ec.2Ed.2Ecom/with/3',
].forEach(hash => check(hash));
});
describe('"/#narrow/is/<>" with valid operand is a special link', () => {
const check = mkCheck(isSpecialNarrow);
[
'/#narrow/is/dm',
'/#narrow/is/private',
'/#narrow/is/starred',
'/#narrow/is/mentioned',
].forEach(hash => check(hash));
});
describe('unexpected link shape gives null', () => {
const check = mkCheck(null);
[
// `near` with no operand
'/#narrow/channel/stream/topic/topic/near/',
// `with` with no operand
'/#narrow/channel/stream/topic/topic/with/',
// `is` with invalid operand
'/#narrow/is/men',
'/#narrow/is/men/channel',
// invalid operand `are`; `channel` operator with no operand
'/#narrow/are/men/channel',
].forEach(hash => check(hash));
});
});
describe('decodeHashComponent', () => {
test('correctly decode MediaWiki-style dot-encoded strings', () => {
expect(decodeHashComponent('some_text')).toEqual('some_text');
expect(decodeHashComponent('some.20text')).toEqual('some text');
expect(decodeHashComponent('some.2Etext')).toEqual('some.text');
expect(decodeHashComponent('na.C3.AFvet.C3.A9')).toEqual('navet');
expect(decodeHashComponent('.C2.AF.5C_(.E3.83.84)_.2F.C2.AF')).toEqual('\\_()_/');
// malformed dot-encoding
expect(() => decodeHashComponent('some.text')).toThrow();
expect(() => decodeHashComponent('some.2gtext')).toThrow();
expect(() => decodeHashComponent('some.arbitrary_text')).toThrow();
// malformed UTF-8
expect(() => decodeHashComponent('.88.99.AA.BB')).toThrow();
});
});
// TODO: Combine / dedupe with "getNarrowFromNarrowLink (part 1)" tests above
describe('getNarrowFromNarrowLink (part 2)', () => {
const [userB, userC] = [eg.makeUser(), eg.makeUser()];
const streamGeneral = eg.makeStream({ name: 'general' });
// TODO: Take URL object instead of string
const get = (url, streams: $ReadOnlyArray<Stream>) =>
getNarrowFromNarrowLink(
new URL(url, 'path_to_url
new URL('path_to_url
new Map(streams.map(s => [s.stream_id, s])),
new Map(streams.map(s => [s.name, s])),
eg.selfUser.user_id,
);
describe('on channel links', () => {
const expectStream = (operand, streams, expectedStream: null | Stream) => {
expect(get(`#narrow/channel/${operand}`, streams)).toEqual(
expectedStream === null ? null : streamNarrow(expectedStream.stream_id),
);
expect(get(`#narrow/stream/${operand}`, streams)).toEqual(
expectedStream === null ? null : streamNarrow(expectedStream.stream_id),
);
};
test('basic', () => {
expectStream(`${streamGeneral.stream_id}-general`, [streamGeneral], streamGeneral);
});
test('if stream not found, use stream ID anyway', () => {
expectStream(`${streamGeneral.stream_id}-general`, [], streamGeneral);
});
test('on channel link with wrong name: ID wins', () => {
expectStream(`${streamGeneral.stream_id}-nonsense`, [streamGeneral], streamGeneral);
expectStream(`${streamGeneral.stream_id}-`, [streamGeneral], streamGeneral);
});
test('on malformed channel link: reject', () => {
expectStream(`-${streamGeneral.stream_id}`, [streamGeneral], null);
expectStream(`${streamGeneral.stream_id}nonsense-general`, [streamGeneral], null);
});
{
const testTeam = eg.makeStream({ name: 'test-team' });
const numbers = eg.makeStream({ name: '311' });
const numbersHyphen = eg.makeStream({ name: '311-' });
const numbersPlus = eg.makeStream({ name: '311-help' });
const dashdash = eg.makeStream({ name: '--help' });
test('on old stream link, for stream with hyphens or even looking like new-style', () => {
expectStream('test-team', [testTeam], testTeam);
expectStream('311', [numbers], numbers);
expectStream('311-', [numbersHyphen], numbersHyphen);
expectStream('311-help', [numbersPlus], numbersPlus);
expectStream('--help', [dashdash], dashdash);
});
test('on ambiguous new- or old-style: new wins', () => {
const collider = eg.makeStream({ stream_id: 311, name: 'collider' });
expectStream('311', [numbers, collider], collider);
expectStream('311-', [numbersHyphen, collider], collider);
expectStream('311-help', [numbersPlus, collider], collider);
});
}
test('on old stream link', () => {
const expectNameMatch = (operand, streamName) => {
const stream = eg.makeStream({ name: streamName });
expect(get(`path_to_url#narrow/stream/${operand}`, [stream])).toEqual(
streamNarrow(stream.stream_id),
);
};
expectNameMatch('jest', 'jest');
expectNameMatch('bot.20testing', 'bot testing');
expectNameMatch('jest.2EAPI', 'jest.API');
expectNameMatch('stream', 'stream');
expectNameMatch('topic', 'topic');
expect(() => get('path_to_url#narrow/stream/jest.API', [])).toThrow();
});
test('on old stream link, without realm info', () => {
expect(get(`/#narrow/stream/${eg.stream.name}`, [eg.stream])).toEqual(
streamNarrow(eg.stream.stream_id),
);
expect(get(`#narrow/stream/${eg.stream.name}`, [eg.stream])).toEqual(
streamNarrow(eg.stream.stream_id),
);
});
});
describe('on topic links', () => {
test('basic', () => {
const expectBasic = (operand, expectedTopic) => {
const url = `#narrow/channel/${streamGeneral.stream_id}-general/topic/${operand}`;
const legacyUrl = `#narrow/stream/${streamGeneral.stream_id}-general/topic/${operand}`;
expect(get(url, [streamGeneral])).toEqual(
topicNarrow(streamGeneral.stream_id, expectedTopic),
);
expect(get(legacyUrl, [streamGeneral])).toEqual(
topicNarrow(streamGeneral.stream_id, expectedTopic),
);
};
expectBasic('(no.20topic)', '(no topic)');
expectBasic('lunch', 'lunch');
});
test('on old topic link (no stream ID), with dot-encoding', () => {
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/topic/(no.20topic)`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, '(no topic)'));
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/topic/google.2Ecom`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, 'google.com'));
expect(() =>
get(`path_to_url#narrow/stream/${eg.stream.name}/topic/google.com`, [eg.stream]),
).toThrow();
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/topic/topic.20name`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, 'topic name'));
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/topic/stream`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, 'stream'));
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/topic/topic`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, 'topic'));
});
test('on old topic link (no stream ID), without realm info', () => {
expect(get(`/#narrow/stream/${eg.stream.name}/topic/topic`, [eg.stream])).toEqual(
topicNarrow(eg.stream.stream_id, 'topic'),
);
expect(get(`#narrow/stream/${eg.stream.name}/topic/topic`, [eg.stream])).toEqual(
topicNarrow(eg.stream.stream_id, 'topic'),
);
});
});
test('on group PM link', () => {
const ids = `${userB.user_id},${userC.user_id}`;
expect(get(`path_to_url#narrow/dm/${ids}-group`, [])).toEqual(
pmNarrowFromUsersUnsafe([userB, userC]),
);
expect(get(`path_to_url#narrow/pm-with/${ids}-group`, [])).toEqual(
pmNarrowFromUsersUnsafe([userB, userC]),
);
});
test('on group PM link including self', () => {
// The webapp doesn't generate these, but best to handle them anyway.
const ids = `${eg.selfUser.user_id},${userB.user_id},${userC.user_id}`;
expect(get(`path_to_url#narrow/dm/${ids}-group`, [])).toEqual(
pmNarrowFromUsersUnsafe([userB, userC]),
);
expect(get(`path_to_url#narrow/pm-with/${ids}-group`, [])).toEqual(
pmNarrowFromUsersUnsafe([userB, userC]),
);
});
test('on a special link', () => {
expect(get('/#narrow/is/dm', [])).toEqual(ALL_PRIVATE_NARROW);
expect(get('/#narrow/is/private', [])).toEqual(ALL_PRIVATE_NARROW);
expect(get('/#narrow/is/starred', [])).toEqual(STARRED_NARROW);
expect(get('/#narrow/is/mentioned', [])).toEqual(MENTIONED_NARROW);
});
test('on a message link', () => {
const ids = `${userB.user_id},${userC.user_id}`;
expect(get(`path_to_url#narrow/dm/${ids}-group/near/2`, [])).toEqual(
pmNarrowFromUsersUnsafe([userB, userC]),
);
expect(get(`path_to_url#narrow/pm-with/${ids}-group/near/2`, [])).toEqual(
pmNarrowFromUsersUnsafe([userB, userC]),
);
expect(
get(
`path_to_url#narrow/channel/${eg.stream.stream_id}-${eg.stream.name}/topic/test/near/1`,
[eg.stream],
),
).toEqual(topicNarrow(eg.stream.stream_id, 'test'));
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/topic/test/near/1`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, 'test'));
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/subject/test/near/1`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, 'test'));
});
test('on a /with/ link', () => {
const ids = `${userB.user_id},${userC.user_id}`;
expect(get(`path_to_url#narrow/dm/${ids}-group/with/2`, [])).toEqual(
pmNarrowFromUsersUnsafe([userB, userC]),
);
expect(get(`path_to_url#narrow/pm-with/${ids}-group/with/2`, [])).toEqual(
pmNarrowFromUsersUnsafe([userB, userC]),
);
expect(
get(
`path_to_url#narrow/channel/${eg.stream.stream_id}-${eg.stream.name}/topic/test/with/1`,
[eg.stream],
),
).toEqual(topicNarrow(eg.stream.stream_id, 'test'));
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/topic/test/with/1`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, 'test'));
expect(
get(`path_to_url#narrow/stream/${eg.stream.name}/subject/test/with/1`, [eg.stream]),
).toEqual(topicNarrow(eg.stream.stream_id, 'test'));
});
});
describe('getNearOperandFromLink', () => {
test('not message link', () => {
expect(getNearOperandFromLink(new URL('/#narrow/is/private', realm), realm)).toBe(null);
expect(getNearOperandFromLink(new URL('/#narrow/channel/jest', realm), realm)).toBe(null);
expect(getNearOperandFromLink(new URL('/#narrow/stream/jest', realm), realm)).toBe(null);
});
test('`near` is the only operator', () => {
expect(getNearOperandFromLink(new URL('/#narrow/near/1', realm), realm)).toBe(1);
});
test('`with` is the only operator', () => {
expect(getNearOperandFromLink(new URL('/#narrow/with/1', realm), realm)).toBe(1);
});
test('when link is a group link, return anchor message id', () => {
expect(getNearOperandFromLink(new URL('/#narrow/dm/1,3-group/near/1/', realm), realm)).toBe(1);
expect(
getNearOperandFromLink(new URL('/#narrow/pm-with/1,3-group/near/1/', realm), realm),
).toBe(1);
});
test('when link is a group link with /with/, return anchor message id', () => {
expect(getNearOperandFromLink(new URL('/#narrow/dm/1,3-group/with/1/', realm), realm)).toBe(1);
expect(
getNearOperandFromLink(new URL('/#narrow/pm-with/1,3-group/with/1/', realm), realm),
).toBe(1);
});
test('when link is a topic link, return anchor message id', () => {
expect(
getNearOperandFromLink(new URL('/#narrow/channel/1-jest/topic/test/near/1', realm), realm),
).toBe(1);
expect(
getNearOperandFromLink(new URL('/#narrow/stream/jest/topic/test/near/1', realm), realm),
).toBe(1);
});
test('when link is a topic link with /with/, return anchor message id', () => {
expect(
getNearOperandFromLink(new URL('/#narrow/channel/1-jest/topic/test/with/1', realm), realm),
).toBe(1);
expect(
getNearOperandFromLink(new URL('/#narrow/stream/jest/topic/test/with/1', realm), realm),
).toBe(1);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/internalLinks-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 5,574
|
```javascript
/* @flow strict-local */
import { isUrlOnRealm, isUrlAbsolute, isUrlRelative, isUrlPathAbsolute } from '../url';
const urlClassifierCases = {
// These data are mostly a selection from this resource:
// path_to_url
// which is referred to at the top of the URL Standard.
absolute: ['path_to_url 'a1234567890-+.:foo/bar', 'AB://c/d'],
pathAbsolute: ['/', '/foo/bar', '/.//path', '/../localhost/', '/:23', '/a/ /c'],
otherRelative: [
'//example.com/foo',
'//foo/bar',
'//',
'///',
'///test',
'//www.example2.com',
'10.0.0.7:8080/foo.html',
'a!@$*=/foo.html',
'#',
],
};
const urlClassifierData = Object.keys(urlClassifierCases).flatMap(key =>
urlClassifierCases[key].map(url => ({
url,
absolute: key === 'absolute',
relative: key !== 'absolute',
pathAbsolute: key === 'pathAbsolute',
})),
);
/* eslint-disable no-underscore-dangle */
describe('isUrlAbsolute', () => {
for (const case_ of urlClassifierData) {
const { url, absolute: expected } = case_;
test(`${expected ? 'accept' : 'reject'} ${url}`, () => {
expect(isUrlAbsolute(url)).toEqual(expected);
});
}
});
describe('isUrlRelative', () => {
for (const case_ of urlClassifierData) {
const { url, relative: expected } = case_;
test(`${expected ? 'accept' : 'reject'} ${url}`, () => {
expect(isUrlRelative(url)).toEqual(expected);
});
}
});
describe('isUrlPathAbsolute', () => {
for (const case_ of urlClassifierData) {
const { url, pathAbsolute: expected } = case_;
test(`${expected ? 'accept' : 'reject'} ${url}`, () => {
expect(isUrlPathAbsolute(url)).toEqual(expected);
});
}
});
describe('isUrlOnRealm', () => {
const realm = new URL('path_to_url
test('when link is on realm, return true', () => {
expect(isUrlOnRealm(new URL('/#narrow/stream/jest', realm), realm)).toBe(true);
expect(isUrlOnRealm(new URL('#narrow/#near/1', realm), realm)).toBe(true);
// path_to_url
expect(isUrlOnRealm(new URL('www.google.com', realm), realm)).toBeTrue();
expect(isUrlOnRealm(realm, realm)).toBeTrue();
expect(isUrlOnRealm(new URL('/foo/bar.baz', realm), realm)).toBeTrue();
});
test('when link is not on realm, return false', () => {
expect(isUrlOnRealm(new URL('path_to_url realm)).toBeFalse();
expect(isUrlOnRealm(new URL('path_to_url realm)).toBeFalse();
});
});
```
|
/content/code_sandbox/src/utils/__tests__/url-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 653
|
```javascript
/* @flow strict-local */
import { isValidEmailFormat, deeperMerge } from '../misc';
describe('deeperMerge', () => {
test('two empty objects merge into an empty object', () => {
const a = {};
const b = {};
const expectedResult = {};
const result = deeperMerge(a, b);
expect(result).toEqual(expectedResult);
});
test('two shallow objects get both keys', () => {
const a = { key1: 1 };
const b = { key2: 2 };
const expectedResult = {
key1: 1,
key2: 2,
};
const result = deeperMerge(a, b);
expect(result).toEqual(expectedResult);
});
test('two deep objects get both keys if keys differ', () => {
const a = { parentKey1: { key1: 1 } };
const b = { parentKey2: { key2: 2 } };
const expectedResult = {
parentKey1: { key1: 1 },
parentKey2: { key2: 2 },
};
const result = deeperMerge(a, b);
expect(result).toEqual(expectedResult);
});
test('two deep object return a merged key if keys are the same', () => {
const a = { parentKey: { key1: 1 } };
const b = { parentKey: { key2: 2 } };
const expectedResult = { parentKey: { key1: 1, key2: 2 } };
const result = deeperMerge(a, b);
expect(result).toEqual(expectedResult);
});
test('objects are merged only two levels deep, then the second one overwrites the first one', () => {
const a = { grandpaKey: { parentKey: { key1: 1 } } };
const b = { grandpaKey: { parentKey: { key2: 2 } } };
const expectedResult = { grandpaKey: { parentKey: { key2: 2 } } };
const result = deeperMerge(a, b);
expect(result).toEqual(expectedResult);
});
});
describe('isValidEmail', () => {
test('return true if email string is in valid format', () => {
expect(isValidEmailFormat('a@a.com')).toBe(true);
});
test('return false if email string is in valid format', () => {
expect(isValidEmailFormat('ab.com')).toBe(false);
expect(isValidEmailFormat('@a.com')).toBe(false);
expect(isValidEmailFormat('a@b')).toBe(false);
expect(isValidEmailFormat('a@.com')).toBe(false);
});
});
```
|
/content/code_sandbox/src/utils/__tests__/misc-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 574
|
```javascript
/* @flow strict-local */
import type { Reaction, AggregatedReaction, UserId } from '../types';
export default (
reactions: $ReadOnlyArray<Reaction>,
ownUserId: UserId,
): $ReadOnlyArray<AggregatedReaction> => {
const reactionMap = new Map();
reactions.forEach(x => {
let item = reactionMap.get(x.emoji_name);
if (!item) {
item = {
name: x.emoji_name,
type: x.reaction_type,
code: x.emoji_code,
count: 0,
selfReacted: false,
users: [],
};
reactionMap.set(x.emoji_name, item);
}
item.count += 1;
item.users.push(x.user_id);
if (x.user_id === ownUserId) {
item.selfReacted = true;
}
});
return Array.from(reactionMap.values()).sort(
(r1: AggregatedReaction, r2: AggregatedReaction) => r2.count - r1.count,
);
};
```
|
/content/code_sandbox/src/reactions/aggregateReactions.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 220
|
```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 UserItem from '../users/UserItem';
import { useNavigation } from '../react-navigation';
type Props = $ReadOnly<{|
reactedUserIds: $ReadOnlyArray<UserId>,
|}>;
/**
* Component showing who made a given reaction on a given message.
*
* Used within `MessageReactionsScreen`.
*/
export default function ReactionUserList(props: Props): Node {
const { reactedUserIds } = props;
const navigation = useNavigation();
return (
<FlatList
data={reactedUserIds}
keyExtractor={userId => `${userId}`}
renderItem={({ item }) => (
<UserItem
key={item}
userId={item}
onPress={(user: UserOrBot) => {
navigation.push('account-details', { userId: user.user_id });
}}
/>
)}
/>
);
}
```
|
/content/code_sandbox/src/reactions/ReactionUserList.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 222
|
```javascript
/* @flow strict-local */
import React, { useEffect } from 'react';
import type { Node } from 'react';
import { View } from 'react-native';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
import type { RouteProp } from '../react-navigation';
import type { AppNavigationProp } from '../nav/AppNavigator';
import * as logging from '../utils/logging';
import ReactionUserList from './ReactionUserList';
import { useSelector } from '../react-redux';
import Screen from '../common/Screen';
import ZulipTextIntl from '../common/ZulipTextIntl';
import ZulipText from '../common/ZulipText';
import { getOwnUserId } from '../selectors';
import aggregateReactions from './aggregateReactions';
import styles from '../styles';
import { materialTopTabNavigatorConfig } from '../styles/tabs';
import Emoji from '../emoji/Emoji';
import { emojiTypeFromReactionType } from '../emoji/data';
import { navigateBack } from '../nav/navActions';
import { usePrevious } from '../reactUtils';
// The tab navigator we make here has a dynamic set of route names, but they
// all take `void` for parameters.
type NavParamList = {| +[name: string]: void |};
const Tab = createMaterialTopTabNavigator<NavParamList>();
type Props = $ReadOnly<{|
navigation: AppNavigationProp<'message-reactions'>,
route: RouteProp<'message-reactions', {| reactionName?: string, messageId: number |}>,
|}>;
/**
* A screen showing who made what reaction on a given message.
*
* The `reactionName` nav-prop controls what reaction is focused when the
* screen first appears.
*/
export default function MessageReactionsScreen(props: Props): Node {
const { navigation } = props;
const { messageId, reactionName } = props.route.params;
const message = useSelector(state => state.messages.get(messageId));
const ownUserId = useSelector(getOwnUserId);
useEffect(() => {
if (message === undefined) {
logging.warn(
'MessageReactionsScreen unexpectedly created without props.message; '
+ 'message with messageId is missing in state.messages',
{ messageId },
);
}
}, [message, messageId]);
const prevMessage = usePrevious(message);
useEffect(() => {
if (prevMessage !== undefined && message === undefined) {
// The message was present, but got purged (currently only caused by a
// REGISTER_COMPLETE following a dead event queue), so go back.
navigation.dispatch(navigateBack());
}
}, [prevMessage, message, navigation]);
const content: Node = (() => {
if (message === undefined) {
return <View style={styles.flexed} />;
} else if (message.reactions.length === 0) {
return (
<View style={[styles.flexed, styles.center]}>
<ZulipTextIntl style={styles.largerText} text="No reactions" />
</View>
);
} else {
const aggregatedReactions = aggregateReactions(message.reactions, ownUserId);
return (
<View style={styles.flexed}>
<Tab.Navigator
backBehavior="none"
// The user may have originally navigated here to look at a reaction
// that's since been removed. Ignore the nav hint in that case.
initialRouteName={
aggregatedReactions.some(aR => aR.name === reactionName) ? reactionName : undefined
}
{...materialTopTabNavigatorConfig()}
swipeEnabled
>
{
// Generate tabs for the reaction list. The tabs depend
// on the distinct reactions on the message.
}
{aggregatedReactions.map(aggregatedReaction => (
// Each tab corresponds to an aggregated reaction, and has a user list.
<Tab.Screen
key={aggregatedReaction.name}
name={aggregatedReaction.name}
component={() => <ReactionUserList reactedUserIds={aggregatedReaction.users} />}
options={{
tabBarLabel: () => (
<View style={styles.row}>
<Emoji
code={aggregatedReaction.code}
type={emojiTypeFromReactionType(aggregatedReaction.type)}
/>
<ZulipText style={styles.paddingLeft} text={`${aggregatedReaction.count}`} />
</View>
),
}}
/>
))}
</Tab.Navigator>
</View>
);
}
})();
return (
<Screen title="Reactions" scrollEnabled={false}>
{content}
</Screen>
);
}
```
|
/content/code_sandbox/src/reactions/MessageReactionsScreen.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 964
|
```javascript
import deepFreeze from 'deep-freeze';
import aggregateReactions from '../aggregateReactions';
describe('aggregateReactions', () => {
test('empty input results in empty aggregate list', () => {
const reactions = deepFreeze([]);
const expectedResult = [];
const actualResult = aggregateReactions(reactions);
expect(actualResult).toEqual(expectedResult);
});
test('a single reaction, results in a single aggregate', () => {
const reactions = deepFreeze([{ emoji_name: 'emoji', user_id: 3 }]);
const expectedResult = [
{
name: 'emoji',
count: 1,
selfReacted: false,
users: [3],
},
];
const actualResult = aggregateReactions(reactions, 1);
expect(actualResult).toEqual(expectedResult);
});
test('every duplicate reaction is aggregated to a single one with appropriate count', () => {
const reactions = deepFreeze([
{ emoji_name: '1', user_id: 1 },
{ emoji_name: '2', user_id: 2 },
{ emoji_name: '1', user_id: 3 },
{ emoji_name: '1', user_id: 4 },
{ emoji_name: '3', user_id: 5 },
{ emoji_name: '2', user_id: 6 },
]);
const expectedResult = [
{
name: '1',
count: 3,
selfReacted: true,
users: [1, 3, 4],
},
{
name: '2',
count: 2,
selfReacted: false,
users: [2, 6],
},
{
name: '3',
count: 1,
selfReacted: false,
users: [5],
},
];
const actualResult = aggregateReactions(reactions, 1);
expect(actualResult).toEqual(expectedResult);
});
test('every duplicate reaction is aggregated, ignoring self', () => {
const reactions = deepFreeze([
{ emoji_name: '1', user_id: 1 },
{ emoji_name: '2', user_id: 2 },
{ emoji_name: '2', user_id: 1 },
{ emoji_name: '3', user_id: 3 },
]);
const expectedResult = [
{
name: '2',
count: 2,
selfReacted: true,
users: [2, 1],
},
{
name: '1',
count: 1,
selfReacted: false,
users: [1],
},
{
name: '3',
count: 1,
selfReacted: false,
users: [3],
},
];
const actualResult = aggregateReactions(reactions, 2);
expect(actualResult).toEqual(expectedResult);
});
});
```
|
/content/code_sandbox/src/reactions/__tests__/aggregateReactions-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 622
|
```javascript
/**
* The core of the user-status model, without dependencies on other models.
*
* @flow strict-local
*/
import Immutable from 'immutable';
import type { UserId } from '../api/apiTypes';
import type { UserStatus } from '../api/modelTypes';
/**
* The canonical default, "unset" user status.
*
* This is the user-status you have if you've just created your account and
* never interacted with the feature.
*
* It's effectively the user-status you have if you're on an old server that
* doesn't support user statuses.
*
* See the corresponding "zero status" in the API described at
* InitialDataUserStatus.
*/
// TODO(server-2.0): Simplify jsdoc.
// PRIVATE: Only to be used in this model's code.
export const kUserStatusZero: UserStatus = {
away: false,
status_text: null,
status_emoji: null,
};
/**
* The user status of each user.
*
* Users who have the "zero" status, `kUserStatusZero`, may be represented
* implicitly by having no record in this map.
*/
export type UserStatusesState = Immutable.Map<UserId, UserStatus>;
//
//
// Getters.
//
/**
* The `UserStatus` object for the given UserId, from `UserStatusesState`.
*
* Use this instead of reading `UserStatusesState` directly, because it
* takes care of this fact about UserStatusesState (from jsdoc):
*
* Users who have the "zero" status, `kUserStatusZero`, may be
* represented implicitly by having no record in this map.
*/
export const getUserStatusFromModel = (state: UserStatusesState, userId: UserId): UserStatus =>
state.get(userId, kUserStatusZero);
```
|
/content/code_sandbox/src/user-statuses/userStatusesCore.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 382
|
```javascript
/* @flow strict-local */
// $FlowFixMe[untyped-import]
import isEqual from 'lodash.isequal';
import React, { useState, useContext, useCallback } from 'react';
import type { Node } from 'react';
import { FlatList, View, Pressable } from 'react-native';
import { TranslationContext } from '../boot/TranslationProvider';
import { noTranslation } from '../i18n/i18n';
import { createStyleSheet, BRAND_COLOR, HIGHLIGHT_COLOR } from '../styles';
import type { RouteProp } from '../react-navigation';
import type { AppNavigationProp } from '../nav/AppNavigator';
import { useSelector } from '../react-redux';
import Input from '../common/Input';
import EmojiInput from './EmojiInput';
import type { Value as EmojiInputValue } from './EmojiInput';
import {
emojiTypeFromReactionType,
reactionTypeFromEmojiType,
displayCharacterForUnicodeEmojiCode,
} from '../emoji/data';
import SelectableOptionRow from '../common/SelectableOptionRow';
import Screen from '../common/Screen';
import ZulipButton from '../common/ZulipButton';
import { getZulipFeatureLevel, getAuth, getOwnUserId } from '../selectors';
import { getUserStatus } from './userStatusesModel';
import type { UserStatus } from '../api/modelTypes';
import { Icon } from '../common/Icons';
import * as api from '../api';
import { getRealm } from '../directSelectors';
type StatusSuggestion = [
string,
$ReadOnly<{| emoji_name: string, emoji_code: string, reaction_type: 'unicode_emoji' |}>,
];
const statusSuggestions: $ReadOnlyArray<StatusSuggestion> = [
['Busy', { emoji_name: 'working_on_it', emoji_code: '1f6e0', reaction_type: 'unicode_emoji' }],
['In a meeting', { emoji_name: 'calendar', emoji_code: '1f4c5', reaction_type: 'unicode_emoji' }],
['Commuting', { emoji_name: 'bus', emoji_code: '1f68c', reaction_type: 'unicode_emoji' }],
['Out sick', { emoji_name: 'sick', emoji_code: '1f912', reaction_type: 'unicode_emoji' }],
['Vacationing', { emoji_name: 'palm_tree', emoji_code: '1f334', reaction_type: 'unicode_emoji' }],
['Working remotely', { emoji_name: 'house', emoji_code: '1f3e0', reaction_type: 'unicode_emoji' }], // prettier-ignore
['At the office', { emoji_name: 'office', emoji_code: '1f3e2', reaction_type: 'unicode_emoji' }],
];
const styles = createStyleSheet({
inputRow: {
flexDirection: 'row',
margin: 16,
},
statusTextInput: {
flex: 1,
},
clearButton: {
// Min touch-target size
minWidth: 48,
minHeight: 48,
alignItems: 'center',
justifyContent: 'center',
// To match margin between the emoji and text inputs
marginLeft: 4,
},
button: {
margin: 8,
},
});
type Props = $ReadOnly<{|
navigation: AppNavigationProp<'user-status'>,
route: RouteProp<'user-status', void>,
|}>;
const statusTextFromInputValue = (v: string): UserStatus['status_text'] => v.trim() || null;
const inputValueFromStatusText = (t: UserStatus['status_text']): string => t ?? '';
const statusEmojiFromInputValue = (v: EmojiInputValue): UserStatus['status_emoji'] =>
v
? {
emoji_name: v.name,
emoji_code: v.code,
reaction_type: reactionTypeFromEmojiType(v.type, v.name),
}
: null;
const inputValueFromStatusEmoji = (e: UserStatus['status_emoji']): EmojiInputValue =>
e
? {
type: emojiTypeFromReactionType(e.reaction_type),
code: e.emoji_code,
name: e.emoji_name,
}
: null;
export default function UserStatusScreen(props: Props): Node {
const { navigation } = props;
// TODO(server-5.0): Cut conditionals on emoji-status support (emoji
// supported as of FL 86: path_to_url )
const serverSupportsEmojiStatus = useSelector(getZulipFeatureLevel) >= 86;
const serverEmojiData = useSelector(state => getRealm(state).serverEmojiData);
const _ = useContext(TranslationContext);
const auth = useSelector(getAuth);
const ownUserId = useSelector(getOwnUserId);
const userStatusText = useSelector(state => getUserStatus(state, ownUserId).status_text);
const userStatusEmoji = useSelector(state => getUserStatus(state, ownUserId).status_emoji);
const [textInputValue, setTextInputValue] = useState<string>(
inputValueFromStatusText(userStatusText),
);
const [emojiInputValue, setEmojiInputValue] = useState<EmojiInputValue>(
inputValueFromStatusEmoji(userStatusEmoji),
);
const sendToServer = useCallback(
partialUserStatus => {
const copy = { ...partialUserStatus };
// TODO: Put conditional inside `api.updateUserStatus` itself; see
// path_to_url#issuecomment-914996061
if (!serverSupportsEmojiStatus) {
delete copy.status_emoji;
}
api.updateUserStatus(auth, copy);
navigation.goBack();
},
[serverSupportsEmojiStatus, navigation, auth],
);
const handlePressSave = useCallback(() => {
sendToServer({
status_text: statusTextFromInputValue(textInputValue),
status_emoji: statusEmojiFromInputValue(emojiInputValue),
});
}, [textInputValue, emojiInputValue, sendToServer]);
const handlePressClear = useCallback(() => {
setTextInputValue(inputValueFromStatusText(null));
setEmojiInputValue(inputValueFromStatusEmoji(null));
}, []);
return (
<Screen title="Set your status">
<View style={styles.inputRow}>
{serverSupportsEmojiStatus && (
<EmojiInput
navigation={navigation}
value={emojiInputValue}
onChangeValue={setEmojiInputValue}
rightMargin
/>
)}
<Input
autoFocus
maxLength={60}
style={styles.statusTextInput}
placeholder="Whats your status?"
value={textInputValue}
onChangeText={setTextInputValue}
/>
{(emojiInputValue !== null || textInputValue.length > 0) && (
<Pressable style={styles.clearButton} onPress={handlePressClear}>
{({ pressed }) => (
<Icon name="x" size={24} color={pressed ? HIGHLIGHT_COLOR : BRAND_COLOR} />
)}
</Pressable>
)}
</View>
<FlatList
data={statusSuggestions}
keyboardShouldPersistTaps="always"
keyExtractor={(item, index) => index.toString() /* list is constant; index OK */}
renderItem={({ item: [text, emoji], index }) => {
const translatedText = _(text);
return (
<SelectableOptionRow
itemKey={index}
title={
serverSupportsEmojiStatus
? noTranslation(
`${displayCharacterForUnicodeEmojiCode(
emoji.emoji_code,
serverEmojiData,
)} ${translatedText}`,
)
: text
}
selected={
translatedText === statusTextFromInputValue(textInputValue)
&& isEqual(emoji, statusEmojiFromInputValue(emojiInputValue))
}
onRequestSelectionChange={() => {
setTextInputValue(translatedText);
setEmojiInputValue(inputValueFromStatusEmoji(emoji));
}}
/>
);
}}
/>
<ZulipButton
disabled={
statusTextFromInputValue(textInputValue) === userStatusText
&& isEqual(statusEmojiFromInputValue(emojiInputValue), userStatusEmoji)
}
style={styles.button}
text="Save"
onPress={handlePressSave}
/>
</Screen>
);
}
```
|
/content/code_sandbox/src/user-statuses/UserStatusScreen.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,750
|
```javascript
/* @flow strict-local */
import Immutable from 'immutable';
import type { UserStatus, UserStatusUpdate } from '../api/modelTypes';
import { makeUserId } from '../api/idTypes';
import { objectEntries } from '../flowPonyfill';
import type { PerAccountState, PerAccountApplicableAction, UserId } from '../types';
import type { UserStatusesState } from './userStatusesCore';
import {
REGISTER_COMPLETE,
EVENT_USER_REMOVE,
EVENT_USER_STATUS_UPDATE,
RESET_ACCOUNT_DATA,
} from '../actionConstants';
import { kUserStatusZero } from './userStatusesCore';
//
//
// Selectors.
//
/**
* The `UserStatusesState`.
*
* Don't read from `UserStatusesState` directly; see `userStatusesCore` for
* a getter that takes a `UserStatusesState`.
*/
export const getUserStatuses = (state: PerAccountState): UserStatusesState => state.userStatuses;
/**
* The `UserStatus` object for the given UserId, from `PerAccountState`.
*/
export const getUserStatus = (state: PerAccountState, userId: UserId): UserStatus =>
getUserStatuses(state).get(userId, kUserStatusZero);
//
//
// Reducer.
//
const initialState: UserStatusesState = Immutable.Map();
function updateUserStatus(
status: UserStatus,
update: $ReadOnly<{ ...UserStatusUpdate, ... }>,
): UserStatus {
const { away, status_text, emoji_name, emoji_code, reaction_type } = update;
return {
away: away ?? status.away,
status_text:
status_text != null ? (status_text === '' ? null : status_text) : status.status_text,
status_emoji:
emoji_name != null && emoji_code != null && reaction_type != null
? emoji_name === '' || emoji_code === '' || reaction_type === ''
? null
: { emoji_name, reaction_type, emoji_code }
: status.status_emoji,
};
}
export const reducer = (
state: UserStatusesState = initialState, // eslint-disable-line default-param-last
action: PerAccountApplicableAction,
): UserStatusesState => {
switch (action.type) {
case RESET_ACCOUNT_DATA:
return initialState;
case REGISTER_COMPLETE: {
const { user_status } = action.data;
if (!user_status) {
// TODO(server-2.0): Drop this.
return initialState;
}
return Immutable.Map(
objectEntries(user_status).map(([id, update]) => [
makeUserId(Number.parseInt(id, 10)),
updateUserStatus(kUserStatusZero, update),
]),
);
}
case EVENT_USER_STATUS_UPDATE: {
const oldUserStatus = state.get(action.user_id, kUserStatusZero);
return state.set(action.user_id, updateUserStatus(oldUserStatus, action));
}
case EVENT_USER_REMOVE: // TODO(#3408) handle this
return state;
default:
return state;
}
};
```
|
/content/code_sandbox/src/user-statuses/userStatusesModel.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 640
|
```javascript
/* @flow strict-local */
import React, { useContext, useCallback, useMemo } from 'react';
import type { Node } from 'react';
import { Platform } from 'react-native';
import type { AppNavigationProp } from '../nav/AppNavigator';
import { ThemeContext } from '../styles/theme';
import Touchable from '../common/Touchable';
import Emoji from '../emoji/Emoji';
import { Icon } from '../common/Icons';
import type { EmojiType } from '../types';
import { createStyleSheet, BORDER_COLOR } from '../styles';
export type Value = null | {| +type: EmojiType, +code: string, +name: string |};
export type Props = $ReadOnly<{|
value: Value,
onChangeValue: Value => void,
/**
* Component must be under the stack nav that has the emoji-picker screen
*
* Pass this down from props or `useNavigation`.
*/
navigation: AppNavigationProp<>,
/**
* Give appropriate right margin
*/
rightMargin?: true,
|}>;
/**
* A controlled input component to let the user choose an emoji.
*
* When pressed, opens the emoji-picker screen, and populates with the emoji
* chosen by the user, if any.
*
* Designed for harmony with our Input component. If changing the appearance
* of this or that component, we should try to keep that harmony.
*/
export default function EmojiInput(props: Props): Node {
const { value, onChangeValue, navigation, rightMargin } = props;
const { color } = useContext(ThemeContext);
const handlePress = useCallback(() => {
navigation.push('emoji-picker', { onPressEmoji: onChangeValue });
}, [navigation, onChangeValue]);
const styles = useMemo(
() =>
createStyleSheet({
touchable: {
// Min touch-target size
minWidth: 48,
minHeight: 48,
alignItems: 'center',
justifyContent: 'center',
marginRight: rightMargin ? 4 : undefined,
// For harmony with the `Input` component, which differs between
// platforms because of platform conventions. Border on iOS, no
// border on Android.
...(Platform.OS === 'ios'
? {
borderWidth: 1,
borderColor: BORDER_COLOR,
borderRadius: 2,
padding: 8,
}
: Object.freeze({})),
},
}),
[rightMargin],
);
return (
<Touchable style={styles.touchable} onPress={handlePress}>
{value ? (
<Emoji code={value.code} type={value.type} size={24} />
) : (
<Icon color={color} size={24} name="smile" />
)}
</Touchable>
);
}
```
|
/content/code_sandbox/src/user-statuses/EmojiInput.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 579
|
```javascript
/* @flow strict-local */
import Immutable from 'immutable';
import { objectFromEntries } from '../../jsBackport';
import { makeUserId, type UserId } from '../../api/idTypes';
import type { UserStatusesState } from '../../types';
import type { UserStatusUpdate } from '../../api/modelTypes';
import * as eg from '../../__tests__/lib/exampleData';
import { EVENT_USER_STATUS_UPDATE } from '../../actionConstants';
import { reducer } from '../userStatusesModel';
import { kUserStatusZero } from '../userStatusesCore';
describe('reducer', () => {
const testUserStatusesState: UserStatusesState = Immutable.Map([
[makeUserId(1), { away: true, status_text: null, status_emoji: null }],
[makeUserId(2), { away: false, status_text: 'Hello, world', status_emoji: null }],
]);
// TODO: vary this data
const mkEmoji = () => ({
emoji_name: 'thumbs_up',
emoji_code: '1f44d',
reaction_type: 'unicode_emoji',
});
const emojiUnset = {
emoji_name: '',
emoji_code: '',
reaction_type: '',
};
describe('RESET_ACCOUNT_DATA', () => {
test('resets state to initial state', () => {
expect(reducer(testUserStatusesState, eg.action.reset_account_data)).toEqual(Immutable.Map());
});
});
describe('REGISTER_COMPLETE', () => {
const mkAction = (...args: Array<[UserId, UserStatusUpdate]>) =>
eg.mkActionRegisterComplete({
user_status: objectFromEntries(args.map(([userId, update]) => [userId.toString(), update])),
});
test('when `user_status` data is provided init state with it', () => {
expect(
reducer(
Immutable.Map(),
mkAction(
[makeUserId(1), { away: true }],
[makeUserId(2), { status_text: 'Hello, world' }],
),
),
).toEqual(testUserStatusesState);
});
test('handles older back-ends that do not have `user_status` data by resetting the state', () => {
expect(
reducer(testUserStatusesState, eg.mkActionRegisterComplete({ user_status: undefined })),
).toEqual(Immutable.Map());
});
test('away set', () => {
expect(reducer(Immutable.Map(), mkAction([eg.selfUser.user_id, { away: true }]))).toEqual(
Immutable.Map([[eg.selfUser.user_id, { ...kUserStatusZero, away: true }]]),
);
});
test('text set', () => {
expect(
reducer(Immutable.Map(), mkAction([eg.selfUser.user_id, { status_text: 'foo' }])),
).toEqual(Immutable.Map([[eg.selfUser.user_id, { ...kUserStatusZero, status_text: 'foo' }]]));
});
test('emoji set', () => {
const emoji = mkEmoji();
expect(reducer(Immutable.Map(), mkAction([eg.selfUser.user_id, { ...emoji }]))).toEqual(
Immutable.Map([[eg.selfUser.user_id, { ...kUserStatusZero, status_emoji: emoji }]]),
);
});
test('all components set together', () => {
const emoji = mkEmoji();
expect(
reducer(
Immutable.Map(),
mkAction([eg.selfUser.user_id, { away: true, status_text: 'Hello, world!', ...emoji }]),
),
).toEqual(
Immutable.Map([
[eg.selfUser.user_id, { away: true, status_text: 'Hello, world!', status_emoji: emoji }],
]),
);
});
});
describe('EVENT_USER_STATUS_UPDATE', () => {
const mkAction = (update: UserStatusUpdate, userId = eg.selfUser.user_id) => ({
id: 0,
type: EVENT_USER_STATUS_UPDATE,
user_id: userId,
...update,
});
test('when the user does not already have entry add a key by their `user_id`', () => {
expect(
reducer(
Immutable.Map([[eg.selfUser.user_id, kUserStatusZero]]),
mkAction({ away: true }, eg.otherUser.user_id),
),
).toEqual(
Immutable.Map([
[eg.selfUser.user_id, kUserStatusZero],
[eg.otherUser.user_id, { ...kUserStatusZero, away: true }],
]),
);
});
test('if the user already has user status stored update their key', () => {
expect(
reducer(
Immutable.Map([
[eg.selfUser.user_id, { away: false, status_text: 'foo', status_emoji: null }],
]),
mkAction({ status_text: 'bar' }),
),
).toEqual(
Immutable.Map([
[eg.selfUser.user_id, { away: false, status_text: 'bar', status_emoji: null }],
]),
);
});
test('when the user_ status text is updated this is reflected in the state', () => {
expect(reducer(Immutable.Map(), mkAction({ status_text: 'Hello, world!' }))).toEqual(
Immutable.Map([
[eg.selfUser.user_id, { away: false, status_text: 'Hello, world!', status_emoji: null }],
]),
);
});
test('away, text, and emoji status components can be set in one event', () => {
const emoji = mkEmoji();
expect(
reducer(
Immutable.Map([[eg.selfUser.user_id, kUserStatusZero]]),
mkAction({ away: true, status_text: 'Hello, world!', ...emoji }),
),
).toEqual(
Immutable.Map([
[eg.selfUser.user_id, { away: true, status_text: 'Hello, world!', status_emoji: emoji }],
]),
);
});
test('away, text, and emoji status components can be unset in one event', () => {
const emoji = mkEmoji();
expect(
reducer(
Immutable.Map([
[
eg.selfUser.user_id,
{ away: true, status_text: 'Hello, world!', status_emoji: emoji },
],
]),
mkAction({ away: false, status_text: '', ...emojiUnset }),
),
).toEqual(Immutable.Map([[eg.selfUser.user_id, kUserStatusZero]]));
});
});
});
```
|
/content/code_sandbox/src/user-statuses/__tests__/userStatusesModel-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,376
|
```javascript
/* @flow strict-local */
// $FlowFixMe[untyped-import]
import omit from 'lodash.omit';
import Immutable from 'immutable';
import type {
MessagesState,
Message,
PerAccountApplicableAction,
PerAccountState,
UpdateMessageEvent,
} from '../types';
import {
REGISTER_COMPLETE,
MESSAGE_FETCH_COMPLETE,
EVENT_NEW_MESSAGE,
EVENT_SUBMESSAGE,
EVENT_MESSAGE_DELETE,
EVENT_REACTION_ADD,
EVENT_REACTION_REMOVE,
EVENT_UPDATE_MESSAGE,
RESET_ACCOUNT_DATA,
} from '../actionConstants';
import { getNarrowsForMessage } from '../utils/narrow';
import * as logging from '../utils/logging';
import { getStreamsById } from '../selectors';
import type { MessageEdit } from '../api/modelTypes';
import type { ReadWrite } from '../generics';
import type { MessageMove } from '../api/misc';
import { getCaughtUpForNarrowInner } from '../caughtup/caughtUpSelectors';
const initialState: MessagesState = Immutable.Map([]);
const eventNewMessage = (state, action) => {
const { message, caughtUp } = action;
const { flags } = message;
if (!flags) {
throw new Error('EVENT_NEW_MESSAGE message missing flags');
}
// Don't add a message that's already been added. It's probably
// very rare for a message to have already been added when we
// get an EVENT_NEW_MESSAGE, and perhaps impossible. (TODO:
// investigate?)
if (state.get(action.message.id)) {
return state;
}
const narrowsForMessage = getNarrowsForMessage(message, action.ownUserId, flags);
const anyNarrowIsCaughtUp = narrowsForMessage.some(
narrow => getCaughtUpForNarrowInner(caughtUp, narrow).newer,
);
// Don't bother adding the message to `state.messages` if it wasn't
// added to `state.narrows`. For why the message might not have been
// added to `state.narrows`, see the condition on `caughtUp` in
// narrowsReducer's handling of EVENT_NEW_MESSAGE.
if (!anyNarrowIsCaughtUp) {
return state;
}
// If changing or adding case where we ignore a message here:
// Careful! Every message in `state.narrows` must exist in
// `state.messages`. If we choose not to include a message in
// `state.messages`, then narrowsReducer MUST ALSO choose not to
// include it in `state.narrows`.
return state.set(action.message.id, omit(action.message, 'flags'));
};
const editHistory = <M: Message>(args: {|
oldMessage: M,
event: UpdateMessageEvent,
move: MessageMove | null,
shouldApplyContentChanges: boolean,
|}) => {
const { oldMessage, event, move, shouldApplyContentChanges } = args;
if (oldMessage.edit_history === null) {
// Either:
// - we dropped edit_history because the server was old and the value
// wouldn't have been in a nice shape, or
// - the realm is set to not allow viewing edit history
//
// (See Message['edit_history'].) Keep maintaining nothing here; don't
// write a partial value, such as a one-item array based on this edit,
// which would be corrupt.
//
// TODO(server-5.0): Simplify away the FL condition; keep the
// allowEditHistory condition.
return null;
}
if (
event.rendering_only === true
// TODO(server-5.0): Simplify away these two checks
|| event.edit_timestamp === undefined
|| event.user_id === undefined
) {
// See doc:
// path_to_url#update_message
// > [] the event does not reflect a user-generated edit and does not
// > modify the message history.
return oldMessage.edit_history;
}
const newEntry: ReadWrite<MessageEdit> = {
timestamp: event.edit_timestamp,
user_id: event.user_id,
};
if (
shouldApplyContentChanges
&& event.message_id === oldMessage.id
&& event.orig_content != null
) {
newEntry.prev_content = event.orig_content;
newEntry.prev_rendered_content = event.orig_rendered_content;
newEntry.prev_rendered_content_version = event.prev_rendered_content_version;
}
if (move) {
if (move.orig_stream_id !== move.new_stream_id) {
newEntry.prev_stream = move.orig_stream_id;
newEntry.stream = move.new_stream_id;
}
if (move.orig_topic !== move.new_topic) {
newEntry.prev_topic = move.orig_topic;
newEntry.topic = move.new_topic;
}
}
return [newEntry, ...(oldMessage.edit_history ?? [])];
};
export default (
state: MessagesState = initialState, // eslint-disable-line default-param-last
action: PerAccountApplicableAction,
globalState: PerAccountState,
): MessagesState => {
switch (action.type) {
case RESET_ACCOUNT_DATA:
return initialState;
// Reset to clear stale data. We don't initialize the
// messages/narrows/flags model using initial data; instead, we fetch
// chunks of data as needed with api.getMessages. See
// path_to_url#messages
case REGISTER_COMPLETE:
return initialState;
case MESSAGE_FETCH_COMPLETE:
return state.merge(
Immutable.Map(
action.messages.map(message => [
message.id,
omit(message, ['flags', 'match_content', 'match_subject']),
]),
),
);
case EVENT_REACTION_ADD:
return state.update(
action.message_id,
<M: Message>(oldMessage: M): M =>
oldMessage && {
...(oldMessage: M),
reactions: oldMessage.reactions.concat({
emoji_name: action.emoji_name,
user_id: action.user_id,
reaction_type: action.reaction_type,
emoji_code: action.emoji_code,
}),
},
);
case EVENT_REACTION_REMOVE:
return state.update(
action.message_id,
<M: Message>(oldMessage: M): M =>
oldMessage && {
...(oldMessage: M),
reactions: oldMessage.reactions.filter(
x => !(x.emoji_name === action.emoji_name && x.user_id === action.user_id),
),
},
);
case EVENT_NEW_MESSAGE:
return eventNewMessage(state, action);
case EVENT_SUBMESSAGE:
return state.update(
action.message_id,
<M: Message>(message: M): M =>
message && {
...(message: M),
submessages: [
...(message.submessages ?? []),
{
id: action.submessage_id,
message_id: action.message_id,
sender_id: action.sender_id,
msg_type: action.msg_type,
content: action.content,
},
],
},
);
case EVENT_MESSAGE_DELETE:
return state.deleteAll(action.messageIds);
case EVENT_UPDATE_MESSAGE: {
const { event, move } = action;
let result = state;
result = result.update(event.message_id, <M: Message>(oldMessage: M): M => {
if (!oldMessage) {
return oldMessage;
}
return {
...(oldMessage: M),
content: event.rendered_content ?? oldMessage.content,
// Don't update last_edit_timestamp if it's a rendering-only
// event. How do we know if it is? From newer servers,
// rendering_only will be true; from older servers, edit_timestamp
// will be missing.
// TODO(server-5.0): Simplify away edit_timestamp-missing condition
last_edit_timestamp:
event.rendering_only === true || event.edit_timestamp == null
? oldMessage.last_edit_timestamp
: event.edit_timestamp,
edit_history: editHistory<M>({
oldMessage,
event,
move,
shouldApplyContentChanges: true,
}),
};
});
if (move) {
const update: { subject: string, stream_id?: number, display_recipient?: string } = {
subject: move.new_topic,
// TODO(#3408): Update topic_links. This is OK for now
// because we don't have any UI to expose it.
// TODO(#3408): Update last_edit_timestamp, probably. But want to
// say "moved" in the UI in this case, not "edited".
};
if (move.new_stream_id !== move.orig_stream_id) {
update.stream_id = move.new_stream_id;
const newStream = getStreamsById(globalState).get(move.new_stream_id);
// It's normal for newStream to potentially be missing here: it
// happens when the move was to a stream our user can't see.
// TODO(i18n): Not sure this "unknown" ever reaches the UI, but
// it'd be nice to somehow translate it in case it can.
update.display_recipient = newStream?.name ?? 'unknown';
}
// eslint-disable-next-line no-shadow
result = result.withMutations(state => {
for (const id of event.message_ids) {
state.update(id, <M: Message>(oldMessage: M | void): M | void => {
if (!oldMessage) {
return oldMessage;
}
if (oldMessage.type !== 'stream') {
logging.warn('messagesReducer: got update_message with stream/topic move on PM');
return oldMessage;
}
return {
...oldMessage,
...update,
// We already processed the message with ID
// `event.message_id`, above; skip it here.
edit_history:
id === event.message_id
? oldMessage.edit_history
: editHistory<M>({
oldMessage,
event,
move,
// See doc:
// path_to_url#update_message
// > Content changes should be applied only to the single message
// > indicated by `message_id`.
shouldApplyContentChanges: false,
}),
};
});
}
});
}
return result;
}
default:
return state;
}
};
```
|
/content/code_sandbox/src/message/messagesReducer.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 2,217
|
```javascript
/* @flow strict-local */
import React from 'react';
import type { Node } from 'react';
import { View } from 'react-native';
import ZulipTextIntl from '../common/ZulipTextIntl';
import styles from '../styles';
export default function AnnouncementOnly(props: {||}): Node {
return (
<View style={styles.disabledComposeBox}>
<ZulipTextIntl
style={styles.disabledComposeText}
text="Only organization admins are allowed to post to this stream."
/>
</View>
);
}
```
|
/content/code_sandbox/src/message/AnnouncementOnly.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 116
|
```javascript
/* @flow strict-local */
import { createSelector, defaultMemoize } from 'reselect';
import invariant from 'invariant';
import type { Message, PmMessage, Outbox, Narrow, Selector, MessageListElement } from '../types';
import { getAllNarrows, getFlags, getMessages } from '../directSelectors';
import * as logging from '../utils/logging';
import { getShownMessagesForNarrow } from '../chat/narrowsSelectors';
import getMessageListElements from './getMessageListElements';
import type { JSONable } from '../utils/jsonable';
import { ALL_PRIVATE_NARROW_STR } from '../utils/narrow';
import { NULL_ARRAY } from '../nullObjects';
/**
* Truncate a potentially-very-long array for logging and/or reporting purposes.
* Returns something which may or may not be an array, but is at least JSONable
* and human-readable.
*/
function truncateForLogging<T: JSONable>(arr: $ReadOnlyArray<T>, len = 10): JSONable {
if (arr.length <= 2 * len) {
return arr;
}
return {
length: arr.length,
start: arr.slice(0, len),
end: arr.slice(-len),
};
}
export const getPrivateMessages: Selector<$ReadOnlyArray<PmMessage>> = createSelector(
getAllNarrows,
getMessages,
(narrows, messages) => {
const privateMessages: PmMessage[] = [];
const unknownIds: number[] = [];
const pmIds = narrows.get(ALL_PRIVATE_NARROW_STR) || NULL_ARRAY;
pmIds.forEach(id => {
const msg = messages.get(id);
if (msg !== undefined) {
// It seems like the code involved in maintaining this invariant
// extends to the server: we go and make a fetch for this narrow,
// and then whatever the server gives us gets put here, and we don't
// seem to try to verify that as it goes in. So in fact ideally this
// check would be at a crunchy shell. But getting that wrong is a
// pretty unlikely bug for the server to have, so just doing
// `invariant` here is fine.
invariant(msg.type === 'private', 'msg is a PM');
privateMessages.push(msg);
} else {
unknownIds.push(id);
}
});
// BUG (#3749): all messages in `narrows` _should_ also be in `messages`.
// Error reports indicate that, somehow, this isn't always so.
if (unknownIds.length > 0) {
logging.error('narrow IDs not found in state.messages', {
all_ids: truncateForLogging(pmIds),
unknown_ids: truncateForLogging(unknownIds),
});
}
return privateMessages;
},
);
export const getMessageListElementsMemoized: (
$ReadOnlyArray<Message | Outbox>,
Narrow,
) => $ReadOnlyArray<MessageListElement> = defaultMemoize(getMessageListElements);
export const getFirstUnreadIdInNarrow: Selector<number | null, Narrow> = createSelector(
(state, narrow) => getShownMessagesForNarrow(state, narrow),
getFlags,
(messages, flags) => {
const firstUnread = messages.find(msg => !flags.read[msg.id]);
return firstUnread?.id ?? null;
},
);
/**
* True just if we know the message has, or had, the given topic.
*
* Gives null if it doesn't have the topic now, but we can't access
* the message's edit history to check in the past.
*/
export function hasMessageEverHadTopic(message: Message, topic: string): boolean | null {
if (message.subject === topic) {
return true;
}
// See comments on Message['edit_history'] for the values it takes
// and what they mean.
if (message.edit_history === null) {
return null;
}
if (message.edit_history === undefined) {
return false;
}
return message.edit_history.findIndex(messageEdit => topic === messageEdit.prev_topic) >= 0;
}
/**
* True just if we know the message is, or was, in the given stream.
*
* Gives null if it's not in the stream now, but we can't access the
* message's edit history to check in the past.
*/
export function hasMessageEverBeenInStream(message: Message, streamId: number): boolean | null {
if (message.stream_id === streamId) {
return true;
}
// See comments on Message['edit_history'] for the values it takes
// and what they mean.
if (message.edit_history === null) {
return null;
}
if (message.edit_history === undefined) {
return false;
}
return message.edit_history.findIndex(messageEdit => streamId === messageEdit.prev_stream) >= 0;
}
```
|
/content/code_sandbox/src/message/messageSelectors.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,038
|
```javascript
/* @flow strict-local */
import React from 'react';
import type { Node } from 'react';
import { View } from 'react-native';
import type { Narrow } from '../types';
import { createStyleSheet } from '../styles';
import ZulipTextIntl from '../common/ZulipTextIntl';
import {
isHomeNarrow,
is1to1PmNarrow,
isGroupPmNarrow,
isSpecialNarrow,
isStreamNarrow,
isTopicNarrow,
isSearchNarrow,
showComposeBoxOnNarrow,
} from '../utils/narrow';
const styles = createStyleSheet({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 20,
paddingLeft: 10,
padding: 8,
},
});
type EmptyMessage = {|
isFunc: Narrow => boolean,
text: string,
|};
const messages: $ReadOnlyArray<EmptyMessage> = [
{ isFunc: isHomeNarrow, text: 'No messages on server' },
{ isFunc: isSpecialNarrow, text: 'No messages' },
{ isFunc: isStreamNarrow, text: 'No messages in stream' },
{ isFunc: isTopicNarrow, text: 'No messages with this topic' },
{ isFunc: is1to1PmNarrow, text: 'No messages with this person' },
{ isFunc: isGroupPmNarrow, text: 'No messages in this group' },
{ isFunc: isSearchNarrow, text: 'No messages' },
];
type Props = $ReadOnly<{|
narrow: Narrow,
|}>;
export default function NoMessages(props: Props): Node {
const { narrow } = props;
const message = messages.find(x => x.isFunc(narrow)) || {};
return (
<View style={styles.container}>
<ZulipTextIntl style={styles.text} text={message.text} />
{showComposeBoxOnNarrow(narrow) ? (
<ZulipTextIntl text="Why not start the conversation?" />
) : null}
</View>
);
}
```
|
/content/code_sandbox/src/message/NoMessages.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 476
|
```javascript
/* @flow strict-local */
import React, { useCallback, useContext, useMemo } from 'react';
import type { Node } from 'react';
import { View, FlatList } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import useFetchedDataWithRefresh from '../common/useFetchedDataWithRefresh';
import ZulipTextIntl from '../common/ZulipTextIntl';
import { useGlobalSelector, useSelector } from '../react-redux';
import * as api from '../api';
import type { AppNavigationProp } from '../nav/AppNavigator';
import type { RouteProp } from '../react-navigation';
import Screen from '../common/Screen';
import { useConditionalEffect, useHasNotChangedForMs, useHasStayedTrueForMs } from '../reactUtils';
import { getAuth, getZulipFeatureLevel } from '../account/accountsSelectors';
import { showToast } from '../utils/info';
import { TranslationContext } from '../boot/TranslationProvider';
import UserItem from '../users/UserItem';
import { tryGetUserForId } from '../users/userSelectors';
import type { UserId } from '../api/idTypes';
import { getGlobalSettings } from '../directSelectors';
import type { UserOrBot } from '../api/modelTypes';
import LoadingIndicator from '../common/LoadingIndicator';
import WebLink from '../common/WebLink';
import { createStyleSheet } from '../styles';
type Props = $ReadOnly<{|
navigation: AppNavigationProp<'read-receipts'>,
route: RouteProp<'read-receipts', {| +messageId: number |}>,
|}>;
export default function ReadReceiptsScreen(props: Props): Node {
const { navigation } = props;
const { messageId } = props.route.params;
const auth = useSelector(getAuth);
const zulipFeatureLevel = useSelector(getZulipFeatureLevel);
const language = useGlobalSelector(state => getGlobalSettings(state).language);
const _ = useContext(TranslationContext);
const callApiMethod = useCallback(
() => api.getReadReceipts(auth, { message_id: messageId }, zulipFeatureLevel),
[auth, messageId, zulipFeatureLevel],
);
const { latestResult, latestSuccessResult } = useFetchedDataWithRefresh(callApiMethod, 15_000);
// TODO: These vanishing toasts are easy to miss. Instead, show
// latestResultIsError, isFirstLoadLate, and haveStaleData with
// something more persistent. A Material Design Snackbar that stays
// until the user dismisses it or the problem resolves?
// path_to_url
const latestResultIsError = latestResult?.type === 'error';
useConditionalEffect(
useCallback(() => {
showToast(_('Could not load data.'));
}, [_]),
latestResultIsError,
);
const isFirstLoadLate = useHasStayedTrueForMs(latestSuccessResult === null, 10_000);
useConditionalEffect(
useCallback(() => showToast(_('Still working')), [_]),
isFirstLoadLate
// If the latest result was an error, we would've shown a "Could not
// load data" message, which sounds final. Reduce confusion by
// suppressing a "Still working" message, even as the Hook continues
// to try to load the data. Confusion, and also false hope: if the
// last fetch failed, we're not optimistic about this one.
&& !latestResultIsError,
);
const haveStaleData =
useHasNotChangedForMs(latestSuccessResult, 40_000) && latestSuccessResult !== null;
useConditionalEffect(
useCallback(() => showToast(_('Updates may be delayed.')), [_]),
haveStaleData,
);
const onPressUser = useCallback(
(user: UserOrBot) => {
navigation.push('account-details', { userId: user.user_id });
},
[navigation],
);
// The web app tries Intl.Collator too, with a fallback for browsers that
// don't support it. See `strcmp` in static/js/util.js in the web app. Our
// platforms should support it:
// - MDN shows that our simple usage here is supported since iOS 10:
// path_to_url
// And we desupported iOS 10 a long time ago.
// - On Android, I don't get an error that suggests an API is missing.
// And it looks like Hermes, which we hope to switch to soon, supports it:
// path_to_url#issuecomment-1156832485
const userSorter = useCallback(
(a, b) => Intl.Collator(language).compare(a.full_name, b.full_name),
[language],
);
const displayUserIds = useSelector(state => {
const userIds: $ReadOnlyArray<UserId> = latestSuccessResult?.data ?? [];
const result = [];
userIds.forEach(userId => {
const user = tryGetUserForId(state, userId);
if (!user) {
// E.g., data out of sync because we're working outside the event
// system. Shrug, drop this one.
return;
}
result.push(user);
});
result.sort(userSorter);
return result.map(user => user.user_id);
});
const renderItem = useCallback(
({ item }) => <UserItem key={item} userId={item} onPress={onPressUser} />,
[onPressUser],
);
const localizableSummaryText = useMemo(
() =>
displayUserIds.length > 0
? {
// This is actually the same string as in the web app; see where
// that's set in static/js/read_receipts.js
text: `\
{num_of_people, plural,
one {This message has been <z-link>read</z-link> by {num_of_people} person:}
other {This message has been <z-link>read</z-link> by {num_of_people} people:}\
}`,
values: {
num_of_people: displayUserIds.length,
'z-link': chunks => (
<WebLink url={new URL('/help/read-receipts', auth.realm)}>{chunks}</WebLink>
),
},
}
: 'No one has read this message yet.',
[auth.realm, displayUserIds.length],
);
const styles = useMemo(
() =>
createStyleSheet({
summaryTextWrapper: { padding: 16 },
flex1: { flex: 1 },
}),
[],
);
return (
<Screen title="Read receipts" scrollEnabled={false}>
{latestSuccessResult ? (
<View style={styles.flex1}>
<SafeAreaView mode="padding" edges={['right', 'left']} style={styles.summaryTextWrapper}>
<ZulipTextIntl text={localizableSummaryText} />
</SafeAreaView>
<FlatList style={styles.flex1} data={displayUserIds} renderItem={renderItem} />
</View>
) : (
<LoadingIndicator size={48} />
)}
</Screen>
);
}
```
|
/content/code_sandbox/src/message/ReadReceiptsScreen.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,527
|
```javascript
/* @flow strict-local */
// $FlowFixMe[untyped-import]
import isEqual from 'lodash.isequal';
import type { Narrow } from '../types';
// TODO: Consider completing this and making it exact, once
// `MessageList`'s props are type-checked.
type Props = $ReadOnly<{
narrow: Narrow,
messages: $ReadOnlyArray<$ReadOnly<{ id: number, ... }>>,
...
}>;
export type ScrollStrategy =
| 'none'
| 'preserve-position'
| 'scroll-to-anchor'
| 'scroll-to-bottom-if-near-bottom';
export const getScrollStrategy = (prevProps: Props, nextProps: Props): ScrollStrategy => {
const prevMessages = prevProps.messages;
const nextMessages = nextProps.messages;
if (nextMessages.length === 0) {
// No messages.
return 'none';
}
if (!isEqual(prevProps.narrow, nextProps.narrow)) {
// Different narrow.
return 'scroll-to-anchor';
}
if (prevMessages.length === 0) {
// All new messages.
return 'scroll-to-anchor';
}
if (prevMessages[prevMessages.length - 1].id < nextMessages[0].id) {
// Messages replaced.
return 'scroll-to-anchor';
}
if (prevMessages.length === nextMessages.length) {
// No new messages.
return 'preserve-position';
}
if (prevMessages[0].id > nextMessages[0].id) {
// Old messages added.
return 'preserve-position';
}
if (
nextMessages.length > 1
&& prevMessages[prevMessages.length - 1].id === nextMessages[nextMessages.length - 2].id
) {
// Only one new message.
return 'scroll-to-bottom-if-near-bottom';
}
return 'preserve-position';
};
```
|
/content/code_sandbox/src/message/scrollStrategy.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 400
|
```javascript
/* @flow strict-local */
import React, { useCallback } from 'react';
import type { Node } from 'react';
import { View } from 'react-native';
import type { Stream, Narrow } from '../types';
import { useSelector } from '../react-redux';
import * as api from '../api';
import ZulipButton from '../common/ZulipButton';
import ZulipTextIntl from '../common/ZulipTextIntl';
import { getAuth, getStreamInNarrow } from '../selectors';
import styles from '../styles';
type Props = $ReadOnly<{|
narrow: Narrow,
|}>;
export default function NotSubscribed(props: Props): Node {
const auth = useSelector(getAuth);
const stream: $ReadOnly<{ ...Stream, ... }> = useSelector(state =>
getStreamInNarrow(state, props.narrow),
);
const subscribeToStream = useCallback(() => {
// This still uses a stream name (#3918) because the API method does; see there.
api.subscriptionAdd(auth, [{ name: stream.name }]);
}, [auth, stream]);
return (
<View style={styles.disabledComposeBox}>
<ZulipTextIntl
style={styles.disabledComposeText}
text="You are not subscribed to this stream"
/>
{!stream.invite_only && (
<ZulipButton
style={styles.disabledComposeButton}
text="Subscribe"
onPress={subscribeToStream}
/>
)}
</View>
);
}
```
|
/content/code_sandbox/src/message/NotSubscribed.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 315
|
```javascript
/* @flow strict-local */
import * as logging from '../utils/logging';
import * as NavigationService from '../nav/NavigationService';
import type { GetText, Message, Narrow, ThunkAction } from '../types';
import { getAuth, getRealm, getMessages, getZulipFeatureLevel } from '../selectors';
import {
getNearOperandFromLink,
getNarrowFromNarrowLink,
isNarrowLink,
} from '../utils/internalLinks';
import { openLinkWithUserPreference } from '../utils/openLink';
import { navigateToChat } from '../nav/navActions';
import { FIRST_UNREAD_ANCHOR } from '../anchor';
import { getStreamsById, getStreamsByName } from '../subscriptions/subscriptionSelectors';
import * as api from '../api';
import { isUrlOnRealm, tryParseUrl } from '../utils/url';
import { getOwnUserId } from '../users/userSelectors';
import {
isTopicNarrow,
isStreamNarrow,
topicNarrow,
streamIdOfNarrow,
topicOfNarrow,
streamNarrow,
caseNarrowDefault,
isConversationNarrow,
} from '../utils/narrow';
import { hasMessageEverBeenInStream, hasMessageEverHadTopic } from './messageSelectors';
import { showErrorAlert } from '../utils/info';
import { isNarrowValid } from '../chat/narrowsSelectors';
/**
* Navigate to the given narrow.
*/
export const doNarrow =
(narrow: Narrow, anchor: number = FIRST_UNREAD_ANCHOR): ThunkAction<void> =>
(dispatch, getState) => {
// TODO: Use `anchor` to open the message list to a particular message.
NavigationService.dispatch(navigateToChat(narrow));
};
/**
* Find the given message, either locally or on the server.
*
* If we have the message locally, avoids any network request.
*
* Returns null if we can't find the message -- it doesn't exist, or our
* user can't see it, or a server request for it failed, or the server was
* simply too old (FL <120).
*
* N.B.: Gives a bad experience when the request takes a long time. We
* should fix that; see TODOs.
*/
const getSingleMessage =
(messageId: number): ThunkAction<Promise<Message | null>> =>
async (dispatch, getState) => {
const state = getState();
const messages = getMessages(state);
let message = messages.get(messageId);
if (message) {
return message;
}
// TODO: Give feedback when the server round trip takes longer than
// expected.
// TODO: Let the user cancel the request so we don't force a doNarrow
// after they've given up on tapping the link, and perhaps forgotten
// about it. Like any request, this might take well over a minute to
// resolve, or never resolve.
// TODO: When these are fixed, remove warning in jsdoc.
const auth = getAuth(state);
const zulipFeatureLevel = getZulipFeatureLevel(state);
const allowEditHistory = getRealm(state).allowEditHistory;
if (zulipFeatureLevel < 120) {
// TODO(server-5.0): Simplify; simplify jsdoc to match.
// api.getSingleMessage won't give us the message's stream and
// topic; see there.
return null;
}
try {
message = await api.getSingleMessage(
auth,
{ message_id: messageId },
zulipFeatureLevel,
allowEditHistory,
);
} catch {
return null;
}
// The FL 120 condition on calling api.getSingleMessage should ensure
// `message` isn't void.
// TODO(server-5.0): Simplify away.
if (!message) {
logging.error('`message` from api.getSingleMessage unexpectedly falsy');
return null;
}
return message;
};
/**
* Adjust a /near/ link as needed to account for message moves.
*
* It feels quite broken when a link is clearly meant to get you to a
* specific message, but tapping it brings you to a narrow where the message
* *used* to be but isn't anymore because it was moved to a new stream or
* topic. This was #5306.
*
* This action, when it can, recognizes when that's about to happen and
* instead finds the narrow for the message's current stream/topic.
*
* To do so, it obviously needs to know the message's current stream/topic.
* If those can't be gotten from Redux, we ask the server. If the server
* can't help us (gives an error), we can't help the user, so we won't
* follow a move in that case.
*/
const adjustNarrowForMoves =
(narrow: Narrow, nearOperand: number): ThunkAction<Promise<Narrow>> =>
async (dispatch, getState) => {
// Many control-flow paths here simply return the original narrow.
//
// We do this when the link is meant to find the specific message
// identified by nearOperand, and:
// - nearOperand refers to a message that wasn't moved outside the
// narrow specified by the link, or
// - nearOperand *might* refer to a message that was moved, but we don't
// know; we've tried and failed to find out.
//
// We also do this to insist on the traditional meaning of "near" before
// the message-move feature: take the narrow's stream/topic/etc.
// literally, and open to the message "nearest" the given ID (sent
// around the same time), even if the message with that ID isn't
// actually in the narrow [1].
//
// User docs on moving messages:
// path_to_url
// path_to_url
//
// [1] Tim points out, at
// path_to_url#narrow/stream/101-design/topic/redirects.20from.20near.20links/near/1343095 :
// "[] useful for situations where you might replace an existing
// search for `stream: 1/topic: 1/near: 15` with
// `stream: 2/topic: 2/near: 15` in order to view what was happening
// in another conversation at the same time as an existing
// conversation."
const streamIdOperand =
isStreamNarrow(narrow) || isTopicNarrow(narrow) ? streamIdOfNarrow(narrow) : null;
const topicOperand = isTopicNarrow(narrow) ? topicOfNarrow(narrow) : null;
if (streamIdOperand === null && topicOperand === null) {
// Message moves only happen by changing the stream and/or topic.
return narrow;
}
const message = await dispatch(getSingleMessage(nearOperand));
if (!message) {
// We couldn't find the message. Hopefully it wasn't moved,
// if it exists or ever did.
return narrow;
}
if (message.type === 'private') {
// A PM could never have been moved.
return narrow;
}
if (
(topicOperand === null || topicOperand === message.subject)
&& (streamIdOperand === null || streamIdOperand === message.stream_id)
) {
// The message is still in the stream and/or topic in the link.
return narrow;
}
if (
(topicOperand !== null && hasMessageEverHadTopic(message, topicOperand) === false)
|| (streamIdOperand !== null && hasMessageEverBeenInStream(message, streamIdOperand) === false)
) {
// The message was never in the narrow specified by the link. That'd
// be an odd link to put in a messageanyway, perhaps we're meant to
// use the traditional meaning of "near"; see large block comment at
// top of function.
return narrow;
}
// If we couldn't access the edit history in the checks above, assume
// the message was moved. It's the likeliest explanation why its topic
// and/or stream don't match the narrow link.
const { stream_id, subject } = message;
// Reinterpret the link's narrow with the message's current stream
// and/or topic.
return caseNarrowDefault(
narrow,
{
stream: () => streamNarrow(stream_id),
topic: () => topicNarrow(stream_id, subject),
},
() => narrow,
);
};
/**
* Narrow to a /near/ link, possibly after reinterpreting it for a message move.
*
* See `adjustNarrowForMoves` for more discussion.
*
* N.B.: Gives a bad experience when the request takes a long time. We
* should fix that; see `getSingleMessage`.
*/
const doNarrowNearLink =
(narrow: Narrow, nearOperand: number): ThunkAction<Promise<void>> =>
async (dispatch, getState) => {
const adjustedNarrow = await dispatch(adjustNarrowForMoves(narrow, nearOperand));
dispatch(doNarrow(adjustedNarrow, nearOperand));
};
/**
* Handle a link tap that isn't an image we want to show in the lightbox.
*/
export const messageLinkPress =
(href: string, _: GetText): ThunkAction<Promise<void>> =>
async (dispatch, getState, { getGlobalSettings }) => {
const state = getState();
const auth = getAuth(state);
const streamsById = getStreamsById(state);
const streamsByName = getStreamsByName(state);
const ownUserId = getOwnUserId(state);
const globalSettings = getGlobalSettings();
const parsedUrl = tryParseUrl(href, auth.realm);
if (!parsedUrl) {
showErrorAlert(_('Cannot open link'), _('Invalid URL.'));
return;
}
if (isNarrowLink(parsedUrl, auth.realm)) {
const narrow = getNarrowFromNarrowLink(
parsedUrl,
auth.realm,
streamsById,
streamsByName,
ownUserId,
);
if (!narrow) {
// Open mobile web, because it could be a valid narrow link that web
// can handle but mobile can't; our Narrow type can't represent it.
//
// Could also be an invalid narrow link, or one that we *could*
// parse but just haven't (e.g., operands in an unexpected order).
// Opening the browser won't be ideal in those cases.
openLinkWithUserPreference(parsedUrl, globalSettings);
return;
}
const nearOperand = getNearOperandFromLink(parsedUrl, auth.realm);
if (!isNarrowValid(state, narrow)) {
// E.g., a stream that's hidden from our user (perhaps doesn't exist).
const msg =
nearOperand !== null
? 'That message could not be found.'
: isConversationNarrow(narrow)
? 'That conversation could not be found.'
: 'Those messages could not be found.';
showErrorAlert(_('Cannot open link'), _(msg));
return;
}
if (nearOperand === null) {
dispatch(doNarrow(narrow));
return;
}
await dispatch(doNarrowNearLink(narrow, nearOperand));
} else if (!isUrlOnRealm(parsedUrl, auth.realm)) {
openLinkWithUserPreference(parsedUrl, globalSettings);
} else {
const url = (await api.tryGetFileTemporaryUrl(parsedUrl, auth)) ?? parsedUrl;
openLinkWithUserPreference(url, globalSettings);
}
};
```
|
/content/code_sandbox/src/message/messagesActions.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 2,531
|
```javascript
/* @flow strict-local */
import type { Message, Narrow, Outbox, MessageListElement } from '../types';
import { isConversationNarrow, isStreamNarrow } from '../utils/narrow';
import { isSameRecipient } from '../utils/recipient';
import { isSameDay } from '../utils/date';
// Prefer getMessageListElementsMemoized.
export default (
messages: $ReadOnlyArray<Message | Outbox>,
narrow: Narrow,
): $ReadOnlyArray<MessageListElement> => {
// A recipient header identifies the conversation the messages after it
// are in. We show them unless the narrow already contains that information.
const canShowRecipientHeaders = !isConversationNarrow(narrow);
const pieces: MessageListElement[] = [];
for (let i = 0; i < messages.length; i++) {
const message = messages[i];
const prevMessage: typeof message | void = messages[i - 1];
// We show a date separator at the top, and whenever the day changes.
const showDateSeparator =
!prevMessage
|| !isSameDay(new Date(prevMessage.timestamp * 1000), new Date(message.timestamp * 1000));
if (showDateSeparator) {
pieces.push({
key: [message.id, 0],
type: 'time',
timestamp: message.timestamp,
subsequentMessage: message,
});
}
// If we show recipient headers here at all, we do so at the top and
// whenever the recipient changes.
const showRecipientHeader =
canShowRecipientHeaders && (!prevMessage || !isSameRecipient(prevMessage, message));
if (showRecipientHeader) {
pieces.push({
type: 'header',
key: [message.id, 1],
style: isStreamNarrow(narrow)
? 'topic+date'
: // eslint-disable-line operator-linebreak
// If it's a conversation narrow (AKA a topic or PM narrow),
// we're not making a HeaderMessageListElement in the first
// place; see `canShowRecipientHeaders` above. So this case
// doesn't mean headers will show up in conversation narrows.
'full',
subsequentMessage: message,
});
}
// We show the sender at the top and whenever the sender changes.
// We also reaffirm the sender whenever we've shown a date separator or
// recipient header, because our visual design has it bind tighter than
// either of those.
const showSender =
!prevMessage
|| prevMessage.sender_id !== message.sender_id
|| showDateSeparator
|| showRecipientHeader;
pieces.push({
key: [message.id, 2],
type: 'message',
isBrief: !showSender,
message,
});
}
return pieces;
};
```
|
/content/code_sandbox/src/message/getMessageListElements.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 604
|
```javascript
/* @flow strict-local */
import * as logging from '../utils/logging';
import type {
Auth,
Narrow,
PerAccountState,
Message,
PerAccountAction,
Stream,
ThunkAction,
UserId,
LocalizableText,
} from '../types';
import * as api from '../api';
import {
Server5xxError,
NetworkError,
ApiError,
MalformedResponseError,
ServerTooOldError,
kMinAllowedServerVersion,
} from '../api/apiErrors';
import {
getAuth,
getRealm,
getCaughtUpForNarrow,
getStreamsById,
getZulipFeatureLevel,
} from '../selectors';
import config from '../config';
import {
MESSAGE_FETCH_START,
MESSAGE_FETCH_ERROR,
MESSAGE_FETCH_COMPLETE,
} from '../actionConstants';
import { FIRST_UNREAD_ANCHOR, LAST_MESSAGE_ANCHOR } from '../anchor';
import { ALL_PRIVATE_NARROW, apiNarrowOfNarrow, caseNarrow, topicNarrow } from '../utils/narrow';
import { BackoffMachine, promiseTimeout, TimeoutError } from '../utils/async';
import { getAllUsersById, getOwnUserId } from '../users/userSelectors';
import type { ServerSettings } from '../api/settings/getServerSettings';
import {
kMinSupportedVersion,
kNextMinSupportedVersion,
kServerSupportDocUrl,
} from '../common/ServerCompatBanner';
const messageFetchStart = (
narrow: Narrow,
numBefore: number,
numAfter: number,
): PerAccountAction => ({
type: MESSAGE_FETCH_START,
narrow,
numBefore,
numAfter,
});
const messageFetchError = (args: {| narrow: Narrow, error: mixed |}): PerAccountAction => {
const { narrow, error } = args;
return {
type: MESSAGE_FETCH_ERROR,
narrow,
error,
};
};
const messageFetchComplete = (args: {|
messages: $ReadOnlyArray<Message>,
narrow: Narrow,
anchor: number,
numBefore: number,
numAfter: number,
foundNewest: boolean,
foundOldest: boolean,
ownUserId: UserId,
|}): PerAccountAction => {
const { messages, narrow, anchor, numBefore, numAfter, foundNewest, foundOldest, ownUserId } =
args;
return {
type: MESSAGE_FETCH_COMPLETE,
messages,
narrow,
anchor,
numBefore,
numAfter,
foundNewest,
foundOldest,
ownUserId,
};
};
/**
* Get and return messages from the network, keeping Redux up-to-date.
*
* The returned Promise resolves with the messages, or rejects on a
* failed network request or any failure to process data and get it
* stored in Redux. If it rejects, it tells Redux about it.
*/
export const fetchMessages =
(fetchArgs: {|
narrow: Narrow,
anchor: number,
numBefore: number,
numAfter: number,
|}): ThunkAction<
Promise<{| messages: $ReadOnlyArray<Message>, foundNewest: boolean, foundOldest: boolean |}>,
> =>
async (dispatch, getState) => {
dispatch(messageFetchStart(fetchArgs.narrow, fetchArgs.numBefore, fetchArgs.numAfter));
try {
const { messages, found_newest, found_oldest } =
// TODO: If `MESSAGE_FETCH_ERROR` isn't the right way to respond
// to a timeout, maybe make a new action.
// eslint-disable-next-line no-use-before-define
await tryFetch(() =>
api.getMessages(
getAuth(getState()),
{
...fetchArgs,
narrow: apiNarrowOfNarrow(
fetchArgs.narrow,
getAllUsersById(getState()),
getStreamsById(getState()),
),
useFirstUnread: fetchArgs.anchor === FIRST_UNREAD_ANCHOR, // TODO: don't use this; see #4203
},
getZulipFeatureLevel(getState()),
getRealm(getState()).allowEditHistory,
),
);
dispatch(
messageFetchComplete({
...fetchArgs,
messages,
foundNewest: found_newest,
foundOldest: found_oldest,
ownUserId: getOwnUserId(getState()),
}),
);
return { messages, foundNewest: found_newest, foundOldest: found_oldest };
} catch (errorIllTyped) {
const e: mixed = errorIllTyped; // path_to_url
dispatch(
messageFetchError({
narrow: fetchArgs.narrow,
error: e,
}),
);
// $FlowFixMe[incompatible-cast]: assuming caught exception was Error
logging.warn((e: Error), {
message: 'Message-fetch error',
// Describe the narrow without sending sensitive data to Sentry.
narrow: caseNarrow(fetchArgs.narrow, {
stream: () => 'stream',
topic: () => 'topic',
pm: ids => (ids.length > 1 ? 'pm (group)' : 'pm (1:1)'),
home: () => 'all',
starred: () => 'starred',
mentioned: () => 'mentioned',
allPrivate: () => 'all-pm',
search: () => 'search',
}),
anchor: fetchArgs.anchor,
numBefore: fetchArgs.numBefore,
numAfter: fetchArgs.numAfter,
});
throw e;
}
};
/** Some message ID in the conversation; void if there are none. */
// This corresponds to web's message_edit.with_first_message_id. (Note
// it's actually the latest, despite the name; really just needs to be
// *some* message ID in the topic.)
export async function fetchSomeMessageIdForConversation(
auth: Auth,
streamId: number,
topic: string,
streamsById: Map<number, Stream>,
zulipFeatureLevel: number,
): Promise<number | void> {
const data = await api.getMessages(
auth,
{
anchor: LAST_MESSAGE_ANCHOR,
numBefore: 1,
numAfter: 0,
// TODO(server-2.1): These users and streams maps should go away;
// cut the streamsById param from this function too.
// HACK: This fake, empty users map is OK because apiNarrowOfNarrow
// doesn't consult the users map for topic narrows.
narrow: apiNarrowOfNarrow(topicNarrow(streamId, topic), new Map(), streamsById),
},
zulipFeatureLevel,
false, // chosen arbitrarily; irrelevant to this function's task
);
// FlowIssue: can be void because array can be empty
const message: Message | void = data.messages[0];
return message?.id;
}
/** Private; exported only for tests. */
export const isFetchNeededAtAnchor = (
state: PerAccountState,
narrow: Narrow,
anchor: number,
): boolean => {
// Ideally this would detect whether, even if we don't have *all* the
// messages in the narrow, we have enough of them around the anchor
// to show a message list already. For now it's simple and cautious.
const caughtUp = getCaughtUpForNarrow(state, narrow);
return !(caughtUp.newer && caughtUp.older);
};
/**
* Fetch messages in the given narrow, around the given anchor.
*
* For almost all types of data we need from the server, the magic of the
* Zulip event system provides us a complete, updating view of all the data
* we could want. For background and links to docs, see `MessagesState` and
* `registerAndStartPolling`.
*
* Message data is the one major exception, where as a result we have to go
* fetch more data from the server as the user navigates around.
*
* This is the main function used for that, especially as the user navigates
* to a given narrow.
*
* See also the `message` event and corresponding `EVENT_NEW_MESSAGE`
* action, which is how we learn about new messages in real time.
*
* See also handlers for the `MESSAGE_FETCH_COMPLETE` action, which this
* dispatches with the data it receives from the server.
*/
export const fetchMessagesInNarrow =
(
narrow: Narrow,
anchor: number = FIRST_UNREAD_ANCHOR,
): ThunkAction<
Promise<{|
messages: $ReadOnlyArray<Message>,
foundNewest: boolean,
foundOldest: boolean,
|} | void>,
> =>
async (dispatch, getState) => {
if (!isFetchNeededAtAnchor(getState(), narrow, anchor)) {
return undefined;
}
return dispatch(
fetchMessages({
narrow,
anchor,
numBefore: config.messagesPerRequest / 2,
numAfter: config.messagesPerRequest / 2,
}),
);
};
/**
* Fetch the few most recent PMs.
*
* For old servers, we do this eagerly in `registerAndStartPolling`, in order to
* let us show something useful in the PM conversations screen.
* Zulip Server 2.1 added a custom-made API to help us do this better;
* see #3133.
*
* See `fetchMessagesInNarrow` for further background.
*/
// TODO(server-2.1): Delete this.
export const fetchPrivateMessages =
(): ThunkAction<Promise<void>> => async (dispatch, getState) => {
const auth = getAuth(getState());
const { messages, found_newest, found_oldest } = await api.getMessages(
auth,
{
narrow: apiNarrowOfNarrow(
ALL_PRIVATE_NARROW,
getAllUsersById(getState()),
getStreamsById(getState()),
),
anchor: LAST_MESSAGE_ANCHOR,
numBefore: 100,
numAfter: 0,
},
getZulipFeatureLevel(getState()),
getRealm(getState()).allowEditHistory,
);
dispatch(
messageFetchComplete({
messages,
narrow: ALL_PRIVATE_NARROW,
anchor: LAST_MESSAGE_ANCHOR,
numBefore: 100,
numAfter: 0,
foundNewest: found_newest,
foundOldest: found_oldest,
ownUserId: getOwnUserId(getState()),
}),
);
};
/**
* Makes a request with a timeout. If asked, retries on
* server/network operational errors until success.
*
* Waits between retries with a backoff.
*
* Other, non-retryable errors (client errors and all unexpected errors)
* will always propagate to the caller to be handled.
*
* The timeout's length is `config.requestLongTimeoutMs` and it is absolute:
* it triggers after that time has elapsed no matter whether the time was
* spent waiting to hear back from one request, or retrying a request
* unsuccessfully many times. The time spent waiting in backoff is included
* in that.
*/
export async function tryFetch<T>(
func: () => Promise<T>,
shouldRetry?: boolean = true,
): Promise<T> {
const backoffMachine = new BackoffMachine();
// TODO: Use AbortController instead of this stateful flag; #4170
let timerHasExpired = false;
try {
return await promiseTimeout(
(async () => {
while (true) {
if (timerHasExpired) {
// No one is listening for this Promise to settle, so stop
// doing more work.
throw new Error();
}
try {
return await func();
} catch (errorIllTyped) {
const e: mixed = errorIllTyped; // path_to_url
if (!(shouldRetry && (e instanceof Server5xxError || e instanceof NetworkError))) {
throw e;
}
}
await backoffMachine.wait();
}
// Without this, Flow 0.149.0 does not know this code is unreachable,
// and it incorrectly thinks Promise<undefined> could be returned,
// which is inconsistent with the stated Promise<T> return type.
// eslint-disable-next-line no-unreachable
throw new Error();
})(),
config.requestLongTimeoutMs,
);
} catch (errorIllTyped) {
const e: mixed = errorIllTyped; // path_to_url
if (e instanceof TimeoutError) {
timerHasExpired = true;
}
throw e;
}
}
export async function fetchServerSettings(realm: URL): Promise<
| {| +type: 'success', +value: ServerSettings |}
| {|
+type: 'error',
+title: LocalizableText,
+message: LocalizableText,
+learnMoreButton: {| +url: URL, +text?: LocalizableText |} | void,
|},
> {
try {
return { type: 'success', value: await api.getServerSettings(realm) };
} catch (errorIllTyped) {
const error: mixed = errorIllTyped;
const title = 'Could not connect';
let message = undefined;
let learnMoreButton = undefined;
// TODO(#4918): Recognize not-yet-implemented "org-deactivated" error;
// see path_to_url
if (error instanceof ApiError && error.message.length > 0) {
// E.g., "Subdomain required".
message = {
text: 'The server at {realm} said:\n\n{message}',
values: { realm: realm.toString(), message: error.message },
};
} else if (error instanceof NetworkError) {
message = {
text: 'Could not connect to {realm}. Please check your network connection and try again.',
values: { realm: realm.toString() },
};
} else if (error instanceof ServerTooOldError) {
message = {
text: '{realm} is running Zulip Server {version}, which is unsupported. The minimum supported version is Zulip Server {minSupportedVersion}.',
values: {
realm: realm.toString(),
version: error.version.raw(),
minSupportedVersion: kMinSupportedVersion.raw(),
},
};
learnMoreButton = { url: kServerSupportDocUrl };
logging.setTagsFromServerVersion(error.version);
logging.error(error, {
kMinAllowedServerVersion: kMinAllowedServerVersion.raw(),
kMinSupportedVersion: kMinSupportedVersion.raw(),
kNextMinSupportedVersion: kNextMinSupportedVersion.raw(),
});
} else if (error instanceof MalformedResponseError && error.httpStatus === 404) {
message = {
text: 'The server at {realm} does not seem to be a Zulip server.',
values: { realm: realm.toString() },
};
learnMoreButton = {
text: 'Find your Zulip server URL',
url: new URL('path_to_url#find-the-zulip-log-in-url'),
};
} else if (error instanceof Server5xxError) {
message = {
text: 'The server at {realm} encountered an error.',
values: { realm: realm.toString() },
};
} else {
message = {
text: 'Failed to connect to server: {realm}',
values: { realm: realm.toString() },
};
}
return { type: 'error', title, message, learnMoreButton };
}
}
```
|
/content/code_sandbox/src/message/fetchActions.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 3,322
|
```javascript
/* @flow strict-local */
import React, { useCallback } from 'react';
import type { Node } from 'react';
import { View, TouchableOpacity } from 'react-native';
import type { Stream, UserOrBot, Subscription } from '../types';
import { createStyleSheet } from '../styles';
import { useSelector } from '../react-redux';
import * as api from '../api';
import ZulipButton from '../common/ZulipButton';
import ZulipTextIntl from '../common/ZulipTextIntl';
import { getAuth } from '../selectors';
import { kWarningColor } from '../styles/constants';
import { getFullNameReactText } from '../users/userSelectors';
import { getRealm } from '../directSelectors';
type Props = $ReadOnly<{|
user: UserOrBot,
stream: Subscription | {| ...Stream, in_home_view: boolean |},
onDismiss: (user: UserOrBot) => void,
|}>;
const styles = createStyleSheet({
outer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
backgroundColor: kWarningColor,
paddingHorizontal: 16,
paddingVertical: 8,
},
text: {
flex: 1,
color: 'black',
},
button: {
backgroundColor: 'orange',
// Based on MarkAsReadButton.
// TODO make these less ad hoc.
// TODO also make the actual touch target taller, like 48px.
// (Can extend beyond the visual representation of the button itself.)
borderWidth: 0,
borderRadius: 16,
height: 32,
paddingLeft: 12,
paddingRight: 12,
},
buttonText: {
color: 'black',
},
});
export default function MentionedUserNotSubscribed(props: Props): Node {
const { user, stream, onDismiss } = props;
const auth = useSelector(getAuth);
const enableGuestUserIndicator = useSelector(state => getRealm(state).enableGuestUserIndicator);
const handleDismiss = useCallback(() => {
onDismiss(user);
}, [user, onDismiss]);
const subscribeToStream = useCallback(() => {
// This still uses a stream name (#3918) because the API method does; see there.
api.subscriptionAdd(auth, [{ name: stream.name }], [user.email]);
handleDismiss();
}, [auth, handleDismiss, stream, user]);
return (
<View>
<TouchableOpacity onPress={handleDismiss} style={styles.outer}>
<ZulipTextIntl
text={{
text: '{username} will not be notified unless you subscribe them to this stream.',
values: {
username: (
<ZulipTextIntl
inheritColor
inheritFontSize
text={getFullNameReactText({ user, enableGuestUserIndicator })}
/>
),
},
}}
style={styles.text}
/>
<ZulipButton
style={styles.button}
textStyle={styles.buttonText}
text="Subscribe"
onPress={subscribeToStream}
/>
</TouchableOpacity>
</View>
);
}
```
|
/content/code_sandbox/src/message/MentionedUserNotSubscribed.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 659
|
```javascript
/* @flow strict-local */
import * as eg from '../../__tests__/lib/exampleData';
import { HOME_NARROW } from '../../utils/narrow';
import getMessageListElements from '../getMessageListElements';
describe('getMessageListElements', () => {
const narrow = HOME_NARROW;
test('empty messages results in no pieces', () => {
const messageListElements = getMessageListElements([], HOME_NARROW);
expect(messageListElements).toEqual([]);
});
test('renders time, header and message for a single input', () => {
const message = { ...eg.streamMessage({ id: 12345 }), timestamp: 123 };
expect(getMessageListElements([message], narrow)).toMatchObject([
{ type: 'time', key: [message.id, 0] },
{ type: 'header', key: [message.id, 1] },
{ type: 'message', key: [message.id, 2] },
]);
});
test('several messages in same stream, from same person result in time row, header for the stream, three messages, only first of which is full detail', () => {
const stream = eg.stream;
const sender = eg.otherUser;
const message1 = eg.streamMessage({ stream, sender, id: 1 });
const message2 = eg.streamMessage({ stream, sender, id: 2 });
const message3 = eg.streamMessage({ stream, sender, id: 3 });
expect(getMessageListElements([message1, message2, message3], narrow)).toMatchObject([
{ type: 'time', key: [message1.id, 0] },
{ type: 'header', key: [message1.id, 1] },
{ type: 'message', key: [message1.id, 2], isBrief: false },
{ type: 'message', key: [message2.id, 2], isBrief: true },
{ type: 'message', key: [message3.id, 2], isBrief: true },
]);
});
test('several messages in same stream, from different people result in time row, header for the stream, three messages, only all full detail', () => {
const stream = eg.stream;
const message1 = eg.streamMessage({ stream, sender: eg.selfUser, id: 1 });
const message2 = eg.streamMessage({ stream, sender: eg.otherUser, id: 2 });
const message3 = eg.streamMessage({ stream, sender: eg.thirdUser, id: 3 });
expect(getMessageListElements([message1, message2, message3], narrow)).toMatchObject([
{ type: 'time', key: [message1.id, 0] },
{ type: 'header', key: [message1.id, 1] },
{ type: 'message', key: [message1.id, 2], isBrief: false },
{ type: 'message', key: [message2.id, 2], isBrief: false },
{ type: 'message', key: [message3.id, 2], isBrief: false },
]);
});
test('private messages between two people, results in time row, header and two full messages', () => {
const message1 = eg.pmMessage({
sender: eg.selfUser,
recipients: [eg.selfUser, eg.otherUser],
id: 1,
});
const message2 = eg.pmMessage({
sender: eg.otherUser,
recipients: [eg.selfUser, eg.otherUser],
id: 2,
});
expect(getMessageListElements([message1, message2], narrow)).toMatchObject([
{ type: 'time', key: [message1.id, 0] },
{ type: 'header', key: [message1.id, 1] },
{ type: 'message', key: [message1.id, 2], isBrief: false },
{ type: 'message', key: [message2.id, 2], isBrief: false },
]);
});
});
```
|
/content/code_sandbox/src/message/__tests__/getMessageListElements-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 872
|
```javascript
/* @flow strict-local */
import configureStore from 'redux-mock-store';
// $FlowFixMe[untyped-import]
import thunk from 'redux-thunk';
import { combinedThunkExtras } from '../../boot/store';
import { navigateToChat } from '../../nav/navActions';
import * as NavigationService from '../../nav/NavigationService';
import { messageLinkPress, doNarrow } from '../messagesActions';
import { streamNarrow, topicNarrow, pmNarrowFromUsersUnsafe } from '../../utils/narrow';
import * as eg from '../../__tests__/lib/exampleData';
import type { GlobalState } from '../../reduxTypes';
import type { Action } from '../../actionTypes';
import type { Stream, User } from '../../types';
import { mock_ } from '../../__tests__/lib/intl';
import * as logging from '../../utils/logging';
const mockStore = configureStore([thunk.withExtraArgument(combinedThunkExtras)]);
const streamNarrowObj = streamNarrow(eg.stream.stream_id);
describe('messageActions', () => {
describe('messageLinkPress', () => {
beforeAll(() => {
// suppress `logging.info` output
// $FlowFixMe[prop-missing]: Jest mock
logging.info.mockReturnValue();
});
function prepare(args: {| streams?: Stream[], users?: User[] |} = Object.freeze({})) {
const { streams = [], users = [] } = args;
return {
store: mockStore<GlobalState, Action>(
eg.reduxStatePlus({
session: { ...eg.plusReduxState.session, isHydrated: true },
streams: [...eg.plusReduxState.streams, ...streams],
users: [...eg.plusReduxState.users, ...users],
}),
),
};
}
/* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "checkLink"] }] */
async function checkLink(store, link, expectedNarrow) {
// $FlowFixMe[cannot-write] Teach Flow about mocking
NavigationService.dispatch = jest.fn();
const action = messageLinkPress(link, mock_);
await store.dispatch(action);
expect(NavigationService.dispatch).toHaveBeenCalledWith(navigateToChat(expectedNarrow));
// $FlowFixMe[prop-missing] Teach Flow about mocking
NavigationService.dispatch.mockReset();
}
test('handles /near/ links', async () => {
const stream = eg.makeStream({ stream_id: 1, name: 'test' });
const user1 = eg.makeUser({ user_id: 1, full_name: 'user 1' });
const user2 = eg.makeUser({ user_id: 2, full_name: 'user 2' });
const { store } = prepare({ streams: [stream], users: [user1, user2] });
await checkLink(store, '#narrow/stream/1-test/topic/hello/near/1', topicNarrow(1, 'hello'));
await checkLink(store, '#narrow/dm/1-user-1/near/1', pmNarrowFromUsersUnsafe([user1]));
await checkLink(
store,
'#narrow/dm/1,2-group/near/1',
pmNarrowFromUsersUnsafe([user1, user2]),
);
});
test('handles /with/ links', async () => {
const stream = eg.makeStream({ stream_id: 1, name: 'test' });
const user1 = eg.makeUser({ user_id: 1, full_name: 'user 1' });
const user2 = eg.makeUser({ user_id: 2, full_name: 'user 2' });
const { store } = prepare({ streams: [stream], users: [user1, user2] });
await checkLink(store, '#narrow/stream/1-test/topic/hello/with/1', topicNarrow(1, 'hello'));
await checkLink(store, '#narrow/dm/1-user-1/with/1', pmNarrowFromUsersUnsafe([user1]));
await checkLink(
store,
'#narrow/dm/1,2-group/with/1',
pmNarrowFromUsersUnsafe([user1, user2]),
);
});
});
describe('doNarrow', () => {
test('action to push to nav dispatched', () => {
// $FlowFixMe[cannot-write]
NavigationService.dispatch = jest.fn();
const store = mockStore<GlobalState, Action>(
eg.reduxState({
accounts: [eg.selfAccount],
session: { ...eg.baseReduxState.session, isHydrated: true },
streams: [eg.stream],
}),
);
store.dispatch(doNarrow(streamNarrowObj));
expect(NavigationService.dispatch).toHaveBeenCalledWith(navigateToChat(streamNarrowObj));
});
});
});
```
|
/content/code_sandbox/src/message/__tests__/messageActions-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,039
|
```javascript
/* @flow strict-local */
import { streamNarrow } from '../../utils/narrow';
import { getScrollStrategy } from '../scrollStrategy';
import * as eg from '../../__tests__/lib/exampleData';
const someNarrow = streamNarrow(eg.stream.stream_id);
const anotherStream = eg.makeStream();
const anotherNarrow = streamNarrow(anotherStream.stream_id);
describe('getScrollStrategy', () => {
test('initial load positions at anchor (first unread)', () => {
const prevProps = {
messages: [],
narrow: someNarrow,
};
const nextProps = {
messages: [{ id: 1 }, { id: 2 }, { id: 3 }],
narrow: someNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('scroll-to-anchor');
});
test('switching narrows position at anchor (first unread)', () => {
const prevProps = {
messages: [{ id: 1 }, { id: 2 }, { id: 3 }],
narrow: someNarrow,
};
const nextProps = {
messages: [{ id: 2 }, { id: 3 }, { id: 5 }, { id: 6 }],
narrow: anotherNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('scroll-to-anchor');
});
test('when no messages, no scroll', () => {
const prevProps = {
messages: [],
narrow: someNarrow,
};
const nextProps = {
messages: [],
narrow: anotherNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('none');
});
test('when messages replaced go to anchor', () => {
const prevProps = {
messages: [{ id: 1 }, { id: 2 }, { id: 3 }],
narrow: someNarrow,
};
const nextProps = {
messages: [{ id: 5 }, { id: 6 }, { id: 7 }],
narrow: someNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('scroll-to-anchor');
});
// (It's not clear this test case makes sense.)
test('when older messages loaded (plus one lost) preserve scroll position', () => {
const prevProps = {
messages: [{ id: 2 }, { id: 3 }, { id: 4 }],
narrow: someNarrow,
};
const nextProps = {
messages: [{ id: 0 }, { id: 1 }, { id: 3 }, { id: 4 }],
narrow: someNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('preserve-position');
});
test('when older messages loaded preserve scroll position', () => {
const prevProps = {
messages: [{ id: 4 }, { id: 5 }, { id: 6 }],
narrow: someNarrow,
};
const nextProps = {
messages: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }],
narrow: someNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('preserve-position');
});
test('when newer messages loaded preserve scroll position', () => {
const prevProps = {
messages: [{ id: 4 }, { id: 5 }, { id: 6 }],
narrow: someNarrow,
};
const nextProps = {
messages: [{ id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }, { id: 8 }, { id: 9 }],
narrow: someNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('preserve-position');
});
test('if only one new message scroll to bottom if near bottom', () => {
const prevProps = {
messages: [{ id: 4 }, { id: 5 }, { id: 6 }],
narrow: someNarrow,
};
const nextProps = {
messages: [{ id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }],
narrow: someNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('scroll-to-bottom-if-near-bottom');
});
test('when loading new messages, scroll to anchor', () => {
const prevProps = {
messages: [],
narrow: someNarrow,
};
const nextProps = {
messages: [{ id: 1 }, { id: 2 }, { id: 3 }],
narrow: someNarrow,
};
const result = getScrollStrategy(prevProps, nextProps);
expect(result).toEqual('scroll-to-anchor');
});
});
```
|
/content/code_sandbox/src/message/__tests__/scrollStrategy-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,080
|
```javascript
/* @flow strict-local */
import invariant from 'invariant';
import configureStore from 'redux-mock-store';
// $FlowFixMe[untyped-import]
import thunk from 'redux-thunk';
import Immutable from 'immutable';
import type { GlobalState } from '../../reduxTypes';
import type { Action } from '../../actionTypes';
import { isFetchNeededAtAnchor, fetchMessages, tryFetch } from '../fetchActions';
import { FIRST_UNREAD_ANCHOR } from '../../anchor';
import type { FetchedMessage } from '../../api/rawModelTypes';
import { streamNarrow, HOME_NARROW, keyFromNarrow } from '../../utils/narrow';
import { GravatarURL } from '../../utils/avatar';
import * as eg from '../../__tests__/lib/exampleData';
import { Server5xxError, NetworkError } from '../../api/apiErrors';
import { fakeSleep } from '../../__tests__/lib/fakeTimers';
import { TimeoutError, BackoffMachine } from '../../utils/async';
import * as logging from '../../utils/logging';
const mockStore = configureStore([thunk]);
const narrow = streamNarrow(eg.stream.stream_id);
const streamNarrowStr = keyFromNarrow(narrow);
// $FlowFixMe[cannot-write]
global.FormData = class FormData {};
const BORING_RESPONSE = JSON.stringify({
messages: [],
result: 'success',
});
describe('fetchActions', () => {
afterEach(() => {
// $FlowFixMe[prop-missing]: See mock in jest/globalFetch.js.
fetch.reset();
});
describe('isFetchNeededAtAnchor', () => {
test("false if we're caught up, even if there are no messages", () => {
const state = eg.reduxStatePlus({
session: { ...eg.plusReduxState.session, isHydrated: true },
caughtUp: {
[streamNarrowStr]: {
newer: true,
older: true,
},
},
narrows: Immutable.Map([[streamNarrowStr, []]]),
streams: [eg.stream],
});
const result = isFetchNeededAtAnchor(state, narrow, FIRST_UNREAD_ANCHOR);
expect(result).toBeFalse();
});
test("true if we're not caught up, even if we have a few messages", () => {
const message1 = eg.streamMessage({ id: 1 });
const message2 = eg.streamMessage({ id: 2 });
const state = eg.reduxStatePlus({
session: { ...eg.plusReduxState.session, isHydrated: true },
caughtUp: {
[streamNarrowStr]: {
newer: false,
older: false,
},
},
narrows: Immutable.Map([[streamNarrowStr, [1]]]),
messages: eg.makeMessagesState([message1, message2]),
streams: [eg.stream],
});
const result = isFetchNeededAtAnchor(state, narrow, FIRST_UNREAD_ANCHOR);
expect(result).toBeTrue();
});
});
describe('tryFetch', () => {
beforeAll(() => {
// So we don't have to think about the (random, with jitter)
// duration of these waits in these tests. `BackoffMachine` has
// its own unit tests already, so we don't have to test that it
// waits for the right amount of time.
// $FlowFixMe[cannot-write]
BackoffMachine.prototype.wait = async function wait() {
return fakeSleep(100);
};
});
afterEach(() => {
expect(jest.getTimerCount()).toBe(0);
jest.clearAllTimers();
});
describe.each([false, true])(
'whether or not asked to retry; was asked this time? %s',
withRetry => {
test('resolves any promise, if there is no exception', async () => {
const tryFetchFunc = jest.fn(async () => {
await fakeSleep(10);
return 'hello';
});
await expect(tryFetch(tryFetchFunc, withRetry)).resolves.toBe('hello');
expect(tryFetchFunc).toHaveBeenCalledTimes(1);
await expect(tryFetchFunc.mock.results[0].value).resolves.toBe('hello');
jest.runAllTimers();
});
test('Rethrows an unexpected error without retrying', async () => {
const unexpectedError = new Error('You have displaced the mirth.');
const func = jest.fn(async () => {
throw unexpectedError;
});
await expect(tryFetch(func, withRetry)).rejects.toThrow(unexpectedError);
expect(func).toHaveBeenCalledTimes(1);
jest.runAllTimers();
});
test('times out after hanging on one request', async () => {
const tryFetchPromise = tryFetch(async () => {
await new Promise((resolve, reject) => {});
}, withRetry);
await fakeSleep(60000);
return expect(tryFetchPromise).rejects.toThrow(TimeoutError);
});
},
);
describe('if asked to retry', () => {
test('retries a call if there is a recoverable error', async () => {
const serverError = new Server5xxError(500);
// fail on first call, succeed second time
let callCount = 0;
const thrower = jest.fn(() => {
callCount++;
if (callCount === 1) {
throw serverError;
}
return 'hello';
});
const tryFetchFunc = jest.fn(async () => {
await fakeSleep(10);
return thrower();
});
await expect(tryFetch(tryFetchFunc, true)).resolves.toBe('hello');
expect(tryFetchFunc).toHaveBeenCalledTimes(2);
await expect(tryFetchFunc.mock.results[0].value).rejects.toThrow(serverError);
await expect(tryFetchFunc.mock.results[1].value).resolves.toBe('hello');
jest.runAllTimers();
});
test('retries a call if there is a network error', async () => {
const networkError = new NetworkError();
// fail on first call, succeed second time
let callCount = 0;
const thrower = jest.fn(() => {
callCount++;
if (callCount === 1) {
throw networkError;
}
return 'hello';
});
const tryFetchFunc = jest.fn(async () => {
await fakeSleep(10);
return thrower();
});
await expect(tryFetch(tryFetchFunc)).resolves.toBe('hello');
expect(tryFetchFunc).toHaveBeenCalledTimes(2);
await expect(tryFetchFunc.mock.results[0].value).rejects.toThrow(networkError);
await expect(tryFetchFunc.mock.results[1].value).resolves.toBe('hello');
jest.runAllTimers();
});
test('times out after many short-duration 5xx errors', async () => {
const func = jest.fn(async () => {
await fakeSleep(50);
throw new Server5xxError(500);
});
await expect(tryFetch(func, true)).rejects.toThrow(TimeoutError);
expect(func.mock.calls.length).toBeGreaterThan(50);
});
});
describe('if not asked to retry', () => {
test('does not retry a call if there is a server error', async () => {
const serverError = new Server5xxError(500);
const tryFetchFunc = jest.fn(async () => {
await fakeSleep(10);
throw serverError;
});
await expect(tryFetch(tryFetchFunc, false)).rejects.toThrow(serverError);
expect(tryFetchFunc).toHaveBeenCalledTimes(1);
jest.runAllTimers();
});
});
});
describe('fetchMessages', () => {
const email = 'abc123@example.com';
const sender = eg.makeUser({
email,
avatar_url: GravatarURL.validateAndConstructInstance({ email }),
});
const message1 = eg.streamMessage({ id: 1, sender });
// message1 exactly as we receive it from the server, before our
// own transformations.
//
// TODO: Deduplicate this logic with similar logic in
// rawModelTypes-test.js.
const fetchedMessage1: FetchedMessage = {
...message1,
reactions: [],
avatar_url: null, // Null in server data will be transformed to a GravatarURL
edit_history: [],
};
const baseState = eg.reduxStatePlus({
narrows: Immutable.Map([[streamNarrowStr, [message1.id]]]),
realm: {
...eg.plusReduxState.realm,
allowEditHistory: true, // TODO: test with this `false`
},
});
describe('success', () => {
beforeEach(() => {
const response = {
messages: [fetchedMessage1],
result: 'success',
};
// $FlowFixMe[prop-missing]: See mock in jest/globalFetch.js.
fetch.mockResponseSuccess(JSON.stringify(response));
});
const store = mockStore<GlobalState, Action>(baseState);
test('message fetch success action is dispatched, messages are returned', async () => {
const returnValue = await store.dispatch(
fetchMessages({ narrow: HOME_NARROW, anchor: 0, numBefore: 1, numAfter: 1 }),
);
const actions = store.getActions();
expect(actions).toHaveLength(2);
expect(actions[0].type).toBe('MESSAGE_FETCH_START');
// Expect MESSAGE_FETCH_COMPLETE to be dispatched.
//
// TODO: More directly test that an error tripped in a reducer
// handling MESSAGE_FETCH_COMPLETE (e.g., from malformed data
// returned by a successful fetch) propagates to the caller.
// redux-mock-store does not call any reducers; it's only
// meant to test actions [1].
//
// We test this indirectly, for now: in the success case,
// check that MESSAGE_FETCH_COMPLETE is dispatched before the
// return. In real-live code (not using redux-mock-store), all
// the reducers will run as part of the dispatch call (or, for
// async actions, during the Promise returned by the dispatch
// call), not scheduled to run later. So, as long as
// MESSAGE_FETCH_COMPLETE is dispatched before the return, any
// errors from the reducers will propagate. It's not an async
// action, so the implementation doesn't even have to await
// it.
//
// In an ideal crunchy-shell [2] world, we'll have validated
// and rebuilt all data at the edge, making errors in the
// reducers impossible -- so we won't have to handle errors at
// that site.
//
// [1] path_to_url#redux-mock-store-
// [2] path_to_url#narrow/stream/243-mobile-team/topic/.23M4156.20Message.20List.20placeholders/near/928778
expect(actions[1].type).toBe('MESSAGE_FETCH_COMPLETE');
expect(returnValue.messages).toEqual([message1]);
});
});
describe('failure', () => {
beforeAll(() => {
// suppress `logging.warn` output
// $FlowFixMe[prop-missing]: Jest mock
logging.warn.mockReturnValue();
});
test('rejects when user is not logged in, dispatches MESSAGE_FETCH_ERROR', async () => {
const stateWithoutAccount = eg.reduxStatePlus({
accounts: [],
});
const store = mockStore<GlobalState, Action>(stateWithoutAccount);
const response = {
messages: [message1, eg.streamMessage({ id: 2 }), eg.streamMessage({ id: 3 })],
result: 'success',
};
// $FlowFixMe[prop-missing]: See mock in jest/globalFetch.js.
fetch.mockResponseSuccess(JSON.stringify(response));
await expect(
store.dispatch(
fetchMessages({ narrow: HOME_NARROW, anchor: 0, numBefore: 1, numAfter: 1 }),
),
).rejects.toThrow(
// Update this with changes to the message string or error type.
new Error('getAccount: must have account'),
);
const actions = store.getActions();
expect(actions[actions.length - 1]).toMatchObject({
type: 'MESSAGE_FETCH_ERROR',
// Update this with changes to the message string or error type.
error: new Error('getAccount: must have account'),
});
});
test("rejects when validation-at-the-edge can't handle data, dispatches MESSAGE_FETCH_ERROR", async () => {
// Regression test for #4156. There was a server bug that caused
// message data to be malformed, and though it was only briefly in
// main, a user did run into it in real life:
// path_to_url#issuecomment-655905093
//
// This validation is done in transformFetchedMessages in
// rawModelTypes.
const store = mockStore<GlobalState, Action>(baseState);
const response = {
// Flow would complain at `sender_email` if it
// type-checked `response`, but we should ignore it if that
// day comes. It's badly typed on purpose.
messages: [{ ...fetchedMessage1, avatar_url: null, sender_email: undefined }],
result: 'success',
};
// $FlowFixMe[prop-missing]: See mock in jest/globalFetch.js.
fetch.mockResponseSuccess(JSON.stringify(response));
const expectedError = Error("Cannot read properties of undefined (reading 'toLowerCase')");
await expect(
store.dispatch(
fetchMessages({ narrow: HOME_NARROW, anchor: 0, numBefore: 1, numAfter: 1 }),
),
).rejects.toThrow(expectedError);
const actions = store.getActions();
expect(actions[actions.length - 1]).toMatchObject({
type: 'MESSAGE_FETCH_ERROR',
error: expectedError,
});
});
test('rejects on fetch failure', async () => {
const store = mockStore<GlobalState, Action>(baseState);
const fetchError = new Error('Network request failed (or something)');
// $FlowFixMe[prop-missing]: See mock in jest/globalFetch.js.
fetch.mockResponseFailure(fetchError);
// $FlowFixMe[prop-missing]: Jest mock
logging.info.mockReturnValue();
await expect(
store.dispatch(
fetchMessages({ narrow: HOME_NARROW, anchor: 0, numBefore: 1, numAfter: 1 }),
),
).rejects.toThrow(fetchError);
// $FlowFixMe[prop-missing]: Jest mock
expect(logging.info.mock.calls).toHaveLength(1);
// $FlowFixMe[prop-missing]: Jest mock
logging.info.mockReset();
});
});
test('when messages to be fetched both before and after anchor, numBefore and numAfter are greater than zero', async () => {
const store = mockStore<GlobalState, Action>(
eg.reduxStatePlus({
narrows: Immutable.Map([[streamNarrowStr, [1]]]),
}),
);
// $FlowFixMe[prop-missing]: See mock in jest/globalFetch.js.
fetch.mockResponseSuccess(BORING_RESPONSE);
await store.dispatch(
fetchMessages({ narrow: HOME_NARROW, anchor: 0, numBefore: 1, numAfter: 1 }),
);
const actions = store.getActions();
expect(actions.length).toBeGreaterThanOrEqual(1);
const [action] = actions;
expect(action.type).toBe('MESSAGE_FETCH_START');
invariant(action.type === 'MESSAGE_FETCH_START', 'expect failed');
expect(action.numBefore).toBeGreaterThan(0);
expect(action.numAfter).toBeGreaterThan(0);
});
test('when no messages to be fetched before the anchor, numBefore is not greater than zero', async () => {
const store = mockStore<GlobalState, Action>(
eg.reduxStatePlus({
narrows: Immutable.Map([[streamNarrowStr, [1]]]),
}),
);
// $FlowFixMe[prop-missing]: See mock in jest/globalFetch.js.
fetch.mockResponseSuccess(BORING_RESPONSE);
await store.dispatch(
fetchMessages({ narrow: HOME_NARROW, anchor: 0, numBefore: -1, numAfter: 1 }),
);
const actions = store.getActions();
expect(actions.length).toBeGreaterThanOrEqual(1);
const [action] = actions;
expect(action.type).toBe('MESSAGE_FETCH_START');
invariant(action.type === 'MESSAGE_FETCH_START', 'expect failed');
expect(action.numBefore).not.toBeGreaterThan(0);
});
test('when no messages to be fetched after the anchor, numAfter is not greater than zero', async () => {
const store = mockStore<GlobalState, Action>(
eg.reduxStatePlus({
narrows: Immutable.Map([[streamNarrowStr, [1]]]),
}),
);
// $FlowFixMe[prop-missing]: See mock in jest/globalFetch.js.
fetch.mockResponseSuccess(BORING_RESPONSE);
await store.dispatch(
fetchMessages({ narrow: HOME_NARROW, anchor: 0, numBefore: 1, numAfter: -1 }),
);
const actions = store.getActions();
expect(actions.length).toBeGreaterThanOrEqual(1);
const [action] = actions;
expect(action.type).toBe('MESSAGE_FETCH_START');
invariant(action.type === 'MESSAGE_FETCH_START', 'expect failed');
expect(action.numAfter).not.toBeGreaterThan(0);
});
});
});
```
|
/content/code_sandbox/src/message/__tests__/fetchActions-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 3,799
|
```javascript
/* @flow strict-local */
// $FlowFixMe[untyped-import]
import Color from 'color';
import React, { useCallback, useContext, useMemo } from 'react';
import type { Node } from 'react';
import { Platform, View, Alert, Linking, Pressable } from 'react-native';
import DocumentPicker from 'react-native-document-picker';
import type { DocumentPickerResponse } from 'react-native-document-picker';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import * as logging from '../utils/logging';
import { TranslationContext } from '../boot/TranslationProvider';
import type { Narrow } from '../types';
import { showErrorAlert } from '../utils/info';
import { createStyleSheet } from '../styles';
import { IconImage, IconCamera, IconAttach, IconVideo } from '../common/Icons';
import { androidEnsureStoragePermission } from '../lightbox/download';
import { ThemeContext } from '../styles/theme';
import type { SpecificIconType } from '../common/Icons';
import { androidSdkVersion } from '../reactNativeUtils';
export type Attachment = {|
+name: string | null,
+url: string,
|};
type Props = $ReadOnly<{|
destinationNarrow: Narrow,
insertAttachments: ($ReadOnlyArray<Attachment>) => Promise<void>,
insertVideoCallLink: (() => void) | null,
|}>;
/**
* Choose an appropriate filename for an image to upload.
*
* On Android, at least, react-native-image-picker gives its own wordy
* prefix to image files from the camera and from the media library. So,
* remove those.
*
* Sometimes we get an image whose filename reflects one format (what it's
* stored as in the camera roll), but the actual image has been converted
* already to another format for interoperability.
*
* The Zulip server will infer the file format from the filename's
* extension, so in this case we need to adjust the extension to match the
* actual format. The clue we get in the image-picker response is the extension
* found in `uri`.
*/
export const chooseUploadImageFilename = (uri: string, fileName: string): string => {
// react-native-image-picker can't currently be configured to use a
// different prefix on Android:
// path_to_url#L48
// So, just trim it out in what we choose to call the file.
const nameWithoutPrefix = fileName.replace(/^rn_image_picker_lib_temp_/, '');
/*
* Photos in an iPhone's camera roll (taken since iOS 11) are typically in
* HEIF format and have file names with the extension `.HEIC`. When the user
* selects one of these photos through the image picker, the file gets
* automatically converted to JPEG format... but the `fileName` property in
* the react-native-image-picker response still has the `.HEIC` extension.
*/
// TODO: Is it still true, after the react-native-image-picker upgrade,
// that `fileName` can end in .HEIC?
if (/\.jpe?g$/i.test(uri)) {
const result = nameWithoutPrefix.replace(/\.heic$/i, '.jpeg');
if (result !== nameWithoutPrefix) {
logging.warn('OK, so .HEIC to .jpeg replacement still seems like a good idea.');
}
return result;
}
return nameWithoutPrefix;
};
// From the doc:
// path_to_url#options
// > Only iOS version >= 14 & Android version >= 13 support [multi-select]
//
// Older versions of react-native-image-picker claim to support multi-select
// on older Android versions; we tried that and it gave a bad experience,
// like a generic file picker that wasn't dedicated to handling images well:
// path_to_url#narrow/stream/243-mobile-team/topic/Android.20select.20multiple.20photos/near/1423109
//
// But multi-select on iOS and on Android 13+ seem to work well.
const kShouldOfferImageMultiselect =
Platform.OS === 'ios'
// Android 13
|| androidSdkVersion() >= 33;
// As of r-n-image-picker v5.3.1, this is needed to ensure that any received
// videos have a `fileName` that includes a filename extension. (Servers
// will interpret the filename extension.) See library implementation.
//
// For older Android, it seems the alternative is a generic file-picker UI
// not specialized to images/videos (in a library codepath that uses
// Intent.ACTION_GET_CONTENT).
const kShouldOfferImagePickerMixedMedia =
Platform.OS === 'ios'
// Android 13
|| androidSdkVersion() >= 33;
type MenuButtonProps = $ReadOnly<{|
onPress: () => void | Promise<void>,
IconComponent: SpecificIconType,
|}>;
function MenuButton(props: MenuButtonProps) {
const { onPress, IconComponent } = props;
const style = useMemo(() => ({ paddingHorizontal: 12, paddingVertical: 8 }), []);
const themeData = useContext(ThemeContext);
// TODO: Use standard colors from a palette; don't do this ad-hoc stuff.
const color: string = useMemo(
() => Color(themeData.color).fade(0.5).toString(),
[themeData.color],
);
const pressedColor: string = useMemo(() => Color(color).fade(0.5).toString(), [color]);
return (
<Pressable style={style} onPress={onPress}>
{({ pressed }) => <IconComponent color={pressed ? pressedColor : color} size={24} />}
</Pressable>
);
}
export default function ComposeMenu(props: Props): Node {
const { insertAttachments, insertVideoCallLink } = props;
const _ = useContext(TranslationContext);
const handleImagePickerResponse = useCallback(
response => {
if (response.didCancel === true) {
return;
}
const errorCode = response.errorCode;
if (errorCode != null) {
if (Platform.OS === 'ios' && errorCode === 'permission') {
// iOS has a quirk where it will only request the native
// permission-request alert once, the first time the app wants to
// use a protected resource. After that, the only way the user can
// grant it is in Settings.
Alert.alert(
_('Permissions needed'),
_('To upload an image, please grant Zulip additional permissions in Settings.'),
[
{ text: _('Cancel'), style: 'cancel' },
{
text: _('Open settings'),
onPress: () => {
Linking.openSettings();
},
style: 'default',
},
],
);
} else if (errorCode === 'camera_unavailable') {
showErrorAlert(_('Error'), _('Camera unavailable.'));
} else {
const { errorMessage } = response;
showErrorAlert(_('Error'), errorMessage);
logging.error('Unexpected error from image picker', {
errorCode,
errorMessage: errorMessage ?? '[nullish]',
});
}
return;
}
// This will have length one for single-select payloads, or more than
// one for multi-select. So we'll treat `assets` uniformly: expect it
// to have length >= 1, and loop over it, even if that means just one
// iteration.
const { assets } = response;
if (!assets || !assets[0]) {
// TODO: See if we these unexpected situations actually happen. Ah,
// yep, reportedly (and we've seen in Sentry):
// path_to_url
showErrorAlert(_('Error'), _('Failed to attach your file.'));
logging.error('Image picker response gave falsy `assets` or falsy `assets[0]`', {
'!assets': !assets,
});
return;
}
const attachments = [];
let numMalformed = 0;
assets.forEach((asset, i) => {
const { uri, fileName } = asset;
if (uri == null || fileName == null) {
// TODO: See if these unexpected situations actually happen.
logging.error('An asset returned from image picker had nullish `url` and/or `fileName`', {
'uri == null': uri == null,
'fileName == null': fileName == null,
i,
});
numMalformed++;
return;
}
attachments.push({ name: chooseUploadImageFilename(uri, fileName), url: uri });
});
if (numMalformed > 0) {
if (assets.length === 1 && numMalformed === 1) {
showErrorAlert(_('Error'), _('Failed to attach your file.'));
return;
} else if (assets.length === numMalformed) {
showErrorAlert(_('Error'), _('Failed to attach your files.'));
return;
} else {
showErrorAlert(_('Error'), _('Failed to attach some of your files.'));
// no return; `attachments` will have some items that we can insert
}
}
insertAttachments(attachments);
},
[_, insertAttachments],
);
const handleImagePicker = useCallback(() => {
launchImageLibrary(
{
mediaType: kShouldOfferImagePickerMixedMedia ? 'mixed' : 'photo',
quality: 1.0,
includeBase64: false,
// From the doc: "[U]se `0` to allow any number of files"
// path_to_url#options
//
// Between single- and multi-select, we expect the payload passed to
// handleImagePickerResponse to differ only in the length of the
// `assets` array (one item vs. multiple).
selectionLimit: kShouldOfferImageMultiselect ? 0 : 1,
},
handleImagePickerResponse,
);
}, [handleImagePickerResponse]);
const handleCameraCapture = useCallback(async () => {
if (Platform.OS === 'android') {
// On Android 9, in order to save the captured photo to storage, we
// have to put up a scary permission request. We don't have to do that
// when using "scoped storage", which we do on later Android versions.
await androidEnsureStoragePermission({
title: _('Storage permission needed'),
message: _(
'Zulip will save a copy of your photo on your device. To do so, Zulip will need permission to store files on your device.',
),
});
}
launchCamera(
{
// Here's how iOS video recording works in an attempt on iOS 16:
// - iOS gives a native interface with a camera preview. You can
// choose "photo" or "video", with "photo" selected by default.
// - On tapping "video" for the first time, it shows a permissions
// prompt with the NSMicrophoneUsageDescription string. (If we
// didn't declare that string, the app would hang here.)
// - If you grant the permission, the interaction proceeds as
// you'd hope: you take a video (or cancel), then confirm,
// retake, or cancel.
// - If you don't grant the permission, it proceeds similarly,
// except the sent video will have no sound. Later interactions
// will also let you take video without sound, and you won't get
// prompted about permissions (!). If you want to record videos
// with sound, you have to look in Settings by yourself and
// grant the permission there.
//
// 'mixed' is not supported on Android:
// path_to_url#options
mediaType: Platform.OS === 'ios' ? 'mixed' : 'photo',
// On Android 9 (see above) and on iOS, this means putting up a
// scary permission request. Shrug, because other apps seem to save
// to storage, and it seems convenient; see
// path_to_url#narrow/stream/48-mobile/topic/saving.20photos.20to.20device.20on.20capture/near/1271633.
// TODO: Still allow capturing and sending the photo, just without
// saving to storage, if storage permission is denied.
saveToPhotos: true,
includeBase64: false,
},
handleImagePickerResponse,
);
}, [_, handleImagePickerResponse]);
const handleFilesPicker = useCallback(async () => {
let response = undefined;
try {
response = (await DocumentPicker.pickMultiple({
type: [DocumentPicker.types.allFiles],
}): $ReadOnlyArray<DocumentPickerResponse>);
} catch (e) {
if (!DocumentPicker.isCancel(e)) {
showErrorAlert(_('Error'), e);
}
return;
}
insertAttachments(response.map(a => ({ name: a.name, url: a.uri })));
}, [_, insertAttachments]);
const styles = useMemo(
() =>
createStyleSheet({
container: {
flexDirection: 'row',
},
}),
[],
);
return (
<View style={styles.container}>
<MenuButton onPress={handleFilesPicker} IconComponent={IconAttach} />
<MenuButton onPress={handleImagePicker} IconComponent={IconImage} />
<MenuButton onPress={handleCameraCapture} IconComponent={IconCamera} />
{insertVideoCallLink !== null ? (
<MenuButton onPress={insertVideoCallLink} IconComponent={IconVideo} />
) : null}
</View>
);
}
```
|
/content/code_sandbox/src/compose/ComposeMenu.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 2,902
|
```javascript
/* @flow strict-local */
import deepFreeze from 'deep-freeze';
import type { Submessage } from '../../types';
import messagesReducer from '../messagesReducer';
import { FIRST_UNREAD_ANCHOR } from '../../anchor';
import {
MESSAGE_FETCH_COMPLETE,
EVENT_SUBMESSAGE,
EVENT_MESSAGE_DELETE,
EVENT_REACTION_ADD,
EVENT_REACTION_REMOVE,
} from '../../actionConstants';
import * as eg from '../../__tests__/lib/exampleData';
import { ALL_PRIVATE_NARROW, HOME_NARROW, HOME_NARROW_STR } from '../../utils/narrow';
import { makeUserId } from '../../api/idTypes';
import { randString } from '../../utils/misc';
describe('messagesReducer', () => {
test('RESET_ACCOUNT_DATA', () => {
expect(
messagesReducer(
eg.makeMessagesState([eg.streamMessage()]),
eg.action.reset_account_data,
eg.baseReduxState,
),
).toEqual(eg.baseReduxState.messages);
});
describe('REGISTER_COMPLETE', () => {
const initialState = eg.baseReduxState.messages;
const prevState = messagesReducer(
initialState,
{ ...eg.action.message_fetch_complete, messages: [eg.streamMessage()] },
eg.baseReduxState,
);
expect(prevState).not.toEqual(initialState);
expect(messagesReducer(prevState, eg.action.register_complete, eg.baseReduxState)).toEqual(
initialState,
);
});
describe('EVENT_NEW_MESSAGE', () => {
test('appends message to state, if any narrow is caught up to newest', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage();
const message3 = eg.streamMessage();
const prevState = eg.makeMessagesState([message1, message2]);
const action = eg.mkActionEventNewMessage(message3, {
caughtUp: {
[HOME_NARROW_STR]: {
older: true,
newer: true,
},
},
});
const expectedState = eg.makeMessagesState([message1, message2, message3]);
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(expectedState);
expect(newState).not.toBe(prevState);
});
test('does nothing, if no narrow is caught up to newest', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage();
const message3 = eg.streamMessage();
const prevState = eg.makeMessagesState([message1, message2]);
const action = eg.mkActionEventNewMessage(message3, {
caughtUp: {
[HOME_NARROW_STR]: {
older: true,
newer: false,
},
},
});
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(prevState);
});
});
describe('EVENT_SUBMESSAGE', () => {
test('if the message does not exist do not mutate the state', () => {
const message1 = eg.streamMessage({ id: 1 });
const message2 = eg.streamMessage({ id: 2 });
const prevState = eg.makeMessagesState([message1, message2]);
const action = deepFreeze({
id: 1,
type: EVENT_SUBMESSAGE,
message_id: 3,
submessage_id: 2,
sender_id: eg.otherUser.user_id,
msg_type: 'widget',
content: randString(),
});
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toBe(prevState);
});
test('if the message exists add the incoming data to `submessages`', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage({
id: 2,
submessages: [
{
id: 1,
message_id: 2,
sender_id: eg.otherUser.user_id,
msg_type: 'widget', // only this type is currently available
content: randString(), // JSON string
},
],
});
const prevState = eg.makeMessagesState([message1, message2]);
const action = deepFreeze({
id: 1,
type: EVENT_SUBMESSAGE,
message_id: message2.id,
submessage_id: 2,
sender_id: eg.otherUser.user_id,
msg_type: 'widget',
content: '{hello: "world"}',
});
const expectedState = eg.makeMessagesState([
message1,
{
...message2,
submessages: [
// We know message2 has `submessages`; we defined it that
// way.
// $FlowFixMe[incompatible-cast]
...(message2.submessages: $ReadOnlyArray<Submessage>),
{
id: 2,
message_id: 2,
sender_id: eg.otherUser.user_id,
msg_type: 'widget',
content: '{hello: "world"}',
},
],
},
]);
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(expectedState);
expect(newState).not.toBe(prevState);
});
});
describe('EVENT_MESSAGE_DELETE', () => {
test('if a message does not exist no changes are made', () => {
const message1 = eg.streamMessage({ id: 1 });
const prevState = eg.makeMessagesState([message1]);
const action = deepFreeze({ type: EVENT_MESSAGE_DELETE, messageIds: [2] });
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(prevState);
expect(newState).toBe(prevState);
});
test('if a message exists it is deleted', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage();
const prevState = eg.makeMessagesState([message1, message2]);
const action = deepFreeze({ type: EVENT_MESSAGE_DELETE, messageIds: [message2.id] });
const expectedState = eg.makeMessagesState([message1]);
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(expectedState);
});
test('if multiple messages indicated, delete the ones that exist', () => {
const message1 = eg.streamMessage({ id: 1 });
const message2 = eg.streamMessage({ id: 2 });
const message3 = eg.streamMessage({ id: 3 });
const prevState = eg.makeMessagesState([message1, message2, message3]);
const action = deepFreeze({
type: EVENT_MESSAGE_DELETE,
messageIds: [message2.id, message3.id, 4],
});
const expectedState = eg.makeMessagesState([message1]);
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(expectedState);
});
});
describe('EVENT_UPDATE_MESSAGE', () => {
const mkAction = args => {
const {
message,
rendering_only = false,
message_ids = [message.id],
propagate_mode = 'change_one',
user_id = message.sender_id,
edit_timestamp = message.timestamp + 1,
...restArgs
} = args;
return eg.mkActionEventUpdateMessage({
rendering_only,
message_id: message.id,
message_ids,
propagate_mode,
user_id,
edit_timestamp,
is_me_message: false,
...restArgs,
});
};
const mkMoveAction = args => {
const { message, ...restArgs } = args;
return mkAction({
message,
// stream_id and orig_subject are always present when either
// the stream or the topic was changed.
stream_id: message.stream_id,
orig_subject: message.subject,
...restArgs,
});
};
test('if a message does not exist no changes are made', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage();
const message3 = eg.streamMessage();
const prevState = eg.makeMessagesState([message1, message2]);
const action = mkAction({
edit_timestamp: Date.now() - 1000,
message: message3,
orig_content: randString(),
orig_rendered_content: randString(),
prev_rendered_content_version: 0,
rendered_content: randString(),
content: randString(),
});
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toBe(prevState);
});
describe('move', () => {
test('edited topic', () => {
const message = eg.streamMessage();
const newTopic = `${message.subject}abc`;
const action = mkMoveAction({ message, subject: newTopic, edit_timestamp: 1000 });
expect(messagesReducer(eg.makeMessagesState([message]), action, eg.plusReduxState)).toEqual(
eg.makeMessagesState([
{
...message,
subject: newTopic,
edit_history: [
{
user_id: message.sender_id,
timestamp: 1000,
prev_topic: 'example topic',
topic: 'example topicabc',
},
],
last_edit_timestamp: 1000,
},
]),
);
});
test('other messages in conversation are unaffected', () => {
const topic = 'some topic';
const message1 = eg.streamMessage({ subject: topic });
const message2 = eg.streamMessage({ subject: topic });
const message3 = eg.streamMessage({ subject: topic });
const newTopic = 'some revised topic';
const action = mkMoveAction({
message: message1,
message_ids: [message1.id, message2.id],
subject: newTopic,
edit_timestamp: 1000,
});
expect(
messagesReducer(
eg.makeMessagesState([message1, message2, message3]),
action,
eg.plusReduxState,
),
).toEqual(
eg.makeMessagesState([
{
...message1,
subject: newTopic,
edit_history: [
{
user_id: message1.sender_id,
timestamp: 1000,
prev_topic: 'some topic',
topic: 'some revised topic',
},
],
last_edit_timestamp: 1000,
},
{
...message2,
subject: newTopic,
edit_history: [
{
user_id: message2.sender_id,
timestamp: 1000,
prev_topic: 'some topic',
topic: 'some revised topic',
},
],
},
message3,
]),
);
});
test('new stream', () => {
const message = eg.streamMessage();
const action = mkMoveAction({
message,
new_stream_id: eg.otherStream.stream_id,
edit_timestamp: 1000,
});
expect(messagesReducer(eg.makeMessagesState([message]), action, eg.plusReduxState)).toEqual(
eg.makeMessagesState([
{
...message,
stream_id: eg.otherStream.stream_id,
display_recipient: eg.otherStream.name,
edit_history: [
{
user_id: message.sender_id,
timestamp: 1000,
prev_stream: message.stream_id,
stream: eg.otherStream.stream_id,
},
],
last_edit_timestamp: 1000,
},
]),
);
});
test('new stream + edited topic', () => {
const message = eg.streamMessage();
const newTopic = `${message.subject}abc`;
const action = mkMoveAction({
message,
new_stream_id: eg.otherStream.stream_id,
subject: newTopic,
edit_timestamp: 1000,
});
expect(messagesReducer(eg.makeMessagesState([message]), action, eg.plusReduxState)).toEqual(
eg.makeMessagesState([
{
...message,
stream_id: eg.otherStream.stream_id,
display_recipient: eg.otherStream.name,
subject: newTopic,
edit_history: [
{
user_id: message.sender_id,
timestamp: 1000,
prev_stream: message.stream_id,
stream: eg.otherStream.stream_id,
prev_topic: 'example topic',
topic: 'example topicabc',
},
],
last_edit_timestamp: 1000,
},
]),
);
});
test('new, unknown stream', () => {
const message = eg.streamMessage();
const unknownStream = eg.makeStream();
const action = mkMoveAction({
message,
new_stream_id: unknownStream.stream_id,
edit_timestamp: 1000,
});
expect(messagesReducer(eg.makeMessagesState([message]), action, eg.plusReduxState)).toEqual(
eg.makeMessagesState([
{
...message,
stream_id: unknownStream.stream_id,
display_recipient: 'unknown',
edit_history: [
{
user_id: message.sender_id,
timestamp: 1000,
prev_stream: message.stream_id,
stream: unknownStream.stream_id,
},
],
last_edit_timestamp: 1000,
},
]),
);
});
test('multiple messages moved in one event', () => {
const message0 = eg.streamMessage({ stream: eg.stream, subject: 'old topic' });
const message1 = eg.streamMessage({ stream: eg.stream, subject: 'old topic' });
const message2 = eg.streamMessage({ stream: eg.stream, subject: 'old topic' });
const action = mkMoveAction({
user_id: eg.thirdUser.user_id,
edit_timestamp: 1000,
message: message0,
message_ids: [message0.id, message1.id, message2.id],
propagate_mode: 'change_later',
new_stream_id: eg.otherStream.stream_id,
subject: 'new topic',
});
expect(
messagesReducer(
eg.makeMessagesState([message0, message1, message2]),
action,
eg.plusReduxState,
),
).toEqual(
eg.makeMessagesState(
[{ ...message0, last_edit_timestamp: 1000 }, message1, message2].map(m => ({
...m,
stream_id: eg.otherStream.stream_id,
display_recipient: eg.otherStream.name,
subject: 'new topic',
edit_history: [
{
user_id: eg.thirdUser.user_id,
timestamp: 1000,
prev_stream: eg.stream.stream_id,
stream: eg.otherStream.stream_id,
prev_topic: 'old topic',
topic: 'new topic',
},
],
})),
),
);
});
test("edited one message's content + multiple messages moved in one event", () => {
const message0 = eg.streamMessage({
stream: eg.stream,
subject: 'old topic',
content: '<p>Old content</p>',
});
const message1 = eg.streamMessage({ stream: eg.stream, subject: 'old topic' });
const message2 = eg.streamMessage({ stream: eg.stream, subject: 'old topic' });
const action = mkMoveAction({
user_id: eg.thirdUser.user_id,
edit_timestamp: 1000,
// content edit (to apply to just one message)
message: message0,
orig_content: 'Old content',
orig_rendered_content: '<p>Old content</p>',
prev_rendered_content_version: 1,
content: 'New content',
rendered_content: '<p>New content</p>',
// move (to apply to all messages in `message_ids`)
message_ids: [message0.id, message1.id, message2.id],
propagate_mode: 'change_later',
new_stream_id: eg.otherStream.stream_id,
subject: 'new topic',
});
expect(
messagesReducer(
eg.makeMessagesState([message0, message1, message2]),
action,
eg.plusReduxState,
),
).toEqual(
eg.makeMessagesState([
{
...message0,
content: '<p>New content</p>',
stream_id: eg.otherStream.stream_id,
display_recipient: eg.otherStream.name,
subject: 'new topic',
edit_history: [
{
user_id: eg.thirdUser.user_id,
timestamp: 1000,
prev_content: 'Old content',
prev_rendered_content: '<p>Old content</p>',
prev_rendered_content_version: 1,
prev_stream: eg.stream.stream_id,
stream: eg.otherStream.stream_id,
prev_topic: 'old topic',
topic: 'new topic',
},
],
last_edit_timestamp: 1000,
},
...[message1, message2].map(m => ({
...m,
stream_id: eg.otherStream.stream_id,
display_recipient: eg.otherStream.name,
subject: 'new topic',
edit_history: [
{
user_id: eg.thirdUser.user_id,
timestamp: 1000,
prev_stream: eg.stream.stream_id,
stream: eg.otherStream.stream_id,
prev_topic: 'old topic',
topic: 'new topic',
},
],
})),
]),
);
});
});
test('when a message exists in state, it is updated', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage();
const message3Old = eg.streamMessage({ content: '<p>Old content</p>' });
const message3New = {
...message3Old,
content: '<p>New content</p>',
last_edit_timestamp: 123,
edit_history: [
{
prev_content: message3Old.content,
prev_rendered_content: message3Old.content,
prev_rendered_content_version: 1,
timestamp: 123,
user_id: message3Old.sender_id,
},
],
};
const prevState = eg.makeMessagesState([message1, message2, message3Old]);
const action = mkAction({
edit_timestamp: 123,
message: message3New,
orig_content: '<p>Old content</p>',
orig_rendered_content: '<p>Old content</p>',
prev_rendered_content_version: 1,
rendered_content: '<p>New content</p>',
content: 'New content',
});
const expectedState = eg.makeMessagesState([message1, message2, message3New]);
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(expectedState);
});
test('when event contains a new subject but no new content only subject is updated', () => {
const message1Old = eg.streamMessage({
content: 'Old content',
subject: 'Old topic',
last_edit_timestamp: 123,
edit_history: [],
});
const message1New = {
...message1Old,
subject: 'New topic',
last_edit_timestamp: 123,
edit_history: [
{
prev_topic: message1Old.subject,
timestamp: 123,
topic: 'New topic',
user_id: message1Old.sender_id,
},
],
};
const prevState = eg.makeMessagesState([message1Old]);
const action = mkMoveAction({
edit_timestamp: 123,
message: message1Old,
subject: message1New.subject,
});
const expectedState = eg.makeMessagesState([message1New]);
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(expectedState);
});
test('when event contains a new subject and a new content, update both', () => {
const message1Old = eg.streamMessage({
content: '<p>Old content</p>',
subject: 'Old topic',
last_edit_timestamp: 123,
});
const message1New = {
...message1Old,
content: '<p>New content</p>',
subject: 'New updated topic',
last_edit_timestamp: 456,
edit_history: [
{
prev_content: message1Old.content,
prev_rendered_content: message1Old.content,
prev_rendered_content_version: 1,
prev_topic: message1Old.subject,
timestamp: 456,
topic: 'New updated topic',
user_id: message1Old.sender_id,
},
],
};
const prevState = eg.makeMessagesState([message1Old]);
const action = mkMoveAction({
edit_timestamp: 456,
message: message1Old,
orig_content: message1Old.content,
orig_rendered_content: message1Old.content,
rendered_content: message1New.content,
content: message1New.content,
subject: message1New.subject,
prev_rendered_content_version: 1,
});
const expectedState = eg.makeMessagesState([message1New]);
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(expectedState);
});
test('handle stealth server-edit (for inline URL previews)', () => {
const message = eg.streamMessage({
content: 'Some content',
edit_history: [],
});
const messageAfter = {
...message,
content: 'Some content with an inline URL preview',
// edit_history still empty
};
const action = mkAction({
rendering_only: true,
message,
orig_content: message.content,
orig_rendered_content: message.content,
content: messageAfter.content,
rendered_content: messageAfter.content,
prev_rendered_content_version: 1,
});
expect(messagesReducer(eg.makeMessagesState([message]), action, eg.plusReduxState)).toEqual(
eg.makeMessagesState([messageAfter]),
);
});
test('handle stealth server-edit, after a real edit', () => {
const message = eg.streamMessage({
content: 'Some content, edited',
edit_history: [
{ user_id: eg.otherUser.user_id, timestamp: 123, prev_rendered_content: 'Some content' },
],
last_edit_timestamp: 123,
});
const messageAfter = {
...message,
content: 'Some content, edited, plus a URL preview ',
// still has last_edit_timestamp, rather than clobbering with
// undefined from action.edit_timestamp
};
const action = mkAction({
rendering_only: true,
message,
orig_content: message.content,
orig_rendered_content: message.content,
content: messageAfter.content,
rendered_content: messageAfter.content,
prev_rendered_content_version: 1,
});
expect(messagesReducer(eg.makeMessagesState([message]), action, eg.plusReduxState)).toEqual(
eg.makeMessagesState([messageAfter]),
);
});
describe('edit_history not covered above', () => {
describe('sequential updates', () => {
const initialContent = 'Old content';
const initialRenderedContent = `<p>${initialContent}</p>`;
const initialTopic = 'Old topic';
const afterNoUpdates = eg.streamMessage({
content: initialRenderedContent,
subject: initialTopic,
edit_history: undefined,
});
const senderId = afterNoUpdates.sender_id;
const update1Content = 'New content';
const update1RenderedContent = `<p>${update1Content}</p>`;
const update1Topic = 'New updated topic';
const update1Action = mkMoveAction({
edit_timestamp: 456,
message: afterNoUpdates,
orig_content: initialContent,
orig_rendered_content: initialRenderedContent,
rendered_content: update1RenderedContent,
content: update1Content,
subject: update1Topic,
prev_rendered_content_version: 1,
});
const afterUpdate1 = {
...afterNoUpdates,
content: update1RenderedContent,
subject: update1Topic,
last_edit_timestamp: 456,
edit_history: [
{
prev_content: initialContent,
prev_rendered_content: initialRenderedContent,
prev_rendered_content_version: 1,
prev_topic: initialTopic,
timestamp: 456,
topic: update1Topic,
user_id: senderId,
},
],
};
const update2Content = 'New content 2';
const update2RenderedContent = `<p>${update2Content}</p>`;
const update2Topic = 'New updated topic 2';
const update2Action = mkMoveAction({
edit_timestamp: 567,
message: afterUpdate1,
orig_content: update1Content,
orig_rendered_content: update1RenderedContent,
rendered_content: update2RenderedContent,
content: update2Content,
subject: update2Topic,
prev_rendered_content_version: 1,
});
const afterUpdate2 = {
...afterUpdate1,
content: update2RenderedContent,
subject: update2Topic,
last_edit_timestamp: 567,
edit_history: [
{
prev_content: update1Content,
prev_rendered_content: update1RenderedContent,
prev_rendered_content_version: 1,
prev_topic: update1Topic,
timestamp: 567,
topic: update2Topic,
user_id: senderId,
},
{
prev_content: initialContent,
prev_rendered_content: initialRenderedContent,
prev_rendered_content_version: 1,
prev_topic: initialTopic,
timestamp: 456,
topic: update1Topic,
user_id: senderId,
},
],
};
test('on never-edited message, creates one-item array', () => {
expect(
messagesReducer(
eg.makeMessagesState([afterNoUpdates]),
update1Action,
eg.plusReduxState,
),
).toEqual(eg.makeMessagesState([afterUpdate1]));
});
test('on once-edited message, adds item at start of array', () => {
expect(
messagesReducer(eg.makeMessagesState([afterUpdate1]), update2Action, eg.plusReduxState),
).toEqual(eg.makeMessagesState([afterUpdate2]));
});
});
test("don't touch it if we dropped it", () => {
const message1Old = eg.streamMessage({
content: '<p>Old content</p>',
subject: 'Old topic',
edit_history: null,
});
const prevState = eg.makeMessagesState([message1Old]);
const action = mkMoveAction({
edit_timestamp: 456,
message: message1Old,
orig_content: message1Old.content,
orig_rendered_content: message1Old.content,
rendered_content: '<p>New content</p>',
content: 'New content',
subject: 'New updated topic',
prev_rendered_content_version: 1,
});
const newState = messagesReducer(prevState, action, eg.plusReduxState);
const newMessage = newState.get(message1Old.id);
expect(newMessage).not.toBeUndefined();
expect(newState.get(message1Old.id)?.edit_history).toBe(null);
});
});
});
describe('EVENT_REACTION_ADD', () => {
test('on event received, add reaction to message with given id', () => {
const message1 = eg.streamMessage({ reactions: [] });
const message2 = eg.streamMessage({ reactions: [] });
const reaction = eg.unicodeEmojiReaction;
const prevState = eg.makeMessagesState([message1, message2]);
const action = deepFreeze({
id: 1,
type: EVENT_REACTION_ADD,
message_id: message2.id,
...reaction,
});
const expectedState = eg.makeMessagesState([
message1,
{
...message2,
reactions: [reaction],
},
]);
const actualState = messagesReducer(prevState, action, eg.plusReduxState);
expect(actualState).toEqual(expectedState);
});
});
describe('EVENT_REACTION_REMOVE', () => {
test('if message does not contain reaction, no change is made', () => {
const message1 = eg.streamMessage({ reactions: [] });
const reaction = eg.unicodeEmojiReaction;
const prevState = eg.makeMessagesState([message1]);
const action = deepFreeze({
id: 1,
type: EVENT_REACTION_REMOVE,
message_id: message1.id,
...reaction,
});
const expectedState = eg.makeMessagesState([message1]);
const actualState = messagesReducer(prevState, action, eg.plusReduxState);
expect(actualState).toEqual(expectedState);
});
test('reaction is removed only from specified message, only for given user', () => {
const reaction1 = {
...eg.unicodeEmojiReaction,
emoji_code: '1f44b',
emoji_name: 'wave',
user_id: makeUserId(1),
};
const reaction2 = {
...eg.unicodeEmojiReaction,
emoji_code: '1f44b',
emoji_name: 'wave',
user_id: makeUserId(2),
};
const reaction3 = {
...eg.unicodeEmojiReaction,
emoji_code: '1f6e0',
emoji_name: 'working_on_it',
user_id: makeUserId(1),
};
const message1 = eg.streamMessage({ reactions: [reaction1, reaction2, reaction3] });
const prevState = eg.makeMessagesState([message1]);
const action = deepFreeze({
id: 1,
type: EVENT_REACTION_REMOVE,
message_id: message1.id,
...reaction1,
});
const expectedState = eg.makeMessagesState([
{ ...message1, reactions: [reaction2, reaction3] },
]);
const actualState = messagesReducer(prevState, action, eg.plusReduxState);
expect(actualState).toEqual(expectedState);
});
});
describe('MESSAGE_FETCH_COMPLETE', () => {
test('fetched messages are added to the state', () => {
const message1 = eg.pmMessage({ id: 1 });
const message2 = eg.pmMessage({ id: 2 });
const message3 = eg.pmMessage({ id: 3 });
const message4 = eg.pmMessage({ id: 4 });
const message5 = eg.pmMessage({ id: 5 });
const prevState = eg.makeMessagesState([message1, message2, message3]);
const action = deepFreeze({
type: MESSAGE_FETCH_COMPLETE,
messages: [message3, message4, message5],
narrow: ALL_PRIVATE_NARROW,
anchor: FIRST_UNREAD_ANCHOR,
numBefore: 50,
numAfter: 50,
foundOldest: false,
foundNewest: false,
ownUserId: eg.selfUser.user_id,
});
const expectedState = eg.makeMessagesState([
message1,
message2,
message3,
message4,
message5,
]);
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState).toEqual(expectedState);
});
test('when anchor is FIRST_UNREAD_ANCHOR common messages are not replaced', () => {
const message1 = eg.streamMessage({ id: 1, timestamp: 3 });
const message2 = eg.streamMessage({ id: 2, timestamp: 4 });
const message3 = eg.streamMessage({ id: 3, timestamp: 5 });
const prevState = eg.makeMessagesState([message1, message2, message3]);
const action = deepFreeze({
type: MESSAGE_FETCH_COMPLETE,
messages: [message2, message3],
narrow: HOME_NARROW,
anchor: FIRST_UNREAD_ANCHOR,
numBefore: 50,
numAfter: 50,
foundOldest: false,
foundNewest: false,
ownUserId: eg.selfUser.user_id,
});
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState.get(message2.id)).toEqual(message2);
expect(newState.get(message3.id)).toEqual(message3);
});
test('when anchor is FIRST_UNREAD_ANCHOR deep equal is performed to separate common messages', () => {
const message1 = eg.streamMessage({ id: 1, timestamp: 3 });
const message2 = eg.streamMessage({ id: 2, timestamp: 4 });
const message3 = eg.streamMessage({ id: 3, timestamp: 5 });
const message4Old = eg.streamMessage({ id: 4, timestamp: 6, subject: 'some topic' });
const message4New = { ...message4Old, subject: 'new topic' };
const prevState = eg.makeMessagesState([message1, message2, message3, message4Old]);
const action = deepFreeze({
type: MESSAGE_FETCH_COMPLETE,
messages: [message2, message3, message4New],
narrow: HOME_NARROW,
anchor: FIRST_UNREAD_ANCHOR,
numBefore: 50,
numAfter: 50,
foundOldest: false,
foundNewest: false,
ownUserId: eg.selfUser.user_id,
});
const newState = messagesReducer(prevState, action, eg.plusReduxState);
expect(newState.get(message2.id)).toEqual(message2);
expect(newState.get(message3.id)).toEqual(message3);
expect(newState.get(message4New.id)).toEqual(message4New);
});
});
});
```
|
/content/code_sandbox/src/message/__tests__/messagesReducer-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 7,179
|
```javascript
/* @flow strict-local */
import type { Narrow, Stream, UserId, UserOrBot, LocalizableText, GetText } from '../types';
import { getFullNameText } from '../users/userSelectors';
import { caseNarrowDefault } from '../utils/narrow';
export default (
narrow: Narrow,
ownUserId: UserId,
allUsersById: Map<UserId, UserOrBot>,
streamsById: Map<number, Stream>,
enableGuestUserIndicator: boolean,
_: GetText,
): LocalizableText =>
caseNarrowDefault(
narrow,
{
pm: ids => {
if (ids.length > 1) {
return { text: 'Message group' };
}
const userId = ids[0];
if (userId === ownUserId) {
return { text: 'Jot down something' };
}
const user = allUsersById.get(userId);
if (!user) {
return { text: 'Type a message' };
}
return {
text: 'Message {recipient}',
values: { recipient: _(getFullNameText({ user, enableGuestUserIndicator })) },
};
},
stream: streamId => {
const stream = streamsById.get(streamId);
if (!stream) {
return { text: 'Type a message' };
}
return { text: 'Message {recipient}', values: { recipient: `#${stream.name}` } };
},
topic: () => ({ text: 'Reply' }),
},
() => ({ text: 'Type a message' }),
);
```
|
/content/code_sandbox/src/compose/getComposeInputPlaceholder.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 331
|
```javascript
/* @flow strict-local */
import React, { useState, useCallback, useContext, forwardRef, useImperativeHandle } from 'react';
import type { AbstractComponent, Node } from 'react';
import type { Stream, Narrow, UserOrBot, Subscription, UserId } from '../types';
import { useSelector } from '../react-redux';
import { TranslationContext } from '../boot/TranslationProvider';
import { getAllUsersById, getAuth } from '../selectors';
import { isPmNarrow } from '../utils/narrow';
import * as api from '../api';
import { showToast } from '../utils/info';
import MentionedUserNotSubscribed from '../message/MentionedUserNotSubscribed';
import { makeUserId } from '../api/idTypes';
import { getFullNameText } from '../users/userSelectors';
import { getRealm } from '../directSelectors';
type Props = $ReadOnly<{|
narrow: Narrow,
stream: Subscription | {| ...Stream, in_home_view: boolean |},
|}>;
/**
* Functions expected to be called by ComposeBox using a ref to this
* component.
*/
type ImperativeHandle = {|
/**
* Check whether the message text entered by the user contains
* an @-mention to a user unsubscribed to the current stream, and if
* so, shows a warning.
*
* @param completion The autocomplete option chosend by the user.
* See JSDoc for AutoCompleteView for details.
*/
handleMentionSubscribedCheck(completion: string): Promise<void>,
clearMentionWarnings(): void,
|};
function MentionWarningsInner(props: Props, ref): Node {
const { stream, narrow } = props;
const auth = useSelector(getAuth);
const allUsersById = useSelector(getAllUsersById);
const enableGuestUserIndicator = useSelector(state => getRealm(state).enableGuestUserIndicator);
const [unsubscribedMentions, setUnsubscribedMentions] = useState<$ReadOnlyArray<UserId>>([]);
const _ = useContext(TranslationContext);
/**
* Tries to parse a user object from an @-mention.
*
* @param completion The autocomplete option chosend by the user.
See JSDoc for AutoCompleteView for details.
*/
const getUserFromMention = useCallback(
(completion: string): UserOrBot | void => {
const unformattedMessage = completion.split('**')[1];
// We skip user groups, for which autocompletes are of the form
// `*<user_group_name>*`, and therefore, message.split('**')[1]
// is undefined.
if (unformattedMessage === undefined) {
return undefined;
}
const [userFullName, userIdRaw] = unformattedMessage.split('|');
if (userIdRaw !== undefined) {
const userId = makeUserId(Number.parseInt(userIdRaw, 10));
return allUsersById.get(userId);
}
for (const user of allUsersById.values()) {
if (user.full_name === userFullName) {
return user;
}
}
return undefined;
},
[allUsersById],
);
const showSubscriptionStatusLoadError = useCallback(
(mentionedUser: UserOrBot) => {
showToast(
_('Couldnt load information about {fullName}', {
fullName: _(getFullNameText({ user: mentionedUser, enableGuestUserIndicator })),
}),
);
},
[enableGuestUserIndicator, _],
);
useImperativeHandle(
ref,
() => ({
handleMentionSubscribedCheck: async (completion: string) => {
if (isPmNarrow(narrow)) {
return;
}
const mentionedUser = getUserFromMention(completion);
if (mentionedUser === undefined || unsubscribedMentions.includes(mentionedUser.user_id)) {
return;
}
let isSubscribed: boolean;
try {
isSubscribed = (
await api.getSubscriptionToStream(auth, mentionedUser.user_id, stream.stream_id)
).is_subscribed;
} catch {
showSubscriptionStatusLoadError(mentionedUser);
return;
}
if (!isSubscribed) {
setUnsubscribedMentions(prevUnsubscribedMentions => [
...prevUnsubscribedMentions,
mentionedUser.user_id,
]);
}
},
clearMentionWarnings: () => {
setUnsubscribedMentions([]);
},
}),
[
auth,
getUserFromMention,
narrow,
showSubscriptionStatusLoadError,
stream,
unsubscribedMentions,
],
);
const handleMentionWarningDismiss = useCallback((user: UserOrBot) => {
setUnsubscribedMentions(prevUnsubscribedMentions =>
prevUnsubscribedMentions.filter(x => x !== user.user_id),
);
}, []);
if (isPmNarrow(narrow)) {
return null;
}
const mentionWarnings = [];
for (const userId of unsubscribedMentions) {
const user = allUsersById.get(userId);
if (user === undefined) {
continue;
}
mentionWarnings.push(
<MentionedUserNotSubscribed
stream={stream}
user={user}
onDismiss={handleMentionWarningDismiss}
key={user.user_id}
/>,
);
}
return mentionWarnings;
}
const MentionWarnings: AbstractComponent<Props, ImperativeHandle> =
forwardRef(MentionWarningsInner);
export default MentionWarnings;
```
|
/content/code_sandbox/src/compose/MentionWarnings.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,172
|
```javascript
/* @flow strict-local */
import deepFreeze from 'deep-freeze';
import getComposeInputPlaceholder from '../getComposeInputPlaceholder';
import {
pm1to1NarrowFromUser,
streamNarrow,
topicNarrow,
pmNarrowFromUsersUnsafe,
} from '../../utils/narrow';
import * as eg from '../../__tests__/lib/exampleData';
import { getStreamsById } from '../../selectors';
import { mock_ } from '../../__tests__/lib/intl';
describe('getComposeInputPlaceholder', () => {
const usersById = new Map([eg.selfUser, eg.otherUser, eg.thirdUser].map(u => [u.user_id, u]));
const ownUserId = eg.selfUser.user_id;
const streamsById = getStreamsById(eg.plusReduxState);
test('returns "Message This Person" object for person narrow', () => {
const narrow = deepFreeze(pm1to1NarrowFromUser(eg.otherUser));
const placeholder = getComposeInputPlaceholder(
narrow,
ownUserId,
usersById,
streamsById,
false,
mock_,
);
expect(placeholder).toEqual({
text: 'Message {recipient}',
values: { recipient: eg.otherUser.full_name },
});
});
test('returns "Jot down something" object for self narrow', () => {
const narrow = deepFreeze(pm1to1NarrowFromUser(eg.selfUser));
const placeholder = getComposeInputPlaceholder(
narrow,
ownUserId,
usersById,
streamsById,
false,
mock_,
);
expect(placeholder).toEqual({ text: 'Jot down something' });
});
test('returns "Message #streamName" for stream narrow', () => {
const narrow = deepFreeze(streamNarrow(eg.stream.stream_id));
const placeholder = getComposeInputPlaceholder(
narrow,
ownUserId,
usersById,
streamsById,
false,
mock_,
);
expect(placeholder).toEqual({
text: 'Message {recipient}',
values: { recipient: `#${eg.stream.name}` },
});
});
test('returns properly for topic narrow', () => {
const narrow = deepFreeze(topicNarrow(eg.stream.stream_id, 'Copenhagen'));
const placeholder = getComposeInputPlaceholder(
narrow,
ownUserId,
usersById,
streamsById,
false,
mock_,
);
expect(placeholder).toEqual({ text: 'Reply' });
});
test('returns "Message group" object for group narrow', () => {
const narrow = deepFreeze(pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]));
const placeholder = getComposeInputPlaceholder(
narrow,
ownUserId,
usersById,
streamsById,
false,
mock_,
);
expect(placeholder).toEqual({ text: 'Message group' });
});
});
```
|
/content/code_sandbox/src/compose/__tests__/getComposeInputPlaceholder-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 621
|
```javascript
/* @flow strict-local */
import * as logging from '../../utils/logging';
import { chooseUploadImageFilename } from '../ComposeMenu';
describe('chooseUploadImageFilename', () => {
test('Does nothing if the image uri does not end with an extension for the JPEG format', () => {
expect(chooseUploadImageFilename('foo', 'foo')).toBe('foo');
});
test(
'Replaces any extension for the HEIC format with an extension for the JPEG format '
+ 'if the file name does end with an extension for the JPEG format',
() => {
// suppress `logging.warn` output
// $FlowFixMe[prop-missing]: Jest mock
logging.warn.mockReturnValue();
const fileNameWithoutExtension = 'foo';
expect(
chooseUploadImageFilename('some/path/something.jpg', `${fileNameWithoutExtension}.heic`),
).toBe(`${fileNameWithoutExtension}.jpeg`);
},
);
test('Replaces prefix from react-native-image-picker', () => {
expect(
chooseUploadImageFilename('some/path/something.jpg', 'rn_image_picker_lib_temp_asdf.jpg'),
).toBe('asdf.jpg');
});
});
```
|
/content/code_sandbox/src/compose/__tests__/ComposeMenu-test.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 { mapOrNull, symmetricDiff } from '../collections';
describe('mapOrNull', () => {
test('behaves right in happy case', () => {
expect(mapOrNull([10, 20], (x, i, a) => x + i + a.length)).toEqual([12, 23]);
});
test('returns null on nullish item', () => {
expect(mapOrNull([1, 2, 3], x => (x === 2 ? null : x))).toEqual(null);
expect(mapOrNull([1, 2, 3], x => (x === 2 ? undefined : x))).toEqual(null);
});
test('aborts on nullish item', () => {
const log = [];
mapOrNull([1, 2, 3], x => {
log.push(x);
return x === 2 ? null : x;
});
expect(log).toEqual([1, 2]);
});
});
describe('symmetricDiff', () => {
for (const [desc, as, bs, aOnly, bOnly] of [
['empty', [], [], [], []],
['empty/inhabited', [], [1, 2], [], [1, 2]],
['inhabited/empty', [1, 2], [], [1, 2], []],
['equal', [1, 2], [1, 2], [], []],
['extra a', [1, 2, 3, 4, 5, 6], [2, 5], [1, 3, 4, 6], []],
['extra b', [2, 5], [1, 2, 3, 4, 5, 6], [], [1, 3, 4, 6]],
['both extra in same place', [1, 3, 4, 5, 7, 8], [2, 3, 6, 7, 9], [1, 4, 5, 8], [2, 6, 9]],
]) {
test(desc, () => {
expect(symmetricDiff(as, bs)).toEqual([aOnly, bOnly]);
});
}
});
```
|
/content/code_sandbox/src/__tests__/collections-test.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 isAppOwnDomain from '../isAppOwnDomain';
describe('isAppOwnDomain', () => {
test.each([
['path_to_url true],
['path_to_url true],
['path_to_url true],
['path_to_url true],
['path_to_url true],
['path_to_url true],
['path_to_url true],
['path_to_url false],
['path_to_url false],
['path_to_url false],
['path_to_url false],
])('%s should be %p', (urlStr: string, expected: boolean) => {
expect(isAppOwnDomain(new URL(urlStr))).toBe(expected);
});
});
```
|
/content/code_sandbox/src/__tests__/isAppOwnDomain-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 148
|
```javascript
/* @flow strict-local */
import React from 'react';
import type { ComponentType } from 'react';
// $FlowFixMe[untyped-import]
import { create, act } from 'react-test-renderer';
// $FlowFixMe[untyped-import]
import * as ReactHooksTesting from '@testing-library/react-hooks';
import { fakeSleep } from './lib/fakeTimers';
import { useDateRefreshedAtInterval, useHasStayedTrueForMs } from '../reactUtils';
describe('useHasNotChangedForMs', () => {
// This gets indirect coverage because useHasStayedTrueForMs calls it, and
// that hook has good coverage, below. But:
// TODO: Test directly.
});
describe('useHasStayedTrueForMs', () => {
/**
* Simulate a mock component using the hook, and inspect hook's value.
*
* - The constructor mounts the component. (`ms` won't change through the
* lifetime of the TestMachine instance.)
* - Use `updateValue` to change the `value` arg passed to the hook.
* - Use `hookOutput` to get the return value of the hook from the latest
* render.
* - (Important) To wait for a duration, use the instance's `sleep` method
* instead of the util `fakeSleep` or similar. It wraps some
* `react-test-renderer` boilerplate.
* - When done, call 'cleanup'.
*
* Encapsulates a few things:
* - react-test-renderer is untyped (so far)
* - boilerplate for using react-test-renderer, like calling `act`
* repeatedly
* - boring details like how the mock component is implemented
*/
// We wrote these tests a long time before our first experiment with
// @testing-library/react-hooks (for useDateRefreshedAtInterval), in which
// we let the library take care of defining and rendering a component. The
// setup for these older tests is much more verbose.
//
// I'm not totally clear on everything `act` does, but react-test-renderer
// seems to recommend it strongly enough that we actually get errors if we
// don't use it. Following links --
// path_to_url#testrendereract
// path_to_url#act
// path_to_url
// -- I see the following, which I think does the best job of explaining.
// (The `act` in `react-dom/test-utils` might not be identical to the
// `act` in `react-test-renderer`, but `react-test-renderer` says they're
// similar.)
// > When writing UI tests, tasks like rendering, user events, or data
// > fetching can be considered as units of interaction with a user
// > interface. `react-dom/test-utils` provides a helper called `act()`
// > that makes sure all updates related to these units have been
// > processed and applied to the DOM before you make any assertions
class TestMachine {
static HOOK_VALUE_TRUE = 'HOOK_VALUE_TRUE';
static HOOK_VALUE_FALSE = 'HOOK_VALUE_FALSE';
_TestComponent: ComponentType<{| value: boolean |}>;
_testRenderer: $FlowFixMe;
constructor(ms: number, initialValue: boolean) {
this._TestComponent = function _TestComponent(props: {| value: boolean |}) {
const hookOutput = useHasStayedTrueForMs(props.value, ms);
return hookOutput ? TestMachine.HOOK_VALUE_TRUE : TestMachine.HOOK_VALUE_FALSE;
};
this._testRenderer = this._createTestRenderer(initialValue);
}
updateValue(value: boolean) {
this._updateTestRenderer(value);
}
hookOutput() {
const result = this._testRenderer.root.children[0] === TestMachine.HOOK_VALUE_TRUE;
return result;
}
async sleep(ms: number): Promise<void> {
// `fakeSleep` causes the timer to run, which causes the hook to set
// some state (with `useState`). `react-test-renderer` says we need to
// use `act` to be sure the state update is processed before we start
// making assertions.
return act(() => fakeSleep(ms));
}
cleanup() {
// path_to_url#testrendererunmount
this._testRenderer.unmount();
}
_createTestRenderer(initialValue: boolean) {
const TestComponent = this._TestComponent;
let testRenderer;
act(() => {
// path_to_url#testrenderercreate
testRenderer = create(<TestComponent value={initialValue} />);
});
return testRenderer;
}
_updateTestRenderer(value: boolean) {
const TestComponent = this._TestComponent;
act(() => {
// path_to_url#testrendererupdate
this._testRenderer.update(<TestComponent value={value} />);
});
}
}
const MS = 1000;
/**
* Simulate the input value changing over time, checking the hook's output.
*
* On each item in the `sequence`, this will:
* 1. Wait for a specified time
* 2. Read and assert the hook's output from the last render, as specified
* 3. Render again, with the specified input for the hook
*/
// Tell ESLint to recognize `testSequence` as a helper function that runs
// assertions.
/* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "testSequence"] }] */
const testSequence = async (args: {
description: string,
initialValue: boolean,
sequence: $ReadOnlyArray<{|
waitBefore: number,
expectedOutput: boolean,
thenUpdateInputTo?: boolean,
|}>,
}) => {
const { initialValue, sequence } = args;
const testMachine = new TestMachine(MS, initialValue);
// Should never be true before any time has passed.
expect(testMachine.hookOutput()).toBeFalse();
for (let i = 0; i < sequence.length; i++) {
const { waitBefore, expectedOutput, thenUpdateInputTo } = sequence[i];
await testMachine.sleep(waitBefore);
expect(testMachine.hookOutput()).toBe(expectedOutput);
if (thenUpdateInputTo !== undefined) {
testMachine.updateValue(thenUpdateInputTo);
}
}
testMachine.cleanup();
};
const sequencesToTest = [
{
description: 'start false, wait long time',
initialValue: false,
sequence: [{ waitBefore: 2 * MS, expectedOutput: false }],
},
{
description: 'start false, wait short time',
initialValue: false,
sequence: [{ waitBefore: MS / 2, expectedOutput: false }],
},
{
description: 'change to true, wait long time, change back to false',
initialValue: false,
sequence: [
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: 2 * MS, expectedOutput: true, thenUpdateInputTo: false },
{ waitBefore: MS / 2, expectedOutput: false },
{ waitBefore: MS, expectedOutput: false },
],
},
{
description: 'start false, quickly back and forth between true and false',
initialValue: false,
sequence: [
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: 2 * MS, expectedOutput: false },
],
},
{
description: 'start false, repeatedly set to false in quick succession',
initialValue: false,
sequence: [
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: false },
],
},
{
description: 'start true, wait short time',
initialValue: true,
sequence: [{ waitBefore: MS / 2, expectedOutput: false }],
},
{
description: 'start true, wait long time',
initialValue: true,
sequence: [{ waitBefore: 2 * MS, expectedOutput: true }],
},
{
description: 'start true, switch to false after short time, wait longer',
initialValue: true,
sequence: [
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS, expectedOutput: false },
],
},
{
description: 'start true, switch to false after long time',
initialValue: true,
sequence: [
{ waitBefore: 2 * MS, expectedOutput: true, thenUpdateInputTo: false },
{ waitBefore: MS / 2, expectedOutput: false },
{ waitBefore: MS, expectedOutput: false },
],
},
{
description: 'start true, quickly back and forth between true and false',
initialValue: true,
sequence: [
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 2, expectedOutput: false, thenUpdateInputTo: false },
{ waitBefore: 2 * MS, expectedOutput: false },
],
},
{
description: 'start true, repeatedly set to true in quick succession',
initialValue: true,
sequence: [
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 5, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 5 - 1, expectedOutput: false, thenUpdateInputTo: true },
{ waitBefore: MS / 5 + 1, expectedOutput: true },
],
},
];
for (let i = 0; i < sequencesToTest.length; i++) {
const currentSequence = sequencesToTest[i];
test(currentSequence.description, async () => {
await testSequence(currentSequence);
});
}
});
test('useDateRefreshedAtInterval', async () => {
const interval = 60_000;
function sleep(ms: number): Promise<void> {
return ReactHooksTesting.act(() => fakeSleep(ms));
}
// path_to_url#renderhook
const { result } = ReactHooksTesting.renderHook(() => useDateRefreshedAtInterval(interval));
let value = result.current;
expect(result.error).toBeUndefined();
await sleep(interval / 10);
expect(result.error).toBeUndefined();
expect(result.current).toBe(value);
await sleep(interval / 10);
expect(result.error).toBeUndefined();
expect(result.current).toBe(value);
await sleep(interval);
expect(result.error).toBeUndefined();
expect(result.current).not.toBe(value);
expect((result.current - value) * 1000).toBeGreaterThanOrEqual(interval);
value = result.current;
await sleep(interval / 10);
expect(result.error).toBeUndefined();
expect(result.current).toBe(value);
await sleep(interval / 10);
expect(result.error).toBeUndefined();
expect(result.current).toBe(value);
});
```
|
/content/code_sandbox/src/__tests__/reactUtils-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 2,743
|
```javascript
/* @flow strict-local */
import { objectFromEntries } from '../jsBackport';
describe('objectFromEntries', () => {
test('basic', () => {
expect(
// prettier-ignore
objectFromEntries([['number', 1], ['null', null], ['obj', {}], ['undef', undefined]]),
).toStrictEqual({ number: 1, null: null, obj: {}, undef: undefined });
});
});
```
|
/content/code_sandbox/src/__tests__/jsBackport-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 96
|
```javascript
/** @jest-environment jest-environment-jsdom-global */
// @flow strict-local
import { assertUsingFakeTimers } from './lib/fakeTimers';
/**
* This file should not test any part of the application. It exists to test that
* certain functionality is present in the development environment used to run
* other tests.
*/
describe('jsdom-global', () => {
/* All cryptic strings are courtesy of random.org's string generator. */
test('is reconfigurable', () => {
const hostname = 'rgi3npqqem36kcabzjct';
const paths = [
'AYfhTK8ABTJPrN7pbc8M',
'8RbKFoRC82El6uop05Xo',
'npiWKcEuuPw90yVQxISh',
'0qrkWHiLXTr3TqgTR3RM',
];
global.jsdom.reconfigure({
url: `path_to_url{hostname}.com/${paths.join('/')}/index.html`,
});
expect(document.location.host).toContain(hostname);
paths.forEach(element => {
expect(document.location.pathname).toContain(element);
});
});
describe('properly resolves a URL', () => {
// Segments of the source URL.
const protocol = 'https';
const hostname = 'jmur7s0lluxumpbgg7kq';
const path = 'nDYYQXuN2yaOe6JQiN0q';
const file = 'gp36FBqcuUxGHgQn9aDX';
// The source URL itself, which later URL references will be resolved
// relative to.
const sourceURL = `${protocol}://www.${hostname}.com/${path}/${file}`;
// Auxiliary function: given a URL, how many of the above segments does it
// share with the sourceURL?
const matchCount: (s: string) => number = (() => {
const vals = [protocol, hostname, path, file];
return (s: string) => vals.reduce((c, val) => c + s.includes(val), 0);
})();
// Test data, as a series of tuples:
// [human-readable-reference-type, url-reference, expected-match-count]
const data: [string, string, number][] = [
['document-internal', '#anchors-aweigh', 4],
['immediate', '.', 3],
['path-relative', 'index2.html', 3],
['explicitly-path-relative', './wat.jpg', 3],
['root-relative', '/an/arbitrary/path.mp3', 2],
['protocol-relative', '//github.com/zulip/zulip-mobile/', 1],
['absolute', 'file:///bin/sh', 0],
];
for (const [urlType, url, expectedCount] of data) {
test(`from a(n) ${urlType} URL`, () => {
global.jsdom.reconfigure({ url: sourceURL });
// implicitly resolve URL via an anchor-element's `href`
const link: HTMLAnchorElement = document.createElement('a');
link.href = url;
const result: string = link.href;
expect(matchCount(result)).toBe(expectedCount);
});
}
});
});
describe('Jest fake timers', () => {
assertUsingFakeTimers();
afterEach(() => {
// clear any unset timers
jest.clearAllTimers();
});
test('Date.now() is mocked', () => {
const start = Date.now();
jest.advanceTimersByTime(5.5e9); // ~63.66 days
const end = Date.now();
const apparentDuration = end - start;
expect(apparentDuration).toBeGreaterThan(5e9);
expect(apparentDuration).toBeLessThan(6e9);
});
test('setInterval is triggered', () => {
let count = 0;
setInterval(() => {
++count;
}, 1e9);
jest.advanceTimersByTime(5.5e9);
expect(count).toBe(5);
});
test('setTimeout is triggered', () => {
let flag = false;
setTimeout(() => {
flag = true;
}, 3e6);
setTimeout(() => {
flag = false;
}, 6e6);
jest.advanceTimersByTime(4.5e6);
expect(flag).toBe(true);
});
test('timer count is properly maintained', () => {
expect(jest.getTimerCount()).toBe(0);
setInterval(() => {}, 10);
setInterval(() => {}, 10);
setInterval(() => {}, 10);
setInterval(() => {}, 10);
setInterval(() => {}, 10);
expect(jest.getTimerCount()).toBe(5);
setTimeout(() => {}, 10);
setTimeout(() => {}, 10);
setTimeout(() => {}, 10);
setTimeout(() => {}, 10);
setTimeout(() => {}, 10);
expect(jest.getTimerCount()).toBe(10);
jest.advanceTimersByTime(20);
expect(jest.getTimerCount()).toBe(5);
jest.clearAllTimers();
expect(jest.getTimerCount()).toBe(0);
});
test('runOnlyPendingTimers runs timers as expected', () => {
const start = Date.now();
// set up eternal interval
let count = 0;
const interval = 10;
setInterval(() => ++count, interval);
const maxTime = 1000;
// set up several timeouts, of length at most `maxTime`
const timeOuts = 37;
for (const k of Array(timeOuts).keys()) {
setTimeout(() => {}, ((k + 1) / timeOuts) * maxTime);
}
jest.runOnlyPendingTimers();
const end = Date.now();
// A long time has passed...
expect(end - start).toBeGreaterThanOrEqual(maxTime);
// ... only the interval timer is still active...
expect(jest.getTimerCount()).toBe(1);
// ... and it has been fired appropriately many times.
expect(count).toBeCloseTo((end - start) / interval, 1);
});
});
```
|
/content/code_sandbox/src/__tests__/test-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,353
|
```javascript
/*
* @flow strict-local
*/
import * as Sentry from '@sentry/react-native';
import { isSentryActive } from '../sentry';
describe('sentry', () => {
describe('is usable without initialization', () => {
// Sentry shouldn't be active at all in debug mode -- certainly not while
// we're specifically testing that its entry points can be used while it's
// uninitialized. These tests assert that.
test('breadcrumbs', () => {
expect(isSentryActive()).toBeFalse();
Sentry.addBreadcrumb({
message: 'test message',
level: 'debug',
});
expect(isSentryActive()).toBeFalse();
});
test('exception reporting', () => {
expect(isSentryActive()).toBeFalse();
// The text here is intended to prevent some hypothetical future reader of
// Sentry event logs dismissing the error as harmless expected noise, in
// case Sentry is somehow actually initialized at this point.
const err = new Error('Jest test error; should not result in a Sentry event');
Sentry.captureException(err);
expect(isSentryActive()).toBeFalse();
});
});
});
```
|
/content/code_sandbox/src/__tests__/sentry-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 246
|
```javascript
/* @flow strict-local */
import React, {
useContext,
useRef,
useState,
useEffect,
useCallback,
useMemo,
useImperativeHandle,
forwardRef,
} from 'react';
import { Platform, View } from 'react-native';
import type { LayoutEvent } from 'react-native/Libraries/Types/CoreEventTypes';
import { SafeAreaView } from 'react-native-safe-area-context';
import invariant from 'invariant';
// $FlowFixMe[untyped-import]
import * as fenced_code from '@zulip/shared/lib/fenced_code';
import { usePrevious } from '../reactUtils';
import * as apiConstants from '../api/constants';
import { ThemeContext, BRAND_COLOR, createStyleSheet } from '../styles';
import type {
Narrow,
VideoChatProvider,
Message,
Outbox,
Stream,
UserOrBot,
GetText,
} from '../types';
import { useSelector, useDispatch } from '../react-redux';
import { TranslationContext } from '../boot/TranslationProvider';
import { draftUpdate, sendTypingStart, sendTypingStop } from '../actions';
import Touchable from '../common/Touchable';
import Input from '../common/Input';
import { showErrorAlert } from '../utils/info';
import { IconDone, IconSend } from '../common/Icons';
import {
isConversationNarrow,
isStreamNarrow,
isStreamOrTopicNarrow,
isTopicNarrow,
streamIdOfNarrow,
topicNarrow,
topicOfNarrow,
} from '../utils/narrow';
import ComposeMenu from './ComposeMenu';
import getComposeInputPlaceholder from './getComposeInputPlaceholder';
import NotSubscribed from '../message/NotSubscribed';
import AnnouncementOnly from '../message/AnnouncementOnly';
import MentionWarnings from './MentionWarnings';
import {
getAuth,
getOwnUser,
getStreamInNarrow,
getStreamsById,
getVideoChatProvider,
getRealm,
getZulipFeatureLevel,
} from '../selectors';
import {
getIsActiveStreamSubscribed,
getIsActiveStreamAnnouncementOnly,
} from '../subscriptions/subscriptionSelectors';
import TopicAutocomplete from '../autocomplete/TopicAutocomplete';
import AutocompleteView from '../autocomplete/AutocompleteView';
import { getAllUsersById, getOwnUserId } from '../users/userSelectors';
import * as api from '../api';
import { ensureUnreachable } from '../generics';
import { roleIsAtLeast } from '../permissionSelectors';
import { Role } from '../api/permissionsTypes';
import useUncontrolledInput from '../useUncontrolledInput';
import { tryFetch } from '../message/fetchActions';
import { getMessageUrl } from '../utils/internalLinks';
import * as logging from '../utils/logging';
import type { Attachment } from './ComposeMenu';
import { ApiError, RequestError } from '../api/apiErrors';
/* eslint-disable no-shadow */
type Props = $ReadOnly<{|
/** The narrow shown in the message list. Must be a conversation or stream. */
// In particular `destinationNarrow` makes assumptions about the narrow
// (and other code might too.)
narrow: Narrow,
onSend: (message: string, destinationNarrow: Narrow) => void,
isEditing: boolean,
/** The contents of the message that the ComposeBox should contain when it's first rendered */
initialMessage?: string,
/** The topic of the message that the ComposeBox should contain when it's first rendered */
initialTopic?: string,
/** Whether the topic input box should auto-foucs when the component renders.
*
* Passed through to the TextInput's autofocus prop. */
autoFocusTopic?: boolean,
/** Whether the message input box should auto-foucs when the component renders.
*
* Passed through to the TextInput's autofocus prop. */
autoFocusMessage?: boolean,
|}>;
// TODO(?): Could deduplicate with this type in ShareWrapper.
export type ValidationError =
| 'upload-in-progress'
| 'message-empty'
| 'mandatory-topic-empty'
| 'quote-and-reply-in-progress';
/**
* Functions expected to be called using a ref to this component.
*/
export type ImperativeHandle = {|
/**
* Take a message ID, fetch its raw Markdown content, and put it in the
* compose box with proper formatting.
*/
+doQuoteAndReply: (message: Message | Outbox) => Promise<void>,
|};
const FOCUS_DEBOUNCE_TIME_MS = 16;
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Get the quote-and-reply text for a message, with fence and silent mention.
*
* Doesn't include any leading or trailing newlines; the caller should do
* that if desired.
*/
function getQuoteAndReplyText(args: {|
message: Message | Outbox,
rawContent: string,
user: UserOrBot,
realm: URL,
streamsById: Map<number, Stream>,
zulipFeatureLevel: number,
_: GetText,
|}): string {
// Modeled on replace_content in static/js/compose_actions.js in the
// zulip/zulip repo.
// TODO(shared): Share that code?
//
// Result looks like:
// @_**Iago|5** [said](link to message):
// ```quote
// message content
// ```
const { message, rawContent, user, realm, streamsById, zulipFeatureLevel, _ } = args;
const authorLine = _({
// Matches the web-app string
text: '{username} [said]({link_to_message}):',
values: {
username: `@_**${user.full_name}|${user.user_id}**`,
link_to_message: getMessageUrl(realm, message, streamsById, zulipFeatureLevel).toString(),
},
});
const fence = fenced_code.get_unused_fence(rawContent);
return `\
${authorLine}
${fence}quote
${rawContent}
${fence}`;
}
const ComposeBox: React$AbstractComponent<Props, ImperativeHandle> = forwardRef((props, ref) => {
const {
narrow,
onSend,
isEditing,
initialMessage,
initialTopic,
autoFocusTopic,
autoFocusMessage,
} = props;
const _ = useContext(TranslationContext);
const dispatch = useDispatch();
const auth = useSelector(getAuth);
const zulipFeatureLevel = useSelector(getZulipFeatureLevel);
const ownUserId = useSelector(getOwnUserId);
const allUsersById = useSelector(getAllUsersById);
const isAtLeastAdmin = useSelector(state => roleIsAtLeast(getOwnUser(state).role, Role.Admin));
const isAnnouncementOnly = useSelector(state =>
getIsActiveStreamAnnouncementOnly(state, props.narrow),
);
const isSubscribed = useSelector(state => getIsActiveStreamSubscribed(state, props.narrow));
const stream = useSelector(state => getStreamInNarrow(state, props.narrow));
const streamsById = useSelector(getStreamsById);
const videoChatProvider = useSelector(getVideoChatProvider);
const { mandatoryTopics, enableGuestUserIndicator } = useSelector(getRealm);
const mentionWarnings = React.useRef<React$ElementRef<typeof MentionWarnings> | null>(null);
const inputBlurTimeoutId = useRef<?TimeoutID>(null);
const [height, setHeight] = useState<number>(20);
const [focusState, setFocusState] = useState<{|
message: boolean,
topic: boolean,
/** Almost the same as message || topic ... except debounced, to stay
* true while those flip from false/true to true/false and back. */
either: boolean,
|}>({
message: false,
topic: false,
either: false,
});
const [
topicInputRef,
topicInputState,
setTopicInputValue,
setTopicInputSelection /* eslint-disable-line no-unused-vars */,
topicInputCallbacks,
] = useUncontrolledInput({
value: initialTopic ?? (isTopicNarrow(narrow) ? topicOfNarrow(narrow) : ''),
});
const [
messageInputRef,
messageInputState,
setMessageInputValue,
setMessageInputSelection /* eslint-disable-line no-unused-vars */,
messageInputCallbacks,
] = useUncontrolledInput({ value: initialMessage ?? '', selection: { start: 0, end: 0 } });
useEffect(
() => () => {
clearTimeout(inputBlurTimeoutId.current);
inputBlurTimeoutId.current = null;
},
[],
);
const prevMessageInputState = usePrevious(messageInputState);
useEffect(() => {
const messageInputValue = messageInputState.value;
const prevMessageInputValue = prevMessageInputState?.value;
if (prevMessageInputValue !== messageInputValue) {
if (messageInputValue.length === 0) {
dispatch(sendTypingStop(narrow));
} else {
dispatch(sendTypingStart(narrow));
}
if (!isEditing) {
dispatch(draftUpdate(narrow, messageInputValue));
}
}
}, [dispatch, isEditing, narrow, messageInputState, prevMessageInputState]);
const updateIsFocused = useCallback(() => {
setFocusState(state => ({ ...state, either: state.message || state.topic }));
}, []);
const topicSelectionAllowed = useMemo(
() => (isEditing ? isStreamOrTopicNarrow(narrow) : isStreamNarrow(narrow)),
[isEditing, narrow],
);
const topicInputVisible = topicSelectionAllowed && (focusState.either || isEditing);
/**
* Inserts text at the message input's cursor position.
*
* Selected text is not replaced: selection-start is ignored, and
* selection-end is taken to be the cursor position.
*
* If padWithEmptyLines is true, adds an empty line before (unless cursor
* is at 0) and after `text`.
*/
// An earlier version of this function *would* replace selected text,
// which could be upsetting if you didn't want to lose the selected text.
const insertMessageTextAtCursorPosition = useCallback(
(text: string, padWithEmptyLines = false) => {
setMessageInputValue(state => {
const cursorPosition = state.selection.end;
const paddingStart = padWithEmptyLines && cursorPosition !== 0 ? '\n\n' : '';
const paddingEnd = padWithEmptyLines ? '\n\n' : '';
return (
state.value.slice(0, cursorPosition)
+ paddingStart
+ text
+ paddingEnd
+ state.value.slice(cursorPosition)
);
});
},
[setMessageInputValue],
);
const insertVideoCallLink = useCallback(
(videoChatProvider: VideoChatProvider) => {
if (videoChatProvider.name === 'jitsi_meet') {
// This is meant to align with the way the webapp generates jitsi video
// call IDs. That logic can be found in the ".video_link" click handler
// in static/js/compose.js.
const videoCallId = randomInt(100000000000000, 999999999999999);
const videoCallUrl = `${videoChatProvider.jitsiServerUrl}/${videoCallId}`;
const linkMessage = _('Click to join video call');
const linkText = `[${linkMessage}](${videoCallUrl})`;
insertMessageTextAtCursorPosition(linkText);
}
},
[insertMessageTextAtCursorPosition, _],
);
const [numUploading, setNumUploading] = useState<number>(0);
const insertAttachments = useCallback(
async (attachments: $ReadOnlyArray<Attachment>) => {
setNumUploading(n => n + 1);
try {
const fileNames: string[] = [];
const placeholders: string[] = [];
for (let i = 0; i < attachments.length; i++) {
const fileName = attachments[i].name ?? _('Attachment {num}', { num: i + 1 });
fileNames.push(fileName);
const placeholder = `[${_('Uploading {fileName}...', { fileName })}]()`;
placeholders.push(placeholder);
}
insertMessageTextAtCursorPosition(placeholders.join('\n\n'));
for (let i = 0; i < attachments.length; i++) {
const fileName = fileNames[i];
const placeholder = placeholders[i];
let response = null;
try {
response = await api.uploadFile(auth, attachments[i].url, fileName);
} catch (errorIllTyped) {
const error: mixed = errorIllTyped; // path_to_url
if (!(error instanceof Error)) {
logging.error('ComposeBox: Unexpected non-error thrown');
}
let msg = undefined;
if (
error instanceof RequestError
&& error.httpStatus === 413 // 413 Payload Too Large:
// path_to_url#issuecomment-1092140960
) {
msg = _('The server said the file is too large.');
} else if (error instanceof ApiError) {
msg = _('The server said:\n\n{errorMessage}', { errorMessage: error.message });
} else if (error instanceof Error && error.message.length > 0) {
msg = error.message;
}
showErrorAlert(_('Failed to upload file: {fileName}', { fileName }), msg);
setMessageInputValue(state =>
state.value.replace(
placeholder,
() => `[${_('Failed to upload file: {fileName}', { fileName })}]()`,
),
);
continue;
}
const linkText = `[${fileName}](${response.uri})`;
setMessageInputValue(state =>
state.value.indexOf(placeholder) !== -1
? state.value.replace(placeholder, () => linkText)
: `${state.value}\n${linkText}`,
);
}
} finally {
setNumUploading(n => n - 1);
}
},
[insertMessageTextAtCursorPosition, _, auth, setMessageInputValue],
);
const activeInvocations = useRef<number[]>([]);
const [activeQuoteAndRepliesCount, setActiveQuoteAndRepliesCount] = useState(0);
const anyQuoteAndReplyInProgress = activeQuoteAndRepliesCount > 0;
const doQuoteAndReply = useCallback(
async message => {
// TODO: For composing a new message (i.e. isEditing is false), if
// not already there, re-narrow to `message`'s conversation narrow,
// with getNarrowForReply, and do the quote-and-reply there.
// Discussion:
// path_to_url#narrow/stream/243-mobile-team/topic/.23M1975.20Quote.20and.20reply/near/1455302
setActiveQuoteAndRepliesCount(v => v + 1);
const serialNumber =
activeInvocations.current.length > 0
? activeInvocations.current[activeInvocations.current.length - 1] + 1
: 0;
activeInvocations.current.push(serialNumber);
try {
const user = allUsersById.get(message.sender_id);
if (!user) {
showErrorAlert(_('Quote-and-reply failed'));
logging.error('Missing user for sender_id in quote-and-reply', {
sender_id: message.sender_id,
});
return;
}
// Set to match quoting_placeholder in quote_and_reply in
// static/js/compose_actions.js in the zulip/zulip repo.
const quotingPlaceholder =
serialNumber > 0
? _({ text: '[Quoting ({serialNumber})]', values: { serialNumber } })
: _('[Quoting]');
insertMessageTextAtCursorPosition(quotingPlaceholder, true);
let rawContent = undefined;
try {
// TODO: Give feedback when the server round trip takes longer than
// expected.
// TODO: Let the user cancel the request so we don't force a
// quote-and-reply after they've given up and perhaps forgotten
// about it.
rawContent = await tryFetch(() =>
api.getRawMessageContent(auth, { message_id: message.id }, zulipFeatureLevel),
);
} catch {
showErrorAlert(_('Quote-and-reply failed'));
return;
}
if (topicSelectionAllowed && topicInputState.value === '' && message.type === 'stream') {
// Later, this won't be necessary in the case of composing a new
// message. See TODO above about re-narrowing to `message`'s
// conversation.
setTopicInputValue(message.subject);
}
const quoteAndReplyText = getQuoteAndReplyText({
message,
rawContent,
user,
realm: auth.realm,
streamsById,
zulipFeatureLevel,
_,
});
setMessageInputValue(state =>
state.value.replace(quotingPlaceholder, () => quoteAndReplyText),
);
messageInputRef.current?.focus();
} finally {
setActiveQuoteAndRepliesCount(v => v - 1);
activeInvocations.current = activeInvocations.current.filter(x => x !== serialNumber);
}
},
[
auth,
allUsersById,
streamsById,
insertMessageTextAtCursorPosition,
setMessageInputValue,
zulipFeatureLevel,
_,
topicSelectionAllowed,
topicInputState.value,
setTopicInputValue,
messageInputRef,
],
);
useImperativeHandle(ref, () => ({ doQuoteAndReply }), [doQuoteAndReply]);
const handleLayoutChange = useCallback((event: LayoutEvent) => {
setHeight(event.nativeEvent.layout.height);
}, []);
const handleTopicAutocomplete = useCallback(
(topic: string) => {
setTopicInputValue(topic);
messageInputRef.current?.focus();
},
[setTopicInputValue, messageInputRef],
);
// See JSDoc on 'onAutocomplete' in 'AutocompleteView.js'.
const handleMessageAutocomplete = useCallback(
(completedText: string, completion: string, lastWordPrefix: string) => {
setMessageInputValue(completedText);
if (lastWordPrefix === '@') {
mentionWarnings.current?.handleMentionSubscribedCheck(completion);
}
},
[setMessageInputValue],
);
const handleMessageFocus = useCallback(() => {
setFocusState(state => ({ ...state, message: true, either: true }));
if (
!isEditing
&& isStreamNarrow(narrow)
&& !focusState.either // not affected by setFocusState above; React state is set asynchronously
&& topicInputState.value === ''
) {
// We weren't showing the topic input when the user tapped on the input
// to focus it, but we're about to show it. Focus that, if the user
// hasn't already selected a topic.
topicInputRef.current?.focus();
}
}, [isEditing, narrow, focusState.either, topicInputState.value, topicInputRef]);
const handleMessageBlur = useCallback(() => {
setFocusState(state => ({ ...state, message: false }));
dispatch(sendTypingStop(narrow));
// give a chance to the topic input to get the focus
clearTimeout(inputBlurTimeoutId.current);
inputBlurTimeoutId.current = setTimeout(updateIsFocused, FOCUS_DEBOUNCE_TIME_MS);
}, [dispatch, narrow, updateIsFocused]);
const handleTopicFocus = useCallback(() => {
setFocusState(state => ({ ...state, topic: true, either: true }));
}, []);
const handleTopicBlur = useCallback(() => {
setFocusState(state => ({ ...state, topic: false }));
// give a chance to the message input to get the focus
clearTimeout(inputBlurTimeoutId.current);
inputBlurTimeoutId.current = setTimeout(updateIsFocused, FOCUS_DEBOUNCE_TIME_MS);
}, [updateIsFocused]);
const destinationNarrow = useMemo(() => {
if (isStreamNarrow(narrow) || (isTopicNarrow(narrow) && isEditing)) {
const streamId = streamIdOfNarrow(narrow);
const topic = topicInputState.value.trim() || apiConstants.kNoTopicTopic;
return topicNarrow(streamId, topic);
}
invariant(isConversationNarrow(narrow), 'destination narrow must be conversation');
return narrow;
}, [isEditing, narrow, topicInputState.value]);
const validationErrors: $ReadOnlyArray<ValidationError> = useMemo(() => {
const { value: messageInputValue } = messageInputState;
const result = [];
if (
isTopicNarrow(destinationNarrow)
&& topicOfNarrow(destinationNarrow) === apiConstants.kNoTopicTopic
&& mandatoryTopics
) {
result.push('mandatory-topic-empty');
}
if (messageInputValue.trim().length === 0) {
result.push('message-empty');
}
if (numUploading > 0) {
result.push('upload-in-progress');
}
if (anyQuoteAndReplyInProgress) {
result.push('quote-and-reply-in-progress');
}
return result;
}, [
destinationNarrow,
mandatoryTopics,
numUploading,
anyQuoteAndReplyInProgress,
messageInputState,
]);
const submitButtonDisabled = validationErrors.length > 0;
const handleSubmit = useCallback(() => {
const { value: messageInputValue } = messageInputState;
if (validationErrors.length > 0) {
const msg = validationErrors
.map(error => {
switch (error) {
case 'upload-in-progress':
return _('Please wait for the upload to complete.');
case 'quote-and-reply-in-progress':
return _('Please wait for the quote-and-reply to complete.');
case 'mandatory-topic-empty':
return _('Please specify a topic.');
case 'message-empty':
return _('Message is empty.');
default:
ensureUnreachable(error);
throw new Error();
}
})
.join('\n\n');
// TODO is this enough to handle the `isEditing` case? See
// path_to_url#discussion_r731341400.
showErrorAlert(isEditing ? _('Message not saved') : _('Message not sent'), msg);
return;
}
onSend(messageInputValue, destinationNarrow);
setMessageInputValue('');
if (mentionWarnings.current) {
mentionWarnings.current.clearMentionWarnings();
}
dispatch(sendTypingStop(destinationNarrow));
}, [
destinationNarrow,
validationErrors,
_,
dispatch,
isEditing,
onSend,
setMessageInputValue,
messageInputState,
]);
const inputMarginPadding = useMemo(
() => ({
paddingHorizontal: 8,
paddingVertical: Platform.select({
ios: 8,
android: 2,
}),
}),
[],
);
const { backgroundColor } = useContext(ThemeContext);
const styles = useMemo(
() =>
createStyleSheet({
wrapper: {
flexShrink: 1,
maxHeight: '60%',
},
autocompleteWrapper: {
position: 'absolute',
bottom: 0,
width: '100%',
marginBottom: height,
},
composeBox: {
flexDirection: 'row',
alignItems: 'flex-end',
flexShrink: 1,
backgroundColor: 'hsla(0, 0%, 50%, 0.1)',
},
composeInputs: {
flex: 1,
paddingTop: 8,
paddingLeft: 8,
},
submitButtonContainer: {
padding: 8,
},
submitButton: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: BRAND_COLOR,
borderRadius: 32,
padding: 8,
opacity: submitButtonDisabled ? 0.25 : 1,
},
topicInput: {
// These border attributes override styles set in <Input />.
borderWidth: 0,
borderRadius: 5,
marginBottom: 8,
...inputMarginPadding,
backgroundColor,
// This is a really dumb hack to work around
// path_to_url
// Someone suggests in that thread that { position: absolute,
// zIndex: -1 } will work, which it does not (the border of the
// TextInput is still visible, even with very negative zIndex
// values). Someone else suggests { transform: [{scale: 0}] }
// (path_to_url which doesn't work
// either. However, a combinarion of the two of them seems to
// work.
...(!topicInputVisible && { position: 'absolute', transform: [{ scale: 0 }] }),
},
composeTextInput: {
// These border attributes override styles set in <Input />.
borderWidth: 0,
borderRadius: 5,
fontSize: 15,
flexShrink: 1,
...inputMarginPadding,
backgroundColor,
},
}),
[inputMarginPadding, backgroundColor, height, submitButtonDisabled, topicInputVisible],
);
const submitButtonHitSlop = useMemo(() => ({ top: 8, right: 8, bottom: 8, left: 8 }), []);
const { value: messageInputValue, selection: messageInputSelection } = messageInputState;
if (!isSubscribed) {
return <NotSubscribed narrow={narrow} />;
} else if (isAnnouncementOnly && !isAtLeastAdmin) {
return <AnnouncementOnly />;
}
const placeholder = getComposeInputPlaceholder(
narrow,
ownUserId,
allUsersById,
streamsById,
enableGuestUserIndicator,
_,
);
const SubmitButtonIcon = isEditing ? IconDone : IconSend;
return (
<View style={styles.wrapper}>
<MentionWarnings narrow={narrow} stream={stream} ref={mentionWarnings} />
<View style={styles.autocompleteWrapper}>
<TopicAutocomplete
isFocused={focusState.topic}
narrow={narrow}
text={topicInputState.value}
onAutocomplete={handleTopicAutocomplete}
/>
<AutocompleteView
isFocused={focusState.message}
selection={messageInputSelection}
text={messageInputValue}
onAutocomplete={handleMessageAutocomplete}
destinationNarrow={destinationNarrow}
/>
</View>
<SafeAreaView
mode="padding"
// When the keyboard is open, this bottom padding is compensated
// for: we pass KeyboardAvoider's compensateOverpadding prop.
edges={['bottom']}
style={styles.composeBox}
onLayout={handleLayoutChange}
>
<View style={styles.composeInputs}>
<Input
style={styles.topicInput}
autoCapitalize="none"
underlineColorAndroid="transparent"
placeholder="Topic"
defaultValue={topicInputState.value}
autoFocus={autoFocusTopic}
selectTextOnFocus
textInputRef={topicInputRef}
{...topicInputCallbacks}
onFocus={handleTopicFocus}
onBlur={handleTopicBlur}
onSubmitEditing={() => messageInputRef.current?.focus()}
blurOnSubmit={false}
returnKeyType="next"
/>
<Input
multiline
style={styles.composeTextInput}
underlineColorAndroid="transparent"
placeholder={placeholder}
defaultValue={messageInputValue}
autoFocus={autoFocusMessage}
textInputRef={messageInputRef}
{...messageInputCallbacks}
onBlur={handleMessageBlur}
onFocus={handleMessageFocus}
/>
<ComposeMenu
destinationNarrow={destinationNarrow}
insertAttachments={insertAttachments}
insertVideoCallLink={
videoChatProvider !== null ? () => insertVideoCallLink(videoChatProvider) : null
}
/>
</View>
<View style={styles.submitButtonContainer}>
<View
// Mask the Android ripple-on-touch so it doesn't extend
// outside the circle
// TODO: `Touchable` should do this, and the `hitSlop`
// workaround below.
style={{
borderRadius: styles.submitButton.borderRadius,
overflow: 'hidden',
}}
// and don't defeat the `Touchable`'s `hitSlop`.
hitSlop={submitButtonHitSlop}
>
<Touchable
style={styles.submitButton}
onPress={handleSubmit}
accessibilityLabel={isEditing ? _('Save message') : _('Send message')}
hitSlop={submitButtonHitSlop}
>
<SubmitButtonIcon size={16} color="white" />
</Touchable>
</View>
</View>
</SafeAreaView>
</View>
);
});
export default ComposeBox;
```
|
/content/code_sandbox/src/compose/ComposeBox.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 6,175
|
```javascript
/* @flow strict-local */
import invariant from 'invariant';
import { getOwnUser, tryGetActiveAccountState, getRealm } from '../selectors';
import {
Role,
CreatePublicOrPrivateStreamPolicy,
type CreatePublicOrPrivateStreamPolicyT,
CreateWebPublicStreamPolicy,
} from '../api/permissionsTypes';
import {
getHasUserPassedWaitingPeriod,
getCanCreatePublicStreams,
getCanCreatePrivateStreams,
getCanCreateWebPublicStreams,
roleIsAtLeast,
} from '../permissionSelectors';
import rootReducer from '../boot/reducers';
import { EVENT } from '../actionConstants';
import * as eg from './lib/exampleData';
import { EventTypes } from '../api/eventTypes';
describe('roleIsAtLeast', () => {
const { Owner, Admin, Moderator, Member, Guest } = Role;
const roleValues: $ReadOnlyArray<Role> = Array.from(Role.members());
// Keep this current with all possible roles, from least to most privilege.
const kRolesAscending = [Guest, Member, Moderator, Admin, Owner];
expect(roleValues).toIncludeSameMembers(kRolesAscending);
expect(roleValues).toBeArrayOfSize(kRolesAscending.length);
const roleEntries = roleValues.map(role => [Role.getName(role), role]);
roleEntries.forEach(([thresholdRoleName, thresholdRole]) => {
roleEntries.forEach(([thisRoleName, thisRole]) => {
const expected = kRolesAscending.indexOf(thisRole) >= kRolesAscending.indexOf(thresholdRole);
const testName = expected
? `${thisRoleName} is at least as high as ${thresholdRoleName}`
: `${thisRoleName} is lower than ${thresholdRoleName}`;
const actual = roleIsAtLeast(thisRole, thresholdRole);
test(testName, () => {
expect(actual).toBe(expected);
});
});
});
});
// TODO(?): Could deduplicate with the other getCanCreate*Streams; see
// path_to_url#discussion_r883215288
describe('getCanCreatePublicStreams', () => {
const { MemberOrAbove, AdminOrAbove, FullMemberOrAbove, ModeratorOrAbove } =
CreatePublicOrPrivateStreamPolicy;
const { Owner, Admin, Moderator, Member, Guest } = Role;
test.each`
policy | role | waitingPeriodPassed | expected
${MemberOrAbove} | ${Owner} | ${undefined} | ${true}
${MemberOrAbove} | ${Admin} | ${undefined} | ${true}
${MemberOrAbove} | ${Moderator} | ${undefined} | ${true}
${MemberOrAbove} | ${Member} | ${undefined} | ${true}
${MemberOrAbove} | ${Guest} | ${undefined} | ${false}
${AdminOrAbove} | ${Owner} | ${undefined} | ${true}
${AdminOrAbove} | ${Admin} | ${undefined} | ${true}
${AdminOrAbove} | ${Moderator} | ${undefined} | ${false}
${AdminOrAbove} | ${Member} | ${undefined} | ${false}
${AdminOrAbove} | ${Guest} | ${undefined} | ${false}
${FullMemberOrAbove} | ${Owner} | ${undefined} | ${true}
${FullMemberOrAbove} | ${Admin} | ${undefined} | ${true}
${FullMemberOrAbove} | ${Moderator} | ${undefined} | ${true}
${FullMemberOrAbove} | ${Member} | ${true} | ${true}
${FullMemberOrAbove} | ${Member} | ${false} | ${false}
${FullMemberOrAbove} | ${Guest} | ${undefined} | ${false}
${ModeratorOrAbove} | ${Owner} | ${undefined} | ${true}
${ModeratorOrAbove} | ${Admin} | ${undefined} | ${true}
${ModeratorOrAbove} | ${Moderator} | ${undefined} | ${true}
${ModeratorOrAbove} | ${Member} | ${undefined} | ${false}
${ModeratorOrAbove} | ${Guest} | ${undefined} | ${false}
`(
'returns $expected when policy is $policy; role is $role; waitingPeriodPassed is $waitingPeriodPassed',
async ({
policy,
role,
waitingPeriodPassed,
expected,
}: {
policy: CreatePublicOrPrivateStreamPolicyT,
role: Role,
waitingPeriodPassed: boolean | void,
expected: boolean,
}) => {
const globalState = [
{
type: EVENT,
event: {
id: 1,
type: EventTypes.realm_user,
op: 'update',
person: { user_id: eg.selfUser.user_id, role },
},
},
{
type: EVENT,
event: {
id: 0,
type: EventTypes.realm,
property: 'default',
op: 'update_dict',
data: { create_public_stream_policy: policy },
},
},
].reduce(rootReducer, eg.plusReduxState);
const newState = tryGetActiveAccountState(globalState);
invariant(newState !== undefined, 'expected newState');
if (waitingPeriodPassed !== undefined) {
// TODO(?): jest.mock getHasUserPassedWaitingPeriod instead (how?)
const daysToAdd =
getRealm(newState).waitingPeriodThreshold + (waitingPeriodPassed ? 2 : -2);
jest.setSystemTime(Date.parse(getOwnUser(newState).date_joined) + daysToAdd * 86400_000);
}
expect(getCanCreatePublicStreams(newState)).toBe(expected);
},
);
});
// TODO(?): Could deduplicate with the other getCanCreate*Streams; see
// path_to_url#discussion_r883215288
describe('getCanCreatePrivateStreams', () => {
const { MemberOrAbove, AdminOrAbove, FullMemberOrAbove, ModeratorOrAbove } =
CreatePublicOrPrivateStreamPolicy;
const { Owner, Admin, Moderator, Member, Guest } = Role;
test.each`
policy | role | waitingPeriodPassed | expected
${MemberOrAbove} | ${Owner} | ${undefined} | ${true}
${MemberOrAbove} | ${Admin} | ${undefined} | ${true}
${MemberOrAbove} | ${Moderator} | ${undefined} | ${true}
${MemberOrAbove} | ${Member} | ${undefined} | ${true}
${MemberOrAbove} | ${Guest} | ${undefined} | ${false}
${AdminOrAbove} | ${Owner} | ${undefined} | ${true}
${AdminOrAbove} | ${Admin} | ${undefined} | ${true}
${AdminOrAbove} | ${Moderator} | ${undefined} | ${false}
${AdminOrAbove} | ${Member} | ${undefined} | ${false}
${AdminOrAbove} | ${Guest} | ${undefined} | ${false}
${FullMemberOrAbove} | ${Owner} | ${undefined} | ${true}
${FullMemberOrAbove} | ${Admin} | ${undefined} | ${true}
${FullMemberOrAbove} | ${Moderator} | ${undefined} | ${true}
${FullMemberOrAbove} | ${Member} | ${true} | ${true}
${FullMemberOrAbove} | ${Member} | ${false} | ${false}
${FullMemberOrAbove} | ${Guest} | ${undefined} | ${false}
${ModeratorOrAbove} | ${Owner} | ${undefined} | ${true}
${ModeratorOrAbove} | ${Admin} | ${undefined} | ${true}
${ModeratorOrAbove} | ${Moderator} | ${undefined} | ${true}
${ModeratorOrAbove} | ${Member} | ${undefined} | ${false}
${ModeratorOrAbove} | ${Guest} | ${undefined} | ${false}
`(
'returns $expected when policy is $policy; role is $role; waitingPeriodPassed is $waitingPeriodPassed',
async ({
policy,
role,
waitingPeriodPassed,
expected,
}: {
policy: CreatePublicOrPrivateStreamPolicyT,
role: Role,
waitingPeriodPassed: boolean | void,
expected: boolean,
}) => {
const globalState = [
{
type: EVENT,
event: {
id: 1,
type: EventTypes.realm_user,
op: 'update',
person: { user_id: eg.selfUser.user_id, role },
},
},
{
type: EVENT,
event: {
id: 0,
type: EventTypes.realm,
property: 'default',
op: 'update_dict',
data: { create_private_stream_policy: policy },
},
},
].reduce(rootReducer, eg.plusReduxState);
const newState = tryGetActiveAccountState(globalState);
invariant(newState !== undefined, 'expected newState');
if (waitingPeriodPassed !== undefined) {
// TODO(?): jest.mock getHasUserPassedWaitingPeriod instead (how?)
const daysToAdd =
getRealm(newState).waitingPeriodThreshold + (waitingPeriodPassed ? 2 : -2);
jest.setSystemTime(Date.parse(getOwnUser(newState).date_joined) + daysToAdd * 86400_000);
}
expect(getCanCreatePrivateStreams(newState)).toBe(expected);
},
);
});
// TODO(?): Could deduplicate with the other getCanCreate*Streams; see
// path_to_url#discussion_r883215288
describe('getCanCreateWebPublicStreams', () => {
const { AdminOrAbove, ModeratorOrAbove, Nobody, OwnerOnly } = CreateWebPublicStreamPolicy;
const { Owner, Admin, Moderator, Member, Guest } = Role;
test('returns false when webPublicStreamsEnabled is false', () => {
const globalState = [
{
type: EVENT,
event: {
id: 0,
type: EventTypes.realm_user,
op: 'update',
person: { user_id: eg.selfUser.user_id, role: Owner },
},
},
].reduce(
rootReducer,
eg.reduxStatePlus({
realm: {
...eg.plusReduxState.realm,
webPublicStreamsEnabled: false,
enableSpectatorAccess: true,
createWebPublicStreamPolicy: ModeratorOrAbove,
},
}),
);
const state = tryGetActiveAccountState(globalState);
invariant(state, 'expected per-account state');
expect(getCanCreateWebPublicStreams(state)).toBeFalse();
});
test('returns false when enableSpectatorAccess is false', () => {
const globalState = [
{
type: EVENT,
event: {
id: 0,
type: EventTypes.realm_user,
op: 'update',
person: { user_id: eg.selfUser.user_id, role: Owner },
},
},
].reduce(
rootReducer,
eg.reduxStatePlus({
realm: {
...eg.plusReduxState.realm,
webPublicStreamsEnabled: true,
enableSpectatorAccess: false,
createWebPublicStreamPolicy: ModeratorOrAbove,
},
}),
);
const state = tryGetActiveAccountState(globalState);
invariant(state, 'expected per-account state');
expect(getCanCreateWebPublicStreams(state)).toBeFalse();
});
test.each`
policy | role | expected
${AdminOrAbove} | ${Owner} | ${true}
${AdminOrAbove} | ${Admin} | ${true}
${AdminOrAbove} | ${Moderator} | ${false}
${AdminOrAbove} | ${Member} | ${false}
${AdminOrAbove} | ${Guest} | ${false}
${ModeratorOrAbove} | ${Owner} | ${true}
${ModeratorOrAbove} | ${Admin} | ${true}
${ModeratorOrAbove} | ${Moderator} | ${true}
${ModeratorOrAbove} | ${Member} | ${false}
${ModeratorOrAbove} | ${Guest} | ${false}
${Nobody} | ${Owner} | ${false}
${Nobody} | ${Admin} | ${false}
${Nobody} | ${Moderator} | ${false}
${Nobody} | ${Member} | ${false}
${Nobody} | ${Guest} | ${false}
${OwnerOnly} | ${Owner} | ${true}
${OwnerOnly} | ${Admin} | ${false}
${OwnerOnly} | ${Moderator} | ${false}
${OwnerOnly} | ${Member} | ${false}
${OwnerOnly} | ${Guest} | ${false}
`(
'returns $expected when policy is $policy and role is $role',
async ({
policy,
role,
expected,
}: {
policy: CreateWebPublicStreamPolicy,
role: Role,
expected: boolean,
}) => {
const globalState = [
{
type: EVENT,
event: {
id: 0,
type: EventTypes.realm_user,
op: 'update',
person: { user_id: eg.selfUser.user_id, role },
},
},
].reduce(
rootReducer,
eg.reduxStatePlus({
realm: {
...eg.plusReduxState.realm,
webPublicStreamsEnabled: true,
enableSpectatorAccess: true,
createWebPublicStreamPolicy: policy,
},
}),
);
const state = tryGetActiveAccountState(globalState);
invariant(state, 'expected per-account state');
expect(getCanCreateWebPublicStreams(state)).toBe(expected);
},
);
});
describe('getHasUserPassedWaitingPeriod', () => {
test.each`
dateJoined | currentDate | threshold | expected
${new Date('2000-01-01')} | ${new Date('2000-01-10')} | ${10} | ${false}
${new Date('2000-01-01')} | ${new Date('2000-01-11')} | ${10} | ${true}
${new Date('2000-01-01')} | ${new Date('2000-01-12')} | ${10} | ${true}
${new Date('2000-01-01')} | ${new Date('2000-03-30')} | ${90} | ${false}
${new Date('2000-01-01')} | ${new Date('2000-03-31')} | ${90} | ${true}
${new Date('2000-01-01')} | ${new Date('2000-04-01')} | ${90} | ${true}
`(
'returns $expected for dateJoined: $dateJoined; currentDate: $currentDate; threshold: $threshold',
async (args: {|
dateJoined: Date,
currentDate: Date,
threshold: number,
expected: boolean,
|}) => {
const { dateJoined, currentDate, threshold, expected } = args;
const globalState = [
{
type: EVENT,
event: {
id: 0,
type: EventTypes.realm,
op: 'update_dict',
property: 'default',
data: { waiting_period_threshold: threshold },
},
},
].reduce(
rootReducer,
eg.reduxStatePlus({
users: eg.plusReduxState.users.map(u =>
u.user_id === eg.selfUser.user_id ? { ...u, date_joined: dateJoined.toString() } : u,
),
}),
);
jest.setSystemTime(currentDate);
const newState = tryGetActiveAccountState(globalState);
expect(newState).toBeTruthy();
expect(newState && getHasUserPassedWaitingPeriod(newState, eg.selfUser.user_id)).toBe(
expected,
);
},
);
});
```
|
/content/code_sandbox/src/__tests__/permissionSelectors-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 3,557
|
```javascript
/* @flow strict-local */
import { sleep } from '../../utils/async';
/**
* Ensure the fake-timer implementation is used.
*
* By setting `timers: 'fake'` in our Jest config, the fake-timer
* implementation is the default. May be used to double-check that
* this default is in fact set, in our Jest setup file.
*
* Also, in one or two files, we switch over to using real timers,
* with `jest.useRealTimers()`. May be used in those files to make
* sure this setting doesn't linger where we don't want it to.
*
* Note: As of Jest 27, there are "modern" and "legacy" fake-timer
* implementations. This checks for the "modern" one, which is the only one
* we should use.
*/
export const assertUsingFakeTimers = () => {
// "Note: This function is only available when using modern fake
// timers implementation"
//
// -- path_to_url#jestgetrealsystemtime
jest.getRealSystemTime();
};
/**
* Return a promise to sleep `ms` after advancing fake timers by `ms`.
*/
export const fakeSleep = async (ms: number): Promise<void> => {
try {
assertUsingFakeTimers();
} catch {
throw new Error('Tried to call `fakeSleep` without fake-timer implementation enabled.');
}
const sleepPromise = sleep(ms);
jest.advanceTimersByTime(ms);
return sleepPromise;
};
```
|
/content/code_sandbox/src/__tests__/lib/fakeTimers.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 326
|
```javascript
/* @flow strict-local */
import type { GetText } from '../../types';
// Our translation function, usually given the name _.
// eslint-disable-next-line no-underscore-dangle
export const mock_: GetText = m => {
if (typeof m === 'object') {
if (m.text === '{_}') {
// $FlowIgnore[incompatible-indexer]
/* $FlowIgnore[incompatible-cast]
We expect an `m.values` that corresponds to `m.text`. */
const values = (m.values: {| +_: string |});
return values._;
}
return m.text;
}
return m;
};
```
|
/content/code_sandbox/src/__tests__/lib/intl.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 138
|
```javascript
/* @flow strict-local */
import type {
RealmState,
PerAccountApplicableAction,
RealmEmojiById,
VideoChatProvider,
} from '../types';
import {
CreatePublicOrPrivateStreamPolicy,
CreateWebPublicStreamPolicy,
} from '../api/permissionsTypes';
import { EventTypes } from '../api/eventTypes';
import {
REGISTER_COMPLETE,
EVENT_REALM_EMOJI_UPDATE,
EVENT,
EVENT_UPDATE_DISPLAY_SETTINGS,
EVENT_REALM_FILTERS,
REFRESH_SERVER_EMOJI_DATA,
RESET_ACCOUNT_DATA,
} from '../actionConstants';
import { objectFromEntries } from '../jsBackport';
import { objectEntries } from '../flowPonyfill';
const initialState = {
//
// InitialDataCustomProfileFields
//
customProfileFields: [],
//
// InitialDataRealm
//
name: '',
description: '',
nonActiveUsers: [],
filters: [],
emoji: {},
defaultExternalAccounts: new Map(),
videoChatProvider: null,
mandatoryTopics: false,
messageContentDeleteLimitSeconds: null,
messageContentEditLimitSeconds: 1,
pushNotificationsEnabled: true,
pushNotificationsEnabledEndTimestamp: null,
createPublicStreamPolicy: CreatePublicOrPrivateStreamPolicy.MemberOrAbove,
createPrivateStreamPolicy: CreatePublicOrPrivateStreamPolicy.MemberOrAbove,
webPublicStreamsEnabled: false,
createWebPublicStreamPolicy: CreateWebPublicStreamPolicy.Nobody,
enableSpectatorAccess: false,
waitingPeriodThreshold: 90,
allowEditHistory: false,
enableReadReceipts: false,
emailAddressVisibility: null,
enableGuestUserIndicator: false,
//
// InitialDataRealmUser
//
canCreateStreams: true,
user_id: undefined,
email: undefined,
crossRealmBots: [],
//
// InitialDataUserSettings
//
twentyFourHourTime: false,
presenceEnabled: false,
//
// Misc.: Not in the /register response.
//
serverEmojiData: null,
};
const convertRealmEmoji = (data): RealmEmojiById =>
objectFromEntries(Object.keys(data).map(id => [id, { ...data[id], code: id.toString() }]));
function getVideoChatProvider({
availableProviders,
jitsiServerUrl,
providerId,
}): VideoChatProvider | null {
// This logic parallels logic in the webapp in static/js/compose.js
// for interpreting similar data from page_params.
if (
availableProviders.jitsi_meet
&& availableProviders.jitsi_meet.id === providerId
&& jitsiServerUrl !== undefined
) {
return { name: 'jitsi_meet', jitsiServerUrl };
} else {
return null;
}
}
export default (
state: RealmState = initialState, // eslint-disable-line default-param-last
action: PerAccountApplicableAction,
): RealmState => {
switch (action.type) {
case RESET_ACCOUNT_DATA:
return initialState;
case REGISTER_COMPLETE: {
return {
...state,
//
// InitialDataCustomProfileFields
//
customProfileFields: action.data.custom_profile_fields,
//
// InitialDataRealm
//
name: action.data.realm_name,
description: action.data.realm_description,
nonActiveUsers: action.data.realm_non_active_users,
filters: action.data.realm_filters,
emoji: convertRealmEmoji(action.data.realm_emoji),
defaultExternalAccounts: new Map(
objectEntries(action.data.realm_default_external_accounts ?? {}).map(
([name, { url_pattern }]) => [name, { url_pattern }],
),
),
// TODO: On EventTypes.realm events with video_chat_provider, update
// the state or cause a re-register.
videoChatProvider: getVideoChatProvider({
availableProviders: action.data.realm_available_video_chat_providers,
jitsiServerUrl: action.data.jitsi_server_url,
providerId: action.data.realm_video_chat_provider,
}),
// Realm settings.
// These should each get updated on realm/update_dict events, below.
mandatoryTopics: action.data.realm_mandatory_topics,
messageContentDeleteLimitSeconds: action.data.realm_message_content_delete_limit_seconds,
messageContentEditLimitSeconds: action.data.realm_message_content_edit_limit_seconds,
pushNotificationsEnabled: action.data.realm_push_notifications_enabled,
pushNotificationsEnabledEndTimestamp:
action.data.realm_push_notifications_enabled_end_timestamp ?? null,
createPublicStreamPolicy:
action.data.realm_create_public_stream_policy
?? action.data.realm_create_stream_policy
// path_to_url#discussion_r883208179
?? CreatePublicOrPrivateStreamPolicy.MemberOrAbove,
createPrivateStreamPolicy:
action.data.realm_create_private_stream_policy
?? action.data.realm_create_stream_policy
// path_to_url#discussion_r883208179
?? CreatePublicOrPrivateStreamPolicy.MemberOrAbove,
webPublicStreamsEnabled: action.data.server_web_public_streams_enabled ?? false,
createWebPublicStreamPolicy:
action.data.realm_create_web_public_stream_policy ?? CreateWebPublicStreamPolicy.Nobody,
enableSpectatorAccess: action.data.realm_enable_spectator_access ?? false,
waitingPeriodThreshold: action.data.realm_waiting_period_threshold,
allowEditHistory: action.data.realm_allow_edit_history,
enableReadReceipts: action.data.realm_enable_read_receipts ?? false,
emailAddressVisibility: action.data.realm_email_address_visibility ?? null,
enableGuestUserIndicator: action.data.realm_enable_guest_user_indicator ?? true,
//
// InitialDataRealmUser
//
canCreateStreams: action.data.can_create_streams,
user_id: action.data.user_id,
email: action.data.email,
crossRealmBots: action.data.cross_realm_bots,
//
// InitialDataUserSettings
//
twentyFourHourTime:
action.data.user_settings?.twenty_four_hour_time
// Fall back to InitialDataUpdateDisplaySettings for servers that
// don't support the user_settings_object client capability.
/* $FlowIgnore[incompatible-cast]: If `user_settings` is absent,
this will be present. */
?? (action.data.twenty_four_hour_time: boolean),
// Let this be null for servers that don't support the
// user_settings_object client capability. Support begins at FL 89,
// and we currently don't need this value when the server is pre-89.
presenceEnabled: action.data.user_settings?.presence_enabled ?? null,
};
}
case REFRESH_SERVER_EMOJI_DATA:
return {
...state,
serverEmojiData: action.data,
};
// TODO on RealmUserUpdateEvent for self: update email, isAdmin, etc.
case EVENT_REALM_FILTERS:
return {
...state,
filters: action.realm_filters,
};
case EVENT_REALM_EMOJI_UPDATE:
return {
...state,
emoji: convertRealmEmoji(action.realm_emoji),
};
case EVENT_UPDATE_DISPLAY_SETTINGS:
switch (action.setting_name) {
case 'twenty_four_hour_time':
return { ...state, twentyFourHourTime: action.setting };
default:
return state;
}
case EVENT: {
const { event } = action;
switch (event.type) {
case EventTypes.custom_profile_fields:
// TODO(server): The API docs suggest that this event just
// contains new custom profile fields, but it looks like in fact
// it's the new entire list of them. See chat thread:
// path_to_url#narrow/stream/378-api-design/topic/custom.20profile.20fields/near/1382993
return { ...state, customProfileFields: event.fields };
case EventTypes.realm:
if (event.op === 'update_dict') {
const { data } = event;
const result = { ...state };
if (data.name !== undefined) {
result.name = data.name;
}
if (data.description !== undefined) {
result.description = data.description;
}
if (data.mandatory_topics !== undefined) {
result.mandatoryTopics = data.mandatory_topics;
}
if (data.message_content_delete_limit_seconds !== undefined) {
result.messageContentDeleteLimitSeconds = data.message_content_delete_limit_seconds;
}
if (data.message_content_edit_limit_seconds !== undefined) {
result.messageContentEditLimitSeconds = data.message_content_edit_limit_seconds;
}
if (data.push_notifications_enabled !== undefined) {
result.pushNotificationsEnabled = data.push_notifications_enabled;
}
if (data.push_notifications_enabled_end_timestamp !== undefined) {
result.pushNotificationsEnabledEndTimestamp =
data.push_notifications_enabled_end_timestamp;
}
if (data.create_stream_policy !== undefined) {
// TODO(server-5.0): Stop expecting create_stream_policy; simplify.
result.createPublicStreamPolicy = data.create_stream_policy;
result.createPrivateStreamPolicy = data.create_stream_policy;
}
if (data.create_public_stream_policy !== undefined) {
result.createPublicStreamPolicy = data.create_public_stream_policy;
}
if (data.create_private_stream_policy !== undefined) {
result.createPrivateStreamPolicy = data.create_private_stream_policy;
}
// no event updates result.webPublicStreamsEnabled, because it's a server setting
if (data.create_web_public_stream_policy !== undefined) {
result.createWebPublicStreamPolicy = data.create_web_public_stream_policy;
}
if (data.enable_spectator_access !== undefined) {
result.enableSpectatorAccess = data.enable_spectator_access;
}
if (data.waiting_period_threshold !== undefined) {
result.waitingPeriodThreshold = data.waiting_period_threshold;
}
if (data.allow_edit_history !== undefined) {
result.allowEditHistory = data.allow_edit_history;
}
if (data.enable_read_receipts !== undefined) {
result.enableReadReceipts = data.enable_read_receipts;
}
if (data.email_address_visibility !== undefined) {
result.emailAddressVisibility = data.email_address_visibility;
}
if (data.enable_guest_user_indicator !== undefined) {
result.enableGuestUserIndicator = data.enable_guest_user_indicator;
}
return result;
}
// (We've converted any `op: 'update'` events to
// `op: 'update_dict'` events near the edge.)
return state;
case EventTypes.user_settings:
if (event.op === 'update') {
const { property, value } = event;
switch (property) {
case 'twenty_four_hour_time': {
// $FlowFixMe[incompatible-cast] - fix UserSettingsUpdateEvent
return { ...state, twentyFourHourTime: (value: boolean) };
}
case 'presence_enabled': {
// $FlowFixMe[incompatible-cast] - fix UserSettingsUpdateEvent
return { ...state, presenceEnabled: (value: boolean) };
}
default:
return state;
}
}
return state;
default:
return state;
}
}
default:
return state;
}
};
```
|
/content/code_sandbox/src/realm/realmReducer.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 2,381
|
```javascript
/* @flow strict-local */
import deepFreeze from 'deep-freeze';
import { createStore } from 'redux';
import Immutable from 'immutable';
import type {
CrossRealmBot,
Message,
PmMessage,
StreamMessage,
PmRecipientUser,
Reaction,
Stream,
Subscription,
User,
UserGroup,
UserId,
UserStatus,
} from '../../api/modelTypes';
import { randString, randInt } from '../../utils/misc';
import { makeUserId } from '../../api/idTypes';
import type { InitialData } from '../../api/apiTypes';
import { EventTypes, type UpdateMessageEvent } from '../../api/eventTypes';
import { CreateWebPublicStreamPolicy, Role } from '../../api/permissionsTypes';
import type {
AccountSwitchAction,
LoginSuccessAction,
ResetAccountDataAction,
RegisterCompleteAction,
MessageFetchStartAction,
MessageFetchCompleteAction,
Action,
PerAccountAction,
PerAccountState,
GlobalState,
CaughtUpState,
MessagesState,
RealmState,
} from '../../reduxTypes';
import type { Auth, Account, StreamOutbox } from '../../types';
import { dubJointState } from '../../reduxTypes';
import { UploadedAvatarURL } from '../../utils/avatar';
import type { AvatarURL } from '../../utils/avatar';
import { ZulipVersion } from '../../utils/zulipVersion';
import {
ACCOUNT_SWITCH,
LOGIN_SUCCESS,
RESET_ACCOUNT_DATA,
REGISTER_COMPLETE,
EVENT_NEW_MESSAGE,
MESSAGE_FETCH_START,
MESSAGE_FETCH_COMPLETE,
EVENT_UPDATE_MESSAGE,
} from '../../actionConstants';
import rootReducer from '../../boot/reducers';
import { authOfAccount, identityOfAccount } from '../../account/accountMisc';
import { HOME_NARROW } from '../../utils/narrow';
import { type BackgroundData, getBackgroundData } from '../../webview/backgroundData';
import { getGlobalSettings } from '../../directSelectors';
import { messageMoved } from '../../api/misc';
/* ========================================================================
* Utilities
*
* Generators for primitive data types.
*/
/**
* Generate a new (nonzero) timestamp, suitable for many uninteresting purposes.
*
* Counts up approximately forever in increments of 1000.
*/
const makeTime: () => number = (() => {
const startTime = 10 ** 13; // 2286-11-20
let calls = 0;
return () => startTime + 1000 * ++calls;
})();
/**
* Return a factory for unique integers 0 <= N < end.
*
* The factory will throw if it ever runs out of integers in its set. Both
* initialization and use should be O(1).
*/
const makeUniqueRandInt = (itemsType: string, end: number, start: number = 0): (() => number) => {
// Sparse array. Pretends to be initialized to iota.
const deck = new Array(end);
return () => {
if (deck.length === start) {
throw new Error(`ran out of ${itemsType}`);
}
// Perform a single step of the Fisher-Yates shuffle...
const leftIndex = randInt(deck.length, start);
const rightIndex = deck.length - 1;
const leftValue = deck[leftIndex] ?? leftIndex;
const rightValue = deck[rightIndex] ?? rightIndex;
deck[leftIndex] = rightValue;
/* deck[rightIndex] = leftValue; */
// ... but, instead of storing the new final value, "pop" it off the end and
// return it.
--deck.length;
return leftValue;
};
};
const intRange = (start, len) => Array.from({ length: len }, (k, i) => i + start);
/** A string with diverse characters to exercise encoding/decoding bugs. */
/* eslint-disable prefer-template */
export const diverseCharacters: string =
// The whole range of lowest code points, including control codes
// and ASCII punctuation like `"` and `&` used in various syntax...
String.fromCharCode(...intRange(0, 0x100))
// ... some characters from other scripts...
+ ''
// ... some unpaired surrogates, which JS strings can have...
+ String.fromCharCode(...intRange(0xdbf0, 0x20))
// ... some characters beyond the BMP ( U+10000)...
+ ''
// ... and some code points at the very end of the Unicode range.
+ String.fromCodePoint(...intRange(0x10fff0, 0x10));
/* ========================================================================
* Users and bots
*/
type UserOrBotPropertiesArgs = {|
user_id?: number, // accept a plain number, for convenience in tests
email?: string,
full_name?: string,
avatar_url?: AvatarURL,
role?: Role,
|};
/**
* An avatar URL, containing the given tag to make it recognizable in debugging.
*
* Beware! This value may not be representative.
*/
const makeAvatarUrl = (tag: string) =>
// Internally the UploadedAvatarURL mutates itself for memoization.
// That conflicts with the deepFreeze we do for tests; so construct it
// here with a full-blown URL object in the first place to prevent that.
new UploadedAvatarURL(new URL(`path_to_url{tag}.png`));
// Why start at 11? To reserve IDs 1 through 10 for use as constants in
// snapshot tests.
const randUserId: () => UserId = (
mk => () =>
makeUserId(mk())
)(makeUniqueRandInt('user IDs', 10000, 11));
const userOrBotProperties = (args: UserOrBotPropertiesArgs) => {
const user_id = args.user_id != null ? makeUserId(args.user_id) : randUserId();
const randName = randString();
return deepFreeze({
avatar_url: args.avatar_url ?? makeAvatarUrl(user_id.toString()),
avatar_version: 0,
date_joined: `2014-04-${(randInt(30) + 1).toString().padStart(2, '0')}`,
email: args.email ?? `${randName}@example.org`,
full_name: args.full_name ?? `${randName} User`,
role: args.role ?? Role.Member,
timezone: 'UTC',
user_id,
});
};
/** Beware! These values may not be representative. */
export const makeUser = (args: UserOrBotPropertiesArgs = Object.freeze({})): User =>
deepFreeze({
...userOrBotProperties(args),
is_bot: false,
bot_type: null,
// bot_owner omitted
profile_data: {},
});
/** Beware! These values may not be representative. */
export const makeCrossRealmBot = (
args: UserOrBotPropertiesArgs = Object.freeze({}),
): CrossRealmBot =>
deepFreeze({
...userOrBotProperties(args),
is_bot: true,
bot_type: 1,
});
export const userStatusEmojiUnicode: UserStatus['status_emoji'] = deepFreeze({
reaction_type: 'unicode_emoji',
emoji_code: '1f44d',
emoji_name: 'thumbs_up',
});
export const userStatusEmojiZulipExtra: UserStatus['status_emoji'] = deepFreeze({
reaction_type: 'zulip_extra_emoji',
emoji_code: 'zulip',
emoji_name: 'zulip',
});
export const userStatusEmojiRealm: UserStatus['status_emoji'] = deepFreeze({
reaction_type: 'realm_emoji',
emoji_code: '80',
emoji_name: 'github_parrot',
});
export const realm: URL = new URL('path_to_url
/** These may be raised but should not be lowered. */
export const recentZulipVersion: ZulipVersion = new ZulipVersion('8.0-dev-2894-g86100cdb4e');
export const recentZulipFeatureLevel = 226;
export const makeAccount = (
args: {|
user?: User,
email?: string,
realm?: URL,
apiKey?: string,
userId?: UserId | null,
zulipFeatureLevel?: number | null,
zulipVersion?: ZulipVersion | null,
ackedPushToken?: string | null,
lastDismissedServerPushSetupNotice?: Date | null,
lastDismissedServerNotifsExpiringBanner?: Date | null,
|} = Object.freeze({}),
): Account => {
const {
user = makeUser(),
userId = user.user_id,
email = user.email,
realm: realmInner = realm,
apiKey = randString() + randString(),
zulipFeatureLevel: zulipFeatureLevelInner = recentZulipFeatureLevel,
zulipVersion: zulipVersionInner = recentZulipVersion,
ackedPushToken = null,
lastDismissedServerPushSetupNotice = null,
lastDismissedServerNotifsExpiringBanner = null,
} = args;
return deepFreeze({
realm: realmInner,
userId,
email,
apiKey,
zulipFeatureLevel: zulipFeatureLevelInner,
zulipVersion: zulipVersionInner,
ackedPushToken,
lastDismissedServerPushSetupNotice,
lastDismissedServerNotifsExpiringBanner,
silenceServerPushSetupWarnings: false,
});
};
const randUserGroupId: () => number = makeUniqueRandInt('user group IDs', 10000);
export const makeUserGroup = (extra?: $Rest<UserGroup, { ... }>): UserGroup => {
const baseUserGroup = {
description: 'My favorite group',
id: randUserGroupId(),
members: [randUserId(), randUserId(), randUserId()],
name: 'Mobile app enthusiasts',
};
return deepFreeze({ ...baseUserGroup, ...extra });
};
export const selfUser: User = makeUser({
full_name: 'Self User',
email: 'self@example.org',
avatar_url: makeAvatarUrl('self'),
});
export const selfAccount: Account = makeAccount({ user: selfUser, realm });
export const selfAuth: Auth = deepFreeze(authOfAccount(selfAccount));
export const otherUser: User = makeUser({
full_name: 'Other User',
email: 'other@example.org',
avatar_url: makeAvatarUrl('other'),
});
export const thirdUser: User = makeUser({
full_name: 'Third User',
email: 'third@example.org',
avatar_url: makeAvatarUrl('third'),
});
export const crossRealmBot: CrossRealmBot = makeCrossRealmBot({
full_name: 'Bot User',
email: 'bot@example.org',
avatar_url: makeAvatarUrl('bot'),
});
/* ========================================================================
* Streams and subscriptions
*/
// Why start at 11? To reserve IDs 1 through 10 for use as constants in
// snapshot tests.
const randStreamId: () => number = makeUniqueRandInt('stream IDs', 1000, 11);
export const makeStream = (
args: {|
stream_id?: number,
name?: string,
description?: string,
invite_only?: boolean,
is_web_public?: boolean,
history_public_to_subscribers?: boolean,
|} = Object.freeze({}),
): Stream => {
const name = args.name ?? randString();
return deepFreeze({
stream_id: args.stream_id ?? randStreamId(),
name,
description: args.description ?? `On the ${randString()} of ${name}`,
rendered_description: args.description ?? `<p>On the ${randString()} of ${name}</p>`,
invite_only: args.invite_only ?? false,
is_announcement_only: false,
is_web_public: args.is_web_public ?? false,
history_public_to_subscribers: args.history_public_to_subscribers ?? true,
first_message_id: null,
});
};
export const stream: Stream = makeStream({
name: 'a stream',
description: 'An example stream.',
});
export const otherStream: Stream = makeStream({
name: 'another stream',
description: 'Another example stream.',
});
/** A subscription, by default to eg.stream. */
export const makeSubscription = (
args: {|
stream?: Stream,
in_home_view?: boolean,
pin_to_top?: boolean,
push_notifications?: boolean,
color?: string,
|} = Object.freeze({}),
): Subscription => {
const { stream: streamInner = stream } = args;
return deepFreeze({
...streamInner,
color: args.color ?? '#123456',
in_home_view: args.in_home_view ?? true,
pin_to_top: args.pin_to_top ?? false,
audible_notifications: false,
desktop_notifications: false,
email_address: '??? make this value representative before using in a test :)',
is_old_stream: true,
push_notifications: args.push_notifications ?? null,
stream_weekly_traffic: 84,
});
};
/** A subscription to eg.stream. */
export const subscription: Subscription = makeSubscription();
/** A subscription to eg.otherStream. */
export const otherSubscription: Subscription = makeSubscription({ stream: otherStream });
/* ========================================================================
* Messages
*/
export const unicodeEmojiReaction: Reaction = deepFreeze({
user_id: randUserId(),
reaction_type: 'unicode_emoji',
emoji_code: '1f44d',
emoji_name: 'thumbs_up',
});
export const zulipExtraEmojiReaction: Reaction = deepFreeze({
user_id: randUserId(),
reaction_type: 'zulip_extra_emoji',
emoji_code: 'zulip',
emoji_name: 'zulip',
});
export const realmEmojiReaction: Reaction = deepFreeze({
user_id: randUserId(),
reaction_type: 'realm_emoji',
emoji_code: '80',
emoji_name: 'github_parrot',
});
export const displayRecipientFromUser = (user: User): PmRecipientUser => {
const { email, full_name, user_id: id } = user;
return deepFreeze({
email,
full_name,
id,
is_mirror_dummy: false,
short_name: '', // what is this, anyway?
});
};
/** Boring properties common to all example Message objects. */
const messagePropertiesBase = deepFreeze({
isOutbox: false,
// match_content omitted
// match_subject omitted
// flags omitted
edit_history: [],
is_me_message: false,
// last_edit_timestamp omitted
reactions: [],
submessages: [],
});
const messagePropertiesFromSender = (user: User) => {
const { user_id: sender_id, email: sender_email, full_name: sender_full_name } = user;
return deepFreeze({
avatar_url: user.avatar_url,
client: 'ExampleClient',
sender_email,
sender_full_name,
sender_id,
sender_realm_str: 'zulip',
});
};
// Why start at 11? To reserve IDs 1 through 10 for use as constants in
// snapshot tests.
const randMessageId: () => number = makeUniqueRandInt('message ID', 10000000, 11);
/**
* A PM, by default a 1:1 from eg.otherUser to eg.selfUser.
*
* Beware! These values may not be representative.
*
* NB that the resulting value has no `flags` property. This matches what
* we expect in `state.messages`, but not some other contexts; see comment
* on the `flags` property of `Message`. For use in an `EVENT_NEW_MESSAGE`
* action, pass to `mkActionEventNewMessage`.
*/
export const pmMessage = (args?: {|
...$Rest<PmMessage, { ... }>,
sender?: User,
recipients?: $ReadOnlyArray<User>,
sender_id?: number, // accept a plain number, for convenience in tests
|}): PmMessage => {
// The `Object.freeze` is to work around a Flow issue:
// path_to_url#issuecomment-695064325
const {
sender_id = undefined,
sender = sender_id != null ? makeUser({ user_id: sender_id }) : otherUser,
recipients = [otherUser, selfUser],
...extra
} = args ?? Object.freeze({});
const baseMessage: PmMessage = {
...messagePropertiesBase,
...messagePropertiesFromSender(sender),
content: '<p>This is an example PM message.</p>',
content_type: 'text/html',
// We don't sort the recipients, because they're inconsistently sorted
// in real messages. (See comments on the Message type.)
display_recipient: recipients.map(displayRecipientFromUser),
id: randMessageId(),
subject: '',
timestamp: 1556579160,
type: 'private',
};
return deepFreeze({
...baseMessage,
...extra,
});
};
export const pmMessageFromTo = (
from: User,
to: $ReadOnlyArray<User>,
extra?: $Rest<PmMessage, { ... }>,
): PmMessage => pmMessage({ sender: from, recipients: [from, ...to], ...extra });
const messagePropertiesFromStream = (stream1: Stream) => {
const { stream_id, name: display_recipient } = stream1;
return deepFreeze({
display_recipient,
stream_id,
});
};
/**
* A stream message, by default in eg.stream sent by eg.otherUser.
*
* Beware! These values may not be representative.
*
* NB that the resulting value has no `flags` property. This matches what
* we expect in `state.messages`, but not some other contexts; see comment
* on the `flags` property of `Message`. For use in an `EVENT_NEW_MESSAGE`
* action, pass to `mkActionEventNewMessage`.
*/
export const streamMessage = (args?: {|
...$Rest<StreamMessage, { ... }>,
stream?: Stream,
sender?: User,
|}): StreamMessage => {
// The `Object.freeze` is to work around a Flow issue:
// path_to_url#issuecomment-695064325
const { stream: streamInner = stream, sender = otherUser, ...extra } = args ?? Object.freeze({});
const baseMessage: StreamMessage = {
...messagePropertiesBase,
...messagePropertiesFromSender(sender),
...messagePropertiesFromStream(streamInner),
content: '<p>This is an example stream message.</p>',
content_type: 'text/html',
id: randMessageId(),
subject: 'example topic',
topic_links: ([]: {| text: string, url: string |}[]),
timestamp: 1556579727,
type: 'stream',
};
return deepFreeze({ ...baseMessage, ...extra });
};
/** Construct a MessagesState from a list of messages. */
export const makeMessagesState = (messages: $ReadOnlyArray<Message>): MessagesState =>
Immutable.Map(messages.map(m => [m.id, m]));
/* ========================================================================
* Outbox messages
*
* (Only stream messages for now. Feel free to add PMs, if you need them.)
*/
/**
* Boring properties common across example outbox messages.
*/
const outboxMessageBase = deepFreeze({
isOutbox: true,
isSent: false,
avatar_url: selfUser.avatar_url,
content: '<p>Test.</p>',
markdownContent: 'Test.',
reactions: [],
sender_email: selfUser.email,
sender_full_name: selfUser.full_name,
sender_id: selfUser.user_id,
});
/**
* Create a stream outbox message from an interesting subset of its
* data.
*
* `.id` is always identical to `.timestamp` and should not be supplied.
*/
export const streamOutbox = (data: $Rest<StreamOutbox, { id: mixed, ... }>): StreamOutbox => {
const { timestamp } = data;
const outputTimestamp = timestamp ?? makeTime() / 1000;
return deepFreeze({
...outboxMessageBase,
type: 'stream',
display_recipient: stream.name,
stream_id: stream.stream_id,
subject: 'test topic',
...data,
id: outputTimestamp,
timestamp: outputTimestamp,
});
};
/* ========================================================================
* Redux state
*/
const privateReduxStore = createStore(rootReducer);
/**
* The global Redux state, at its initial value.
*
* See `plusReduxState` for a version of the state that incorporates
* `selfUser` and other standard example data.
*/
// TODO(#5006): Split this (and its friends below) into global and
// per-account versions. (This may be easiest to do after actually
// migrating settings and session to split them per-account vs global, so
// that the global and per-account states have disjoint sets of
// properties.)
// For now, the intersection type (with `&`) says this value can be used as
// either kind of state.
export const baseReduxState: GlobalState & PerAccountState = dubJointState(
deepFreeze(privateReduxStore.getState()),
);
/**
* A global Redux state, with `baseReduxState` plus the given data.
*
* See `reduxStatePlus` for a version that automatically includes `selfUser`
* and other standard example data.
*/
export const reduxState = (extra?: $Rest<GlobalState, { ... }>): GlobalState & PerAccountState =>
dubJointState(
deepFreeze({
...(baseReduxState: GlobalState),
...extra,
}),
);
/**
* The global Redux state, reflecting standard example data like `selfUser`.
*
* This approximates what the state might look like at a time when the app
* is showing its main UI: so when the user has logged into some account and
* we have our usual server data for it.
*
* In particular:
* * The self-user is `selfUser`.
* * Users `otherUser` and `thirdUser` also exist.
* * The stream `stream` exists, with subscription `subscription`.
*
* More generally, each object in the Zulip app model -- a user, a stream,
* etc. -- that this module exports as a constant value (rather than only as
* a function to make a value) will typically appear here.
*
* That set will grow over time, so a test should never rely on
* `plusReduxState` containing only the things it currently contains. For
* example, it should not assume there are only three users, even if that
* happens to be true now. If the test needs a user (or stream, etc.) that
* isn't in this state, it should create the user privately for itself, with
* a helper like `makeUser`.
*
* On the other hand, a test *can* rely on an item being here if it
* currently is here. So for example a test which uses `plusReduxState` can
* assume it contains `otherUser`; it need not, and should not bother to,
* add `otherUser` to the state.
*
* See `baseReduxState` for a minimal version of the state.
*/
export const plusReduxState: GlobalState & PerAccountState = reduxState({
accounts: [
{
...selfAuth,
userId: selfUser.user_id,
ackedPushToken: null,
zulipVersion: recentZulipVersion,
zulipFeatureLevel: recentZulipFeatureLevel,
lastDismissedServerPushSetupNotice: null,
lastDismissedServerNotifsExpiringBanner: null,
silenceServerPushSetupWarnings: false,
},
],
realm: {
...baseReduxState.realm,
user_id: selfUser.user_id,
email: selfUser.email,
crossRealmBots: [crossRealmBot],
emoji: {
[realmEmojiReaction.emoji_code]: {
deactivated: false,
code: realmEmojiReaction.emoji_code,
name: realmEmojiReaction.emoji_name,
source_url: `/user_avatars/2/emoji/images/${realmEmojiReaction.emoji_code}.gif`,
},
},
},
users: [selfUser, otherUser, thirdUser],
streams: [stream, otherStream],
subscriptions: [subscription, otherSubscription],
});
/**
* A global Redux state, adding the given data to `plusReduxState`.
*
* This automatically includes standard example data like `selfUser` and
* `otherUser`, so that there's no need to add those explicitly. See
* `plusReduxState` for details on what's included.
*
* See `reduxState` for a version starting from a minimal state.
*/
export const reduxStatePlus = (
extra?: $Rest<GlobalState, { ... }>,
): GlobalState & PerAccountState =>
dubJointState(deepFreeze({ ...(plusReduxState: GlobalState), ...extra }));
export const realmState = (extra?: $Rest<RealmState, { ... }>): RealmState =>
deepFreeze({
...baseReduxState.realm,
...extra,
});
/* ========================================================================
* Actions
*
* Complete actions which need no further data.
*/
export const action = Object.freeze({
account_switch: (deepFreeze({
type: ACCOUNT_SWITCH,
identity: identityOfAccount(makeAccount()),
}): AccountSwitchAction),
login_success: (deepFreeze({
type: LOGIN_SUCCESS,
realm: selfAccount.realm,
email: selfAccount.email,
apiKey: selfAccount.apiKey,
}): LoginSuccessAction),
reset_account_data: (deepFreeze({ type: RESET_ACCOUNT_DATA }): ResetAccountDataAction),
/**
* A minimal well-typed REGISTER_COMPLETE action from a recent server.
*
* Beware! The data here may not be representative. Generally each test
* should specify the particular properties that it cares about.
*
* See also `eg.mkActionRegisterComplete`, for combining this data with
* test-specific other data.
*/
register_complete: (deepFreeze({
type: REGISTER_COMPLETE,
data: {
// InitialDataBase
last_event_id: 34,
msg: '',
queue_id: '1',
zulip_feature_level: recentZulipFeatureLevel,
zulip_version: recentZulipVersion,
// InitialDataAlertWords
alert_words: [],
// InitialDataCustomProfileFields
custom_profile_fields: [],
// InitialDataMessage
max_message_id: 100,
// InitialDataMutedUsers
muted_users: [],
// InitialDataPresence
presences: {},
// InitialDataRealm
development_environment: false,
event_queue_longpoll_timeout_seconds: 600,
// jitsi_server_url omitted
max_avatar_file_size_mib: 3,
max_file_upload_size_mib: 3,
max_icon_file_size_mib: 3,
max_logo_file_size_mib: 3,
max_message_length: 10000,
max_stream_description_length: 500,
max_stream_name_length: 100,
max_topic_length: 50,
password_min_length: 8,
password_min_guesses: 3,
realm_add_custom_emoji_policy: 3,
realm_allow_edit_history: true,
realm_allow_message_editing: true,
realm_authentication_methods: { GitHub: true, Email: true, Google: true },
realm_available_video_chat_providers: {},
realm_avatar_changes_disabled: false,
realm_bot_creation_policy: 3,
realm_bot_domain: 'example.com',
realm_create_private_stream_policy: 3,
realm_create_public_stream_policy: 3,
realm_create_web_public_stream_policy: CreateWebPublicStreamPolicy.ModeratorOrAbove,
realm_default_code_block_language: 'python',
realm_default_external_accounts: {
github: {
name: 'GitHub',
text: 'GitHub',
hint: 'Enter your GitHub username',
url_pattern: 'path_to_url
},
},
realm_default_language: 'en',
realm_delete_own_message_policy: 3,
realm_description: 'description',
realm_digest_emails_enabled: true,
realm_digest_weekday: 2,
realm_disallow_disposable_email_addresses: true,
realm_edit_topic_policy: 3,
realm_email_auth_enabled: true,
realm_email_changes_disabled: true,
realm_emails_restricted_to_domains: false,
realm_enable_read_receipts: false,
realm_enable_spectator_access: true,
realm_giphy_rating: 3,
realm_icon_source: 'U',
realm_icon_url: 'example.com/some/path',
realm_inline_image_preview: true,
realm_inline_url_embed_preview: true,
realm_invite_required: true,
realm_invite_to_realm_policy: 3,
realm_invite_to_stream_policy: 3,
realm_is_zephyr_mirror_realm: true,
realm_logo_source: 'D',
realm_logo_url: '',
realm_mandatory_topics: true,
realm_message_content_allowed_in_email_notifications: true,
realm_message_content_delete_limit_seconds: 3,
realm_message_content_edit_limit_seconds: 3,
realm_message_retention_days: 3,
realm_move_messages_between_streams_policy: 3,
realm_name: 'Test',
realm_name_changes_disabled: true,
realm_night_logo_source: 'D',
realm_night_logo_url: '',
realm_notifications_stream_id: 3,
realm_org_type: 0,
realm_password_auth_enabled: true,
realm_plan_type: 3,
realm_presence_disabled: true,
realm_private_message_policy: 3,
realm_push_notifications_enabled: true,
realm_push_notifications_enabled_end_timestamp: 1704926069,
realm_send_welcome_emails: true,
realm_signup_notifications_stream_id: 3,
realm_upload_quota_mib: 10,
realm_user_group_edit_policy: 3,
realm_uri: selfAccount.realm.toString(),
realm_video_chat_provider: 1,
realm_waiting_period_threshold: 3,
realm_want_advertise_in_communities_directory: false,
realm_wildcard_mention_policy: 3,
server_avatar_changes_disabled: false,
server_emoji_data_url: new URL(
'/static/generated/emoji/emoji_api.7820ba9750aa.json',
selfAccount.realm,
).toString(),
server_generation: 3,
server_inline_image_preview: true,
server_inline_url_embed_preview: true,
server_name_changes_disabled: false,
server_needs_upgrade: false,
server_web_public_streams_enabled: true,
settings_send_digest_emails: true,
upgrade_text_for_wide_organization_logo: '',
zulip_plan_is_not_limited: false,
// InitialDataRealmEmoji
realm_emoji: {},
// InitialDataRealmFilters
realm_filters: [],
// InitialDataRealmUser
realm_users: [],
realm_non_active_users: [],
avatar_source: 'G',
avatar_url_medium: 'url',
avatar_url: null, // ideally would agree with selfUser.avatar_url
can_create_streams: false, // new servers don't send, but we fill in
can_create_public_streams: false,
can_create_private_streams: false,
can_create_web_public_streams: false,
can_subscribe_other_users: false,
can_invite_others_to_realm: false,
is_admin: false,
is_owner: false,
is_billing_admin: selfUser.is_billing_admin,
is_moderator: false,
is_guest: false,
user_id: selfUser.user_id,
email: selfAccount.email, // aka selfUser.email
delivery_email: selfUser.email,
full_name: selfUser.full_name,
cross_realm_bots: [],
// InitialDataRealmUserGroups
realm_user_groups: [],
// InitialDataRecentPmConversations
recent_private_conversations: [],
// InitialDataStream
streams: [],
// InitialDataSubscription
never_subscribed: [],
subscriptions: [],
unsubscribed: [],
// InitialDataUpdateMessageFlags
unread_msgs: {
streams: [],
huddles: [],
pms: [],
mentions: [],
count: 0,
},
// InitialDataUserSettings
user_settings: {
twenty_four_hour_time: true,
dense_mode: true,
starred_message_counts: true,
fluid_layout_width: false,
high_contrast_mode: false,
color_scheme: 3,
translate_emoticons: true,
display_emoji_reaction_users: true,
default_language: 'en',
default_view: 'recent_topics',
escape_navigates_to_default_view: true,
left_side_userlist: false,
emojiset: 'google',
demote_inactive_streams: 2,
user_list_style: 1,
timezone: selfUser.timezone ?? 'UTC',
enter_sends: false,
enable_drafts_synchronization: true,
enable_stream_desktop_notifications: false,
enable_stream_email_notifications: false,
enable_stream_push_notifications: false,
enable_stream_audible_notifications: false,
notification_sound: 'zulip',
enable_desktop_notifications: true,
enable_sounds: true,
email_notifications_batching_period_seconds: 120,
enable_offline_email_notifications: true,
enable_offline_push_notifications: true,
enable_online_push_notifications: true,
enable_digest_emails: true,
enable_marketing_emails: true,
enable_login_emails: false,
message_content_in_email_notifications: true,
pm_content_in_desktop_notifications: true,
wildcard_mentions_notify: true,
desktop_icon_count_display: 1,
realm_name_in_notifications: false,
presence_enabled: true,
available_notification_sounds: ['zulip'],
emojiset_choices: [{ key: 'google', text: 'Google modern' }],
send_private_typing_notifications: true,
send_stream_typing_notifications: true,
send_read_receipts: true,
},
// InitialDataUserStatus
user_status: {},
// InitialDataUserTopic
user_topics: [],
},
}): RegisterCompleteAction),
message_fetch_start: (deepFreeze({
type: MESSAGE_FETCH_START,
narrow: HOME_NARROW,
numBefore: 0,
numAfter: 20,
}): MessageFetchStartAction),
message_fetch_complete: (deepFreeze({
type: MESSAGE_FETCH_COMPLETE,
messages: [],
narrow: HOME_NARROW,
anchor: 0,
numBefore: 50,
numAfter: 50,
foundNewest: false,
foundOldest: false,
ownUserId: selfUser.user_id,
}): MessageFetchCompleteAction),
// If a given action is only relevant to a single test file, no need to
// provide a generic example of it here; just define it there.
});
// Ensure every `eg.action.foo` is some well-typed action.
(action: {| [string]: Action |});
/* ========================================================================
* Action factories
*
* Useful for action types where a static object of boilerplate data doesn't
* suffice. Generally this is true where (a) there's some boilerplate data
* that's useful to supply here, but (b) there's some other places where a
* given test will almost always need to fill in specific data of its own.
*
* For action types without (b), a static example value `eg.action.foo` is
* enough. For action types without (a), even that isn't necessary, because
* each test might as well define the action values it needs directly.
*/
/**
* A REGISTER_COMPLETE action.
*
* The result will be based on `eg.action.register_complete`, but with the
* additional data given in the argument.
*/
export const mkActionRegisterComplete = (extra: {|
...$Rest<InitialData, { ... }>,
unread_msgs?: $Rest<InitialData['unread_msgs'], { ... }>,
|}): PerAccountAction => {
const { unread_msgs, ...rest } = extra;
return deepFreeze({
...action.register_complete,
data: {
...action.register_complete.data,
...rest,
unread_msgs: {
...action.register_complete.data.unread_msgs,
...unread_msgs,
},
},
});
};
/**
* An EVENT_NEW_MESSAGE action.
*
* The message argument can either have or omit a `flags` property; if
* omitted, it defaults to empty. (The `message` property on an
* `EVENT_NEW_MESSAGE` action must have `flags`, while `Message` objects in
* some other contexts must not. See comments on `Message` for details.)
*/
export const mkActionEventNewMessage = (
message: Message,
args?: {| caughtUp?: CaughtUpState, local_message_id?: number, ownUserId?: UserId |},
): PerAccountAction =>
deepFreeze({
type: EVENT_NEW_MESSAGE,
id: 1001,
caughtUp: {},
ownUserId: selfUser.user_id,
...args,
message: { ...message, flags: message.flags ?? [] },
});
/**
* An EVENT_UPDATE_MESSAGE action.
*/
export const mkActionEventUpdateMessage = (args: {|
...$Rest<UpdateMessageEvent, { id: mixed, type: mixed, flags?: mixed }>,
|}): PerAccountAction => {
const event = {
id: 1,
type: EventTypes.update_message,
flags: [],
...args,
};
return {
type: EVENT_UPDATE_MESSAGE,
event,
move: messageMoved(event),
};
};
// If a given action is only relevant to a single test file, no need to
// provide a generic factory for it here; just define the test data there.
/* ========================================================================
* Miscellaneous
*/
/**
* A BackgroundData value corresponding mostly to baseReduxState.
*
* Includes a few elements of plusReduxState, where necessary for
* constructing a valid BackgroundData.
*/
export const baseBackgroundData: BackgroundData = deepFreeze(
getBackgroundData(
reduxState({
accounts: plusReduxState.accounts,
realm: { ...baseReduxState.realm, user_id: plusReduxState.realm.user_id },
users: [selfUser],
}),
getGlobalSettings(baseReduxState),
),
);
/** A BackgroundData value corresponding to plusReduxState. */
export const plusBackgroundData: BackgroundData = deepFreeze(
getBackgroundData(plusReduxState, getGlobalSettings(plusReduxState)),
);
```
|
/content/code_sandbox/src/__tests__/lib/exampleData.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 8,297
|
```javascript
/* @flow strict-local */
import deepFreeze from 'deep-freeze';
import type { RealmState } from '../../types';
import realmReducer from '../realmReducer';
import {
EVENT_REALM_EMOJI_UPDATE,
EVENT_UPDATE_DISPLAY_SETTINGS,
EVENT_REALM_FILTERS,
EVENT,
} from '../../actionConstants';
import type { UserSettings } from '../../api/modelTypes';
import type { RealmDataForUpdate } from '../../api/realmDataTypes';
import {
CreatePublicOrPrivateStreamPolicy,
CreateWebPublicStreamPolicy,
EmailAddressVisibility,
} from '../../api/permissionsTypes';
import { CustomProfileFieldType } from '../../api/modelTypes';
import { EventTypes } from '../../api/eventTypes';
import * as eg from '../../__tests__/lib/exampleData';
const labelFromValue = value =>
/* $FlowFixMe[incompatible-use] - CreateWebPublicStreamPolicy is a
Flow enum. Values are numbers, so they do have .toStringbut
Flow reasonably hides that detail from consumers. For
CreateWebPublicStreamPolicy, it would actually be better to use
CreateWebPublicStreamPolicy.getName(initialStateValue), if we
find a nice way to write that with type checking. */
value?.toString() ?? '[nullish]';
describe('realmReducer', () => {
describe('REGISTER_COMPLETE', () => {
test('updates as appropriate on a boring but representative REGISTER_COMPLETE', () => {
const action = eg.action.register_complete;
expect(realmReducer(eg.baseReduxState.realm, action)).toEqual({
//
// InitialDataCustomProfileFields
//
customProfileFields: action.data.custom_profile_fields,
//
// InitialDataRealm
//
name: action.data.realm_name,
description: action.data.realm_description,
nonActiveUsers: action.data.realm_non_active_users,
filters: action.data.realm_filters,
emoji: {}, // update as necessary if example data changes
defaultExternalAccounts: new Map([
[
'github',
{ url_pattern: action.data.realm_default_external_accounts?.github.url_pattern },
],
]),
videoChatProvider: null, // update as necessary if example data changes
mandatoryTopics: action.data.realm_mandatory_topics,
messageContentDeleteLimitSeconds: action.data.realm_message_content_delete_limit_seconds,
messageContentEditLimitSeconds: action.data.realm_message_content_edit_limit_seconds,
pushNotificationsEnabled: action.data.realm_push_notifications_enabled,
pushNotificationsEnabledEndTimestamp:
action.data.realm_push_notifications_enabled_end_timestamp,
webPublicStreamsEnabled: action.data.server_web_public_streams_enabled,
createPublicStreamPolicy: action.data.realm_create_public_stream_policy,
createPrivateStreamPolicy: action.data.realm_create_private_stream_policy,
createWebPublicStreamPolicy: action.data.realm_create_web_public_stream_policy,
enableSpectatorAccess: action.data.realm_enable_spectator_access,
waitingPeriodThreshold: action.data.realm_waiting_period_threshold,
allowEditHistory: action.data.realm_allow_edit_history,
enableReadReceipts: action.data.realm_enable_read_receipts,
emailAddressVisibility: null,
enableGuestUserIndicator: true,
//
// InitialDataRealmUser
//
canCreateStreams: action.data.can_create_streams,
user_id: action.data.user_id,
email: action.data.email,
crossRealmBots: action.data.cross_realm_bots,
//
// InitialDataUserSettings
//
/* $FlowIgnore[incompatible-use] - testing modern servers, which
send user_settings. */
twentyFourHourTime: action.data.user_settings.twenty_four_hour_time,
// $FlowIgnore[incompatible-use] - see above
presenceEnabled: action.data.user_settings.presence_enabled,
//
// Misc.: Not in the /register response. (These should be unchanged.)
//
serverEmojiData: eg.baseReduxState.realm.serverEmojiData,
});
});
});
describe('RESET_ACCOUNT_DATA', () => {
test('resets state', () => {
const initialState = eg.plusReduxState.realm;
const expectedState = eg.baseReduxState.realm;
const actualState = realmReducer(initialState, eg.action.reset_account_data);
expect(actualState).toEqual(expectedState);
});
});
describe('EVENT_UPDATE_DISPLAY_SETTINGS', () => {
test('change the display settings', () => {
const initialState = eg.reduxStatePlus({
realm: {
...eg.plusReduxState.realm,
twentyFourHourTime: false,
emoji: {
customEmoji1: {
code: 'customEmoji1',
deactivated: false,
name: 'Custom Emoji 1',
source_url: 'path_to_url
},
},
},
}).realm;
const action = deepFreeze({
type: EVENT_UPDATE_DISPLAY_SETTINGS,
id: 1,
setting: true,
setting_name: 'twenty_four_hour_time',
});
const expectedState = {
...initialState,
twentyFourHourTime: true,
};
const actualState = realmReducer(initialState, action);
expect(actualState).toEqual(expectedState);
});
});
describe('EVENT_REALM_EMOJI_UPDATE', () => {
test('update state to new realm_emoji', () => {
const initialState = eg.reduxStatePlus({
realm: {
...eg.plusReduxState.realm,
twentyFourHourTime: false,
emoji: {},
filters: [],
},
}).realm;
const action = deepFreeze({
id: 4,
realm_emoji: {
customEmoji1: {
code: 'customEmoji1',
deactivated: false,
name: 'Custom Emoji 1',
source_url: 'path_to_url
},
customEmoji2: {
code: 'customEmoji2',
deactivated: false,
name: 'Custom Emoji 2',
source_url: 'path_to_url
},
},
type: EVENT_REALM_EMOJI_UPDATE,
});
const expectedState = {
...initialState,
emoji: {
customEmoji1: {
code: 'customEmoji1',
deactivated: false,
name: 'Custom Emoji 1',
source_url: 'path_to_url
},
customEmoji2: {
code: 'customEmoji2',
deactivated: false,
name: 'Custom Emoji 2',
source_url: 'path_to_url
},
},
};
const newState = realmReducer(initialState, action);
expect(newState).toEqual(expectedState);
});
});
describe('EVENT_REALM_FILTERS', () => {
test('update state to new realm_filter', () => {
const initialState = eg.reduxStatePlus({
realm: {
...eg.plusReduxState.realm,
twentyFourHourTime: false,
emoji: {},
filters: [],
},
}).realm;
const action = deepFreeze({
id: 4,
realm_filters: [['#(?P<id>[0-9]+)', 'path_to_url 2]],
type: EVENT_REALM_FILTERS,
});
const expectedState = {
...initialState,
filters: [['#(?P<id>[0-9]+)', 'path_to_url 2]],
};
const newState = realmReducer(initialState, action);
expect(newState).toEqual(expectedState);
});
});
describe('EVENT', () => {
/**
* The part of RealmState that we expect to test EVENT actions on.
*/
type EventUpdatableRealmState = $Rest<
RealmState,
{|
serverEmojiData: mixed,
// Incomplete; add others as needed to satisfy Flow.
|},
>;
describe('type `custom_profile_fields`', () => {
const mkState = fields =>
deepFreeze({ ...eg.plusReduxState.realm, customProfileFields: fields });
const mkAction = fields =>
deepFreeze({
type: EVENT,
event: { id: 0, type: EventTypes.custom_profile_fields, fields },
});
const mkField = props => ({
type: CustomProfileFieldType.ShortText,
hint: '',
field_data: '',
...props,
});
test('add from none', () => {
const field = mkField({ id: 0, order: 0, name: 'thing' });
expect(realmReducer(mkState([]), mkAction([field]))).toEqual(mkState([field]));
});
test('remove all', () => {
const field = mkField({ id: 0, order: 0, name: 'thing' });
expect(realmReducer(mkState([field]), mkAction([]))).toEqual(mkState([]));
});
test('update, delete, remove', () => {
const field0 = mkField({ id: 12, order: 0, name: 'thing' });
const field1 = mkField({ id: 3, order: 1, name: 'other thing' });
const field2 = mkField({ id: 42, order: 0, name: 'new thing' });
const field0a = mkField({ id: field0.id, order: 1, name: 'thing again' });
expect(realmReducer(mkState([field0, field1]), mkAction([field2, field0a]))).toEqual(
mkState([field2, field0a]),
);
});
});
describe('type `user_settings`, op `update`', () => {
const eventCommon = { id: 0, type: EventTypes.user_settings, op: 'update' };
const mkCheck =
<S: $Keys<EventUpdatableRealmState>, E: $Keys<UserSettings>>(
statePropertyName: S,
eventPropertyName: E,
): ((RealmState[S], UserSettings[E]) => void) =>
(initialStateValue, eventValue) => {
test(`${labelFromValue(initialStateValue)} ${labelFromValue(eventValue)}`, () => {
const initialState = { ...eg.plusReduxState.realm };
// $FlowFixMe[prop-missing]
// $FlowFixMe[class-object-subtyping]
/* $FlowFixMe[incompatible-type]: Trust that the caller passed the
right kind of value for its chosen key. */
initialState[statePropertyName] = initialStateValue;
const expectedState = { ...initialState };
/* $FlowFixMe[incompatible-type]: Trust that the caller passed the
right kind of value for its chosen key. */
expectedState[statePropertyName] = eventValue;
expect(
realmReducer(initialState, {
type: EVENT,
event: { ...eventCommon, property: eventPropertyName, value: eventValue },
}),
).toEqual(expectedState);
});
};
describe('twentyFourHourTime / twenty_four_hour_time', () => {
const check = mkCheck('twentyFourHourTime', 'twenty_four_hour_time');
check(true, true);
check(true, false);
check(false, true);
check(false, false);
});
describe('presenceEnabled / presence_enabled', () => {
const check = mkCheck('presenceEnabled', 'presence_enabled');
check(true, true);
check(true, false);
check(false, true);
check(false, false);
});
});
describe('type `realm`, op `update_dict`', () => {
const eventCommon = { id: 0, type: EventTypes.realm, op: 'update_dict', property: 'default' };
const mkCheck =
<S: $Keys<EventUpdatableRealmState>, E: $Keys<RealmDataForUpdate>>(
statePropertyName: S,
eventPropertyName: E,
): ((RealmState[S], RealmDataForUpdate[E]) => void) =>
(initialStateValue, eventValue) => {
test(`${labelFromValue(initialStateValue)} ${labelFromValue(eventValue)}`, () => {
const initialState = { ...eg.plusReduxState.realm };
// $FlowFixMe[prop-missing]
// $FlowFixMe[class-object-subtyping]
/* $FlowFixMe[incompatible-type]: Trust that the caller passed the
right kind of value for its chosen key. */
initialState[statePropertyName] = initialStateValue;
const expectedState = { ...initialState };
/* $FlowFixMe[incompatible-type]: Trust that the caller passed the
right kind of value for its chosen key. */
expectedState[statePropertyName] = eventValue;
expect(
realmReducer(initialState, {
type: EVENT,
event: {
...eventCommon,
// $FlowFixMe[invalid-computed-prop]
data: { [eventPropertyName]: eventValue },
},
}),
).toEqual(expectedState);
});
};
describe('name / name', () => {
const check = mkCheck('name', 'name');
check('foo', 'foo');
check('foo', 'bar');
});
describe('description / description', () => {
const check = mkCheck('description', 'description');
check('foo', 'foo');
check('foo', 'bar');
});
describe('mandatoryTopics / mandatory_topics', () => {
const check = mkCheck('mandatoryTopics', 'mandatory_topics');
check(true, true);
check(true, false);
check(false, true);
check(false, false);
});
describe('messageContentDeleteLimitSeconds / message_content_delete_limit_seconds', () => {
const check = mkCheck(
'messageContentDeleteLimitSeconds',
'message_content_delete_limit_seconds',
);
check(900, 900);
check(900, 300);
});
describe('messageContentEditLimitSeconds / message_content_edit_limit_seconds', () => {
const check = mkCheck(
'messageContentEditLimitSeconds',
'message_content_edit_limit_seconds',
);
check(900, 900);
check(900, 300);
});
describe('pushNotificationsEnabled / push_notifications_enabled', () => {
const check = mkCheck('pushNotificationsEnabled', 'push_notifications_enabled');
check(true, true);
check(true, false);
check(false, true);
check(false, false);
});
describe('pushNotificationsEnabledEndTimestamp / push_notifications_enabled_end_timestamp', () => {
const check = mkCheck(
'pushNotificationsEnabledEndTimestamp',
'push_notifications_enabled_end_timestamp',
);
check(123, null);
check(null, 123);
check(123, 234);
});
describe('create{Private,Public}StreamPolicy / create_stream_policy', () => {
// TODO(server-5.0): Stop expecting create_stream_policy; remove.
const { MemberOrAbove, AdminOrAbove, FullMemberOrAbove, ModeratorOrAbove } =
CreatePublicOrPrivateStreamPolicy;
const check = (initialStateValue, eventValue) => {
test(`${initialStateValue.toString()} ${eventValue.toString()}`, () => {
const initialState = {
...eg.plusReduxState.realm,
createPublicStreamPolicy: initialStateValue,
createPrivateStreamPolicy: initialStateValue,
};
expect(
realmReducer(initialState, {
type: EVENT,
event: { ...eventCommon, data: { create_stream_policy: eventValue } },
}),
).toEqual({
...initialState,
createPublicStreamPolicy: eventValue,
createPrivateStreamPolicy: eventValue,
});
});
};
check(MemberOrAbove, AdminOrAbove);
check(MemberOrAbove, FullMemberOrAbove);
check(MemberOrAbove, ModeratorOrAbove);
check(AdminOrAbove, MemberOrAbove);
check(AdminOrAbove, FullMemberOrAbove);
check(AdminOrAbove, ModeratorOrAbove);
check(FullMemberOrAbove, MemberOrAbove);
check(FullMemberOrAbove, AdminOrAbove);
check(FullMemberOrAbove, ModeratorOrAbove);
check(ModeratorOrAbove, MemberOrAbove);
check(ModeratorOrAbove, AdminOrAbove);
check(ModeratorOrAbove, FullMemberOrAbove);
});
describe('createPublicStreamPolicy / create_public_stream_policy', () => {
const { MemberOrAbove, AdminOrAbove, FullMemberOrAbove, ModeratorOrAbove } =
CreatePublicOrPrivateStreamPolicy;
const check = mkCheck('createPublicStreamPolicy', 'create_public_stream_policy');
check(MemberOrAbove, AdminOrAbove);
check(MemberOrAbove, FullMemberOrAbove);
check(MemberOrAbove, ModeratorOrAbove);
check(AdminOrAbove, MemberOrAbove);
check(AdminOrAbove, FullMemberOrAbove);
check(AdminOrAbove, ModeratorOrAbove);
check(FullMemberOrAbove, MemberOrAbove);
check(FullMemberOrAbove, AdminOrAbove);
check(FullMemberOrAbove, ModeratorOrAbove);
check(ModeratorOrAbove, MemberOrAbove);
check(ModeratorOrAbove, AdminOrAbove);
check(ModeratorOrAbove, FullMemberOrAbove);
});
describe('createPrivateStreamPolicy / create_private_stream_policy', () => {
const { MemberOrAbove, AdminOrAbove, FullMemberOrAbove, ModeratorOrAbove } =
CreatePublicOrPrivateStreamPolicy;
const check = mkCheck('createPrivateStreamPolicy', 'create_private_stream_policy');
check(MemberOrAbove, AdminOrAbove);
check(MemberOrAbove, FullMemberOrAbove);
check(MemberOrAbove, ModeratorOrAbove);
check(AdminOrAbove, MemberOrAbove);
check(AdminOrAbove, FullMemberOrAbove);
check(AdminOrAbove, ModeratorOrAbove);
check(FullMemberOrAbove, MemberOrAbove);
check(FullMemberOrAbove, AdminOrAbove);
check(FullMemberOrAbove, ModeratorOrAbove);
check(ModeratorOrAbove, MemberOrAbove);
check(ModeratorOrAbove, AdminOrAbove);
check(ModeratorOrAbove, FullMemberOrAbove);
});
describe('createWebPublicStreamPolicy / create_web_public_stream_policy', () => {
const { AdminOrAbove, ModeratorOrAbove, Nobody, OwnerOnly } = CreateWebPublicStreamPolicy;
const check = mkCheck('createWebPublicStreamPolicy', 'create_web_public_stream_policy');
check(AdminOrAbove, ModeratorOrAbove);
check(AdminOrAbove, Nobody);
check(AdminOrAbove, OwnerOnly);
check(ModeratorOrAbove, AdminOrAbove);
check(ModeratorOrAbove, Nobody);
check(ModeratorOrAbove, OwnerOnly);
check(Nobody, AdminOrAbove);
check(Nobody, ModeratorOrAbove);
check(Nobody, OwnerOnly);
check(OwnerOnly, AdminOrAbove);
check(OwnerOnly, ModeratorOrAbove);
check(OwnerOnly, Nobody);
});
describe('enableSpectatorAccess / enable_spectator_access', () => {
const check = mkCheck('enableSpectatorAccess', 'enable_spectator_access');
check(true, true);
check(true, false);
check(false, true);
check(false, false);
});
describe('waitingPeriodThreshold / waiting_period_threshold', () => {
const check = mkCheck('waitingPeriodThreshold', 'waiting_period_threshold');
check(90, 90);
check(90, 30);
});
describe('allowEditHistory / allow_edit_history', () => {
const check = mkCheck('allowEditHistory', 'allow_edit_history');
check(true, true);
check(true, false);
check(false, true);
check(false, false);
});
describe('enableReadReceipts / enable_read_receipts', () => {
const check = mkCheck('enableReadReceipts', 'enable_read_receipts');
check(true, true);
check(true, false);
check(false, true);
check(false, false);
});
describe('emailAddressVisibility / email_address_visibility', () => {
const { Everyone, Members, Admins, Nobody, Moderators } = EmailAddressVisibility;
const check = mkCheck('emailAddressVisibility', 'email_address_visibility');
check(Everyone, Members);
check(Everyone, Admins);
check(Everyone, Nobody);
check(Everyone, Moderators);
check(Members, Everyone);
check(Members, Admins);
check(Members, Nobody);
check(Members, Moderators);
check(Admins, Everyone);
check(Admins, Members);
check(Admins, Nobody);
check(Admins, Moderators);
check(Nobody, Everyone);
check(Nobody, Admins);
check(Nobody, Members);
check(Nobody, Moderators);
check(Moderators, Everyone);
check(Moderators, Admins);
check(Moderators, Members);
check(Moderators, Nobody);
});
describe('enableGuestUserIndicator / enable_guest_user_indicator', () => {
const check = mkCheck('enableGuestUserIndicator', 'enable_guest_user_indicator');
check(true, true);
check(true, false);
check(false, true);
check(false, false);
});
});
});
});
```
|
/content/code_sandbox/src/realm/__tests__/realmReducer-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 4,534
|
```javascript
/* @flow strict-local */
import React from 'react';
import type { Node } from 'react';
import { View } from 'react-native';
import type { Narrow } from '../types';
import { createStyleSheet } from '../styles';
import { useSelector } from '../react-redux';
import { getUnreadCountForNarrow } from '../selectors';
import ZulipTextIntl from '../common/ZulipTextIntl';
import MarkAsReadButton from './MarkAsReadButton';
import AnimatedScaleComponent from '../animation/AnimatedScaleComponent';
const styles = createStyleSheet({
unreadContainer: {
paddingHorizontal: 8,
paddingVertical: 4,
backgroundColor: 'hsl(232, 89%, 78%)',
flexDirection: 'row',
justifyContent: 'space-between',
overflow: 'hidden',
},
unreadTextWrapper: {
flexDirection: 'row',
alignItems: 'center',
},
unreadNumber: {
fontSize: 14,
color: 'white',
paddingRight: 4,
},
unreadText: {
fontSize: 14,
color: 'white',
},
});
type Props = $ReadOnly<{|
narrow: Narrow,
|}>;
export default function UnreadNotice(props: Props): Node {
const { narrow } = props;
const unreadCount = useSelector(state => getUnreadCountForNarrow(state, narrow));
return (
<AnimatedScaleComponent visible={unreadCount > 0} style={styles.unreadContainer}>
<View style={styles.unreadTextWrapper}>
<ZulipTextIntl
style={styles.unreadText}
text={{
text: `\
{unreadCount, plural,
one {{unreadCount} unread message}
other {{unreadCount} unread messages}
}`,
values: { unreadCount },
}}
/>
</View>
<MarkAsReadButton narrow={narrow} />
</AnimatedScaleComponent>
);
}
```
|
/content/code_sandbox/src/chat/UnreadNotice.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 410
|
```javascript
/* @flow strict-local */
import React, { useCallback } from 'react';
import type { Node } from 'react';
import type { Narrow } from '../types';
import { createStyleSheet } from '../styles';
import { useSelector } from '../react-redux';
import ZulipButton from '../common/ZulipButton';
import * as api from '../api';
import { getAuth, getOwnUserId } from '../selectors';
import { getUnread, getUnreadIdsForPmNarrow } from '../unread/unreadModel';
import {
isHomeNarrow,
isStreamNarrow,
isTopicNarrow,
isPmNarrow,
streamIdOfNarrow,
topicOfNarrow,
} from '../utils/narrow';
const styles = createStyleSheet({
button: {
borderRadius: 16,
height: 32,
paddingLeft: 12,
paddingRight: 12,
},
});
type Props = $ReadOnly<{|
narrow: Narrow,
|}>;
export default function MarkAsReadButton(props: Props): Node {
const { narrow } = props;
const auth = useSelector(getAuth);
const unread = useSelector(getUnread);
const ownUserId = useSelector(getOwnUserId);
const markAllAsRead = useCallback(() => {
api.markAllAsRead(auth);
}, [auth]);
const markStreamAsRead = useCallback(() => {
api.markStreamAsRead(auth, streamIdOfNarrow(narrow));
}, [auth, narrow]);
const markTopicAsRead = useCallback(() => {
api.markTopicAsRead(auth, streamIdOfNarrow(narrow), topicOfNarrow(narrow));
}, [auth, narrow]);
const markPmAsRead = useCallback(() => {
// The message IDs come from our unread-messages data, which is
// initialized with "only" the most recent 50K unread messages. So
// we'll occasionally, but rarely, miss some messages here; see #5156.
const messageIds = getUnreadIdsForPmNarrow(unread, narrow, ownUserId);
if (messageIds.length === 0) {
return;
}
api.updateMessageFlags(auth, messageIds, 'add', 'read');
}, [auth, unread, narrow, ownUserId]);
if (isHomeNarrow(narrow)) {
return <ZulipButton style={styles.button} text="Mark all as read" onPress={markAllAsRead} />;
}
if (isStreamNarrow(narrow)) {
return (
<ZulipButton style={styles.button} text="Mark stream as read" onPress={markStreamAsRead} />
);
}
if (isTopicNarrow(narrow)) {
return (
<ZulipButton style={styles.button} text="Mark topic as read" onPress={markTopicAsRead} />
);
}
if (isPmNarrow(narrow)) {
return (
<ZulipButton style={styles.button} text="Mark conversation as read" onPress={markPmAsRead} />
);
}
return null;
}
```
|
/content/code_sandbox/src/chat/MarkAsReadButton.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 667
|
```javascript
/* @flow strict-local */
import type { Fetching, PerAccountState, Narrow } from '../types';
import { getFetching } from '../directSelectors';
import { keyFromNarrow } from '../utils/narrow';
/** The value implicitly represented by a missing entry in FetchingState. */
export const DEFAULT_FETCHING = { older: false, newer: false };
export const getFetchingForNarrow = (state: PerAccountState, narrow: Narrow): Fetching =>
getFetching(state)[keyFromNarrow(narrow)] || DEFAULT_FETCHING;
```
|
/content/code_sandbox/src/chat/fetchingSelectors.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 115
|
```javascript
/* @flow strict-local */
import React from 'react';
import type { Node } from 'react';
import { StyleSheet, View } from 'react-native';
import type { Narrow } from '../types';
import ZulipTextIntl from '../common/ZulipTextIntl';
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 20,
paddingLeft: 10,
padding: 8,
},
});
type Props = $ReadOnly<{|
narrow: Narrow,
|}>;
export default function InvalidNarrow(props: Props): Node {
return (
<View style={styles.container}>
<ZulipTextIntl style={styles.text} text="That conversation doesnt seem to exist." />
</View>
);
}
```
|
/content/code_sandbox/src/chat/InvalidNarrow.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 179
|
```javascript
/* @flow strict-local */
// $FlowFixMe[untyped-import]
import isEqual from 'lodash.isequal';
import { createSelector } from 'reselect';
import type {
PerAccountState,
Message,
Narrow,
Outbox,
Selector,
Stream,
Subscription,
} from '../types';
import { getAllNarrows, getMessages, getOutbox, getFlags } from '../directSelectors';
import { getCaughtUpForNarrow } from '../caughtup/caughtUpSelectors';
import { getAllUsersById, getOwnUserId } from '../users/userSelectors';
import {
isStreamOrTopicNarrow,
isMessageInNarrow,
caseNarrowDefault,
keyFromNarrow,
caseNarrow,
streamIdOfNarrow,
} from '../utils/narrow';
import { getMute, isTopicVisibleInStream, isTopicVisible } from '../mute/muteModel';
import { NULL_ARRAY, NULL_SUBSCRIPTION } from '../nullObjects';
import * as logging from '../utils/logging';
import { getStreamsById, getSubscriptionsById } from '../subscriptions/subscriptionSelectors';
export const outboxMessagesForNarrow: Selector<$ReadOnlyArray<Outbox>, Narrow> = createSelector(
(state, narrow) => narrow,
getCaughtUpForNarrow,
state => getOutbox(state),
getOwnUserId,
(narrow, caughtUp, outboxMessages, ownUserId) => {
if (!caughtUp.newer) {
return NULL_ARRAY;
}
// TODO?: Handle @-mention flags in outbox messages. As is, if you
// @-mention yourself (or a wildcard) and then go look at the
// is:mentioned view while your message is still unsent, we wrongly
// leave it out. Pretty uncommon edge case, though.
//
// No other narrows rely on flags except the "starred" narrow. Outbox
// messages can't be starred, so "no flags" gives that the right answer.
const fakeFlags = [];
const filtered = outboxMessages.filter(message =>
isMessageInNarrow(message, fakeFlags, narrow, ownUserId),
);
return isEqual(filtered, outboxMessages) ? outboxMessages : filtered;
},
);
export const getFetchedMessageIdsForNarrow = (
state: PerAccountState,
narrow: Narrow,
): $ReadOnlyArray<number> => getAllNarrows(state).get(keyFromNarrow(narrow)) || NULL_ARRAY;
const getFetchedMessagesForNarrow: Selector<$ReadOnlyArray<Message>, Narrow> = createSelector(
getFetchedMessageIdsForNarrow,
state => getMessages(state),
(messageIds, messages) =>
messageIds.map(id => {
const message = messages.get(id);
if (!message) {
const msg = 'getFetchedMessagesForNarrow: message with id is missing in getMessages(state)';
logging.error(msg, { id });
throw new Error(msg);
}
return message;
}),
);
// Prettier mishandles this Flow syntax.
// prettier-ignore
export const getMessagesForNarrow: Selector<$ReadOnlyArray<Message | Outbox>, Narrow> =
createSelector(
getFetchedMessagesForNarrow,
outboxMessagesForNarrow,
(fetchedMessages, outboxMessages) => {
if (outboxMessages.length === 0) {
return fetchedMessages;
}
return [...fetchedMessages, ...outboxMessages].sort((a, b) => a.id - b.id);
},
);
/**
* The known messages that should appear in the given narrow's message list.
*
* This is like {@link getMessagesForNarrow} but returns a subset of the
* messages, to implement the muted-stream and muted-topic features.
*/
// Prettier mishandles this Flow syntax.
// prettier-ignore
export const getShownMessagesForNarrow: Selector<$ReadOnlyArray<Message | Outbox>, Narrow> =
createSelector(
(state, narrow) => narrow,
getMessagesForNarrow,
state => getSubscriptionsById(state),
state => getMute(state),
state => getFlags(state),
(narrow, messagesForNarrow, subscriptions, mute, flags) =>
caseNarrow(narrow, {
home: _ =>
messagesForNarrow.filter(message => {
if (message.type === 'private') {
return true;
}
if (flags.mentioned[message.id]) {
return true;
}
const sub = subscriptions.get(message.stream_id);
if (!sub) {
// If there's no matching subscription, then the user must have
// unsubscribed from the stream since the message was received.
// Leave those messages out of this view, just as we would if
// the user had muted the stream (without unmuting topics).
return false;
}
return isTopicVisible(message.stream_id, message.subject, sub, mute);
}),
stream: _ =>
messagesForNarrow.filter(message => {
if (message.type === 'private') {
return true;
}
if (flags.mentioned[message.id]) {
return true;
}
return isTopicVisibleInStream(message.stream_id, message.subject, mute);
}),
// In the starred-message view, ignore stream/topic mutes.
// TODO: What about starred messages in other views?
starred: _ => messagesForNarrow,
// When viewing a topic narrow, we show all the messages even if the
// topic or stream is muted.
topic: _ => messagesForNarrow,
// In a PM narrow, no messages can be in a muted stream or topic.
pm: _ => messagesForNarrow,
// In the @-mentions narrow, all messages are mentions, which we
// always show despite stream or topic mutes.
mentioned: _ => messagesForNarrow,
// The all-PMs narrow doesn't matter here, because we don't offer a
// message list for it in the UI. (It exists for the sake of
// `getRecentConversationsLegacy`.)
allPrivate: _ => messagesForNarrow,
// Search narrows don't matter here, because we never reach this code
// when searching (we don't get the messages from Redux.)
search: _ => messagesForNarrow,
}),
);
export const getFirstMessageId = (state: PerAccountState, narrow: Narrow): number | void => {
const ids = getFetchedMessageIdsForNarrow(state, narrow);
return ids.length > 0 ? ids[0] : undefined;
};
export const getLastMessageId = (state: PerAccountState, narrow: Narrow): number | void => {
const ids = getFetchedMessageIdsForNarrow(state, narrow);
return ids.length > 0 ? ids[ids.length - 1] : undefined;
};
// Prettier mishandles this Flow syntax.
// prettier-ignore
// TODO: clean up what this returns; possibly to just `Stream`
export const getStreamInNarrow: Selector<Subscription | {| ...Stream, in_home_view: boolean |}, Narrow> = createSelector(
(state, narrow) => narrow,
state => getSubscriptionsById(state),
state => getStreamsById(state),
(narrow, subscriptions, streams) => {
if (!isStreamOrTopicNarrow(narrow)) {
return NULL_SUBSCRIPTION;
}
const streamId = streamIdOfNarrow(narrow);
const subscription = subscriptions.get(streamId);
if (subscription) {
return subscription;
}
const stream = streams.get(streamId);
if (stream) {
return {
...stream,
in_home_view: true,
};
}
return NULL_SUBSCRIPTION;
},
);
/**
* Whether PerAccountState has all data mentioned in `narrow` (user IDs etc.)
*/
export const isNarrowValid: Selector<boolean, Narrow> = createSelector(
(state, narrow) => narrow,
state => getStreamsById(state),
state => getAllUsersById(state),
(narrow, streams, allUsersById) =>
caseNarrowDefault(
narrow,
{
stream: streamId => streams.get(streamId) !== undefined,
topic: streamId => streams.get(streamId) !== undefined,
pm: ids => ids.every(id => allUsersById.get(id) !== undefined),
},
() => true,
),
);
```
|
/content/code_sandbox/src/chat/narrowsSelectors.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,815
|
```javascript
/* @flow strict-local */
import React, { useCallback } from 'react';
import type { Node } from 'react';
import { FlatList } from 'react-native';
import type { RouteProp } from '../react-navigation';
import type { AppNavigationProp } from '../nav/AppNavigator';
import { useSelector } from '../react-redux';
import type { UserOrBot } from '../types';
import { pmUiRecipientsFromKeyRecipients, type PmKeyRecipients } from '../utils/recipient';
import Screen from '../common/Screen';
import UserItem from '../users/UserItem';
import { getOwnUserId } from '../selectors';
type Props = $ReadOnly<{|
navigation: AppNavigationProp<'pm-conversation-details'>,
route: RouteProp<'pm-conversation-details', {| recipients: PmKeyRecipients |}>,
|}>;
export default function PmConversationDetailsScreen(props: Props): Node {
const { navigation } = props;
const { recipients } = props.route.params;
const ownUserId = useSelector(getOwnUserId);
const handlePress = useCallback(
(user: UserOrBot) => {
navigation.push('account-details', { userId: user.user_id });
},
[navigation],
);
return (
<Screen title="Recipients" scrollEnabled={false}>
<FlatList
initialNumToRender={10}
data={pmUiRecipientsFromKeyRecipients(recipients, ownUserId)}
keyExtractor={item => String(item)}
renderItem={({ item }) => (
<UserItem key={item} userId={item} showEmail onPress={handlePress} />
)}
/>
</Screen>
);
}
```
|
/content/code_sandbox/src/chat/PmConversationDetailsScreen.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 350
|
```javascript
/* @flow strict-local */
import React, { useCallback, useContext } from 'react';
import type { Node } from 'react';
import { useIsFocused } from '@react-navigation/native';
import { useSelector, useDispatch } from '../react-redux';
import type { RouteProp } from '../react-navigation';
import type { AppNavigationProp } from '../nav/AppNavigator';
import { ThemeContext, createStyleSheet } from '../styles';
import type { Narrow, EditMessage } from '../types';
import KeyboardAvoider from '../common/KeyboardAvoider';
import ChatNavBar from '../nav/ChatNavBar';
import MessageList from '../webview/MessageList';
import NoMessages from '../message/NoMessages';
import FetchError from './FetchError';
import InvalidNarrow from './InvalidNarrow';
import { fetchMessagesInNarrow, fetchMessages } from '../message/fetchActions';
import ComposeBox, {
type ImperativeHandle as ComposeBoxImperativeHandle,
} from '../compose/ComposeBox';
import UnreadNotice from './UnreadNotice';
import { showComposeBoxOnNarrow, caseNarrowDefault, keyFromNarrow } from '../utils/narrow';
import { getLoading, getSession } from '../directSelectors';
import { getFetchingForNarrow } from './fetchingSelectors';
import {
getFirstMessageId,
getLastMessageId,
getShownMessagesForNarrow,
isNarrowValid as getIsNarrowValid,
} from './narrowsSelectors';
import { getFirstUnreadIdInNarrow } from '../message/messageSelectors';
import { getDraftForNarrow } from '../drafts/draftsSelectors';
import { addToOutbox } from '../actions';
import { getAuth, getCaughtUpForNarrow } from '../selectors';
import { showErrorAlert } from '../utils/info';
import { TranslationContext } from '../boot/TranslationProvider';
import * as api from '../api';
import { useConditionalEffect } from '../reactUtils';
import config from '../config';
type Props = $ReadOnly<{|
navigation: AppNavigationProp<'chat'>,
route: RouteProp<'chat', {| narrow: Narrow, editMessage: EditMessage | null |}>,
|}>;
const componentStyles = createStyleSheet({
screen: {
flex: 1,
flexDirection: 'column',
},
});
/**
* Fetch messages for this narrow and report an error, if any
*
* See `MessagesState` for background about the fetching, including
* why this is nearly the only place where additional data fetching
* is required. See `fetchMessagesInNarrow` and `fetchMessages` for
* more details, including how Redux is kept up-to-date during the
* whole process.
*/
const useMessagesWithFetch = args => {
const { narrow } = args;
const dispatch = useDispatch();
const isFocused = useIsFocused();
const eventQueueId = useSelector(state => getSession(state).eventQueueId);
const loading = useSelector(getLoading);
const fetching = useSelector(state => getFetchingForNarrow(state, narrow));
const isFetching = fetching.older || fetching.newer || loading;
const caughtUp = useSelector(state => getCaughtUpForNarrow(state, narrow));
const messages = useSelector(state => getShownMessagesForNarrow(state, narrow));
const firstUnreadIdInNarrow = useSelector(state => getFirstUnreadIdInNarrow(state, narrow));
// This could live in state, but then we'd risk pointless rerenders;
// we only use it in our `useEffect` callbacks. Using `useRef` is
// like using instance variables in class components:
// path_to_url#is-there-something-like-instance-variables
const shouldFetchWhenNextFocused = React.useRef<boolean>(false);
const scheduleFetch = useCallback(() => {
shouldFetchWhenNextFocused.current = true;
}, []);
const [fetchError, setFetchError] = React.useState<mixed>(null);
const fetch = React.useCallback(async () => {
shouldFetchWhenNextFocused.current = false;
try {
await dispatch(fetchMessagesInNarrow(narrow));
} catch (errorIllTyped) {
const e: mixed = errorIllTyped; // path_to_url
setFetchError(e);
}
}, [dispatch, narrow]);
// When we have a new event queue, schedule a fetch.
React.useEffect(() => {
if (eventQueueId !== null) {
scheduleFetch();
}
}, [eventQueueId, scheduleFetch]);
// If we stop having any data at all about the messages in this narrow --
// we don't know any, and nor do we know if there are some -- then
// schedule a fetch. (As long as we have *some* messages, we'll show a
// proper MessageList, and scroll events can cause us to fetch newer or
// older messages. But with none, we'll show NoMessages.)
//
// TODO: We may still briefly show NoMessages; this render will have
// isFetching false, even though the fetch effect will cause a rerender
// with isFetching true. It'd be nice to avoid that.
const nothingKnown = messages.length === 0 && !caughtUp.older && !caughtUp.newer;
useConditionalEffect(scheduleFetch, nothingKnown);
// On first mount, fetch. (This also makes a fetch no longer scheduled,
// so the if-scheduled fetch below doesn't also fire.)
React.useEffect(() => {
fetch();
}, [fetch]);
// When a fetch is scheduled and we're focused, fetch.
React.useEffect(() => {
if (shouldFetchWhenNextFocused.current && isFocused === true) {
fetch();
}
// No dependencies list, to run this effect after every render. This
// effect does its own checking of whether any work needs to be done.
});
return { fetchError, isFetching, messages, firstUnreadIdInNarrow };
};
export default function ChatScreen(props: Props): Node {
const { route, navigation } = props;
const { backgroundColor } = React.useContext(ThemeContext);
const { narrow, editMessage } = route.params;
const setEditMessage = useCallback(
(value: EditMessage | null) => navigation.setParams({ editMessage: value }),
[navigation],
);
const isNarrowValid = useSelector(state => getIsNarrowValid(state, narrow));
const draft = useSelector(state => getDraftForNarrow(state, narrow));
const { fetchError, isFetching, messages, firstUnreadIdInNarrow } = useMessagesWithFetch({
narrow,
});
const showMessagePlaceholders = messages.length === 0 && isFetching;
const sayNoMessages = messages.length === 0 && !isFetching;
const showComposeBox = showComposeBoxOnNarrow(narrow) && !showMessagePlaceholders;
const composeBoxRef = React.useRef<ComposeBoxImperativeHandle | null>(null);
const auth = useSelector(getAuth);
const caughtUp = useSelector(state => getCaughtUpForNarrow(state, narrow));
const dispatch = useDispatch();
const fetching = useSelector(state => getFetchingForNarrow(state, narrow));
const firstMessageId = useSelector(state => getFirstMessageId(state, narrow));
const lastMessageId = useSelector(state => getLastMessageId(state, narrow));
const loading = useSelector(getLoading);
const _ = useContext(TranslationContext);
const fetchOlder = () => {
if (!loading && !fetching.older && !caughtUp.older && firstMessageId !== undefined) {
dispatch(
fetchMessages({
narrow,
anchor: firstMessageId,
numBefore: config.messagesPerRequest,
numAfter: 0,
}),
);
}
};
const fetchNewer = () => {
if (!loading && !fetching.newer && !caughtUp.newer && lastMessageId !== undefined) {
dispatch(
fetchMessages({
narrow,
anchor: lastMessageId,
numBefore: 0,
numAfter: config.messagesPerRequest,
}),
);
}
};
const sendCallback = useCallback(
(message: string, destinationNarrow: Narrow) => {
if (editMessage) {
const content = editMessage.content !== message ? message : undefined;
const topic = caseNarrowDefault(
destinationNarrow,
// eslint-disable-next-line no-shadow
{ topic: (streamId, topic) => (topic !== editMessage.topic ? topic : undefined) },
() => undefined,
);
if ((content !== undefined && content !== '') || (topic !== undefined && topic !== '')) {
api.updateMessage(auth, editMessage.id, { content, subject: topic }).catch(error => {
showErrorAlert(_('Failed to edit message'), error.message);
});
}
setEditMessage(null);
} else {
if (fetching.newer) {
// If we're fetching, that means that (a) we're scrolled near the
// bottom, and likely are scrolled to the very bottom so that it
// looks like we're showing the latest messages, but (b) we don't
// actually have the latest messages. So the user may be misled
// and send a reply that doesn't make sense with the later context.
//
// Ideally in this condition we'd show a warning to make sure the
// user knows what they're getting into, and then let them send
// anyway. We'd also then need to take care with how the
// resulting message appears in the message list: see #3800 and
// path_to_url#narrow/stream/48-mobile/topic/Failed.20to.20send.20on.20Android/near/1158162
//
// For now, just refuse to send. After all, this condition will
// resolve itself when we complete the fetch, and if that doesn't
// happen soon then it's unlikely we could successfully send a
// message anyway.
showErrorAlert(_('Failed to send message'));
return;
}
dispatch(addToOutbox(destinationNarrow, message));
}
},
[_, auth, fetching.newer, dispatch, editMessage, setEditMessage],
);
return (
<KeyboardAvoider
style={[componentStyles.screen, { backgroundColor }]}
behavior="padding"
compensateOverpadding={
// We let the compose box pad the bottom inset.
showComposeBox
}
>
<ChatNavBar narrow={narrow} editMessage={editMessage} />
<UnreadNotice narrow={narrow} />
{(() => {
if (!isNarrowValid) {
return <InvalidNarrow narrow={narrow} />;
} else if (fetchError !== null) {
return <FetchError narrow={narrow} error={fetchError} />;
} else if (sayNoMessages) {
return <NoMessages narrow={narrow} />;
} else {
return (
<MessageList
narrow={narrow}
messages={messages}
initialScrollMessageId={
firstUnreadIdInNarrow
// `messages` might be empty
?? (messages[messages.length - 1]: (typeof messages)[number] | void)?.id
?? null
}
showMessagePlaceholders={showMessagePlaceholders}
startEditMessage={setEditMessage}
fetchOlder={fetchOlder}
fetchNewer={fetchNewer}
composeBoxRef={composeBoxRef}
/>
);
}
})()}
{showComposeBox && (
<ComposeBox
ref={composeBoxRef}
narrow={narrow}
isEditing={editMessage !== null}
initialTopic={editMessage ? editMessage.topic : undefined}
initialMessage={editMessage ? editMessage.content : draft}
onSend={sendCallback}
autoFocusMessage={editMessage !== null}
key={keyFromNarrow(narrow) + (editMessage?.id.toString() ?? 'noedit')}
/>
)}
</KeyboardAvoider>
);
}
```
|
/content/code_sandbox/src/chat/ChatScreen.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 2,602
|
```javascript
/* @flow strict-local */
// $FlowFixMe[untyped-import]
import union from 'lodash.union';
import Immutable from 'immutable';
import type { NarrowsState, PerAccountApplicableAction } from '../types';
import { ensureUnreachable } from '../types';
import {
REGISTER_COMPLETE,
MESSAGE_FETCH_START,
MESSAGE_FETCH_ERROR,
MESSAGE_FETCH_COMPLETE,
EVENT_NEW_MESSAGE,
EVENT_MESSAGE_DELETE,
EVENT_UPDATE_MESSAGE_FLAGS,
EVENT_UPDATE_MESSAGE,
RESET_ACCOUNT_DATA,
} from '../actionConstants';
import { LAST_MESSAGE_ANCHOR, FIRST_UNREAD_ANCHOR } from '../anchor';
import {
getNarrowsForMessage,
MENTIONED_NARROW_STR,
STARRED_NARROW_STR,
isSearchNarrow,
keyFromNarrow,
topicNarrow,
streamNarrow,
} from '../utils/narrow';
import { getCaughtUpForNarrowInner } from '../caughtup/caughtUpSelectors';
const initialState: NarrowsState = Immutable.Map();
function removeMessages(state: NarrowsState, narrow, messageIds): NarrowsState {
return state.update(
keyFromNarrow(narrow),
messages => messages && messages.filter(id => !messageIds.has(id)),
);
}
/**
* Incorporate possibly old, possibly discontiguous, messages in the narrow.
*
* This differs from the MESSAGE_FETCH_COMPLETE case in that we aren't
* assured that the messages listed are a contiguous segment of the full
* list of messages in the narrow. (For example, someone may have merged
* one conversation into another, where some messages already in the
* destination conversation fall in between some of the moved messages.)
*/
// We need to maintain the state.narrows invariant -- the fact that the
// message IDs we have in a narrow should be a contiguous segment of the
// full list of messages that actually exist in the narrow. That can
// prevent us from adding the messages to our record of the narrow, and
// force us to instead downgrade how much we think we know about the narrow.
function addMessages(state: NarrowsState, narrow, messageIds): NarrowsState {
// NOTE: This behavior must stay parallel with how the caughtUp reducer
// handles the same cases.
const key = keyFromNarrow(narrow);
// TODO: If the state at the narrow covers the given messages, then
// incorporate them.
// TODO: If the state at a *parent* narrow -- in particular the stream
// narrow, if this is a topic narrow -- covers the given messages, then
// use that.
// Do what's simple and always correct, even when not optimal: stop
// claiming to know anything about the narrow. (The caughtUp reducer must
// also delete its record.)
return state.delete(key);
}
const messageFetchComplete = (state, action) => {
// We don't want to accumulate old searches that we'll never need again.
if (isSearchNarrow(action.narrow)) {
return state;
}
const key = keyFromNarrow(action.narrow);
const fetchedMessageIds = action.messages.map(message => message.id);
const replaceExisting =
action.anchor === FIRST_UNREAD_ANCHOR || action.anchor === LAST_MESSAGE_ANCHOR;
return state.set(
key,
replaceExisting
? fetchedMessageIds
: union(state.get(key), fetchedMessageIds).sort((a, b) => a - b),
);
};
const eventNewMessage = (state, action) => {
const { message } = action;
const { flags } = message;
if (!flags) {
throw new Error('EVENT_NEW_MESSAGE message missing flags');
}
return state.withMutations(stateMutable => {
const narrowsForMessage = getNarrowsForMessage(message, action.ownUserId, flags);
narrowsForMessage.forEach(narrow => {
const key = keyFromNarrow(narrow);
const value = stateMutable.get(key);
if (!value) {
// We haven't loaded this narrow. The time to add a new key
// isn't now; we do that in MESSAGE_FETCH_COMPLETE, when we
// might have a reasonably long, contiguous list of messages
// to show.
return; // i.e., continue
}
if (!getCaughtUpForNarrowInner(action.caughtUp, narrow).newer) {
// Don't add a message to the end of the list unless we know
// it's the most recent message, i.e., unless we know we're
// currently looking at (caught up with) the newest messages
// in the narrow. We don't want to accidentally show a message
// at the end of a message list if there might be messages
// between the currently latest-shown message and this
// message.
//
// See a corresponding condition in messagesReducer, where we
// don't bother to add to `state.messages` if this condition
// (after running on all of `narrowsForMessage`) means the new
// message wasn't added anywhere in `state.narrows`.
return; // i.e., continue
}
if (value.some(id => action.message.id === id)) {
// Don't add a message that's already been added. It's probably
// very rare for a message to have already been added when we
// get an EVENT_NEW_MESSAGE, and perhaps impossible. (TODO:
// investigate?)
return; // i.e., continue
}
// If changing or removing a case where we ignore a message
// here: Careful! Every message in `state.narrows` must exist in
// `state.messages`. If we choose to include a message in
// `state.narrows`, then messagesReducer MUST ALSO choose to
// include it in `state.messages`.
stateMutable.set(key, [...value, message.id]);
});
});
};
const eventMessageDelete = (state, action) => {
let stateChange = false;
const newState = state.map((value, key) => {
const result = value.filter(id => !action.messageIds.includes(id));
stateChange = stateChange || result.length < value.length;
return result;
});
return stateChange ? newState : state;
};
const updateFlagNarrow = (state, narrowStr, op, messageIds): NarrowsState => {
const value = state.get(narrowStr);
if (!value) {
return state;
}
switch (op) {
case 'add': {
return state.set(
narrowStr,
[...value, ...messageIds].sort((a, b) => a - b),
);
}
case 'remove': {
const messageIdSet = new Set(messageIds);
return state.set(
narrowStr,
value.filter(id => !messageIdSet.has(id)),
);
}
default:
ensureUnreachable(op);
throw new Error(`Unexpected operation ${op} in an EVENT_UPDATE_MESSAGE_FLAGS action`);
}
};
const eventUpdateMessageFlags = (state, action) => {
const { flag, op, messages: messageIds } = action;
if (flag === 'starred') {
return updateFlagNarrow(state, STARRED_NARROW_STR, op, messageIds);
} else if (['mentioned', 'wildcard_mentioned'].includes(flag)) {
return updateFlagNarrow(state, MENTIONED_NARROW_STR, op, messageIds);
}
return state;
};
export default (
state: NarrowsState = initialState, // eslint-disable-line default-param-last
action: PerAccountApplicableAction,
): NarrowsState => {
switch (action.type) {
case RESET_ACCOUNT_DATA:
return initialState;
// Reset to clear stale data. We don't initialize the
// messages/narrows/flags model using initial data; instead, we fetch
// chunks of data as needed with api.getMessages. See
// path_to_url#messages
case REGISTER_COMPLETE:
return initialState;
case MESSAGE_FETCH_START: {
// We don't want to accumulate old searches that we'll never need again.
if (isSearchNarrow(action.narrow)) {
return state;
}
// Currently this whole case could be subsumed in `default`. But
// we don't want to add this case with something else in mind,
// later, and forget about the search-narrow check above.
return state;
}
/**
* The reverse of MESSAGE_FETCH_START, for cleanup.
*/
case MESSAGE_FETCH_ERROR: {
return state;
}
case MESSAGE_FETCH_COMPLETE: {
return messageFetchComplete(state, action);
}
case EVENT_NEW_MESSAGE:
return eventNewMessage(state, action);
case EVENT_MESSAGE_DELETE:
return eventMessageDelete(state, action);
case EVENT_UPDATE_MESSAGE: {
// Compare the corresponding caughtUpReducer case.
let result: NarrowsState = state;
const { event, move } = action;
if (move) {
// The edit changed topic and/or stream.
const { orig_stream_id, orig_topic, new_stream_id, new_topic } = move;
const messageIdSet = new Set(event.message_ids);
result = addMessages(result, topicNarrow(new_stream_id, new_topic), event.message_ids);
result = removeMessages(result, topicNarrow(orig_stream_id, orig_topic), messageIdSet);
if (new_stream_id !== orig_stream_id) {
result = addMessages(result, streamNarrow(new_stream_id), event.message_ids);
result = removeMessages(result, streamNarrow(orig_stream_id), messageIdSet);
}
}
// We don't attempt to update search narrows.
// The other way editing a message can affect what narrows it falls
// into is by changing its flags. Those cause a separate event; see
// the EVENT_UPDATE_MESSAGE_FLAGS case.
return result;
}
case EVENT_UPDATE_MESSAGE_FLAGS:
return eventUpdateMessageFlags(state, action);
default:
return state;
}
};
```
|
/content/code_sandbox/src/chat/narrowsReducer.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 2,173
|
```javascript
/* @flow strict-local */
import React from 'react';
import type { Node } from 'react';
import { StyleSheet, View } from 'react-native';
import type { Narrow } from '../types';
import ZulipTextIntl from '../common/ZulipTextIntl';
import { TimeoutError } from '../utils/async';
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 20,
paddingLeft: 10,
padding: 8,
},
});
type Props = $ReadOnly<{|
narrow: Narrow,
error: mixed,
|}>;
export default function FetchError(props: Props): Node {
return (
<View style={styles.container}>
{(() => {
if (props.error instanceof TimeoutError) {
return <ZulipTextIntl style={styles.text} text="Request timed out." />;
} else {
return <ZulipTextIntl style={styles.text} text="Oops! Something went wrong." />;
}
})()}
</View>
);
}
```
|
/content/code_sandbox/src/chat/FetchError.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 238
|
```javascript
/* @flow strict-local */
import invariant from 'invariant';
import type { ReadWrite } from '../generics';
import type { PerAccountApplicableAction, FlagsState, Message } from '../types';
import {
REGISTER_COMPLETE,
MESSAGE_FETCH_COMPLETE,
EVENT_NEW_MESSAGE,
EVENT_UPDATE_MESSAGE_FLAGS,
RESET_ACCOUNT_DATA,
} from '../actionConstants';
import { deeperMerge } from '../utils/misc';
import type { UserMessageFlag } from '../api/modelTypes';
type ReadWriteFlagsState = $Rest<ReadWrite<$ObjMap<FlagsState, <V>(V) => ReadWrite<V>>>, { ... }>;
type ReadWritePerFlagState = $Values<ReadWriteFlagsState>;
const initialState = {
read: {},
starred: {},
collapsed: {},
mentioned: {},
wildcard_mentioned: {},
has_alert_word: {},
historical: {},
};
const addFlagsForMessages = (
state: FlagsState,
messages: $ReadOnlyArray<number>,
flags: $ReadOnlyArray<UserMessageFlag>,
): FlagsState => {
if (messages.length === 0 || flags.length === 0) {
return state;
}
/* $FlowFixMe[incompatible-exact] - We should ignore flags from the server
that we don't already know about. After all, we can't have any code
intending to do anything with them. */
const newState: ReadWriteFlagsState = {};
flags.forEach(flag => {
const perFlag: ReadWritePerFlagState = { ...(state[flag] || {}) };
messages.forEach(message => {
perFlag[message] = true;
});
newState[flag] = perFlag;
});
return {
...state,
...newState,
};
};
const removeFlagForMessages = (
state: FlagsState,
messages: $ReadOnlyArray<number>,
flag: string,
): FlagsState => {
const newStateForFlag = { ...(state[flag] || {}) };
messages.forEach(message => {
delete newStateForFlag[message];
});
return {
...state,
// TODO: We should ignore flags from the server that we don't already
// know about. After all, we can't have any code intending to do
// anything with them. Flow should be complaining here:
// path_to_url#narrow/stream/243-mobile-team/topic/Flow.20spread.20bug/near/1318081
[flag]: newStateForFlag,
};
};
const processFlagsForMessages = (
state: FlagsState,
messages: $ReadOnlyArray<Message>,
): FlagsState => {
let stateChanged = false;
/* $FlowFixMe[incompatible-exact] - We should ignore flags from the server
that we don't already know about. After all, we can't have any code
intending to do anything with them. */
const newState: ReadWriteFlagsState = {};
messages.forEach(msg => {
(msg.flags || []).forEach(flag => {
if (!state[flag] || !state[flag][msg.id]) {
const perFlag: ReadWritePerFlagState = newState[flag] || (newState[flag] = {});
perFlag[msg.id] = true;
stateChanged = true;
}
});
});
/* $FlowFixMe[incompatible-indexer]: Flow can't follow this
objects-as-maps logic. */
return stateChanged ? deeperMerge(state, newState) : state;
};
const eventUpdateMessageFlags = (state, action) => {
if (action.all) {
if (action.op === 'add') {
return addFlagsForMessages(state, action.allMessages.keySeq().toArray().map(Number), [
action.flag,
]);
}
if (action.op === 'remove') {
// TODO: We should ignore flags from the server that we don't already
// know about. After all, we can't have any code intending to do
// anything with them. Flow should be complaining here:
// path_to_url#narrow/stream/243-mobile-team/topic/Flow.20spread.20bug/near/1318081
return { ...state, [(action.flag: string)]: {} };
}
}
if (action.op === 'add') {
return addFlagsForMessages(state, action.messages, [action.flag]);
}
if (action.op === 'remove') {
return removeFlagForMessages(state, action.messages, action.flag);
}
return state;
};
export default (
state: FlagsState = initialState, // eslint-disable-line default-param-last
action: PerAccountApplicableAction,
): FlagsState => {
switch (action.type) {
case RESET_ACCOUNT_DATA:
return initialState;
// Reset to clear stale data. We don't initialize the
// messages/narrows/flags model using initial data; instead, we fetch
// chunks of data as needed with api.getMessages. See
// path_to_url#messages
case REGISTER_COMPLETE:
return initialState;
case MESSAGE_FETCH_COMPLETE:
return processFlagsForMessages(state, action.messages);
case EVENT_NEW_MESSAGE: {
invariant(action.message.flags, 'message in EVENT_NEW_MESSAGE must have flags');
return addFlagsForMessages(state, [action.message.id], action.message.flags);
}
case EVENT_UPDATE_MESSAGE_FLAGS:
return eventUpdateMessageFlags(state, action);
default:
return state;
}
};
```
|
/content/code_sandbox/src/chat/flagsReducer.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,155
|
```javascript
import deepFreeze from 'deep-freeze';
import { getFetchingForNarrow } from '../fetchingSelectors';
import { HOME_NARROW, HOME_NARROW_STR } from '../../utils/narrow';
describe('getFetchingForNarrow', () => {
test('if no narrow information exists in state, return a null fetching object', () => {
const state = deepFreeze({
fetching: {},
});
const expectedResult = { older: false, newer: false };
const actualResult = getFetchingForNarrow(state, HOME_NARROW);
expect(actualResult).toEqual(expectedResult);
});
test('if an entry matching current narrow exists, it is returned', () => {
const state = deepFreeze({
fetching: {
[HOME_NARROW_STR]: { older: true, newer: true },
},
});
const expectedResult = { older: true, newer: true };
const actualResult = getFetchingForNarrow(state, HOME_NARROW);
expect(actualResult).toEqual(expectedResult);
});
});
```
|
/content/code_sandbox/src/chat/__tests__/fetchingSelectors-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 223
|
```javascript
/* @flow strict-local */
import type { FetchingState, PerAccountApplicableAction } from '../types';
import {
MESSAGE_FETCH_START,
MESSAGE_FETCH_ERROR,
MESSAGE_FETCH_COMPLETE,
RESET_ACCOUNT_DATA,
REGISTER_COMPLETE,
} from '../actionConstants';
import { NULL_OBJECT } from '../nullObjects';
import { DEFAULT_FETCHING } from './fetchingSelectors';
import { isSearchNarrow, keyFromNarrow } from '../utils/narrow';
const initialState: FetchingState = NULL_OBJECT;
const messageFetchStart = (state, action) => {
// We don't want to accumulate old searches that we'll never need
// again.
if (isSearchNarrow(action.narrow)) {
return state;
}
const key = keyFromNarrow(action.narrow);
const currentValue = state[key] || DEFAULT_FETCHING;
return {
...state,
[key]: {
older: currentValue.older || action.numBefore > 0,
newer: currentValue.newer || action.numAfter > 0,
},
};
};
const messageFetchError = (state, action) => {
const key = keyFromNarrow(action.narrow);
if (isSearchNarrow(action.narrow)) {
return state;
}
return {
...state,
[key]: DEFAULT_FETCHING,
};
};
const messageFetchComplete = (state, action) => {
// We don't want to accumulate old searches that we'll never need again.
if (isSearchNarrow(action.narrow)) {
return state;
}
const key = keyFromNarrow(action.narrow);
const currentValue = state[key] || DEFAULT_FETCHING;
return {
...state,
[key]: {
older: currentValue.older && !(action.numBefore > 0),
newer: currentValue.newer && !(action.numAfter > 0),
},
};
};
export default (
state: FetchingState = initialState, // eslint-disable-line default-param-last
action: PerAccountApplicableAction,
): FetchingState => {
switch (action.type) {
case RESET_ACCOUNT_DATA:
return initialState;
// Reset just because `fetching` is server-data metadata, and we're
// resetting the server data it's supposed to apply to
// (`state.narrows`) But really, we should have canceled any
// in-progress message fetches by now; that's #5623. Still, even if
// there is an in-progress fetch, we probably don't want to show loading
// indicators for it in the UI.
// TODO(#5623): Remove reference to #5623.
case REGISTER_COMPLETE:
return initialState;
case MESSAGE_FETCH_START:
return messageFetchStart(state, action);
/**
* The reverse of MESSAGE_FETCH_START, for cleanup.
*/
case MESSAGE_FETCH_ERROR: {
return messageFetchError(state, action);
}
case MESSAGE_FETCH_COMPLETE:
return messageFetchComplete(state, action);
default:
return state;
}
};
```
|
/content/code_sandbox/src/chat/fetchingReducer.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 648
|
```javascript
/* @flow strict-local */
import Immutable from 'immutable';
import {
getFirstMessageId,
getLastMessageId,
getMessagesForNarrow,
getStreamInNarrow,
isNarrowValid,
getShownMessagesForNarrow,
} from '../narrowsSelectors';
import {
HOME_NARROW,
HOME_NARROW_STR,
pm1to1NarrowFromUser,
streamNarrow,
topicNarrow,
MENTIONED_NARROW,
STARRED_NARROW,
pmNarrowFromUsersUnsafe,
keyFromNarrow,
} from '../../utils/narrow';
import { NULL_SUBSCRIPTION } from '../../nullObjects';
import * as eg from '../../__tests__/lib/exampleData';
import { makeMuteState } from '../../mute/__tests__/mute-testlib';
import { UserTopicVisibilityPolicy } from '../../api/modelTypes';
describe('getMessagesForNarrow', () => {
const message = eg.streamMessage({ id: 123 });
const messages = eg.makeMessagesState([message]);
const outboxMessage = eg.streamOutbox({});
test('if no outbox messages returns messages with no change', () => {
const state = eg.reduxState({
narrows: Immutable.Map([[HOME_NARROW_STR, [123]]]),
messages,
outbox: [],
users: [eg.selfUser],
realm: eg.realmState({ user_id: eg.selfUser.user_id, email: eg.selfUser.email }),
});
const result = getMessagesForNarrow(state, HOME_NARROW);
expect(result).toEqual([state.messages.get(123)]);
});
test('combine messages and outbox in same narrow', () => {
const state = eg.reduxState({
narrows: Immutable.Map([[HOME_NARROW_STR, [123]]]),
messages,
outbox: [outboxMessage],
caughtUp: {
[HOME_NARROW_STR]: { older: false, newer: true },
},
users: [eg.selfUser],
realm: eg.realmState({ user_id: eg.selfUser.user_id, email: eg.selfUser.email }),
});
const result = getMessagesForNarrow(state, HOME_NARROW);
expect(result).toEqual([message, outboxMessage]);
});
test('do not combine messages and outbox if not caught up', () => {
const state = eg.reduxState({
narrows: Immutable.Map([[HOME_NARROW_STR, [123]]]),
messages,
outbox: [outboxMessage],
users: [eg.selfUser],
realm: eg.realmState({ user_id: eg.selfUser.user_id, email: eg.selfUser.email }),
});
const result = getMessagesForNarrow(state, HOME_NARROW);
expect(result).toEqual([state.messages.get(123)]);
});
test('do not combine messages and outbox in different narrow', () => {
const state = eg.reduxState({
narrows: Immutable.Map([[keyFromNarrow(pm1to1NarrowFromUser(eg.otherUser)), [123]]]),
messages,
outbox: [outboxMessage],
users: [eg.selfUser],
realm: eg.realmState({ user_id: eg.selfUser.user_id, email: eg.selfUser.email }),
});
const result = getMessagesForNarrow(state, pm1to1NarrowFromUser(eg.otherUser));
expect(result).toEqual([message]);
});
});
/* eslint-disable no-shadow */
describe('getShownMessagesForNarrow', () => {
const stream = eg.stream;
const message = eg.streamMessage();
const subscription = eg.subscription;
const mutedSubscription = { ...subscription, in_home_view: false };
const muteTopic = makeMuteState([[stream, message.subject]]);
const unmuteTopic = makeMuteState([[stream, message.subject, UserTopicVisibilityPolicy.Unmuted]]);
const makeStateGeneral = (message, narrow, extra) =>
eg.reduxStatePlus({
messages: eg.makeMessagesState([message]),
narrows: Immutable.Map([[keyFromNarrow(narrow), [message.id]]]),
...extra,
});
const shownGeneral = (state, narrow) => getShownMessagesForNarrow(state, narrow).length > 0;
describe('HOME_NARROW', () => {
const narrow = HOME_NARROW;
const makeState = extra => makeStateGeneral(message, narrow, extra);
const shown = state => shownGeneral(state, narrow);
test('private message shown', () => {
expect(shown(makeStateGeneral(eg.pmMessage(), narrow))).toEqual(true);
});
test('stream message shown in base case', () => {
expect(shown(makeState())).toEqual(true);
});
test('stream message hidden if not subscribed to stream', () => {
expect(shown(makeState({ subscriptions: [] }))).toEqual(false);
});
test('stream message hidden if stream muted', () => {
expect(shown(makeState({ subscriptions: [mutedSubscription] }))).toEqual(false);
});
test('stream message shown if topic unmuted, even though stream muted', () => {
expect(shown(makeState({ subscriptions: [mutedSubscription], mute: unmuteTopic }))).toEqual(
true,
);
});
test('stream message hidden if topic muted', () => {
expect(shown(makeState({ mute: muteTopic }))).toEqual(false);
});
test('@-mention message is always shown', () => {
const flags = { ...eg.plusReduxState.flags, mentioned: { [message.id]: true } };
expect(shown(makeState({ flags, subscriptions: [] }))).toEqual(true);
expect(shown(makeState({ flags, subscriptions: [mutedSubscription] }))).toEqual(true);
expect(shown(makeState({ flags, mute: muteTopic }))).toEqual(true);
});
});
describe('stream narrow', () => {
const narrow = streamNarrow(stream.stream_id);
const makeState = extra => makeStateGeneral(message, narrow, extra);
const shown = state => shownGeneral(state, narrow);
test('message shown even if not subscribed to stream', () => {
expect(shown(makeState({ subscriptions: [] }))).toEqual(true);
});
test('message shown even if stream muted', () => {
expect(shown(makeState({ subscriptions: [mutedSubscription] }))).toEqual(true);
});
test('message hidden if topic muted', () => {
expect(shown(makeState({ mute: muteTopic }))).toEqual(false);
});
test('@-mention message is always shown', () => {
const flags = { ...eg.plusReduxState.flags, mentioned: { [message.id]: true } };
expect(shown(makeState({ flags, subscriptions: [] }))).toEqual(true);
expect(shown(makeState({ flags, subscriptions: [mutedSubscription] }))).toEqual(true);
expect(shown(makeState({ flags, mute: muteTopic }))).toEqual(true);
});
});
describe('topic narrow', () => {
const narrow = topicNarrow(stream.stream_id, message.subject);
const makeState = extra => makeStateGeneral(message, narrow, extra);
const shown = state => shownGeneral(state, narrow);
test('message shown even if not subscribed to stream', () => {
expect(shown(makeState({ subscriptions: [] }))).toEqual(true);
});
test('message shown even if stream muted', () => {
expect(shown(makeState({ subscriptions: [mutedSubscription] }))).toEqual(true);
});
test('message shown even if topic muted', () => {
expect(shown(makeState({ mute: muteTopic }))).toEqual(true);
});
});
describe('starred-messages narrow', () => {
const narrow = STARRED_NARROW;
const makeState = extra => makeStateGeneral(message, narrow, extra);
const shown = state => shownGeneral(state, narrow);
test('message shown even if not subscribed to stream', () => {
expect(shown(makeState({ subscriptions: [] }))).toEqual(true);
});
test('message shown even if stream muted', () => {
expect(shown(makeState({ subscriptions: [mutedSubscription] }))).toEqual(true);
});
test('message shown even if topic muted', () => {
expect(shown(makeState({ mute: muteTopic }))).toEqual(true);
});
});
describe('@-mentions narrow', () => {
const narrow = MENTIONED_NARROW;
const makeState = extra => makeStateGeneral(message, narrow, extra);
const shown = state => shownGeneral(state, narrow);
test('message shown even if not subscribed to stream', () => {
expect(shown(makeState({ subscriptions: [] }))).toEqual(true);
});
test('message shown even if stream muted', () => {
expect(shown(makeState({ subscriptions: [mutedSubscription] }))).toEqual(true);
});
test('message shown even if topic muted', () => {
expect(shown(makeState({ mute: muteTopic }))).toEqual(true);
});
});
});
describe('getFirstMessageId', () => {
test('return undefined when there are no messages', () => {
const state = eg.reduxState({
narrows: Immutable.Map([[HOME_NARROW_STR, []]]),
outbox: [],
});
const result = getFirstMessageId(state, HOME_NARROW);
expect(result).toEqual(undefined);
});
test('returns first message id', () => {
const state = eg.reduxState({
narrows: Immutable.Map([[HOME_NARROW_STR, [1, 2, 3]]]),
messages: eg.makeMessagesState([
eg.streamMessage({ id: 1 }),
eg.streamMessage({ id: 2 }),
eg.streamMessage({ id: 3 }),
]),
outbox: [],
});
const result = getFirstMessageId(state, HOME_NARROW);
expect(result).toEqual(1);
});
});
describe('getLastMessageId', () => {
test('return undefined when there are no messages', () => {
const state = eg.reduxState({
narrows: Immutable.Map([[HOME_NARROW_STR, []]]),
messages: eg.makeMessagesState([]),
outbox: [],
});
const result = getLastMessageId(state, HOME_NARROW);
expect(result).toEqual(undefined);
});
test('returns last message id', () => {
const state = eg.reduxState({
narrows: Immutable.Map([[HOME_NARROW_STR, [1, 2, 3]]]),
messages: eg.makeMessagesState([
eg.streamMessage({ id: 1 }),
eg.streamMessage({ id: 2 }),
eg.streamMessage({ id: 3 }),
]),
outbox: [],
});
const result = getLastMessageId(state, HOME_NARROW);
expect(result).toEqual(3);
});
});
describe('getStreamInNarrow', () => {
const stream1 = eg.makeStream({ name: 'stream' });
const stream2 = eg.makeStream({ name: 'stream2' });
const stream3 = eg.makeStream({ name: 'stream3' });
const stream4 = eg.makeStream({ name: 'stream4' });
const sub1 = eg.makeSubscription({ stream: stream1, in_home_view: false });
const sub2 = eg.makeSubscription({ stream: stream2, in_home_view: true });
const state = eg.reduxState({
streams: [stream1, stream2, stream3],
subscriptions: [sub1, sub2],
});
test('return subscription if stream in narrow is subscribed', () => {
const narrow = streamNarrow(stream1.stream_id);
expect(getStreamInNarrow(state, narrow)).toEqual(sub1);
});
test('return stream if stream in narrow is not subscribed', () => {
const narrow = streamNarrow(stream3.stream_id);
expect(getStreamInNarrow(state, narrow)).toEqual({ ...stream3, in_home_view: true });
});
test('return NULL_SUBSCRIPTION if stream in narrow is not valid', () => {
const narrow = streamNarrow(stream4.stream_id);
expect(getStreamInNarrow(state, narrow)).toEqual(NULL_SUBSCRIPTION);
});
test('return NULL_SUBSCRIPTION is narrow is not topic or stream', () => {
expect(getStreamInNarrow(state, pm1to1NarrowFromUser(eg.otherUser))).toEqual(NULL_SUBSCRIPTION);
expect(getStreamInNarrow(state, topicNarrow(stream4.stream_id, 'topic'))).toEqual(
NULL_SUBSCRIPTION,
);
});
});
describe('isNarrowValid', () => {
test('narrowing to a special narrow is always valid', () => {
const narrow = STARRED_NARROW;
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(true);
});
test('narrowing to an existing stream is valid', () => {
const narrow = streamNarrow(eg.stream.stream_id);
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(true);
});
test('narrowing to a non-existing stream is invalid', () => {
const narrow = streamNarrow(eg.makeStream().stream_id);
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(false);
});
test('narrowing to an existing stream is valid regardless of topic', () => {
const narrow = topicNarrow(eg.stream.stream_id, 'topic does not matter');
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(true);
});
test('narrowing to a PM with existing user is valid', () => {
const narrow = pm1to1NarrowFromUser(eg.otherUser);
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(true);
});
test('narrowing to a PM with non-existing user is not valid', () => {
const narrow = pm1to1NarrowFromUser(eg.makeUser());
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(false);
});
test('narrowing to a group chat with existing users is valid', () => {
const narrow = pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]);
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(true);
});
test('narrowing to a group chat with non-existing users is not valid', () => {
const narrow = pmNarrowFromUsersUnsafe([eg.otherUser, eg.makeUser()]);
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(false);
});
test('narrowing to a PM with bots is valid', () => {
const narrow = pm1to1NarrowFromUser(eg.crossRealmBot);
expect(isNarrowValid(eg.plusReduxState, narrow)).toBe(true);
});
test('narrowing to non active users is valid', () => {
const notActiveUser = eg.makeUser();
const state = eg.reduxState({ realm: { ...eg.realmState(), nonActiveUsers: [notActiveUser] } });
const narrow = pm1to1NarrowFromUser(notActiveUser);
expect(isNarrowValid(state, narrow)).toBe(true);
});
});
```
|
/content/code_sandbox/src/chat/__tests__/narrowsSelectors-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 3,294
|
```javascript
/* @flow strict-local */
import deepFreeze from 'deep-freeze';
import Immutable from 'immutable';
import narrowsReducer from '../narrowsReducer';
import {
HOME_NARROW,
HOME_NARROW_STR,
pm1to1NarrowFromUser,
ALL_PRIVATE_NARROW_STR,
pmNarrowFromUsersUnsafe,
streamNarrow,
topicNarrow,
STARRED_NARROW_STR,
keyFromNarrow,
SEARCH_NARROW,
} from '../../utils/narrow';
import {
MESSAGE_FETCH_ERROR,
EVENT_MESSAGE_DELETE,
EVENT_UPDATE_MESSAGE_FLAGS,
} from '../../actionConstants';
import { LAST_MESSAGE_ANCHOR, FIRST_UNREAD_ANCHOR } from '../../anchor';
import * as eg from '../../__tests__/lib/exampleData';
describe('narrowsReducer', () => {
const privateNarrowStr = keyFromNarrow(pm1to1NarrowFromUser(eg.otherUser));
const groupNarrowStr = keyFromNarrow(pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]));
const streamNarrowStr = keyFromNarrow(streamNarrow(eg.stream.stream_id));
const egTopic = eg.streamMessage().subject;
const topicNarrowStr = keyFromNarrow(topicNarrow(eg.stream.stream_id, egTopic));
describe('RESET_ACCOUNT_DATA', () => {
const initialState = eg.baseReduxState.narrows;
const action1 = { ...eg.action.message_fetch_complete, messages: [eg.streamMessage()] };
const prevState = narrowsReducer(initialState, action1);
expect(prevState).not.toEqual(initialState);
expect(narrowsReducer(prevState, eg.action.reset_account_data)).toEqual(initialState);
});
describe('REGISTER_COMPLETE', () => {
const initialState = eg.baseReduxState.narrows;
const prevState = narrowsReducer(initialState, {
...eg.action.message_fetch_complete,
messages: [eg.streamMessage()],
});
expect(prevState).not.toEqual(initialState);
expect(narrowsReducer(prevState, eg.action.register_complete)).toEqual(initialState);
});
describe('EVENT_NEW_MESSAGE', () => {
test('if not caught up in narrow, do not add message in home narrow', () => {
const message = eg.streamMessage({ id: 3, flags: [] });
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2]]]);
expect(narrowsReducer(prevState, eg.mkActionEventNewMessage(message))).toEqual(
Immutable.Map([[HOME_NARROW_STR, [1, 2]]]),
);
});
test('appends message to state producing a copy of messages', () => {
const message = eg.streamMessage({ id: 3, flags: [] });
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2]]]);
const newState = narrowsReducer(
prevState,
eg.mkActionEventNewMessage(message, {
caughtUp: { [HOME_NARROW_STR]: { older: false, newer: true } },
}),
);
expect(newState).toEqual(Immutable.Map([[HOME_NARROW_STR, [1, 2, 3]]]));
expect(newState).not.toBe(prevState);
});
test('if new message key does not exist do not create it', () => {
const message = eg.streamMessage({ id: 3, flags: [], stream: eg.makeStream() });
const prevState = Immutable.Map([[topicNarrowStr, [1, 2]]]);
expect(narrowsReducer(prevState, eg.mkActionEventNewMessage(message))).toEqual(
Immutable.Map([[topicNarrowStr, [1, 2]]]),
);
});
});
test('if new message is private or group add it to the "allPrivate" narrow', () => {
const message = eg.pmMessage({
id: 1,
recipients: [eg.selfUser, eg.otherUser, eg.thirdUser],
flags: [],
});
const prevState = Immutable.Map([[ALL_PRIVATE_NARROW_STR, []]]);
expect(
narrowsReducer(
prevState,
eg.mkActionEventNewMessage(message, {
caughtUp: { [ALL_PRIVATE_NARROW_STR]: { older: true, newer: true } },
}),
),
).toEqual(Immutable.Map([[ALL_PRIVATE_NARROW_STR, [1]]]));
});
test('message sent to topic is stored correctly', () => {
const message = eg.streamMessage({ id: 3, flags: [] });
const prevState = Immutable.Map([
[HOME_NARROW_STR, [1, 2]],
[topicNarrowStr, [2]],
]);
expect(
narrowsReducer(
prevState,
eg.mkActionEventNewMessage(message, {
caughtUp: {
[HOME_NARROW_STR]: { older: false, newer: false },
[topicNarrowStr]: { older: false, newer: true },
},
}),
),
).toEqual(
Immutable.Map([
[HOME_NARROW_STR, [1, 2]],
[topicNarrowStr, [2, message.id]],
]),
);
});
test('message sent to self is stored correctly', () => {
const narrowWithSelfStr = keyFromNarrow(pm1to1NarrowFromUser(eg.selfUser));
const message = eg.pmMessage({
id: 1,
sender: eg.selfUser,
recipients: [eg.selfUser],
flags: [],
});
const prevState = Immutable.Map([
[HOME_NARROW_STR, []],
[narrowWithSelfStr, []],
]);
const newState = narrowsReducer(
prevState,
eg.mkActionEventNewMessage(message, {
caughtUp: {
[HOME_NARROW_STR]: { older: false, newer: true },
[narrowWithSelfStr]: { older: false, newer: true },
},
}),
);
expect(newState).toEqual(
Immutable.Map([
[HOME_NARROW_STR, [message.id]],
[narrowWithSelfStr, [message.id]],
]),
);
expect(newState).not.toBe(prevState);
});
test('appends stream message to all cached narrows that match and are caught up', () => {
const message = eg.streamMessage({ id: 5, flags: [] });
const prevState = Immutable.Map([
[HOME_NARROW_STR, [1, 2]],
[ALL_PRIVATE_NARROW_STR, [1, 2]],
[streamNarrowStr, [2, 3]],
[topicNarrowStr, [2, 3]],
[privateNarrowStr, [2, 4]],
[groupNarrowStr, [2, 4]],
]);
const newState = narrowsReducer(
prevState,
eg.mkActionEventNewMessage(message, {
caughtUp: {
[HOME_NARROW_STR]: { older: false, newer: true },
[streamNarrowStr]: { older: false, newer: true },
[topicNarrowStr]: { older: false, newer: true },
},
}),
);
expect(newState).toEqual(
Immutable.Map([
[HOME_NARROW_STR, [1, 2, message.id]],
[ALL_PRIVATE_NARROW_STR, [1, 2]],
[streamNarrowStr, [2, 3, message.id]],
[topicNarrowStr, [2, 3, message.id]],
[privateNarrowStr, [2, 4]],
[groupNarrowStr, [2, 4]],
]),
);
expect(newState).not.toBe(prevState);
});
test('does not append stream message to not cached narrows', () => {
const message = eg.streamMessage({ id: 3, flags: [] });
const prevState = Immutable.Map([[HOME_NARROW_STR, [1]]]);
const newState = narrowsReducer(
prevState,
eg.mkActionEventNewMessage(message, {
caughtUp: { [HOME_NARROW_STR]: { older: false, newer: true } },
}),
);
expect(newState).toEqual(Immutable.Map([[HOME_NARROW_STR, [1, message.id]]]));
expect(newState).not.toBe(prevState);
});
test('appends private message to multiple cached narrows', () => {
const message = eg.pmMessage({
id: 5,
flags: [],
sender: eg.selfUser,
recipients: [eg.selfUser, eg.otherUser],
});
const prevState = Immutable.Map([
[HOME_NARROW_STR, [1, 2]],
[ALL_PRIVATE_NARROW_STR, [1, 2]],
[streamNarrowStr, [2, 3]],
[topicNarrowStr, [2, 3]],
[privateNarrowStr, [2, 4]],
[groupNarrowStr, [2, 4]],
]);
const newState = narrowsReducer(
prevState,
eg.mkActionEventNewMessage(message, {
caughtUp: prevState.map(_ => ({ older: false, newer: true })).toObject(),
}),
);
expect(newState).toEqual(
Immutable.Map([
[HOME_NARROW_STR, [1, 2, message.id]],
[ALL_PRIVATE_NARROW_STR, [1, 2, message.id]],
[streamNarrowStr, [2, 3]],
[topicNarrowStr, [2, 3]],
[privateNarrowStr, [2, 4, message.id]],
[groupNarrowStr, [2, 4]],
]),
);
expect(newState).not.toBe(prevState);
});
describe('EVENT_MESSAGE_DELETE', () => {
test('if a message does not exist no changes are made', () => {
const prevState = Immutable.Map([
[HOME_NARROW_STR, [1, 2]],
[privateNarrowStr, []],
]);
expect(
narrowsReducer(prevState, deepFreeze({ type: EVENT_MESSAGE_DELETE, messageIds: [3] })),
).toBe(prevState);
});
test('if a message exists in one or more narrows delete it from there', () => {
const prevState = Immutable.Map([
[HOME_NARROW_STR, [1, 2, 3]],
[privateNarrowStr, [2]],
]);
expect(
narrowsReducer(prevState, deepFreeze({ type: EVENT_MESSAGE_DELETE, messageIds: [2] })),
).toEqual(
Immutable.Map([
[HOME_NARROW_STR, [1, 3]],
[privateNarrowStr, []],
]),
);
});
test('if multiple messages indicated, delete the ones that exist', () => {
const prevState = Immutable.Map([
[HOME_NARROW_STR, [1, 2, 3]],
[privateNarrowStr, [2]],
]);
expect(
narrowsReducer(
prevState,
deepFreeze({ type: EVENT_MESSAGE_DELETE, messageIds: [2, 3, 4] }),
),
).toEqual(
Immutable.Map([
[HOME_NARROW_STR, [1]],
[privateNarrowStr, []],
]),
);
});
});
describe('MESSAGE_FETCH_START', () => {
test('if fetching for a search narrow, ignore', () => {
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2]]]);
expect(
narrowsReducer(
prevState,
deepFreeze({ ...eg.action.message_fetch_start, narrow: SEARCH_NARROW('some query') }),
),
).toEqual(prevState);
});
});
describe('MESSAGE_FETCH_ERROR', () => {
test('reverses the effect of MESSAGE_FETCH_START as much as possible', () => {
// As of the addition of this test, it's fully possible:
// MESSAGE_FETCH_START applies the identity function to the
// state (i.e., it doesn't do anything to it). Reversing that
// effect is also done with the identity function.
const narrow1 = pm1to1NarrowFromUser(eg.otherUser);
const narrow2 = pm1to1NarrowFromUser(eg.thirdUser);
// Include some other narrow to test that the reducer doesn't go mess
// something up there.
const initialState = Immutable.Map([[keyFromNarrow(narrow1), [1, 2]]]);
expect(
[
deepFreeze({ ...eg.action.message_fetch_start, narrow: narrow2 }),
deepFreeze({ type: MESSAGE_FETCH_ERROR, narrow: narrow2, error: new Error() }),
].reduce(narrowsReducer, initialState),
).toEqual(initialState);
});
});
describe('MESSAGE_FETCH_COMPLETE', () => {
test('if no messages returned still create the key in state', () => {
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2, 3]]]);
expect(
narrowsReducer(prevState, {
...eg.action.message_fetch_complete,
narrow: pm1to1NarrowFromUser(eg.otherUser),
messages: [],
}),
).toEqual(
Immutable.Map([
[HOME_NARROW_STR, [1, 2, 3]],
[keyFromNarrow(pm1to1NarrowFromUser(eg.otherUser)), []],
]),
);
});
test('no duplicate messages', () => {
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2, 3]]]);
const newState = narrowsReducer(prevState, {
...eg.action.message_fetch_complete,
narrow: HOME_NARROW,
anchor: 2,
messages: [
eg.streamMessage({ id: 2 }),
eg.streamMessage({ id: 3 }),
eg.streamMessage({ id: 4 }),
],
});
expect(newState).toEqual(Immutable.Map([[HOME_NARROW_STR, [1, 2, 3, 4]]]));
expect(newState).not.toBe(prevState);
});
test('added messages are sorted by id', () => {
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2]]]);
const newState = narrowsReducer(prevState, {
...eg.action.message_fetch_complete,
narrow: HOME_NARROW,
anchor: 2,
messages: [
eg.streamMessage({ id: 3, timestamp: 2 }),
eg.streamMessage({ id: 4, timestamp: 1 }),
],
});
expect(newState).toEqual(Immutable.Map([[HOME_NARROW_STR, [1, 2, 3, 4]]]));
expect(newState).not.toBe(prevState);
});
test('when anchor is FIRST_UNREAD_ANCHOR previous messages are replaced', () => {
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2]]]);
expect(
narrowsReducer(prevState, {
...eg.action.message_fetch_complete,
narrow: HOME_NARROW,
anchor: FIRST_UNREAD_ANCHOR,
messages: [
eg.streamMessage({ id: 3, timestamp: 2 }),
eg.streamMessage({ id: 4, timestamp: 1 }),
],
}),
).toEqual(Immutable.Map([[HOME_NARROW_STR, [3, 4]]]));
});
test('when anchor is LAST_MESSAGE_ANCHOR previous messages are replaced', () => {
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2]]]);
const action = {
...eg.action.message_fetch_complete,
narrow: HOME_NARROW,
anchor: LAST_MESSAGE_ANCHOR,
messages: [
eg.streamMessage({ id: 3, timestamp: 2 }),
eg.streamMessage({ id: 4, timestamp: 1 }),
],
};
expect(narrowsReducer(prevState, action)).toEqual(Immutable.Map([[HOME_NARROW_STR, [3, 4]]]));
});
test('if fetched messages are from a search narrow, ignore them', () => {
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2]]]);
expect(
narrowsReducer(prevState, {
...eg.action.message_fetch_complete,
narrow: SEARCH_NARROW('some query'),
}),
).toEqual(prevState);
});
});
describe('EVENT_UPDATE_MESSAGE', () => {
const mkAction = args => {
const { messages, ...restArgs } = args;
const message = messages[0];
return eg.mkActionEventUpdateMessage({
message_id: message.id,
message_ids: messages.map(m => m.id),
stream_id: message.stream_id,
orig_subject: message.subject,
...restArgs,
});
};
const mkKey = (stream, topic) =>
topic !== undefined
? keyFromNarrow(topicNarrow(stream.stream_id, topic))
: keyFromNarrow(streamNarrow(stream.stream_id));
const topic1 = 'topic foo';
const topic2 = 'topic bar';
// const message1a = eg.streamMessage({ subject: topic1, id: 1 });
const message1b = eg.streamMessage({ subject: topic1, id: 2 });
// const message1c = eg.streamMessage({ subject: topic1, id: 3 });
// const message2a = eg.streamMessage({ subject: topic2, id: 4 });
test('new topic, same stream', () => {
expect(
narrowsReducer(
Immutable.Map([
[mkKey(eg.stream, topic1), [1, 2, 3]],
[mkKey(eg.stream, topic2), [4]],
[mkKey(eg.stream), [1, 2, 3, 4]],
]),
mkAction({ messages: [message1b], subject: topic2 }),
),
).toEqual(
Immutable.Map([
[mkKey(eg.stream, topic1), [1, 3]], // removed from old topic narrow
// new topic narrow gets cleared
[mkKey(eg.stream), [1, 2, 3, 4]], // stream narrow unchanged
]),
);
});
test('same topic, new stream', () => {
expect(
narrowsReducer(
Immutable.Map([
[mkKey(eg.stream, topic1), [1, 2, 3]],
[mkKey(eg.stream), [1, 2, 3]],
[mkKey(eg.otherStream, topic1), [4]],
[mkKey(eg.otherStream), [4]],
]),
mkAction({ messages: [message1b], new_stream_id: eg.otherStream.stream_id }),
),
).toEqual(
Immutable.Map([
[mkKey(eg.stream, topic1), [1, 3]], // removed from old topic narrow
[mkKey(eg.stream), [1, 3]], // removed from old stream narrow
// new topic narrow and stream narrow both cleared
]),
);
});
// Try to keep these tests corresponding closely to those for the
// caughtUp reducer. (In the future these should really be a single
// sub-reducer.)
});
describe('EVENT_UPDATE_MESSAGE_FLAGS', () => {
const allMessages = eg.makeMessagesState([
eg.streamMessage({ id: 1 }),
eg.streamMessage({ id: 2 }),
eg.streamMessage({ id: 4 }),
]);
test('Do nothing if the is:starred narrow has not been fetched', () => {
const prevState = Immutable.Map([[HOME_NARROW_STR, [1, 2]]]);
expect(
narrowsReducer(
prevState,
deepFreeze({
type: EVENT_UPDATE_MESSAGE_FLAGS,
id: 1,
allMessages,
all: false,
flag: 'starred',
op: 'add',
messages: [4, 2],
}),
),
).toEqual(prevState);
});
test("Do nothing if action.flag is not 'starred'", () => {
const prevState = Immutable.Map([[STARRED_NARROW_STR, [1, 2]]]);
expect(
narrowsReducer(
prevState,
deepFreeze({
type: EVENT_UPDATE_MESSAGE_FLAGS,
id: 1,
all: false,
allMessages,
op: 'add',
messages: [1],
flag: 'read',
}),
),
).toEqual(prevState);
});
test(
'Adds, while maintaining chronological order, '
+ 'newly starred messages to the is:starred narrow',
() => {
const prevState = Immutable.Map([[STARRED_NARROW_STR, [1, 3, 5]]]);
expect(
narrowsReducer(
prevState,
deepFreeze({
type: EVENT_UPDATE_MESSAGE_FLAGS,
id: 1,
allMessages,
all: false,
flag: 'starred',
op: 'add',
messages: [4, 2],
}),
),
).toEqual(Immutable.Map([[STARRED_NARROW_STR, [1, 2, 3, 4, 5]]]));
},
);
test(
'Removes, while maintaining chronological order, '
+ 'newly unstarred messages from the is:starred narrow',
() => {
const prevState = Immutable.Map([[STARRED_NARROW_STR, [1, 2, 3, 4, 5]]]);
expect(
narrowsReducer(
prevState,
deepFreeze({
type: EVENT_UPDATE_MESSAGE_FLAGS,
id: 1,
allMessages,
all: false,
flag: 'starred',
op: 'remove',
messages: [4, 2],
}),
),
).toEqual(Immutable.Map([[STARRED_NARROW_STR, [1, 3, 5]]]));
},
);
});
});
```
|
/content/code_sandbox/src/chat/__tests__/narrowsReducer-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 4,752
|
```javascript
/* @flow strict-local */
import deepFreeze from 'deep-freeze';
import * as eg from '../../__tests__/lib/exampleData';
import fetchingReducer from '../fetchingReducer';
import {
HOME_NARROW,
HOME_NARROW_STR,
streamNarrow,
keyFromNarrow,
SEARCH_NARROW,
} from '../../utils/narrow';
import { MESSAGE_FETCH_START, MESSAGE_FETCH_ERROR } from '../../actionConstants';
import { DEFAULT_FETCHING } from '../fetchingSelectors';
describe('fetchingReducer', () => {
describe('RESET_ACCOUNT_DATA', () => {
const initialState = eg.baseReduxState.fetching;
const action1 = { type: MESSAGE_FETCH_START, narrow: HOME_NARROW, numBefore: 10, numAfter: 10 };
const prevState = fetchingReducer(initialState, action1);
expect(prevState).not.toEqual(initialState);
expect(fetchingReducer(prevState, eg.action.reset_account_data)).toEqual(initialState);
});
test('REGISTER_COMPLETE', () => {
const initialState = eg.baseReduxState.fetching;
const action1 = { type: MESSAGE_FETCH_START, narrow: HOME_NARROW, numBefore: 10, numAfter: 10 };
const prevState = fetchingReducer(initialState, action1);
expect(prevState).not.toEqual(initialState);
expect(fetchingReducer(prevState, eg.action.register_complete)).toEqual(initialState);
});
describe('MESSAGE_FETCH_START', () => {
test('if messages are fetched before or after the corresponding flag is set', () => {
const prevState = deepFreeze({ [HOME_NARROW_STR]: { older: false, newer: false } });
expect(
fetchingReducer(
prevState,
deepFreeze({
type: MESSAGE_FETCH_START,
narrow: HOME_NARROW,
numBefore: 10,
numAfter: 10,
}),
),
).toEqual({ [HOME_NARROW_STR]: { older: true, newer: true } });
});
test('if key for narrow does not exist, it is created and corresponding flags are set', () => {
const narrow = streamNarrow(eg.stream.stream_id);
const prevState = deepFreeze({ [HOME_NARROW_STR]: { older: false, newer: false } });
expect(
fetchingReducer(
prevState,
deepFreeze({ type: MESSAGE_FETCH_START, narrow, numBefore: 10, numAfter: 0 }),
),
).toEqual({
[HOME_NARROW_STR]: { older: false, newer: false },
[keyFromNarrow(narrow)]: { older: true, newer: false },
});
});
test('if fetching for a search narrow, ignore', () => {
const prevState = deepFreeze({ [HOME_NARROW_STR]: { older: false, newer: false } });
expect(
fetchingReducer(
deepFreeze(prevState),
deepFreeze({ ...eg.action.message_fetch_start, narrow: SEARCH_NARROW('some query') }),
),
).toEqual(prevState);
});
});
describe('MESSAGE_FETCH_ERROR', () => {
test('reverses the effect of MESSAGE_FETCH_START as much as possible', () => {
// As of the addition of this test, that means setting
// DEFAULT_FETCHING as the key.
expect(
[
deepFreeze({ ...eg.action.message_fetch_start, narrow: HOME_NARROW }),
deepFreeze({ type: MESSAGE_FETCH_ERROR, narrow: HOME_NARROW, error: new Error() }),
].reduce(fetchingReducer, eg.baseReduxState.fetching),
).toEqual({ [HOME_NARROW_STR]: DEFAULT_FETCHING });
});
});
describe('MESSAGE_FETCH_COMPLETE', () => {
test('sets corresponding fetching flags to false, if messages are received before or after', () => {
const prevState = deepFreeze({ [HOME_NARROW_STR]: { older: true, newer: true } });
expect(
fetchingReducer(prevState, {
...eg.action.message_fetch_complete,
narrow: HOME_NARROW,
numBefore: 10,
numAfter: 0,
}),
).toEqual({ [HOME_NARROW_STR]: { older: false, newer: true } });
});
test('if fetched messages are from a search narrow, ignore them', () => {
const prevState = deepFreeze({ [HOME_NARROW_STR]: { older: true, newer: true } });
expect(
fetchingReducer(
prevState,
deepFreeze({ ...eg.action.message_fetch_complete, narrow: SEARCH_NARROW('some query') }),
),
).toEqual(prevState);
});
});
});
```
|
/content/code_sandbox/src/chat/__tests__/fetchingReducer-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,002
|
```javascript
// @flow strict-local
import autoRehydrate from './autoRehydrate';
import createPersistor from './createPersistor';
import persistStore from './persistStore';
export type { Persistor, Config } from './types';
export { autoRehydrate, createPersistor, persistStore };
```
|
/content/code_sandbox/src/third/redux-persist/index.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 60
|
```javascript
/* @flow strict-local */
import { REHYDRATE } from './constants';
export type Storage = interface {
multiSet(keyValuePairs: Array<Array<string>>): Promise<mixed>,
getItem(key: string): Promise<string | null>,
removeItem(string): Promise<mixed>,
getAllKeys(): Promise<$ReadOnlyArray<string>>,
};
export type Config = {|
+whitelist: $ReadOnlyArray<string>,
+storage: Storage,
+serialize: mixed => string,
+deserialize: string => mixed,
+keyPrefix?: string,
|};
/**
* The action dispatched to rehydrate the store.
*
* This type is "overpromised" in that the type given for the `payload`
* property is impossibly specific -- it allows the code consuming one of
* these actions to make absolutely any assumptions it likes about the
* payload. Put another way, this type makes all kinds of promises about
* the payload.
*
* A more truthful type would be `payload: { ... }`. It's an object with
* whatever data was retrieved from storage, which in particular may be from
* an old version of the app's schema.
*
* TODO find a cleaner way to express this type. A tricky bit is that after
* the migration middleware operates, the rehydrate action that it passes
* through has a more-specific payload type than `{ ... }`: it should
* actually be (a partial version of) the current schema. So that
* more-specific type is what we write down for our reducers to rely on.
*/
export type OverpromisedRehydrateAction = {|
type: typeof REHYDRATE,
payload: empty, // Not really `empty`, but see jsdoc above.
|};
export type Persistor = {
purge: (keys?: $ReadOnlyArray<string>) => void | Promise<mixed>,
pause: () => void,
resume: () => void,
/** Internal to redux-persist; don't call from elsewhere. */
_resetLastWrittenState: () => void,
...
};
```
|
/content/code_sandbox/src/third/redux-persist/types.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 439
|
```javascript
/* @flow strict-local */
import deepFreeze from 'deep-freeze';
import * as eg from '../../__tests__/lib/exampleData';
import flagsReducer from '../flagsReducer';
import { EVENT_UPDATE_MESSAGE_FLAGS } from '../../actionConstants';
describe('flagsReducer', () => {
describe('REGISTER_COMPLETE', () => {
const initialState = eg.baseReduxState.flags;
const prevState = flagsReducer(
initialState,
eg.mkActionEventNewMessage(eg.streamMessage({ flags: ['read', 'starred'] })),
);
expect(prevState).not.toEqual(initialState);
expect(flagsReducer(prevState, eg.action.register_complete)).toEqual(initialState);
});
describe('MESSAGE_FETCH_COMPLETE', () => {
test('flags from all messages are extracted and stored by id', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage({ flags: [] });
const message3 = eg.streamMessage({ flags: ['read'] });
const prevState = eg.plusReduxState.flags;
expect(
flagsReducer(
prevState,
deepFreeze({
...eg.action.message_fetch_complete,
messages: [message1, message2, message3],
}),
),
).toEqual({ ...prevState, read: { [message3.id]: true } });
});
test('when flags for messages already exist in state, do not change state', () => {
const message = eg.streamMessage({ flags: ['read', 'starred'] });
const prevState = {
...eg.plusReduxState.flags,
read: { [message.id]: true },
starred: { [message.id]: true },
};
expect(
flagsReducer(
prevState,
deepFreeze({ ...eg.action.message_fetch_complete, messages: [message] }),
),
).toBe(prevState);
});
});
test('flags are added or replace existing flags', () => {
const message1 = eg.streamMessage({ flags: ['read'] });
const message2 = eg.streamMessage({ flags: [] });
const message3 = eg.streamMessage();
const prevState = deepFreeze({ ...eg.plusReduxState.flags, read: { [message3.id]: true } });
expect(
flagsReducer(
prevState,
deepFreeze({ ...eg.action.message_fetch_complete, messages: [message1, message2] }),
),
).toEqual({ ...prevState, read: { [message1.id]: true, [message3.id]: true } });
});
describe('EVENT_NEW_MESSAGE', () => {
test('adds to store flags from new message', () => {
const message = eg.streamMessage({ flags: ['read'] });
const prevState = eg.plusReduxState.flags;
expect(flagsReducer(prevState, eg.mkActionEventNewMessage(message))).toEqual({
...prevState,
read: { [message.id]: true },
});
});
});
describe('EVENT_UPDATE_MESSAGE_FLAGS', () => {
test('when operation is "add", adds flag to an empty state', () => {
const message = eg.streamMessage();
const prevState = eg.plusReduxState.flags;
expect(
flagsReducer(
prevState,
deepFreeze({
id: 1,
type: EVENT_UPDATE_MESSAGE_FLAGS,
all: false,
allMessages: eg.makeMessagesState([message]),
messages: [message.id],
flag: 'starred',
op: 'add',
}),
),
).toEqual({ ...prevState, starred: { [message.id]: true } });
});
test('if flag already exists, do not duplicate', () => {
const message = eg.streamMessage();
const prevState = deepFreeze({ ...eg.plusReduxState.flags, starred: { [message.id]: true } });
expect(
flagsReducer(
prevState,
deepFreeze({
id: 1,
type: EVENT_UPDATE_MESSAGE_FLAGS,
all: false,
allMessages: eg.makeMessagesState([message]),
messages: [message.id],
flag: 'starred',
op: 'add',
}),
),
).toEqual({ ...prevState, starred: { [message.id]: true } });
});
test('if other flags exist, adds new one to the list', () => {
const message = eg.streamMessage();
const prevState = deepFreeze({ ...eg.plusReduxState.flags, starred: { [message.id]: true } });
expect(
flagsReducer(
prevState,
deepFreeze({
id: 1,
type: EVENT_UPDATE_MESSAGE_FLAGS,
all: false,
allMessages: eg.makeMessagesState([message]),
messages: [message.id],
flag: 'read',
op: 'add',
}),
),
).toEqual({ ...prevState, starred: { [message.id]: true }, read: { [message.id]: true } });
});
test('adds flags for multiple messages', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage();
const message3 = eg.streamMessage();
const prevState = deepFreeze({
...eg.plusReduxState.flags,
read: { [message1.id]: true },
starred: { [message2.id]: true },
});
expect(
flagsReducer(
prevState,
deepFreeze({
id: 1,
type: EVENT_UPDATE_MESSAGE_FLAGS,
all: false,
allMessages: eg.makeMessagesState([message1, message2, message3]),
messages: [message1.id, message2.id, message3.id],
flag: 'starred',
op: 'add',
}),
),
).toEqual({
...prevState,
read: { [message1.id]: true },
starred: { [message1.id]: true, [message2.id]: true, [message3.id]: true },
});
});
test('when operation is "remove" removes a flag from message', () => {
const message = eg.streamMessage();
const prevState = deepFreeze({ ...eg.plusReduxState.flags, read: { [message.id]: true } });
expect(
flagsReducer(
prevState,
deepFreeze({
id: 1,
type: EVENT_UPDATE_MESSAGE_FLAGS,
all: false,
allMessages: eg.makeMessagesState([message]),
messages: [message.id],
flag: 'read',
op: 'remove',
}),
),
).toEqual({ ...prevState, read: {} });
});
test('if flag does not exist, do nothing', () => {
const message = eg.streamMessage();
const prevState = eg.plusReduxState.flags;
expect(
flagsReducer(
prevState,
deepFreeze({
id: 1,
type: EVENT_UPDATE_MESSAGE_FLAGS,
all: false,
allMessages: eg.makeMessagesState([message]),
messages: [message.id],
flag: 'read',
op: 'remove',
}),
),
).toEqual({ ...prevState, read: {} });
});
test('removes flags from multiple messages', () => {
const message1 = eg.streamMessage();
const message2 = eg.streamMessage();
const message3 = eg.streamMessage();
const message4 = eg.streamMessage();
const prevState = deepFreeze({
...eg.plusReduxState.flags,
read: { [message1.id]: true, [message3.id]: true },
starred: { [message1.id]: true, [message3.id]: true },
});
expect(
flagsReducer(
prevState,
deepFreeze({
id: 1,
type: EVENT_UPDATE_MESSAGE_FLAGS,
all: false,
allMessages: eg.makeMessagesState([message1, message2, message3, message4]),
messages: [message1.id, message2.id, message3.id, message4.id],
flag: 'starred',
op: 'remove',
}),
),
).toEqual({ ...prevState, read: { [message1.id]: true, [message3.id]: true }, starred: {} });
});
test('when all=true, flag=read, and op=add, all messages become read; other flags untouched', () => {
const m1 = eg.streamMessage();
const m2 = eg.streamMessage();
const m3 = eg.streamMessage();
const m4 = eg.streamMessage();
const m5 = eg.streamMessage();
const prevState = deepFreeze({
...eg.plusReduxState.flags,
starred: { [m1.id]: true, [m4.id]: true },
read: { [m1.id]: true, [m3.id]: true },
});
expect(
flagsReducer(
prevState,
deepFreeze({
id: 1,
type: EVENT_UPDATE_MESSAGE_FLAGS,
all: true,
allMessages: eg.makeMessagesState([m1, m2, m3, m4, m5]),
messages: [],
flag: 'read',
op: 'add',
}),
),
).toEqual({
...prevState,
read: { [m1.id]: true, [m2.id]: true, [m3.id]: true, [m4.id]: true, [m5.id]: true },
});
});
});
describe('RESET_ACCOUNT_DATA', () => {
test('resets to initial state', () => {
const message = eg.streamMessage();
const prevState = deepFreeze({
read: { [message.id]: true },
starred: { [message.id]: true },
collapsed: { [message.id]: true },
mentioned: { [message.id]: true },
wildcard_mentioned: { [message.id]: true },
has_alert_word: { [message.id]: true },
historical: { [message.id]: true },
});
expect(flagsReducer(prevState, eg.action.reset_account_data)).toEqual(
eg.baseReduxState.flags,
);
});
});
});
```
|
/content/code_sandbox/src/chat/__tests__/flagsReducer-test.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 2,111
|
```javascript
/* @flow strict-local */
import type { Config } from './types';
import { KEY_PREFIX } from './constants';
import * as logging from '../../utils/logging';
import { allSettled } from '../../jsBackport';
export default async function getStoredState(config: Config): Promise<{ ... }> {
const storage = config.storage;
const deserializer = config.deserialize;
const whitelist = config.whitelist;
const keyPrefix = config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX;
let allKeys = undefined;
try {
allKeys = await storage.getAllKeys();
} catch (err) {
logging.warn(err, { message: 'redux-persist/getStoredState: Error in storage.getAllKeys' });
throw err;
}
const persistKeys = allKeys
.filter(key => key.indexOf(keyPrefix) === 0)
.map(key => key.slice(keyPrefix.length));
const keysToRestore = persistKeys.filter(key => whitelist.indexOf(key) !== -1);
const restoredState = {};
await allSettled(
keysToRestore.map(key =>
(async () => {
let serialized = undefined;
try {
serialized = await storage.getItem(createStorageKey(key));
} catch (err) {
logging.warn(err, {
message: 'redux-persist/getStoredState: Error restoring data for a key.',
key,
});
return;
}
if (serialized === null) {
// This shouldn't be possible, but empirically it does happen, so
// we don't use `invariant` here. It may have to do with the janky
// way AsyncStorage stores large values out-of-line in separate
// files on iOS? \_()_/ If so, it will go away when we switch
// to a sound version of AsyncStorage, #4841.
logging.warn('key was found above, should be present here', { key });
return;
}
try {
restoredState[key] = deserializer(serialized);
} catch (err) {
logging.warn(err, {
message: 'redux-persist/getStoredState: Error restoring data for a key.',
key,
});
}
})(),
),
);
return restoredState;
function createStorageKey(key) {
return `${keyPrefix}${key}`;
}
}
```
|
/content/code_sandbox/src/third/redux-persist/getStoredState.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 type { Store } from 'redux';
import { historicalCacheKeys24 } from '../../storage/migrations';
import type { Config, OverpromisedRehydrateAction, Persistor } from './types';
import { REHYDRATE } from './constants';
import getStoredState from './getStoredState';
import createPersistor from './createPersistor';
import { randString } from '../../utils/misc';
export default function persistStore<
// The state type should have a schema version for migrations, like so.
S: { +migrations: { +version?: number }, ... },
A,
// The dispatch type should accept our rehydrate actions.
D: OverpromisedRehydrateAction => mixed,
>(
store: Store<S, A, D>,
config: Config, // = Object.freeze({}),
onComplete?: () => void,
): Persistor {
let purgeKeys = null;
const persistor = createPersistor(store, config);
persistor.pause();
setImmediate(restore);
return {
...persistor,
purge: keys => {
purgeKeys = keys || '*';
return persistor.purge(keys);
},
};
async function restore() {
try {
let restoredState: { ... } = await getStoredState(config);
// do not persist state for purgeKeys
if (purgeKeys) {
if (purgeKeys === '*') {
restoredState = {};
} else {
purgeKeys.forEach(key => delete restoredState[key]);
}
}
// The version (in redux-persist-migrate's terms) that was
// current in the previous session.
//
// Caution: this same expression would give a different
// value if it were run after the `store.dispatch` line,
// because redux-persist-migrate's store enhancer
// `createMigration` mutates `migrations.version` in the
// action's payload (see `realVersionSetter` in
// redux-persist-migrate).
//
// $FlowFixMe[prop-missing] This can indeed be missing; that's why we check
const prevVersion: mixed = restoredState.migrations?.version;
if (typeof prevVersion !== 'number' || prevVersion < 24) {
// Super-powered `dropCache` to clear out corrupted
// (because not-fully-migrated) data from #4458.
// TODO: A proper, non-hacky fix, as Greg describes at
// path_to_url#narrow/stream/243-mobile-team/topic/.23M4458.3A.20.22t.2Eget.20is.20not.20a.20function.22.20on.20state.2Enarrows.20at.20sta.2E.2E.2E/near/1119541.
await persistor.purge(historicalCacheKeys24);
}
// This fixme is how we make the impossible promise in
// OverpromisedRehydrateAction. See that type's jsdoc.
store.dispatch(rehydrateAction((restoredState: $FlowFixMe)));
// The version (in redux-persist-migrate's terms) that is
// current now, after rehydration.
const currentVersion = store.getState().migrations.version;
if (prevVersion !== undefined && prevVersion === currentVersion) {
// Don't persist `REHYDRATE`'s payload unnecessarily.
//
// The state in memory now (after `REHYDRATE` has fired)
// contains no useful information beyond what has already
// been saved to storage, so we can skip saving it back to
// storage. That's because:
//
// (a) The state in memory was empty before `REHYDRATE`
// fired. There wasn't anything interesting there that
// was merged with `REHYDRATE`'s payload. And,
//
// (b) The `REHYDRATE` payload itself came straight (via
// our reviver) from what was saved to storage. It
// would only have changed if at least one migration
// had run, and it hasn't. In this conditional, we
// know that it hasn't because the previous version
// (in redux-persist-migrate's terms) is the same as
// the current version.
//
// Part of the work for preventing the save is already
// done: `.pause()` is called on `persistor` above, and
// `.resume()` is called after. This does mean that
// persisting `REHYDRATE`'s payload isn't triggered
// directly on `REHYDRATE`. However, it is triggered on a
// *subsequent* action, because, upon each action, the
// persistor compares a piece of `lastState` to the
// corresponding piece of `state` to check whether that
// piece needs to be persisted -- and, on an action just
// after `REHYDRATE`, `lastState` is stale, containing the
// pre-`REHYDRATE` state. That's because `lastState`
// doesn't naturally update when the persistor is paused.
//
// So, fix that by still resetting `lastState` with the
// result of `REHYDRATE` when the persistor is paused; we
// can do that because we've exposed `_resetLastWrittenState` on
// the persistor.
persistor._resetLastWrittenState(); // eslint-disable-line no-underscore-dangle
}
} finally {
persistor.resume();
// As mentioned in a comment above, the current strategy of using
// `.pause()` and `.resume()` means that the time at which the
// `REHYDRATE` payload is persisted (if we've asked it to be
// persisted; i.e., if a migration has been done) is not during
// the processing of `REHYDRATE` itself, but rather during the
// processing of the action that immediately follows it. Rather
// than postponing the important task of persisting a migration's
// results until some arbitrary next action fired somewhere in the
// app, fire a next action right here, right now.
//
// TODO: Find a cleaner way of handling this.
store.dispatch(
({
// Include a random string, to be sure no other action type
// matches this one. Like Redux does for the initial action.
type: `PERSIST_DUMMY/${randString()}`,
// The intended param type for `dispatch` would be a union where one
// branch is "any other `type`". There isn't a way to specify that
// without losing the information of what the type looks like for
// known `type`. So just ignore that case.
}: $FlowFixMe),
);
if (onComplete) {
onComplete();
}
}
}
}
function rehydrateAction(payload) {
return {
type: REHYDRATE,
payload,
};
}
```
|
/content/code_sandbox/src/third/redux-persist/persistStore.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,558
|
```javascript
/* @flow strict-local */
export const KEY_PREFIX: string = 'reduxPersist:';
export const REHYDRATE: 'persist/REHYDRATE' = 'persist/REHYDRATE';
```
|
/content/code_sandbox/src/third/redux-persist/constants.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 42
|
```javascript
/* @flow strict-local */
import type { StoreEnhancer, Reducer } from 'redux';
import invariant from 'invariant';
import * as logging from '../../utils/logging';
import { REHYDRATE } from './constants';
import isStatePlainEnough from './utils/isStatePlainEnough';
export default function autoRehydrate<S: { ... }, A: { +type: string, ... }, D>(
config: {|
log?: boolean,
stateReconciler?: empty,
|} = Object.freeze({}),
): StoreEnhancer<S, A, D> {
const stateReconciler = config.stateReconciler || defaultStateReconciler;
// The StoreEnhancer API has an overload that's hard to represent with
// Flow.
return next => (reducer: Reducer<S, A>, initialState: $FlowFixMe, enhancer?: $FlowFixMe) => {
const store = next(liftReducer(reducer), initialState, enhancer);
return {
...store,
replaceReducer: reducer => store.replaceReducer(liftReducer(reducer)),
};
};
function liftReducer(reducer: Reducer<S, A>): Reducer<S, A> {
let rehydrated = false;
const preRehydrateActions = [];
return (state: S | void, action: A): S => {
if (action.type !== REHYDRATE) {
if (config.log === true && !rehydrated) {
// store pre-rehydrate actions for debugging
preRehydrateActions.push(action);
}
return reducer(state, action);
} else {
// This is the REHYDRATE action, not the initial action. The state
// will only ever be undefined before the initial action.
invariant(state, 'expected non-void state');
if (config.log === true && !rehydrated) {
logPreRehydrate(preRehydrateActions);
}
rehydrated = true;
// If type is REHYDRATE, action will have a payload
const inboundState = (action: $FlowFixMe).payload;
const reducedState = reducer(state, action);
return stateReconciler(state, inboundState, reducedState, config.log === true);
}
};
}
}
function logPreRehydrate<A: { +type: string, ... }>(preRehydrateActions: $ReadOnlyArray<A>) {
const concernedActions = preRehydrateActions.slice(1);
if (concernedActions.length > 0) {
logging.warn(
`
redux-persist/autoRehydrate: ${concernedActions.length} actions were fired before rehydration completed. This can be a symptom of a race
condition where the rehydrate action may overwrite the previously affected state. Consider running these actions
after rehydration.
`,
{ concernedActionTypes: concernedActions.map(a => a.type) },
);
}
}
function defaultStateReconciler<S: { ... }>(
state: S,
inboundState: S,
reducedState: S,
log: boolean,
): S {
const newState = { ...reducedState };
Object.keys(inboundState).forEach(key => {
// if initialState does not have key, skip auto rehydration
/* $FlowIgnore[method-unbinding]: This is the standard way to call
`hasOwnProperty`. See discussion:
path_to_url#narrow/stream/243-mobile-team/topic/Flow.20158.20errors/near/1375563
*/
if (!Object.prototype.hasOwnProperty.call(state, key)) {
return;
}
// if initial state is an object but inbound state is null/undefined, skip
if (typeof state[key] === 'object' && !inboundState[key]) {
if (log) {
logging.warn(
'redux-persist/autoRehydrate: sub state for a key is falsy but initial state is an object, skipping autoRehydrate.',
{ key },
);
}
return;
}
// if reducer modifies substate, skip auto rehydration
if (state[key] !== reducedState[key]) {
if (log) {
logging.warn(
'redux-persist/autoRehydrate: sub state for a key modified, skipping autoRehydrate.',
{ key },
);
}
newState[key] = reducedState[key];
return;
}
// otherwise take the inboundState
if (isStatePlainEnough(inboundState[key]) && isStatePlainEnough(state[key])) {
// shallow merge
newState[key] = { ...state[key], ...inboundState[key] };
} else {
// hard set
newState[key] = inboundState[key];
}
});
return newState;
}
```
|
/content/code_sandbox/src/third/redux-persist/autoRehydrate.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 1,010
|
```javascript
/* @flow strict-local */
import invariant from 'invariant';
import * as logging from '../../utils/logging';
import { KEY_PREFIX } from './constants';
import type { Storage } from './types';
export default function purgeStoredState(
config: { +storage: Storage, +keyPrefix?: string, ... },
keys: void | $ReadOnlyArray<string>,
): Promise<mixed> {
const storage = config.storage;
const keyPrefix = config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX;
// basic validation
if (Array.isArray(config)) {
throw new Error(
'redux-persist: purgeStoredState requires config as a first argument (found array). An array of keys is the optional second argument.',
);
}
if (!storage) {
throw new Error('redux-persist: config.storage required in purgeStoredState');
}
if (typeof keys === 'undefined') {
// if keys is not defined, purge all keys
return new Promise((resolve, reject) => {
(async () => {
let err = null;
let allKeys = undefined;
try {
allKeys = await storage.getAllKeys();
} catch (e) {
err = e;
}
if (err) {
logging.warn(err, {
message: 'redux-persist: error during purgeStoredState in storage.getAllKeys',
});
reject(err);
} else {
invariant(allKeys, 'allKeys is truthy');
resolve(
purgeStoredState(
config,
allKeys
.filter(key => key.indexOf(keyPrefix) === 0)
.map(key => key.slice(keyPrefix.length)),
),
);
}
})();
});
} else {
// otherwise purge specified keys
return Promise.all(
keys.map(async key => {
try {
return await storage.removeItem(`${keyPrefix}${key}`);
} catch (err) {
warnIfRemoveError(key)(err);
throw err;
}
}),
);
}
}
function warnIfRemoveError(key) {
return function removeError(err) {
if (err) {
logging.warn(err, { message: 'Error storing data for a key.', key });
}
};
}
```
|
/content/code_sandbox/src/third/redux-persist/purgeStoredState.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 473
|
```javascript
/* @flow strict-local */
export default function isStatePlainEnough(a: mixed): boolean {
// isPlainObject + duck type not immutable
if (a === null) {
return false;
}
if (typeof a !== 'object') {
return false;
}
if (typeof a.asMutable === 'function') {
return false;
}
const proto = Object.getPrototypeOf(a);
return proto === null || Object.getPrototypeOf(proto) === null;
}
```
|
/content/code_sandbox/src/third/redux-persist/utils/isStatePlainEnough.js
|
javascript
| 2016-05-08T05:41:48
| 2024-08-15T07:25:47
|
zulip-mobile
|
zulip/zulip-mobile
| 1,274
| 103
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.