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
```swift import Foundation import UIKit @objc(ZLPConstants) class ZLPConstants: NSObject { // For why we include this, see // path_to_url#exporting-constants @objc static func requiresMainQueueSetup() -> Bool { // UIApplication, which we use in `constantsToExport`, is provided by // UIKit. I think that means we should return `true` here. From the doc // linked above: // > If your module does not require access to UIKit, then you should // > respond to `+ requiresMainQueueSetup` with NO. return true } @objc func constantsToExport() -> [String: Any]! { var result: [String: Any] = [:] result["resourceURL"] = Bundle.main.resourceURL!.absoluteString result["UIApplication.openSettingsURLString"] = UIApplication.openSettingsURLString if #available(iOS 16.0, *) { // New name for the notification-settings URL // path_to_url // TODO(ios-16.0): Remove conditional and fallback for 15.4+. result["UIApplication.openNotificationSettingsURLString"] = UIApplication.openNotificationSettingsURLString } if #available(iOS 15.4, *) { // Old name for the notification-settings URL // path_to_url // TODO(ios-15.4): Remove conditional. result["UIApplicationOpenNotificationSettingsURLString"] = UIApplicationOpenNotificationSettingsURLString } return result } } ```
/content/code_sandbox/ios/ZulipMobile/ZLPConstants.swift
swift
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
335
```unknown [ignore] ; ### From React Native's template app: ; We fork some components by platform .*/*[.]android.js ; Ignore polyfills node_modules/react-native/Libraries/polyfills/.* ; Flow doesn't support platforms .*/Libraries/Utilities/LoadingView.js ; ### Custom ignores .*/ios/Pods/* .*/node_modules/mitt/src/.* .*/node_modules/match-at/lib/.* .*/node_modules/eslint-plugin-jsx-a11y/.* ; path_to_url .*/node_modules/resolve/test/resolver/malformed_package_json/.* .*/node_modules/react-native-tab-view/.* .*/node_modules/react-native-safe-area/.* .*/node_modules/flow-coverage-report/.* .*/node_modules/@snyk/.* ; As of v4.1.1, this package only has TypeScript. That's fine as far as ; running the code goes -- Metro transpiles it -- but this line causes Flow ; to stop looking for types in that TypeScript, and then go and look in our ; libdef. .*/node_modules/react-native-image-picker/.* [untyped] .*/node_modules/@react-native-community/cli/.*/.* ; Our libdef is more complete, as of 2021-08. .*/node_modules/@react-native-async-storage/async-storage.* [include] ; Effectively this line warns Flow that this path might be a symlink ; (because the developer might be using `yarn link` to have this point into ; their zulip.git worktree), and it should watch/inotify at the target. node_modules/@zulip/shared/ node_modules/zulip-markdown-parser/ ; Add more as needed! See also metro.config.js and docs/howto/yarn-link.md . [libs] node_modules/react-native/interface.js node_modules/react-native/flow/ ; If the following files are not explicitly named, Flow ignores them in favor of ; their autogenerated versions in flow-typed/npm. (Contrast commit 6219e5a23, ; where the opposite behavior is exhibited!) flow-typed/@sentry/react-native_v1.x.x.js flow-typed/react-native-url-polyfill_vx.x.x.js flow-typed/expo-screen-orientation_vx.x.x.js ; Explicitly name these so that Flow sees them instead of their ; counterparts in node_modules/react-native: flow-typed/jest_v27.x.x.js [strict] ; These apply only to files where `@flow strict` is enabled. ; See path_to_url . ; from RN deprecated-type nonstrict-import sketchy-null unclear-type unsafe-getters-setters untyped-import untyped-type-import [lints] ; from RN sketchy-null-number=warn sketchy-null-mixed=warn untyped-type-import=warn nonstrict-import=warn deprecated-type=warn unsafe-getters-setters=warn unnecessary-invariant=warn ; ours sketchy-number=error unnecessary-optional-chain=warn implicit-inexact-object=error [options] emoji=true # The main warning is "Unused suppression comment". include_warnings=true munge_underscores=true module.name_mapper='^react-native/\(.*\)$' -> '<PROJECT_ROOT>/node_modules/react-native/\1' module.name_mapper='^@?[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> '<PROJECT_ROOT>/node_modules/react-native/Libraries/Image/RelativeImageStub' # This causes Flow to find our `types/foo/bar.js.flow`, if one exists, # when looking at an import from `foo/bar`. (The `[^.]` is so Flow doesn't # try to apply this to relative imports.) module.name_mapper='^\([^.].*\)$' -> '<PROJECT_ROOT>/types/\0' suppress_type=$FlowIssue suppress_type=$FlowFixMe suppress_type=$FlowFixMeProps suppress_type=$FlowFixMeState module.file_ext=.js module.file_ext=.json module.file_ext=.ios.js ; This is the future of Flow; see ; path_to_url ; But we should anticipate that not all our third-party code acts sensibly ; when this is turned on (e.g., see dfa52ab46). As of turning it on, though, ; we're error-free! exact_by_default=true enums=true [version] ^0.175.1 ```
/content/code_sandbox/.flowconfig
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,030
```unknown <?xml version="1.0" encoding="UTF-8"?> <Workspace version = "1.0"> <FileRef location = "group:ZulipMobile.xcodeproj"> </FileRef> <FileRef location = "group:Pods/Pods.xcodeproj"> </FileRef> </Workspace> ```
/content/code_sandbox/ios/ZulipMobile.xcworkspace/contents.xcworkspacedata
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
77
```unknown <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>NSPrivacyCollectedDataTypes</key> <array/> <key>NSPrivacyAccessedAPITypes</key> <array> <dict> <key>NSPrivacyAccessedAPIType</key> <string>NSPrivacyAccessedAPICategoryFileTimestamp</string> <key>NSPrivacyAccessedAPITypeReasons</key> <array> <string>3B52.1</string> <string>C617.1</string> </array> </dict> <dict> <key>NSPrivacyAccessedAPIType</key> <string>NSPrivacyAccessedAPICategorySystemBootTime</string> <key>NSPrivacyAccessedAPITypeReasons</key> <array> <string>35F9.1</string> </array> </dict> <dict> <key>NSPrivacyAccessedAPIType</key> <string>NSPrivacyAccessedAPICategoryDiskSpace</string> <key>NSPrivacyAccessedAPITypeReasons</key> <array> <string>E174.1</string> <string>85F4.1</string> </array> </dict> <dict> <key>NSPrivacyAccessedAPIType</key> <string>NSPrivacyAccessedAPICategoryUserDefaults</string> <key>NSPrivacyAccessedAPITypeReasons</key> <array> <string>CA92.1</string> </array> </dict> </array> </dict> </plist> ```
/content/code_sandbox/ios/PrivacyInfo.xcprivacy
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
424
```javascript module.exports = { /** * These two were added to the RN template file in * `facebook/react-native@f4d5e8c23` (released in 0.60.5) because of * conflicts with `eslint-config-react-native-community`. We haven't * activated that config (we might, it's #4119), and we haven't * otherwise found a use for these rules; we don't follow them. */ // bracketSpacing: false, // jsxBracketSameLine: true, printWidth: 100, // Changed to "flow" just because Flow claims it's necessary for // formatting Flow enums. Unconfirmedbut it doesn't seem to hurt. Doc: // path_to_url#toc-upgrade-tooling parser: 'flow', singleQuote: true, trailingComma: 'all', arrowParens: 'avoid', }; ```
/content/code_sandbox/.prettierrc.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
202
```javascript /* @flow strict-local */ // React Navigation requires this react-native-gesture-handler import, // as the very first import of this entry-point file. See our #5373. import 'react-native-gesture-handler'; import { AppRegistry } from 'react-native'; import ZulipMobile from './src/ZulipMobile'; AppRegistry.registerComponent('ZulipMobile', () => ZulipMobile); ```
/content/code_sandbox/index.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
86
```objective-c #import "React/RCTBridgeModule.h" // Register the ZLPConstants implementation with React Native, needed // because ZLPConstants is in Swift: // path_to_url#exporting-swift @interface RCT_EXTERN_MODULE(ZLPConstants, NSObject) @end ```
/content/code_sandbox/ios/ZulipMobile/ZLPConstantsBridge.m
objective-c
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
56
```yaml # Our main ESLint config. # Tips for developing on this file: # # * To see what config currently applies, try a command like: # # $ npx eslint --print-config src/types.js | less # # or for a specific rule: # # $ npx eslint --print-config src/types.js | jq '.rules["no-continue"]' # # Especially handy for seeing the default or base setting, when we don't # configure a rule ourselves. # # * A variation to canonicalize the config output for comparison: # # $ npx eslint --print-config src/foo.js | jq . --sorted >/tmp/foo.json # $ npx eslint --print-config src/bar.js | jq . --sorted >/tmp/bar.json # $ git diff --no-index /tmp/{foo,bar}.json parser: "hermes-eslint" extends: - airbnb - plugin:jest/recommended - plugin:react-hooks/recommended - ./tools/formatting.eslintrc.yaml plugins: - jest - ft-flow # - react-native # see commented-out rules config below env: browser: true mocha: true node: true jest: true globals: # true/false means mutable/const __DEV__: false __TEST__: false settings: # This setting is shared by the rules `import/*`. For details, see: # path_to_url#resolvers # path_to_url import/resolver: node: extensions: [.js, .ios.js, .android.js, .json] jest: # Some Jest rules depend on the Jest version. In particular, # "jest/no-deprecated-functions". If we don't provide it here, # that rule will use `process.cwd()` to grab the Jest version # from node_modules. But our VSCode plugin for ESLint seems to # be changing the working directory in a way that interferes # with that, and I haven't found the right value for that # plugin's `eslint.workingDirectories` setting to fix the # problem. Even if I did, though, that'd be one more thing to # document as part of the dev setup, so we might as well fix the # problem here. version: "26" rules: # # ================================================================ # Airbnb rule repeals / adjustments. # # Our settings for a rule supersede Airbnb's, so we duplicate some # of Airbnb's settings where we don't want a full repeal. # # When switching on a Flow-enum value, we want to omit a `default` case # when Flow says the `case`s are exhaustive. See discussion: # path_to_url#discussion_r928049374 default-case: off # When switching on a Flow-enum value, we want to omit a `default` case # when Flow says the `case`s are exhaustive. And if each `case` has a # `return` statement, then any return statement after the `switch` will be # unreachable. This rule would have us write one anyway. See discussion: # path_to_url#discussion_r928049374 consistent-return: off # With hermes-eslint for `parser`, above, this rule can analyze Flow # types. It would fire on global types like $ReadOnly, for which it # doesn't see a declaration. We could find out how to teach the rule that # these types are globally definedor just turn the rule off, because it's # redundant with Flow (specifically `Flow(cannot-resolve-name)`, I think): # path_to_url#issue-1274050123 no-undef: off # path_to_url # Tricky-looking code. These are all sometimes perfectly legitimate. no-bitwise: off no-confusing-arrow: off no-continue: off no-plusplus: off no-nested-ternary: off no-control-regex: off # We prefer `let foo = undefined;` over `let foo;`, not vice versa. # # Sadly there doesn't seem to be a rule to say what we want, but at least # turn off the one that says the opposite. # # See rationale at: # path_to_url#explicit-initializer no-undef-init: off # Allow multiple classes per file. # # It's best to have just one class per file, but there are cases # where it's useful to have some tiny helper React components # declared in the same file as a main component. max-classes-per-file: off # Don't forbid prop spreading (it works fine for us) react/jsx-props-no-spreading: off # Don't enforce linebreaks in curly braces in JSX # # The difference this would make is minor, and leaving this rule off # better aligns with our practices in JS proper (not JSX). react/jsx-curly-newline: off # This rule has a bug that causes annoying irrelevant messages: # path_to_url # The rule isn't important enough to be worth hacking around, # especially now that we have few remaining class components. react/static-property-placement: off # Enforce state initialization style (never in constructor) react/state-in-constructor: - error - never # Airbnb uses four selectors under 'no-restricted-syntax': # # ForInStatement, ForOfStatement, LabeledStatement, WithStatement. # path_to_url#L334. no-restricted-syntax: - error # ForInStatement: We agree to forbid 'for..in' loops. - selector: ForInStatement message: 'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.' # Further to Airbnb's explanation: They're also slightly buggy # in JSC [1], on which react-native is built... and, # surprisingly, their semantics weren't fully nailed down until # as late as 2019-12 [2]. But the above is reason enough. # [1]: path_to_url # [2]: path_to_url # ForOfStatement: We don't agree to forbid 'for..of' loops. # # Airbnb's style guide discourages language-level loops in favor of # array iterations. We don't share this controversial view; see it # expressed at path_to_url # LabeledStatement: We don't agree to forbid labeled statements. # # We don't really use them, but Airbnb's reasoning flows from their # anti-loop position, mentioned above, which we don't share. # WithStatement: Agree to forbid with statements, but not this way. # Instead, ... # ... use ESLint's built-in `no-with` rule to do the same thing more simply. no-with: error # # ================================================================ # Formatting. # # Disable a bunch of rules that should be taken care of by prettier. array-bracket-spacing: off arrow-parens: off brace-style: off comma-dangle: off function-paren-newline: off indent: off lines-between-class-members: off max-len: off no-mixed-operators: off no-multi-spaces: off object-curly-newline: off one-var-declaration-per-line: off quote-props: off # For more formatting rules, see tools/formatting.eslintrc.yaml . # # ================================================================ # Naming. # camelcase: off # Permit dangling underscores in class property names, to denote "private" # fields. (These should be replaced with true private fields per the TC39 # class fields proposal [1], once that's available to us.) # # [1]: path_to_url no-underscore-dangle: ["error", { allowAfterThis: true } ] # Disallow names with double underscores and trailing underscores. id-match: - error - "^_?([a-zA-Z0-9$]+_?)*$" - # Don't apply to property names; see comment on no-underscore-dangle. properties: true # Only apply to declarations, not uses. That way a local override for # a given name only needs to appear once, not at each use. # # The docs (path_to_url say this # only applies to `var`, `function`, and `class` declarations, but in # fact it seems to correctly apply to `const` and other declarations. onlyDeclarations: true # # ================================================================ # Language syntax, operators, control flow. # # Repeal some rather absurd rules that make some code impossible to write in # the most reasonable way. no-else-return: off no-await-in-loop: off # Promise.all is not always desirable prefer-destructuring: - error - AssignmentExpression: {array: false, object: false} no-constant-condition: - error - checkLoops: false # new Promise(r => setTimeout(r, 1000)); # Certain other things could be nice to catch, but see # path_to_url#discussion_r883237343 no-promise-executor-return: off # More noisy than helpful; see # path_to_url#discussion_r883233303 class-methods-use-this: off # Likely-wrong code no-unused-vars: [warn, {vars: local, args: none}] # no-param-reassign seems well-intentioned... but fires on common uses # of Array#reduce. Too noisy. no-param-reassign: off # # ================================================================ # Imports; plugin `import`. # # Issue with Flow enums: # path_to_url # Turn off; seems like this rule's purpose is covered by Flow; discussion: # path_to_url#narrow/stream/243-mobile-team/topic/Flow.20enums/near/1406529 import/named: off # path_to_url import/prefer-default-export: off # Compare these two rules with the override below. import/no-extraneous-dependencies: - error - devDependencies: ['**/__tests__/**/*.js', tools/**] no-restricted-imports: - error - paths: - name: 'react-native' importNames: ['Clipboard'] message: 'Use Clipboard from @react-native-clipboard/clipboard instead.' patterns: - group: ['**/__tests__/**'] - group: ['/react-redux'] message: 'Use our own src/react-redux.js instead.' import/no-cycle: error import/export: off # This is redundant with Flow, and buggy. # # ================================================================ # Jest; plugin `jest`. # # This rule could be useful if it fired only on new instances; but we # don't have a way to do that, and it doesn't make sense to keep these # out of the repo. jest/no-disabled-tests: off # Only using string literals for test names, under the heading # `titleMustBeString`, [1] is silly and should probably not be a # thing [2]. We wish we could get all of this rule except that part. # In fact, it's possible to ignore it *for describe blocks # only* [3], but there are no plans to allow turning it off for # `test` blocks. # # [1] path_to_url # [2] path_to_url # [3] path_to_url jest/valid-title: off # The docs for this rule [1] say that placing an `expect` call # outside a `test` or `it` block (e.g., in a `beforeEach` or # `afterEach`) means that the assertion isn't executed. Empirically, # this seems just wrong [2], and there are a few places where we # want to call `expect` in a `beforeEach` or `afterEach` to assert # that multiple tests in the same file aren't interfering with each # other by leaving bits of state lying around. # # [1] path_to_url # [2] path_to_url#discussion_r489984717 jest/no-standalone-expect: off # # ================================================================ # React; plugin `react`. # # These two are workarounds to suppress no-unused-vars when the parser # doesn't understand JSX. Our parser (hermes-eslint, set above) does, so # they're unnecessary: # path_to_url#issue-1274050123 react/jsx-uses-react: off # path_to_url react/jsx-uses-vars: off # path_to_url react/jsx-filename-extension: off # Like RN upstream, we call the files *.js. react/destructuring-assignment: off # The opposite is often much cleaner. react/no-multi-comp: off # This often just forces making code worse. react/no-unused-prop-types: off # This can be perfectly appropriate. react/default-props-match-prop-types: off # We handle this better with types. react/prop-types: off # We handle this better with types. react/require-default-props: off # We handle this better with types. react/no-unstable-nested-components: - error # Avoid some regressions in clarity: # path_to_url#discussion_r893924345 - allowAsProps: true # These could be good to fix. react/prefer-stateless-function: off react/sort-comp: off # # ================================================================ # React Native; plugin `react-native`. # # This plugin isn't included in the airbnb config, and it doesn't # itself enable any rules by default, so this config is it. # (From the docs as of 2020-03, these are the rules we'd like to use. # Plugin disabled only because the rules are; bring it back when # reviving either of them.) # This is buggy on the `this.styles` pattern. # react-native/no-unused-styles: error # TODO eliminate these and enable. # react-native/no-color-literals: error # # ================================================================ # Flow; plugin `ft-flow`. # # These two are workarounds to suppress no-undef and no-unused-vars, # respectively, when the parser doesn't understand Flow types. Our parser # (hermes-eslint, set above) does, so they're unnecessary: # path_to_url#issue-1274050123 # In fact, linting breaks if I leave define-flow-type on with this parser: # TypeError: globalScope.__defineGeneric is not a function # (See commit message for full error output.) ft-flow/define-flow-type: off # path_to_url#define-flow-type ft-flow/use-flow-type: off # path_to_url#use-flow-type ft-flow/boolean-style: [error, boolean] ft-flow/delimiter-dangle: off ft-flow/no-dupe-keys: error ft-flow/no-primitive-constructor-types: error ft-flow/no-types-missing-file-annotation: error ################# ft-flow/no-weak-types: error # ft-flow/require-parameter-type: error ft-flow/require-readonly-react-props: error # ft-flow/require-return-type: [error, always, {annotateUndefined: never}] ft-flow/require-valid-file-annotation: error ft-flow/semi: [error, always] ft-flow/space-before-generic-bracket: [error, never] ft-flow/space-before-type-colon: [error, never] # For more formatting rules, see tools/formatting.eslintrc.yaml. ft-flow/type-id-match: [error, '^([A-Z][a-z0-9]+)+$'] ft-flow/union-intersection-spacing: [error, always] ft-flow/valid-syntax: warn overrides: # # ================================================================ # Our test suite. - files: ['**/__tests__/**', 'jest/jestSetup.js'] rules: no-restricted-imports: off no-import-assign: off # Jest mocking # # ================================================================ # Third-party code: redux-persist. # # We leave this code in the style we received it in. - files: ['src/third/redux-persist/**'] rules: # function declarations are made (we favor function expressions # with `const`), so these functions may be used above the # declaration because they are hoisted. Don't change them to our # style without addressing this! no-use-before-define: off # a few variables already declared in upper scope; no bugs known # to result from this no-shadow: off # # ================================================================ # Third-party code: react-native. # # We leave this code in the style we received it in. - files: ['src/third/react-native/**'] rules: strict: off import/order: off import/first: off object-curly-spacing: off react/state-in-constructor: off no-unused-vars: off no-case-declarations: off react/jsx-closing-bracket-location: off ```
/content/code_sandbox/.eslintrc.yaml
yaml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,961
```unknown # This should be the only .eslintignore file in our tree. # See apply_eslintignore in tools/test. # These are purely type definitions, no runtime code. Most of them # are third-party code, too, so naturally don't match our style. **/flow-typed/** types/react-intl.js.flow types/@react-native-community/netinfo/** types/@sentry/react-native.js.flow types/expo-web-browser/** types/react-native-webview.js.flow # These are type-tests, made up of code that gets type-checked but # never actually run. They're naturally full of dead code which # ESLint would complain about; and because the code never runs, other # things it might complain about don't really matter anyway. **/__flow-tests__/** ```
/content/code_sandbox/.eslintignore
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
166
```unknown <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>aps-environment</key> <string>development</string> <key>com.apple.developer.applesignin</key> <array> <string>Default</string> </array> </dict> </plist> ```
/content/code_sandbox/ios/ZulipMobile/ZulipMobile.entitlements
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
102
```unknown # Windows users might need to set an absolute path for this. # See path_to_url . script-shell = bash ```
/content/code_sandbox/.npmrc
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
25
```objective-c #import <UIKit/UIKit.h> #import "AppDelegate.h" int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } ```
/content/code_sandbox/ios/ZulipMobile/main.m
objective-c
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
44
```unknown [android] target = Google Inc.:Google APIs:23 [maven_repositories] central = path_to_url ```
/content/code_sandbox/.buckconfig
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
28
```unknown # This should match the iOS Deployment Target # (project > ZulipMobile > Info in Xcode) platform :ios, '14.0' require_relative '../node_modules/expo/scripts/autolinking.rb' require_relative '../node_modules/react-native/scripts/react_native_pods' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' install! 'cocoapods', :deterministic_uuids => false target 'ZulipMobile' do config = use_native_modules! # Flags change depending on the env values. flags = get_default_flags() use_react_native!( :path => config[:reactNativePath], # to enable hermes on iOS, change `false` to `true` and then install pods :hermes_enabled => flags[:hermes_enabled], :fabric_enabled => flags[:fabric_enabled], # An absolute path to your application root. :app_path => "#{Pod::Config.instance.installation_root}/.." ) # Enables Flipper. # # Note that if you have use_frameworks! enabled, Flipper will not work and # you should disable the next line. # Flipper is breaking things with recent Xcode; cut it out (we've never # used it): # path_to_url # use_flipper!() post_install do |installer| react_native_post_install(installer) __apply_Xcode_12_5_M1_post_install_workaround(installer) # Apparently, Xcode 14 newly defaults CODE_SIGNING_ALLOWED to YES, and # that's caused some build errors like # > Signing for "Foo" requires a development team. [] # where for "Foo" we've seen, so far, "EXConstants-EXConstants" and # "React-Core-AccessibilityResources". # # The code for our fix follows the Expo template app # (expo/expo@d970a9ecb) by switching CODE_SIGNING_ALLOWED to NO, # specifically for "resource bundles". The Flutter maintainers give some # helpful analysis ( path_to_url ): # > Bundles can contain resources like images and localization files. # > They are embedded in the framework and should not be codesigned. # > Xcode 14 changed behavior and is erroneously codesigning these. # # There are reports of sporadic App Store Review rejections with # code-signing disabled, though, e.g.: # path_to_url#issuecomment-1258608914 # But some developers had success, and it's plausible that the reported # failures were red herrings. See discussion: # path_to_url#narrow/stream/48-mobile/topic/.22signing.20requires.20development.20team.22.20build.20error/near/1472700 # # In facebook/react-native@967de03f3, React Native v0.71.0-rc.0 applies # the same workaround (in react_native_post_install, which we call # above), except limited to the React-Core pod. So we'll double-process # React-Core, which we expect to be harmless. # # Flutter and React Native's workarounds mention the CocoaPods issue # path_to_url with hope that # CocoaPods will publish a fix. installer.target_installation_results.pod_target_installation_results .each do |pod_name, target_installation_result| target_installation_result.resource_bundle_targets.each do |resource_bundle_target| resource_bundle_target.build_configurations.each do |config| config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO' end end end end use_expo_modules! # If we need to enable use_frameworks!, see the change to # templates/expo-template-bare-minimum/ios/Podfile in # expo/expo@9886c0aaf. # TODO: Find out if use_frameworks! is something you might actually need # to use these days. People are still talking about it (see above), but # also see path_to_url . end ```
/content/code_sandbox/ios/Podfile
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
916
```nix # All our non-NPM dependencies and dev-dependencies, expressed with Nix. # # TODO: Expand this to cover the full Android dev environment, # and everything in tools/. # # If you're using NixOS, this file may be helpful: # * Type `nix-shell` in this directory. # * You'll get a shell with the environment all set up # so that `yarn install` and `tools/test --all` work. # * Also `android-studio`, and from there you can run the # Android emulator and build and run the app: # * Start emulator from Android Studio. # * Run `adb reverse tcp:8081 tcp:8081` in the shell. # * Run `node_modules/.bin/react-native start` in the shell. # * Run the app from Android Studio. # # If you're using any other Linux distro, or macOS, or Windows, see # our setup instructions at `docs/howto/build-run.md`. But possibly # this is a useful reference for some of our dependencies. (Note # that you almost certainly already have the more obscure of these # dependencies already, namely ncurses and the C++ standard library.) # For developing changes to this file, use `nix-shell --pure --run` # to check that the dependencies here are complete, without relying # on things that happen to be in your local environment. E.g.: # # $ nix-shell --pure --run 'yarn && tools/test --all' { pkgs ? import <nixpkgs> {} }: with pkgs; mkShell { nativeBuildInputs = [ nodejs-16_x yarn jdk11 android-studio android-tools # Used by various `tools/` scripts: git jq perl rsync ncurses # Used by Flow (via the `tset` binary) vscode ]; LD_LIBRARY_PATH = lib.makeLibraryPath [ gcc11.cc # Needed by Flow (the one from NPM.) ]; } ```
/content/code_sandbox/shell.nix
nix
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
459
```objective-c #import <React/RCTBridgeDelegate.h> #import <UIKit/UIKit.h> #import <UserNotifications/UNUserNotificationCenter.h> #import <Expo/Expo.h> @interface AppDelegate : EXAppDelegateWrapper <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate> @property (nonatomic, strong) UIWindow *window; @end ```
/content/code_sandbox/ios/ZulipMobile/AppDelegate.h
objective-c
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
66
```objective-c // To use an Objective-C module in a Swift file, first just try importing it // at the top of your Swift file, like so: // // import React.RCTBridgeModule // // If you can't find an import line that Xcode understands, instead try // adding an import line in this file, like so: // // #import <React/RCTBridgeModule.h> // // That should make the module (plus the modules *it* imports, actually) // available in all our project's Swift files, without the Swift files // needing an import line of their own. // // The first approach (an import line in the Swift file) is preferred // because it looks like how imports normally work in Swift. But sometimes // we can't find an import line that works; not sure why. Discussion: // path_to_url#narrow/stream/243-mobile-team/topic/ios.2FZulipMobile-Bridging-Header.2Eh/near/1520435 ```
/content/code_sandbox/ios/ZulipMobile-Bridging-Header.h
objective-c
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
214
```javascript // @format const path = require('path'); // Packages we might apply `yarn link` to. // TODO compute what packages actually *are* under `yarn link` instead. const linkablePackages = [ '@zulip/shared', 'zulip-markdown-parser', // Add more as needed! See also .flowconfig and docs/howto/yarn-link.md . ]; // Most of the complexity here comes from teaching Metro to properly // handle the case where we're using `yarn link` to get packages from // worktrees outside the zulip-mobile tree: e.g., to make // `node_modules/@zulip/shared` be a symlink into a zulip.git worktree. // // Out of the box, Metro (in e.g. the guise of `react-native start`) // breaks in that situation in two ways: // * Imports of modules in those packages fail. // * Once that's fixed, imports *from* modules in those packages, of // modules found in our node_modules, fail. // // In both cases, the symptom is a red-screen error in the (debug) // app, and in Metro a stacktrace under a message saying "Unable to // resolve module [...] does not exist in the Haste module map". /** Absolute path to the directory at the root of the given package. */ const packagePath = packageName => path.dirname(require.resolve(`${packageName}/package.json`)); /** Direct (not transitive) dependencies of the given package. */ const packageDeps = packageName => Object.keys(require(`${packageName}/package.json`).dependencies); // Backport of Object.fromEntries... backported to plain JS from our src/jsBackport.js. function objectFromEntries(entries) { const obj = {}; entries.forEach(entry => { obj[entry[0]] = entry[1]; }); return obj; } // Backport of Array.flatMap. function arrayFlatMap(a, f) { return [].concat(...a.map(f)); } module.exports = { // This causes Metro to even look outside the zulip-mobile tree in // the first place. watchFolders: linkablePackages.map(packagePath), resolver: { // These are to help Metro find modules imported from files found // outside our tree. Without it, Metro tries to resolve them from // the ancestor directories of those files and doesn't look in our // own node_modules. extraNodeModules: objectFromEntries( // @babel/runtime makes the list because our Babel config (?) causes // files like @zulip/shared/lib/typing_status.js to need it, whereas // it's not a dependency of @zulip/shared itself. ['@babel/runtime', ...arrayFlatMap(linkablePackages, packageDeps)].map(name => [ name, packagePath(name), ]), ), }, transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: true, }, }), // Use 'metro-minify-terser' (the default minifier at Metro v0.73.0+, // but we're not there yet) to get the keep_classnames option in the // minifierConfig, below. // TODO(react-native-71): Remove "not there yet" comment, and maybe // leave this unspecified to accept the default. minifierPath: 'metro-minify-terser', minifierConfig: { // Looking at the implementation, it seems that the "minifier config" // is passed straight to the `terser` minifier (thanks to // `minifierPath` being set to 'metro-minify-terser'), so we should // use `terser`'s doc: // path_to_url#minify-options // Don't minify our custom Error class names (for logging's sake) keep_classnames: /Error$/, }, }, }; ```
/content/code_sandbox/metro.config.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
858
```javascript module.exports = (wallaby) => ({ files: ['src/**/*.js', '!src/**/__tests__/*.js'], tests: ['src/**/__tests__/*.js'], env: { type: 'node', runner: 'node', }, testFramework: 'jest', compilers: { 'src/**/*.js': wallaby.compilers.babel(), }, setup: () => wallaby.testFramework.configure({ // path_to_url#config-options // you may just pass `require('./package.json').jest`, if you use it for your Jest config // don't forget to include package.json in the files list in this case }), }); ```
/content/code_sandbox/wallaby.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
147
```objective-c // // UtilManager.h // ZulipMobile // #import <React/RCTBridgeModule.h> @interface UtilManager : NSObject <RCTBridgeModule> @end ```
/content/code_sandbox/ios/ZulipMobile/UtilManager.h
objective-c
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
37
```objective-c #import "React/RCTBridgeModule.h" #import "React/RCTEventEmitter.h" // Register our Swift modules with React Native: // path_to_url#exporting-swift @interface RCT_EXTERN_MODULE(ZLPNotificationsEvents, RCTEventEmitter) @end @interface RCT_EXTERN_MODULE(ZLPNotificationsStatus, NSObject) RCT_EXTERN_METHOD(areNotificationsAuthorized: (RCTPromiseResolveBlock) resolve rejecter: (RCTPromiseRejectBlock) reject ) @end ```
/content/code_sandbox/ios/ZulipMobile/ZLPNotificationsBridge.m
objective-c
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
103
```javascript // This file is seen only by Babel 7, not Babel 6. // There are other semantic differences: see // path_to_url module.exports = { presets: [ 'module:metro-react-native-babel-preset', ], plugins: [ // We can remove this once it's included in // metro-react-native-babel-preset; see // path_to_url It's already in // @babel/reset-env, but that doesn't get used as a base plugin; see a // comment on that issue explaining why. '@babel/plugin-proposal-numeric-separator', // Flow enums: // path_to_url#toc-enable-enums [ '@babel/plugin-syntax-flow', // Required by 'transform-flow-enums': // path_to_url { enums: true } ], 'transform-flow-enums' ], }; ```
/content/code_sandbox/babel.config.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
196
```unknown # This file teaches `git log` and friends the canonical names # and email addresses to use for our contributors. # # For details on the format, see: # path_to_url # # Handy commands for examining or adding to this file: # # # shows all names/emails after mapping, sorted: # $ git shortlog -es | sort -k2 # # # shows raw names/emails, filtered by mapped name: # $ git log --format='%an %ae' --author=$NAME | uniq -c Adithya Vardhan <imadithyavardhan@gmail.com> Adithya Vardhan <imadithyavardhan@gmail.com> <64399555+im-adithya@users.noreply.github.com> Akash Dhiman <akash.d0407@gmail.com> Alicja Raszkowska <malavarena@gmail.com> Alicja Raszkowska <malavarena@gmail.com> <trueskawka@users.noreply.github.com> Anirudh Jain <anirudh.jain@outlook.com> Aswin G <aswinganesh666@gmail.com> Brock Whittaker <brock@zulip.com> <brock@zulipchat.com> Chris Bobbe <cbobbe@zulip.com> <cbobbe@zulipchat.com> Chris Bobbe <cbobbe@zulip.com> <csbobbe@gmail.com> Greg Price <greg@zulip.com> <greg@zulipchat.com> Kunal Gupta <kunall.gupta17@gmail.com> Neeraj Wahi <neeraj.wahi@gmail.com> <nw@dropbox.com> Ray Kraesig <rkraesig@zulip.com> <rkraesig@zulipchat.com> Saket Kumar <saket.singh1410@gmail.com> Saket Kumar <saket.singh1410@gmail.com> <saketkumar95@users.noreply.github.com> Saumya Bhatnagar <saumya.bhatnagar.sb@gmail.com> Tomasz Kolek <tomasz-kolek@o2.pl> <tomasz-kolek@go2.pl> Vishwesh Jainkuniya <jainkuniya@gmail.com> Vishwesh Jainkuniya <jainkuniya@gmail.com> <15ucs161@lnmiit.ac.in> Vishwesh Jainkuniya <jainkuniya@gmail.com> <catchvishwesh@gmail.com> Vishwesh Jainkuniya <jainkuniya@gmail.com> <gitvishwesh@gmail.com> Vishwesh Jainkuniya <jainkuniya@gmail.com> <vishwesh03071998@gmail.com> # The goal when editing this file is to group all of a given person's # contributions together, and under their preferred name and email # address. # # Where possible, to find out what name and email address to use for a # person, we ask them. # # In cases where we have several names or email addresses for one # person and we don't directly know their preferences, we make a guess # based on public information, with the following principles: # # * When making a guess, we always choose from among the names and # email addresses the person has used in the Git history. # # * If the contributions come from the same GitHub account, they're # the same person. # # * Prefer the name or email found in the contributor's GitHub profile # or their chat.zulip.org profile. # # * If one name looks like a full name and another a GitHub username, # prefer the full name. # # * If one email is at users.noreply.github.com, prefer any other. # # * Prefer the name or email the contributor has used more often # most recently. ```
/content/code_sandbox/.mailmap
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
863
```javascript // Modules in `node_modules` which are published in uncompiled form, and // therefore need to be compiled by Babel before Jest can use them. // // These will be used as regexp fragments. const transformModulesWhitelist = [ 'expo-apple-authentication', 'expo-application', 'expo-modules-core', 'expo-sqlite', 'expo-web-browser', 'react-native', '@react-native', // @rnc/async-storage itself is precompiled, but its mock-helper is not '@react-native-async-storage/async-storage', '@react-native-community/push-notification-ios', '@expo/react-native-action-sheet', 'react-navigation', '@sentry/react-native', '@zulip/', ]; // The rest of `node_modules`, however, should not be transformed. We express this // with a negative-lookahead suffix, as suggested in the Jest docs: // // path_to_url#transformignorepatterns-customization // // (This value is correctly a string, not a RegExp.) const transformIgnorePattern = `node_modules/(?!${transformModulesWhitelist.join('|')})`; const projectForPlatform = platform => { if (!['ios', 'android'].includes(platform)) { throw new Error(`Unsupported platform '${platform}'.`); } return { displayName: platform, // Ideally, these would simply be `jest-expo/ios` and // `jest-expo/android`; see // path_to_url#platforms. // These custom presets are a workaround for a bug: // // `jest-expo`'s presets are based on `react-native`'s preset, // which does something messy: it overwrites the global `Promise`. // That's facebook/react-native#29303. Jest doesn't work well with // that; that's facebook/jest#10221. // // So, until one of those is fixed, we use these custom presets to // sandwich the code that replaces `global.Promise` with a fix: // // 1) save `global.Promise` to something else on `global` // 2) let the `react-native` preset do its thing (like mocking RN // libraries) // 3) assign `global.Promise` back to what we saved in step 1 preset: platform === 'ios' ? './jest/presetIos' : './jest/presetAndroid', // // // Config for finding and transforming source code. // testPathIgnorePatterns: ['/node_modules/', '/src/__tests__/lib/', '-testlib.js$'], // When some source file foo.js says `import 'bar'`, Jest looks in the // directories above foo.js for a directory like `node_modules` to find // `bar` in. If foo.js is behind a `yarn link` symlink and outside our // tree, that won't work; so have it look at our node_modules too. moduleDirectories: ['node_modules', '<rootDir>/node_modules'], transform: { '^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js', }, transformIgnorePatterns: [transformIgnorePattern], // // // Config for the runtime test environment. // globals: { __TEST__: true, }, timers: 'fake', globalSetup: './jest/globalSetup.js', setupFiles: [ './jest/globalFetch.js', './node_modules/react-native-gesture-handler/jestSetup.js', ], setupFilesAfterEnv: ['./jest/jestSetup.js', 'jest-extended/all'], }; }; module.exports = { // The substantive difference between these two is whether `foo.ios.js` // or `foo.android.js` is used. In particular that also has the effect // of controlling the value of `Platform.OS`. projects: [projectForPlatform('ios'), projectForPlatform('android')], }; ```
/content/code_sandbox/jest.config.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
856
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>IDEDidComputeMac32BitWarning</key> <true/> </dict> </plist> ```
/content/code_sandbox/ios/ZulipMobile.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
72
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>method</key> <string>app-store</string> <key>destination</key> <string>upload</string> <key>signingStyle</key> <string>manual</string> <key>provisioningProfiles</key> <dict> <key>org.zulip.Zulip</key> <!-- TODO: Try a name that doesn't have to change when we renew --> <string>iOS app distribution 2022</string> </dict> </dict> </plist> ```
/content/code_sandbox/ios/upload.plist
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
167
```javascript /** * See path_to_url * * To print the full config from the React Native CLI, run * `react-native config`. */ module.exports = { /** * See path_to_url * * Currently, we only use this to blacklist some native-code * libraries, per-platform, that we don't want to be linked with * "autolinking". * * For more about "autolinking", see * path_to_url */ dependencies: { 'react-native-vector-icons': { platforms: { // We're using a setup that doesn't involve linking // `VectorIconsPackage` on Android. android: null, }, }, }, }; ```
/content/code_sandbox/react-native.config.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
156
```objective-c // // UtilManager.m // ZulipMobile // #import "UtilManager.h" @implementation UtilManager RCT_EXPORT_MODULE(); RCT_EXPORT_METHOD(randomBase64:(NSUInteger)length resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { NSMutableData *data = [NSMutableData dataWithLength:length]; int ret = SecRandomCopyBytes(kSecRandomDefault, length, [data mutableBytes]); if (ret != 0) { NSError *error = [NSError errorWithDomain:@"zulip" code:ret userInfo:nil]; reject(@"random_failed", @"Could not generate random data", error); } else { resolve([data base64EncodedStringWithOptions:0]); } } @end ```
/content/code_sandbox/ios/ZulipMobile/UtilManager.m
objective-c
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
164
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleDisplayName</key> <string>Zulip</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>27.230</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLName</key> <string>org.zulip.Zulip</string> <key>CFBundleURLSchemes</key> <array> <string>zulip</string> </array> </dict> </array> <key>CFBundleVersion</key> <string>1</string> <key>EXDefaultScreenOrientationMask</key> <string>UIInterfaceOrientationMaskAll</string> <key>ITSAppUsesNonExemptEncryption</key> <false/> <key>LSRequiresIPhoneOS</key> <true/> <key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>localhost</key> <dict> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict> </dict> <key>NSCameraUsageDescription</key> <string>By allowing camera access, you can take photos and send them in Zulip messages.</string> <key>NSLocationWhenInUseUsageDescription</key> <string></string> <key>NSMicrophoneUsageDescription</key> <string>By allowing microphone access, you can take videos and send them in Zulip messages.</string> <key>NSPhotoLibraryAddUsageDescription</key> <string>Save photos you choose from Zulip to your photo library.</string> <key>NSPhotoLibraryUsageDescription</key> <string>Choose photos from your library and send them in Zulip messages.</string> <key>UIAppFonts</key> <array> <string>zulip-icons.ttf</string> <string>Entypo.ttf</string> <string>EvilIcons.ttf</string> <string>FontAwesome.ttf</string> <string>Foundation.ttf</string> <string>Ionicons.ttf</string> <string>Feather.ttf</string> <string>MaterialIcons.ttf</string> <string>Octicons.ttf</string> <string>Zocial.ttf</string> <string>SimpleLineIcons.ttf</string> <string>MaterialCommunityIcons.ttf</string> </array> <key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> </array> <key>UIViewControllerBasedStatusBarAppearance</key> <false/> </dict> </plist> ```
/content/code_sandbox/ios/ZulipMobile/Info.plist
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
991
```xml <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM"> <device id="retina4_7" orientation="portrait" appearance="light"/> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17126"/> <capability name="Named colors" minToolsVersion="9.0"/> <capability name="Safe area layout guides" minToolsVersion="9.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="EHf-IW-A2E"> <objects> <viewController storyboardIdentifier="LaunchScreenViewController" id="01J-lp-oVM" sceneMemberID="viewController"> <view key="view" contentMode="scaleToFill" id="2Zo-eZ-ckx"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/> <viewLayoutGuide key="safeArea" id="yBM-Xp-f8I"/> <color key="backgroundColor" name="Brand"/> </view> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="52.173913043478265" y="375"/> </scene> </scenes> <resources> <namedColor name="Brand"> <color red="0.31764705882352939" green="0.76078431372549016" blue="0.68627450980392157" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> </namedColor> </resources> </document> ```
/content/code_sandbox/ios/ZulipMobile/Base.lproj/LaunchScreen.storyboard
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
520
```json PODS: - boost (1.76.0) - DoubleConversion (1.1.6) - EXAppleAuthentication (4.2.1): - ExpoModulesCore - EXApplication (4.1.0): - ExpoModulesCore - EXConstants (13.1.1): - ExpoModulesCore - EXErrorRecovery (3.1.0): - ExpoModulesCore - EXFileSystem (14.0.0): - ExpoModulesCore - EXFont (10.1.0): - ExpoModulesCore - EXMailComposer (11.2.0): - ExpoModulesCore - Expo (45.0.8): - ExpoModulesCore - ExpoKeepAwake (10.1.1): - ExpoModulesCore - ExpoModulesCore (0.9.2): - React-Core - ReactCommon/turbomodule/core - ExpoWebBrowser (10.2.1): - ExpoModulesCore - EXScreenOrientation (4.2.0): - ExpoModulesCore - React-Core - EXSQLite (10.2.0): - ExpoModulesCore - FBLazyVector (0.68.7) - FBReactNativeSpec (0.68.7): - RCT-Folly (= 2021.06.28.00-v2) - RCTRequired (= 0.68.7) - RCTTypeSafety (= 0.68.7) - React-Core (= 0.68.7) - React-jsi (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - fmt (6.2.1) - glog (0.3.5) - RCT-Folly (2021.06.28.00-v2): - boost - DoubleConversion - fmt (~> 6.2.1) - glog - RCT-Folly/Default (= 2021.06.28.00-v2) - RCT-Folly/Default (2021.06.28.00-v2): - boost - DoubleConversion - fmt (~> 6.2.1) - glog - RCTRequired (0.68.7) - RCTTypeSafety (0.68.7): - FBLazyVector (= 0.68.7) - RCT-Folly (= 2021.06.28.00-v2) - RCTRequired (= 0.68.7) - React-Core (= 0.68.7) - React (0.68.7): - React-Core (= 0.68.7) - React-Core/DevSupport (= 0.68.7) - React-Core/RCTWebSocket (= 0.68.7) - React-RCTActionSheet (= 0.68.7) - React-RCTAnimation (= 0.68.7) - React-RCTBlob (= 0.68.7) - React-RCTImage (= 0.68.7) - React-RCTLinking (= 0.68.7) - React-RCTNetwork (= 0.68.7) - React-RCTSettings (= 0.68.7) - React-RCTText (= 0.68.7) - React-RCTVibration (= 0.68.7) - React-callinvoker (0.68.7) - React-Codegen (0.68.7): - FBReactNativeSpec (= 0.68.7) - RCT-Folly (= 2021.06.28.00-v2) - RCTRequired (= 0.68.7) - RCTTypeSafety (= 0.68.7) - React-Core (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-Core (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default (= 0.68.7) - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/CoreModulesHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/Default (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/DevSupport (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default (= 0.68.7) - React-Core/RCTWebSocket (= 0.68.7) - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-jsinspector (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTActionSheetHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTAnimationHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTBlobHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTImageHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTLinkingHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTNetworkHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTSettingsHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTTextHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTVibrationHeaders (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-Core/RCTWebSocket (0.68.7): - glog - RCT-Folly (= 2021.06.28.00-v2) - React-Core/Default (= 0.68.7) - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-jsiexecutor (= 0.68.7) - React-perflogger (= 0.68.7) - Yoga - React-CoreModules (0.68.7): - RCT-Folly (= 2021.06.28.00-v2) - RCTTypeSafety (= 0.68.7) - React-Codegen (= 0.68.7) - React-Core/CoreModulesHeaders (= 0.68.7) - React-jsi (= 0.68.7) - React-RCTImage (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-cxxreact (0.68.7): - boost (= 1.76.0) - DoubleConversion - glog - RCT-Folly (= 2021.06.28.00-v2) - React-callinvoker (= 0.68.7) - React-jsi (= 0.68.7) - React-jsinspector (= 0.68.7) - React-logger (= 0.68.7) - React-perflogger (= 0.68.7) - React-runtimeexecutor (= 0.68.7) - React-jsi (0.68.7): - boost (= 1.76.0) - DoubleConversion - glog - RCT-Folly (= 2021.06.28.00-v2) - React-jsi/Default (= 0.68.7) - React-jsi/Default (0.68.7): - boost (= 1.76.0) - DoubleConversion - glog - RCT-Folly (= 2021.06.28.00-v2) - React-jsiexecutor (0.68.7): - DoubleConversion - glog - RCT-Folly (= 2021.06.28.00-v2) - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-perflogger (= 0.68.7) - React-jsinspector (0.68.7) - React-logger (0.68.7): - glog - react-native-cameraroll (5.2.4): - React-Core - react-native-document-picker (8.2.2): - React-Core - react-native-image-picker (5.7.0): - React-Core - react-native-netinfo (6.0.0): - React-Core - react-native-photo-view (1.5.3): - React-Core - react-native-safe-area-context (4.9.0): - React-Core - react-native-simple-toast (1.1.4): - React-Core - Toast (~> 4.0.0) - react-native-webview (11.26.1): - React-Core - React-perflogger (0.68.7) - React-RCTActionSheet (0.68.7): - React-Core/RCTActionSheetHeaders (= 0.68.7) - React-RCTAnimation (0.68.7): - RCT-Folly (= 2021.06.28.00-v2) - RCTTypeSafety (= 0.68.7) - React-Codegen (= 0.68.7) - React-Core/RCTAnimationHeaders (= 0.68.7) - React-jsi (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-RCTBlob (0.68.7): - RCT-Folly (= 2021.06.28.00-v2) - React-Codegen (= 0.68.7) - React-Core/RCTBlobHeaders (= 0.68.7) - React-Core/RCTWebSocket (= 0.68.7) - React-jsi (= 0.68.7) - React-RCTNetwork (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-RCTImage (0.68.7): - RCT-Folly (= 2021.06.28.00-v2) - RCTTypeSafety (= 0.68.7) - React-Codegen (= 0.68.7) - React-Core/RCTImageHeaders (= 0.68.7) - React-jsi (= 0.68.7) - React-RCTNetwork (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-RCTLinking (0.68.7): - React-Codegen (= 0.68.7) - React-Core/RCTLinkingHeaders (= 0.68.7) - React-jsi (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-RCTNetwork (0.68.7): - RCT-Folly (= 2021.06.28.00-v2) - RCTTypeSafety (= 0.68.7) - React-Codegen (= 0.68.7) - React-Core/RCTNetworkHeaders (= 0.68.7) - React-jsi (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-RCTSettings (0.68.7): - RCT-Folly (= 2021.06.28.00-v2) - RCTTypeSafety (= 0.68.7) - React-Codegen (= 0.68.7) - React-Core/RCTSettingsHeaders (= 0.68.7) - React-jsi (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-RCTText (0.68.7): - React-Core/RCTTextHeaders (= 0.68.7) - React-RCTVibration (0.68.7): - RCT-Folly (= 2021.06.28.00-v2) - React-Codegen (= 0.68.7) - React-Core/RCTVibrationHeaders (= 0.68.7) - React-jsi (= 0.68.7) - ReactCommon/turbomodule/core (= 0.68.7) - React-runtimeexecutor (0.68.7): - React-jsi (= 0.68.7) - ReactCommon/turbomodule/core (0.68.7): - DoubleConversion - glog - RCT-Folly (= 2021.06.28.00-v2) - React-callinvoker (= 0.68.7) - React-Core (= 0.68.7) - React-cxxreact (= 0.68.7) - React-jsi (= 0.68.7) - React-logger (= 0.68.7) - React-perflogger (= 0.68.7) - rn-fetch-blob (0.11.2): - React-Core - RNCAsyncStorage (1.17.12): - React-Core - RNCClipboard (1.13.2): - React-Core - RNCMaskedView (0.1.11): - React - RNCPushNotificationIOS (1.11.0): - React-Core - RNGestureHandler (2.16.0): - React-Core - RNReanimated (2.2.4): - DoubleConversion - FBLazyVector - FBReactNativeSpec - glog - RCT-Folly - RCTRequired - RCTTypeSafety - React - React-callinvoker - React-Core - React-Core/DevSupport - React-Core/RCTWebSocket - React-CoreModules - React-cxxreact - React-jsi - React-jsiexecutor - React-jsinspector - React-RCTActionSheet - React-RCTAnimation - React-RCTBlob - React-RCTImage - React-RCTLinking - React-RCTNetwork - React-RCTSettings - React-RCTText - React-RCTVibration - ReactCommon/turbomodule/core - Yoga - RNScreens (3.29.0): - React-Core - React-RCTImage - RNSentry (5.20.0): - React-Core - Sentry/HybridSDK (= 8.21.0) - RNVectorIcons (9.2.0): - React-Core - Sentry/HybridSDK (8.21.0): - SentryPrivate (= 8.21.0) - SentryPrivate (8.21.0) - Toast (4.0.0) - Yoga (1.14.0) DEPENDENCIES: - boost (from `../node_modules/react-native/third-party-podspecs/boost.podspec`) - DoubleConversion (from `../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec`) - EXAppleAuthentication (from `../node_modules/expo-apple-authentication/ios`) - EXApplication (from `../node_modules/expo-application/ios`) - EXConstants (from `../node_modules/expo-constants/ios`) - EXErrorRecovery (from `../node_modules/expo-error-recovery/ios`) - EXFileSystem (from `../node_modules/expo-file-system/ios`) - EXFont (from `../node_modules/expo-font/ios`) - EXMailComposer (from `../node_modules/expo-mail-composer/ios`) - Expo (from `../node_modules/expo/ios`) - ExpoKeepAwake (from `../node_modules/expo-keep-awake/ios`) - ExpoModulesCore (from `../node_modules/expo-modules-core/ios`) - ExpoWebBrowser (from `../node_modules/expo-web-browser/ios`) - EXScreenOrientation (from `../node_modules/expo-screen-orientation/ios`) - EXSQLite (from `../node_modules/expo-sqlite/ios`) - FBLazyVector (from `../node_modules/react-native/Libraries/FBLazyVector`) - FBReactNativeSpec (from `../node_modules/react-native/React/FBReactNativeSpec`) - glog (from `../node_modules/react-native/third-party-podspecs/glog.podspec`) - RCT-Folly (from `../node_modules/react-native/third-party-podspecs/RCT-Folly.podspec`) - RCTRequired (from `../node_modules/react-native/Libraries/RCTRequired`) - RCTTypeSafety (from `../node_modules/react-native/Libraries/TypeSafety`) - React (from `../node_modules/react-native/`) - React-callinvoker (from `../node_modules/react-native/ReactCommon/callinvoker`) - React-Codegen (from `build/generated/ios`) - React-Core (from `../node_modules/react-native/`) - React-Core/DevSupport (from `../node_modules/react-native/`) - React-Core/RCTWebSocket (from `../node_modules/react-native/`) - React-CoreModules (from `../node_modules/react-native/React/CoreModules`) - React-cxxreact (from `../node_modules/react-native/ReactCommon/cxxreact`) - React-jsi (from `../node_modules/react-native/ReactCommon/jsi`) - React-jsiexecutor (from `../node_modules/react-native/ReactCommon/jsiexecutor`) - React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`) - React-logger (from `../node_modules/react-native/ReactCommon/logger`) - "react-native-cameraroll (from `../node_modules/@react-native-camera-roll/camera-roll`)" - react-native-document-picker (from `../node_modules/react-native-document-picker`) - react-native-image-picker (from `../node_modules/react-native-image-picker`) - "react-native-netinfo (from `../node_modules/@react-native-community/netinfo`)" - react-native-photo-view (from `../node_modules/react-native-photo-view`) - react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`) - react-native-simple-toast (from `../node_modules/react-native-simple-toast`) - react-native-webview (from `../node_modules/react-native-webview`) - React-perflogger (from `../node_modules/react-native/ReactCommon/reactperflogger`) - React-RCTActionSheet (from `../node_modules/react-native/Libraries/ActionSheetIOS`) - React-RCTAnimation (from `../node_modules/react-native/Libraries/NativeAnimation`) - React-RCTBlob (from `../node_modules/react-native/Libraries/Blob`) - React-RCTImage (from `../node_modules/react-native/Libraries/Image`) - React-RCTLinking (from `../node_modules/react-native/Libraries/LinkingIOS`) - React-RCTNetwork (from `../node_modules/react-native/Libraries/Network`) - React-RCTSettings (from `../node_modules/react-native/Libraries/Settings`) - React-RCTText (from `../node_modules/react-native/Libraries/Text`) - React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`) - React-runtimeexecutor (from `../node_modules/react-native/ReactCommon/runtimeexecutor`) - ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`) - rn-fetch-blob (from `../node_modules/rn-fetch-blob`) - "RNCAsyncStorage (from `../node_modules/@react-native-async-storage/async-storage`)" - "RNCClipboard (from `../node_modules/@react-native-clipboard/clipboard`)" - "RNCMaskedView (from `../node_modules/@react-native-community/masked-view`)" - "RNCPushNotificationIOS (from `../node_modules/@react-native-community/push-notification-ios`)" - RNGestureHandler (from `../node_modules/react-native-gesture-handler`) - RNReanimated (from `../node_modules/react-native-reanimated`) - RNScreens (from `../node_modules/react-native-screens`) - "RNSentry (from `../node_modules/@sentry/react-native`)" - RNVectorIcons (from `../node_modules/react-native-vector-icons`) - Yoga (from `../node_modules/react-native/ReactCommon/yoga`) SPEC REPOS: trunk: - fmt - Sentry - SentryPrivate - Toast EXTERNAL SOURCES: boost: :podspec: "../node_modules/react-native/third-party-podspecs/boost.podspec" DoubleConversion: :podspec: "../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec" EXAppleAuthentication: :path: "../node_modules/expo-apple-authentication/ios" EXApplication: :path: "../node_modules/expo-application/ios" EXConstants: :path: "../node_modules/expo-constants/ios" EXErrorRecovery: :path: "../node_modules/expo-error-recovery/ios" EXFileSystem: :path: "../node_modules/expo-file-system/ios" EXFont: :path: "../node_modules/expo-font/ios" EXMailComposer: :path: "../node_modules/expo-mail-composer/ios" Expo: :path: "../node_modules/expo/ios" ExpoKeepAwake: :path: "../node_modules/expo-keep-awake/ios" ExpoModulesCore: :path: "../node_modules/expo-modules-core/ios" ExpoWebBrowser: :path: "../node_modules/expo-web-browser/ios" EXScreenOrientation: :path: "../node_modules/expo-screen-orientation/ios" EXSQLite: :path: "../node_modules/expo-sqlite/ios" FBLazyVector: :path: "../node_modules/react-native/Libraries/FBLazyVector" FBReactNativeSpec: :path: "../node_modules/react-native/React/FBReactNativeSpec" glog: :podspec: "../node_modules/react-native/third-party-podspecs/glog.podspec" RCT-Folly: :podspec: "../node_modules/react-native/third-party-podspecs/RCT-Folly.podspec" RCTRequired: :path: "../node_modules/react-native/Libraries/RCTRequired" RCTTypeSafety: :path: "../node_modules/react-native/Libraries/TypeSafety" React: :path: "../node_modules/react-native/" React-callinvoker: :path: "../node_modules/react-native/ReactCommon/callinvoker" React-Codegen: :path: build/generated/ios React-Core: :path: "../node_modules/react-native/" React-CoreModules: :path: "../node_modules/react-native/React/CoreModules" React-cxxreact: :path: "../node_modules/react-native/ReactCommon/cxxreact" React-jsi: :path: "../node_modules/react-native/ReactCommon/jsi" React-jsiexecutor: :path: "../node_modules/react-native/ReactCommon/jsiexecutor" React-jsinspector: :path: "../node_modules/react-native/ReactCommon/jsinspector" React-logger: :path: "../node_modules/react-native/ReactCommon/logger" react-native-cameraroll: :path: "../node_modules/@react-native-camera-roll/camera-roll" react-native-document-picker: :path: "../node_modules/react-native-document-picker" react-native-image-picker: :path: "../node_modules/react-native-image-picker" react-native-netinfo: :path: "../node_modules/@react-native-community/netinfo" react-native-photo-view: :path: "../node_modules/react-native-photo-view" react-native-safe-area-context: :path: "../node_modules/react-native-safe-area-context" react-native-simple-toast: :path: "../node_modules/react-native-simple-toast" react-native-webview: :path: "../node_modules/react-native-webview" React-perflogger: :path: "../node_modules/react-native/ReactCommon/reactperflogger" React-RCTActionSheet: :path: "../node_modules/react-native/Libraries/ActionSheetIOS" React-RCTAnimation: :path: "../node_modules/react-native/Libraries/NativeAnimation" React-RCTBlob: :path: "../node_modules/react-native/Libraries/Blob" React-RCTImage: :path: "../node_modules/react-native/Libraries/Image" React-RCTLinking: :path: "../node_modules/react-native/Libraries/LinkingIOS" React-RCTNetwork: :path: "../node_modules/react-native/Libraries/Network" React-RCTSettings: :path: "../node_modules/react-native/Libraries/Settings" React-RCTText: :path: "../node_modules/react-native/Libraries/Text" React-RCTVibration: :path: "../node_modules/react-native/Libraries/Vibration" React-runtimeexecutor: :path: "../node_modules/react-native/ReactCommon/runtimeexecutor" ReactCommon: :path: "../node_modules/react-native/ReactCommon" rn-fetch-blob: :path: "../node_modules/rn-fetch-blob" RNCAsyncStorage: :path: "../node_modules/@react-native-async-storage/async-storage" RNCClipboard: :path: "../node_modules/@react-native-clipboard/clipboard" RNCMaskedView: :path: "../node_modules/@react-native-community/masked-view" RNCPushNotificationIOS: :path: "../node_modules/@react-native-community/push-notification-ios" RNGestureHandler: :path: "../node_modules/react-native-gesture-handler" RNReanimated: :path: "../node_modules/react-native-reanimated" RNScreens: :path: "../node_modules/react-native-screens" RNSentry: :path: "../node_modules/@sentry/react-native" RNVectorIcons: :path: "../node_modules/react-native-vector-icons" Yoga: :path: "../node_modules/react-native/ReactCommon/yoga" SPEC CHECKSUMS: boost: a7c83b31436843459a1961bfd74b96033dc77234 DoubleConversion: 831926d9b8bf8166fd87886c4abab286c2422662 EXAppleAuthentication: 709a807fe7f48ac6986a2ceed206ee6a8baf28df EXApplication: d6562af1204162e0ac46d341a7d4e5dc720b33de EXConstants: fdbe52259365b6a6faaa5e99a3b82cfa6bc2eb61 EXErrorRecovery: 3ce46e5d42e53c0371ff048a7f0cbc959968ef4a EXFileSystem: 2aa2d9289f84bca9532b9ccbd81504fa31eb1ded EXFont: 04235cc22e6fef86028feb67db452978dc6f240f EXMailComposer: 2e5fdf265f3a1d5d5ef03724ce361cdedb0f546f Expo: 1133eaf0e12dc265ac82a256f3815401b7570f96 ExpoKeepAwake: c0c494b442ecd8122974c13b93ccfb57bd408e88 ExpoModulesCore: e4278a668e8c13c0269ed8b8a4200989deea2973 ExpoWebBrowser: 4b5f9633e5f169dc948587cb6d26d2d1d1406187 EXScreenOrientation: e3c072fb0add472a3037482ea43ccbade9b88a25 EXSQLite: 2b9accd925438293f9f39e0a57a08cca13bdffb2 FBLazyVector: 63b89dc85804d5817261f56dc4cfb43a9b6d57f5 FBReactNativeSpec: 1fa200a9862d9369a53b6fddbbfcdc22bab24062 fmt: ff9d55029c625d3757ed641535fd4a75fedc7ce9 glog: 476ee3e89abb49e07f822b48323c51c57124b572 RCT-Folly: 4d8508a426467c48885f1151029bc15fa5d7b3b8 RCTRequired: 530916cd48c5f7cf1fc16966ad5ea01638ca4799 RCTTypeSafety: 5fb4cb3080efd582e5563c3e9a0e459fc51396c5 React: 097b19fbc7aecb3bd23de54b462d2051d7ca8a38 React-callinvoker: 4f118545cf884f0d8fce5bcd6e1847147ea9cc05 React-Codegen: 24e59be16f8ed24b3e49e5ff0738dad91988c760 React-Core: 0b464d0bec18dde90fa819c4be14dbcbdbf3077f React-CoreModules: 9bb7d5d5530d474cf8514e2dc8274af82a0bcf2f React-cxxreact: 027e192b8008ba5c200163ab6ded55d134c839d5 React-jsi: 9019a0a0b42e9eac6c1e8c251a8dffe65055a2f1 React-jsiexecutor: 7c0bd030a84f2ec446fb104b7735af2f5ed11eea React-jsinspector: cab4d37ebde480f84c79ac89568abbf76b916c3e React-logger: b75b80500ea80457b2cf169427d66de986cdcb29 react-native-cameraroll: cb752fda6d5268f1646b4390bd5be1f27706b9a0 react-native-document-picker: cd4d6b36a5207ad7a9e599ebb9eb0c2e84fa0b87 react-native-image-picker: 3269f75c251cdcd61ab51b911dd30d6fff8c6169 react-native-netinfo: e849fc21ca2f4128a5726c801a82fc6f4a6db50d react-native-photo-view: ea0ec91bf5991a6843e740b1f47ab355171c996c react-native-safe-area-context: b97eb6f9e3b7f437806c2ce5983f479f8eb5de4b react-native-simple-toast: 8ee5d23f0b92b935ab7434cdb65159ce12dfb4b7 react-native-webview: 9f111dfbcfc826084d6c507f569e5e03342ee1c1 React-perflogger: 44436b315d757100a53dfb1ab6b77c58cb646d7d React-RCTActionSheet: 1888a229684762c40cc96c7ff4716f809655dc09 React-RCTAnimation: f05da175751867521d14b02ab4d3994a7b96f131 React-RCTBlob: 792b966e48d599383d7a0753f75e8f2ff71be1ce React-RCTImage: 065cf66546f625295efd36bce3a1806a9b93399c React-RCTLinking: 8246290c072bd2d1f336792038d7ec4b91f9847a React-RCTNetwork: 6b2331c74684fae61b1ef38f4510fe5da3de3f3a React-RCTSettings: 2898e15b249b085f8b8c7401cfab71983a2d40da React-RCTText: bd1da1cd805e0765e3ba9089a9fd807d4860a901 React-RCTVibration: 2a4bf853281d4981ab471509102300d3c9e6c693 React-runtimeexecutor: 18932e685b4893be88d1efc18f5f8ca1c9cd39d8 ReactCommon: 29bb6fad3242e30e9d049bc9d592736fa3da9e50 rn-fetch-blob: f525a73a78df9ed5d35e67ea65e79d53c15255bc RNCAsyncStorage: 09fc8595e6d6f6d5abf16b23a56b257d9c6b7c5b RNCClipboard: 60fed4b71560d7bfe40e9d35dea9762b024da86d RNCMaskedView: 0e1bc4bfa8365eba5fbbb71e07fbdc0555249489 RNCPushNotificationIOS: 64218f3c776c03d7408284a819b2abfda1834bc8 RNGestureHandler: 998887f1b2c6098ffa2506402087c0e8ef5d69a1 RNReanimated: e7d8afaf8fed4b3bf1a46e06adb2e04a2b248f1c RNScreens: fa9b582d85ae5d62c91c66003b5278458fed7aaa RNSentry: f30463ce11af9cfec0dde79265d29e10c3b902d7 RNVectorIcons: fcc2f6cb32f5735b586e66d14103a74ce6ad61f8 Sentry: ebc12276bd17613a114ab359074096b6b3725203 SentryPrivate: d651efb234cf385ec9a1cdd3eff94b5e78a0e0fe Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 Yoga: 0bc4b37c3b8a345336ff601e2cf7d9704bab7e93 PODFILE CHECKSUM: fe17e730c08576abd6133867554e6cb03f685fee COCOAPODS: 1.15.2 ```
/content/code_sandbox/ios/Podfile.lock
json
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
9,005
```unknown <?xml version="1.0" encoding="UTF-8"?> <Scheme LastUpgradeVersion = "1250" version = "1.3"> <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES"> <BuildActionEntries> <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "ZulipMobile.app" BlueprintName = "ZulipMobile" ReferencedContainer = "container:ZulipMobile.xcodeproj"> </BuildableReference> </BuildActionEntry> </BuildActionEntries> </BuildAction> <TestAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "ZulipMobile.app" BlueprintName = "ZulipMobile" ReferencedContainer = "container:ZulipMobile.xcodeproj"> </BuildableReference> </MacroExpansion> <Testables> </Testables> </TestAction> <LaunchAction buildConfiguration = "Release" selectedDebuggerIdentifier = "" selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "ZulipMobile.app" BlueprintName = "ZulipMobile" ReferencedContainer = "container:ZulipMobile.xcodeproj"> </BuildableReference> </BuildableProductRunnable> <EnvironmentVariables> <EnvironmentVariable key = "OS_ACTIVITY_MODE" value = "disable" isEnabled = "YES"> </EnvironmentVariable> </EnvironmentVariables> </LaunchAction> <ProfileAction buildConfiguration = "Release" shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES"> <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "ZulipMobile.app" BlueprintName = "ZulipMobile" ReferencedContainer = "container:ZulipMobile.xcodeproj"> </BuildableReference> </BuildableProductRunnable> </ProfileAction> <AnalyzeAction buildConfiguration = "Debug"> </AnalyzeAction> <ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES"> </ArchiveAction> </Scheme> ```
/content/code_sandbox/ios/ZulipMobile.xcodeproj/xcshareddata/xcschemes/ZulipMobile release-mode.xcscheme
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
808
```unknown <?xml version="1.0" encoding="UTF-8"?> <Scheme LastUpgradeVersion = "1250" version = "1.3"> <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES"> <BuildActionEntries> <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "ZulipMobile.app" BlueprintName = "ZulipMobile" ReferencedContainer = "container:ZulipMobile.xcodeproj"> </BuildableReference> </BuildActionEntry> </BuildActionEntries> </BuildAction> <TestAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "ZulipMobile.app" BlueprintName = "ZulipMobile" ReferencedContainer = "container:ZulipMobile.xcodeproj"> </BuildableReference> </MacroExpansion> <Testables> </Testables> </TestAction> <LaunchAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "ZulipMobile.app" BlueprintName = "ZulipMobile" ReferencedContainer = "container:ZulipMobile.xcodeproj"> </BuildableReference> </BuildableProductRunnable> <EnvironmentVariables> <EnvironmentVariable key = "OS_ACTIVITY_MODE" value = "disable" isEnabled = "YES"> </EnvironmentVariable> </EnvironmentVariables> </LaunchAction> <ProfileAction buildConfiguration = "Release" shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES"> <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "13B07F861A680F5B00A75B9A" BuildableName = "ZulipMobile.app" BlueprintName = "ZulipMobile" ReferencedContainer = "container:ZulipMobile.xcodeproj"> </BuildableReference> </BuildableProductRunnable> </ProfileAction> <AnalyzeAction buildConfiguration = "Debug"> </AnalyzeAction> <ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES"> </ArchiveAction> </Scheme> ```
/content/code_sandbox/ios/ZulipMobile.xcodeproj/xcshareddata/xcschemes/ZulipMobile.xcscheme
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
816
```unknown #!/usr/bin/env bash set -euo pipefail this_dir=${BASH_SOURCE[0]%/*} . "${this_dir}"/lib/ensure-coreutils.sh root_dir=$(readlink -f "${this_dir}"/..) exec "${root_dir}"/android/gradlew -p "${root_dir}"/android "$@" ```
/content/code_sandbox/tools/gradle
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
71
```unknown #!/usr/bin/env node // TODO: Type-check this file // Sadly our auto-format doesn't seem to run eslint on this file; give in to // Prettier here. // TODO: debug /* eslint-disable operator-linebreak */ const fs = require('fs'); const path = require('path'); const { namedTypes: n, visit } = require('ast-types'); const flowParser = require('flow-parser'); const { parse } = require('recast'); const messages_en = require('../static/translations/messages_en.json'); /** * Make a list of files that might contain UI strings, by recursing in src/. */ function getPossibleUiStringFilePaths() { const result = []; const kSrcDirName = 'src/'; function walk(dir, _dirName = '') { let dirent; // eslint-disable-next-line no-cond-assign while ((dirent = dir.readSync())) { // To reduce false negatives, `continue` when nothing in `dirent` can // cause UI strings to appear in the app. if (dirent.isFile()) { if (!dirent.name.endsWith('.js')) { // Non-JS code, and Flow type definitions in .js.flow files. continue; } result.push(path.join(kSrcDirName, _dirName, dirent.name)); } else if (dirent.isDirectory()) { const subdirName = path.join(_dirName, dirent.name); // e.g., /__tests__ and /__flow-tests__ if (subdirName.endsWith('tests__')) { // Test code. continue; } walk(fs.opendirSync(path.join(kSrcDirName, subdirName)), subdirName); } else { // Something we don't expect to find under src/, probably containing // no UI strings. (symlinks? fifos, sockets, devices??) continue; } } } walk(fs.opendirSync(kSrcDirName)); return result; } const parseOptions = { parser: { parse(src) { return flowParser.parse(src, { // Comments can't cause UI strings to appear in the app; ignore them. all_comments: false, comments: false, // We use Flow enums; the parser shouldn't crash on them. enums: true, // Set `tokens: true` just to work around a mysterious error. // // From the doc for this option: // // > include a list of all parsed tokens in a top-level tokens // > property // // We don't actually want this list of tokens. String literals do // get represented in the list, but as tokens, i.e., meaningful // chunks of the literal source code. They come with surrounding // quotes, escape syntax, etc: // // 'doesn\'t' // "doesn't" // // What we really want is the *value* of a string literal: // // doesn't // // and we get that from the AST. // // Anyway, we set `true` for this because otherwise I've been seeing // `parse` throw an error: // // Error: Line 72: Invalid regular expression: missing / // // TODO: Debug and/or file an issue upstream. tokens: true, }); }, }, }; /** * Look at all given files and collect all strings that might be UI strings. * * The result will include non-UI strings because we can't realistically * filter them all out. That means, when the caller checks messages_en * against these strings, it could get false negatives: perhaps messages_en * has a string 'message-empty' (why would it, though), and that string * won't be flagged because it appears as an enum value in ComposeBox. * * To reduce these false negatives, we filter out low-hanging fruit, like * the string 'foo' in `import Foo from 'foo'`. */ function getPossibleUiStrings(possibleUiStringFilePaths) { const result = new Set(); possibleUiStringFilePaths.forEach(filePath => { const source = fs.readFileSync(filePath).toString(); const ast = parse(source, parseOptions); visit(ast, { // Find nodes with type "Literal" in the AST. /* eslint-disable no-shadow */ visitLiteral(path) { const { value } = path.value; if ( // (Non-string literals include numbers, booleans, etc.) typeof value === 'string' && // This string isn't like 'react' in `import React from 'react'`. !n.ImportDeclaration.check(path.parent.value) ) { result.add(value); } // A literal is always a leaf, right? No need to call this.traverse. return false; }, // Find nodes with type "TemplateLiteral" in the AST. We sometimes use // template literals in UI strings for readability. /* eslint-disable no-shadow */ visitTemplateLiteral(path) { if ( // Translatable UI strings are unlikely to contain // sub-expressions. // // Also, if a template literal has nontrivial sub-expressions, we // can't reasonably interpret them here anyway. path.value.quasis.length === 1 && path.value.expressions.length === 0 ) { result.add(path.value.quasis[0].value.cooked); } return this.traverse(path); }, }); }); return result; } function main() { let didError = false; // We use a convention where a message's ID matches its value; a mismatch // is probably accidental. const mismatchedMessageEntries = Object.entries(messages_en).filter( ([messageId, message]) => messageId !== message, ); if (mismatchedMessageEntries.length > 0) { console.error( 'Each message in static/translations/messages_en.json should match its ID, but some do not:', ); console.error(mismatchedMessageEntries); didError = true; } // Mobile's style is to use curly quotes. They look nicer, but also: since // v3, react-intl uses the single straight quote as an escape character: // path_to_url#features const messagesWithStraightQuotes = Object.values(messages_en).filter(message => /['"]/.test(message), ); if (messagesWithStraightQuotes.length > 0) { console.error( 'Found messages in static/translations/messages_en.json that have straight quotes. Please use smart quotes: and .', ); console.error(messagesWithStraightQuotes); didError = true; } const possibleUiStrings = getPossibleUiStrings(getPossibleUiStringFilePaths()); // Check each key ("message ID" in formatjs's lingo) against // possibleUiStrings, and make a list of any that aren't found. const danglingMessageIds = Object.keys(messages_en).filter( messageId => !possibleUiStrings.has(messageId), ); if (danglingMessageIds.length > 0) { console.error( "Found message IDs in static/translations/messages_en.json that don't seem to be used in the app:", ); console.error(danglingMessageIds); didError = true; } if (didError) { process.exit(1); } } main(); ```
/content/code_sandbox/tools/check-messages-en
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,600
```unknown #!/usr/bin/env bash set -e ## CLI PARSING usage() { cat >&2 <<EOF usage: tools/ios {build | upload} Build the app for release on iOS, or upload the result to the App Store. EOF exit 2 } action= case "${1}" in build|upload) action="${1}"; shift;; *) usage;; esac if (( ${#} )); then usage fi ## EXECUTION rootdir=$(git rev-parse --show-toplevel) cd "${rootdir}"/ios archive_path="${rootdir}"/ios/build/ZulipMobile.xcarchive # These two steps "build" and "upload" are logically part of a single # sequence: when all goes well, we invariably follow each "build" with # one "upload". (As described in docs/howto/release.md .) # # They're separate because sometimes things do not go well, and in # particular sometimes "upload" fails for transient reasons. And the # "build" step is slow, so when retrying and/or debugging the upload, # it's very helpful to reuse the build output. do_build() { yarn echo >&2 mkdir -p build logfile="$(mktemp build/log.XXXX)" echo >&2 "Logs going to: ${logfile}" echo >&2 echo >&2 "Archiving (i.e. building)..." xcodebuild \ >"${logfile}" 2>&1 \ -workspace ZulipMobile.xcworkspace \ -scheme ZulipMobile \ archive \ -archivePath "${archive_path}" \ USE_SENTRY=YES } do_upload() { echo >&2 "Uploading..." xcodebuild \ -exportArchive \ -archivePath "${archive_path}" \ -allowProvisioningUpdates \ -exportOptionsPlist upload.plist } case "${action}" in build) do_build ;; upload) do_upload ;; esac ```
/content/code_sandbox/tools/ios
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
439
```unknown #!/usr/bin/env bash set -eu run_visibly () { set -x "$@" { set +x; } 2>&- } THIS_DIR=${BASH_SOURCE[0]%/*} . "${THIS_DIR}"/lib/ensure-coreutils.sh ROOT_DIR=$(readlink -f "${THIS_DIR}"/..) cd "${ROOT_DIR}" # These steps are based on observing `react-native run-android` # with a command `strace -eexecve -f react-native run-android`. run_visibly tools/gradle -q :app:installDebug "$@" devices=( $(run_visibly adb devices | perl -0ne 'print "$_\n" for (/^(\S+) \s+ device$/gmx)') ) if ! (( ${#devices[@]} )); then echo >&2 "No devices connected!" exit 1 fi for device in "${devices[@]}"; do run_visibly adb -s "${device}" reverse tcp:8081 tcp:8081 # This is the part that `react-native run-android` doesn't have the # option to do correctly: even when you pass a --main-activity flag, # it appends that value to the app ID. So it's impossible to specify # the correct activity when its name doesn't begin with the full app ID. run_visibly adb -s "${device}" shell \ am start -n com.zulipmobile.debug/com.zulipmobile.MainActivity done ```
/content/code_sandbox/tools/run-android
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
323
```unknown #!/usr/bin/env bash set -e root_dir=$(git rev-parse --show-toplevel) this_dir=${BASH_SOURCE[0]%/*} . "${this_dir}"/lib/eslintignore.sh ## CLI PARSING usage() { cat >&2 <<EOF usage: tools/fmt [--all] Options: --all Run on all files (default: only files changed in this branch, as found by \`tools/git changed-files\`.) EOF exit 2 } all= while (( $# )); do case "$1" in --all) all=1; shift;; *) usage;; esac done ## EXECUTION cd "$(git rev-parse --show-toplevel)" PATH=node_modules/.bin:"$PATH" if [ -z "$all" ]; then candidates=( $(tools/git changed-files "$(tools/git base)" -- 'src/*.js') ) else candidates=( 'src/**/*.js' ) fi files=( $(apply_eslintignore "${candidates[@]}" ) ) prettier-eslint \ --write \ --eslint-config-path "${root_dir}"/tools/formatting.eslintrc.yaml \ --log-level=warn \ "${files[@]}" eslint --no-eslintrc -c tools/formatting.eslintrc.yaml --fix "${files[@]}" ```
/content/code_sandbox/tools/fmt
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
285
```unknown // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 54; objects = { /* Begin PBXBuildFile section */ 13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.mm */; }; 13B07FBF1A68108700A75B9A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Assets.xcassets */; }; 13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; 42689E9C23466FF7007540AA /* webview in Resources */ = {isa = PBXBuildFile; fileRef = 42689E9B23466FF7007540AA /* webview */; }; 8B40B9F327F7AEEC00D33897 /* zulip-icons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 3787526927F5503200B81DB8 /* zulip-icons.ttf */; }; 8B44AB3E295B7601003D41A8 /* ZLPConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B44AB3A295B7263003D41A8 /* ZLPConstants.swift */; }; 8B44AB40295B7D4D003D41A8 /* ZLPConstantsBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B44AB3F295B7D45003D41A8 /* ZLPConstantsBridge.m */; }; 8BD55E9B295CB7A10091C181 /* ZLPNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BD55E9A295CB61E0091C181 /* ZLPNotifications.swift */; }; 8BD55E9C295CB7A10091C181 /* ZLPNotificationsBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BD55E99295CB61E0091C181 /* ZLPNotificationsBridge.m */; }; 8BDD410B2BD1C8F80030774C /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 8BDD410A2BD1C8F80030774C /* PrivacyInfo.xcprivacy */; }; 8BE55043253A2B6600B0BC8A /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8BE55041253A2B6600B0BC8A /* LaunchScreen.storyboard */; }; A148FEFC1E9D8CB900479280 /* zulip.mp3 in Resources */ = {isa = PBXBuildFile; fileRef = A148FEFB1E9D8CB900479280 /* zulip.mp3 */; }; A65C1ECEE03CA6692FC807AA /* ExpoModulesProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2C68E38F2AA306A2C56A4B3 /* ExpoModulesProvider.swift */; }; C091D09FD11FDDB8E939257D /* libPods-ZulipMobile.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 74F3CD22CB932FA7EEE0BB66 /* libPods-ZulipMobile.a */; }; CFA67D201EC23BCB0070048E /* UtilManager.m in Sources */ = {isa = PBXBuildFile; fileRef = CFA67D1F1EC23BCB0070048E /* UtilManager.m */; }; ED297163215061F000B7C4FE /* JavaScriptCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED297162215061F000B7C4FE /* JavaScriptCore.framework */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 13B07F961A680F5B00A75B9A /* ZulipMobile.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ZulipMobile.app; sourceTree = BUILT_PRODUCTS_DIR; }; 13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = ZulipMobile/AppDelegate.h; sourceTree = "<group>"; }; 13B07FB01A68108700A75B9A /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = ZulipMobile/AppDelegate.mm; sourceTree = "<group>"; }; 13B07FB51A68108700A75B9A /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = ZulipMobile/Assets.xcassets; sourceTree = "<group>"; }; 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = ZulipMobile/Info.plist; sourceTree = "<group>"; }; 13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = ZulipMobile/main.m; sourceTree = "<group>"; }; 2C68A2E34977F3A580059AC7 /* Pods-ZulipMobile.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ZulipMobile.release.xcconfig"; path = "Target Support Files/Pods-ZulipMobile/Pods-ZulipMobile.release.xcconfig"; sourceTree = "<group>"; }; 3787526927F5503200B81DB8 /* zulip-icons.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; name = "zulip-icons.ttf"; path = "../static/assets/fonts/zulip-icons.ttf"; sourceTree = "<group>"; }; 3C4249EC1EF6E16500D245F1 /* ZulipMobile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; name = ZulipMobile.entitlements; path = ZulipMobile/ZulipMobile.entitlements; sourceTree = "<group>"; }; 42689E9B23466FF7007540AA /* webview */ = {isa = PBXFileReference; lastKnownFileType = folder; path = webview; sourceTree = "<group>"; }; 66E34CC6219226D10091B852 /* ZulipMobile-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "ZulipMobile-Bridging-Header.h"; sourceTree = "<group>"; }; 74F3CD22CB932FA7EEE0BB66 /* libPods-ZulipMobile.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ZulipMobile.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 8B44AB3A295B7263003D41A8 /* ZLPConstants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ZLPConstants.swift; path = ZulipMobile/ZLPConstants.swift; sourceTree = "<group>"; }; 8B44AB3F295B7D45003D41A8 /* ZLPConstantsBridge.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = ZLPConstantsBridge.m; path = ZulipMobile/ZLPConstantsBridge.m; sourceTree = "<group>"; }; 8BD55E99295CB61E0091C181 /* ZLPNotificationsBridge.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = ZLPNotificationsBridge.m; path = ZulipMobile/ZLPNotificationsBridge.m; sourceTree = "<group>"; }; 8BD55E9A295CB61E0091C181 /* ZLPNotifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ZLPNotifications.swift; path = ZulipMobile/ZLPNotifications.swift; sourceTree = "<group>"; }; 8BDD410A2BD1C8F80030774C /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; }; 8BE55042253A2B6600B0BC8A /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = ZulipMobile/Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; }; A148FEFB1E9D8CB900479280 /* zulip.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; path = zulip.mp3; sourceTree = "<group>"; }; CFA67D1F1EC23BCB0070048E /* UtilManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = UtilManager.m; path = ZulipMobile/UtilManager.m; sourceTree = "<group>"; }; CFA67D211EC23BDD0070048E /* UtilManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = UtilManager.h; path = ZulipMobile/UtilManager.h; sourceTree = "<group>"; }; ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; }; F2C68E38F2AA306A2C56A4B3 /* ExpoModulesProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExpoModulesProvider.swift; path = "Pods/Target Support Files/Pods-ZulipMobile/ExpoModulesProvider.swift"; sourceTree = "<group>"; }; FB0511DD408657240F6D4EA3 /* Pods-ZulipMobile.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ZulipMobile.debug.xcconfig"; path = "Target Support Files/Pods-ZulipMobile/Pods-ZulipMobile.debug.xcconfig"; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 13B07F8C1A680F5B00A75B9A /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ED297163215061F000B7C4FE /* JavaScriptCore.framework in Frameworks */, C091D09FD11FDDB8E939257D /* libPods-ZulipMobile.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 13B07FAE1A68108700A75B9A /* ZulipMobile */ = { isa = PBXGroup; children = ( 8BD55E9A295CB61E0091C181 /* ZLPNotifications.swift */, 8BD55E99295CB61E0091C181 /* ZLPNotificationsBridge.m */, 8B44AB3F295B7D45003D41A8 /* ZLPConstantsBridge.m */, 8B44AB3A295B7263003D41A8 /* ZLPConstants.swift */, 3C4249EC1EF6E16500D245F1 /* ZulipMobile.entitlements */, 13B07FAF1A68108700A75B9A /* AppDelegate.h */, 13B07FB01A68108700A75B9A /* AppDelegate.mm */, 13B07FB51A68108700A75B9A /* Assets.xcassets */, 13B07FB61A68108700A75B9A /* Info.plist */, 3787526927F5503200B81DB8 /* zulip-icons.ttf */, 13B07FB71A68108700A75B9A /* main.m */, CFA67D1F1EC23BCB0070048E /* UtilManager.m */, CFA67D211EC23BDD0070048E /* UtilManager.h */, 66E34CC6219226D10091B852 /* ZulipMobile-Bridging-Header.h */, 8BE55041253A2B6600B0BC8A /* LaunchScreen.storyboard */, ); name = ZulipMobile; sourceTree = "<group>"; }; 35C857DE057BA42A6919FBE9 /* Frameworks */ = { isa = PBXGroup; children = ( ED297162215061F000B7C4FE /* JavaScriptCore.framework */, 74F3CD22CB932FA7EEE0BB66 /* libPods-ZulipMobile.a */, ); name = Frameworks; sourceTree = "<group>"; }; 55810A95684B8D7A1251DAB2 /* ExpoModulesProviders */ = { isa = PBXGroup; children = ( C957E4090AA7A6389ABA170C /* ZulipMobile */, ); name = ExpoModulesProviders; sourceTree = "<group>"; }; 832341AE1AAA6A7D00B99B32 /* Libraries */ = { isa = PBXGroup; children = ( ); name = Libraries; sourceTree = "<group>"; }; 83CBB9F61A601CBA00E9B192 = { isa = PBXGroup; children = ( 8BDD410A2BD1C8F80030774C /* PrivacyInfo.xcprivacy */, 42689E9B23466FF7007540AA /* webview */, A148FEFB1E9D8CB900479280 /* zulip.mp3 */, 13B07FAE1A68108700A75B9A /* ZulipMobile */, 832341AE1AAA6A7D00B99B32 /* Libraries */, 83CBBA001A601CBA00E9B192 /* Products */, F9E946BE712842C5A02C7F51 /* Resources */, 35C857DE057BA42A6919FBE9 /* Frameworks */, A1FC272D1F75F05200546415 /* Recovered References */, F8C26711A6226C32E43092A9 /* Pods */, 55810A95684B8D7A1251DAB2 /* ExpoModulesProviders */, ); indentWidth = 2; sourceTree = "<group>"; tabWidth = 2; }; 83CBBA001A601CBA00E9B192 /* Products */ = { isa = PBXGroup; children = ( 13B07F961A680F5B00A75B9A /* ZulipMobile.app */, ); name = Products; sourceTree = "<group>"; }; A1FC272D1F75F05200546415 /* Recovered References */ = { isa = PBXGroup; children = ( ); name = "Recovered References"; sourceTree = "<group>"; }; C957E4090AA7A6389ABA170C /* ZulipMobile */ = { isa = PBXGroup; children = ( F2C68E38F2AA306A2C56A4B3 /* ExpoModulesProvider.swift */, ); name = ZulipMobile; sourceTree = "<group>"; }; F8C26711A6226C32E43092A9 /* Pods */ = { isa = PBXGroup; children = ( FB0511DD408657240F6D4EA3 /* Pods-ZulipMobile.debug.xcconfig */, 2C68A2E34977F3A580059AC7 /* Pods-ZulipMobile.release.xcconfig */, ); path = Pods; sourceTree = "<group>"; }; F9E946BE712842C5A02C7F51 /* Resources */ = { isa = PBXGroup; children = ( ); name = Resources; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 13B07F861A680F5B00A75B9A /* ZulipMobile */ = { isa = PBXNativeTarget; buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "ZulipMobile" */; buildPhases = ( 52F8B8FD88489D79CA92AA16 /* [CP] Check Pods Manifest.lock */, 8BC51697242D4EF80019892C /* Start Metro */, 13B07F871A680F5B00A75B9A /* Sources */, 13B07F8C1A680F5B00A75B9A /* Frameworks */, CF6CFE0C1E7DC27200F687C7 /* Run Script: tools/build-webview */, 13B07F8E1A680F5B00A75B9A /* Resources */, 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */, 6FD412E618344A7FB938E4AC /* Upload Debug Symbols to Sentry */, B6911BDB8DAEAAB45D9600A4 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( ); name = ZulipMobile; productName = "Hello World"; productReference = 13B07F961A680F5B00A75B9A /* ZulipMobile.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 83CBB9F71A601CBA00E9B192 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 1250; TargetAttributes = { 13B07F861A680F5B00A75B9A = { DevelopmentTeam = 66KHCWMEYB; LastSwiftMigration = 1010; ProvisioningStyle = Automatic; SystemCapabilities = { com.apple.BackgroundModes = { enabled = 1; }; com.apple.Push = { enabled = 1; }; }; }; }; }; buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "ZulipMobile" */; compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 83CBB9F61A601CBA00E9B192; productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 13B07F861A680F5B00A75B9A /* ZulipMobile */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 13B07F8E1A680F5B00A75B9A /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 8BDD410B2BD1C8F80030774C /* PrivacyInfo.xcprivacy in Resources */, 8B40B9F327F7AEEC00D33897 /* zulip-icons.ttf in Resources */, 42689E9C23466FF7007540AA /* webview in Resources */, 13B07FBF1A68108700A75B9A /* Assets.xcassets in Resources */, A148FEFC1E9D8CB900479280 /* zulip.mp3 in Resources */, 8BE55043253A2B6600B0BC8A /* LaunchScreen.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Bundle React Native code and images"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "if [[ $USE_SENTRY != \"YES\" ]]; then\necho [Bundle React Native code and images] Skipping sentry\n../node_modules/react-native/scripts/react-native-xcode.sh\nelse\nexport SENTRY_PROPERTIES=sentry.properties\nexport EXTRA_PACKAGER_ARGS=\"--sourcemap-output $DERIVED_FILE_DIR/main.jsbundle.map\"\nexport NODE_BINARY=node\n../node_modules/@sentry/cli/bin/sentry-cli react-native xcode ../node_modules/react-native/scripts/react-native-xcode.sh\nfi\n"; }; 52F8B8FD88489D79CA92AA16 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-ZulipMobile-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; 6FD412E618344A7FB938E4AC /* Upload Debug Symbols to Sentry */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Upload Debug Symbols to Sentry"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "if [[ $USE_SENTRY != \"YES\" ]]; then\necho [Upload Debug Symbols to Sentry] Skipping sentry\nelse\nexport SENTRY_PROPERTIES=sentry.properties\n\n[[ $SENTRY_INCLUDE_NATIVE_SOURCES == \"true\" ]] && INCLUDE_SOURCES_FLAG=\"--include-sources\" || INCLUDE_SOURCES_FLAG=\"\"\nSENTRY_CLI=\"../node_modules/@sentry/cli/bin/sentry-cli\"\n$SENTRY_CLI debug-files upload \"$INCLUDE_SOURCES_FLAG\" \"$DWARF_DSYM_FOLDER_PATH\"\nfi\n"; }; 8BC51697242D4EF80019892C /* Start Metro */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( ); name = "Start Metro"; outputFileListPaths = ( ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "export RCT_METRO_PORT=\"${RCT_METRO_PORT:=8081}\"\necho \"export RCT_METRO_PORT=${RCT_METRO_PORT}\" > \"${SRCROOT}/../node_modules/react-native/scripts/.packager.env\"\nif [ -z \"${RCT_NO_LAUNCH_PACKAGER+xxx}\" ] ; then\n if nc -w 5 -z localhost ${RCT_METRO_PORT} ; then\n if ! curl -s \"path_to_url{RCT_METRO_PORT}/status\" | grep -q \"packager-status:running\" ; then\n echo \"Port ${RCT_METRO_PORT} already in use, packager is either not running or not running correctly\"\n exit 2\n fi\n else\n open \"$SRCROOT/../node_modules/react-native/scripts/launchPackager.command\" || echo \"Can't start packager automatically\"\n fi\nfi\n"; }; B6911BDB8DAEAAB45D9600A4 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-ZulipMobile/Pods-ZulipMobile-resources-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Copy Pods Resources"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-ZulipMobile/Pods-ZulipMobile-resources-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-ZulipMobile/Pods-ZulipMobile-resources.sh\"\n"; showEnvVarsInLog = 0; }; CF6CFE0C1E7DC27200F687C7 /* Run Script: tools/build-webview */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Run Script: tools/build-webview"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/bash; shellScript = "exec $SRCROOT/../tools/build-webview ios --check-path-name --destination $SRCROOT/webview\n# See this script, or src/webview/static/README.md, for more information.\n"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 13B07F871A680F5B00A75B9A /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( CFA67D201EC23BCB0070048E /* UtilManager.m in Sources */, 8B44AB3E295B7601003D41A8 /* ZLPConstants.swift in Sources */, 8B44AB40295B7D4D003D41A8 /* ZLPConstantsBridge.m in Sources */, 8BD55E9B295CB7A10091C181 /* ZLPNotifications.swift in Sources */, 8BD55E9C295CB7A10091C181 /* ZLPNotificationsBridge.m in Sources */, 13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */, 13B07FC11A68108700A75B9A /* main.m in Sources */, A65C1ECEE03CA6692FC807AA /* ExpoModulesProvider.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ 8BE55041253A2B6600B0BC8A /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( 8BE55042253A2B6600B0BC8A /* Base */, ); name = LaunchScreen.storyboard; sourceTree = "<group>"; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 13B07F941A680F5B00A75B9A /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = FB0511DD408657240F6D4EA3 /* Pods-ZulipMobile.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZulipMobile/ZulipMobile.entitlements; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEVELOPMENT_TEAM = 66KHCWMEYB; FRAMEWORK_SEARCH_PATHS = "$(inherited)"; HEADER_SEARCH_PATHS = "$(inherited)"; INFOPLIST_FILE = ZulipMobile/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", "-lc++", ); OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG"; PRODUCT_BUNDLE_IDENTIFIER = org.zulip.Zulip; PRODUCT_NAME = ZulipMobile; PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OBJC_BRIDGING_HEADER = "ZulipMobile-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = "1,2"; USE_SENTRY = NO; }; name = Debug; }; 13B07F951A680F5B00A75B9A /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 2C68A2E34977F3A580059AC7 /* Pods-ZulipMobile.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ZulipMobile/ZulipMobile.entitlements; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEVELOPMENT_TEAM = 66KHCWMEYB; FRAMEWORK_SEARCH_PATHS = "$(inherited)"; HEADER_SEARCH_PATHS = "$(inherited)"; INFOPLIST_FILE = ZulipMobile/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", "-lc++", ); OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE"; PRODUCT_BUNDLE_IDENTIFIER = org.zulip.Zulip; PRODUCT_NAME = ZulipMobile; PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OBJC_BRIDGING_HEADER = "ZulipMobile-Bridging-Header.h"; SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = "1,2"; USE_SENTRY = NO; }; name = Release; }; 83CBBA201A601CBA00E9B192 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "c++17"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = ""; IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( /usr/lib/swift, "$(inherited)", ); MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-DFOLLY_NO_CONFIG", "-DFOLLY_MOBILE=1", "-DFOLLY_USE_LIBCPP=1", ); PRODUCT_BUNDLE_IDENTIFIER = org.zulip.ZulipMobile; SDKROOT = iphoneos; }; name = Debug; }; 83CBBA211A601CBA00E9B192 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "c++17"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = ""; IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( /usr/lib/swift, "$(inherited)", ); MTL_ENABLE_DEBUG_INFO = NO; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-DFOLLY_NO_CONFIG", "-DFOLLY_MOBILE=1", "-DFOLLY_USE_LIBCPP=1", ); PRODUCT_BUNDLE_IDENTIFIER = org.zulip.ZulipMobile; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "ZulipMobile" */ = { isa = XCConfigurationList; buildConfigurations = ( 13B07F941A680F5B00A75B9A /* Debug */, 13B07F951A680F5B00A75B9A /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "ZulipMobile" */ = { isa = XCConfigurationList; buildConfigurations = ( 83CBBA201A601CBA00E9B192 /* Debug */, 83CBBA211A601CBA00E9B192 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */; } ```
/content/code_sandbox/ios/ZulipMobile.xcodeproj/project.pbxproj
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
9,195
```unknown #!/usr/bin/env bash shopt -s globstar this_file=$(readlink -f "$0") rootdir=${this_file%/*/*} bindir=$rootdir/node_modules/.bin import_pairs() { "$bindir"/flow get-imports --json "$rootdir"/src/**/*.js \ | jq '.[] | .requirements[] | [.import, .path] | map(ltrimstr("'"$rootdir"'/")) | join(" ") ' \ -r \ # | sort -u } sorted_files() { import_pairs | tsort 2>/dev/null } sorted_ourfiles() { grep -l '@flow' -- $(sorted_files | grep ^src/.*js$) } with_flow() { grep '@flow' -- $(sorted_files | grep ^src/.*js$) } todo() { with_flow | number_lines | grep -Ev '@flow strict(\s|$)' } depends() { local f="$1"; import_pairs | perl -lane 'print $F[0] if (m( '"$f"'$))' } rdepends() { local f="$1"; import_pairs | perl -lane 'print $F[1] if (m(^'"$f"' ))' } number_lines() { nl -ba -nln -w3 -s' ' } case "$1" in pairs) import_pairs;; ''|list) sorted_ourfiles;; flow) with_flow | number_lines;; todo) todo;; depends) depends "$2";; rdepends) rdepends "$2";; esac ```
/content/code_sandbox/tools/tsort-modules
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
347
```unknown #!/usr/bin/env bash # Careful! `set -e` doesn't do everything you'd think it does. In # fact, we don't get its benefit in any of the `run_foo` functions. # # This is because it has an effect only when it can exit the whole shell. # (Its full name is `set -o errexit`, and it means "exit" literally.) See: # path_to_url#The-Set-Builtin # # When one test suite fails, we want to go on to run the other suites, so # we use `||` to prevent the whole script from exiting there, and that # defeats `set -e`. # # For now our workaround is to put `|| return` in the `run_foo` just # after each nontrivial command that isn't the final command in the # function. set -e this_dir=${BASH_SOURCE[0]%/*} . "${this_dir}"/lib/eslintignore.sh ## CLI PARSING default_suites=(native flow lint jest prettier deps tsflower) extra_suites=( intl # Takes several seconds to run. ) usage() { cat >&2 <<EOF usage: tools/test [OPTION]... [SUITE]... Run our tests. By default, run only on files changed in this branch as found by \`tools/git changed-files \$(tools/git base)\`. By default, run ${#default_suites[@]} suite(s): ${default_suites[*]} and skip ${#extra_suites[@]} suite(s): ${extra_suites[*]} What tests to run: --all-files Run on all files, not only changed files. --diff COMMIT Run only on files that differ from the given commit. (E.g., \`--diff @\` for files with uncommitted changes; \`--diff @~10\` for files changed in last 10 commits; or see \`git help revisions\` for many more ways to name a commit.) --platform <ios|android|both|sloppy> Run tests as if on iOS, or Android, or both. The default, "sloppy", takes a shortcut in some suites, so the tests run faster but full coverage of both platforms isn't guaranteed. Specifically, "sloppy" will run both Android and iOS native tests, but will run Jest tests on only one platform (iOS). This is usually fine, because the vast majority of our Jest tests don't depend meaningfully on the platform. --all In the given suites, run all tests on all files, equivalently to \`--all-files --platform both\`. If no list of suites was specified, run all suites. Extra things to do: --coverage Collect test-coverage information. Only meaningful with --all. --fix Fix issues found, where possible. EOF exit 2 } opt_coverage= opt_files=branch opt_platform=sloppy opt_all= opt_fix= opt_suites=() while (( $# )); do case "$1" in --coverage) opt_coverage=1; shift;; --diff) shift; opt_files=diff:"$1"; shift;; --all-files) opt_files=all; shift;; --platform) shift; case "$1" in ios|android|both|sloppy) opt_platform="$1";; *) usage;; esac shift ;; --all) opt_files=all; opt_platform=both; opt_all=1; shift;; --fix) opt_fix=1; shift;; native|flow|lint|jest|prettier|deps|tsflower|intl) opt_suites+=("$1"); shift;; *) usage;; esac done if [ -z "$opt_suites" ]; then if [ -n "${opt_all}" ]; then opt_suites=( "${default_suites[@]}" "${extra_suites[@]}" ) else opt_suites=( "${default_suites[@]}" ) fi fi files_base_commit= case "$opt_files" in all) ;; branch) files_base_commit="$(tools/git base)";; diff:*) files_base_commit="${opt_files#diff:}";; esac ## EXECUTION rootdir=$(git rev-parse --show-toplevel) cd "$rootdir" PATH=node_modules/.bin:"$PATH" # Intersect $opt_files with the set of our JS files in src/. # # Prints a list of newline-terminated paths; either files, or # directories meaning their whole subtrees. files_js() { case "$opt_files" in all) echo src/ ;; branch | diff:*) tools/git changed-files "${files_base_commit}" -- 'src/*.js' ;; esac } # True just if $files intersects the given set of paths. files_check() { case "$opt_files" in all) ;; branch | diff:*) ! git diff --quiet "${files_base_commit}" "$@" ;; esac } run_native_android() { files_check android/ \ || return 0 tools/gradle -q :app:assembleDebug :app:assembleDebugUnitTest \ :app:bundleDebug || return # The `-q` suppresses noise from warnings about obsolete build config # in our dependencies from the React Native ecosystem. # But it also suppresses the names of tests that failed. # So on failure, rerun without it. tools/gradle -q :app:testDebugUnitTest \ || tools/gradle :app:testDebugUnitTest } run_native_ios() { : # TODO: At least make an iOS build. } run_native() { if [[ $opt_platform == android || $opt_platform == both || $opt_platform == sloppy ]]; then echo 'Running Android native tests...'; run_native_android || return fi if [[ $opt_platform == ios || $opt_platform == both || $opt_platform == sloppy ]]; then # TODO: Run if on macOS; otherwise, echo that these tests are # skipped because they can't be run. # echo 'Running iOS native tests...'; run_native_ios || return fi } run_lint() { local files files=( $(files_js) ) files=( $(apply_eslintignore "${files[@]}") ) (( ${#files[@]} )) || return 0 eslint ${opt_fix:+--fix} --report-unused-disable-directives --max-warnings=0 "${files[@]}" } run_jest() { # Unlike some others, this inspects "$opt_files" for itself. local jest_args=() case "$opt_files" in all) if [ -n "$opt_coverage" ]; then jest_args+=( --coverage ) fi ;; branch) jest_args+=( --changedSince "$(tools/git upstream-ref)" ) ;; diff:*) local file_list file_list=( $(files_js) ) (( ${#file_list[@]} )) || return 0 jest_args+=( --findRelatedTests "${file_list[@]}" ) ;; esac local platforms=( ios android ) case "$opt_platform" in ios) jest_args+=( --selectProjects ios );; android) jest_args+=( --selectProjects android );; both) jest_args+=( --selectProjects ios android );; # This is where `sloppy` is sloppy: we choose a platform randomly, so # the tests will run faster, but at the expense of a (relatively small) # loss of coverage. sloppy) jest_args+=( --selectProjects "${platforms[RANDOM%2]}" );; esac jest "${jest_args[@]}" } run_prettier() { local patterns case "$opt_files" in all) # The prettier-eslint CLI won't take directories; # but it's happy to take glob patterns, and supports `**`. patterns=( {src,types}/'**/*'.js{,.flow} ) ;; branch | diff:*) patterns=( $(tools/git changed-files "${files_base_commit}" \ -- {src,types}/\*.js{,.flow}) ) ;; esac (( ${#patterns[@]} )) || return 0 # Workaround for path_to_url patterns=( "${patterns[@]/#/$rootdir/}" ) prettier-eslint \ ${opt_fix:+--write} \ --list-different \ --eslint-config-path "${rootdir}"/tools/formatting.eslintrc.yaml \ "${patterns[@]}" } run_deps() { files_check package.json yarn.lock \ || return 0 if ! yarn-deduplicate --fail --list; then cat >&2 <<EOF Found duplicate dependencies in yarn.lock which could be dedup'd. Run: yarn yarn-deduplicate && yarn EOF return 1 fi } run_tsflower() { # This suite depends on: # * the tools/tsflower script # * the type definitions in types/**/*.js.flow # * the patches in types/patches/*.patch # * the versions of `tsflower` and of libraries it processes files_check tools/tsflower types/ yarn.lock \ || return 0 # NB this suite will fail (with a reasonable error message) if # there are any local Git changes, because it can't do its work # without making changes to the worktree. (Short of making a # temporary worktree somewhere, anyway; but that'd probably mean a # slow test suite.) Hopefully in normal development this is fine: # it usually won't run because of files_check; if it does, the # error message comes fast and is short, and doesn't get in the # way of the other suites doing their jobs. tools/tsflower check } run_intl() { tools/check-messages-en } failed=() for suite in "${opt_suites[@]}"; do echo "Running $suite..." case "$suite" in native) run_native ;; flow) flow ;; lint) run_lint ;; jest) run_jest ;; prettier) run_prettier ;; deps) run_deps ;; tsflower) run_tsflower ;; intl) run_intl ;; esac || failed+=($suite) done if [ -n "$failed" ]; then cat >&2 <<EOF FAILED: ${failed[*]} To rerun the suites that failed, run: $ tools/test ${failed[*]} EOF exit 1 fi echo "Passed!" ```
/content/code_sandbox/tools/test
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,370
```unknown #!/usr/bin/env node /* eslint-env node */ const { rollup } = require('rollup'); const rollupBabel = require('@rollup/plugin-babel').default; const rollupNodeResolve = require('@rollup/plugin-node-resolve').default; const assert = require('assert'); const fs = require('fs'); const util = require('util'); const sourceFilename = 'src/webview/js/js.js'; const outputFilename = 'src/webview/js/generatedEs3.js'; /** * The minimum browser versions we support for the WebView. * * These should agree with the block comment at the top of js.js. * See also docs/architecture/platform-versions.md. */ /* Fun tip for seeing which transforms will stop being needed on an upgrade: $ jq -c ' to_entries | map(.value + { name: .key }) | sort_by(.chrome // "999" | tonumber) # or (.ios // "999" | tonumber) | .[] | { chrome, safari, ios, name } ' node_modules/@babel/compat-data/data/plugins.json */ const targetPlatforms = { // Babel doesn't distinguish Chrome for Android vs. other Chrome. // See their data table, in node_modules/@babel/compat-data/data/plugins.json . // // Keep this at the Chrome version originally shipped with the oldest // Android version we support. chrome: 51, // (Babel accepts an "android" key here too. But that refers to the old // Android System WebView, which Android 5 replaced with an auto-updating // Chrome; see our b3eced058. So there's no such thing as "android: 5" or // later, and because we don't support older Android versions than that, // we don't use the "android" key.) // Babel does distinguish `safari` (meaning on macOS, I guess) from `ios`. // Some features arrive in e.g. "safari 11.1" but "ios 11.3", or in // 13.1 vs 13.4, so the distinction is still relevant. ios: 14, }; // Disable the default react-native transformations. // See `$ROOT/babel.config.js`. process.env.BABEL_ENV = 'webview'; // node's fs predates async/await, alas const writeFileAsync = util.promisify(fs.writeFile); /** * Transform the transpiled code into the text of a module which exports that * code as a string. */ const wrapCode = es3Code => { /* eslint-disable-next-line no-useless-concat */ const generatedMarker = '@' + 'generated'; return `/* * This is a GENERATED file -- do not edit. * To make changes: * 1. Edit \`js.js\` or the files it imports, which together make up * the source for this file. * 2. Run \`tools/generate-webview-js\`. * * ${generatedMarker} * @flow strict */ export default \` 'use strict'; ${es3Code.replace(/\\/g, '\\\\')} \`; `; }; (async () => { // Define the build process. const build = await rollup({ input: sourceFilename, plugins: [ rollupNodeResolve(), rollupBabel({ exclude: 'node_modules/**', /* Our global config file applies React-Native-supplied and -targeted transforms. Those are somewhat counterproductive here. */ configFile: false, babelrc: false, // 'bundled' is the default, but it's recommended to set it // explicitly; see // path_to_url#babelhelpers babelHelpers: 'bundled', compact: false, comments: false, plugins: [ ['@babel/transform-flow-strip-types'], /* Add TC39 stage 3+ transforms here as needed. */ ['@babel/plugin-proposal-optional-chaining'], ], // See comments below about (the absence of) automatic polyfills via // `core-js`. presets: [ [ '@babel/preset-env', { targets: targetPlatforms, // Remove unescaped template-literal syntax in the output // string (backticks, string interpolation with ${}, etc.), // since for now we wrap the output in a template literal. // TODO(?): Remove that wrapping, and just send the output to // a file which is read as a string. Or: // TODO(?): Properly escape template-literal syntax in the // output string. include: ['@babel/plugin-transform-template-literals'], }, ], ], }), ], }); // Execute the build process. const { output } = await build.generate({ format: 'iife' /* "immediately-invoked function expression" */, name: 'compiledWebviewJs', // TODO: eliminate `wrappedOutput`. See "TODO", below. /* file: outputFilename, */ }); // In general, Babel may return multiple output chunks. This particular // compilation setup, however, should return only a single chunk. assert.strictEqual(output.length, 1); // Extract and wrap that chunk's code. const wrappedOutput = wrapCode(output[0].code); // Write the transformed code. await writeFileAsync(outputFilename, wrappedOutput); })().catch( // eslint-disable-next-line no-console console.error, ); /* TODO: At present, `webview/script.js` wraps this script's output; in turn this script applies a wrapper around (the compiled text of) `webview/js.js`. This is at least one layer of abstraction more than we need. In the future, we'll probably want to make `js.js` compile to a single static asset file. Only a <script> tag and a one-to-three-line invocation should need to be emitted into the dynamically-rendered HTML. */ /** * # Babel, core-js and polyfills * * The `@babel/preset-env` package relies on the definitions and compatibility * declarations in `core-js` to select polyfills for rollup to include. * * Alas, this induces problems. * * The `core-js` package is dedicated to 100% compatibility, even on very old * (ES3) engines. This means that its compatibility profile includes polyfills * for marginal (read: irrelevant) functionality like `@@species` support * [c#644]. * * Furthermore, the compatibility table checks aren't run recursively on the * dependencies of those polyfills; instead, the polyfills' dependencies are * polyfilled automatically. [t] `core-js`'s feature-detection _should_ prevent * these unnecessary polyfills from actually attaching to global objects; but * Rollup is entirely oblivious to this, and will (as directed by `core-js`) * cheerfully push into the final bundle all sorts of unnecessary-but- * `require()`d polyfills containing all sorts of support functionality that, * due to their runtime checks, can't be tree-shaken away. [c#388] * * It is possible to exclude individual polyfills on an item-by-item basis * [b.excl]; but this will only block detection at the top level by * @babel/preset-env. Even `core-js`'s own exclusion system [c.cloa] will not * honor internal polyfill block requests. [c#388] * * It's bad enough that `core-js` inflates the bundle with things like IE8- bug * workarounds [t] [c#388] and unstripped comments [t], and that it replaces * fast, sufficient native code with complex, less-JITtable code. Worse, though, * is that its aggressive replacement of native functionality can introduce * slowdown even on formally-unrelated code paths. [b#5771] [c#306] * * For all that, `core-js` _does_ work. Using it, or not using it, is a * tradeoff... but then, so is supporting older WebViews at all. * * See docs/architecture/platform-versions.md for details about our * version-support strategy. */ /** * Footnotes (separated to keep the paragraph rewrapper from trying to wrap * them): * * [b#5771] path_to_url * [b.excl] path_to_url#exclude * [c#306] path_to_url * [c#388] path_to_url * [c#644] path_to_url * [c.cloa] path_to_url#configurable-level-of-aggressiveness * [t] Observed in tests. */ ```
/content/code_sandbox/tools/generate-webview-js
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,892
```unknown #!/usr/bin/env bash set -eu ROOT_DIR=$(git rev-parse --show-toplevel) patch_package() { node_modules/.bin/patch-package } pod_install() { [[ "$OSTYPE" == "darwin"* ]] \ || return 0 if ! hash pod 2>/dev/null; then cat >&2 <<EOF The Zulip mobile app requires CocoaPods for its iOS build. Please install it, following the instructions at path_to_url Then, rerun yarn. EOF exit 1 fi pod install --project-directory="$ROOT_DIR/ios" } jetify() { node_modules/.bin/jetify } patch_package pod_install jetify echo "tools/postinstall finished with no errors!" ```
/content/code_sandbox/tools/postinstall
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
169
```unknown #!/usr/bin/env bash set -e usage () { cat <<EOF >&2 usage: bump-version VERSION_NAME Updates the version number in our Android and iOS build configs, and in the changelog. Example: bump-version 27.155 EOF exit 2 } version_name="$1"; shift || usage; shift && usage; version_code="${version_name##*.}" tag_name=v"${version_name}" date="$(date --iso)" had_uncommitted= if ! git diff-index --quiet HEAD; then had_uncommitted=1 fi perl -i -0pe ' s/versionCode \K[0-9]+/'"$version_code"'/; s/versionName "\K[0-9.]+/'"$version_name"'/; ' android/app/build.gradle perl -i -0pe ' s|<key>CFBundleShortVersionString</key> \s* <string>\K [0-9.]+ |'"$version_name"'|xs ' ios/ZulipMobile/Info.plist perl -i -0pe ' s/^\#\#\ Unreleased\n\K / ## '"$version_name"' ('"$date"') /xms ' docs/changelog.md msg="version: Bump version to $version_name." if [ -n "$had_uncommitted" ]; then { echo "There were uncommitted changes. To commit:" echo " git commit -am ${msg@Q}" # NB if tempted to use the ${...@Q} feature: it's new in bash 4.4, # released 2016-09, found in stretch and bionic but not xenial. echo echo "Then tag the commit:" echo " git tag ${tag_name}" echo "inspect the result, and push:" echo " git push upstream main ${tag_name}" } >&2 exit 1 fi git commit -am "$msg" git tag "${tag_name}" { echo echo "Committed and tagged." echo "Inspect the result, then push; for example:" echo " git push upstream main ${tag_name}" } >&2 ```
/content/code_sandbox/tools/bump-version
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
469
```unknown #!/usr/bin/env bash set -eu unset CDPATH # tools/build-webview: WebView assets collection script. # CAVEAT EMENDATOR: Neither of the build systems have any visibility into this # script's dependencies -- it is run unconditionally, and must ensure on its own # that it performs as few actions as possible when nothing has changed. ################################################################################ # Common functions ################################################################################ # print usage message; do not die usage() { cat >&2 <<EOF usage: $0 [ios | android] --destination DEST [--check-path-name] Build our webview assets, into directory DEST. This script is mainly for internal use by our build scripts. They go on to use the contents of DEST as the webview-assets folder, which our message-list WebView relies on for its static assets. See src/webview/MessageList.js for details. With --check-path-name, make some defensive checks that DEST has the form expected from the actual build scripts. EOF } # print error and die err() { echo -e "$0:" $'\e[31merror:\e[0m' "$@" >&2 exit 1; } # If verbose, format and log message. First arg is format string. verbose_printf() { if ! (( verbose )); then return fi # shellcheck disable=SC2059 # format string from parameter printf >&2 "%s: $1\n" "$0" "${@:2}" } ################################################################################ # Environment ################################################################################ # The project root, for absolutizing paths and accessing auxiliary scripts. # (Assumed to be one directory up from the script's own location.) root="$(cd "$(dirname "${BASH_SOURCE[0]}")"/../ && pwd)" # Ensure that we have access to a functional, modern `readlink`. . "$root"/tools/lib/ensure-coreutils.sh # Normalize and absolutize $root. # # This must return a name for the project root directory which coincides with # the one Gradle/Xcode will provide. This is unlikely to be a problem on Linux # or macOS, but has caused issues on Windows; see GitHub issue #3777.) root="$(readlink -m "$root")" readonly root ################################################################################ # Parameters ################################################################################ # Parse arguments. Sloppy, but sufficient for now. unset target unset dest check_path_name=0 verbose=0 while (( $# )); do case "$1" in --help|-h|help) usage; exit 0;; android|ios) # no check for multiple nouns; oh well target="$1"; shift;; --destination) # note: this doesn't permit an equals sign after `--destination` shift; dest="$1"; shift;; --check-path-name) shift; check_path_name=1;; --verbose|-v) shift; verbose=1;; *) usage; exit 2;; esac done # All arguments are required; complain if any were omitted. if [ -z "${target-}" ]; then usage; exit 2 elif [ -z "${dest-}" ]; then usage; exit 2 fi # Interpret destination path based on current directory... dest=$(realpath -m --relative-to="$root" "$dest") # ... then cd to the root. cd "$root" # Argument parsing has concluded; argument variables are no longer mutable. readonly target dest check_path_name verbose if (( check_path_name )); then case "$target" in ios) if [ "$(uname)" != "Darwin" ]; then err "iOS builds only supported on macOS"; fi # $dest should be copied to `${bundle_root}/webview`. # # $dest itself must be specified twice in Xcode: once in the invocation # of this script, and once in the "Copy Bundle Resources" step. If you # change it, you'll need to change it in both places. (And here, of # course.) if [[ "$dest" != "ios/"* ]]; then err "unexpected destination directory '$dest' (expected target in ios/)" fi ;; android) # $dest should be copied to `file:///android_asset/webview`. # # Gradle -- more precisely, the Android Gradle plugin -- is already # configured to copy some directory from `build/` into the APK. We # determine which directory that is in Gradle, and pass it here. if [[ "$dest" != "android/app/build/"* ]]; then err "unexpected destination directory '$dest' (expected target in android/app/build/)" fi ;; *) err "impossible target $target";; esac # As implied above, the ultimate destination of these files should be a # directory named `./webview` (relative to the platform-dependent asset # root directory). # # The target directory basename should therefore be 'webview': both build # systems will preserve the name they're given here. if [[ "$dest" != *"/webview" ]]; then err "unexpected destination directory '$dest' (expected basename \"webview\")" fi fi # if $check_path_name ################################################################################ # (Build and) sync ################################################################################ # Sync files from src to dest, reading rsync filter rules from stdin. # # Both src and dest should be directories. # # Files in dest not mentioned will be deleted by default. A rule # like `-,r /foo` will override this to leave `foo` in place. # # For documentation on rsync filter rules, see `man rsync` or: # path_to_url#FILTER_RULES sync() { # "_dest" because bash's `readonly` means can't shadow with `local` local src="$1" _dest="$2" mkdir -p "${_dest}" verbose_printf "RSYNC %q -> %q" "${src}" "${_dest}" rsync -aR --no-D --delete --delete-excluded \ "${src}/./" "${_dest}/." \ --filter='. -' } # Copy over files from KaTeX. sync "node_modules/katex/dist" "${dest}/katex" <<EOF + /katex.min.css # The KaTeX JS renders LaTeX code into HTML and MathML. # Our webview already has HTML and MathML, and just needs to style it. #+ /katex.min.js # The woff2 font format is preferred for browsers that support it, # which include Chrome 36+ and Mobile Safari 10+. So that's all we need. + /fonts/ + /fonts/*.woff2 - * EOF # Copy over our own files. sync "src/webview/static" "${dest}" <<EOF # Leave alone the katex directory we just made. -,r /katex + /base.css + /images/ + /images/follow.svg + /images/loader-black.svg + /images/loader-white.svg + /images/play_button.svg - * EOF ```
/content/code_sandbox/tools/build-webview
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,531
```unknown #!/usr/bin/env bash set -eu # Generate the many different versions of our logo we need across the app. # # This script is not run as part of the build, in order to avoid introducing # its somewhat specialized dependencies as requirements for normal # development. Instead, we keep its outputs checked into the repo. # Because this script isn't meant to be run routinely, we let it be a bit # rough-and-ready in its interface. But it should error early if it's # missing anything it needs. # # Much of the knowledge it encodes -- what contexts call for which # graphical variation of the logo, in what sizes and what format -- # was compiled at path_to_url # before being turned into this executable form. # TIP: Everything in this script has the handy property that its # outputs are reproducible. That means that if you run it and # `git status` shows that it's changed any of the files in the # tree... then either the source images, or something in the # script itself, has changed since the run reflected in your # current tree. this_dir=${BASH_SOURCE[0]%/*} . "${this_dir}"/lib/ensure-coreutils.sh root_dir=$(readlink -f "${this_dir}"/..) tmpdir=$(mktemp -d) die() { echo >&2 "$1" exit 1 } inkscape --version >/dev/null 2>&1 \ || die "Need inkscape -- try 'apt install inkscape'." cwebp -version >/dev/null 2>&1 \ || die "Need cwebp -- try 'apt install webp'." jq --version >/dev/null 2>&1 \ || die "Need jq -- try 'apt install jq'." # This should point to a zulip.git worktree. zulip_root="${root_dir%/*}"/zulip # White Z in gradient-colored circle. src_icon_circle="${zulip_root}"/static/images/logo/zulip-icon-circle.svg # White Z in gradient-colored circle with DEBUG banner. # Contains a link to the equivalent of ${src_icon_circle}. src_icon_debug="${root_dir}"/tools/zulip-icon-debug.svg # White Z in gradient-colored square, full-bleed. src_icon_square="${zulip_root}"/static/images/logo/zulip-icon-square.svg # White Z in gray circle. src_icon_circle_gray="${zulip_root}"/static/images/zulip-logo.svg # White Z on transparent background. src_icon_white_z="${root_dir}"/tools/z-white.svg [ -r "${src_icon_circle}" ] \ || die "Expected Zulip worktree at: ${zulip_root}" make_one_ios_app_icon() { # SET BY CALLER: contents iconset local size_pt="$1" scale="$2" idiom="$3" local size_px="${4-$(( size_pt * scale ))}" local output_basename=Icon-"${size_pt}x${size_pt}@${scale}x".png local output="${iconset}"/"${output_basename}" if [ ! -f "${output}" ]; then inkscape "${src_icon_square}" -w "${size_px}" --export-png="${output}" fi printf >>"${contents}" \ ' { "size": "%s", "idiom": "%s", "filename": "%s", "scale": "%s" }\n' \ "${size_pt}x${size_pt}" "${idiom}" "${output_basename}" "${scale}x" } make_ios_app_icon() { local iconset=ios/ZulipMobile/Assets.xcassets/AppIcon.appiconset rm -rf "${iconset}" mkdir -p "${iconset}" local contents="${tmpdir}"/Contents.json.in rm -f "${contents}" # Handy command for a compact view of what's in the contents: # $ jq '.images[] | "\(.size) \(.scale) \(.idiom)"' -r \ # <"${iconset}"/Contents.json # From "App Icon Sizes" at: # path_to_url make_one_ios_app_icon 60 3 iphone make_one_ios_app_icon 60 2 iphone make_one_ios_app_icon 83.5 2 ipad 167 make_one_ios_app_icon 76 2 ipad make_one_ios_app_icon 1024 1 ios-marketing # From "Spotlight, Settings, and Notification Icons" # in the same iOS doc make_one_ios_app_icon 40 3 iphone make_one_ios_app_icon 40 2 iphone make_one_ios_app_icon 40 2 ipad make_one_ios_app_icon 29 3 iphone make_one_ios_app_icon 29 2 iphone make_one_ios_app_icon 29 2 ipad make_one_ios_app_icon 20 3 iphone make_one_ios_app_icon 20 2 iphone make_one_ios_app_icon 20 2 ipad jq <"${contents}" \ -s '{ "images": ., "info": { "version": 1, "author": "xcode" } }' \ >"${iconset}"/Contents.json } make_ios() { make_ios_app_icon # This seems to be used only in LaunchScreen.xib... # which it isn't clear actually ever appears when using the app. # TODO take it out? inkscape "${src_icon_circle}" -w 512 --export-png=ios/zulip-logo.png } make_webp() { local input="$1" size="$2" output="$3" inkscape "${input}" -w "${size}" --export-png="${tmpdir}"/tmp.png # `cwebp -z 9` means lossless, and max/slowest compression cwebp -z 9 "${tmpdir}"/tmp.png -o "${output}" } make_one_android_icon() { # SET BY CALLER: src sourceset restype name local size_px="$1" density="$2" local output=android/app/src/"${sourceset}"/res/"${restype}"-"${density}"/"${name}".webp mkdir -p "${output%/*}" make_webp "${src}" "${size_px}" "${output}" } make_android_icon() { local src="$1" size_dp="$2" sourceset="$3" restype="$4" name="$5" rm -f android/app/src/"${sourceset}"/res/*/"${name}".* # Scale factors from: # path_to_url#TaskProvideAltBmp make_one_android_icon "${size_dp}" mdpi make_one_android_icon $(( size_dp * 3 / 2 )) hdpi make_one_android_icon $(( size_dp * 2 )) xhdpi make_one_android_icon $(( size_dp * 3 )) xxhdpi make_one_android_icon $(( size_dp * 4 )) xxxhdpi } make_android() { # path_to_url # This generated file we don't commit to the repo, because it isn't # needed in the build. inkscape "${src_icon_square}" -w 512 --export-png=zulip-icon-google-play.png # Launcher icon goes in a mipmap: # path_to_url#mipmap make_android_icon "${src_icon_circle}" 48 main mipmap ic_launcher make_android_icon "${src_icon_debug}" 48 debug mipmap ic_launcher # docs: path_to_url#BehaviorNotifications make_android_icon "${src_icon_white_z}" 24 main drawable zulip_notification } inkscape "${src_icon_circle_gray}" -w 512 --export-png=static/img/message-loading.png # Appears at 40px logical; 4x scale to correspond to Android's xxxhdpi inkscape "${src_icon_circle}" -w 160 --export-png=static/img/logo.png make_ios make_android cat <<'EOF' Done! If `git status` shows any changes in this script's outputs, be sure to commit those alongside your changes to the script itself. EOF ```
/content/code_sandbox/tools/generate-logos
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,804
```unknown #!/usr/bin/env bash oldjs=$(<./src/webview/js/generatedEs3.js) tools/generate-webview-js newjs=$(<./src/webview/js/generatedEs3.js) if [ "$oldjs" != "$newjs" ]; then echo "generatedEs3.js is not updated with current js file." exit 1 fi ```
/content/code_sandbox/tools/verify-webview-js
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
78
```unknown #!/usr/bin/env bash # Compute what remote name is being used for the upstream repo. upstream_remote_name() { # Out of the names listed by `git remote`, pick one from the # list below, in preference order. grep -m1 -xFf <(git remote) <<EOF upstream origin EOF } upstream_ref() { echo refs/remotes/"$(upstream_remote_name)"/main } # usage: base_commit [TIP [UPSTREAM]] # # The merge-base of TIP (default: current HEAD) with # UPSTREAM (default: upstream/main or origin/main). base_commit() { tip_commit=${1:-@} upstream=${2:-$(upstream_ref)} git merge-base "$tip_commit" "$upstream" } # usage: files_changed [DIFFARGS..] # # Lists files that have changed, excluding files that no longer exist. # # Arguments are passed through to `git diff`. files_changed() { git diff --name-only --diff-filter=d "$@" } case "$1" in upstream-ref) upstream_ref; exit;; base) shift; base_commit "$@"; exit;; '' | changed-files) shift; files_changed "$@"; exit;; *) exit 1;; esac ```
/content/code_sandbox/tools/git
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
276
```yaml # Formatting rules which overrule Prettier. These are in their own file so # we can follow each Prettier run with a streamlined (and faster) ESLint run # that uses only these rules. parser: "hermes-eslint" plugins: - ft-flow - import - jest - react - react-hooks rules: # Disallow tucking a condition or loop body in at the end of a line, like # `if (condition) return;`. That makes it much too easy to miss control flow. nonblock-statement-body-position: [error, below] curly: [error, all] # When breaking a line at a binary operator, the operator goes # at the start of a line, not the end. This makes it much more # conspicuous whether we're using e.g. `&&` or `||`. operator-linebreak: - error - before - overrides: # Assignment operators are a very different beast, which it would make # no sense to format this way. "=": after "+=": after "-=": after # ... There are 10 other assignment operators in JavaScript; # if they come up, add them. # This *would* overrule Prettier, and in particular run roughshod over # line-length limits. Let Prettier take care of it. implicit-arrow-linebreak: off ```
/content/code_sandbox/tools/formatting.eslintrc.yaml
yaml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
322
```unknown #!/usr/bin/env bash this_file=$(readlink -f "${BASH_SOURCE[0]}") root=${this_file%/*/*} changelog_file=${root}/docs/changelog.md . "${root}"/tools/lib/ensure-coreutils.sh # Extract the most recent changelog entry. extract() { perl -0n \ -e 'print $& if ( /^ \#\#\ (?!Unreleased) # any h2 not matching "Unreleased" .*? # ... up to the first following ... (?= ^ \#\#\ ) # h2. /xms)' \ "${changelog_file}" } # Extract the most recent user-highlights entry. extract_highlights() { perl -0n \ -e 'print $& if ( /^ \#\#\#\ Highlights\ for\ users # any matching h3 .*? # ... up to the first following ... (?= ^ \#{1,3}\ ) # h3 or less. /xms)' \ "${changelog_file}" } # Undo line-wrapping. unwrap() { fmt --tagged-paragraph --width=2000 } # Print changelog entry, with line-wrapping removed. cmd_unwrap() { extract | unwrap } # Print user-highlights entry, with line-wrapping removed. cmd_user() { extract_highlights | tail -n +2 | unwrap } show_hash() { local artifacts filename output hash basename artifacts=( "${root}"/android/app/build/outputs/apk/release/app-*-release.apk "${root}"/android/app/build/outputs/bundle/release/app-release.aab ) echo "sha256sum -c <<EOF" for filename in "${artifacts[@]}"; do output=$(sha256sum "${filename}") hash=${output%% *} basename="${filename##*/}" echo "${hash} ${basename}" done echo "EOF" } # Print release notes suitable for posting on e.g. GitHub. cmd_notes() { cmd_unwrap echo '```'; show_hash; echo '```' } # Print release notes suitable for posting on chat.zulip.org. cmd_czo() { # Converts #1234 to #M1234, matching a linkifier we have on czo. cmd_unwrap \ | perl -pe 's<\# (?= \d{2,8} )> <#M>xg' } usage() { cat >&2 <<EOF usage: ${BASH_SOURCE[0]} { unwrap | user | notes | czo } EOF } case "$1" in unwrap) shift; cmd_unwrap "$@";; user) shift; cmd_user "$@";; notes) shift; cmd_notes "$@";; czo) shift; cmd_czo "$@";; *) usage;; esac ```
/content/code_sandbox/tools/changelog
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
628
```unknown #!/usr/bin/env bash set -e set -o pipefail shopt -s extglob this_file=$(readlink -f "${BASH_SOURCE[0]}") root=${this_file%/*/*} . "${root}"/tools/lib/ensure-coreutils.sh rn_gh_base_url=path_to_url # Fetch the package.json of the given RN version. get_rn_pjson() { local version=$1 curl -sf "${rn_gh_base_url}/${version}"/package.json \ || { echo >&2 "bad RN version: ${version}"; return 1; } } # Get all dependencies of the given RN version. # # Output is stored in the given associative array, which should # already have been declared with `local -A`. # # @param $1 version In the form `v0.NN.M`. # @param $2 out The name of an associative array. get_rn_deps_by_ref() { local version_git=$1 out=$2 local rn_deps_txt=$( \ get_rn_pjson "${version_git}" \ | jq '.devDependencies + .dependencies + .peerDependencies | to_entries | .[] | "\(.key) \(.value)"' \ -r) { local ref IFS=$'\n' for line in ${rn_deps_txt}; do printf -v "${out}[${line% *}]" %s "${line#* }" done } } # Set the given dep and version in our package.json, # regardless of which kind of dependency it is. set_version() { local dep=$1 version=$2 local subst=$(printf 's/"%s":\ "\K .*? (?= " )/%s/x' \ "${dep}" "${version}") perl -i -0pe "${subst}" "${root}"/package.json } cmd_rn() { (( $# == 1 )) || usage local version_git=$1 [[ "${version_git}" = v* ]] || usage local -A rn_deps get_rn_deps_by_ref "${version_git}" rn_deps local dep version echo "Versions:" printf " %-20s %s\n" react-native "${version_git#v}" set_version react-native "${version_git#v}" for dep in react react-test-renderer flow-bin; do version=${rn_deps["${dep}"]} printf " %-20s %s\n" "${dep}" "${version}" set_version "${dep}" "${version}" done echo local subst=$(printf 's/\\[version\\]\\n \\K .*? $/%s/xms' \ "${rn_deps[flow-bin]}" ) perl -i -0pe "${subst}" "${root}"/.flowconfig yarn echo echo "Upgraded. Diff:" git diff -U0 package.json git diff -U1 .flowconfig local changelog_anchor="${version_git//@(v|.)}" cat <<EOF Changelog: path_to_url#${changelog_anchor} EOF } usage() { cat >&2 <<EOF usage: ${BASH_SOURCE[0]} CMD [OPTS...] ${BASH_SOURCE[0]} rn v0.NN.M Upgrade react-native and closely-related dependencies. EOF exit 2 } case "$1" in rn) shift; cmd_rn "$@";; *) usage;; esac ```
/content/code_sandbox/tools/upgrade
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
754
```unknown #!/usr/bin/env bash set -euo pipefail shopt -s globstar usage() { cat >&2 <<EOF usage: tools/tsflower SUBCOMMAND [ARGS...] This tool runs TsFlower to generate Flow type definitions for some of our dependencies using TS type definitions from upstream. It also manages a stack of our own patches to the generated output. Subcommands include: run - Rerun TsFlower, and reapply patches check - Check definitions up to date; used by \`tools/test tsflower\` unpack - Turn patches into a Git branch for editing, and rerun TsFlower pack - Turn a Git branch back into an updated set of patches help - Print this help Workflow for revising the type definitions or patch stack: 1. Run \`tools/tsflower unpack -s\` to unpack patches into a Git branch. (The \`-s\` skips rerunning TsFlower.) 2. Make desired changes and commit them, or use \`git rebase -i\`. 3. Run \`tools/tsflower pack\` to re-pack the revised branch into patches. This returns to your original branch, with the type definitions and patches updated to reflect your changes. 4. Commit your changes. Workflow for updating dependencies, full version: 1. Update \`package.json\` and run \`yarn\` as usual. Commit the results (though the commit may not yet be mergeable.) 2. Run \`tools/tsflower unpack\` to unpack patches into a Git branch, rerun TsFlower, and attempt to rebase them on the updated definitions. 3. Resolve any rebase conflicts to complete the rebase. 4. Check that Flow passes; make any needed fixes and commit them. 5. Run \`tools/tsflower pack\` as above. 6. Commit your changes, and squash them into the commit that updated \`package.json\` and \`yarn.lock\`. 7. Run \`tools/test\` to confirm the tests pass. In particular this will run \`tools/tsflower check\`. Workflow for updating dependencies, fast path: 1. As above. 2-5. Run \`tools/tsflower run\` to rerun TsFlower and re-apply patches. If the dependency update didn't affect anything the patches touch, this should succeed. If this doesn't work, or if there are Flow errors, use the full workflow above with \`unpack\` and \`pack\`. 6-7. As above. EOF } this_file=$(readlink -f "$0") rootdir=${this_file%/*/*} bindir=${rootdir}/node_modules/.bin cd "${rootdir}" patch_dir=${rootdir}/types/patches # Options to give `patch` our preferred behavior. patch_opts=( --quiet # Don't spew names of patched files. (Let Git handle that info.) --no-backup-if-mismatch # Let Git handle the version control. --reject-file - # Don't spew `.rej` files on error. --force # Don't ask questions, like "Unreversed patch detected! Ignore -R?" --fuzz 0 # Don't ignore any context. (Match `git am`'s behavior.) ) no_uncommitted_changes() { if ! git diff-index --quiet --cached HEAD; then # Index differs from HEAD. return 1 fi if ! git diff-files --quiet; then # Worktree differs from index. return 1 fi } check_no_uncommitted_changes() { if ! no_uncommitted_changes; then echo >&2 "There are uncommitted changes. Doing nothing, to avoid losing your work." return 1 fi } run_on_package() { # TODO(tsflower): put all this into a tsflower command local package="$1" local src="${rootdir}"/node_modules/"${package}" local dest="${rootdir}"/types/"${package}" rm -f "${dest}"/**/*.js.flow "${bindir}"/tsflower tree "${src}" "${dest}" local index="${dest}"/index.js.flow if ! [ -e "${index}" ]; then local typeref typeref=$(jq .types -r "${src}"/package.json) local at="@" echo >"${index}" "\ /* ${at}flow * ${at}generated */ export * from './${typeref%.d.ts}.js.flow';" fi } format_dir() { local dir="$1" "${bindir}"/prettier-eslint --write --log-level silent \ --eslint-config-path "${rootdir}"/tools/formatting.eslintrc.yaml \ -- "${dir}"/**/*.js.flow } run_only() { local package # TODO get list of packages from data... better yet, make it # one tsflower command, reading a TsFlower config file package=expo-mail-composer run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=@react-native-clipboard/clipboard run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=react-native-document-picker run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=react-native-open-notification run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=expo-application run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=react-native-image-picker run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=expo-modules-core run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=expo-screen-orientation run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=expo-web-browser run_on_package "${package}" # TODO(tsflower): skip node_modules when acting on package, # so we don't have to delete it here rm -rf "${rootdir}"/types/"${package}"/node_modules/ format_dir "${rootdir}"/types/"${package}" package=react-native-safe-area-context run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" package=@react-native-camera-roll/camera-roll run_on_package "${package}" format_dir "${rootdir}"/types/"${package}" for package in @react-navigation/{routers,core,native,stack,bottom-tabs,material-top-tabs}; do run_on_package "${package}" # TODO(tsflower): skip node_modules when acting on package, # so we don't have to delete it here rm -rf "${rootdir}"/types/"${package}"/node_modules/ done format_dir "${rootdir}"/types/@react-navigation package=react-native-tab-view run_on_package "${package}" # TODO: Send r-n-tab-view a .npmignore patch to stop shipping this directory. # Also perhaps give TsFlower a way to tell it things to skip. rm -rf "${rootdir}"/types/"${package}"/lib/typescript/example/ format_dir "${rootdir}"/types/"${package}" # Remove all *.web.js.flow files, etc. We don't use RN on those platforms. # TODO(tsflower): When tsflower supports skipping files, simplify away. rm -f "${rootdir}"/types/**/*.web.js.flow rm -f "${rootdir}"/types/**/*.macos.js.flow rm -f "${rootdir}"/types/**/*.windows.js.flow } apply_patches() { for p in "${patch_dir}"/*.patch; do if ! patch "${patch_opts[@]}" -p0 <"${p}"; then echo >&2 "apply-patches: Failed at patch: ${p#"${rootdir}/"}" return 1 fi done } run() { run_only echo >&2 "TsFlower run complete. Applying patches..." apply_patches echo >&2 'Patches complete!' } unapply_patches() { local patches=( "${patch_dir}"/*.patch ) local i p for (( i = ${#patches[@]} - 1; i >= 0; i-- )); do p="${patches[i]}" if ! patch "${patch_opts[@]}" -p0 -R <"${p}"; then echo >&2 "unapply-patches: Failed at patch: ${p#"${rootdir}/"}" return 1 fi done } write_patches() { local commit_range="${1:-upstream..tsflower}" rm -f "${patch_dir}"/*.patch local format_patch_config=( # Print the paths verbatim, without added a/ and b/ prefixes. # This makes it a bit simpler to jump to the file when seeing # the patch in the terminal. (Corresponds to passing `-p0` to # `patch` and `git am` when consuming the patches.) -c diff.noprefix=true # Merge the context of hunks that nearly touch. (Can make # diffs a bit more readable; more importantly, override user # config with some consistent value for reproducibility.) -c diff.interHunkContext=6 ) git "${format_patch_config[@]}" \ format-patch --quiet --zero-commit \ --no-thread --no-numbered --keep-subject \ -o "${patch_dir}" "${commit_range}" # `git format-patch` writes the Git version number at the end. # For reproducibility, normalize that to an arbitrary (realistic) value. perl -i -0pe ' s< ^ # beginning of a line (with "m" flag below) 2 \. .* # a 2.x version number (in case a future 3.x # actually makes a difference here) \n\n \Z # end of line, blank line, end of file ><2.32.0\n\n>xm ' "${patch_dir}"/*.patch } check_consistent() { if ! no_uncommitted_changes; then echo >&2 "There are uncommitted changes. Aborting, to avoid losing your work." return 1 fi unapply_patches # TODO: also catch if one patch touches something and another reverts if ! git diff --exit-code HEAD -- ':!types/*.js.flow'; then echo >&2 "Error: patches should only apply to type definitions in types/." return 1 fi echo >&2 "Patches are clean. Running TsFlower..." git add -u run_only if ! git diff --exit-code; then echo >&2 "Error: fresh TsFlower run didn't match existing definitions" return 1 fi echo >&2 "TsFlower run successful." git reset --hard --quiet } check_branch_unused() { local branchname="$1" if ! git rev-parse --verify --quiet "${branchname}" >/dev/null; then # Branch doesn't exist. return 0 fi if ! git rev-list -n1 HEAD.."${branchname}" | grep -q .; then # Branch is an ancestor of HEAD. return 0 fi # Branch does exist, and contains commits not in HEAD. return 1 } unpack() { local branchname= local shortcut= while (( $# )); do case "$1" in -s | --shortcut) shortcut=1; shift;; -*) echo >&2 "tools/tsflower unpack: bad option: $1" return 1;; *) if [ -n "${branchname}" ]; then echo >&2 "tools/tsflower unpack: too many arguments" return 1 fi branchname="$1" shift;; esac done branchname="${branchname:-tsflower}" local basebranch="${branchname}-base" check_no_uncommitted_changes if git ls-files --others --exclude-standard -- 'types/*.js.flow' \ | grep -q .; then cat >&2 <<EOF There are untracked type definitions in types/: EOF git status >&2 --short --untracked-files=normal -- 'types/*.js.flow' cat >&2 <<EOF Doing nothing, to avoid losing your work. Either remove them: git clean -ix 'types/*.js.flow' or ignore them, by adding to \`.gitignore\` or your \`.git/info/exclude\`. EOF return 1 fi if ! check_branch_unused "${branchname}" \ || ! check_branch_unused "${basebranch}"; then cat >&2 <<EOF Branch '${branchname}' or '${basebranch}' already exists and is not an ancestor of HEAD. Doing nothing, to avoid losing your work. To choose a different branch name: tools/tsflower unpack SOMENAME To delete the branches: git branch -D ${branchname@Q} ; git branch -D ${basebranch@Q} To reset the branches: git branch -f ${branchname@Q} ; git branch -f ${basebranch@Q} EOF return 1 fi local start start=$(git rev-parse --verify --quiet @) git checkout --quiet -B "${basebranch}" unapply_patches git commit -am 'tsflower: Revert patches' git checkout --quiet --detach git am --quiet --whitespace=nowarn -p0 --keep "${patch_dir}"/*.patch git checkout --quiet -B "${branchname}" git branch --set-upstream-to "${basebranch}" if [ -z "${shortcut}" ]; then git checkout --quiet "${basebranch}" echo "Running TsFlower to regenerate type definitions from upstream..." run_only git add -- 'types/*.js.flow' git commit --allow-empty -m 'tsflower: Regenerate from upstream' fi echo echo "Base branch '${basebranch}':" git log --oneline --reverse --boundary --decorate-refs=refs/ \ "${start}".."${basebranch}" echo echo "Patch branch '${branchname}':" git log --oneline --reverse --boundary --decorate-refs=refs/ \ "${basebranch}".."${branchname}" if [ -z "${shortcut}" ]; then echo echo "Attempting rebase of '${branchname}' onto '${basebranch}'..." git checkout --quiet "${branchname}" if ! git rebase "${basebranch}"; then cat >&2 <<EOF tools/tsflower: Rebase stopped. After you resolve the issue and complete the rebase, you can re-pack the revised branch into patches with: $ tools/tsflower pack EOF return 1 fi fi cat >&2 <<EOF Check that Flow passes, and make commits for any needed fixes. Then re-pack the revised branch into patches with: $ tools/tsflower pack EOF } pack() { check_no_uncommitted_changes local ref ref=$(git symbolic-ref HEAD) if ! [[ "${ref}" =~ ^refs/heads/ ]]; then echo >&2 "You are at a detached HEAD; no current branch." return 1 fi local branch=${ref#refs/heads/} local baseref baseref=$(git for-each-ref --format='%(upstream)' "${ref}") if [[ "${baseref}" != "${ref}"-base ]]; then echo >&2 "Current branch '${branch}' does not have '${branch}-base' as upstream." echo >&2 "Aborting. Did you want \`tools/tsflower unpack\` first?" return 1 fi local basebranch=${baseref#refs/heads/} local basebaseref basebaseref=$(git for-each-ref --format='%(upstream)' "${baseref}") if ! [[ "${basebaseref}" =~ ^refs/heads/ ]]; then echo >&2 "Base branch '${basebranch}' has non-branch '${basebaseref}' as upstream." echo >&2 "Aborting. Did you want \`tools/tsflower unpack\` first?" return 1 fi local basebasebranch=${basebaseref#refs/heads/} git checkout "${basebasebranch}" git restore -s "${ref}" -- 'types/*.js.flow' write_patches "${baseref}".."${ref}" # These globs are quoted because we don't want the shell expanding # them (to files that actually exist): we want Git to receive them # literally and interpret them as Git "pathspecs", so that they cover # deleted files as well as still- or newly-existing files. git add --no-ignore-removal -- \ 'types/patches/*.patch' 'types/*.js.flow' cat >&2 <<EOF Updated types and patches to reflect branch '${branch}'. \`git diff --shortstat HEAD\` says the differences are: 'types/*.js.flow': $(git diff --shortstat @ -- 'types/*.js.flow') 'types/patches/*.patch': $(git diff --shortstat @ -- 'types/patches/*.patch') Leaving it to you to commit, or amend existing commit. EOF } case "${1:-}" in check) check_consistent;; run) run;; # TODO also as default run-only) run_only;; apply-patches) apply_patches;; unapply-patches) unapply_patches;; write-patches) write_patches "${2:-}";; unpack) unpack "${@:2}";; pack) pack;; help | --help) usage;; '' | *) usage; exit 2;; esac ```
/content/code_sandbox/tools/tsflower
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
4,016
```unknown #!/usr/bin/env bash set -eu usage () { cat >&2 <<EOF usage: $0 Sync translations from and to Transifex, and commit. For background and setup instructions, see docs: docs/howto/translations.md This script is only useful for maintainers of the app (people who merge PRs), with Transifex credentials set up. In addition to the changes seen in the local repo and worktree, this has an important side effect in Transifex: the local set of message strings to be translated is taken as authoritative and synced to Transifex. This is how we provide new message strings to our translators; and it means this script should not be run on old or experimental versions of the app where the set of message strings may be different from what we currently want to request translations for. This makes up to two separate commits for different types of changes: * new translations already present in Transifex * default values in all languages for message strings recently added A third type of change is left uncommitted (and a link to docs is provided) because some steps are not yet automated: * new target languages EOF } err_echo () { echo >&2 "$@" } die () { err_echo "$@" exit 1 } run_visibly () { set -x "$@" { set +x; } 2>&- } while (( $# )); do case "$1" in --help) usage; exit 0;; *) usage; exit 2;; esac done this_dir=${BASH_SOURCE[0]%/*} . "${this_dir}"/lib/ensure-coreutils.sh root_dir=$(readlink -f "${this_dir}"/..) # This should point to a zulip.git worktree. Because this is a # maintainer script, we don't mind just requiring that convention. zulip_root="${root_dir%/*}"/zulip [ -r "${zulip_root}"/tools/lib/git-tools.bash ] \ || die "Expected Zulip worktree at: ${zulip_root}" . "${zulip_root}"/tools/lib/git-tools.bash # Ensure the index is up to date. Important before `git diff-files` # and other index-using porcelain commands. git_update_index () { # This incantation is borrowed from require_clean_work_tree. git update-index -q --ignore-submodules --refresh } require_clean_work_tree 'sync translations' err_echo err_echo 'Step 1: Download translated strings...' run_visibly cd "${root_dir}" run_visibly tx pull --silent --all --force git_update_index if ! git diff-files --quiet; then git commit -a -m ' i18n: Sync translations from Transifex Thanks as always to our kind volunteer translators. ' # I've (Greg) typed versions of that thanks many times, always # previously by hand. I feel slightly awkward having a script say # it... but that falls out of automating the rest of the workflow, # and the thanks remain real and I'd hardly want to stop saying them. git diff --stat @^ cat >&2 <<EOF Has a new language made major progress? See docs on updating the languages offered in the UI: path_to_url EOF else err_echo 'Step 1: ...none.' fi err_echo err_echo 'Step 2: Handle new languages...' git_update_index # This incantation checks if there are untracked files in the given directory. if git status -unormal --porcelain static/translations/ \ | grep -q .; then cat >&2 <<EOF There is at least one new language: EOF run_visibly git status -s static/translations/ cat >&2 <<EOF To finish adding it, see docs: path_to_url Then rerun this script to complete the rest of the sync. EOF exit 1 else err_echo 'Step 2: ...none.' fi err_echo err_echo 'Step 3: Upload strings to translate...' run_visibly tx push --silent run_visibly tx pull --silent --all --force git_update_index if ! git diff-files --quiet; then git commit -a -m ' i18n: Sync recently-added message strings across languages. ' cat >&2 <<'EOF' There were new message strings. Please push this commit promptly, to keep these changes separate from any new translations picked up the next time someone runs `tools/tx-sync`. If your branch has other changes that still need work or review, please rebase/cherry-pick the automated `tools/tx-sync` changes so you can push them promptly in isolation. EOF else err_echo 'Step 3: ...none.' fi ```
/content/code_sandbox/tools/tx-sync
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,063
```unknown #!/usr/bin/env bash set -euo pipefail shopt -s globstar # Tool to explore import cycles, as seen by Flow. # # Basic usage: # # # See what cycles exist: # $ tools/import-cycles # # # Then pick one and investigate: # $ tools/import-cycles inspect src/foo/bar.js # # Look for edges that seem like they're pointing in the wrong # direction, e.g. pointing out from subsystems that should be # self-contained. Then try cutting them and rerunning. # # Tip: To quickly find out how helpful it'd be to cut a given edge, # just comment that import out (even though it causes an error where # it's used) and rerun. # # NB these cycles generally do *not* mean an import cycle in the # transpiled runtime code. In fact, we use ESLint to prohibit those, # with rule import/no-cycle. this_file=$(readlink -f "$0") rootdir=${this_file%/*/*} bindir=${rootdir}/node_modules/.bin # List all the files and import-edges in this file's cycle-blob. # # If this file doesn't participate in any (nontrivial) import cycles, # then the output is empty. inspect_blob() { local f="$1"; "${bindir}"/flow cycle --strip-root "${f}" } # List the files that participate in a cycle-blob with this one. # # If this file doesn't participate in any (nontrivial) import cycles, # then the output is empty. blob_at() { local f="$1"; inspect_blob "${f}" \ | perl -lane 'print $1 if (/"(.*?)"/)' \ | sort -u } # List at least one file from each cycle-blob. # # Note this may not include all the files that participate in import # cycles, even if it includes most of them. survey() { "${rootdir}"/tools/tsort-modules pairs \ | tsort 2>&1 >/dev/null \ | sort -u \ | perl -lne 'print $1 if (/ (.*\.js)$/)' \ || : # expect tsort to fail } # List all the (nontrivial) import cycle-blobs. # # That is, all the strongly-connected components of the import graph, # other than those consisting of a single node. list_blobs() { local tmpdir f tmpdir="$(mktemp -d)" survey >"${tmpdir}"/survey cp "${tmpdir}"/survey "${tmpdir}"/todo while [ -s "${tmpdir}"/todo ]; do read -r f <"${tmpdir}"/todo blob_at "${f}" | tee -a "${tmpdir}"/found echo grep -vxFf "${tmpdir}"/found "${tmpdir}"/survey >"${tmpdir}"/todo done } case "${1:-}" in inspect) inspect_blob "$2";; at) blob_at "$2";; survey) survey;; ''|list) list_blobs;; esac ```
/content/code_sandbox/tools/import-cycles
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
690
```unknown #!/usr/bin/env bash this_file=$(readlink -f "${BASH_SOURCE[0]}") root=${this_file%/*/*} # List all direct dependencies, as package names. direct_dep_names() { <package.json \ jq '.dependencies + .devDependencies | keys[]' -r \ | LC_ALL=C sort } usage() { cat >&2 <<EOF usage: ${BASH_SOURCE[0]} EOF exit 1 } if (( $# > 0 )); then usage fi direct_dep_names ```
/content/code_sandbox/tools/deps
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
116
```unknown #!/usr/bin/env bash set -e ## CLI PARSING usage() { cat >&2 <<EOF usage: tools/android {apk | aab} Build the app for release on Android, either as an APK or an Android App Bundle. EOF exit 2 } action= case "${1}" in apk|aab) action="${1}"; shift;; *) usage;; esac if (( ${#} )); then usage fi ## MISC run_visibly () { set -x "$@" { set +x; } 2>&- } ## EXECUTION rootdir=$(git rev-parse --show-toplevel) cd "${rootdir}" check_yarn_link() { local linked_paths=() for f in node_modules/* node_modules/@*/*; do [[ -L "$f" ]] && linked_paths+=( "${f}" ) done if (( ${#linked_paths[@]} )); then cat >&2 <<EOF Error: There are dependencies set to local patched versions with \`yarn link\`. Consider the following to clean up: $ rm -- ${linked_paths[*]@Q} $ yarn install --force Then retry. EOF exit 1 fi } do_apk() { check_yarn_link run_visibly yarn run_visibly tools/gradle :app:assembleRelease -Psigned -Psentry } do_aab() { check_yarn_link run_visibly yarn run_visibly tools/gradle :app:bundleRelease -Psigned -Psentry } case "${action}" in apk) do_apk ;; aab) do_aab ;; esac ```
/content/code_sandbox/tools/android
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
376
```unknown #!/usr/bin/env bash set -e ## CLI PARSING usage() { cat >&2 <<EOF usage: tools/checkout-keystore Temporarily decrypt the keystore file for signing an Android release. By using this, a release manager can ensure that the secrets are only accessible for short periods when they're explicitly thinking about a release. This primarily guards against accidents: no slip of the keyboard, no sharp-edged tool with surprising behavior in an edge case, and no outright buggy tool can cause a validly-signed release build unless the release manager has decrypted the key. Setup: * You'll need the \`sq\` command installed, the CLI for Sequoia PGP, which is a modern implementation of OpenPGP. * The decryption key is expected by default at a path ~/.config/sq/KEYNAME.key.pgp , where KEYNAME defaults to \$USER. KEYNAME can be set with \`git config zulip.keystoreKeyName\`. The directory ~/.config can be overridden by \$XDG_CONFIG_HOME. * See also setup instructions in docs/howto/release.md . EOF exit 2 } if (( ${#} )); then usage fi ## EXECUTION rootdir=$(git rev-parse --show-toplevel) cleartext="${rootdir}"/android/release.keystore cryptotext="${rootdir}"/android/release.keystore.pgp key_name=$(git config zulip.keystoreKeyName || echo "${USER}") sq_user_dir="${XDG_CONFIG_HOME:-${HOME}/.config}"/sq recipient_key="${sq_user_dir}"/"${key_name}".key.pgp # `sq decrypt` prints obnoxious, confusing output about the key file # to stderr. Filter that out (as a normal pipe-style filter, from # stdin to stdout.) filter_sq_stderr() { grep -vE '^(Compressed|Encrypted) ' } sq decrypt --recipient-key "${recipient_key}" \ -o "${cleartext}" "${cryptotext}" \ 2> >(filter_sq_stderr >&2) wait_min=15 ( sleep "$(( ${wait_min} * 60 ))" rm -f "${cleartext}" ) & cat >&2 <<EOF Wrote decrypted file: ${cleartext} This file will be deleted in ${wait_min} minutes. EOF ```
/content/code_sandbox/tools/checkout-keystore
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
507
```yaml parser: hermes-eslint plugins: - ft-flow rules: ft-flow/no-weak-types: error ft-flow/require-parameter-type: - error - excludeArrowFunctions: true ft-flow/require-return-type: - error - always - excludeArrowFunctions: true excludeMatching: - "^render$" # Things that might also be good and we might do after the areas above # are clean or nearly clean: # - change `excludeArrowFunctions` to "expressionsOnly", for both # parameter and return types ```
/content/code_sandbox/tools/flow-todo.eslintrc.yaml
yaml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
128
```unknown #!/usr/bin/env node /** * Rebuild our custom icon font, zulip-icons.ttf. * * To use these icons, just use our component `ZulipIcon`. * * To add a new icon: * * * Update the shared package to a version that has the icon. * (The icons are `shared/icons/*.svg`.) See: * path_to_url * * * Rerun this script. It will update two files: * static/assets/fonts/zulip-icons.ttf * static/assets/fonts/zulip-icons.map.js * * * If you have a debug build of the app, hot reload will not work * across this change. You must rebuild the app (with * `tools/run-android`, `react-native run-ios`, or the equivalents * inside Android Studio or Xcode), just like if you'd edited native * code. * * * Now the new icon will be available for use. * * * Commit the changes, and include them in a PR. * * (An alternate way we could have this work would be for the script to run * automatically at build time, instead of having the generated font live in * the Git tree. That would have a small downside in that Flow would no * longer see the actual set of available icon names for type-checking uses * of `ZulipIcon`.) */ /* eslint-env node */ const fs = require('fs'); const os = require('os'); const path = require('path'); const webfontsGenerator = require('@vusion/webfonts-generator'); /** Absolute path to the directory at the root of the given package. */ const packagePath = packageName => path.dirname(require.resolve(`${packageName}/package.json`)); const fontName = 'zulip-icons'; // The root of our tree. const rootDir = path.dirname(__dirname); function listSvgFiles(dirPath) { return fs .readdirSync(dirPath) .filter(name => name.endsWith('.svg')) .map(name => path.join(dirPath, name)); } async function main() { const iconFiles = [ ...listSvgFiles(path.join(packagePath('@zulip/shared'), 'icons')), ...listSvgFiles(path.join(rootDir, 'static/icons')), ]; const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'build-icon-font-')); // This gets mutated by `webfonts-generator` to tell us the generated mapping. const codepoints = {}; await new Promise((resolve, reject) => webfontsGenerator( { dest: tmpDir, codepoints, fontName, files: iconFiles, types: ['ttf'], css: false, // Useful for debugging: // html: true, }, err => (err ? reject(err) : resolve()), ), ); const destDir = path.join(rootDir, 'static', 'assets', 'fonts'); fs.copyFileSync(path.join(tmpDir, `${fontName}.ttf`), path.join(destDir, `${fontName}.ttf`)); fs.writeFileSync( path.join(destDir, `${fontName}.map.js`), `\ /* * This file is @${'generated'} -- do not edit. * To make changes, see tools/build-icon-font. * * @flow strict */ export default ${JSON.stringify(codepoints, undefined, 2)}; `, ); fs.rmSync(tmpDir, { recursive: true }); } main(); ```
/content/code_sandbox/tools/build-icon-font
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
746
```shell # shellcheck shell=bash # Filter out filenames excluded by our .eslintignore. # # Filenames are expected as arguments, and printed, leaving out those that # should be ignored. # # (This is a workaround: the ideal solution would be for ESLint to accept an # option saying to apply its ignore rules and to not worry if that filters # out some or all of the files we named, and then we wouldn't need this.) apply_eslintignore() { # This uses only the .eslintignore file at the root. It relies on us # having no other sources of ESLint file ignores: other .eslintignore # files, `ignorePatterns` in the eslintrc, etc. # # But if we do, the worst case is that we'll reintroduce #5081: the # interactive `tools/test` (never CI) will fail when one of those # ignored files is touched, because of an awkward CLI choice in ESLint. # ESLint ignore files are documented as having the gitignore syntax: # path_to_url # So we ask Git to interpret the file for us. The main limitation is # that while we can tell it one file to apply, we can't give it several, # or tell it to look for .eslintignore files throughout the tree. # # The `git check-ignore` command wants to tell us what files have been # excluded, not included. With `-nv` it gives us both and we can # extract which is which. (( $# )) || return 0 # if no arguments, no output git -c core.excludesFile=.eslintignore check-ignore --no-index -nv "$@" \ | perl -lne 'print if (s/^::\t//)' } ```
/content/code_sandbox/tools/lib/eslintignore.sh
shell
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
395
```shell # shellcheck shell=bash # # Usage: # . ensure-coreutils.sh # # Ensures GNU coreutils are available in PATH. # May add to PATH, or exit with a message to stderr. # # The GNU coreutils are a basic piece of infrastructure for having # a reasonable 21st-century shell scripting environment, so we # freely invoke this in any of our scripts that need `readlink -f` # or other features not always found without them. # # On any GNU/Linux system this is of course a non-issue. Likewise # on Windows: we inevitably require Git, and Git for Windows comes # with a GNU environment called "Git BASH", based on MSYS2. # # So this is really all about macOS. Fortunately it's easy to get # coreutils installed there too... plus, many people already have # it installed but just not in their PATH. We write our scripts # for a GNU environment, so we bring it into the PATH. # Check, silently, for a working coreutils on the PATH. check_coreutils() { # Check a couple of commands for GNU-style --help and --version, # which macOS's default BSD-based implementations don't understand. fmt --help >/dev/null 2>&1 readlink --version 2>&1 | grep -q GNU } # Either get Homebrew's coreutils on the PATH, or error out. try_homebrew() { local homebrew_prefix="$1" # Homebrew provides names like `greadlink` on the PATH, # but also provides the standard names in this directory. homebrew_gnubin="${homebrew_prefix}"/opt/coreutils/libexec/gnubin if ! [ -d "${homebrew_gnubin}" ]; then cat >&2 <<EOF This script requires GNU coreutils. Found Homebrew at: ${homebrew_prefix} but no coreutils at: ${homebrew_gnubin} Try installing coreutils with: brew install coreutils EOF return 2 fi export PATH="${homebrew_gnubin}":"$PATH" if ! check_coreutils; then cat >&2 <<EOF This script requires GNU coreutils. Found Homebrew installation of coreutils at: ${homebrew_gnubin} but it doesn't seem to work. Please report this in #mobile-dev-help on path_to_url and we'll help debug. EOF return 2 fi } ensure_coreutils() { # If we already have it, then great. check_coreutils && return # Else try finding a Homebrew install of coreutils, # and putting that on the PATH. homebrew_prefix=$(brew --prefix || :) if [ -n "${homebrew_prefix}" ]; then # Found Homebrew. Either use that, or if we can't then # print an error with Homebrew-specific instructions. try_homebrew "${homebrew_prefix}" return fi cat >&2 <<EOF This script requires GNU coreutils. Install from upstream: path_to_url or from your favorite package manager. If you have any questions, ask in #mobile-dev-help on path_to_url and we'll be happy to help. EOF return 2 } ensure_coreutils || exit ```
/content/code_sandbox/tools/lib/ensure-coreutils.sh
shell
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
724
```javascript /** * Setup: * yarn global add jscodeshift * * Sample usage: * jscodeshift -t tools/codemod/intersection-to-spread.js src/actionTypes.js * * NOTE doesn't quite work right -- turns `type Foo` to `type type Foo`. * This seems to be a bug triggered by handing jscodeshift's `replaceWith` * a result from its `objectTypeAnnotation`. Easy to work around in * post-processing, at least... but it doesn't give a ton of confidence * in jscodeshift as a solid piece of infrastructure. * * For future codemods, consider using `recast` directly (the underlying * engine employed by jscodeshift), or finding some other helpful wrapper * around it. Quick braindump of ideas and/or browser tabs: * * An ESLint rule with a fixer? * * Could keep the jscodeshift CLI, and just skip its parse/replace/unparse * methods; that'd look like `recast.parse(fileInfo.source)`, then * `recast.visit` and mutate the relevant nodes, then `recast.print`. * See `recast` docs, or example users of it like: * path_to_url * * Scan through path_to_url * * Other handy tips: * * See path_to_url and choose parser `flow` (in the bit of * UI that initially says `acorn`.) Super handy for finding the AST * names for the constructs you want to find/modify. * * For bringing in fancier analyses from an external tool like Flow, see * the technique used here -- it ends up being super simple, thankfully: * path_to_url */ export const parser = 'flow'; export default function (fileInfo, { jscodeshift: j, report }) { const root = j(fileInfo.source); root.find(j.IntersectionTypeAnnotation).forEach(anno => { const { types } = anno.value; const endType = types[types.length - 1]; if (endType.type !== 'ObjectTypeAnnotation') { report(`ixn with non-object at ${JSON.stringify(anno.value.range)}`); return; } const leftTypes = types.slice(0, types.length - 1); const newType = j.objectTypeAnnotation([ ...leftTypes.map(type => j.objectTypeSpreadProperty(type)), ...endType.properties, ]); j(anno).replaceWith(newType); }); return root.toSource(); } ```
/content/code_sandbox/tools/codemod/intersection-to-spread.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
552
```javascript // For facebook/jest#10221. After savePromise.js and Jest's setup // files have run, restore the natural value of `global.Promise`. global.Promise = global.originalPromise; ```
/content/code_sandbox/jest/restorePromise.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
40
```javascript // For facebook/jest#10221. Before Jest's setup files have run, take // note of what the natural value of `global.Promise` is, so we can // restore it in restorePromise.js. global.originalPromise = Promise; ```
/content/code_sandbox/jest/savePromise.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
52
```javascript /** * The preset we're making tweaks to. */ const basePreset = require('../node_modules/jest-expo/ios/jest-preset.js'); // See comment in our Jest config about how this is used. module.exports = { ...basePreset, setupFiles: [ require.resolve('./savePromise.js'), ...basePreset.setupFiles, require.resolve('./restorePromise.js'), ], }; ```
/content/code_sandbox/jest/presetIos.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
88
```javascript global.fetch = jest.fn(); fetch.mockResponseSuccess = body => { fetch.mockImplementation(() => Promise.resolve({ json: () => Promise.resolve(JSON.parse(body)), status: 200, ok: true }), ); }; fetch.mockResponseFailure = error => { fetch.mockImplementation(() => Promise.reject(error)); }; fetch.mockErrorStatusCode = status => { fetch.mockImplementation({ status }); }; fetch.reset = () => { fetch.mockReset(); }; ```
/content/code_sandbox/jest/globalFetch.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
94
```javascript /** * The preset we're making tweaks to. */ const basePreset = require('../node_modules/jest-expo/android/jest-preset.js'); // See comment in our Jest config about how this is used. module.exports = { ...basePreset, setupFiles: [ require.resolve('./savePromise.js'), ...basePreset.setupFiles, require.resolve('./restorePromise.js'), ], }; ```
/content/code_sandbox/jest/presetAndroid.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
87
```javascript // @flow strict-local /* eslint-disable no-underscore-dangle */ let _allowUnhandled = false; /** * (If using this, be sure to check for unhandled.) * * For example: beforeAll(() => immediate.allowUnhandled()); afterAll(() => immediate.disallowUnhandled()); afterEach(() => expect(immediate.takeUnhandled()).toEqual([])); Then each test can check for the expected unhandled errors like: expect(immediate.takeUnhandled()).toMatchObject([new Error('some message')]); or can explicitly discard unhandled errors, if desired, like: immediate.takeUnhandled(); */ export function allowUnhandled() { _allowUnhandled = true; } export function disallowUnhandled() { _allowUnhandled = false; } let unhandledErrors: mixed[] = []; // TODO also have a way to await for immediates to settle? export function takeUnhandled(): mixed[] { const e = unhandledErrors; unhandledErrors = []; return e; } export function immediate(cb: () => void): void { if (!_allowUnhandled) { Promise.resolve().then(cb); return; } Promise.resolve().then(() => { try { cb(); } catch (e) { unhandledErrors.push(e); } }); } export default immediate; immediate.allowUnhandled = allowUnhandled; immediate.disallowUnhandled = disallowUnhandled; immediate.takeUnhandled = takeUnhandled; ```
/content/code_sandbox/jest/mock-immediate.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
298
```javascript // @flow strict-local // // TODO: this should probably go to expo-sqlite upstream. // // Not really so much a "mock" as a fourth platform-specific implementation: // this one for Node (and therefore for Jest), complementing upstream's for // Android, iOS, and web. // // OK, well, it's a mock in one respect: the databases are all in-memory, // which is helpful for isolation. There's also a `deleteDatabase` function // which is useful for tests. import type { Query, SQLiteCallback, WebSQLDatabase } from 'expo-sqlite'; // We import this dependency of expo-sqlite directly, because we're // substituting for the expo-sqlite implementation that uses it. (In a // future where expo-sqlite no longer used this dependency, we'd want to // make a similar change here, not keep using it.) /* eslint-disable import/no-extraneous-dependencies */ // $FlowFixMe[untyped-import] import customOpenDatabase from '@expo/websql/custom'; import sqlite3, { type Database, type QueryParameter } from 'sqlite3'; /* eslint-disable no-underscore-dangle */ /* eslint-disable no-void */ const dbs = new Map(); function openDb(name: string) { const db = dbs.get(name); if (db != null) { return db; } const newDb = new sqlite3.Database(':memory:'); dbs.set(name, newDb); return newDb; } class SQLiteDatabase { _db: Database; _closed: boolean = false; _allowUnhandled: boolean = false; constructor(name: string) { this._db = openDb(name); } exec(queries: Query[], readOnly: boolean, callback: SQLiteCallback): void { if (this._closed) { throw new Error('already closed'); } void this._exec(queries, callback); } async _exec(queries, callback) { const results = []; try { for (const { sql, args } of queries) { /* eslint-disable no-shadow */ const rows = await new Promise((resolve, reject) => /* $FlowFixMe[incompatible-cast] -- expo-sqlite has "args: mixed[]", which seems too broad */ this._db.all(sql, (args: QueryParameter[]), (err, rows) => err ? reject(err) : resolve(rows), ), ); // TODO get rowsAffected and insertId. This will mean calling // `this._db.run` instead of `this._db.all`: // path_to_url#databaserunsql-param--callback // which on the other hand will mean it doesn't return rows. // // The way the Android implementation makes the equivalent choice // is by checking if the statement looks like a SELECT. // The iOS implementation uses the SQLite C API, and ends up looking // more sensible. // Given what node-sqlite3 gives us, our best strategy is probably // the one in the Android implementation. results.push({ rowsAffected: 0, rows }); } } catch (e) { try { callback(e); } catch (e) { if (!this._allowUnhandled) { throw e; } } return; } try { callback(null, results); } catch (e) { if (!this._allowUnhandled) { throw e; } } } close() { this._closed = true; this._db.close(); } /** * Suppress otherwise-unhandled Promise rejections when a statement callback throws. * * Not found in expo-sqlite itself, but helpful for tests. */ allowUnhandled() { this._allowUnhandled = true; } } /** Not found in expo-sqlite itself, but helpful for tests. */ export function deleteDatabase(name: string) { const db = dbs.get(name); if (!db) { return; } db.close(); dbs.delete(name); } export function openDatabase( name: string, version?: string, description?: string, size?: number, callback?: (db: WebSQLDatabase) => void, ): WebSQLDatabase { const db = customOpenDatabase(SQLiteDatabase)(name, version, description, size, callback); db._db = new SQLiteDatabase(name); db.exec = (...args) => db._db.exec(...args); return db; } ```
/content/code_sandbox/jest/mock-expo-sqlite.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
985
```javascript /* @flow strict-local */ // This is supposed to be an async function: // path_to_url#globalsetup-string. // But something goes wrong with React Native v0.64, and the global // `regeneratorRuntime` from @babel/plugin-transform-runtime, the thing that // transpiles away async function syntax, isn't available when the code in // this file runs. Easy enough to make it a non-async function as a // workaround. module.exports = () => { // Where this has any effect (macOS and Linux), set Node's timezone to // UTC, to help make snapshot tests be consistent in local testing and in // CI. To handle places this doesn't have an effect (Windows), we should // also modify our code (e.g., in src/utils/date.js) so that, only when // testing, they negate the UTC offset of a `Date` object before using it. // // This is in `globalSetup.js` so that it runs as early as possible; we // don't want a wrong TZ value to be cached and then used instead of UTC: // path_to_url#issuecomment-149583284 process.env.TZ = 'UTC'; }; ```
/content/code_sandbox/jest/globalSetup.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
267
```javascript /* * This file is @generated -- do not edit. * To make changes, see tools/build-icon-font. * * @flow strict */ export default { "bot": 61697, "ellipsis-v-solid": 61698, "gif": 61699, "globe": 61700, "language": 61701, "mute": 61702, "readreceipts": 61703, "follow": 61704 }; ```
/content/code_sandbox/static/assets/fonts/zulip-icons.map.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
104
```javascript /* @flow strict-local */ import type { Subscription } from './types'; export const NULL_OBJECT: {||} = Object.freeze({}); export const NULL_ARRAY: $ReadOnlyArray<empty> = Object.freeze([]); /* * All the below objects are DEPRECATED; rather than using one, choose the * appropriate fallback behavior explicitly. See 25125db94 for more * discussion. * * Further changes to eliminate the remaining uses of these would be great. * * For examples of explicit fallback behavior, see: * * * Selector `getAuth` -- throw an error. Good when missing data is a bug * and the caller can't reasonably do without it. This is the right * thing for most callers of most selectors. * * * Selectors `tryGetActiveAccountState` and `tryGetAuth` -- return undefined, * and reflect that in the type. Caller then gets to decide what to do; * see callsites of `tryGetAuth`. * * * Commit 7829bef43 -- simple cases showing a couple of different * fallbacks. * * * Commit e22596c24 -- throwing an error, in a case that required some * more work to decide that was the right thing. */ /** DEPRECATED; don't add new uses. See block comment above definition. */ export const NULL_SUBSCRIPTION: Subscription = { audible_notifications: false, color: 'gray', description: '', rendered_description: '', desktop_notifications: false, email_address: '', in_home_view: false, invite_only: false, name: '', pin_to_top: false, stream_id: 0, stream_weekly_traffic: 0, push_notifications: false, is_old_stream: false, is_announcement_only: false, is_web_public: false, history_public_to_subscribers: false, first_message_id: null, }; ```
/content/code_sandbox/src/nullObjects.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
414
```javascript /* @flow strict-local */ /* eslint-disable global-require */ import * as ReactNative from 'react-native'; import { polyfillGlobal } from 'react-native/Libraries/Utilities/PolyfillFunctions'; import { URL, URLSearchParams } from 'react-native-url-polyfill'; // $FlowIgnore[untyped-import] - this is not anywhere near critical import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'; // $FlowIgnore[untyped-import] import mockClipboard from '@react-native-clipboard/clipboard/jest/clipboard-mock'; import { assertUsingFakeTimers } from '../src/__tests__/lib/fakeTimers'; // Use the same `URL` polyfill we do in the app. // // In the app we let `react-native-url-polyfill` handle doing this, by // importing `react-native-url-polyfill/auto`. But in Jest, that produces // warnings apparently due to the lazy `require()` calls in the getters // provided for the polyfill; perhaps from them getting invoked by the Jest // framework after the test environment has been torn down. // path_to_url#issuecomment-749247080 // So we mimic the library's way of doing the polyfill, except we do the // imports eagerly so there's no dynamic `require`. polyfillGlobal('URL', () => URL); polyfillGlobal('URLSearchParams', () => URLSearchParams); // Default should be set with `timers: 'fake'` in Jest config. assertUsingFakeTimers(); // Mock `react-native` ourselves, following upstream advice [1] [2]. // // Note that React Native's Jest setup (in their jest/setup.js) // means that most of `react-native` is already mocked; we add to that // here. // // We can't do `ReactNative.Foo = ...` because all properties Foo on // the react-native module have getters but no setters. But we can set // properties freely at the next level down: // // ReactNative.Foo.Bar = ... // // Or set multiple properties at this level, together: // `Object.assign(ReactNative.Foo, { ... })`. // // If we *really* want to replace a top-level property: // // Object.defineProperty(ReactNative, "Foo", { ... }); // // [1] path_to_url#issuecomment-535244001 // [2] path_to_url#narrow/stream/243-mobile-team/topic/.23M3781.20RN.20v0.2E61.20upgrade/near/931219 jest.mock('react-native', () => { if (ReactNative.Platform.OS === 'ios') { ReactNative.NativeModules.ZLPConstants = { resourceURL: 'file:///private/var/containers/Bundle/Application/4DCD4D2B-F745-4C70-AD74-8E5F690CF593/ZulipMobile.app/', }; } else if (ReactNative.Platform.OS === 'android') { const header = 'z|mock|'; ReactNative.NativeModules.TextCompressionModule = { header, compress: jest.fn( async (input: string) => `${header}${Buffer.from(input).toString('base64')}`, ), decompress: jest.fn(async (input: string) => Buffer.from(input.replace(header, ''), 'base64').toString('utf8'), ), }; } return ReactNative; }); jest.mock('immediate', () => require('./mock-immediate').default); jest.mock('expo-sqlite', () => require('./mock-expo-sqlite')); /** * Boring mocks * * We aren't interested in any specific data in these mocks; they just * make things not break. Usually it's because these JS modules depend * on something being available on NativeModules, and we'd rather not * mock that precisely, as it's an implementation detail that may * change. * * If Jest complains about syntax errors in a module in node_modules, * it's likely because the only code it finds for the module is modern * JavaScript that needs to be transformed by Babel. In that case, try * adding the module to `transformModulesWhitelist` in our Jest config * before mocking it here. */ // As instructed at path_to_url jest.mock('react-native-reanimated', () => { /* $FlowIgnore[untyped-import] - This is just a mock setup file; no need for a libdef. */ const Reanimated = require('react-native-reanimated/mock'); // The mock for `call` immediately calls the callback which is incorrect // So we override it with a no-op Reanimated.default.call = () => {}; return Reanimated; }); jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage); // As instructed at // path_to_url#mocking-clipboard jest.mock('@react-native-clipboard/clipboard', () => mockClipboard); // We don't try to actually exercise this module in tests; we just test // some code in the same module as other code that imports it. Unmocked, // it complains of missing native modules. jest.mock('@react-native-camera-roll/camera-roll', () => ({})); // Without this, we get lots of these errors on importing the module: // `Invariant Violation: Native module cannot be null.` jest.mock('@react-native-community/push-notification-ios', () => ({ presentLocalNotification: jest.fn(), scheduleLocalNotification: jest.fn(), cancelAllLocalNotifications: jest.fn(), removeAllDeliveredNotifications: jest.fn(), getDeliveredNotifications: jest.fn(), removeDeliveredNotifications: jest.fn(), // etc. (incomplete) })); jest.mock('rn-fetch-blob', () => ({ DocumentDir: () => {}, })); jest.mock('react-native-simple-toast', () => ({ SHORT: 2.0, LONG: 3.5, TOP: 3, BOTTOM: 1, CENTER: 2, show: jest.fn(), showWithGravity: jest.fn(), })); // Set up our `logging` module with mocks, which tests can use as desired. // // This global version just passes the calls right through to the real // implementations. To suppress logging in a specific test, make a call // like `logging.warn.mockReturnValue()`. For more, see: // path_to_url // or search our code for `logging.warn.` for examples. jest.mock('../src/utils/logging', () => { const logging = jest.requireActual('../src/utils/logging'); return { __esModule: true, // eslint-disable-line id-match error: jest.fn().mockImplementation(logging.error), warn: jest.fn().mockImplementation(logging.warn), info: jest.fn().mockImplementation(logging.info), ExtendableError: logging.ExtendableError, }; }); ```
/content/code_sandbox/jest/jestSetup.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,475
```javascript /** * Backports of handy functions from newer (or proposed) versions of JavaScript. * * Almost like polyfills -- except rather than actually muck with names and * objects that belong to the standard library, we give our versions their * own distinct names. * * @flow strict-local */ /** * Backport of `Object.fromEntries`. * * See documentation on MDN: * path_to_url * * This version requires an `Array` just because that was easiest to * implement and is all we happened to need. Would be nice to extend to * iterables. */ export function objectFromEntries<+K, +V>(entries: $ReadOnlyArray<[K, V]>): {| [K]: V |} { const obj = ({}: {| [K]: V |}); entries.forEach(entry => { obj[entry[0]] = entry[1]; }); return obj; } /** * A simplified version of Promise#allSettled. * * See doc on MDN: * path_to_url * * This version is simplified for convenient implementation and because we * didn't happen to need the extra features: * * The argument must be an `Array`. * * No details about the promises' outcomes are provided. */ export function allSettled(promises: $ReadOnlyArray<Promise<mixed>>): Promise<void> { const total = promises.length; if (total === 0) { return Promise.resolve(); } let completed = 0; return new Promise(resolve => { promises.forEach(async p => { try { await p; } finally { completed++; if (completed === total) { resolve(); } } }); }); } ```
/content/code_sandbox/src/jsBackport.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
371
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View, Text, TextInput, ScrollView, Button, Platform } from 'react-native'; import Clipboard from '@react-native-clipboard/clipboard'; import Toast from 'react-native-simple-toast'; import * as logging from './utils/logging'; import { type JSONableDict } from './utils/jsonable'; type Props = $ReadOnly<{| children: Node, |}>; type State = $ReadOnly<{| error: Error | null, |}>; /** * A React error boundary to go as near the root as possible. * * React error boundaries [1] shouldn't be used as part of a normal * control flow; it's best and simplest to strive to keep our * component hierarchy error-free. But mistakes happen, and when they * do, we don't want to leave the user empty-handed in debugging * conversations when we can have the app provide some useful * information. So, cast a wide net for errors at the edge. * * Implemented carefully so that we don't get a white-screen crash * from this component itself. It doesn't depend on any external setup * except Sentry's initialization (without which we'd have no hope of * reporting the error to Sentry), e.g., from other React components * in the tree. N.B., this means things like proper safe-area * handling, light-dark theming, and translation won't work. * * [1] path_to_url#how-about-event-handlers */ export default class ErrorBoundary extends React.PureComponent<Props, State> { static getDerivedStateFromError(error: Error): State { return { error }; } componentDidCatch(error: Error, errorInfo: mixed) { // The error was caught [1], so Sentry wouldn't hear about it // unless we intervene. // // [1] Er, possibly it gets rethrown in development mode. See // path_to_url // "In development mode, React will rethrow errors caught // within an error boundary. This will result in errors being // reported twice to Sentry with the above setup, but this // wont occur in your production build." logging.error( error, // Pretend errorInfo is a JSONableDict. // // Empirically, Sentry will still be notified even if the value at // some key in errorInfo is non-JSONable. It seems like Sentry calls // JSON.stringify(value) first, and if that fails it calls // value.toString(). If *that* fails (either because value.toString // isn't a function, or if it's a function that throws an error)then // the "Additional Data" section in Sentry's UI will have an error box // that says "There was a problem rendering this component". But in // all cases, the Sentry event successfully makes it to Sentry. // // $FlowIgnore[incompatible-cast] (errorInfo: JSONableDict), ); } state: State = { error: null, }; render(): Node { const { error } = this.state; if (error) { const details = `${error.toString()} Component Stack: ${ /* $FlowFixMe[prop-missing] - I've seen this empirically in debug and release builds on iOS and Android */ error.componentStack ?? '<none available>' } Call Stack: ${error.stack}`; return ( <View style={{ // Fill the whole screen (well, the parent, which is // hopefully the whole screen). flex: 1, alignItems: 'center', justifyContent: 'center', // Simulate `SafeAreaView` without counting on // `SafeAreaProvider`. padding: 50, }} > <Text>Ouch, there was an error.</Text> <Button title="Copy details" // If something in `onPress` fails, we shouldn't get a // white screen [1]: "Unlike the render method and // lifecycle methods, the event handlers dont happen // during rendering. So if they throw, React still knows // what to display on the screen." // // [1] path_to_url#how-about-event-handlers. onPress={() => { Clipboard.setString(details); Toast.show('Copied!'); }} /> {Platform.select({ ios: ( <TextInput style={{ // To not grow outside the parent View flex: 1, // This doesn't seem to work on Android fontFamily: 'Courier', }} multiline editable={false} value={details} /> ), android: ( // For Android-only symptoms like // facebook/react-native#23117 <ScrollView> <TextInput style={{ // To not grow outside the parent View flex: 1, // This doesn't seem to work on iOS fontFamily: 'monospace', }} multiline editable={false} value={details} /> </ScrollView> ), })} </View> ); } return this.props.children; } } ```
/content/code_sandbox/src/RootErrorBoundary.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,134
```javascript /* @flow strict-local */ import type { PerAccountState, GlobalState, AccountsState, SubscriptionsState, StreamsState, OutboxState, UsersState, UserGroupsState, DraftsState, FetchingState, FlagsState, MessagesState, MutedUsersState, NarrowsState, TopicsState, CrossRealmBot, RealmEmojiById, RealmState, PerAccountSettingsState, GlobalSettingsState, TypingState, VideoChatProvider, User, } from './types'; import type { PerAccountSessionState, GlobalSessionState } from './session/sessionReducer'; export const getAccounts = (state: GlobalState): AccountsState => state.accounts; export const getSession = (state: PerAccountState): PerAccountSessionState => state.session; export const getGlobalSession = (state: GlobalState): GlobalSessionState => state.session; export const getIsOnline = (state: GlobalState): boolean | null => state.session.isOnline; export const getIsHydrated = (state: GlobalState): boolean => state.session.isHydrated; export const getCanCreateStreams = (state: PerAccountState): boolean => state.realm.canCreateStreams; export const getDrafts = (state: PerAccountState): DraftsState => state.drafts; export const getLoading = (state: PerAccountState): boolean => state.session.loading; export const getMessages = (state: PerAccountState): MessagesState => state.messages; export const getMutedUsers = (state: PerAccountState): MutedUsersState => state.mutedUsers; export const getTyping = (state: PerAccountState): TypingState => state.typing; export const getTopics = (state: PerAccountState): TopicsState => state.topics; export const getUserGroups = (state: PerAccountState): UserGroupsState => state.userGroups; /** * WARNING: despite the name, only (a) `is_active` users (b) excluding cross-realm bots. * * See `getAllUsers`. */ export const getUsers = (state: PerAccountState): UsersState => state.users; export const getFetching = (state: PerAccountState): FetchingState => state.fetching; export const getFlags = (state: PerAccountState): FlagsState => state.flags; export const getAllNarrows = (state: PerAccountState): NarrowsState => state.narrows; export const getSettings = (state: PerAccountState): PerAccountSettingsState => state.settings; export const getGlobalSettings = (state: GlobalState): GlobalSettingsState => state.settings; export const getSubscriptions = (state: PerAccountState): SubscriptionsState => state.subscriptions; /** * All streams in the current realm. * * This is rarely the right selector to use: consider `getStreamForId` * or `getStreamsById` instead. */ export const getStreams = (state: PerAccountState): StreamsState => state.streams; export const getOutbox = (state: PerAccountState): OutboxState => state.outbox; export const getRealm = (state: PerAccountState): RealmState => state.realm; export const getRealmName = (state: PerAccountState): string => state.realm.name; export const getRealmDescription = (state: PerAccountState): string => state.realm.description; export const getCrossRealmBots = (state: PerAccountState): $ReadOnlyArray<CrossRealmBot> => state.realm.crossRealmBots; export const getRawRealmEmoji = (state: PerAccountState): RealmEmojiById => state.realm.emoji; export const getNonActiveUsers = (state: PerAccountState): $ReadOnlyArray<User> => state.realm.nonActiveUsers; export const getVideoChatProvider = (state: PerAccountState): VideoChatProvider | null => state.realm.videoChatProvider; ```
/content/code_sandbox/src/directSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
817
```javascript /* @flow strict-local */ /** * Tools for manipulating generic types in the Flow type system. */ /** * The type `S`, plus a check that `S` is a supertype of `T`. * * Gives an error unless `S` is a supertype of `T` -- i.e., a `T` can always * be used where an `S` is required. * * See also `typesEquivalent`, which can be more convenient when not already * in the context of a type-level expression. */ // Flow would also accept `+S, +T`. But `+T` is wrong and it's a bug // that Flow would accept it; see demo_variance_short_circuit in tests. export type IsSupertype<+S, -T: S> = S; // eslint-disable-line no-unused-vars /** * Gives a type error unless a T can be used as a U and vice versa. * * In other words this gives an error unless, in the preorder (*) where each * type A is a "subtype" of B just if an A can be used as a B, the types T * and U are equivalent. * * Handy when testing or debugging complex type expressions, to check that * they come out to something equivalent to what you think they are. * * When two types are equivalent (and neither one involves an "unclear" type * like `any`), they are interchangeable for any direct uses. * * Examples: * * // These are two ways of spelling the same type. * typesEquivalent<$ReadOnly<{| x: number |}>, {| +x: number |}>(); * * // FlowExpectedError - These are different types :-) * typesEquivalent<number, number | void>(); // error * * Important caveat #1: When T or U is an "unclear type", i.e. one involving * `any` or its less-common friends `Object` or `Function`, this can give * misleading results. In particular, `any` will be reported as * "equivalent" to *whatever* type you try, even types that are not * equivalent to each other. * * This is because the subtype relation is only a preorder (*) when * unclear types are excluded. The meaning of `any` is that any A can be * used as `any`, and `any` as any B, even when A can't be used as B; and * that makes the relation not transitive. The "equivalent" terminology * really only makes sense in the context of a preorder. * * Not 100% sure the subtype relation is entirely a preorder even without * `any` and friends -- Flow is unfortunately not well documented at this * conceptual level. * * Important caveat #2: Sometimes complex type operations like $Diff can * take types that are equivalent in this sense and produce inequivalent * results. The only known examples of this involve types that probably * shouldn't be equivalent in the first place, namely object types where * the same property is optional on the one hand and required on the * other. See test `test_typesEquivalent_$Diff_surprise`. * * (*) "Preorder" means the relation is reflexive (A subtype A, for all A) * and transitive (whenever A subtype B subtype C, then also A subtype C.) * * See also `IsSupertype`, which is suitable to use directly in type-level * expressions. */ // eslint-disable-next-line no-unused-vars export function typesEquivalent<T, U: T, _InternalDoNotPass: U = T>() {} // Another formulation that's believed to give the same results: // (x: T): U => x; // (x: U): T => x; // Those together should be accepted exactly when typesEquivalent<T, U>() is. /** * An inverse of the operation `(A, B) => {| ...A, ...B |}`, with checking. * * Similar to `$Diff`, but checks that the subtraction makes sense. * Also always subtracts a given property completely, even if its type on * `L` happens to be more specific than on `U`. * * Assumes both `U` and `L` are exact, read-only, object types. (If not, * behavior unknown.) Returns a solution `D`, where possible, to the type * equation * `U == {| ...D, ...L |}` * with an (exact, read-only) object type `D`. * * More generally, returns the most general solution `D` to the relation * `{| ...D, ...L |}: U` (read "subtype of") * I.e., the most general type `D` such that `{| ...D, ...L |}` can be used * where a `U` is expected. If there is no such `D`, causes a type error. * * In particular, this means: * * Error if `L` has any extra properties that aren't in `U`. * * Error unless each property of `L` has the same type as in `U`, or a subtype * (i.e., the property's values in `L` are valid for `U`). * * `D` has exactly the properties in `U` that aren't in `L`. * * Each property of `D` has the same type as in `U`. */ // Flow would also accept `-U` or `+L` or any combination. But either of // those is wrong and Flow shouldn't accept them, for the same reasons as // around `IsSupertype`; see demo_variance_short_circuit in tests. // // This version `+U, -L` probably also shouldn't be accepted by Flow, given // that we haven't explained to it our requirement that U and L be exact, // read-only object types. But given that assumption, if one considers // type expressions BoundedDiff<U1, L1> and BoundedDiff<U2, L2> with // U1 <: U2 and on the other hand L2 <: L1, then working through each of the // points listed at the end of the jsdoc, one can see that if // BoundedDiff<U1, L1> is valid then so is BoundedDiff<U2, L2>, and the // former can appropriately flow to the latter. export type BoundedDiff<+U, -L> = // The $ReadOnly is to work around a Flow bug that `$Diff` loses variance: // path_to_url // (If we wanted to use BoundedDiff with non-read-only `U`, this // workaround wouldn't work; but happily we don't.) $ReadOnly< $Diff< // This `IsSupertype` is the part that checks that all of L's properties // (a) are present on U and (b) have appropriate types to use on U. IsSupertype<U, $ReadOnly<{| ...U, ...L |}>>, // This `$ObjMap` makes a variant of `L` that `$Diff` treats as more // powerful, ensuring that all properties in `L` are removed completely. $ObjMap<L, () => mixed>, >, >; /** * The object type `T` with its readonly annotation stripped. */ // The implementation relies on facebook/flow#6225, so it will // naturally have to change when that gets fixed. // // See discussion for an alternative, with `$ObjMap`, that seemed like // it was going to work, but didn't: // path_to_url#discussion_r593394451. // // TODO test this, so we notice when the Flow bug is fixed and breaks it. export type ReadWrite<T: $ReadOnly<{ ... }>> = $Diff<T, {||}>; /** * An object type with a subset of T's properties, namely those in U. * * Gives an error unless all properties of U also appear in T. Each * property's type in the result is the type of the same property in T. * * Handy when T is something like an options object and you want a type * representing a subset of the options in T. Write e.g. * `SubsetProperties<T, {| frobMode?: mixed |}>` for an object type that * permits only the `frobMode` option, with the exact same type T allows, * but without having to repeat the details of that type. * * A limitation: this implementation can't tell which properties are * *optional* in T, i.e. spelled with `?:`, as in `foo?: number`. Instead, * properties in the result will be optional or required based on how they * are in U. To avoid confusion, be sure to make the same properties * optional in U as are optional in T. (In the "options object" use case, * typically all the properties are optional.) */ // Implementation note: You might think to write this as something like // $Diff<T, $Diff<T, U>>. Or $Diff<T, $ObjMap<$Diff<T, U>, () => mixed>>. // In particular you might hope for this to avoid the limitation mentioned // above. // // Sadly that doesn't work (as of Flow v0.130) when T has any optional // properties not found in U: the first diff type will still have them // optional, this will still be true after the $ObjMap, and so the second // diff won't remove them and they'll all wind up in the resulting type. // // Possibly this will get better after a project to fix the handling of // $Diff and other "type destructors", which as of 2020-08 the Flow team is // taking up as a priority: // path_to_url#issuecomment-669977952 export type SubsetProperties<T, U> = $ObjMapi<U, <K>(K) => T[K]>; /** * Assert a contradiction, statically. Do nothing at runtime. * * The `empty` type is the type with no values. So, apart from certain bugs * in Flow, the only way a call to this function can ever be valid is when * the type-checker can actually prove the call site is unreachable. * * Especially useful for statically asserting that a `switch` statement is * exhaustive: * * type Foo = * | {| type: 'frob', ... |} * | {| type: 'twiddle', ... |}; * * * const foo: Foo = ...; * switch (foo.type) { * case 'frob': ...; break; * * case 'twiddle': ...; break; * * default: * ensureUnreachable(foo); // Asserts no possible cases for `foo` remain. * break; * } * * In this example if by mistake a case is omitted, or if another case is * added to the type without a corresponding `case` statement here, then * Flow will report a type error at the `ensureUnreachable` call. */ export function ensureUnreachable(x: empty) {} ```
/content/code_sandbox/src/generics.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,418
```javascript /* @flow strict-local */ import React, { type ComponentType, type ElementConfig, useRef } from 'react'; import { connectGlobal } from './react-redux'; import { getHaveServerDataGlobal } from './haveServerDataSelectors'; import FullScreenLoading from './common/FullScreenLoading'; /** * A HOC for any server-data-dependent screen component that might be * mounted when we don't have server data. * * Prevents rerendering of the component's subtree unless we have * server data. * * The implementation uses props named `dispatch` and `haveServerData`; the * inner component shouldn't try to accept props with those names, and the * caller shouldn't try to pass them in. * * Inside a render method, don't call this directly: like most HOCs, it will * return a new value each time. Instead, use `useHaveServerDataGate`. */ // It sure seems like Flow should catch the `dispatch` / `haveServerData` // thing and reflect it in the types; it's not clear why it doesn't. export default function withHaveServerDataGate<P: { ... }, C: ComponentType<$Exact<P>>>( Comp: C, ): ComponentType<$Exact<ElementConfig<C>>> { // `connect` does something useful for us that `useSelector` doesn't // do: it interposes a new `ReactReduxContext.Provider` component, // which proxies subscriptions so that the descendant components only // rerender if this one continues to say their subtree should be kept // around. See // path_to_url#discussion_r578140524 // and some discussion around // path_to_url#narrow/stream/243-mobile-team/topic/converting.20to.20Hooks/near/1111970 // where we describe some limits of our understanding. // // We found these things out while investigating an annoying crash: we // found that `mapStateToProps` on a descendant of `MainTabsScreen` // was running -- and throwing an uncaught error -- on logout, and // `MainTabsScreen`'s early return on `!haveServerData` wasn't // preventing that from happening. // // TODO(#5005): Should this be per-account, i.e. with getHaveServerData? return connectGlobal(state => ({ haveServerData: getHaveServerDataGlobal(state) }))( ({ dispatch, haveServerData, ...props }: {| dispatch: mixed, haveServerData: boolean, ...$Exact<P>, |}) => haveServerData ? ( <Comp {...props} /> ) : ( // Show a full-screen loading indicator while waiting for the // initial fetch to complete, if we don't have potentially stale // data to show instead. Also show it for the duration of the nav // transition just after the user logs out (see our #4275). // // And avoid rendering any of our main UI, to maintain the // guarantee that it can all rely on server data existing. <FullScreenLoading /> ), ); } /** * Like `withHaveServerDataGate`, but with a stable value on React re-render. * * This is a React hook. On initial render, it returns the same value as * `withHaveServerDataGate` would. On re-render, it returns the same value * as on the previous render. */ export function useHaveServerDataGate<P: { ... }, C: ComponentType<$Exact<P>>>( Comp: C, ): ComponentType<$Exact<ElementConfig<C>>> { // Not `useMemo`, because that function's memoization is only a // performance optimization and not a semantic guarantee. return useRef(withHaveServerDataGate(Comp)).current; } ```
/content/code_sandbox/src/withHaveServerDataGate.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
824
```javascript /* @flow strict-local */ import React from 'react'; import { AppState, Platform } from 'react-native'; import type { AppStateValues as AppStateValuesBusted } from 'react-native/Libraries/AppState/AppState'; // eslint-disable-next-line id-match import type { ____ViewStyle_Internal } from 'react-native/Libraries/StyleSheet/StyleSheetTypes'; import invariant from 'invariant'; import * as logging from './utils/logging'; import type { BoundedDiff } from './generics'; import { typesEquivalent } from './generics'; // A copy of the same-named type in // node_modules/react-native/Libraries/StyleSheet/StyleSheetTypes.js, for // use in ViewStylePropWithout, below. type GenericStyleProp<+T> = null | void | T | false | '' | $ReadOnlyArray<GenericStyleProp<T>>; /** * `View`'s style prop, but without the style attributes defined in T. */ // RN's type for `View`'s style prop is `ViewStyleProp` in // node_modules/react-native/Libraries/StyleSheet/StyleSheet.js; our // implementation builds on a copy of that. export type ViewStylePropWithout<T: { ... }> = GenericStyleProp< // Uses unsound $Shape just because the upstream type does, and we're // copying that. $ReadOnly<$Shape<BoundedDiff<____ViewStyle_Internal, T>>>, >; /** * Documented app-state values, plus any we've seen in the wild. */ type AppStateValues = AppStateValuesBusted | 'unknown'; /** * A hook for AppState's current state value, updated on 'change' events. * * Gives `null` if the state isn't one of the expected values * (AppStateValues), and logs to Sentry in that case. */ export function useAppState(): null | AppStateValues { // Upstream has `?string` probably they mean `AppStateValues`, but we'll // take them at their word and handle the differences by logging, to // prompt investigation if needed: // - nullish // - some string that's not an AppStateValues let initialState = AppState.currentState; if ( initialState == null || (typeof initialState === 'string' && initialState !== 'inactive' && initialState !== 'background' && initialState !== 'active' && initialState !== 'unknown') ) { // If Flow errors here, adjust cases in the conditional. typesEquivalent<AppStateValues, 'inactive' | 'background' | 'active' | 'unknown'>(); logging.warn(`Unexpected AppState.currentState: ${initialState?.toString() ?? '[nullish]'}`); initialState = null; } const [value, setValue] = React.useState(initialState); React.useEffect(() => { const sub = AppState.addEventListener('change', setValue); return () => sub.remove(); }, []); return value; } /** * The Android SDK version (e.g., 33 for Android 13 a.k.a. Tiramisu). * * Throws if called on iOS. */ export function androidSdkVersion(): number { invariant(Platform.OS === 'android', 'androidSdkVersion called on iOS'); // Flow isn't refining `Platform` to a type that corresponds to values // we'll see on Android. We do expect `Platform.Version` to be a number on // Android; see path_to_url#version. Empirically // (and this isn't in the doc yet), it's the SDK version, so for Android // 10 it won't be 10, it'll be 29. return (Platform.Version: number); } /** * The Android user-visible version string, with no promised structure. */ // This is Build.VERSION.RELEASE as of RN v0.68.5: // path_to_url#constants // path_to_url#L69 // path_to_url#RELEASE export function androidRelease(): string { invariant(Platform.OS === 'android', 'androidRelease called on iOS'); // Flow isn't refining `Platform` to a type that corresponds to values // we'll see on Android. // // (If changing the implementation, adjust comment below jsdoc.) return (Platform.constants.Release: string); } /** * The manufacturer of the Android device. * * E.g., "Google", "samsung". */ // This is Build.MANUFACTURER as of RN v0.68.7: // path_to_url#constants // path_to_url#L73 // path_to_url#MANUFACTURER export function androidManufacturer(): string { invariant(Platform.OS === 'android', 'androidManufacturer called on iOS'); return (Platform.constants.Manufacturer: string); } /** * "The consumer-visible brand with which the product/hardware will be associated, if any." * * E.g., "google", "samsung". */ // This is Build.BRAND as of RN v0.68.7: // path_to_url#constants // path_to_url#L74 // path_to_url#BRAND export function androidBrand(): string { invariant(Platform.OS === 'android', 'androidBrand called on iOS'); return (Platform.constants.Brand: string); } /** * "The end-user-visible name for the end product." * * E.g., "Pixel 5", "sdk_gphone64_x86_64", "SM-G960U1". */ // This is Build.MODEL as of RN v0.68.7: // path_to_url#constants // path_to_url#L72 // path_to_url#MODEL export function androidModel(): string { invariant(Platform.OS === 'android', 'androidModel called on iOS'); return (Platform.constants.Model: string); } ```
/content/code_sandbox/src/reactNativeUtils.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 config from './config'; /** * Whether a URL is hosted by the same org that publishes the app. */ export default function isAppOwnDomain(url: URL): boolean { return config.appOwnDomains.some( domain => url.host === domain || url.host.endsWith(`.${domain}`), ); } ```
/content/code_sandbox/src/isAppOwnDomain.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
70
```javascript // @flow strict-local import type { GlobalState, PerAccountState } from './types'; import { getUsers } from './directSelectors'; import { tryGetAuth, tryGetActiveAccountState, getAccount } from './account/accountsSelectors'; import { getUsersById } from './users/userSelectors'; import { kMinAllowedServerVersion } from './api/apiErrors'; /** * Whether we have server data for the active account. * * This can be used to decide whether the app's main UI which shows data * from the server should render itself, or should fall back to a loading * screen. * * See {@link getHaveServerData}. */ export const getHaveServerDataGlobal = (globalState: GlobalState): boolean => { // Any valid server data is about the active account. So if there is no // active account, then any server data we appear to have can't be valid. const state = tryGetActiveAccountState(globalState); if (!state) { // (For background to this comment's reasoning, see getHaveServerData.) // // From `accountsReducer`: // * This condition is resolved by LOGIN_SUCCESS. // * It's created only by ACCOUNT_REMOVE. // // When this condition applies, LOGIN_SUCCESS is the only way we might // navigate to the main UI. // // ACCOUNT_REMOVE is available only from the account-picker screen (not // the main UI), and moreover is available for the active account only // when not logged in, in which case the main UI can't be on the // navigation stack either. return false; } /* eslint-disable-next-line no-use-before-define */ return getHaveServerData(state); }; /** * Whether we have server data for this account. * * See also {@link getHaveServerDataGlobal}. */ // Note that in our pre-#5006 model where a PerAccountState is secretly just // GlobalState and implicitly means the active account, if there is *no* // active account (i.e. if there are no accounts at all), then this will // throw an exception, not return false. If that's not desired, then the // caller is really working with global state and should use // `getHaveServerDataGlobal`. export const getHaveServerData = (state: PerAccountState): boolean => { // The implementation has to be redundant, because upon rehydrate we can // unfortunately have some of our state subtrees containing server data // while others don't, reflecting different points in time from the last // time the app ran. In particular, if the user switched accounts (so // that we cleared server data in Redux) and then the app promptly // crashed, or was killed, that clearing-out may have reached some // subtrees but not others. See #4587 for an example, and #4841 overall. // It's important that we never stick around in a state where we're trying // to show the main UI but this function returns false. When in that // state, we just show a loading screen with no UI, so there has to be // something happening in the background that will get us out of it. // // The basic strategy is: // * When we start showing the main UI, we always kick off an initial // fetch. Specifically: // * If at startup (upon rehydrate) we show the main UI, we do so. // This is controlled by `getInitialRouteInfo`, together with // an effect in StoreProvider. // * When we navigate to the main UI (via `resetToMainTabs`), we always // also dispatch an action that causes an initial fetch. // * Plus, that initial fetch has a timeout, so it will always take us // away from a loading screen regardless of server/network behavior. // // * When we had server data and we stop having it, we always also either // navigate away from the main UI, or kick off a new initial fetch. // Specifically: // * Between this function and the reducers, we should only stop having // server data upon certain actions in `accountActions`. // * Some of those actions cause an initial fetch, as above. // * Those that don't should always be accompanied by navigating away // from the main UI, with `resetToAccountPicker`. // // Ideally the decisions "should we show the loading screen" and "should // we kick off a fetch" would be made together in one place, so that it'd // be possible to confirm they align without so much nonlocal reasoning. // Specific facts used in the reasoning below (within the strategy above): // * The actions LOGIN_SUCCESS and ACCOUNT_SWITCH are dispatched along // with an initial fetch. // * The action LOGOUT is always accompanied by navigating away from the // main UI. // * A successful initial fetch causes a REGISTER_COMPLETE action. A failed one // causes either LOGOUT, or an abort that ensures we're not at a // loading screen. // // (The same background facts are used in getHaveServerDataGlobal, too.) // Any valid server data comes from the account being logged in. if (!tryGetAuth(state)) { // From `accountsReducer`: // * This condition is resolved by LOGIN_SUCCESS. // * It's created only by ACCOUNT_REMOVE, by LOGOUT, and by (a // hypothetical) ACCOUNT_SWITCH for a logged-out account. // // When this condition applies, LOGIN_SUCCESS is the only way we might // navigate to the main UI. // // For ACCOUNT_REMOVE, see the previous condition. // ACCOUNT_SWITCH we only do for logged-in accounts. return false; } const { zulipVersion } = getAccount(state); // The server version comes with the rest of the server data. if (!zulipVersion) { return false; } // We may have server data, but it would be from an ancient server that we // don't support, so it might be malformed. if (!zulipVersion.isAtLeast(kMinAllowedServerVersion)) { return false; } // Valid server data must have a user: the self user, at a minimum. if (getUsers(state).length === 0) { // From `usersReducer`: // * This condition is resolved by REGISTER_COMPLETE. // * It's created only by LOGIN_SUCCESS, LOGOUT, and ACCOUNT_SWITCH. return false; } // It must also have the self user's user ID. const ownUserId = state.realm.user_id; if (ownUserId === undefined) { // From `realmReducer`: // * This condition is resolved by REGISTER_COMPLETE. // * It's created only by LOGIN_SUCCESS, LOGOUT, and ACCOUNT_SWITCH. return false; } // We can also do a basic consistency check between those two subtrees: // the self user identified in `state.realm` is among those we have in // `state.users`. (If for example the previous run of the app switched // accounts, and got all the way to writing the new account's // `state.realm` but not even clearing out `state.users` or vice versa, // then this check would fire. And in that situation without this check, // we crash early on because `getOwnUser` fails.) if (!getUsersById(state).get(ownUserId)) { // From the reducers (and assumptions about the server's data): // * This condition is resolved by REGISTER_COMPLETE. // * It's never created (post-rehydrate.) return false; } // TODO: A nice bonus would be to check that the account matches the // server data, given any of: // * user ID in `Account` (#4951) // * realm URL in `RealmState` // * delivery email in `RealmState` and/or `User` (though not sure this // is available from server, even for self, in all configurations) // Any other subtree could also have been emptied while others weren't, // or otherwise be out of sync. // // But it appears that in every other subtree containing server state, the // empty state (i.e. the one we reset to on logout or account switch) is a // valid possible state. That means (a) we can't so easily tell that it's // out of sync, but also (b) the app's UI is not so likely to just crash // from the get-go if it is -- because at least it won't crash simply // because the state is empty. // // There're still plenty of other ways different subtrees can be out of // sync with each other: `state.narrows` could know about some new message // that `state.messages` doesn't, or `state.messages` have a message sent // by a user that `state.users` has no record of. // // But given that shortly after starting to show the main app UI (whether // that's at startup, or after picking an account or logging in) we go // fetch fresh data from the server anyway, the checks above are hopefully // enough to let the app survive that long. return true; }; ```
/content/code_sandbox/src/haveServerDataSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,082
```javascript /* @flow strict-local */ import invariant from 'invariant'; import * as React from 'react'; /** * Like React.ElementConfig, but includes the pseudoprops `ref` and `key`. * * That is, this contains exactly the set of JSX attributes one can pass * when creating an element of this component-type. * * Assumes the underlying props type is an exact object type. */ export type ElementConfigFull<+C> = {| ...$Exact<React.ElementConfig<C>>, +ref?: React.Ref<C>, +key?: React.Key, |}; /** * A Hook for the value of a prop, state, etc., from the previous render. * * On first render, returns `initValue`. * * The second argument `initValue` is optional (even though the type doesn't * at first look that way): if omitted, it's `undefined` and the return type * is `T | void`. * * Adapted from * path_to_url#how-to-get-the-previous-props-or-state, * which says, "Its possible that in the future React will provide a * `usePrevious` Hook out of the box since its a relatively common * use case." */ // It's `initValue:`, not `initValue?:`, but initValue is still effectively // optional because `U` can be void. // // If we did write `initValue?:`, we'd get the wrong return type when the // caller omitted it: there'd be nothing to force `U` to include void // (because effectively the `?` would handle it instead), and so `U` would // be the empty type and `T | U` would be just `T`. export function usePrevious<T, U>(value: T, initValue: U): T | U { const ref = React.useRef<T | U>(initValue); React.useEffect(() => { ref.current = value; }); return ref.current; } const NODE_ENV = process.env.NODE_ENV; /** * In debug mode, assert the given value is constant through a component's life. * * In production mode, do nothing. * * This is meant to be used as a React Hook. */ export function useDebugAssertConstant<T>(value: T) { if (NODE_ENV === 'production') { return; } // Conditional, but on a per-process constant. // eslint-disable-next-line react-hooks/rules-of-hooks const origValue = React.useRef(value); invariant(value === origValue.current, ''); } /** * True just when `value` has not changed for the past `duration`. * * "Changed" means last render's and this render's `value`s aren't ===. * * When the given time has elapsed so that this hook's return value becomes * true, it causes a rerender through a state update. * * The caller must use a constant `duration` through the lifetime of a given * component instance. * * Note this hook doesn't (and can't) do anything to cause a rerender when * `value` changes. The caller must ensure that the component rerenders (so * that in particular this hook gets called again) whenever `value` will * have changed; for example, by using a prop or a `useState` value. */ export function useHasNotChangedForMs(value: mixed, duration: number): boolean { useDebugAssertConstant(duration); const [result, setResult] = React.useState(false); React.useEffect(() => { setResult(false); const id = setTimeout(() => setResult(true), duration); return () => clearTimeout(id); }, [ // If `duration` changes, we'll tear down the old timeout and start the // timer over. That isn't really ideal behavior... but we don't // actually have a use case for a dynamic `duration`, and supporting it // properly would be more complex, so we've just forbidden that as part // of this hook function's interface. duration, // Otherwise, trigger the effect just if React sees a change in `value`. // In other words, just when last render's and this render's `value`s // aren't ===. value, ]); return result; } /** * True just when `value` has been true continuously for the past `duration`. * * When the given time has elapsed so that this hook's return value becomes * true, it causes a rerender through a state update. * * The caller must use a constant `duration` through the lifetime of a given * component instance. * * Note this hook doesn't (and can't) do anything to cause a rerender when * `value` changes. The caller must ensure that the component rerenders (so * that in particular this hook gets called again) whenever `value` will * have changed; for example, by using a prop or a `useState` value. */ export const useHasStayedTrueForMs = (value: boolean, duration: number): boolean => { useDebugAssertConstant(duration); const hasNotChangedForDuration = useHasNotChangedForMs(value, duration); return value && hasNotChangedForDuration; }; /** * Like `useEffect`, but the callback only runs when `value` is true. * * Callers should wrap the callback in `useCallback` with an appropriate * array of dependencies. * * The callback will run once at the beginning of every period of `value` * being true, and again throughout such a period whenever the value of the * callback changes. * * As with `useEffect`, the cleanup function, if provided, will run once for * every time the callback is called. If `value` goes from true to false, * the cleanup function will be called at that time. */ // The claims about when `cb` runs assume that useEffect doesn't run its // callback on non-initial renders where its dependencies are unchanged. The // docs could be clearer about that: // path_to_url#tip-optimizing-performance-by-skipping-effects export const useConditionalEffect = (cb: () => void | (() => void), value: boolean): void => React.useEffect(() => (value ? cb() : undefined), [value, cb]); /** * A Date, as React state that refreshes regularly at an interval. * * Use this in a React component that relies on the current date, to make it * periodically rerender with a refreshed date value. * * Don't change the value of refreshIntervalMs. * * This uses `setTimeout`, which is subject to slightly late timeouts: * path_to_url#reasons_for_delays_longer_than_specified * so don't expect millisecond precision. */ export const useDateRefreshedAtInterval = (refreshIntervalMs: number): Date => { useDebugAssertConstant(refreshIntervalMs); const [date, setDate] = React.useState(new Date()); useConditionalEffect( React.useCallback(() => { setDate(new Date()); }, []), useHasNotChangedForMs(date, refreshIntervalMs), ); return date; }; ```
/content/code_sandbox/src/reactUtils.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,520
```javascript /* @flow strict-local */ export const REHYDRATE: 'persist/REHYDRATE' = 'persist/REHYDRATE'; export const APP_ONLINE: 'APP_ONLINE' = 'APP_ONLINE'; export const APP_ORIENTATION: 'APP_ORIENTATION' = 'APP_ORIENTATION'; export const DEAD_QUEUE: 'DEAD_QUEUE' = 'DEAD_QUEUE'; export const ACCOUNT_REMOVE: 'ACCOUNT_REMOVE' = 'ACCOUNT_REMOVE'; export const ACCOUNT_SWITCH: 'ACCOUNT_SWITCH' = 'ACCOUNT_SWITCH'; export const LOGIN_SUCCESS: 'LOGIN_SUCCESS' = 'LOGIN_SUCCESS'; export const LOGOUT: 'LOGOUT' = 'LOGOUT'; export const REGISTER_START: 'REGISTER_START' = 'REGISTER_START'; export const REGISTER_ABORT: 'REGISTER_ABORT' = 'REGISTER_ABORT'; export const REGISTER_COMPLETE: 'REGISTER_COMPLETE' = 'REGISTER_COMPLETE'; export const RESET_ACCOUNT_DATA: 'RESET_ACCOUNT_DATA' = 'RESET_ACCOUNT_DATA'; export const REFRESH_SERVER_EMOJI_DATA: 'REFRESH_SERVER_EMOJI_DATA' = 'REFRESH_SERVER_EMOJI_DATA'; export const DISMISS_SERVER_PUSH_SETUP_NOTICE: 'DISMISS_SERVER_PUSH_SETUP_NOTICE' = 'DISMISS_SERVER_PUSH_SETUP_NOTICE'; export const DISMISS_SERVER_NOTIFS_EXPIRING_BANNER: 'DISMISS_SERVER_NOTIFS_EXPIRING_BANNER' = 'DISMISS_SERVER_NOTIFS_EXPIRING_BANNER'; export const SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS: 'SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS' = 'SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS'; export const INIT_TOPICS: 'INIT_TOPICS' = 'INIT_TOPICS'; export const EVENT: 'EVENT' = 'EVENT'; export const EVENT_NEW_MESSAGE: 'EVENT_NEW_MESSAGE' = 'EVENT_NEW_MESSAGE'; export const EVENT_SUBMESSAGE: 'EVENT_SUBMESSAGE' = 'EVENT_SUBMESSAGE'; export const EVENT_MESSAGE_DELETE: 'EVENT_MESSAGE_DELETE' = 'EVENT_MESSAGE_DELETE'; export const EVENT_SUBSCRIPTION: 'EVENT_SUBSCRIPTION' = 'EVENT_SUBSCRIPTION'; export const EVENT_UPDATE_MESSAGE: 'EVENT_UPDATE_MESSAGE' = 'EVENT_UPDATE_MESSAGE'; export const EVENT_REACTION_ADD: 'EVENT_REACTION_ADD' = 'EVENT_REACTION_ADD'; export const EVENT_REACTION_REMOVE: 'EVENT_REACTION_REMOVE' = 'EVENT_REACTION_REMOVE'; export const EVENT_PRESENCE: 'EVENT_PRESENCE' = 'EVENT_PRESENCE'; export const EVENT_USER_STATUS_UPDATE: 'EVENT_USER_STATUS_UPDATE' = 'EVENT_USER_STATUS_UPDATE'; export const EVENT_TYPING_START: 'EVENT_TYPING_START' = 'EVENT_TYPING_START'; export const EVENT_TYPING_STOP: 'EVENT_TYPING_STOP' = 'EVENT_TYPING_STOP'; export const EVENT_UPDATE_MESSAGE_FLAGS: 'EVENT_UPDATE_MESSAGE_FLAGS' = 'EVENT_UPDATE_MESSAGE_FLAGS'; export const EVENT_USER_ADD: 'EVENT_USER_ADD' = 'EVENT_USER_ADD'; export const EVENT_USER_REMOVE: 'EVENT_USER_REMOVE' = 'EVENT_USER_REMOVE'; export const EVENT_MUTED_TOPICS: 'EVENT_MUTED_TOPICS' = 'EVENT_MUTED_TOPICS'; export const EVENT_MUTED_USERS: 'EVENT_MUTED_USERS' = 'EVENT_MUTED_USERS'; export const EVENT_USER_GROUP_ADD: 'EVENT_USER_GROUP_ADD' = 'EVENT_USER_GROUP_ADD'; export const EVENT_USER_GROUP_REMOVE: 'EVENT_USER_GROUP_REMOVE' = 'EVENT_USER_GROUP_REMOVE'; export const EVENT_USER_GROUP_UPDATE: 'EVENT_USER_GROUP_UPDATE' = 'EVENT_USER_GROUP_UPDATE'; export const EVENT_USER_GROUP_ADD_MEMBERS: 'EVENT_USER_GROUP_ADD_MEMBERS' = 'EVENT_USER_GROUP_ADD_MEMBERS'; export const EVENT_USER_GROUP_REMOVE_MEMBERS: 'EVENT_USER_GROUP_REMOVE_MEMBERS' = 'EVENT_USER_GROUP_REMOVE_MEMBERS'; export const MESSAGE_FETCH_START: 'MESSAGE_FETCH_START' = 'MESSAGE_FETCH_START'; export const MESSAGE_FETCH_ERROR: 'MESSAGE_FETCH_ERROR' = 'MESSAGE_FETCH_ERROR'; export const MESSAGE_FETCH_COMPLETE: 'MESSAGE_FETCH_COMPLETE' = 'MESSAGE_FETCH_COMPLETE'; export const PRESENCE_RESPONSE: 'PRESENCE_RESPONSE' = 'PRESENCE_RESPONSE'; export const SET_GLOBAL_SETTINGS: 'SET_GLOBAL_SETTINGS' = 'SET_GLOBAL_SETTINGS'; export const DISMISS_SERVER_COMPAT_NOTICE: 'DISMISS_SERVER_COMPAT_NOTICE' = 'DISMISS_SERVER_COMPAT_NOTICE'; export const GOT_PUSH_TOKEN: 'GOT_PUSH_TOKEN' = 'GOT_PUSH_TOKEN'; export const REGISTER_PUSH_TOKEN_START: 'REGISTER_PUSH_TOKEN_START' = 'REGISTER_PUSH_TOKEN_START'; export const REGISTER_PUSH_TOKEN_END: 'REGISTER_PUSH_TOKEN_END' = 'REGISTER_PUSH_TOKEN_END'; export const ACK_PUSH_TOKEN: 'ACK_PUSH_TOKEN' = 'ACK_PUSH_TOKEN'; export const UNACK_PUSH_TOKEN: 'UNACK_PUSH_TOKEN' = 'UNACK_PUSH_TOKEN'; export const EVENT_REALM_EMOJI_UPDATE: 'EVENT_REALM_EMOJI_UPDATE' = 'EVENT_REALM_EMOJI_UPDATE'; export const EVENT_REALM_FILTERS: 'EVENT_REALM_FILTERS' = 'EVENT_REALM_FILTERS'; // TODO(server-5.0): Remove these two, when all supported servers can handle // the `user_settings_object` client capability (FL 89). export const EVENT_UPDATE_DISPLAY_SETTINGS: 'EVENT_UPDATE_DISPLAY_SETTINGS' = 'EVENT_UPDATE_DISPLAY_SETTINGS'; export const EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS: 'EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS' = 'EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS'; export const EVENT_ALERT_WORDS: 'EVENT_ALERT_WORDS' = 'EVENT_ALERT_WORDS'; export const MESSAGE_SEND_START: 'MESSAGE_SEND_START' = 'MESSAGE_SEND_START'; export const MESSAGE_SEND_COMPLETE: 'MESSAGE_SEND_COMPLETE' = 'MESSAGE_SEND_COMPLETE'; export const TOGGLE_OUTBOX_SENDING: 'TOGGLE_OUTBOX_SENDING' = 'TOGGLE_OUTBOX_SENDING'; export const DELETE_OUTBOX_MESSAGE: 'DELETE_OUTBOX_MESSAGE' = 'DELETE_OUTBOX_MESSAGE'; export const DRAFT_UPDATE: 'DRAFT_UPDATE' = 'DRAFT_UPDATE'; export const CLEAR_TYPING: 'CLEAR_TYPING' = 'CLEAR_TYPING'; ```
/content/code_sandbox/src/actionConstants.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,233
```javascript /* @flow strict-local */ import type { Node } from 'react'; import type { IntlShape } from 'react-intl'; import type { DangerouslyImpreciseStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import type { BoundedDiff, SubsetProperties } from './generics'; import type { Auth, Topic, Message, PmMessage, StreamMessage, ReactionType, UserId, } from './api/apiTypes'; import type { ZulipVersion } from './utils/zulipVersion'; import type { PmKeyUsers } from './utils/recipient'; export type * from './generics'; export type * from './reduxTypes'; export type * from './api/apiTypes'; export type { Narrow } from './utils/narrow'; export { ensureUnreachable } from './generics'; /* * TODO as the name suggests, this should be broken down more specifically. * Each use should be one of ViewStyleProp, TextStyleProp, ImageStyleProp. */ export type Style = DangerouslyImpreciseStyleProp; export type Orientation = 'LANDSCAPE' | 'PORTRAIT'; export type Dimensions = {| bottom: number, left: number, right: number, top: number, |}; export type InputSelection = {| +start: number, +end: number, |}; /** * An `Identity`, a secret, and some other per-identity information. * * This includes all the information the API client library * needs in order to talk to the server on the user's behalf. * Use `authOfAccount` to extract that information as an `Auth`, * the form used by the API client library. * * NB in particular this includes an API key, which must be handled with * care. * * Use `Identity` instead for code where an API key is not required, * with `identityOfAccount` to convert at the boundary. * TODO: move more code that way. */ export type Account = $ReadOnly<{| ...Auth, /** * The user's numeric ID. * * We learn the user ID each time we complete an initial fetch. * * This is `null` briefly when we've logged in but not yet completed our * first initial fetch on the account. It's also `null` when representing * an account which was last used on a version of the app which didn't * record this information. It's never `null` for an account for which we * have server data. */ // A subtle key step in making that invariant true, that server data means // this isn't `null`, is migration 34 dropping server data after this was // added. Otherwise on first startup after upgrade, we'd be using server // data from an initial fetch made when we didn't yet store this property. userId: UserId | null, /** * The version of the Zulip server. * * We learn the server's version from /server_settings at the start of the * login process, and again from /register when setting up an event queue. * Because a server deploy invalidates event queues, this means the value * is always up to date for a server we have an active event queue on. * * This is `null` briefly when we've logged in but not yet completed our * first initial fetch on the account. It's also `null` when representing * an account which was last used on a version of the app which didn't * record this information. It's never `null` for an account for which we * have server data. * * For use in: * * how we make some API requests, in order to keep the logic isolated * to the edge, where we communicate with the server, to keep with the * "crunchy shell" pattern (see docs/architecture/crunchy-shell.md); * * context data in Sentry reports. */ // See discussion at userId for a subtle piece of why that not-null invariant holds. zulipVersion: ZulipVersion | null, /** * An integer indicating what features are available on the server. * * The feature level increases monotonically; a value of N means the * server supports all API features introduced before feature level N. * This is designed to provide a simple way for mobile apps to decide * whether the server supports a given feature or API change. * * This is `null` briefly when we've logged in but not yet completed our * first initial fetch on the account. It's also `null` when representing * an account which was last used on a version of the app which didn't * record this information. It's never `null` for an account for which we * have server data. * * Like zulipVersion, we learn the feature level from /server_settings * at the start of the login process, and again from /register when * setting up an event queue. */ // See discussion at userId for a subtle piece of why that not-null invariant holds. zulipFeatureLevel: number | null, /** * The last device token value the server has definitely heard from us. * * This is `null` until we make a successful request to the server to * tell it the token. * * See the `pushToken` property in `SessionState`, and docs linked there. */ ackedPushToken: string | null, /** * When the user last dismissed the server-not-set-up-for-notifs notice. * * `null` when the user hasn't dismissed this notice. * * "This notice" means the currently applicable notice. If the server does * get setup for push notifications, then gets un-setup, a new notice will * apply. */ lastDismissedServerPushSetupNotice: Date | null, /** * When the user last dismissed the server-notifs-soon-to-expire notice. * * `null` when the user hasn't dismissed this notice. */ lastDismissedServerNotifsExpiringBanner: Date | null, /** * The setting to silence prominent warnings about disabled notifications. * * ("Disabled" meaning in particular that the realm hasn't enabled * notifications, i.e., RealmState.pushNotificationsEnabled is false; * or that the realm is expected to disable them soon, i.e., * RealmState.pushNotificationsEnabledEndTimestamp is approaching.) * * Users will set this if they want something more permanent than the * "Dismiss" button on the ServerNotifsDisabledBanner or the * ServerNotifsExpiringBanner. That button only snoozes the banner, but * this setting makes the banner never appear. (The banner's information * will still be available on the "Notifications" screen.) * * Defaults to off / `false`. */ silenceServerPushSetupWarnings: boolean, |}>; /** * An identity belonging to this user in some Zulip org, with no secrets. * * This should be used in preference to `Auth` or `Account` in code that * doesn't need to make (authenticated) requests to the server and only * needs to pick their own email or ID out of a list, use the org's base URL * to make a relative URL absolute, etc. * * Use `identityOfAuth` or `identityOfAccount` to make one of these where * you have an `Auth` or `Account`. */ export type Identity = BoundedDiff<Auth, {| +apiKey: Auth['apiKey'] |}>; export type EmojiType = 'image' | 'unicode'; /** An emoji, in a shape we can pass to @zulip/shared */ export type EmojiForShared = {| reaction_type: ReactionType, emoji_type: EmojiType, emoji_name: string, emoji_code: string, |}; /** An aggregate of all the reactions with one emoji to one message. */ export type AggregatedReaction = {| code: string, count: number, name: string, selfReacted: boolean, type: ReactionType, users: $ReadOnlyArray<UserId>, |}; /** * ID and original topic/content of an already-sent message that the * user is currently editing. */ export type EditMessage = {| id: number, content: string, topic: string, |}; export type TopicExtended = {| ...$Exact<Topic>, isMuted: boolean, unreadCount: number, |}; /** * Properties in common among the two different flavors of a * `Outbox`: `PmOutbox` and `StreamOutbox`. */ type OutboxBase = $ReadOnly<{| /** Used for distinguishing from a `Message` object. */ isOutbox: true, /** * False until we successfully send the message, then true. * * As described in the type's jsdoc (above), once we've sent the message * we still keep the `Outbox` object around for a (usually short) time * until we can replace it with a `Message` object. */ isSent: boolean, // `markdownContent` doesn't exist in `Message`. // It's used for sending the message to the server. markdownContent: string, ...SubsetProperties< // Could use `MessageBase` here. Then Flow would check that the listed // properties are in `MessageBase`, rather than just in both branches of // `Message` but potentially separately. Message, {| avatar_url: mixed, content: mixed, id: mixed, reactions: mixed, sender_id: mixed, sender_email: mixed, sender_full_name: mixed, timestamp: mixed, |}, >, |}>; export type PmOutbox = $ReadOnly<{| ...OutboxBase, ...SubsetProperties< PmMessage, {| type: mixed, display_recipient: mixed, subject: mixed, |}, >, |}>; export type StreamOutbox = $ReadOnly<{| ...OutboxBase, ...SubsetProperties< StreamMessage, {| type: mixed, display_recipient: mixed, stream_id: mixed, subject: mixed, |}, >, |}>; /** * A message we're in the process of sending. * * We use these objects for two purposes: * * (a) They make up the queue of messages the user has asked us to send, and * which we'll retry sending if initial attempts fail. See * `trySendMessages`. * * (b) We show them immediately in the message list, even before we've * successfully gotten them to the server (but with an activity * indicator to show we're still working on them.) * * Even after (a) is complete for a given message, we still need the * `Outbox` object for the sake of (b), until we hear an `EVENT_NEW_MESSAGE` * event from the server that lets us replace it with the corresponding * `Message` object. * * This type most often appears in the union `Message | Outbox`, and so its * properties are deliberately similar to those of `Message`. */ export type Outbox = PmOutbox | StreamOutbox; /** * MessageLike: Imprecise alternative to `Message | Outbox`. * * Flow reasonably dispermits certain classes of access on union types. In * particular, * ``` * const { match_content } = (message: Message | Outbox); // error * ``` * is not allowed. However, as long as you're prepared to handle values of * `undefined`, it's both JavaScript-legal to do so and occasionally convenient. * * We therefore construct an intermediate type which Flow recognizes as a * subtype of `Message | Outbox`, but which Flow will permit us to directly (and * soundly) destructure certain `Message`-only fields from: * ``` * const { match_content } = (message: MessageLike); // ok! * ``` * * * Note: `MessageLike` <: `Message | Outbox`, but the converse does not hold. * It is therefore strongly advised _never_ to use `MessageLike` as either an * argument or return type; instead, always accept and produce values of * `Message | Outbox`, and cast them to `MessageLike` at their use-site when * necessary. * * * Note 2: This class is asymmetric mostly because there is no current use case * for accessing Outbox-only fields on a `Message | Outbox`. * */ export type MessageLike = | $ReadOnly<Message> | $ReadOnly<{| // $Shape<T> is unsound, per Flow docs, but $ReadOnly<$Shape<T>> is not ...$Shape<{| [$Keys<Message>]: void |}>, ...Outbox, |}>; // Name and type copied from docs: // path_to_url#formatmessage type MessageFormatPrimitiveValue = string | number | boolean | null | void; // For rich text formatting: // path_to_url#rich-text-formatting // Name FormatXMLElementFn found in the docs (our name follows Google's // style guide for camel case): // path_to_url#formatmessage // Type taken by hand from TypeScript. type FormatXmlElementFn = (parts: $ReadOnlyArray<string | Node>) => Node; /** * A string to show, translated, in the UI as a plain string. * * For when formatting is needed (and possible), see `LocalizableReactText`. */ export type LocalizableText = | string | {| +text: string, +values?: {| +[string]: MessageFormatPrimitiveValue |} |}; /** * A string to show, translated, in the UI as a React node. * * Here the values can be React nodes, and so the translated result will be * a React node. For when the result is a plain string and React nodes * aren't permitted in the values, see `LocalizableText`. */ export type LocalizableReactText = | string | {| +text: string, +values?: {| +[string]: MessageFormatPrimitiveValue | Node | FormatXmlElementFn |}, |}; /** * Usually called `_`, and invoked like `_('Message')` -> `'Nachricht'`. * * To use: * const _ = React.useContext(TranslationContext); */ export type GetText = {| (message: string, values?: {| +[string]: MessageFormatPrimitiveValue |}): string, /** Convenient in contexts where callers pass `LocalizableText`. */ (message: LocalizableText): string, /** The full react-intl API, for more complex situations. */ intl: IntlShape, |}; export type TimeMessageListElement = {| type: 'time', // TODO(facebook/flow#4509): Read-only tuple type, when supported key: [number, 0], timestamp: number, subsequentMessage: Message | Outbox, |}; export type MessageMessageListElement = {| type: 'message', // TODO(facebook/flow#4509): Read-only tuple type, when supported key: [number, 2], message: Message | Outbox, isBrief: boolean, |}; export type HeaderMessageListElement = {| type: 'header', // TODO(facebook/flow#4509): Read-only tuple type, when supported key: [number, 1], style: 'topic+date' | 'full', subsequentMessage: Message | Outbox, |}; /** * Data object for a unit in the message list. * * Formerly called "message peers" and "HTML piece descriptors". * * A list of these is sortable by the `key` property, which holds a tuple * with two members: * - `.key[0]` is the message ID that the MessageListElement is related to. * - `.key[1]` is an integer representing whether the element is a * TimeMessageListElement (0), HeaderMessageListElement (1), or * MessageMessageListElement (2). The message list should present them in * that order (0-2). * * See generateInboundEventEditSequence for where we implement the compare * function for `key`. */ export type MessageListElement = | TimeMessageListElement | MessageMessageListElement | HeaderMessageListElement; // Check that all FooMessageListElement.key is reasonable. // // TODO(facebook/flow#4509): $ReadOnlyArray<number> is a proxy for tuple // type [number, number] with its two members marked as covariant. Flow // has no syntax for that yet. // eslint-disable-next-line no-unused-expressions (k: MessageListElement['key']): $ReadOnlyArray<number> => k; export type TimingItemType = {| text: string, startMs: number, endMs: number, |}; /** * Summary of a PM conversation (either 1:1 or group PMs). */ export type PmConversationData = {| /** * A comma-separated (numerically-)sorted sequence of the IDs of the users * involved in this conversation. Omits the self-user just if there are * exactly two recipients. * * (This unusual specification is intended to simultaneously match the * disjoint key-spaces of `unreadPms` and `unreadHuddles`.) */ key: string, keyRecipients: PmKeyUsers, /** The most recent message in this conversation. */ msgId: number, /** The count of unread messages in this conversation. */ unread: number, |}; ```
/content/code_sandbox/src/types.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,895
```javascript /** * Ponyfills for better-typed versions of functions than the Flow stdlib. * * FlowIssue: Everything here should really become a fix upstream in * flowlib. * * @flow strict */ /** * Ponyfill for properly-typed `Object.entries`. * * See also `objectValues`, for `Object.values`. */ export function objectEntries<K: string, V>(obj: {| +[K]: V |}): Array<[K, V]> { // Flow's definition for Object.entries is simply // static entries(object: mixed): Array<[string, mixed]>; // .... which is almost useless. return (Object.entries(obj): $FlowIssue); } /** * Ponyfill for properly-typed `Object.values`. * * See also `objectEntries`, for `Object.entries`. */ export function objectValues<K: string, V>(obj: {| +[K]: V |}): V[] { return (Object.values(obj): $FlowIssue); // Really should be fixed in flowlib. } ```
/content/code_sandbox/src/flowPonyfill.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
214
```javascript /* @flow strict-local */ export * from './account/accountsSelectors'; export * from './pm-conversations/pmConversationsSelectors'; export * from './caughtup/caughtUpSelectors'; export * from './chat/narrowsSelectors'; export * from './chat/fetchingSelectors'; export * from './directSelectors'; export * from './emoji/emojiSelectors'; export * from './message/messageSelectors'; export * from './subscriptions/subscriptionSelectors'; export * from './topics/topicSelectors'; export * from './typing/typingSelectors'; export * from './unread/unreadSelectors'; export * from './users/userSelectors'; ```
/content/code_sandbox/src/selectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
125
```javascript /* @flow strict-local */ /** * A special value we internally take to mean "first unread message". * * In particular this is interpreted by the `fetchMessages*` functions in * `fetchActions.js` as meaning the underlying API request should set * `use_first_unread_anchor: true`. (Which causes the actual `anchor` value * to be ignored.) */ // Awkwardly, this is a very different convention from the one understood by // the Zulip server! The latter takes `anchor: 0` literally -- and because // no message has ID less than 0, it effectively means "the very first // messages". export const FIRST_UNREAD_ANCHOR = 0; /** * Pointer to the newest message in a narrow. * * Usually, an anchor is a message ID. This constant can be used when we * want to retrieve the newest messages for a narrow, without actually * knowing their IDs. */ // This special value is understood by the server, corresponding to // LARGER_THAN_MAX_MESSAGE_ID there. See #3654. export const LAST_MESSAGE_ANCHOR = 10000000000000000; // sixteen zeroes ```
/content/code_sandbox/src/anchor.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
252
```javascript /** General helpers to augment Immutable.js. */ // @flow strict-local import Immutable from 'immutable'; // Like `Immutable.Map#update`, but prune returned values equal to `zero`. export function updateAndPrune<K, V>( map: Immutable.Map<K, V>, zero: V, key: K, updater: (V | void) => V, ): Immutable.Map<K, V> { const value = map.get(key); const newValue = updater(value); if (newValue === zero) { return map.delete(key); } if (newValue === value) { return map; } return map.set(key, newValue); } // Like `Immutable.Map#map`, but with the update-only-if-different semantics // of `Immutable.Map#update`. Kept for comparison to `updateAllAndPrune`. export function updateAll<K, V>(map: Immutable.Map<K, V>, updater: V => V): Immutable.Map<K, V> { return map.withMutations(mapMut => { map.forEach((value, key) => { const newValue = updater(value); if (newValue !== value) { mapMut.set(key, newValue); } }); }); } // Like `updateAll`, but prune values equal to `zero` given by `updater`. export function updateAllAndPrune<K, V>( map: Immutable.Map<K, V>, zero: V, updater: V => V, ): Immutable.Map<K, V> { return map.withMutations(mapMut => { map.forEach((value, key) => { const newValue = updater(value); if (newValue === zero) { mapMut.delete(key); return; } if (newValue === value) { return; // i.e., continue } mapMut.set(key, newValue); }); }); } /** * The union of sets, represented as sorted lists. * * The inputs must be sorted (by `<`) and without duplicates (by `===`). * * The output will contain all the elements found in either input, again * sorted and without duplicates. */ // TODO: This implementation is (n log n), because it repeatedly looks up // elements by numerical index. It would be nice to instead use cursors // within the tree to get an O(n) implementation. export function setUnion<T: number>( xs: Immutable.List<T>, ys: Immutable.List<T>, ): Immutable.List<T> { // TODO: Perhaps build a List directly, with setSize up front. const result = []; let i = 0; let x = xs.get(i++); let j = 0; let y = ys.get(j++); while (x !== undefined && y !== undefined) { if (x < y) { result.push(x); x = xs.get(i++); } else if (x !== y) { result.push(y); y = ys.get(j++); } else { // x === y result.push(x); x = xs.get(i++); y = ys.get(j++); } } while (x !== undefined) { result.push(x); x = xs.get(i++); } while (y !== undefined) { result.push(y); y = ys.get(j++); } return Immutable.List(result); } ```
/content/code_sandbox/src/immutableUtils.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
716
```javascript /* @flow strict-local */ import type { PerAccountState, UserId } from './types'; import { ensureUnreachable } from './types'; import { Role, CreateWebPublicStreamPolicy } from './api/permissionsTypes'; import { getRealm, getOwnUser, getUserForId } from './selectors'; const { Member, Moderator, Admin, Owner } = Role; export function roleIsAtLeast(thisRole: Role, thresholdRole: Role): boolean { return (thisRole: number) <= (thresholdRole: number); // Roles with more privilege have lower numbers. } /** * Whether the user has passed the realm's waiting period to be a full member. * * See: * path_to_url#determining-if-a-user-is-a-full-member * * To determine if a user is a full member, callers must also check that the * user's role is at least Role.Member. * * Note: If used with useSelector, the value will be out-of-date, though * realistically only by seconds or minutes at most; see implementation. */ export function getHasUserPassedWaitingPeriod(state: PerAccountState, userId: UserId): boolean { const { waitingPeriodThreshold } = getRealm(state); const { date_joined } = getUserForId(state, userId); const intervalLengthInDays = (Date.now() - Date.parse(date_joined)) / 86400_000; // When used with useSelector, the result will be based on the time at // which the most recent Redux action was dispatched. This would break // if we made this a caching selector; don't do that. // TODO(?): To upper-bound how long ago that can be, we could dispatch // actions at a regular short-ish interval. If those actions // contained a current-date value, we could even store that value in // Redux and consume it here, letting this be a caching selector if // we wanted it to be. return intervalLengthInDays >= waitingPeriodThreshold; } /** * Whether the self-user is authorized to create or edit a stream to be * public. * * Note: This isn't about web-public streams. For those, see * getCanCreateWebPublicStreams. */ // TODO(?): Could deduplicate with the other getCanCreate*Streams; see // path_to_url#discussion_r883215288 export function getCanCreatePublicStreams(state: PerAccountState): boolean { const { createPublicStreamPolicy } = getRealm(state); const ownUser = getOwnUser(state); const role = ownUser.role; switch (createPublicStreamPolicy) { case 4: // ModeratorOrAbove return roleIsAtLeast(role, Moderator); case 3: // FullMemberOrAbove return role === Member ? getHasUserPassedWaitingPeriod(state, ownUser.user_id) : roleIsAtLeast(role, Member); case 2: // AdminOrAbove return roleIsAtLeast(role, Admin); case 1: // MemberOrAbove return roleIsAtLeast(role, Member); default: { ensureUnreachable(createPublicStreamPolicy); // (Unreachable as long as the cases are exhaustive.) return false; } } } /** * Whether the self-user is authorized to create or edit a stream to be * private. */ // TODO(?): Could deduplicate with the other getCanCreate*Streams; see // path_to_url#discussion_r883215288 export function getCanCreatePrivateStreams(state: PerAccountState): boolean { const { createPrivateStreamPolicy } = getRealm(state); const ownUser = getOwnUser(state); const role = ownUser.role; switch (createPrivateStreamPolicy) { case 4: // ModeratorOrAbove return roleIsAtLeast(role, Moderator); case 3: // FullMemberOrAbove return role === Member ? getHasUserPassedWaitingPeriod(state, ownUser.user_id) : roleIsAtLeast(role, Member); case 2: // AdminOrAbove return roleIsAtLeast(role, Admin); case 1: // MemberOrAbove return roleIsAtLeast(role, Member); default: { ensureUnreachable(createPrivateStreamPolicy); // (Unreachable as long as the cases are exhaustive.) return false; } } } /** * Whether the self-user can create or edit a stream to be web-public. * * True just if: * - the server has opted into the concept of web-public streams (see * server_web_public_streams_enabled in * path_to_url and * - spectator access is enabled (see realm_enable_spectator_access in * path_to_url and * - the user's role is high enough, according to the realm's policy (see * realm_users[].role and realm_create_web_public_stream_policy in * path_to_url * * Like user_can_create_web_public_streams in the web-app's * static/js/settings_data.ts. */ // TODO(?): Could deduplicate with the other getCanCreate*Streams; see // path_to_url#discussion_r883215288 export function getCanCreateWebPublicStreams(state: PerAccountState): boolean { const { webPublicStreamsEnabled, enableSpectatorAccess, createWebPublicStreamPolicy } = getRealm(state); const role = getOwnUser(state).role; if (!webPublicStreamsEnabled || !enableSpectatorAccess) { return false; } switch (createWebPublicStreamPolicy) { case CreateWebPublicStreamPolicy.Nobody: return false; case CreateWebPublicStreamPolicy.OwnerOnly: return roleIsAtLeast(role, Owner); case CreateWebPublicStreamPolicy.AdminOrAbove: return roleIsAtLeast(role, Admin); case CreateWebPublicStreamPolicy.ModeratorOrAbove: return roleIsAtLeast(role, Moderator); } } ```
/content/code_sandbox/src/permissionSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,279
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Platform, UIManager } from 'react-native'; import 'react-native-url-polyfill/auto'; // $FlowFixMe[untyped-import] import { ActionSheetProvider } from '@expo/react-native-action-sheet'; import RootErrorBoundary from './RootErrorBoundary'; import ZulipNavigationContainer from './nav/ZulipNavigationContainer'; import StoreProvider from './boot/StoreProvider'; import StoreHydratedGate from './boot/StoreHydratedGate'; import TranslationProvider from './boot/TranslationProvider'; import ThemeProvider from './boot/ThemeProvider'; import CompatibilityChecker from './boot/CompatibilityChecker'; import AppEventHandlers from './boot/AppEventHandlers'; import { initializeSentry } from './sentry'; import ZulipSafeAreaProvider from './boot/ZulipSafeAreaProvider'; import { OfflineNoticeProvider } from './boot/OfflineNoticeProvider'; initializeSentry(); // $FlowFixMe[prop-missing] console.disableYellowBox = true; // eslint-disable-line // Enable `LayoutAnimation` on Android. Already enabled on iOS. // path_to_url if (Platform.OS === 'android') { // In the future, layout animation may be enabled by default. If // that happens, this method will probably be removed: // path_to_url#L741-L755. // // In the meantime, we should be on the lookout for any issues with // this feature on Android. // // There are some bad interactions with react-native-screens. From // testing, they seem to be Android only, and they go away with // react-native-screens disabled: // - With react-native-screens enabled, at least at 3.13.1 and 3.17.0, be // careful when you want a single action to trigger animated layout // changes on multiple screens at the same time. If a screen isn't // focused when the layout change happens, the layout change and its // animation might not happen until you focus the screen. I seemed to // be able to fix this by calling react-native-screens's // enableFreeze(true) at the top of this file, but I don't really // understand why; here's the doc: // path_to_url // - With react-native-screens enabled, at least at 3.13.1 and 3.17.0, if // I'm on a screen where a layout change is happening, and I navigate // away during the animation, when I come back to the first screen it // seems stuck at a snapshot of its layout, mid-animation, when I // navigated away. I haven't found a fix except, at the moment the // screen regains focus, to unmount and remount *all* affected views on // the screen, with a changing `key` pseudoprop. This is awkward and // unfortunately doesn't prevent the frozen layout from showing for a // split second before the layout resets. UIManager.setLayoutAnimationEnabledExperimental(true); } export default function ZulipMobile(): Node { // If using react-native-gesture-handler directly, not just via React // Navigation, we should use a GestureHandlerRootView; see // path_to_url#js // // React Nav seems to have followed the following advice, in that doc: // > If you're using gesture handler in your component library, you may // > want to wrap your library's code in the GestureHandlerRootView // > component. This will avoid extra configuration for the user. // which I think is why they don't mention GestureHandlerRootView in their // own setup doc, and why I think it's probably fine to omit it if we're // not using r-n-gesture-handler directly ourselves. return ( <RootErrorBoundary> <CompatibilityChecker> <StoreProvider> <ZulipSafeAreaProvider> <StoreHydratedGate> <AppEventHandlers> <TranslationProvider> <ThemeProvider> <OfflineNoticeProvider> <ActionSheetProvider> <ZulipNavigationContainer /> </ActionSheetProvider> </OfflineNoticeProvider> </ThemeProvider> </TranslationProvider> </AppEventHandlers> </StoreHydratedGate> </ZulipSafeAreaProvider> </StoreProvider> </CompatibilityChecker> </RootErrorBoundary> ); } ```
/content/code_sandbox/src/ZulipMobile.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
996
```javascript /* @flow strict-local */ /** * The Sentry "client key" aka "DSN". * * When non-null, this is the destination we send Sentry events to. * When null, the app does not send anything to Sentry. * * For more on the meaning of this value, see Sentry upstream docs: * path_to_url#dsn * path_to_url */ // The published official builds of the Zulip mobile app contain a non-null // value here. Because the key is there in those published builds, it's // fundamentally not a secret. // // But it's important to make sure Zulip developers and people distributing // their own modified versions of the app don't accidentally end up sending // Sentry events that get mixed in amongst events from the official builds: // path_to_url#issuecomment-773479895 // So we keep the key out of the public source tree, to ensure there's no // way to accidentally start using it. // // If you're making your own builds and want to use Sentry with them, please // create your own Sentry client key / DSN, and fill it in here. // See also the comment in AndroidManifest.xml about `io.sentry.dsn`. export const sentryKey: string | null = null; ```
/content/code_sandbox/src/sentryConfig.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
271
```javascript /* @flow strict-local */ import { ensureUnreachable } from './generics'; import { REHYDRATE, APP_ONLINE, DEAD_QUEUE, APP_ORIENTATION, ACCOUNT_SWITCH, ACCOUNT_REMOVE, LOGIN_SUCCESS, LOGOUT, RESET_ACCOUNT_DATA, DISMISS_SERVER_PUSH_SETUP_NOTICE, GOT_PUSH_TOKEN, UNACK_PUSH_TOKEN, ACK_PUSH_TOKEN, MESSAGE_FETCH_START, MESSAGE_FETCH_ERROR, MESSAGE_FETCH_COMPLETE, REGISTER_START, REGISTER_ABORT, REGISTER_COMPLETE, REFRESH_SERVER_EMOJI_DATA, SET_GLOBAL_SETTINGS, DRAFT_UPDATE, PRESENCE_RESPONSE, MESSAGE_SEND_START, MESSAGE_SEND_COMPLETE, DELETE_OUTBOX_MESSAGE, TOGGLE_OUTBOX_SENDING, EVENT_MESSAGE_DELETE, EVENT_USER_GROUP_ADD, EVENT_USER_GROUP_REMOVE, EVENT_USER_GROUP_UPDATE, EVENT_USER_GROUP_ADD_MEMBERS, EVENT_USER_GROUP_REMOVE_MEMBERS, EVENT_USER_STATUS_UPDATE, EVENT_TYPING_START, EVENT_TYPING_STOP, EVENT_NEW_MESSAGE, EVENT_REACTION_ADD, EVENT_REACTION_REMOVE, EVENT_PRESENCE, EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, EVENT_UPDATE_MESSAGE, EVENT_UPDATE_MESSAGE_FLAGS, EVENT_USER_ADD, CLEAR_TYPING, EVENT_ALERT_WORDS, INIT_TOPICS, EVENT_MUTED_TOPICS, EVENT_MUTED_USERS, EVENT_REALM_FILTERS, EVENT_USER_REMOVE, EVENT_REALM_EMOJI_UPDATE, EVENT_UPDATE_DISPLAY_SETTINGS, EVENT_SUBMESSAGE, EVENT_SUBSCRIPTION, EVENT, DISMISS_SERVER_COMPAT_NOTICE, REGISTER_PUSH_TOKEN_START, REGISTER_PUSH_TOKEN_END, SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS, DISMISS_SERVER_NOTIFS_EXPIRING_BANNER, } from './actionConstants'; import type { UserMessageFlag } from './api/modelTypes'; import type { CustomProfileFieldsEvent, MessageEvent, MutedUsersEvent, PresenceEvent, StreamEvent, RealmUpdateEvent, RealmUpdateDictEvent, UserSettingsUpdateEvent, SubmessageEvent, UpdateMessageFlagsMessageDetails, RestartEvent, UpdateMessageEvent, RealmUserUpdateEvent, UserTopicEvent, } from './api/eventTypes'; import type { MutedTopicTuple, PresenceSnapshot } from './api/apiTypes'; import type { MessageMove } from './api/misc'; import type { Orientation, GlobalState, Message, MessagesState, Outbox, Narrow, Reaction, Identity, User, UserGroup, InitialData, RealmFilter, Subscription, Topic, RealmEmojiById, ServerEmojiData, GlobalSettingsState, CaughtUpState, UserId, UserStatusEvent, } from './types'; /** * Dispatched by redux-persist when the stored state is loaded. * * It can be very convenient to pass `payload` to selectors, but beware it's * incomplete. At a minimum, reducers should always separately handle the * case where the state is empty before passing the object to any selector. * * @prop payload A version of the global Redux state, as persisted by the * app's previous runs. This will have a subset of the properties the * Redux state has: it has only those we configure to be persisted, it * may lack any of those too if they aren't present in storage (or we * hit an error reading them), and in particular it will be empty on * first launch. * * On the other hand, before this action reaches reducers its payload has * been put through our migrations, so any properties it does have should * actually have the expected type. */ type RehydrateAction = $ReadOnly<{| type: typeof REHYDRATE, +payload: $ReadOnly<$Rest<GlobalState, { ... }>>, |}>; type AppOnlineAction = $ReadOnly<{| type: typeof APP_ONLINE, isOnline: boolean | null, |}>; type DeadQueueAction = $ReadOnly<{| type: typeof DEAD_QUEUE, |}>; type AppOrientationAction = $ReadOnly<{| type: typeof APP_ORIENTATION, orientation: Orientation, |}>; type DismissServerCompatNoticeAction = $ReadOnly<{| type: typeof DISMISS_SERVER_COMPAT_NOTICE, |}>; export type AccountSwitchAction = $ReadOnly<{| type: typeof ACCOUNT_SWITCH, identity: Identity, |}>; type AccountRemoveAction = $ReadOnly<{| type: typeof ACCOUNT_REMOVE, identity: Identity, |}>; export type LoginSuccessAction = $ReadOnly<{| type: typeof LOGIN_SUCCESS, realm: URL, email: string, apiKey: string, |}>; type LogoutAction = $ReadOnly<{| type: typeof LOGOUT, |}>; export type ResetAccountDataAction = $ReadOnly<{| type: typeof RESET_ACCOUNT_DATA, |}>; type DismissServerPushSetupNoticeAction = $ReadOnly<{| type: typeof DISMISS_SERVER_PUSH_SETUP_NOTICE, date: Date, |}>; type DismissServerNotifsExpiringBannerAction = $ReadOnly<{| type: typeof DISMISS_SERVER_NOTIFS_EXPIRING_BANNER, date: Date, |}>; type SetSilenceServerPushSetupWarningsAction = $ReadOnly<{| type: typeof SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS, value: boolean, |}>; /** We learned the device token from the system. See `SessionState`. */ type GotPushTokenAction = $ReadOnly<{| type: typeof GOT_PUSH_TOKEN, pushToken: null | string, |}>; /** We're about to tell the server to forget our device token. */ type UnackPushTokenAction = $ReadOnly<{| type: typeof UNACK_PUSH_TOKEN, identity: Identity, |}>; /** We've started a request to register our device token. */ type RegisterPushTokenStartAction = $ReadOnly<{| type: typeof REGISTER_PUSH_TOKEN_START, identity: Identity, |}>; /** A request to register our device token has ended (success or failure). */ type RegisterPushTokenEndAction = $ReadOnly<{| type: typeof REGISTER_PUSH_TOKEN_END, identity: Identity, |}>; /** The server acknowledged our device token. */ type AckPushTokenAction = $ReadOnly<{| type: typeof ACK_PUSH_TOKEN, identity: Identity, pushToken: string, |}>; export type MessageFetchStartAction = $ReadOnly<{| type: typeof MESSAGE_FETCH_START, narrow: Narrow, numBefore: number, numAfter: number, |}>; /** * Any unexpected failure in a message fetch. * * Includes request timeout errors and any errors we throw when * validating and reshaping the server data at the edge. * * In an ideal crunchy-shell world [1], none of these will be thrown * from our Redux reducers: as part of the "soft center" of the app, * the data should already be valid at that point. We're not yet in * that world, so, we take care to catch those errors and dispatch * this action there too. See discussion [2] for implementation notes. * * [1] path_to_url * [2] path_to_url#narrow/stream/243-mobile-team/topic/.23M4156.20Message.20List.20placeholders/near/937480 */ type MessageFetchErrorAction = $ReadOnly<{| type: typeof MESSAGE_FETCH_ERROR, narrow: Narrow, // Before storing this in state, be sure to replace/revive Error // instances so they aren't coerced into plain objects; see // bfe794955 for an example. error: mixed, |}>; export type MessageFetchCompleteAction = $ReadOnly<{| type: typeof MESSAGE_FETCH_COMPLETE, messages: $ReadOnlyArray<Message>, narrow: Narrow, anchor: number, numBefore: number, numAfter: number, foundNewest: boolean, foundOldest: boolean, ownUserId: UserId, |}>; type RegisterStartAction = $ReadOnly<{| type: typeof REGISTER_START, |}>; export type RegisterAbortReason = 'server' | 'network' | 'timeout' | 'unexpected'; /** * Notify Redux that we've given up on the initial fetch. * * Not for unrecoverable errors, like ApiErrors, which indicate that we * tried and failed, not that we gave up trying. */ type RegisterAbortAction = $ReadOnly<{| type: typeof REGISTER_ABORT, reason: RegisterAbortReason, |}>; export type RegisterCompleteAction = $ReadOnly<{| type: typeof REGISTER_COMPLETE, data: InitialData, |}>; type ServerEvent = $ReadOnly<{| id: number, |}>; /** path_to_url#alert_words */ type EventAlertWordsAction = $ReadOnly<{| type: typeof EVENT_ALERT_WORDS, alert_words: $ReadOnlyArray<string>, |}>; type EventRealmFiltersAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_REALM_FILTERS, realm_filters: $ReadOnlyArray<RealmFilter>, |}>; // TODO(server-5.0): Remove, when all supported servers can handle the // `user_settings_object` client capability (FL 89). type EventUpdateGlobalNotificationsSettingsAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, notification_name: | 'enable_offline_push_notifications' | 'enable_online_push_notifications' | 'enable_stream_push_notifications', setting: boolean, |}>; type EventSubscriptionAddAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_SUBSCRIPTION, op: 'add', subscriptions: $ReadOnlyArray<Subscription>, |}>; type EventSubscriptionRemoveAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_SUBSCRIPTION, op: 'remove', subscriptions: $ReadOnlyArray<{| +stream_id: number, -name: string |}>, |}>; type EventSubscriptionUpdateAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_SUBSCRIPTION, op: 'update', stream_id: number, property: string, value: boolean | number | string, // TODO(server-4.0): Delete these commented-out properties. // name: string, // exists pre-4.0, but expected to be removed soon // email: string, // gone in 4.0; was the user's own email, so never useful |}>; type EventSubscriptionPeerAddAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_SUBSCRIPTION, op: 'peer_add', subscriptions: $ReadOnlyArray<string>, user_id: UserId, |}>; type EventSubscriptionPeerRemoveAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_SUBSCRIPTION, op: 'peer_remove', subscriptions: $ReadOnlyArray<string>, user_id: UserId, |}>; type GenericEventAction = $ReadOnly<{| type: typeof EVENT, event: | CustomProfileFieldsEvent | StreamEvent | RestartEvent | RealmUpdateEvent | RealmUpdateDictEvent | RealmUserUpdateEvent | UserSettingsUpdateEvent | UserTopicEvent, |}>; type EventNewMessageAction = $ReadOnly<{| ...$Diff<MessageEvent, {| flags: mixed |}>, type: typeof EVENT_NEW_MESSAGE, caughtUp: CaughtUpState, ownUserId: UserId, |}>; type EventSubmessageAction = $ReadOnly<{| ...SubmessageEvent, type: typeof EVENT_SUBMESSAGE, |}>; type EventMessageDeleteAction = $ReadOnly<{| type: typeof EVENT_MESSAGE_DELETE, messageIds: $ReadOnlyArray<number>, |}>; type EventUpdateMessageAction = $ReadOnly<{| type: typeof EVENT_UPDATE_MESSAGE, /** Here `message_ids` is sorted. (This isn't guaranteed in the server event.) */ event: UpdateMessageEvent, move: null | MessageMove, |}>; type EventReactionCommon = $ReadOnly<{| ...ServerEvent, ...$Exact<Reaction>, message_id: number, |}>; type EventReactionAddAction = $ReadOnly<{| ...ServerEvent, ...EventReactionCommon, type: typeof EVENT_REACTION_ADD, |}>; type EventReactionRemoveAction = $ReadOnly<{| ...ServerEvent, ...EventReactionCommon, type: typeof EVENT_REACTION_REMOVE, |}>; type EventPresenceAction = $ReadOnly<{| ...PresenceEvent, type: typeof EVENT_PRESENCE, |}>; type EventTypingCommon = $ReadOnly<{| ...ServerEvent, ownUserId: UserId, recipients: $ReadOnlyArray<{| +user_id: UserId, +email: string |}>, sender: {| +user_id: UserId, +email: string |}, time: number, |}>; type EventTypingStartAction = $ReadOnly<{| ...EventTypingCommon, type: typeof EVENT_TYPING_START, op: 'start', |}>; type EventTypingStopAction = $ReadOnly<{| ...EventTypingCommon, type: typeof EVENT_TYPING_STOP, op: 'stop', |}>; type EventUpdateMessageFlagsAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_UPDATE_MESSAGE_FLAGS, all: boolean, allMessages: MessagesState, flag: UserMessageFlag, messages: $ReadOnlyArray<number>, op: 'add' | 'remove', message_details?: Map<number, UpdateMessageFlagsMessageDetails>, |}>; type EventUserAddAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_USER_ADD, person: User, |}>; type EventUserRemoveAction = $ReadOnly<{| type: typeof EVENT_USER_REMOVE, // In reality there's more -- but this will prevent accidentally using // the type before going and adding those other properties here properly. |}>; type EventMutedTopicsAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_MUTED_TOPICS, muted_topics: $ReadOnlyArray<MutedTopicTuple>, |}>; type EventMutedUsersAction = $ReadOnly<{| ...MutedUsersEvent, type: typeof EVENT_MUTED_USERS, |}>; type EventUserGroupAddAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_USER_GROUP_ADD, op: 'add', group: UserGroup, |}>; type EventUserGroupRemoveAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_USER_GROUP_REMOVE, op: 'remove', group_id: number, |}>; type EventUserGroupUpdateAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_USER_GROUP_UPDATE, op: 'update', group_id: number, data: {| +description?: string, +name?: string |}, |}>; type EventUserGroupAddMembersAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_USER_GROUP_ADD_MEMBERS, op: 'add_members', group_id: number, user_ids: $ReadOnlyArray<UserId>, |}>; type EventUserGroupRemoveMembersAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_USER_GROUP_REMOVE_MEMBERS, op: 'remove_members', group_id: number, user_ids: $ReadOnlyArray<UserId>, |}>; type EventRealmEmojiUpdateAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_REALM_EMOJI_UPDATE, realm_emoji: RealmEmojiById, |}>; // TODO(server-5.0): Remove, when all supported servers can handle the // `user_settings_object` client capability (FL 89). type EventUpdateDisplaySettingsAction = $ReadOnly<{| ...ServerEvent, type: typeof EVENT_UPDATE_DISPLAY_SETTINGS, setting_name: string, /** In reality, this can be a variety of types. It's boolean for a * `setting_name` of `twenty_four_hour_time`, which is the only case we * currently look at. */ setting: boolean, |}>; type EventReactionAction = EventReactionAddAction | EventReactionRemoveAction; type EventUserStatusUpdateAction = $ReadOnly<{| ...UserStatusEvent, type: typeof EVENT_USER_STATUS_UPDATE, |}>; type EventSubscriptionAction = | EventSubscriptionAddAction | EventSubscriptionRemoveAction | EventSubscriptionUpdateAction | EventSubscriptionPeerAddAction | EventSubscriptionPeerRemoveAction; type EventTypingAction = EventTypingStartAction | EventTypingStopAction; // For the update-user event, the action type is GenericEventAction, and the // event type is RealmUserUpdateEvent. type EventUserAction = EventUserAddAction | EventUserRemoveAction; type EventUserGroupAction = | EventUserGroupAddAction | EventUserGroupRemoveAction | EventUserGroupUpdateAction | EventUserGroupAddMembersAction | EventUserGroupRemoveMembersAction; /** Covers all actions we make from server events. */ export type EventAction = | GenericEventAction // Specific actions. | EventAlertWordsAction | EventMessageDeleteAction | EventMutedTopicsAction | EventMutedUsersAction | EventNewMessageAction | EventSubmessageAction | EventPresenceAction | EventRealmEmojiUpdateAction | EventRealmFiltersAction | EventUpdateGlobalNotificationsSettingsAction | EventUpdateDisplaySettingsAction | EventUpdateMessageAction | EventUpdateMessageFlagsAction // Unions, found just above. | EventReactionAction | EventSubscriptionAction | EventTypingAction | EventUserAction | EventUserGroupAction | EventUserStatusUpdateAction; type SetGlobalSettingsAction = $ReadOnly<{| type: typeof SET_GLOBAL_SETTINGS, update: $Shape<$Exact<GlobalSettingsState>>, |}>; type DraftUpdateAction = $ReadOnly<{| type: typeof DRAFT_UPDATE, narrow: Narrow, content: string, |}>; type PresenceResponseAction = $ReadOnly<{| type: typeof PRESENCE_RESPONSE, presence: PresenceSnapshot, serverTimestamp: number, |}>; type MessageSendStartAction = $ReadOnly<{| type: typeof MESSAGE_SEND_START, outbox: Outbox, |}>; type MessageSendCompleteAction = $ReadOnly<{| type: typeof MESSAGE_SEND_COMPLETE, local_message_id: number, |}>; type DeleteOutboxMessageAction = $ReadOnly<{| type: typeof DELETE_OUTBOX_MESSAGE, local_message_id: number, |}>; type ToggleOutboxSendingAction = $ReadOnly<{| type: typeof TOGGLE_OUTBOX_SENDING, sending: boolean, |}>; type ClearTypingAction = $ReadOnly<{| type: typeof CLEAR_TYPING, outdatedNotifications: $ReadOnlyArray<string>, |}>; type InitTopicsAction = $ReadOnly<{| type: typeof INIT_TOPICS, topics: $ReadOnlyArray<Topic>, streamId: number, |}>; type RefreshServerEmojiDataAction = $ReadOnly<{| type: typeof REFRESH_SERVER_EMOJI_DATA, data: ServerEmojiData, |}>; /* eslint-disable spaced-comment */ //// // // The `Action` union type, and some subtypes. // //// // // First, some convenience unions without much meaning. // (We should perhaps just inline these below.) type LoadingAction = | DeadQueueAction | RegisterStartAction | RegisterAbortAction | RegisterCompleteAction; type MessageAction = MessageFetchStartAction | MessageFetchErrorAction | MessageFetchCompleteAction; type OutboxAction = MessageSendStartAction | MessageSendCompleteAction | DeleteOutboxMessageAction; // // Then, the primary subtypes of `Action`. Each of these should have some // coherent meaning in terms of what kind of state it applies to; and they // should have no overlap. (Subtypes that might overlap are formed below // as unions of these primary subtypes.) /* eslint-disable semi-style */ /** * Plain actions applying to this account's state. * * That is, these should only be dispatched from a per-account context, and * they apply to the account the caller is acting on. In a pre-#5006 world, * that means the active account. */ // prettier-ignore export type PerAccountAction = // The grouping here is completely arbitrary; don't worry about it. | EventAction | LoadingAction | ResetAccountDataAction | RefreshServerEmojiDataAction | MessageAction | OutboxAction | DraftUpdateAction | PresenceResponseAction | InitTopicsAction | ClearTypingAction // state.session | DismissServerCompatNoticeAction | DismissServerPushSetupNoticeAction | DismissServerNotifsExpiringBannerAction | SetSilenceServerPushSetupWarningsAction | ToggleOutboxSendingAction ; /** Plain actions applying to other accounts' per-account state. */ // prettier-ignore export type AllAccountsAction = // This affects all the per-account states as well as everything else. | RehydrateAction // These can rearrange the `state.accounts` list itself. | AccountSwitchAction | AccountRemoveAction | LoginSuccessAction | LogoutAction // These four are about a specific account but not just the active one, // and they encode which one they mean. | RegisterPushTokenEndAction | RegisterPushTokenStartAction | AckPushTokenAction | UnackPushTokenAction ; /** Plain actions not affecting any per-account state. */ // prettier-ignore export type AccountIndependentAction = | SetGlobalSettingsAction // state.session | AppOnlineAction | AppOrientationAction | GotPushTokenAction ; // // `Action` itself. /** * Covers all plain actions we ever `dispatch`. * * For *all* actions we ever dispatch, see also the thunk action types in * `reduxTypes.js`. */ // prettier-ignore export type Action = // This should consist of the primary subtypes defined just above. | PerAccountAction | AllAccountsAction | AccountIndependentAction ; // // Other subtypes of `Action`. // // These should be unions of the primary subtypes, to express different // meanings about what contexts the actions can be used in. /** Plain actions that per-account reducers may respond to. */ // prettier-ignore export type PerAccountApplicableAction = | PerAccountAction | AllAccountsAction ; // Plain actions that global reducers may respond to are... well, at the // moment we have no reducers that act only on global state. Our state // subtrees `session` and `settings` mix global with per-account state, // while `accounts` contains per-account state for all accounts, and its // reducer does respond to some of PerAccountAction as well as // AllAccountsAction. // TODO(#5006): Make a GlobalApplicableAction for global session and // settings state, once those are separate from per-account. // TODO(#5006): would be nice to assert these types have empty intersection // (a: PerAccountApplicableAction & AccountIndependentAction): empty => a; // eslint-disable-line // (a: GlobalApplicableAction & PerAccountAction): empty => a; // eslint-disable-line /** Actions that can be dispatched without reference to a specific account. */ // prettier-ignore export type DispatchableWithoutAccountAction = | AllAccountsAction | AccountIndependentAction ; /** True just if the action is a PerAccountApplicableAction. */ export function isPerAccountApplicableAction(action: Action): boolean { switch (action.type) { case RESET_ACCOUNT_DATA: case EVENT: case EVENT_ALERT_WORDS: case EVENT_MESSAGE_DELETE: case EVENT_MUTED_TOPICS: case EVENT_MUTED_USERS: case EVENT_NEW_MESSAGE: case EVENT_PRESENCE: case EVENT_REACTION_ADD: case EVENT_REACTION_REMOVE: case EVENT_REALM_EMOJI_UPDATE: case EVENT_REALM_FILTERS: case EVENT_SUBMESSAGE: case EVENT_SUBSCRIPTION: case EVENT_TYPING_START: case EVENT_TYPING_STOP: case EVENT_UPDATE_DISPLAY_SETTINGS: case EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS: case EVENT_UPDATE_MESSAGE: case EVENT_UPDATE_MESSAGE_FLAGS: case EVENT_USER_ADD: case EVENT_USER_GROUP_ADD: case EVENT_USER_GROUP_ADD_MEMBERS: case EVENT_USER_GROUP_REMOVE: case EVENT_USER_GROUP_REMOVE_MEMBERS: case EVENT_USER_GROUP_UPDATE: case EVENT_USER_REMOVE: case EVENT_USER_STATUS_UPDATE: case DEAD_QUEUE: case REGISTER_START: case REGISTER_ABORT: case REGISTER_COMPLETE: case REFRESH_SERVER_EMOJI_DATA: case MESSAGE_FETCH_COMPLETE: case MESSAGE_FETCH_ERROR: case MESSAGE_FETCH_START: case MESSAGE_SEND_COMPLETE: case MESSAGE_SEND_START: case DELETE_OUTBOX_MESSAGE: case DRAFT_UPDATE: case PRESENCE_RESPONSE: case INIT_TOPICS: case CLEAR_TYPING: case DISMISS_SERVER_COMPAT_NOTICE: case DISMISS_SERVER_PUSH_SETUP_NOTICE: case DISMISS_SERVER_NOTIFS_EXPIRING_BANNER: case SET_SILENCE_SERVER_PUSH_SETUP_WARNINGS: case TOGGLE_OUTBOX_SENDING: (action: PerAccountAction); (action: PerAccountApplicableAction); return true; case REHYDRATE: case ACCOUNT_SWITCH: case ACCOUNT_REMOVE: case LOGIN_SUCCESS: case LOGOUT: case REGISTER_PUSH_TOKEN_START: case REGISTER_PUSH_TOKEN_END: case ACK_PUSH_TOKEN: case UNACK_PUSH_TOKEN: (action: AllAccountsAction); (action: PerAccountApplicableAction); return true; case SET_GLOBAL_SETTINGS: case APP_ONLINE: case APP_ORIENTATION: case GOT_PUSH_TOKEN: (action: AccountIndependentAction); return false; default: ensureUnreachable(action); return false; } } ```
/content/code_sandbox/src/actionTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
5,619
```javascript /** * Handy generic functions for operating on JS collections. * * Any function here is the sort of thing that perhaps should be in the * language's standard library, or is just a bit too algorithmical for that. * * See also * * `jsBackport.js`, for things that actually are in newer versions of JS, * or late-stage proposals for future versions * * `generics.js`, for things that operate on types * * @flow strict-local */ /** * Like `Array#map`, but returns null if `f` ever returns a nullish value. * * If `f` returns nullish at any element, the iteration stops and `f` is not * called on any later elements. * * This replaces either (a) writing an explicit loop, in order to be able to * abort on a nullish value, or (b) using `Array#map` and then running * through the list again to look for nullish values. */ export function mapOrNull<T, U>( array: $ReadOnlyArray<T>, f: (T, number, $ReadOnlyArray<T>) => U, // `Array#map` has one more parameter, "thisArg". Skipping that because // it seems like there isn't a way to type it properly in Flow (flowlib // has `any`), and we haven't had a need for it. ): Array<$NonMaybeType<U>> | null { const result = []; for (let i = 0; i < array.length; i++) { const r = f(array[i], i, array); if (r == null) { return null; } result.push(r); } return result; } /** * Find items that are in one but not both of the given arrays. * * The two returned arrays consist of items in only the first array, and * items in only the second array, respectively. * * Both input arrays must be sorted. The output arrays will also be sorted. * * This function takes linear time, i.e., O(as.length + bs.length). * * (The implementation would work just as well for strings; it only needs * `<`. The type is narrower just because `number | string` would mean * comparing numbers and strings to each other, which in JS is no good.) */ // prettier-ignore export function symmetricDiff( as: $ReadOnlyArray<number>, bs: $ReadOnlyArray<number>, ): [number[], number[]] { /* eslint-disable one-var */ const aOnly = [], bOnly = []; let ia = 0, ib = 0; while (ia < as.length && ib < bs.length) { const a = as[ia], b = bs[ib]; if (a === b) { ia++; ib++; } else if (a < b) { aOnly.push(a); ia++; } else { bOnly.push(b); ib++; } } if (ia < as.length) { aOnly.push(...as.slice(ia)); } else if (ib < bs.length) { bOnly.push(...bs.slice(ib)); } return [aOnly, bOnly]; } ```
/content/code_sandbox/src/collections.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
690
```javascript /** * Type-wrappers for the react-redux package. * * These functions each correspond directly to a function exported by * react-redux upstream, but with more-specific types. * * @flow strict-local */ import type { ComponentType, ElementConfig } from 'react'; // We use the ESLint rule `no-restricted-imports` to ensure the rest of the // codebase gets its react-redux from here, rather than directly from // upstream. That means this file is the exception that does import // directly from upstream. // eslint-disable-next-line no-restricted-imports import { connect as connectInner, useSelector as useSelectorInner, useDispatch as useDispatchInner, } from 'react-redux'; import type { PerAccountState, GlobalState, Dispatch, GlobalDispatch } from './types'; import type { BoundedDiff } from './generics'; // There's not a lot to say about the type of `Provider`, and it only has // one use-site anyway; so we don't wrap it. But do re-export it from here, // so everything else can uniformly never import directly from react-redux. // eslint-disable-next-line no-restricted-imports export { Provider } from 'react-redux'; // We leave this as invariant in `C` (i.e., we don't write `-C` or `+C`) // because Flow says `ElementConfig` is invariant. (If you try writing // `OwnProps<-C, ` or `OwnProps<+C, `, Flow gives an error saying the `C` // in `ElementConfig<C>` is an "input/output position", which is a synonym // of "invariant" as opposed to "contravariant" or "covariant".) // // Meanwhile `SP` is contravariant (so we write `-S`): its one occurrence is // as the second (contravariant) parameter of a `BoundedDiff`, which gets // used as the first (covariant) parameter of another `BoundedDiff`, which // is the whole type. That's an odd number of contravariants, so it's a // contravariant position / "input position" overall. // // As for `-D`: a `+` object property, in the bottom of a BoundedDiff, // makes a + inside a -, which is again an odd number of - and produces -. export type OwnProps<C, -SP, -D> = BoundedDiff< BoundedDiff<$Exact<ElementConfig<C>>, SP>, {| +dispatch: D |}, >; /** * Exactly like the `connect` in `react-redux` upstream, but more typed. * * Upstream docs: * path_to_url * * NOTE: * * This version works great with a `mapStateToProps` that takes only * the state and not the outer props. * * * For two-argument `mapStateToProps`, Flow needs a little help: write * * connect<SelectorProps, _, _>((state, props) => )(MyComponent) * * where `SelectorProps` describes the return value of `mapStateToProps`. * This type will get fully checked; Flow just can't infer it. * See our commit fcde7005e, and previous discussion at f8c981028. * * * For no-argument `connect`, Flow also needs help: write * * connect<{||}, _, _>()(MyComponent) * * Awkwardly, in this case Flow will actually infer the wrong thing if * the explicit `{||}` is omitted, and fail to catch errors. See our * commit 1e0006e5b. * TODO: fix this, perhaps with an overload. * * The upstream function, and its libdef in `flow-typed`, has an extremely * complex type involving many overloads, and it's difficult to get useful * results with it from the type-checker. This trivial wrapper leaves out a * bunch of features we don't use, and then gives a more specific type. * * This version also takes advantage of being in our codebase, rather than a * general libdef, by encoding once and for all the type of our Redux state. * * (Most of those features probably *could* be supported with a more-helpful * type like this if desired, just with a moderate amount of further work. * Finding this type was a lot of work, and the extra features were left out * for the sake of focus while iterating on that.) */ // prettier-ignore export function connect<SP, P, C: ComponentType<P>>( mapStateToProps?: (PerAccountState, OwnProps<C, // Error "property `foo` is missing"? Add to inner component's props. SP, Dispatch>) => SP, ): C => ComponentType<$ReadOnly<OwnProps<C, SP, Dispatch>>> { return connectInner(mapStateToProps); } /** Just like `connect`, but for global rather than per-account state. */ export function connectGlobal<SP, P, C: ComponentType<P>>( mapStateToProps?: ( GlobalState, OwnProps< C, // Error "property `foo` is missing"? Add to inner component's props. SP, GlobalDispatch, >, ) => SP, ): C => ComponentType<$ReadOnly<OwnProps<C, SP, GlobalDispatch>>> { return connectInner(mapStateToProps); } /** * Exactly like the `useSelector` in `react-redux` upstream, but more typed. * * Specifically, this encodes once and for all the type of our Redux state. * * Upstream docs: * path_to_url#useselector */ // Without this, if Flow isn't specifically told that the type of `state` is // `PerAccountState`, it'll infer it as `empty` -- which means the selector // function effectively gets no type-checking of anything it does with it. export function useSelector<SS>( selector: (state: PerAccountState) => SS, equalityFn?: (a: SS, b: SS) => boolean, ): SS { return useSelectorInner<PerAccountState, SS>(selector, equalityFn); } /** Just like `useSelector`, but for global rather than per-account state. */ export function useGlobalSelector<SS>( selector: (state: GlobalState) => SS, equalityFn?: (a: SS, b: SS) => boolean, ): SS { return useSelectorInner<GlobalState, SS>(selector, equalityFn); } /** * Exactly like the `useDispatch` in `react-redux` upstream, but more typed. * * Specifically, this encodes once and for all the type of our Redux * dispatch function. * * Upstream docs: * path_to_url#usedispatch */ // Without this, if Flow isn't told that the return value is of type // `Dispatch`, it'll infer it as `empty` -- which means we effectively // get no type-checking on the actions we pass to our dispatch // function. export function useDispatch(): Dispatch { return useDispatchInner<Dispatch>(); } /** Just like `useDispatch`, but for a global rather than per-account context. */ export function useGlobalDispatch(): GlobalDispatch { return useDispatchInner<GlobalDispatch>(); } ```
/content/code_sandbox/src/react-redux.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,551
```javascript /* @flow strict-local */ export * from './account/accountActions'; export * from './events/eventActions'; export * from './nav/navActions'; export * from './drafts/draftsActions'; export * from './message/fetchActions'; export * from './message/messagesActions'; export * from './outbox/outboxActions'; export * from './session/sessionActions'; export * from './settings/settingsActions'; export * from './streams/streamsActions'; export * from './topics/topicActions'; export * from './typing/typingActions'; export * from './users/usersActions'; ```
/content/code_sandbox/src/actions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
119
```javascript /** * Types describing our Redux state and store. * * This isn't the place for types that are borrowed from the API; * those go under `src/api/` (typically in `src/api/modelTypes.js`) * and can be imported here as needed. * * @flow strict-local */ import type Immutable from 'immutable'; import type { InputSelector } from 'reselect'; import type { Account, Outbox } from './types'; import type { Action, DispatchableWithoutAccountAction } from './actionTypes'; import type { CustomProfileField, Topic, Message, CrossRealmBot, RealmEmojiById, RealmFilter, Stream, Subscription, User, UserGroup, UserId, UserPresence, CreatePublicOrPrivateStreamPolicyT, CreateWebPublicStreamPolicy, } from './api/apiTypes'; import type { PerAccountSessionState, GlobalSessionState, SessionState, } from './session/sessionReducer'; import type { MuteState } from './mute/muteModelTypes'; import type { PmConversationsState } from './pm-conversations/pmConversationsModel'; import type { UnreadState } from './unread/unreadModelTypes'; import type { UserStatusesState } from './user-statuses/userStatusesCore'; import type { ServerEmojiData, UserMessageFlag } from './api/modelTypes'; import type { EmailAddressVisibility } from './api/permissionsTypes'; import { typesEquivalent } from './generics'; export type { MuteState } from './mute/muteModelTypes'; export type { UserStatusesState } from './user-statuses/userStatusesCore'; export type * from './actionTypes'; /* eslint-disable no-unused-expressions */ /** * The list of known accounts, with the active account first. * * Some accounts in the list may have a blank API key (if the user hasn't * yet completed login, or has logged out) or even a blank email (if the * user hasn't completed login.) * * See: * * "active account" in `docs/glossary.md`. * * `getIdentity`, `getAuth`, and related selectors, for getting * information about the active account as needed in most codepaths of * the app. * * `Account` for details on the properties of each account object. */ export type AccountsState = $ReadOnlyArray<Account>; export type AlertWordsState = $ReadOnlyArray<string>; /** * Info about how complete our knowledge is of the messages in some narrow. * * @prop older - true just if in some fetch we reached the oldest message * in the narrow. No need to fetch more in that direction. * @prop newer - true just if in some fetch we reached the newest message in * the narrow. Of course their may always be new messages, but we should * learn about them through events; so again, no need to fetch more. */ export type CaughtUp = $ReadOnly<{| older: boolean, newer: boolean, |}>; /** * Info about how completely we know the messages in each narrow. * * The keys correspond to the keys in `NarrowsState`. * * See `CaughtUp` for details on what each value means. */ export type CaughtUpState = $ReadOnly<{| [narrow: string]: CaughtUp, |}>; /** * The user's draft message, if any, in each conversation. * * The keys correspond to the keys in `NarrowsState`. */ export type DraftsState = $ReadOnly<{| [narrow: string]: string, |}>; export type Fetching = $ReadOnly<{| older: boolean, newer: boolean, |}>; /** * Info about which narrows we're actively fetching more messages from. * * The keys correspond to the keys in `NarrowsState`. * * See also: `CaughtUpState`, `NarrowsState`. */ export type FetchingState = $ReadOnly<{| [narrow: string]: Fetching, |}>; /** * The message flags corresponding to all the messages in `MessagesState`. * * Unlike almost all other subtrees of our state, this one can be * incomplete, always in exactly the same way that `MessagesState` is. * * We expect most of these flags to be very sparse: the number of messages * you have starred, or where you're @-mentioned, is typically a very small * fraction of the total number of messages you have. That's why it probably * doesn't make sense for this data structure to explicitly indicate "not * starred", "not @-mentioned", etc., for every known message. That could * significantly increase the memory and storage requirement when we know * about a lot of messages. If we need to distinguish "unknown message" from * "message without flag", we can look up the message ID in * `state.messages`. */ export type FlagsState = $ReadOnly<{| read: {| +[messageId: number]: true |}, starred: {| +[messageId: number]: true |}, collapsed: {| +[messageId: number]: true |}, mentioned: {| +[messageId: number]: true |}, wildcard_mentioned: {| +[messageId: number]: true |}, has_alert_word: {| +[messageId: number]: true |}, historical: {| +[messageId: number]: true |}, |}>; // The flags in FlagsState correspond with those in the server API, // as expressed by UserMessageFlag. typesEquivalent<$Keys<FlagsState>, UserMessageFlag>(); /** * A map with all messages we've stored locally, indexed by ID. * * For almost all types of data we need from the server, we use the Zulip * event system to get a complete snapshot and to maintain it incrementally. * See `registerAndStartPolling` for discussion, and see our docs from the * client-side perspective: * path_to_url * and a mainly server-side perspective: * path_to_url * As a result, there are very few types of data we need to go fetch from * the server as the user navigates through the app or as different * information is to appear on screen. * * Message data is the one major exception. For new messages while we're * online, and updates to existing messages, we learn them in real time * through the event system; but because the full history of messages can be * very large, it's left out of the snapshot obtained through `/register` by * `registerAndStartPolling`. Instead, we fetch specific message history as * needed. * * This subtree of our state stores all the messages we've fetched, prompted * by any of a variety of reasons. * * Although this map is *incomplete*, it should always be *accurate* about * each message it does contain -- once a message appears here, we use the * Zulip event system to make sure it stays up to date through edits, emoji * reactions, or other changes to its data. * * These `Message` objects lack the `flags` property; we store that * information separately, as `FlagsState`. * * See also `NarrowsState`, which is an index on this data that identifies * messages belonging to a given narrow. */ export type MessagesState = Immutable.Map<number, Message>; export type MigrationsState = $ReadOnly<{| version?: number, |}>; /** A map from user IDs to the Unix timestamp in seconds when they were muted. */ export type MutedUsersState = Immutable.Map<UserId, number>; /** * An index on `MessagesState`, listing messages in each narrow. * * Unlike almost all other subtrees of our state, this one can be incomplete * compared to the data that exists on the server and the user has access * to; see `MessagesState` for more context. The data here should * correspond exactly to the data in `MessagesState`. * * Keys are those given by `keyFromNarrow`. * Values are sorted lists of message IDs. * * See also: * * `MessagesState`, which stores the message data indexed by ID; * * `CaughtUpState` for information about where this data *is* * complete for a given narrow; * * `FetchingState` for information about which narrows we're actively * fetching more messages from. */ export type NarrowsState = Immutable.Map<string, $ReadOnlyArray<number>>; export type OutboxState = $ReadOnlyArray<Outbox>; /** * The `presence` subtree of our Redux state. * * @prop (email) - Indexes over all users for which the app has received a * presence status. */ export type PresenceState = $ReadOnly<{| pingIntervalSeconds: number, offlineThresholdSeconds: number, byEmail: Immutable.Map<string, UserPresence>, |}>; /** * Configuration for a video chat provider, as specified by the server. * * The `name` property identifies the selected provider. Depending on the * provider, other properties may provide other configuration details * required. * * See `src/realm/realmReducer.js` for where these values are produced based * on information from the server. */ // Right now there's just one branch here; if we add another provider, this // should become a disjoint union on `name`. export type VideoChatProvider = $ReadOnly<{| name: 'jitsi_meet', jitsiServerUrl: string |}>; /** * State with miscellaneous data from the server; our state subtree `realm`. * * "Initial data", below, refers to data in the register-queue response: * path_to_url#response * * Despite the name, this info doesn't necessarily have much to do with the * Zulip organization/realm; some properties do, but others are per-user, * and others are per-server. * * About the server: * @prop crossRealmBots - Corresponds to cross_realm_bots in initial data. * We use our `AvatarURL` class at `.avatar_url`. * * About the org/realm: * @prop name - Corresponds to realm_name in initial data. * @prop description - Corresponds to realm_description in initial data. * @prop nonActiveUsers - Corresponds to realm_non_active_users in initial * data. We use our `AvatarURL` class at `.avatar_url`. * @prop filters - Corresponds to realm_linkifiers/realm_filters in initial * data. For now, we use the legacy realm_filters form internally. * @prop emoji - Corresponds to realm_emoji in initial data. * @prop videoChatProvider - The video chat provider configured by the * server; null if none, or if the configured provider is one we don't * support. * @prop mandatoryTopics - Corresponds to realm_mandatory_topics in initial * data. * @prop messageContentDeleteLimitSeconds - Corresponds to * realm_message_content_delete_limit_seconds in initial data. We use the * Zulip Server 5.0+ convention that `null` means no limit, and 0 is * invalid. * @prop messageContentEditLimitSeconds - Corresponds to * realm_message_content_edit_limit_seconds in initial data. * @prop pushNotificationsEnabled - Corresponds to realm_push_notifications_enabled in initial data. * * About the user: * @prop email * @prop user_id * @prop twentyFourHourTime * @prop canCreateStreams * @prop isAdmin */ export type RealmState = {| // // InitialDataCustomProfileFields // +customProfileFields: $ReadOnlyArray<CustomProfileField>, // // InitialDataRealm // +name: string, +description: string, +nonActiveUsers: $ReadOnlyArray<User>, +filters: $ReadOnlyArray<RealmFilter>, +emoji: RealmEmojiById, +defaultExternalAccounts: Map<string, {| +url_pattern: string |}>, +videoChatProvider: VideoChatProvider | null, +mandatoryTopics: boolean, +messageContentDeleteLimitSeconds: number | null, +messageContentEditLimitSeconds: number, +pushNotificationsEnabled: boolean, +pushNotificationsEnabledEndTimestamp: number | null, +createPublicStreamPolicy: CreatePublicOrPrivateStreamPolicyT, +createPrivateStreamPolicy: CreatePublicOrPrivateStreamPolicyT, +webPublicStreamsEnabled: boolean, +createWebPublicStreamPolicy: CreateWebPublicStreamPolicy, +enableSpectatorAccess: boolean, +waitingPeriodThreshold: number, +allowEditHistory: boolean, +enableReadReceipts: boolean, +emailAddressVisibility: EmailAddressVisibility | null, +enableGuestUserIndicator: boolean, // // InitialDataRealmUser // +canCreateStreams: boolean, +user_id: UserId | void, +email: string | void, +crossRealmBots: $ReadOnlyArray<CrossRealmBot>, // // InitialDataUserSettings // +twentyFourHourTime: boolean, // We let this be null if `user_settings` isn't supported, just because we // don't currently need the value for pre-FL 89 servers. If we start // needing it, we can fall back to the deprecated `presence_enabled` // directly on the /register response. // TODO(server-5.0): user_settings supported in FL 89; remove null case +presenceEnabled: boolean | null, // // Misc.: Not in the /register response. // /** * Our most recent read of the server_emoji_data_url data, if any. * * We check for changes in the data after every /register; see comment * where we dispatch maybeRefreshServerEmojiData. */ +serverEmojiData: ServerEmojiData | null, |}; /** * The visual theme of the app. * * To get a ThemeName from the ThemeSetting, first check the current * OS theme by calling the React Native hook useColorScheme and pass * that to the helper function getThemeToUse. */ export type ThemeName = 'light' | 'dark'; /** * The theme setting. * * This represents the value the user chooses in SettingsScreen. * * To determine the actual theme to show the user, use a ThemeName; * see there for details. */ export type ThemeSetting = 'default' | 'night'; /** What browser the user has set to use for opening links in messages. * * * embedded: The in-app browser * * external: The user's default browser app * * default: 'external' on iOS, 'embedded' on Android * * Use the `shouldUseInAppBrowser` function from src/utils/openLink.js in order to * parse this. * * See path_to_url#narrow/stream/48-mobile/topic/in-app.20browser * for the reasoning behind these options. */ export type BrowserPreference = 'embedded' | 'external' | 'default'; /** * The user's chosen settings specific to this account. */ export type PerAccountSettingsState = $ReadOnly<{ offlineNotification: boolean, onlineNotification: boolean, streamNotification: boolean, displayEmojiReactionUsers: boolean, ... }>; /** * The user's chosen settings independent of account, on this client. * * These apply across all the user's accounts on this client (i.e. on this * install of the app on this device). * * See also {@link PerAccountSettingsState}. */ // Because these apply independent of account, they necessarily can't come // from the server. export type GlobalSettingsState = $ReadOnly<{ // The user's chosen language, as an IETF BCP 47 language tag. language: string, theme: ThemeSetting, browser: BrowserPreference, // TODO cut this? what was it? experimentalFeaturesEnabled: boolean, // Possibly this should be per-account. If so it should probably be put // on the server, so it can also be cross-device for the account. markMessagesReadOnScroll: 'always' | 'never' | 'conversation-views-only', ... }>; /** * The user's chosen settings. * * This is a mix of server data representing the active account (see * {@link PerAccountSettingsState}), and client-only data that applies * across all the user's accounts on this client (see * {@link GlobalSettingsState}). */ export type SettingsState = $ReadOnly<{| ...$Exact<GlobalSettingsState>, ...$Exact<PerAccountSettingsState>, |}>; // As part of letting GlobalState freely convert to PerAccountState, // we'll want the same for SettingsState. (This is also why // PerAccountSettingsState is inexact.) (s: SettingsState): PerAccountSettingsState => s; export type StreamsState = $ReadOnlyArray<Stream>; export type SubscriptionsState = $ReadOnlyArray<Subscription>; export type TopicsState = $ReadOnly<{| [number]: $ReadOnlyArray<Topic>, |}>; export type TypingState = $ReadOnly<{| [normalizedRecipients: string]: $ReadOnly<{| time: number, userIds: $ReadOnlyArray<UserId>, |}>, |}>; export type UserGroupsState = $ReadOnlyArray<UserGroup>; /** * A collection of (almost) all users in the Zulip org; our `users` state subtree. * * This contains all users except deactivated users and cross-realm bots. * For those, see RealmState. */ export type UsersState = $ReadOnlyArray<User>; /* eslint-disable no-use-before-define */ /** * The portion of our Redux state with a single account's data. * * In a multi-account world (#5005), the full Redux state will contain one * of these per account. Before that, in a multi-account-ready schema * (#5006), the full Redux state may contain just one of these but as a * subtree somewhere inside it. * * Initially, though, the full Redux state tree actually qualifies as a * value of this type, and the values of this type we pass around are * secretly just the full Redux state. The purpose of this type is to * expose only the data that in a multi-account future will live on a single * account's state subtree, and to recruit Flow's help in tracking which * parts of our code will in that future operate on a particular account and * which parts will operate on all accounts' data or none. */ type PerAccountStateImpl = $ReadOnly<{ // TODO(#5006): Secretly we assume these objects also have `Account` data, // like so: // accounts: [Account, ...mixed], // which they do because they're always actually `GlobalState` objects. // Need to put that data somewhere that's less mixed up with other accounts' // data. See `accountsSelectors` for where we make that assumption. // Jumbles of per-account state and client state. session: PerAccountSessionState, settings: PerAccountSettingsState, // Per-account state that's *not* from the server. drafts: DraftsState, outbox: OutboxState, // Per-account state: server data for the active account. alertWords: AlertWordsState, caughtUp: CaughtUpState, fetching: FetchingState, flags: FlagsState, messages: MessagesState, mute: MuteState, mutedUsers: MutedUsersState, narrows: NarrowsState, pmConversations: PmConversationsState, presence: PresenceState, realm: RealmState, streams: StreamsState, subscriptions: SubscriptionsState, topics: TopicsState, typing: TypingState, unread: UnreadState, userGroups: UserGroupsState, userStatuses: UserStatusesState, users: UsersState, ... }>; export opaque type PerAccountState: PerAccountStateImpl = PerAccountStateImpl; /** * Our complete Redux state tree. * * Each property is a subtree maintained by its own reducer function. These * are named in a regular pattern; see also `src/boot/reducers.js`. * * We use `redux-persist` to write parts of this state tree to persistent * device storage that survives when the app is closed, and to read it back * ("rehydrate" it) from that storage at launch time. See `src/boot/store.js`. * Other parts of the state tree are not persisted. * * See in particular `discardKeys`, `storeKeys`, and `cacheKeys`, which * identify which subtrees are persisted and which are not. */ export type GlobalState = $ReadOnly<{| ...$Exact<PerAccountState>, // Metadata for the global state, as persisted on disk. migrations: MigrationsState, // Jumbles of per-account state and client state. session: SessionState, settings: SettingsState, // Per-account state but for all accounts together. // Mix of server data and otherwise. accounts: AccountsState, |}>; /** * Assume the given per-account state object is secretly a GlobalState. * * At present, this assumption is always true. But in the future it won't * be. Calling this function has much the same effect as a fixme, but just * makes it quite explicit that this particular assumption is being used. * * TODO(#5006): We'll have to fix and eliminate each call to this. */ export function assumeSecretlyGlobalState(state: PerAccountState): GlobalState { // $FlowFixMe[incompatible-exact] // $FlowFixMe[prop-missing] return state; } /** * Use the given state object as a per-account state. * * TODO(#5006): We'll have to fix and eliminate each call to this. */ export function dubPerAccountState(state: GlobalState): PerAccountState { // Here in this file, we can make this cast with no fixmes (for now, under // our single-active-account model.) But from anywhere outside this file, // that's forbidden because PerAccountState is opaque, so the way to do it // is by calling this function. return state; } /** * For tests only. Use the given state object as *both* kinds of state. * * TODO(#5006): We'll have to fix and eliminate each call to this. */ export function dubJointState(state: GlobalState): GlobalState & PerAccountState { return state; } // No substate should allow `undefined`; our use of AsyncStorage // depends on it. (This check will also complain on `null`, which I // don't think we'd have a problem with. We could try to write this // differently if we want to allow `null`.) type NonMaybeProperties<O: { ... }> = $ObjMap<O, <V>(V) => $NonMaybeType<V>>; type NonMaybeGlobalState = NonMaybeProperties<GlobalState>; // This function definition will fail typechecking if GlobalState is wrong. (s: GlobalState): NonMaybeGlobalState => s; /** A per-account selector returning TResult, with extra parameter TParam. */ // Seems like this should be OutputSelector... but for whatever reason, // putting that on a selector doesn't cause the result type to propagate to // the corresponding parameter when used in `createSelector`, and this does. export type Selector<TResult, TParam = void> = InputSelector<PerAccountState, TParam, TResult>; /** A GlobalState selector returning TResult, with extra parameter TParam. */ // Seems like this should be OutputSelector; see comment on Selector above. export type GlobalSelector<TResult, TParam = void> = InputSelector<GlobalState, TParam, TResult>; /** * The extras object passed to a per-account thunk action. * * This allows the thunk action to get access to information which isn't on * PerAccountState, but which is perfectly legitimate for per-account code * to use. */ export type ThunkExtras = $ReadOnly<{ getGlobalSession: () => GlobalSessionState, getGlobalSettings: () => GlobalSettingsState, ... }>; /** The Redux `dispatch` for a per-account context. */ export interface Dispatch { <A: Action>(action: A): A; <T>(ThunkAction<T>): T; } /** A per-account thunk action returning T. */ export type ThunkAction<T> = (Dispatch, () => PerAccountState, ThunkExtras) => T; /** The extras object passed to a global thunk action. */ export type GlobalThunkExtras = $ReadOnly<{ /** A per-account `dispatch` that acts on the active account. */ activeAccountDispatch: Dispatch, ... }>; /** The Redux `dispatch` for a global context. */ export interface GlobalDispatch { <A: DispatchableWithoutAccountAction>(action: A): A; <T>(GlobalThunkAction<T>): T; } /** A global thunk action returning T. */ export type GlobalThunkAction<T> = (GlobalDispatch, () => GlobalState, GlobalThunkExtras) => T; // The two pairs of dispatch/thunk-action types aren't interchangeable, // in either direction. // $FlowExpectedError[incompatible-return] (d: GlobalDispatch): Dispatch => d; // $FlowExpectedError[prop-missing] // $FlowExpectedError[incompatible-return] <T>(a: ThunkAction<T>): GlobalThunkAction<T> => a; // $FlowExpectedError[incompatible-return] (d: Dispatch): GlobalDispatch => d; // $FlowExpectedError[incompatible-exact] // $FlowExpectedError[prop-missing] // $FlowExpectedError[incompatible-return] <T>(a: GlobalThunkAction<T>): ThunkAction<T> => a; ```
/content/code_sandbox/src/reduxTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
5,558
```javascript /* @flow strict-local */ import type { ComponentType, ElementConfig } from 'react'; // $FlowFixMe[untyped-import] import { connectActionSheet as connectActionSheetInner } from '@expo/react-native-action-sheet'; import type { BoundedDiff } from './generics'; export type ShowActionSheetWithOptions = ( { options: string[], cancelButtonIndex: number, ... }, (number) => void, ) => void; /** * Exactly like the `connectActionSheet` in * `react-native-action-sheet` upstream, but more typed. */ export function connectActionSheet<P, C: ComponentType<P>>( WrappedComponent: C, ): ComponentType< BoundedDiff< $Exact<ElementConfig<C>>, {| +showActionSheetWithOptions: ShowActionSheetWithOptions |}, >, > { return connectActionSheetInner(WrappedComponent); } ```
/content/code_sandbox/src/react-native-action-sheet.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
185
```javascript /* @flow strict-local */ import * as Sentry from '@sentry/react-native'; import { nativeApplicationVersion } from 'expo-application'; // $FlowFixMe[untyped-import] import md5 from 'blueimp-md5'; import { Platform } from 'react-native'; import type { Identity } from './types'; import isAppOwnDomain from './isAppOwnDomain'; import store from './boot/store'; import { getIdentities } from './account/accountsSelectors'; import { sentryKey } from './sentryConfig'; import { isUrlOnRealm } from './utils/url'; // TODO import from @sentry/react-native libdef type Breadcrumb = $FlowFixMe; type BreadcrumbHint = $FlowFixMe; export const isSentryActive = (): boolean => { // Hub#getClient() is documented as possibly returning undefined, but the // significance of `undefined` is not. In practice, it appears to be // `undefined` exactly when `Sentry.init()` has not yet been called. const client = Sentry.getCurrentHub().getClient(); /* The `enabled` option in getOptions() is theoretically togglable at runtime: path_to_url#issuecomment-486674574 We avoid this, however, as it will only toggle the JavaScript SDK and not the lower-level native-code SDKs. */ // return (client && client.getOptions().enabled) ?? false; return !!client; }; const preventNoise = (): void => { /* Sentry should not normally be used in debug mode. (For one thing, the debug-mode build process doesn't ordinarily create bundles or .map files, so you'll probably get nonsensical stack traces.) */ if (process.env.NODE_ENV === 'development' && sentryKey !== null) { /* If you have some reason to initialize Sentry in debug mode anyway, please change the app's version name (currently specified in `ios/Info.plist` and/or `android/app/build.gradle`) to something that doesn't look like a normal version number -- preferably with your name and/or Github ID in it. This will allow events produced by these debug builds to be easily identified in the Sentry console. */ if (nativeApplicationVersion !== null && nativeApplicationVersion.match(/^\d+\.\d+\.\d+$/)) { throw new Error('Sentry should not be initialized in debug builds'); } } /* Jest has no reason to even _try_ to initialize Sentry, even if `sentryKey` is `null`. */ // (See the following links concerning detecting Jest.) // [1] path_to_url#using-babel // [2] path_to_url if (process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined) { throw new Error('Sentry must not be initialized during testing!'); } }; /** * An HTTP request made by the app. * * One of the builtin "recognized breadcrumb types": * path_to_url#breadcrumb-types */ type HttpBreadcrumb = $ReadOnly<{| ...Breadcrumb, type: 'http', data: {| url?: string, method?: string, status_code?: number, reason?: string, |}, |}>; function shouldScrubHost(url: URL, identities: $ReadOnlyArray<Identity>) { if (isAppOwnDomain(url)) { return false; } if (url.pathname.startsWith('/api/v1')) { // Most likely an API request to a Zulip realm. This will catch // `/api/v1/server_settings` and `/api/v1/fetch_api_key` requests to a // realm before the account is added to the account-statuses state. return true; } if (identities.some(({ realm }) => isUrlOnRealm(url, realm))) { // Definitely a request to a Zulip realm. Will catch requests to realms // in the account-statuses state, including those without `/api/v1`, // like `/avatar/{user_id}` (zulip/zulip@0f9970fd3 confirms that this // and potentially others don't / won't use `/api/v1`). return true; } return false; } function scrubUrl(unscrubbedUrl: void | string): void | string { if (unscrubbedUrl === undefined) { return undefined; } const parsedUrl = new URL(unscrubbedUrl); const identities = getIdentities(store.getState()); if (!shouldScrubHost(parsedUrl, identities)) { return unscrubbedUrl; } parsedUrl.host = `hidden-${ // So different realms are still distinguishable md5(parsedUrl.host).substring(0, 6) }.zulip.invalid`; return parsedUrl.toString(); } /** * Scrubs possibly personal information from a breadcrumb. * * - Removes the realm hostnames in API requests, except if the realm is * hosted by the organization that publishes the app and gets Sentry * reports from the published app. That organization knows which realms it * hosts and already has their server logs. */ function scrubBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): Breadcrumb { switch (breadcrumb.type) { case 'http': { const httpBreadcrumb: HttpBreadcrumb = breadcrumb; return { ...httpBreadcrumb, data: { ...httpBreadcrumb.data, url: scrubUrl(httpBreadcrumb.data.url), }, }; } default: return breadcrumb; } } /** Initialize Sentry into its default configuration. */ export const initializeSentry = () => { // Check to make sure it's safe to run Sentry. Abort if not. preventNoise(); const key = sentryKey; if (key !== null) { // The DSN is formatted as an `https:` URL. Omit the scheme. const displayKey = `${key.slice(8, 12)}......`; // eslint-disable-next-line no-console console.log(`Sentry key ${displayKey} provided; initializing`); Sentry.init({ dsn: key, ignoreErrors: [ // RN's fetch implementation can raise these; we sometimes mimic it 'Network request failed', ], ...(Platform.OS === 'android' ? { // Disable Sentry's native code (libsentry.so), because it has // memory-corruption bugs that cause the app to crash. // path_to_url // path_to_url#issuecomment-1739030872 enableNdk: false, } : Object.freeze({})), beforeBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): Breadcrumb | null { try { return scrubBreadcrumb(breadcrumb, hint); } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url // $FlowFixMe[incompatible-type]: assume what was thrown is an Error const e: Error = error; // We don't expect any errors here. But: // - We can't just drop breadcrumbs on the floor, which is what // would happen on an uncaught Error in `beforeBreadcrumb`. We'd // lose valuable information, including the fact that there was // supposed to be a breadcrumb in the first place. // - We shouldn't knowingly send an un-scrubbed breadcrumb. // // So, make a substitute breadcrumb with none of the real // breadcrumb's data, and include `e.message` from the scrubbing // error. // // We currently don't send a separate event for the scrubbing // error. It would be easy for that code to accidentally add a // breadcrumb of its own, starting an infinite loop if // `beforeBreadcrumb` fails on it too. And we mustn't break the // First Law of debuggers, which is that they not break the // program's normal functionality. // One of the builtin "recognized breadcrumb types": // path_to_url#breadcrumb-types return { type: 'error', category: 'error', level: 'error', message: `Breadcrumb scrub failed: ${e.message}`, timestamp: breadcrumb.timestamp, }; } }, }); } else { // This is normal behavior when running locally; only published release // builds will have a Sentry key. // (It's not documented anywhere what happens when functions on Sentry are // called without first initializing Sentry. Fortunately, it seems to have // worked without warnings, so far.) // eslint-disable-next-line no-console console.log('no Sentry key provided; skipping initialization'); } }; ```
/content/code_sandbox/src/sentry.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,882
```javascript /* @flow strict-local */ import type { Store } from 'redux'; import type { GlobalSelector, GlobalState, Action } from './reduxTypes'; /** * Call a function whenever a selected piece of state changes. * * When the return value of `select` isn't equal (===) to the previous * value, `onChange` gets called, with the old and new value. * `onChange` is called once, immediately and unconditionally, at the * beginning. * * Returns a teardown function. */ export function observeStore<T>( store: Store<GlobalState, Action>, select: GlobalSelector<T>, onChange: (state: T) => void, ): () => void { // Start as a nonce object, so the initial `prevState !== state` // must return true. let prevState = {}; function handleChange() { const state = select(store.getState()); if (prevState !== state) { onChange(state); prevState = state; } } const unsubscribe = store.subscribe(handleChange); handleChange(); return unsubscribe; } ```
/content/code_sandbox/src/redux.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
225
```javascript /** * Helpers for using react-navigation and its relatives. * * @flow strict-local */ import { type ElementConfig } from 'react'; import { useNavigation as useNavigationInner, type Route } from '@react-navigation/native'; import type { AppNavigationMethods } from './nav/AppNavigator'; /** * A type to use for the `route` prop on a screen component. * * Typically used in the component definition, to annotate its `route` prop. * * The type this produces is just like the one produced by `RouteProp` in * the upstream libdef. The difference is that this one takes `RouteParams` * as an argument directly, making it suitable for expressing the params * type directly in the component's own source, just like props types. The * navigator's central param list can then use `RouteParamsOf` to get the * appropriate type from the component definition, rather than vice versa. * * @param {RouteName} - Must equal the route name this screen will be known * by at the navigator. (This is type-checked at the navigator.) * @param {RouteParams} - The type to use for `props.route.params`. */ export type RouteProp<+RouteName: string, +RouteParams: { ... } | void> = {| ...$Exact<Route<RouteName>>, +params: RouteParams, |}; /** * The type of the route params on the given screen component. * * This is intended for use in the params-list type for a navigator. * Sample usage, following the same example as in the upstream docs * at path_to_url : * * export type RootStackParamList = {| * 'Profile': RouteParamsOf<typeof Profile>, * |}; * * This allows each component's route-params type to be defined within the * component's own source, just like props types. Continuing the example, * the definition of the `Profile` component might contain a definition like * this one: * * type Props = {| * +navigation: StackNavigationProp<RootStackParamList, 'Profile'>, * +route: RouteProp<'Profile', {| +userId: string |}, * |}; * * (Or better yet, next to the params-list type we might define an alias * to simplify the `navigation` prop's type, to something like * `RootStackNavigationProp<'Profile'>`.) */ // The $NonMaybeType means that if `route` on the component is optional, we // ignore the optional-ness and just look at the type the `params` property // is expected to have when `route` is present at all. This feels a bit // ad hoc, but should be perfectly correct as far as it goes: even if // `route` is optional, the navigator will always pass it, so as far as it's // concerned `route` might as well be required. // // (Similarly if `route` has a type that permits null or void, which // $NonMaybeType will also eliminate: the navigator will never be interested // in passing one of those values anyway, so as far as it's concerned the // type expected for `route` might as well exclude them.) export type RouteParamsOf<-C> = $NonMaybeType<ElementConfig<C>['route']>['params']; /** * Exactly like `useNavigation` upstream, but more typed. * * In particular, this provides a type that should be accurate when used on * any screen in the app, with methods only for using the app's main * navigator (which is an ancestor of all our other navigators.) * * This doesn't describe parts of the returned object that will exist only * when on a particular navigator. If we start needing those, we can make * type-wrappers for them too. */ export function useNavigation(): AppNavigationMethods { // The upstream type sure isn't very informative: it lets us do this. return useNavigationInner<empty>(); // The intended way to call it looks to be like this: // useNavigationInner<AppNavigationMethods>() // But that gives a number of puzzling errors. And the one thing it // actually does with the type argument is to determine the return type, // anyway. We know what that should be, so just handle it ourselves. } ```
/content/code_sandbox/src/react-navigation.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
928